3 // It is anticipated that when userid support is added to phpwiki,
4 // this object will hold much more information (e-mail,
5 // home(wiki)page, etc.) about the user.
7 // There seems to be no clean way to "log out" a user when using HTTP
8 // authentication. So we'll hack around this by storing the currently
9 // logged in username and other state information in a cookie.
11 // 2002-09-08 11:44:04 rurban
12 // Todo: Fix prefs cookie/session handling:
13 // _userid and _homepage cookie/session vars still hold the
15 // If no homepage, fallback to prefs in cookie as in 1.3.3.
17 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
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); // Wiki Admin
23 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
25 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
26 if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
28 $UserPreferences = array(
29 'userid' => new _UserPreference(''), // really store this also?
30 'passwd' => new _UserPreference(''),
31 'email' => new _UserPreference(''),
32 'emailVerified' => new _UserPreference_bool(),
33 'notifyPages' => new _UserPreference(''),
34 'theme' => new _UserPreference_theme(THEME),
35 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
36 'editWidth' => new _UserPreference_int(80, 30, 150),
37 'noLinkIcons' => new _UserPreference_bool(),
38 'editHeight' => new _UserPreference_int(22, 5, 80),
39 'timeOffset' => new _UserPreference_numeric(0, -26, 26),
40 'relativeDates' => new _UserPreference_bool(),
41 'googleLink' => new _UserPreference_bool(), // 1.3.10
42 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
45 function WikiUserClassname() {
49 function UpgradeUser ($olduser, $user) {
50 if (isa($user,'WikiUser') and isa($olduser,'WikiUser')) {
51 // populate the upgraded class with the values from the old object
52 foreach (get_object_vars($olduser) as $k => $v) {
55 $GLOBALS['request']->_user = $user;
68 var $_request, $_dbi, $_authdbi, $_homepage;
69 var $_authmethod = '', $_authhow = '';
74 * Populates the instance variables and calls $this->_ok()
75 * to ensure that the parameters are valid.
76 * @param mixed $userid String of username or WikiUser object.
77 * @param integer $authlevel Authorization level.
79 function WikiUser (&$request, $userid = false, $authlevel = false) {
80 $this->_request =& $request;
81 $this->_dbi =& $this->_request->getDbh();
83 if (isa($userid, 'WikiUser')) {
84 $this->_userid = $userid->_userid;
85 $this->_level = $userid->_level;
88 $this->_userid = $userid;
89 $this->_level = $authlevel;
92 // Paranoia: if state is at all inconsistent, log out...
93 $this->_userid = false;
94 $this->_level = false;
95 $this->_homepage = false;
96 $this->_authhow .= ' paranoia logout';
99 $this->_homepage = $this->_dbi->getPage($this->_userid);
104 * Get the string indicating how the user was authenticated.
106 * Get the string indicating how the user was authenticated.
107 * Does not seem to be set - jbw
108 * @return string The method of authentication.
110 function auth_how() {
111 return $this->_authhow;
117 * If the WikiUser object has a valid authorization level and the
118 * userid is a string returns true, else false.
119 * @return boolean If valid level and username string true, else false
122 if ((in_array($this->_level, array(WIKIAUTH_BOGO,
126 (is_string($this->_userid)))) {
132 function UserName() {
133 return $this->_userid;
138 return $this->_userid;
139 if (!empty($this->_request))
140 return $this->_request->get('REMOTE_ADDR');
141 if (empty($this->_request))
142 return Request::get('REMOTE_ADDR');
143 return ( $this->isSignedIn()
145 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
148 function getAuthenticatedId() {
149 //assert($this->_request);
150 return ( $this->isAuthenticated()
152 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
155 function isSignedIn () {
156 return $this->_level >= WIKIAUTH_BOGO;
159 function isAuthenticated () {
160 return $this->_level >= WIKIAUTH_BOGO;
163 function isAdmin () {
164 return $this->_level == WIKIAUTH_ADMIN;
167 function hasAuthority ($require_level) {
168 return $this->_level >= $require_level;
171 function isValidName ($userid = false) {
173 $userid = $this->_userid;
174 return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32;
177 function AuthCheck ($postargs) {
178 // Normalize args, and extract.
179 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
181 foreach ($keys as $key)
182 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
184 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
187 return new WikiUser($this->_request); // Log out
189 return false; // User hit cancel button.
190 elseif (!$login && !$userid)
191 return false; // Nothing to do?
193 if (!$this->isValidName($userid))
194 return _("Invalid username.");
196 $authlevel = $this->_pwcheck($userid, $passwd);
198 return _("Invalid password or userid.");
199 elseif ($authlevel < $require_level)
200 return _("Insufficient permissions.");
203 $user = new WikiUser($this->_request, $userid, $authlevel);
207 function PrintLoginForm (&$request, $args, $fail_message = false,
208 $seperate_page = true) {
209 include_once 'lib/Template.php';
210 // Call update_locale in case the system's default language is not 'en'.
211 // (We have no user pref for lang at this point yet, no one is logged in.)
212 update_locale(DEFAULT_LANGUAGE);
215 extract($args); // fixme
217 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
219 $pagename = $request->getArg('pagename');
220 $login = new Template('login', $request,
221 compact('pagename', 'userid', 'require_level',
222 'fail_message', 'pass_required'));
223 if ($seperate_page) {
224 $request->discardOutput();
225 $page = $request->getPage($pagename);
226 $revision = $page->getCurrentRevision();
227 return GeneratePage($login,_("Sign In"),$revision);
236 function _pwcheck ($userid, $passwd) {
237 global $WikiNameRegexp;
239 if (!empty($userid) && $userid == ADMIN_USER) {
240 // $this->_authmethod = 'pagedata';
241 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
243 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
244 return WIKIAUTH_ADMIN;
247 if (!empty($passwd)) {
248 if ($passwd == ADMIN_PASSWD)
249 return WIKIAUTH_ADMIN;
251 // maybe we forgot to enable ENCRYPTED_PASSWD?
252 if ( function_exists('crypt')
253 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
254 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your config/config.ini"),
256 return WIKIAUTH_ADMIN;
262 // HTTP Authentication
263 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
264 // if he ignored the password field, because he is already
265 // authenticated try the previously given password.
267 $passwd = $PHP_AUTH_PW;
270 // WikiDB_User DB/File Authentication from $DBAuthParams
271 // Check if we have the user. If not try other methods.
272 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
273 if (!$this->isValidName($userid)) {
274 trigger_error(_("Invalid username."), E_USER_WARNING);
277 $request = $this->_request;
278 // first check if the user is known
279 if ($this->exists($userid)) {
280 $this->_authmethod = 'pagedata';
281 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
283 // else try others such as LDAP authentication:
284 if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid,'*')) {
285 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
286 $r = @ldap_bind($ldap); // this is an anonymous bind
287 $st_search = "uid=$userid";
288 // Need to set the right root search information. see ../index.php
289 $sr = ldap_search($ldap, LDAP_BASE_DN,
291 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
292 for ($i = 0; $i < $info["count"]; $i++) {
293 $dn = $info[$i]["dn"];
294 // The password is still plain text.
295 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
296 // ldap_bind will return TRUE if everything matches
298 $this->_authmethod = 'LDAP';
299 return WIKIAUTH_USER;
303 trigger_error("Unable to connect to LDAP server "
304 . LDAP_AUTH_HOST, E_USER_WARNING);
307 // imap authentication. added by limako
308 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
309 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}INBOX",
310 $userid, $passwd, OP_HALFOPEN );
313 $this->_authmethod = 'IMAP';
314 return WIKIAUTH_USER;
319 if ( ALLOW_BOGO_LOGIN
320 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
321 $this->_authmethod = 'BOGO';
322 return WIKIAUTH_BOGO;
327 // Todo: try our WikiDB backends.
328 function getPreferences() {
329 // Restore saved preferences.
331 // I'd rather prefer only to store the UserId in the cookie or
332 // session, and get the preferences from the db or page.
333 if (isset($this->_request)) {
334 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
335 $prefs = $this->_request->getSessionVar('wiki_prefs');
338 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
339 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
342 // before we get his prefs we should check if he is signed in
343 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
345 if ($pref = $this->_homepage->get('pref')) {
346 //trigger_error("pref=".$pref);//debugging
347 $prefs = unserialize($pref);
350 return new UserPreferences($prefs);
353 // No cookies anymore for all prefs, only the userid. PHP creates
354 // a session cookie in memory, which is much more efficient,
355 // but not persistent. Get persistency with a homepage or DB Prefs
357 // Return the number of changed entries
358 function setPreferences($prefs, $id_only = false) {
359 if (!is_object($prefs)) {
360 $prefs = new UserPreferences($prefs);
362 // update the session and id
363 $this->_request->setSessionVar('wiki_prefs', $prefs);
364 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
365 // simple unpacked cookie
366 if ($this->_userid) setcookie(getCookieName(), $this->_userid, 365, '/');
368 // We must ensure that any password is encrypted.
369 // We don't need any plaintext password.
371 if ($this->isSignedIn()) {
372 if ($this->isAdmin())
373 $prefs->set('passwd', '');
374 // already stored in config/config.ini, and it might be
375 // plaintext! well oh well
376 if ($homepage = $this->homePage()) {
377 // check for page revision 0
378 if (! $this->_dbi->isWikiPage($this->_userid)) {
379 trigger_error(_("Your home page has not been created yet so your preferences cannot not be saved."),
383 if ($this->isAdmin() || !$homepage->get('locked')) {
384 $homepage->set('pref', serialize($prefs->_prefs));
385 return sizeof($prefs->_prefs);
388 // An "empty" page could still be
389 // intentionally locked by admin to
390 // prevent its creation.
392 // FIXME: This permission situation should
393 // probably be handled by the DB backend,
394 // once the new WikiUser code has been
396 trigger_error(_("Your home page is locked so your preferences cannot not be saved.")
397 . " " . _("Please contact your PhpWiki administrator for assistance."),
402 trigger_error("No homepage for user found. Creating one...",
404 $this->createHomepage($prefs);
405 //$homepage->set('pref', serialize($prefs->_prefs));
406 return sizeof($prefs->_prefs);
409 trigger_error("you must be signed in", E_USER_WARNING);
415 // check for homepage with user flag.
416 // can be overriden from the auth backends
418 $homepage = $this->homePage();
419 return ($this->_userid && $homepage && $homepage->get('pref'));
422 // doesn't check for existance!!! hmm.
423 // how to store metadata in not existing pages? how about versions?
424 function homePage() {
427 if (!empty($this->_homepage)) {
428 return $this->_homepage;
430 if (empty($this->_dbi)) {
431 if (DEBUG) printSimpleTrace(debug_backtrace());
433 $this->_homepage = $this->_dbi->getPage($this->_userid);
435 return $this->_homepage;
439 function hasHomePage() {
440 return !$this->homePage();
443 // create user by checking his homepage
444 function createUser ($pref, $createDefaultHomepage = true) {
447 if ($createDefaultHomepage) {
448 $this->createHomepage($pref);
451 include 'lib/loadsave.php';
452 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
453 'versiondata' => array('author' => $this->_userid),
454 'pagename' => $this->_userid,
455 'content' => _('CategoryHomepage'));
456 SavePage ($this->_request, $pageinfo, false, false);
458 $this->setPreferences($pref);
461 // create user and default user homepage
462 function createHomepage ($pref) {
463 $pagename = $this->_userid;
464 include 'lib/loadsave.php';
466 // create default homepage:
467 // properly expanded template and the pref metadata
468 $template = Template('homepage.tmpl', $this->_request);
469 $text = $template->getExpansion();
470 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
471 'versiondata' => array('author' => $this->_userid),
472 'pagename' => $pagename,
474 SavePage ($this->_request, $pageinfo, false, false);
477 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Calendar');
478 if (! isWikiPage($pagename)) {
479 $pageinfo = array('pagedata' => array(),
480 'versiondata' => array('author' => $this->_userid),
481 'pagename' => $pagename,
482 'content' => "<?plugin Calendar ?>\n");
483 SavePage ($this->_request, $pageinfo, false, false);
486 // create Preferences
487 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
488 if (! isWikiPage($pagename)) {
489 $pageinfo = array('pagedata' => array(),
490 'versiondata' => array('author' => $this->_userid),
491 'pagename' => $pagename,
492 'content' => "<?plugin UserPreferences ?>\n");
493 SavePage ($this->_request, $pageinfo, false, false);
497 function tryAuthBackends() {
498 return ''; // crypt('') will never be ''
501 // Auth backends must store the crypted password where?
502 // Not in the preferences.
503 function checkPassword($passwd) {
504 $prefs = $this->getPreferences();
505 $stored_passwd = $prefs->get('passwd'); // crypted
506 if (empty($prefs->_prefs['passwd'])) // not stored in the page
507 // allow empty passwords? At least store a '*' then.
508 // try other backend. hmm.
509 $stored_passwd = $this->tryAuthBackends($this->_userid);
510 if (empty($stored_passwd)) {
511 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
512 $this->_userid), E_USER_NOTICE);
513 $prefs->set('passwd','*');
516 if ($stored_passwd == '*')
519 && crypt($passwd, $stored_passwd) == $stored_passwd )
525 function changePassword($newpasswd, $passwd2 = false) {
526 if (! $this->mayChangePass() ) {
527 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
528 $this->_userid), E_USER_ERROR);
531 if ($passwd2 && $passwd2 != $newpasswd) {
532 trigger_error("The second password must be the same as the first to change it",
536 if (!$this->isAuthenticated()) return false;
538 $prefs = $this->getPreferences();
539 if (ENCRYPTED_PASSWD)
540 $prefs->set('passwd', crypt($newpasswd));
542 $prefs->set('passwd', $newpasswd);
543 $this->setPreferences($prefs);
547 function mayChangePass() {
548 // on external DBAuth maybe. on IMAP or LDAP not
549 // on internal DBAuth yes
550 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
552 if ($this->isAdmin())
554 if ($this->_authmethod == 'pagedata')
556 if ($this->_authmethod == 'authdb')
561 // create user and default user homepage
562 // FIXME: delete this, not used?
564 function createUser ($userid, $pref) {
566 $user = new WikiUser ($request, $userid);
567 $user->createUser($pref);
571 class _UserPreference
573 function _UserPreference ($default_value) {
574 $this->default_value = $default_value;
577 function sanify ($value) {
578 return (string)$value;
581 function update ($value) {
585 class _UserPreference_numeric
586 extends _UserPreference
588 function _UserPreference_numeric ($default, $minval = false,
590 $this->_UserPreference((double)$default);
591 $this->_minval = (double)$minval;
592 $this->_maxval = (double)$maxval;
595 function sanify ($value) {
596 $value = (double)$value;
597 if ($this->_minval !== false && $value < $this->_minval)
598 $value = $this->_minval;
599 if ($this->_maxval !== false && $value > $this->_maxval)
600 $value = $this->_maxval;
605 class _UserPreference_int
606 extends _UserPreference_numeric
608 function _UserPreference_int ($default, $minval = false, $maxval = false) {
609 $this->_UserPreference_numeric((int)$default, (int)$minval,
613 function sanify ($value) {
614 return (int)parent::sanify((int)$value);
618 class _UserPreference_bool
619 extends _UserPreference
621 function _UserPreference_bool ($default = false) {
622 $this->_UserPreference((bool)$default);
625 function sanify ($value) {
626 if (is_array($value)) {
627 /* This allows for constructs like:
629 * <input type="hidden" name="pref[boolPref][]" value="0" />
630 * <input type="checkbox" name="pref[boolPref][]" value="1" />
632 * (If the checkbox is not checked, only the hidden input
633 * gets sent. If the checkbox is sent, both inputs get
636 foreach ($value as $val) {
642 return (bool) $value;
646 class _UserPreference_language
647 extends _UserPreference
649 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
650 $this->_UserPreference($default);
653 // FIXME: check for valid locale
654 function sanify ($value) {
655 // Revert to DEFAULT_LANGUAGE if user does not specify
656 // language in UserPreferences or chooses <system language>.
657 if ($value == '' or empty($value))
658 $value = DEFAULT_LANGUAGE;
660 return (string) $value;
664 class _UserPreference_theme
665 extends _UserPreference
667 function _UserPreference_theme ($default = THEME) {
668 $this->_UserPreference($default);
671 function sanify ($value) {
672 if (findFile($this->_themefile($value), true))
674 return $this->default_value;
677 function update ($newvalue) {
679 include_once($this->_themefile($newvalue));
680 if (empty($WikiTheme))
681 include_once($this->_themefile(THEME));
684 function _themefile ($theme) {
685 return "themes/$theme/themeinfo.php";
689 // don't save default preferences for efficiency.
690 class UserPreferences {
691 function UserPreferences ($saved_prefs = false) {
692 $this->_prefs = array();
694 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
695 foreach ($saved_prefs->_prefs as $name => $value)
696 $this->set($name, $value);
697 } elseif (is_array($saved_prefs)) {
698 foreach ($saved_prefs as $name => $value)
699 $this->set($name, $value);
703 function _getPref ($name) {
704 global $UserPreferences;
705 if (!isset($UserPreferences[$name])) {
706 if ($name == 'passwd2') return false;
707 trigger_error("$name: unknown preference", E_USER_NOTICE);
710 return $UserPreferences[$name];
713 function get ($name) {
714 if (isset($this->_prefs[$name]))
715 return $this->_prefs[$name];
716 if (!($pref = $this->_getPref($name)))
718 return $pref->default_value;
721 function set ($name, $value) {
722 if (!($pref = $this->_getPref($name)))
725 $newvalue = $pref->sanify($value);
726 $oldvalue = $this->get($name);
729 if ($newvalue != $oldvalue)
730 $pref->update($newvalue);
732 // don't set default values to save space (in cookies, db and
734 if ($value == $pref->default_value)
735 unset($this->_prefs[$name]);
737 $this->_prefs[$name] = $newvalue;
740 function pack ($nonpacked) {
741 return serialize($nonpacked);
743 function unpack ($packed) {
746 if (substr($packed,0,2) == "O:") {
747 // Looks like a serialized object
748 return unserialize($packed);
750 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
756 return wikihash($this->_prefs);
764 // c-hanging-comment-ender-p: nil
765 // indent-tabs-mode: nil