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()
50 function UpgradeUser($olduser, $user)
52 if (isa($user, 'WikiUser') and isa($olduser, 'WikiUser')) {
53 // populate the upgraded class with the values from the old object
54 foreach (get_object_vars($olduser) as $k => $v) {
57 $GLOBALS['request']->_user = $user;
71 var $_request, $_dbi, $_authdbi, $_homepage;
72 var $_authmethod = '', $_authhow = '';
77 * Populates the instance variables and calls $this->_ok()
78 * to ensure that the parameters are valid.
79 * @param mixed $userid String of username or WikiUser object.
80 * @param integer $authlevel Authorization level.
82 function WikiUser(&$request, $userid = false, $authlevel = false)
84 $this->_request =& $request;
85 $this->_dbi =& $this->_request->getDbh();
87 if (isa($userid, 'WikiUser')) {
88 $this->_userid = $userid->_userid;
89 $this->_level = $userid->_level;
91 $this->_userid = $userid;
92 $this->_level = $authlevel;
95 // Paranoia: if state is at all inconsistent, log out...
96 $this->_userid = false;
97 $this->_level = false;
98 $this->_homepage = false;
99 $this->_authhow .= ' paranoia logout';
101 if ($this->_userid) {
102 $this->_homepage = $this->_dbi->getPage($this->_userid);
107 * Get the string indicating how the user was authenticated.
109 * Get the string indicating how the user was authenticated.
110 * Does not seem to be set - jbw
111 * @return string The method of authentication.
115 return $this->_authhow;
121 * If the WikiUser object has a valid authorization level and the
122 * userid is a string returns true, else false.
123 * @return boolean If valid level and username string true, else false
127 if ((in_array($this->_level, array(WIKIAUTH_BOGO,
131 (is_string($this->_userid)))
140 return $this->_userid;
146 return $this->_userid;
147 if (!empty($this->_request))
148 return $this->_request->get('REMOTE_ADDR');
149 if (empty($this->_request))
150 return Request::get('REMOTE_ADDR');
151 return ($this->isSignedIn()
153 : $this->_request->get('REMOTE_ADDR')); // FIXME: globals
156 function getAuthenticatedId()
158 //assert($this->_request);
159 return ($this->isAuthenticated()
161 : $this->_request->get('REMOTE_ADDR')); // FIXME: globals
164 function isSignedIn()
166 return $this->_level >= WIKIAUTH_BOGO;
169 function isAuthenticated()
171 return $this->_level >= WIKIAUTH_BOGO;
176 return $this->_level == WIKIAUTH_ADMIN;
179 function hasAuthority($require_level)
181 return $this->_level >= $require_level;
184 function isValidName($userid = false)
187 $userid = $this->_userid;
188 return preg_match("/^[\w\.@\-]+$/", $userid) and strlen($userid) < 32;
191 function AuthCheck($postargs)
193 // Normalize args, and extract.
194 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
196 foreach ($keys as $key)
197 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
199 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
202 return new WikiUser($this->_request); // Log out
204 return false; // User hit cancel button.
205 elseif (!$login && !$userid)
206 return false; // Nothing to do?
208 if (!$this->isValidName($userid))
209 return _("Invalid username.");
211 $authlevel = $this->_pwcheck($userid, $passwd);
213 return _("Invalid password or userid.");
214 elseif ($authlevel < $require_level)
215 return _("Insufficient permissions.");
218 $user = new WikiUser($this->_request, $userid, $authlevel);
222 function PrintLoginForm(&$request, $args, $fail_message = false,
223 $seperate_page = true)
225 include_once 'lib/Template.php';
226 // Call update_locale in case the system's default language is not 'en'.
227 // (We have no user pref for lang at this point yet, no one is logged in.)
228 update_locale(DEFAULT_LANGUAGE);
231 extract($args); // fixme
233 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
235 $pagename = $request->getArg('pagename');
236 $login = new Template('login', $request,
237 compact('pagename', 'userid', 'require_level',
238 'fail_message', 'pass_required'));
239 if ($seperate_page) {
240 $request->discardOutput();
241 $page = $request->getPage($pagename);
242 $revision = $page->getCurrentRevision();
243 return GeneratePage($login, _("Sign In"), $revision);
252 function _pwcheck($userid, $passwd)
254 global $WikiNameRegexp;
256 if (!empty($userid) && $userid == ADMIN_USER) {
257 // $this->_authmethod = 'pagedata';
258 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
260 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD
262 return WIKIAUTH_ADMIN;
265 if (!empty($passwd)) {
266 if ($passwd == ADMIN_PASSWD)
267 return WIKIAUTH_ADMIN;
269 // maybe we forgot to enable ENCRYPTED_PASSWD?
270 if (function_exists('crypt')
271 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD
273 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your config/config.ini"),
275 return WIKIAUTH_ADMIN;
280 } // HTTP Authentication
281 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
282 // if he ignored the password field, because he is already
283 // authenticated try the previously given password.
285 $passwd = $PHP_AUTH_PW;
288 // WikiDB_User DB/File Authentication from $DBAuthParams
289 // Check if we have the user. If not try other methods.
290 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
291 if (!$this->isValidName($userid)) {
292 trigger_error(_("Invalid username."), E_USER_WARNING);
295 $request = $this->_request;
296 // first check if the user is known
297 if ($this->exists($userid)) {
298 $this->_authmethod = 'pagedata';
299 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
301 // else try others such as LDAP authentication:
302 if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid, '*')) {
303 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
304 $r = @ldap_bind($ldap); // this is an anonymous bind
305 $st_search = "uid=$userid";
306 // Need to set the right root search information. see ../index.php
307 $sr = ldap_search($ldap, LDAP_BASE_DN,
309 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
310 for ($i = 0; $i < $info["count"]; $i++) {
311 $dn = $info[$i]["dn"];
312 // The password is still plain text.
313 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
314 // ldap_bind will return TRUE if everything matches
316 $this->_authmethod = 'LDAP';
317 return WIKIAUTH_USER;
321 trigger_error("Unable to connect to LDAP server "
322 . LDAP_AUTH_HOST, E_USER_WARNING);
325 // imap authentication. added by limako
326 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
327 $mbox = @imap_open("{" . IMAP_AUTH_HOST . "}INBOX",
328 $userid, $passwd, OP_HALFOPEN);
331 $this->_authmethod = 'IMAP';
332 return WIKIAUTH_USER;
338 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid)
340 $this->_authmethod = 'BOGO';
341 return WIKIAUTH_BOGO;
346 // Todo: try our WikiDB backends.
347 function getPreferences()
349 // Restore saved preferences.
351 // I'd rather prefer only to store the UserId in the cookie or
352 // session, and get the preferences from the db or page.
353 if (isset($this->_request)) {
354 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
355 $prefs = $this->_request->getSessionVar('wiki_prefs');
358 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
359 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
362 // before we get his prefs we should check if he is signed in
363 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
365 if ($pref = $this->_homepage->get('pref')) {
366 //trigger_error("pref=".$pref);//debugging
367 $prefs = unserialize($pref);
370 return new UserPreferences($prefs);
373 // No cookies anymore for all prefs, only the userid. PHP creates
374 // a session cookie in memory, which is much more efficient,
375 // but not persistent. Get persistency with a homepage or DB Prefs
377 // Return the number of changed entries
378 function setPreferences($prefs, $id_only = false)
380 if (!is_object($prefs)) {
381 $prefs = new UserPreferences($prefs);
383 // update the session and id
384 $this->_request->setSessionVar('wiki_prefs', $prefs);
385 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
386 // simple unpacked cookie
387 if ($this->_userid) setcookie(getCookieName(), $this->_userid, 365, '/');
389 // We must ensure that any password is encrypted.
390 // We don't need any plaintext password.
392 if ($this->isSignedIn()) {
393 if ($this->isAdmin())
394 $prefs->set('passwd', '');
395 // already stored in config/config.ini, and it might be
396 // plaintext! well oh well
397 if ($homepage = $this->homePage()) {
398 // check for page revision 0
399 if (!$this->_dbi->isWikiPage($this->_userid)) {
400 trigger_error(_("Your home page has not been created yet so your preferences cannot not be saved."),
403 if ($this->isAdmin() || !$homepage->get('locked')) {
404 $homepage->set('pref', serialize($prefs->_prefs));
405 return sizeof($prefs->_prefs);
407 // An "empty" page could still be
408 // intentionally locked by admin to
409 // prevent its creation.
411 // FIXME: This permission situation should
412 // probably be handled by the DB backend,
413 // once the new WikiUser code has been
415 trigger_error(_("Your home page is locked so your preferences cannot not be saved.")
416 . " " . _("Please contact your PhpWiki administrator for assistance."),
421 trigger_error("No homepage for user found. Creating one...",
423 $this->createHomepage($prefs);
424 //$homepage->set('pref', serialize($prefs->_prefs));
425 return sizeof($prefs->_prefs);
428 trigger_error("you must be signed in", E_USER_WARNING);
434 // check for homepage with user flag.
435 // can be overriden from the auth backends
438 $homepage = $this->homePage();
439 return ($this->_userid && $homepage && $homepage->get('pref'));
442 // doesn't check for existance!!! hmm.
443 // how to store metadata in not existing pages? how about versions?
448 if (!empty($this->_homepage)) {
449 return $this->_homepage;
451 if (empty($this->_dbi)) {
452 if (DEBUG) printSimpleTrace(debug_backtrace());
454 $this->_homepage = $this->_dbi->getPage($this->_userid);
456 return $this->_homepage;
460 function hasHomePage()
462 return !$this->homePage();
465 // create user by checking his homepage
466 function createUser($pref, $createDefaultHomepage = true)
470 if ($createDefaultHomepage) {
471 $this->createHomepage($pref);
474 include 'lib/loadsave.php';
475 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
476 'versiondata' => array('author' => $this->_userid),
477 'pagename' => $this->_userid,
478 'content' => _('CategoryHomepage'));
479 SavePage($this->_request, $pageinfo, false, false);
481 $this->setPreferences($pref);
484 // create user and default user homepage
485 function createHomepage($pref)
487 $pagename = $this->_userid;
488 include 'lib/loadsave.php';
490 // create default homepage:
491 // properly expanded template and the pref metadata
492 $template = Template('homepage.tmpl', $this->_request);
493 $text = $template->getExpansion();
494 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
495 'versiondata' => array('author' => $this->_userid),
496 'pagename' => $pagename,
498 SavePage($this->_request, $pageinfo, false, false);
501 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Calendar');
502 if (!isWikiPage($pagename)) {
503 $pageinfo = array('pagedata' => array(),
504 'versiondata' => array('author' => $this->_userid),
505 'pagename' => $pagename,
506 'content' => "<?plugin Calendar ?>\n");
507 SavePage($this->_request, $pageinfo, false, false);
510 // create Preferences
511 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
512 if (!isWikiPage($pagename)) {
513 $pageinfo = array('pagedata' => array(),
514 'versiondata' => array('author' => $this->_userid),
515 'pagename' => $pagename,
516 'content' => "<?plugin UserPreferences ?>\n");
517 SavePage($this->_request, $pageinfo, false, false);
521 function tryAuthBackends()
523 return ''; // crypt('') will never be ''
526 // Auth backends must store the crypted password where?
527 // Not in the preferences.
528 function checkPassword($passwd)
530 $prefs = $this->getPreferences();
531 $stored_passwd = $prefs->get('passwd'); // crypted
532 if (empty($prefs->_prefs['passwd'])) // not stored in the page
533 // allow empty passwords? At least store a '*' then.
534 // try other backend. hmm.
535 $stored_passwd = $this->tryAuthBackends($this->_userid);
536 if (empty($stored_passwd)) {
537 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
538 $this->_userid), E_USER_NOTICE);
539 $prefs->set('passwd', '*');
542 if ($stored_passwd == '*')
545 && crypt($passwd, $stored_passwd) == $stored_passwd
552 function changePassword($newpasswd, $passwd2 = false)
554 if (!$this->mayChangePass()) {
555 trigger_error(sprintf("Attempt to change an external password for “%s”. Not allowed!",
556 $this->_userid), E_USER_ERROR);
559 if ($passwd2 && $passwd2 != $newpasswd) {
560 trigger_error("The second password must be the same as the first to change it",
564 if (!$this->isAuthenticated()) return false;
566 $prefs = $this->getPreferences();
567 if (ENCRYPTED_PASSWD)
568 $prefs->set('passwd', crypt($newpasswd));
570 $prefs->set('passwd', $newpasswd);
571 $this->setPreferences($prefs);
575 function mayChangePass()
577 // on external DBAuth maybe. on IMAP or LDAP not
578 // on internal DBAuth yes
579 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
581 if ($this->isAdmin())
583 if ($this->_authmethod == 'pagedata')
585 if ($this->_authmethod == 'authdb')
590 // create user and default user homepage
591 // FIXME: delete this, not used?
593 function createUser ($userid, $pref) {
595 $user = new WikiUser ($request, $userid);
596 $user->createUser($pref);
600 class _UserPreference
602 function _UserPreference($default_value)
604 $this->default_value = $default_value;
607 function sanify($value)
609 return (string)$value;
612 function update($value)
617 class _UserPreference_numeric
618 extends _UserPreference
620 function _UserPreference_numeric($default, $minval = false,
623 $this->_UserPreference((double)$default);
624 $this->_minval = (double)$minval;
625 $this->_maxval = (double)$maxval;
628 function sanify($value)
630 $value = (double)$value;
631 if ($this->_minval !== false && $value < $this->_minval)
632 $value = $this->_minval;
633 if ($this->_maxval !== false && $value > $this->_maxval)
634 $value = $this->_maxval;
639 class _UserPreference_int
640 extends _UserPreference_numeric
642 function _UserPreference_int($default, $minval = false, $maxval = false)
644 $this->_UserPreference_numeric((int)$default, (int)$minval,
648 function sanify($value)
650 return (int)parent::sanify((int)$value);
654 class _UserPreference_bool
655 extends _UserPreference
657 function _UserPreference_bool($default = false)
659 $this->_UserPreference((bool)$default);
662 function sanify($value)
664 if (is_array($value)) {
665 /* This allows for constructs like:
667 * <input type="hidden" name="pref[boolPref][]" value="0" />
668 * <input type="checkbox" name="pref[boolPref][]" value="1" />
670 * (If the checkbox is not checked, only the hidden input
671 * gets sent. If the checkbox is sent, both inputs get
674 foreach ($value as $val) {
684 class _UserPreference_language
685 extends _UserPreference
687 function _UserPreference_language($default = DEFAULT_LANGUAGE)
689 $this->_UserPreference($default);
692 // FIXME: check for valid locale
693 function sanify($value)
695 // Revert to DEFAULT_LANGUAGE if user does not specify
696 // language in UserPreferences or chooses <system language>.
697 if ($value == '' or empty($value))
698 $value = DEFAULT_LANGUAGE;
700 return (string)$value;
704 class _UserPreference_theme
705 extends _UserPreference
707 function _UserPreference_theme($default = THEME)
709 $this->_UserPreference($default);
712 function sanify($value)
714 if (findFile($this->_themefile($value), true))
716 return $this->default_value;
719 function update($newvalue)
722 include_once($this->_themefile($newvalue));
723 if (empty($WikiTheme))
724 include_once($this->_themefile(THEME));
727 function _themefile($theme)
729 return "themes/$theme/themeinfo.php";
733 // don't save default preferences for efficiency.
734 class UserPreferences
736 function UserPreferences($saved_prefs = false)
738 $this->_prefs = array();
740 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
741 foreach ($saved_prefs->_prefs as $name => $value)
742 $this->set($name, $value);
743 } elseif (is_array($saved_prefs)) {
744 foreach ($saved_prefs as $name => $value)
745 $this->set($name, $value);
749 function _getPref($name)
751 global $UserPreferences;
752 if (!isset($UserPreferences[$name])) {
753 if ($name == 'passwd2') return false;
754 trigger_error("$name: unknown preference", E_USER_NOTICE);
757 return $UserPreferences[$name];
762 if (isset($this->_prefs[$name]))
763 return $this->_prefs[$name];
764 if (!($pref = $this->_getPref($name)))
766 return $pref->default_value;
769 function set($name, $value)
771 if (!($pref = $this->_getPref($name)))
774 $newvalue = $pref->sanify($value);
775 $oldvalue = $this->get($name);
778 if ($newvalue != $oldvalue)
779 $pref->update($newvalue);
781 // don't set default values to save space (in cookies, db and
783 if ($value == $pref->default_value)
784 unset($this->_prefs[$name]);
786 $this->_prefs[$name] = $newvalue;
789 function pack($nonpacked)
791 return serialize($nonpacked);
794 function unpack($packed)
798 if (substr($packed, 0, 2) == "O:") {
799 // Looks like a serialized object
800 return unserialize($packed);
802 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
809 return wikihash($this->_prefs);
817 // c-hanging-comment-ender-p: nil
818 // indent-tabs-mode: nil