1 <?php rcs_id('$Id: WikiUser.php,v 1.17 2002-08-23 18:29:29 rurban 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 = '';
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;
67 if (empty($this->_userid) || empty($this->_level)) {
68 // This is okay if truly logged out.
69 return $this->_userid === false && $this->_level === false;
71 // User is logged in...
73 // Check for valid authlevel.
74 if (!in_array($this->_level, array(WIKIAUTH_BOGO, WIKIAUTH_USER, WIKIAUTH_ADMIN)))
77 // Check for valid userid.
78 if (!is_string($this->_userid))
84 return ( $this->isSignedIn()
86 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
89 function getAuthenticatedId() {
90 return ( $this->isAuthenticated()
92 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
95 function isSignedIn () {
96 return $this->_level >= WIKIAUTH_BOGO;
99 function isAuthenticated () {
100 return $this->_level >= WIKIAUTH_USER;
103 function isAdmin () {
104 return $this->_level == WIKIAUTH_ADMIN;
107 function hasAuthority ($require_level) {
108 return $this->_level >= $require_level;
112 function AuthCheck ($postargs) {
113 // Normalize args, and extract.
114 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', 'cancel');
115 foreach ($keys as $key)
116 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
118 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
121 return new WikiUser; // Log out
123 return false; // User hit cancel button.
124 elseif (!$login && !$userid)
125 return false; // Nothing to do?
127 $authlevel = $this->_pwcheck($userid, $passwd);
129 return _("Invalid password or userid.");
130 elseif ($authlevel < $require_level)
131 return _("Insufficient permissions.");
134 $user = new WikiUser;
135 $user->_userid = $userid;
136 $user->_level = $authlevel;
140 function PrintLoginForm (&$request, $args, $fail_message = false, $seperate_page = true) {
141 include_once('lib/Template.php');
145 extract($args); // fixme
147 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
149 $pagename = $request->getArg('pagename');
150 $login = new Template('login', $request,
151 compact('pagename', 'userid', 'require_level', 'fail_message', 'pass_required'));
152 if ($seperate_page) {
153 $top = new Template('html', $request, array('TITLE' => _("Sign In")));
154 return $top->printExpansion($login);
163 function _pwcheck ($userid, $passwd) {
164 global $WikiNameRegexp;
166 if (!empty($userid) && $userid == ADMIN_USER) {
167 // $this->_authmethod = 'pagedata';
168 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
169 if (!empty($passwd) && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD)
170 return WIKIAUTH_ADMIN;
171 if (!empty($passwd)) {
172 if ($passwd == ADMIN_PASSWD)
173 return WIKIAUTH_ADMIN;
175 // maybe we forgot to enable ENCRYPTED_PASSWD?
176 if (function_exists('crypt') and crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD) {
177 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"), E_USER_WARNING);
178 return WIKIAUTH_ADMIN;
184 // HTTP Authentification
185 elseif (ALLOW_HTTP_AUTH_LOGIN and !empty($PHP_AUTH_USER)) {
186 // if he ignored the password field, because he is already authentificated
187 // try the previously given password.
188 if (empty($passwd)) $passwd = $PHP_AUTH_PW;
191 // WikiDB_User DB/File Authentification from $DBAuthParams
192 // Check if we have the user. If not try other methods.
193 if (ALLOW_USER_LOGIN and !empty($passwd)) {
194 $request = $this->_request;
195 // first check if the user is known
196 if ($this->exists($userid)) {
197 $this->_authmethod = 'pagedata';
198 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
200 // else try others such as LDAP authentication:
201 if (ALLOW_LDAP_LOGIN and !empty($passwd)) {
202 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
203 $r = @ldap_bind($ldap); // this is an anonymous bind
204 $st_search = "uid=$userid";
205 // Need to set the right root search information. see ../index.php
206 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH, "$st_search");
207 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
208 for ($i=0; $i<$info["count"]; $i++) {
209 $dn = $info[$i]["dn"];
210 // The password is still plain text.
211 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
212 // ldap_bind will return TRUE if everything matches
214 $this->_authmethod = 'LDAP';
215 return WIKIAUTH_USER;
219 trigger_error("Unable to connect to LDAP server " . LDAP_AUTH_HOST, E_USER_WARNING);
222 // imap authentication. added by limako
223 if (ALLOW_IMAP_LOGIN and !empty($passwd)) {
224 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}", $userid, $passwd, OP_HALFOPEN );
227 $this->_authmethod = 'IMAP';
228 return WIKIAUTH_USER;
234 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)) {
235 $this->_authmethod = 'BOGO';
236 return WIKIAUTH_BOGO;
241 // Todo: try our WikiDB backends.
242 function getPreferences() {
243 // Restore saved preferences.
244 // I'd rather prefer only to store the UserId in the cookie or session,
245 // and get the preferences from the db or page.
246 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
247 $prefs = $this->request->getSessionVar('wiki_prefs');
249 if (!$this->_userid and !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
250 $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
253 // before we get his prefs we should check if he is signed in
254 if (!$prefs->_prefs and USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
255 if ($pref = $this->_homepage->get('pref'))
256 $prefs = unserialize($pref);
258 return new UserPreferences($prefs);
261 // No cookies anymore for all prefs, only the userid.
262 // PHP creates a session cookie in memory, which is much more efficient.
263 function setPreferences($prefs, $id_only = false) {
265 $this->_request->setSessionVar('wiki_prefs', $prefs);
266 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
267 // simple unpacked cookie
268 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
270 // We must ensure that any password is encrypted.
271 // We don't need any plaintext password.
272 if (! $id_only and $this->isSignedIn() and ($homepage = $this->homePage())) {
273 if ($this->isAdmin())
274 $prefs->set('passwd',''); // this is already stored in index.php,
275 // and it might be plaintext! well oh well
276 $homepage->set('pref',serialize($prefs->_prefs));
280 // check for homepage with user flag.
281 // can be overriden from the auth backends
283 $homepage = $this->homePage();
284 return ($this->_userid and $homepage and $homepage->get('pref'));
287 // doesn't check for existance!!! hmm.
288 // how to store metadata in not existing pages? how about versions?
289 function homePage() {
290 if (!$this->_userid) return false;
291 if ($this->_homepage)
292 return $this->_homepage;
294 $this->_homepage = $this->_dbi->getPage($this->_userid);
295 return $this->_homepage;
299 // create user by checking his homepage
300 function createUser ($pref, $createDefaultHomepage = true) {
301 if ($this->exists()) return;
302 if ($createDefaultHomepage) {
303 $this->createHomepage ($pref);
306 include "lib/loadsave.php";
307 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
308 'versiondata' => array('author' => $this->_userid),
309 'pagename' => $this->_userid,
310 'content' => _('CategoryHomepage'));
311 SavePage (&$this->_request, $pageinfo, false, false);
313 $this->setPreferences($pref);
316 // create user and default user homepage
317 function createHomepage ($pref) {
318 $pagename = $this->_userid;
319 include "lib/loadsave.php";
321 // create default homepage:
322 // properly expanded template and the pref metadata
323 $template = Template('homepage.tmpl',$this->_request);
324 $text = $template->getExpansion();
325 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
326 'versiondata' => array('author' => $this->_userid),
327 'pagename' => $pagename,
329 SavePage (&$this->_request, $pageinfo, false, false);
332 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
333 if (! isWikiPage($pagename)) {
334 $pageinfo = array('pagedata' => array(),
335 'versiondata' => array('author' => $this->_userid),
336 'pagename' => $pagename,
337 'content' => "<?plugin Calender ?>\n");
338 SavePage (&$this->_request, $pageinfo, false, false);
341 // create Preferences
342 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
343 if (! isWikiPage($pagename)) {
344 $pageinfo = array('pagedata' => array(),
345 'versiondata' => array('author' => $this->_userid),
346 'pagename' => $pagename,
347 'content' => "<?plugin UserPreferences ?>\n");
348 SavePage (&$this->_request, $pageinfo, false, false);
352 function tryAuthBackends() {
353 return ''; // crypt('') will never be ''
356 // Auth backends must store the crypted password where?
357 // Not in the preferences.
358 function checkPassword($passwd) {
359 $prefs = $this->getPreferences();
360 $stored_passwd = $prefs->get('passwd'); // crypted
361 if (empty($prefs->_prefs['passwd'])) // not stored in the page
362 // allow empty passwords? At least store a '*' then.
364 $stored_passwd = $this->tryAuthBackends($this->_userid);
365 if (empty($stored_passwd)) {
366 trigger_error(sprintf(_("WikiUser backend problem: Old UserPage %s. No password to check against! Update your UserPreferences."), $this->_userid), E_USER_NOTICE);
370 if ($stored_passwd == '*')
372 if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
378 function changePassword($newpasswd, $passwd2 = false) {
379 if (! $this->mayChangePassword() ) {
380 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
381 $this->_userid), E_USER_ERROR);
384 if ($passwd2 and $passwd2 != $newpasswd) {
385 trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
388 $prefs = $this->getPreferences();
389 //$oldpasswd = $prefs->get('passwd');
390 $prefs->set('passwd', crypt($newpasswd));
391 $this->setPreferences($prefs);
394 function mayChangePassword() {
395 // on external DBAuth maybe. on IMAP or LDAP not
396 // on internal DBAuth yes
397 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
399 if ($this->isAdmin())
401 if ($this->_authmethod == 'pagedata')
403 if ($this->_authmethod == 'authdb')
408 // create user and default user homepage
409 function createUser ($userid, $pref) {
410 $user = new WikiUser ($userid);
411 $user->createUser($pref);
414 class _UserPreference
416 function _UserPreference ($default_value) {
417 $this->default_value = $default_value;
420 function sanify ($value) {
421 return (string) $value;
425 class _UserPreference_numeric extends _UserPreference
427 function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
428 $this->_UserPreference((double) $default);
429 $this->_minval = (double) $minval;
430 $this->_maxval = (double) $maxval;
433 function sanify ($value) {
434 $value = (double) $value;
435 if ($this->_minval !== false && $value < $this->_minval)
436 $value = $this->_minval;
437 if ($this->_maxval !== false && $value > $this->_maxval)
438 $value = $this->_maxval;
443 class _UserPreference_int extends _UserPreference_numeric
445 function _UserPreference_int ($default, $minval = false, $maxval = false) {
446 $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
449 function sanify ($value) {
450 return (int) parent::sanify((int)$value);
454 class _UserPreference_bool extends _UserPreference
456 function _UserPreference_bool ($default = false) {
457 $this->_UserPreference((bool) $default);
460 function sanify ($value) {
461 if (is_array($value)) {
462 /* This allows for constructs like:
464 * <input type="hidden" name="pref[boolPref][]" value="0" />
465 * <input type="checkbox" name="pref[boolPref][]" value="1" />
467 * (If the checkbox is not checked, only the hidden input gets sent.
468 * If the checkbox is sent, both inputs get sent.)
470 foreach ($value as $val) {
476 return (bool) $value;
480 // don't save default preferences for efficiency.
481 class UserPreferences {
482 function UserPreferences ($saved_prefs = false) {
483 $this->_prefs = array();
485 if (isa($saved_prefs, 'UserPreferences')) {
486 foreach ($saved_prefs->_prefs as $name => $value)
487 $this->set($name, $value);
488 } elseif (is_array($saved_prefs)) {
489 foreach ($saved_prefs as $name => $value)
490 $this->set($name, $value);
494 function _getPref ($name) {
495 global $UserPreferences;
496 if (!isset($UserPreferences[$name])) {
497 if ($name == 'passwd2') return false;
498 trigger_error("$name: unknown preference", E_USER_NOTICE);
501 return $UserPreferences[$name];
504 function get ($name) {
505 if (isset($this->_prefs[$name]))
506 return $this->_prefs[$name];
507 if (!($pref = $this->_getPref($name)))
509 return $pref->default_value;
512 function set ($name, $value) {
513 if (!($pref = $this->_getPref($name)))
515 // don't set default values to safe space (in cookies, db and sesssion)
516 if ($value == $pref->default_value)
517 unset($this->_prefs[$name]);
520 $newvalue = $pref->sanify($value);
521 if (!empty($this->_prefs[$name]) and $this->_prefs[$name] != $newvalue) {
523 // check updates (theme, lang, ...)
526 include_once("themes/$value/themeinfo.php");
529 $LANG = ($value == 'en') ? 'C' : $value;
530 update_locale ($LANG);
534 $this->_prefs[$name] = $pref->sanify($value);
543 // c-hanging-comment-ender-p: nil
544 // indent-tabs-mode: nil