1 <?php rcs_id('$Id: WikiUser.php,v 1.21 2002-08-30 04:49:59 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(''), // really store this also?
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.
269 // Return the number of changed entries?
270 function setPreferences($prefs, $id_only = false) {
272 $this->_request->setSessionVar('wiki_prefs', $prefs);
273 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
274 // simple unpacked cookie
275 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
277 // We must ensure that any password is encrypted.
278 // We don't need any plaintext password.
280 if ($this->isSignedIn()) {
281 if ($this->isAdmin()) $prefs->set('passwd',''); // this is already stored in index.php,
282 // and it might be plaintext! well oh well
283 if ($homepage = $this->homePage()) {
284 $homepage->set('pref',serialize($prefs->_prefs));
285 return sizeof($prefs->_prefs);
287 trigger_error('No homepage for user found. Creating one...', E_USER_WARNING);
288 $this->createHomepage($prefs);
289 //$homepage->set('pref',serialize($prefs->_prefs));
290 return sizeof($prefs->_prefs);
293 trigger_error('you must be signed in',E_USER_WARNING);
299 // check for homepage with user flag.
300 // can be overriden from the auth backends
302 $homepage = $this->homePage();
303 return ($this->_userid and $homepage and $homepage->get('pref'));
306 // doesn't check for existance!!! hmm.
307 // how to store metadata in not existing pages? how about versions?
308 function homePage() {
309 if (!$this->_userid) return false;
310 if ($this->_homepage)
311 return $this->_homepage;
313 $this->_homepage = $this->_dbi->getPage($this->_userid);
314 return $this->_homepage;
318 // create user by checking his homepage
319 function createUser ($pref, $createDefaultHomepage = true) {
320 if ($this->exists()) return;
321 if ($createDefaultHomepage) {
322 $this->createHomepage ($pref);
325 include "lib/loadsave.php";
326 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
327 'versiondata' => array('author' => $this->_userid),
328 'pagename' => $this->_userid,
329 'content' => _('CategoryHomepage'));
330 SavePage (&$this->_request, $pageinfo, false, false);
332 $this->setPreferences($pref);
335 // create user and default user homepage
336 function createHomepage ($pref) {
337 $pagename = $this->_userid;
338 include "lib/loadsave.php";
340 // create default homepage:
341 // properly expanded template and the pref metadata
342 $template = Template('homepage.tmpl',$this->_request);
343 $text = $template->getExpansion();
344 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
345 'versiondata' => array('author' => $this->_userid),
346 'pagename' => $pagename,
348 SavePage (&$this->_request, $pageinfo, false, false);
351 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
352 if (! isWikiPage($pagename)) {
353 $pageinfo = array('pagedata' => array(),
354 'versiondata' => array('author' => $this->_userid),
355 'pagename' => $pagename,
356 'content' => "<?plugin Calender ?>\n");
357 SavePage (&$this->_request, $pageinfo, false, false);
360 // create Preferences
361 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
362 if (! isWikiPage($pagename)) {
363 $pageinfo = array('pagedata' => array(),
364 'versiondata' => array('author' => $this->_userid),
365 'pagename' => $pagename,
366 'content' => "<?plugin UserPreferences ?>\n");
367 SavePage (&$this->_request, $pageinfo, false, false);
371 function tryAuthBackends() {
372 return ''; // crypt('') will never be ''
375 // Auth backends must store the crypted password where?
376 // Not in the preferences.
377 function checkPassword($passwd) {
378 $prefs = $this->getPreferences();
379 $stored_passwd = $prefs->get('passwd'); // crypted
380 if (empty($prefs->_prefs['passwd'])) // not stored in the page
381 // allow empty passwords? At least store a '*' then.
382 // try other backend. hmm.
383 $stored_passwd = $this->tryAuthBackends($this->_userid);
384 if (empty($stored_passwd)) {
385 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), $this->_userid), E_USER_NOTICE);
386 $prefs->set('passwd','*');
389 if ($stored_passwd == '*')
391 if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
397 function changePassword($newpasswd, $passwd2 = false) {
398 if (! $this->mayChangePassword() ) {
399 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
400 $this->_userid), E_USER_ERROR);
403 if ($passwd2 and $passwd2 != $newpasswd) {
404 trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
407 $prefs = $this->getPreferences();
408 //$oldpasswd = $prefs->get('passwd');
409 $prefs->set('passwd', crypt($newpasswd));
410 $this->setPreferences($prefs);
413 function mayChangePassword() {
414 // on external DBAuth maybe. on IMAP or LDAP not
415 // on internal DBAuth yes
416 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
418 if ($this->isAdmin())
420 if ($this->_authmethod == 'pagedata')
422 if ($this->_authmethod == 'authdb')
427 // create user and default user homepage
428 function createUser ($userid, $pref) {
429 $user = new WikiUser ($userid);
430 $user->createUser($pref);
433 class _UserPreference
435 function _UserPreference ($default_value) {
436 $this->default_value = $default_value;
439 function sanify ($value) {
440 return (string) $value;
444 class _UserPreference_numeric extends _UserPreference
446 function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
447 $this->_UserPreference((double) $default);
448 $this->_minval = (double) $minval;
449 $this->_maxval = (double) $maxval;
452 function sanify ($value) {
453 $value = (double) $value;
454 if ($this->_minval !== false && $value < $this->_minval)
455 $value = $this->_minval;
456 if ($this->_maxval !== false && $value > $this->_maxval)
457 $value = $this->_maxval;
462 class _UserPreference_int extends _UserPreference_numeric
464 function _UserPreference_int ($default, $minval = false, $maxval = false) {
465 $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
468 function sanify ($value) {
469 return (int) parent::sanify((int)$value);
473 class _UserPreference_bool extends _UserPreference
475 function _UserPreference_bool ($default = false) {
476 $this->_UserPreference((bool) $default);
479 function sanify ($value) {
480 if (is_array($value)) {
481 /* This allows for constructs like:
483 * <input type="hidden" name="pref[boolPref][]" value="0" />
484 * <input type="checkbox" name="pref[boolPref][]" value="1" />
486 * (If the checkbox is not checked, only the hidden input gets sent.
487 * If the checkbox is sent, both inputs get sent.)
489 foreach ($value as $val) {
495 return (bool) $value;
499 // don't save default preferences for efficiency.
500 class UserPreferences {
501 function UserPreferences ($saved_prefs = false) {
502 $this->_prefs = array();
504 if (isa($saved_prefs, 'UserPreferences')) {
505 foreach ($saved_prefs->_prefs as $name => $value)
506 $this->set($name, $value);
507 } elseif (is_array($saved_prefs)) {
508 foreach ($saved_prefs as $name => $value)
509 $this->set($name, $value);
513 function _getPref ($name) {
514 global $UserPreferences;
515 if (!isset($UserPreferences[$name])) {
516 if ($name == 'passwd2') return false;
517 trigger_error("$name: unknown preference", E_USER_NOTICE);
520 return $UserPreferences[$name];
523 function get ($name) {
524 if (isset($this->_prefs[$name]))
525 return $this->_prefs[$name];
526 if (!($pref = $this->_getPref($name)))
528 return $pref->default_value;
531 function set ($name, $value) {
532 if (!($pref = $this->_getPref($name)))
534 // don't set default values to safe space (in cookies, db and sesssion)
535 if ($value == $pref->default_value)
536 unset($this->_prefs[$name]);
539 $newvalue = $pref->sanify($value);
540 if (!empty($this->_prefs[$name]) and $this->_prefs[$name] != $newvalue) {
542 // check updates (theme, lang, ...)
545 include_once("themes/$value/themeinfo.php");
548 update_locale ($LANG);
549 $GLOBALS['LANG'] = $value;
553 $this->_prefs[$name] = $pref->sanify($value);
562 // c-hanging-comment-ender-p: nil
563 // indent-tabs-mode: nil