1 <?php rcs_id('$Id: WikiUser.php,v 1.25 2002-09-18 18:35:24 dairiki 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 // 2002-09-08 11:44:04 rurban
13 // Todo: Fix prefs cookie/session handling:
14 // _userid and _homepage cookie/session vars still hold the serialized string.
15 // 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()
42 var $_request, $_dbi, $_authdbi, $_homepage;
43 var $_authmethod = '', $_authhow = '';
48 function WikiUser ($userid = false, $authlevel = false) {
49 $this->_request = &$GLOBALS['request'];
50 $this->_dbi = &$this->_request->getDbh();
52 if (isa($userid, 'WikiUser')) {
53 $this->_userid = $userid->_userid;
54 $this->_level = $userid->_level;
57 $this->_userid = $userid;
58 $this->_level = $authlevel;
61 $this->_homepage = $this->_dbi->getPage($this->_userid);
63 // Paranoia: if state is at all inconsistent, log out...
64 $this->_userid = false;
65 $this->_level = false;
66 $this->_homepage = false;
67 $this->_authhow .= ' paranoia logout';
72 return $this->_authhow;
78 if (empty($this->_userid) || empty($this->_level)) {
79 // This is okay if truly logged out.
80 return $this->_userid === false && $this->_level === false;
82 // User is logged in...
84 // Check for valid authlevel.
85 if (!in_array($this->_level, array(WIKIAUTH_BOGO, WIKIAUTH_USER, WIKIAUTH_ADMIN)))
88 // Check for valid userid.
89 if (!is_string($this->_userid))
95 return ( $this->isSignedIn()
97 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
100 function getAuthenticatedId() {
101 return ( $this->isAuthenticated()
103 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
106 function isSignedIn () {
107 return $this->_level >= WIKIAUTH_BOGO;
110 function isAuthenticated () {
111 return $this->_level >= WIKIAUTH_USER;
114 function isAdmin () {
115 return $this->_level == WIKIAUTH_ADMIN;
118 function hasAuthority ($require_level) {
119 return $this->_level >= $require_level;
122 function AuthCheck ($postargs) {
123 // Normalize args, and extract.
124 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', 'cancel');
125 foreach ($keys as $key)
126 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
128 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
131 return new WikiUser; // Log out
133 return false; // User hit cancel button.
134 elseif (!$login && !$userid)
135 return false; // Nothing to do?
137 $authlevel = $this->_pwcheck($userid, $passwd);
139 return _("Invalid password or userid.");
140 elseif ($authlevel < $require_level)
141 return _("Insufficient permissions.");
144 $user = new WikiUser;
145 $user->_userid = $userid;
146 $user->_level = $authlevel;
150 function PrintLoginForm (&$request, $args, $fail_message = false, $seperate_page = true) {
151 include_once('lib/Template.php');
155 extract($args); // fixme
157 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
159 $pagename = $request->getArg('pagename');
160 $login = new Template('login', $request,
161 compact('pagename', 'userid', 'require_level', 'fail_message', 'pass_required'));
162 if ($seperate_page) {
163 $top = new Template('html', $request, array('TITLE' => _("Sign In")));
164 return $top->printExpansion($login);
173 function _pwcheck ($userid, $passwd) {
174 global $WikiNameRegexp;
176 if (!empty($userid) && $userid == ADMIN_USER) {
177 // $this->_authmethod = 'pagedata';
178 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
179 if (!empty($passwd) && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD)
180 return WIKIAUTH_ADMIN;
181 if (!empty($passwd)) {
182 if ($passwd == ADMIN_PASSWD)
183 return WIKIAUTH_ADMIN;
185 // maybe we forgot to enable ENCRYPTED_PASSWD?
186 if (function_exists('crypt') and crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD) {
187 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"), E_USER_WARNING);
188 return WIKIAUTH_ADMIN;
194 // HTTP Authentification
195 elseif (ALLOW_HTTP_AUTH_LOGIN and !empty($PHP_AUTH_USER)) {
196 // if he ignored the password field, because he is already authentificated
197 // try the previously given password.
198 if (empty($passwd)) $passwd = $PHP_AUTH_PW;
201 // WikiDB_User DB/File Authentification from $DBAuthParams
202 // Check if we have the user. If not try other methods.
203 if (ALLOW_USER_LOGIN) { // and !empty($passwd)) {
204 $request = $this->_request;
205 // first check if the user is known
206 if ($this->exists($userid)) {
207 $this->_authmethod = 'pagedata';
208 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
210 // else try others such as LDAP authentication:
211 if (ALLOW_LDAP_LOGIN and !empty($passwd)) {
212 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
213 $r = @ldap_bind($ldap); // this is an anonymous bind
214 $st_search = "uid=$userid";
215 // Need to set the right root search information. see ../index.php
216 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH, "$st_search");
217 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
218 for ($i=0; $i<$info["count"]; $i++) {
219 $dn = $info[$i]["dn"];
220 // The password is still plain text.
221 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
222 // ldap_bind will return TRUE if everything matches
224 $this->_authmethod = 'LDAP';
225 return WIKIAUTH_USER;
229 trigger_error("Unable to connect to LDAP server " . LDAP_AUTH_HOST, E_USER_WARNING);
232 // imap authentication. added by limako
233 if (ALLOW_IMAP_LOGIN and !empty($passwd)) {
234 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}", $userid, $passwd, OP_HALFOPEN );
237 $this->_authmethod = 'IMAP';
238 return WIKIAUTH_USER;
244 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)) {
245 $this->_authmethod = 'BOGO';
246 return WIKIAUTH_BOGO;
251 // Todo: try our WikiDB backends.
252 function getPreferences() {
253 // Restore saved preferences.
254 // I'd rather prefer only to store the UserId in the cookie or session,
255 // and get the preferences from the db or page.
256 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
257 $prefs = $this->_request->getSessionVar('wiki_prefs');
259 //if (!$this->_userid and !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
260 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
263 // before we get his prefs we should check if he is signed in
264 if (!$prefs->_prefs and USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
265 if ($pref = $this->_homepage->get('pref'))
266 $prefs = unserialize($pref);
268 return new UserPreferences($prefs);
271 // No cookies anymore for all prefs, only the userid.
272 // PHP creates a session cookie in memory, which is much more efficient.
274 // Return the number of changed entries?
275 function setPreferences($prefs, $id_only = false) {
277 $this->_request->setSessionVar('wiki_prefs', $prefs);
278 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
279 // simple unpacked cookie
280 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
282 // We must ensure that any password is encrypted.
283 // We don't need any plaintext password.
285 if ($this->isSignedIn()) {
286 if ($this->isAdmin()) $prefs->set('passwd',''); // this is already stored in index.php,
287 // and it might be plaintext! well oh well
288 if ($homepage = $this->homePage()) {
289 $homepage->set('pref',serialize($prefs->_prefs));
290 return sizeof($prefs->_prefs);
292 trigger_error('No homepage for user found. Creating one...', E_USER_WARNING);
293 $this->createHomepage($prefs);
294 //$homepage->set('pref',serialize($prefs->_prefs));
295 return sizeof($prefs->_prefs);
298 trigger_error('you must be signed in',E_USER_WARNING);
304 // check for homepage with user flag.
305 // can be overriden from the auth backends
307 $homepage = $this->homePage();
308 return ($this->_userid and $homepage and $homepage->get('pref'));
311 // doesn't check for existance!!! hmm.
312 // how to store metadata in not existing pages? how about versions?
313 function homePage() {
314 if (!$this->_userid) return false;
315 if (!empty($this->_homepage)) {
316 return $this->_homepage;
318 $this->_homepage = $this->_dbi->getPage($this->_userid);
319 return $this->_homepage;
323 // create user by checking his homepage
324 function createUser ($pref, $createDefaultHomepage = true) {
325 if ($this->exists()) return;
326 if ($createDefaultHomepage) {
327 $this->createHomepage ($pref);
330 include "lib/loadsave.php";
331 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
332 'versiondata' => array('author' => $this->_userid),
333 'pagename' => $this->_userid,
334 'content' => _('CategoryHomepage'));
335 SavePage (&$this->_request, $pageinfo, false, false);
337 $this->setPreferences($pref);
340 // create user and default user homepage
341 function createHomepage ($pref) {
342 $pagename = $this->_userid;
343 include "lib/loadsave.php";
345 // create default homepage:
346 // properly expanded template and the pref metadata
347 $template = Template('homepage.tmpl',$this->_request);
348 $text = $template->getExpansion();
349 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
350 'versiondata' => array('author' => $this->_userid),
351 'pagename' => $pagename,
353 SavePage (&$this->_request, $pageinfo, false, false);
356 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
357 if (! isWikiPage($pagename)) {
358 $pageinfo = array('pagedata' => array(),
359 'versiondata' => array('author' => $this->_userid),
360 'pagename' => $pagename,
361 'content' => "<?plugin Calender ?>\n");
362 SavePage (&$this->_request, $pageinfo, false, false);
365 // create Preferences
366 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
367 if (! isWikiPage($pagename)) {
368 $pageinfo = array('pagedata' => array(),
369 'versiondata' => array('author' => $this->_userid),
370 'pagename' => $pagename,
371 'content' => "<?plugin UserPreferences ?>\n");
372 SavePage (&$this->_request, $pageinfo, false, false);
376 function tryAuthBackends() {
377 return ''; // crypt('') will never be ''
380 // Auth backends must store the crypted password where?
381 // Not in the preferences.
382 function checkPassword($passwd) {
383 $prefs = $this->getPreferences();
384 $stored_passwd = $prefs->get('passwd'); // crypted
385 if (empty($prefs->_prefs['passwd'])) // not stored in the page
386 // allow empty passwords? At least store a '*' then.
387 // try other backend. hmm.
388 $stored_passwd = $this->tryAuthBackends($this->_userid);
389 if (empty($stored_passwd)) {
390 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), $this->_userid), E_USER_NOTICE);
391 $prefs->set('passwd','*');
394 if ($stored_passwd == '*')
396 if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
402 function changePassword($newpasswd, $passwd2 = false) {
403 if (! $this->mayChangePassword() ) {
404 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
405 $this->_userid), E_USER_ERROR);
408 if ($passwd2 and $passwd2 != $newpasswd) {
409 trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
412 $prefs = $this->getPreferences();
413 //$oldpasswd = $prefs->get('passwd');
414 $prefs->set('passwd', crypt($newpasswd));
415 $this->setPreferences($prefs);
418 function mayChangePassword() {
419 // on external DBAuth maybe. on IMAP or LDAP not
420 // on internal DBAuth yes
421 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
423 if ($this->isAdmin())
425 if ($this->_authmethod == 'pagedata')
427 if ($this->_authmethod == 'authdb')
432 // create user and default user homepage
433 function createUser ($userid, $pref) {
434 $user = new WikiUser ($userid);
435 $user->createUser($pref);
438 class _UserPreference
440 function _UserPreference ($default_value) {
441 $this->default_value = $default_value;
444 function sanify ($value) {
445 return (string) $value;
448 function update ($value) {
452 class _UserPreference_numeric extends _UserPreference
454 function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
455 $this->_UserPreference((double) $default);
456 $this->_minval = (double) $minval;
457 $this->_maxval = (double) $maxval;
460 function sanify ($value) {
461 $value = (double) $value;
462 if ($this->_minval !== false && $value < $this->_minval)
463 $value = $this->_minval;
464 if ($this->_maxval !== false && $value > $this->_maxval)
465 $value = $this->_maxval;
470 class _UserPreference_int extends _UserPreference_numeric
472 function _UserPreference_int ($default, $minval = false, $maxval = false) {
473 $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
476 function sanify ($value) {
477 return (int) parent::sanify((int)$value);
481 class _UserPreference_bool extends _UserPreference
483 function _UserPreference_bool ($default = false) {
484 $this->_UserPreference((bool) $default);
487 function sanify ($value) {
488 if (is_array($value)) {
489 /* This allows for constructs like:
491 * <input type="hidden" name="pref[boolPref][]" value="0" />
492 * <input type="checkbox" name="pref[boolPref][]" value="1" />
494 * (If the checkbox is not checked, only the hidden input gets sent.
495 * If the checkbox is sent, both inputs get sent.)
497 foreach ($value as $val) {
503 return (bool) $value;
508 class _UserPreference_language extends _UserPreference
510 function _UserPreference_language ($default = 'en') {
511 $this->_UserPreference($default);
514 function sanify ($value) {
515 // FIXME: check for valid locale
518 function update ($newvalue) {
519 update_locale ($newvalue);
523 class _UserPreference_theme extends _UserPreference
525 function _UserPreference_theme ($default = 'default') {
526 $this->_UserPreference($default);
529 function sanify ($value) {
530 if (file_exists($this->_themefile($value)))
532 return $this->default;
535 function update ($newvalue) {
536 include($this->_themefile($value));
539 function _themefile ($theme) {
540 return "themes/$theme/themeinfo.php";
544 // don't save default preferences for efficiency.
545 class UserPreferences {
546 function UserPreferences ($saved_prefs = false) {
547 $this->_prefs = array();
549 if (isa($saved_prefs, 'UserPreferences') and $saved_prefs->_prefs) {
550 foreach ($saved_prefs->_prefs as $name => $value)
551 $this->set($name, $value);
552 } elseif (is_array($saved_prefs)) {
553 foreach ($saved_prefs as $name => $value)
554 $this->set($name, $value);
558 function _getPref ($name) {
559 global $UserPreferences;
560 if (!isset($UserPreferences[$name])) {
561 if ($name == 'passwd2') return false;
562 trigger_error("$name: unknown preference", E_USER_NOTICE);
565 return $UserPreferences[$name];
568 function get ($name) {
569 if (isset($this->_prefs[$name]))
570 return $this->_prefs[$name];
571 if (!($pref = $this->_getPref($name)))
573 return $pref->default_value;
576 function set ($name, $value) {
577 if (!($pref = $this->_getPref($name)))
580 $newvalue = $pref->sanify($value);
581 $oldvalue = $this->get($name);
584 if ($newvalue != $oldvalue)
585 $pref->update($newvalue);
587 // don't set default values to save space (in cookies, db and sesssion)
588 if ($value == $pref->default_value)
589 unset($this->_prefs[$name]);
591 $this->_prefs[$name] = $newvalue;
599 // c-hanging-comment-ender-p: nil
600 // indent-tabs-mode: nil