1 <?php rcs_id('$Id: WikiUser.php,v 1.22 2002-09-09 08:38:19 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 // 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),
32 'lang' => new _UserPreference($LANG),
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;
123 function AuthCheck ($postargs) {
124 // Normalize args, and extract.
125 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout', 'cancel');
126 foreach ($keys as $key)
127 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
129 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
132 return new WikiUser; // Log out
134 return false; // User hit cancel button.
135 elseif (!$login && !$userid)
136 return false; // Nothing to do?
138 $authlevel = $this->_pwcheck($userid, $passwd);
140 return _("Invalid password or userid.");
141 elseif ($authlevel < $require_level)
142 return _("Insufficient permissions.");
145 $user = new WikiUser;
146 $user->_userid = $userid;
147 $user->_level = $authlevel;
151 function PrintLoginForm (&$request, $args, $fail_message = false, $seperate_page = true) {
152 include_once('lib/Template.php');
156 extract($args); // fixme
158 $require_level = max(0, min(WIKIAUTH_ADMIN, (int) $require_level));
160 $pagename = $request->getArg('pagename');
161 $login = new Template('login', $request,
162 compact('pagename', 'userid', 'require_level', 'fail_message', 'pass_required'));
163 if ($seperate_page) {
164 $top = new Template('html', $request, array('TITLE' => _("Sign In")));
165 return $top->printExpansion($login);
174 function _pwcheck ($userid, $passwd) {
175 global $WikiNameRegexp;
177 if (!empty($userid) && $userid == ADMIN_USER) {
178 // $this->_authmethod = 'pagedata';
179 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
180 if (!empty($passwd) && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD)
181 return WIKIAUTH_ADMIN;
182 if (!empty($passwd)) {
183 if ($passwd == ADMIN_PASSWD)
184 return WIKIAUTH_ADMIN;
186 // maybe we forgot to enable ENCRYPTED_PASSWD?
187 if (function_exists('crypt') and crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD) {
188 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your /index.php"), E_USER_WARNING);
189 return WIKIAUTH_ADMIN;
195 // HTTP Authentification
196 elseif (ALLOW_HTTP_AUTH_LOGIN and !empty($PHP_AUTH_USER)) {
197 // if he ignored the password field, because he is already authentificated
198 // try the previously given password.
199 if (empty($passwd)) $passwd = $PHP_AUTH_PW;
202 // WikiDB_User DB/File Authentification from $DBAuthParams
203 // Check if we have the user. If not try other methods.
204 if (ALLOW_USER_LOGIN) { // and !empty($passwd)) {
205 $request = $this->_request;
206 // first check if the user is known
207 if ($this->exists($userid)) {
208 $this->_authmethod = 'pagedata';
209 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
211 // else try others such as LDAP authentication:
212 if (ALLOW_LDAP_LOGIN and !empty($passwd)) {
213 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
214 $r = @ldap_bind($ldap); // this is an anonymous bind
215 $st_search = "uid=$userid";
216 // Need to set the right root search information. see ../index.php
217 $sr = ldap_search($ldap, LDAP_AUTH_SEARCH, "$st_search");
218 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
219 for ($i=0; $i<$info["count"]; $i++) {
220 $dn = $info[$i]["dn"];
221 // The password is still plain text.
222 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
223 // ldap_bind will return TRUE if everything matches
225 $this->_authmethod = 'LDAP';
226 return WIKIAUTH_USER;
230 trigger_error("Unable to connect to LDAP server " . LDAP_AUTH_HOST, E_USER_WARNING);
233 // imap authentication. added by limako
234 if (ALLOW_IMAP_LOGIN and !empty($passwd)) {
235 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . ":143}", $userid, $passwd, OP_HALFOPEN );
238 $this->_authmethod = 'IMAP';
239 return WIKIAUTH_USER;
245 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)) {
246 $this->_authmethod = 'BOGO';
247 return WIKIAUTH_BOGO;
252 // Todo: try our WikiDB backends.
253 function getPreferences() {
254 // Restore saved preferences.
255 // I'd rather prefer only to store the UserId in the cookie or session,
256 // and get the preferences from the db or page.
257 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
258 $prefs = $this->_request->getSessionVar('wiki_prefs');
260 if (!$this->_userid and !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
261 $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
264 // before we get his prefs we should check if he is signed in
265 if (!$prefs->_prefs and USE_PREFS_IN_PAGE and $this->homePage()) { // in page metadata
266 if ($pref = $this->_homepage->get('pref'))
267 $prefs = unserialize($pref);
269 return new UserPreferences($prefs);
272 // No cookies anymore for all prefs, only the userid.
273 // PHP creates a session cookie in memory, which is much more efficient.
275 // Return the number of changed entries?
276 function setPreferences($prefs, $id_only = false) {
278 $this->_request->setSessionVar('wiki_prefs', $prefs);
279 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
280 // simple unpacked cookie
281 if ($this->_userid) setcookie('WIKI_ID', $this->_userid, 365, '/');
283 // We must ensure that any password is encrypted.
284 // We don't need any plaintext password.
286 if ($this->isSignedIn()) {
287 if ($this->isAdmin()) $prefs->set('passwd',''); // this is already stored in index.php,
288 // and it might be plaintext! well oh well
289 if ($homepage = $this->homePage()) {
290 $homepage->set('pref',serialize($prefs->_prefs));
291 return sizeof($prefs->_prefs);
293 trigger_error('No homepage for user found. Creating one...', E_USER_WARNING);
294 $this->createHomepage($prefs);
295 //$homepage->set('pref',serialize($prefs->_prefs));
296 return sizeof($prefs->_prefs);
299 trigger_error('you must be signed in',E_USER_WARNING);
305 // check for homepage with user flag.
306 // can be overriden from the auth backends
308 $homepage = $this->homePage();
309 return ($this->_userid and $homepage and $homepage->get('pref'));
312 // doesn't check for existance!!! hmm.
313 // how to store metadata in not existing pages? how about versions?
314 function homePage() {
315 if (!$this->_userid) return false;
316 if ($this->_homepage)
317 return $this->_homepage;
319 $this->_homepage = $this->_dbi->getPage($this->_userid);
320 return $this->_homepage;
324 // create user by checking his homepage
325 function createUser ($pref, $createDefaultHomepage = true) {
326 if ($this->exists()) return;
327 if ($createDefaultHomepage) {
328 $this->createHomepage ($pref);
331 include "lib/loadsave.php";
332 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
333 'versiondata' => array('author' => $this->_userid),
334 'pagename' => $this->_userid,
335 'content' => _('CategoryHomepage'));
336 SavePage (&$this->_request, $pageinfo, false, false);
338 $this->setPreferences($pref);
341 // create user and default user homepage
342 function createHomepage ($pref) {
343 $pagename = $this->_userid;
344 include "lib/loadsave.php";
346 // create default homepage:
347 // properly expanded template and the pref metadata
348 $template = Template('homepage.tmpl',$this->_request);
349 $text = $template->getExpansion();
350 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
351 'versiondata' => array('author' => $this->_userid),
352 'pagename' => $pagename,
354 SavePage (&$this->_request, $pageinfo, false, false);
357 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
358 if (! isWikiPage($pagename)) {
359 $pageinfo = array('pagedata' => array(),
360 'versiondata' => array('author' => $this->_userid),
361 'pagename' => $pagename,
362 'content' => "<?plugin Calender ?>\n");
363 SavePage (&$this->_request, $pageinfo, false, false);
366 // create Preferences
367 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
368 if (! isWikiPage($pagename)) {
369 $pageinfo = array('pagedata' => array(),
370 'versiondata' => array('author' => $this->_userid),
371 'pagename' => $pagename,
372 'content' => "<?plugin UserPreferences ?>\n");
373 SavePage (&$this->_request, $pageinfo, false, false);
377 function tryAuthBackends() {
378 return ''; // crypt('') will never be ''
381 // Auth backends must store the crypted password where?
382 // Not in the preferences.
383 function checkPassword($passwd) {
384 $prefs = $this->getPreferences();
385 $stored_passwd = $prefs->get('passwd'); // crypted
386 if (empty($prefs->_prefs['passwd'])) // not stored in the page
387 // allow empty passwords? At least store a '*' then.
388 // try other backend. hmm.
389 $stored_passwd = $this->tryAuthBackends($this->_userid);
390 if (empty($stored_passwd)) {
391 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."), $this->_userid), E_USER_NOTICE);
392 $prefs->set('passwd','*');
395 if ($stored_passwd == '*')
397 if (!empty($passwd) && crypt($passwd, $stored_passwd) == $stored_passwd)
403 function changePassword($newpasswd, $passwd2 = false) {
404 if (! $this->mayChangePassword() ) {
405 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
406 $this->_userid), E_USER_ERROR);
409 if ($passwd2 and $passwd2 != $newpasswd) {
410 trigger_error("The second passwort must be the same as the first to change it", E_USER_ERROR);
413 $prefs = $this->getPreferences();
414 //$oldpasswd = $prefs->get('passwd');
415 $prefs->set('passwd', crypt($newpasswd));
416 $this->setPreferences($prefs);
419 function mayChangePassword() {
420 // on external DBAuth maybe. on IMAP or LDAP not
421 // on internal DBAuth yes
422 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
424 if ($this->isAdmin())
426 if ($this->_authmethod == 'pagedata')
428 if ($this->_authmethod == 'authdb')
433 // create user and default user homepage
434 function createUser ($userid, $pref) {
435 $user = new WikiUser ($userid);
436 $user->createUser($pref);
439 class _UserPreference
441 function _UserPreference ($default_value) {
442 $this->default_value = $default_value;
445 function sanify ($value) {
446 return (string) $value;
450 class _UserPreference_numeric extends _UserPreference
452 function _UserPreference_numeric ($default, $minval = false, $maxval = false) {
453 $this->_UserPreference((double) $default);
454 $this->_minval = (double) $minval;
455 $this->_maxval = (double) $maxval;
458 function sanify ($value) {
459 $value = (double) $value;
460 if ($this->_minval !== false && $value < $this->_minval)
461 $value = $this->_minval;
462 if ($this->_maxval !== false && $value > $this->_maxval)
463 $value = $this->_maxval;
468 class _UserPreference_int extends _UserPreference_numeric
470 function _UserPreference_int ($default, $minval = false, $maxval = false) {
471 $this->_UserPreference_numeric((int) $default, (int)$minval, (int)$maxval);
474 function sanify ($value) {
475 return (int) parent::sanify((int)$value);
479 class _UserPreference_bool extends _UserPreference
481 function _UserPreference_bool ($default = false) {
482 $this->_UserPreference((bool) $default);
485 function sanify ($value) {
486 if (is_array($value)) {
487 /* This allows for constructs like:
489 * <input type="hidden" name="pref[boolPref][]" value="0" />
490 * <input type="checkbox" name="pref[boolPref][]" value="1" />
492 * (If the checkbox is not checked, only the hidden input gets sent.
493 * If the checkbox is sent, both inputs get sent.)
495 foreach ($value as $val) {
501 return (bool) $value;
505 // don't save default preferences for efficiency.
506 class UserPreferences {
507 function UserPreferences ($saved_prefs = false) {
508 $this->_prefs = array();
510 if (isa($saved_prefs, 'UserPreferences')) {
511 foreach ($saved_prefs->_prefs as $name => $value)
512 $this->set($name, $value);
513 } elseif (is_array($saved_prefs)) {
514 foreach ($saved_prefs as $name => $value)
515 $this->set($name, $value);
519 function _getPref ($name) {
520 global $UserPreferences;
521 if (!isset($UserPreferences[$name])) {
522 if ($name == 'passwd2') return false;
523 trigger_error("$name: unknown preference", E_USER_NOTICE);
526 return $UserPreferences[$name];
529 function get ($name) {
530 if (isset($this->_prefs[$name]))
531 return $this->_prefs[$name];
532 if (!($pref = $this->_getPref($name)))
534 return $pref->default_value;
537 function set ($name, $value) {
538 if (!($pref = $this->_getPref($name)))
540 // don't set default values to save space (in cookies, db and sesssion)
541 if ($value == $pref->default_value)
542 unset($this->_prefs[$name]);
545 $newvalue = $pref->sanify($value);
546 if (!empty($this->_prefs[$name]) and $this->_prefs[$name] != $newvalue) {
547 // check updates (theme, lang, ...)
550 include_once("themes/$newvalue/themeinfo.php");
553 update_locale ($newvalue);
557 $this->_prefs[$name] = $pref->sanify($value);
566 // c-hanging-comment-ender-p: nil
567 // indent-tabs-mode: nil