1 <?php rcs_id('$Id: WikiUser.php,v 1.19 2002-08-24 22:09:14 wainstead Exp $');
3 // It is anticipated that when userid support is added to phpwiki,
4 // this object will hold much more information (e-mail, home(wiki)page,
5 // etc.) about the user.
7 // There seems to be no clean way to "log out" a user when using
8 // HTTP authentication.
9 // So we'll hack around this by storing the currently logged
10 // in username and other state information in a cookie.
12 define('WIKIAUTH_ANON', 0);
13 define('WIKIAUTH_BOGO', 1); // any valid WikiWord is enough
14 define('WIKIAUTH_USER', 2); // real auth from a database/file/server.
16 define('WIKIAUTH_ADMIN', 10);
17 define('WIKIAUTH_FORBIDDEN', 11); // Completely not allowed.
19 $UserPreferences = array(
20 'userid' => new _UserPreference(''),
21 'passwd' => new _UserPreference(''),
22 'email' => new _UserPreference(''),
23 'emailVerified' => new _UserPreference_bool(),
24 'notifyPages' => new _UserPreference(''),
25 'theme' => new _UserPreference(THEME),
26 'lang' => new _UserPreference($LANG),
27 'editWidth' => new _UserPreference_int(80, 30, 150),
28 'editHeight' => new _UserPreference_int(22, 5, 80),
29 'timeOffset' => new _UserPreference_numeric(0, -26, 26),
30 'relativeDates' => new _UserPreference_bool()
36 var $_request, $_dbi, $_authdbi, $_homepage;
37 var $_authmethod = '', $_authhow = '';
42 function WikiUser ($userid = false, $authlevel = false) {
43 $this->_request = &$GLOBALS['request'];
44 $this->_dbi = &$this->_request->getDbh();
46 if (isa($userid, 'WikiUser')) {
47 $this->_userid = $userid->_userid;
48 $this->_level = $userid->_level;
51 $this->_userid = $userid;
52 $this->_level = $authlevel;
55 $this->_homepage = $this->_dbi->getPage($this->_userid);
57 // Paranoia: if state is at all inconsistent, log out...
58 $this->_userid = false;
59 $this->_level = false;
60 $this->_homepage = false;
61 $this->_authhow .= ' paranoia logout';
66 return $this->_authhow;
72 if (empty($this->_userid) || empty($this->_level)) {
73 // This is okay if truly logged out.
74 return $this->_userid === false && $this->_level === false;
76 // User is logged in...
78 // Check for valid authlevel.
79 if (!in_array($this->_level, array(WIKIAUTH_BOGO, WIKIAUTH_USER, WIKIAUTH_ADMIN)))
82 // Check for valid userid.
83 if (!is_string($this->_userid))
89 return ( $this->isSignedIn()
91 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
94 function getAuthenticatedId() {
95 return ( $this->isAuthenticated()
97 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
100 function isSignedIn () {
101 return $this->_level >= WIKIAUTH_BOGO;
104 function isAuthenticated () {
105 return $this->_level >= WIKIAUTH_USER;
108 function isAdmin () {
109 return $this->_level == WIKIAUTH_ADMIN;
112 function hasAuthority ($require_level) {
113 return $this->_level >= $require_level;
117 function AuthCheck ($postargs) {
118 // Normalize args, and extract.
119 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', 'cancel');
120 foreach ($keys as $key)
121 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
123 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
126 return new WikiUser; // Log out
128 return false; // User hit cancel button.
129 elseif (!$login && !$userid)
130 return false; // Nothing to do?
132 $authlevel = $this->_pwcheck($userid, $passwd);
134 return _("Invalid password or userid.");
135 elseif ($authlevel < $require_level)
136 return _("Insufficient permissions.");
139 $user = new WikiUser;
140 $user->_userid = $userid;
141 $user->_level = $authlevel;
145 function PrintLoginForm (&$request, $args, $fail_message = false, $seperate_page = true) {
146 include_once('lib/Template.php');
150 extract($args); // fixme
152 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
154 $pagename = $request->getArg('pagename');
155 $login = new Template('login', $request,
156 compact('pagename', 'userid', 'require_level', 'fail_message', 'pass_required'));
157 if ($seperate_page) {
158 $top = new Template('html', $request, array('TITLE' => _("Sign In")));
159 return $top->printExpansion($login);
168 function _pwcheck ($userid, $passwd) {
169 global $WikiNameRegexp;
171 if (!empty($userid) && $userid == ADMIN_USER) {
172 // $this->_authmethod = 'pagedata';
173 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
174 if (!empty($passwd) && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD)
175 return WIKIAUTH_ADMIN;
176 if (!empty($passwd)) {
177 if ($passwd == ADMIN_PASSWD)
178 return WIKIAUTH_ADMIN;
180 // maybe we forgot to enable ENCRYPTED_PASSWD?
181 if (function_exists('crypt') and crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD) {
182 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"), E_USER_WARNING);
183 return WIKIAUTH_ADMIN;
189 // HTTP Authentification
190 elseif (ALLOW_HTTP_AUTH_LOGIN and !empty($PHP_AUTH_USER)) {
191 // if he ignored the password field, because he is already authentificated
192 // try the previously given password.
193 if (empty($passwd)) $passwd = $PHP_AUTH_PW;
196 // WikiDB_User DB/File Authentification from $DBAuthParams
197 // Check if we have the user. If not try other methods.
198 if (ALLOW_USER_LOGIN and !empty($passwd)) {
199 $request = $this->_request;
200 // first check if the user is known
201 if ($this->exists($userid)) {
202 $this->_authmethod = 'pagedata';
203 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
205 // else try others such as LDAP authentication:
206 if (ALLOW_LDAP_LOGIN and !empty($passwd)) {
207 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
208 $r = @ldap_bind($ldap); // this is an anonymous bind
209 $st_search = "uid=$userid";
210 // Need to set the right root search information. see ../index.php
211 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH, "$st_search");
212 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
213 for ($i=0; $i<$info["count"]; $i++) {
214 $dn = $info[$i]["dn"];
215 // The password is still plain text.
216 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
217 // ldap_bind will return TRUE if everything matches
219 $this->_authmethod = 'LDAP';
220 return WIKIAUTH_USER;
224 trigger_error("Unable to connect to LDAP server " . LDAP_AUTH_HOST, E_USER_WARNING);
227 // imap authentication. added by limako
228 if (ALLOW_IMAP_LOGIN and !empty($passwd)) {
229 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}", $userid, $passwd, OP_HALFOPEN );
232 $this->_authmethod = 'IMAP';
233 return WIKIAUTH_USER;
239 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)) {
240 $this->_authmethod = 'BOGO';
241 return WIKIAUTH_BOGO;
246 // Todo: try our WikiDB backends.
247 function getPreferences() {
248 // Restore saved preferences.
249 // I'd rather prefer only to store the UserId in the cookie or session,
250 // and get the preferences from the db or page.
251 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
252 $prefs = $this->_request->getSessionVar('wiki_prefs');
254 if (!$this->_userid and !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
255 $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
258 // before we get his prefs we should check if he is signed in
259 if (!$prefs->_prefs and USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
260 if ($pref = $this->_homepage->get('pref'))
261 $prefs = unserialize($pref);
263 return new UserPreferences($prefs);
266 // No cookies anymore for all prefs, only the userid.
267 // PHP creates a session cookie in memory, which is much more efficient.
268 function setPreferences($prefs, $id_only = false) {
270 $this->_request->setSessionVar('wiki_prefs', $prefs);
271 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
272 // simple unpacked cookie
273 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
275 // We must ensure that any password is encrypted.
276 // We don't need any plaintext password.
277 if (! $id_only and $this->isSignedIn() and ($homepage = $this->homePage())) {
278 if ($this->isAdmin())
279 $prefs->set('passwd',''); // this is already stored in index.php,
280 // and it might be plaintext! well oh well
281 $homepage->set('pref',serialize($prefs->_prefs));
285 // check for homepage with user flag.
286 // can be overriden from the auth backends
288 $homepage = $this->homePage();
289 return ($this->_userid and $homepage and $homepage->get('pref'));
292 // doesn't check for existance!!! hmm.
293 // how to store metadata in not existing pages? how about versions?
294 function homePage() {
295 if (!$this->_userid) return false;
296 if ($this->_homepage)
297 return $this->_homepage;
299 $this->_homepage = $this->_dbi->getPage($this->_userid);
300 return $this->_homepage;
304 // create user by checking his homepage
305 function createUser ($pref, $createDefaultHomepage = true) {
306 if ($this->exists()) return;
307 if ($createDefaultHomepage) {
308 $this->createHomepage ($pref);
311 include "lib/loadsave.php";
312 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
313 'versiondata' => array('author' => $this->_userid),
314 'pagename' => $this->_userid,
315 'content' => _('CategoryHomepage'));
316 SavePage (&$this->_request, $pageinfo, false, false);
318 $this->setPreferences($pref);
321 // create user and default user homepage
322 function createHomepage ($pref) {
323 $pagename = $this->_userid;
324 include "lib/loadsave.php";
326 // create default homepage:
327 // properly expanded template and the pref metadata
328 $template = Template('homepage.tmpl',$this->_request);
329 $text = $template->getExpansion();
330 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
331 'versiondata' => array('author' => $this->_userid),
332 'pagename' => $pagename,
334 SavePage (&$this->_request, $pageinfo, false, false);
337 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
338 if (! isWikiPage($pagename)) {
339 $pageinfo = array('pagedata' => array(),
340 'versiondata' => array('author' => $this->_userid),
341 'pagename' => $pagename,
342 'content' => "<?plugin Calender ?>\n");
343 SavePage (&$this->_request, $pageinfo, false, false);
346 // create Preferences
347 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
348 if (! isWikiPage($pagename)) {
349 $pageinfo = array('pagedata' => array(),
350 'versiondata' => array('author' => $this->_userid),
351 'pagename' => $pagename,
352 'content' => "<?plugin UserPreferences ?>\n");
353 SavePage (&$this->_request, $pageinfo, false, false);
357 function tryAuthBackends() {
358 return ''; // crypt('') will never be ''
361 // Auth backends must store the crypted password where?
362 // Not in the preferences.
363 function checkPassword($passwd) {
364 $prefs = $this->getPreferences();
365 $stored_passwd = $prefs->get('passwd'); // crypted
366 if (empty($prefs->_prefs['passwd'])) // not stored in the page
367 // allow empty passwords? At least store a '*' then.
369 $stored_passwd = $this->tryAuthBackends($this->_userid);
370 if (empty($stored_passwd)) {
371 trigger_error(sprintf(_("WikiUser backend problem: Old UserPage %s. No password to check against! Update your UserPreferences."), $this->_userid), E_USER_NOTICE);
375 if ($stored_passwd == '*')
377 if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
383 function changePassword($newpasswd, $passwd2 = false) {
384 if (! $this->mayChangePassword() ) {
385 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
386 $this->_userid), E_USER_ERROR);
389 if ($passwd2 and $passwd2 != $newpasswd) {
390 trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
393 $prefs = $this->getPreferences();
394 //$oldpasswd = $prefs->get('passwd');
395 $prefs->set('passwd', crypt($newpasswd));
396 $this->setPreferences($prefs);
399 function mayChangePassword() {
400 // on external DBAuth maybe. on IMAP or LDAP not
401 // on internal DBAuth yes
402 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
404 if ($this->isAdmin())
406 if ($this->_authmethod == 'pagedata')
408 if ($this->_authmethod == 'authdb')
413 // create user and default user homepage
414 function createUser ($userid, $pref) {
415 $user = new WikiUser ($userid);
416 $user->createUser($pref);
419 class _UserPreference
421 function _UserPreference ($default_value) {
422 $this->default_value = $default_value;
425 function sanify ($value) {
426 return (string) $value;
430 class _UserPreference_numeric extends _UserPreference
432 function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
433 $this->_UserPreference((double) $default);
434 $this->_minval = (double) $minval;
435 $this->_maxval = (double) $maxval;
438 function sanify ($value) {
439 $value = (double) $value;
440 if ($this->_minval !== false && $value < $this->_minval)
441 $value = $this->_minval;
442 if ($this->_maxval !== false && $value > $this->_maxval)
443 $value = $this->_maxval;
448 class _UserPreference_int extends _UserPreference_numeric
450 function _UserPreference_int ($default, $minval = false, $maxval = false) {
451 $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
454 function sanify ($value) {
455 return (int) parent::sanify((int)$value);
459 class _UserPreference_bool extends _UserPreference
461 function _UserPreference_bool ($default = false) {
462 $this->_UserPreference((bool) $default);
465 function sanify ($value) {
466 if (is_array($value)) {
467 /* This allows for constructs like:
469 * <input type="hidden" name="pref[boolPref][]" value="0" />
470 * <input type="checkbox" name="pref[boolPref][]" value="1" />
472 * (If the checkbox is not checked, only the hidden input gets sent.
473 * If the checkbox is sent, both inputs get sent.)
475 foreach ($value as $val) {
481 return (bool) $value;
485 // don't save default preferences for efficiency.
486 class UserPreferences {
487 function UserPreferences ($saved_prefs = false) {
488 $this->_prefs = array();
490 if (isa($saved_prefs, 'UserPreferences')) {
491 foreach ($saved_prefs->_prefs as $name => $value)
492 $this->set($name, $value);
493 } elseif (is_array($saved_prefs)) {
494 foreach ($saved_prefs as $name => $value)
495 $this->set($name, $value);
499 function _getPref ($name) {
500 global $UserPreferences;
501 if (!isset($UserPreferences[$name])) {
502 if ($name == 'passwd2') return false;
503 trigger_error("$name: unknown preference", E_USER_NOTICE);
506 return $UserPreferences[$name];
509 function get ($name) {
510 if (isset($this->_prefs[$name]))
511 return $this->_prefs[$name];
512 if (!($pref = $this->_getPref($name)))
514 return $pref->default_value;
517 function set ($name, $value) {
518 if (!($pref = $this->_getPref($name)))
520 // don't set default values to safe space (in cookies, db and sesssion)
521 if ($value == $pref->default_value)
522 unset($this->_prefs[$name]);
525 $newvalue = $pref->sanify($value);
526 if (!empty($this->_prefs[$name]) and $this->_prefs[$name] != $newvalue) {
528 // check updates (theme, lang, ...)
531 include_once("themes/$value/themeinfo.php");
534 $LANG = ($value == 'en') ? 'C' : $value;
535 update_locale ($LANG);
539 $this->_prefs[$name] = $pref->sanify($value);
548 // c-hanging-comment-ender-p: nil
549 // indent-tabs-mode: nil