4 // It is anticipated that when userid support is added to phpwiki,
5 // this object will hold much more information (e-mail,
6 // home(wiki)page, etc.) about the user.
8 // There seems to be no clean way to "log out" a user when using HTTP
9 // authentication. So we'll hack around this by storing the currently
10 // logged 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
16 // If no homepage, fallback to prefs in cookie as in 1.3.3.
18 define('WIKIAUTH_FORBIDDEN', -1); // Completely not allowed.
19 define('WIKIAUTH_ANON', 0);
20 define('WIKIAUTH_BOGO', 1); // any valid WikiWord is enough
21 define('WIKIAUTH_USER', 2); // real auth from a database/file/server.
23 define('WIKIAUTH_ADMIN', 10); // Wiki Admin
24 define('WIKIAUTH_UNOBTAINABLE', 100); // Permissions that no user can achieve
26 if (!defined('COOKIE_EXPIRATION_DAYS')) define('COOKIE_EXPIRATION_DAYS', 365);
27 if (!defined('COOKIE_DOMAIN')) define('COOKIE_DOMAIN', '/');
29 $UserPreferences = array(
30 'userid' => new _UserPreference(''), // really store this also?
31 'passwd' => new _UserPreference(''),
32 'email' => new _UserPreference(''),
33 'emailVerified' => new _UserPreference_bool(),
34 'notifyPages' => new _UserPreference(''),
35 'theme' => new _UserPreference_theme(THEME),
36 'lang' => new _UserPreference_language(DEFAULT_LANGUAGE),
37 'editWidth' => new _UserPreference_int(80, 30, 150),
38 'noLinkIcons' => new _UserPreference_bool(),
39 'editHeight' => new _UserPreference_int(22, 5, 80),
40 'timeOffset' => new _UserPreference_numeric(0, -26, 26),
41 'relativeDates' => new _UserPreference_bool(),
42 'googleLink' => new _UserPreference_bool(), // 1.3.10
43 'doubleClickEdit' => new _UserPreference_bool(), // 1.3.11
46 function WikiUserClassname() {
50 function UpgradeUser ($olduser, $user) {
51 if (isa($user,'WikiUser') and isa($olduser,'WikiUser')) {
52 // populate the upgraded class with the values from the old object
53 foreach (get_object_vars($olduser) as $k => $v) {
56 $GLOBALS['request']->_user = $user;
69 var $_request, $_dbi, $_authdbi, $_homepage;
70 var $_authmethod = '', $_authhow = '';
75 * Populates the instance variables and calls $this->_ok()
76 * to ensure that the parameters are valid.
77 * @param mixed $userid String of username or WikiUser object.
78 * @param integer $authlevel Authorization level.
80 function WikiUser (&$request, $userid = false, $authlevel = false) {
81 $this->_request =& $request;
82 $this->_dbi =& $this->_request->getDbh();
84 if (isa($userid, 'WikiUser')) {
85 $this->_userid = $userid->_userid;
86 $this->_level = $userid->_level;
89 $this->_userid = $userid;
90 $this->_level = $authlevel;
93 // Paranoia: if state is at all inconsistent, log out...
94 $this->_userid = false;
95 $this->_level = false;
96 $this->_homepage = false;
97 $this->_authhow .= ' paranoia logout';
100 $this->_homepage = $this->_dbi->getPage($this->_userid);
105 * Get the string indicating how the user was authenticated.
107 * Get the string indicating how the user was authenticated.
108 * Does not seem to be set - jbw
109 * @return string The method of authentication.
111 function auth_how() {
112 return $this->_authhow;
118 * If the WikiUser object has a valid authorization level and the
119 * userid is a string returns true, else false.
120 * @return boolean If valid level and username string true, else false
123 if ((in_array($this->_level, array(WIKIAUTH_BOGO,
127 (is_string($this->_userid)))) {
133 function UserName() {
134 return $this->_userid;
139 return $this->_userid;
140 if (!empty($this->_request))
141 return $this->_request->get('REMOTE_ADDR');
142 if (empty($this->_request))
143 return Request::get('REMOTE_ADDR');
144 return ( $this->isSignedIn()
146 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
149 function getAuthenticatedId() {
150 //assert($this->_request);
151 return ( $this->isAuthenticated()
153 : $this->_request->get('REMOTE_ADDR') ); // FIXME: globals
156 function isSignedIn () {
157 return $this->_level >= WIKIAUTH_BOGO;
160 function isAuthenticated () {
161 return $this->_level >= WIKIAUTH_BOGO;
164 function isAdmin () {
165 return $this->_level == WIKIAUTH_ADMIN;
168 function hasAuthority ($require_level) {
169 return $this->_level >= $require_level;
172 function isValidName ($userid = false) {
174 $userid = $this->_userid;
175 return preg_match("/^[\w\.@\-]+$/",$userid) and strlen($userid) < 32;
178 function AuthCheck ($postargs) {
179 // Normalize args, and extract.
180 $keys = array('userid', 'passwd', 'require_level', 'login', 'logout',
182 foreach ($keys as $key)
183 $args[$key] = isset($postargs[$key]) ? $postargs[$key] : false;
185 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
188 return new WikiUser($this->_request); // Log out
190 return false; // User hit cancel button.
191 elseif (!$login && !$userid)
192 return false; // Nothing to do?
194 if (!$this->isValidName($userid))
195 return _("Invalid username.");
197 $authlevel = $this->_pwcheck($userid, $passwd);
199 return _("Invalid password or userid.");
200 elseif ($authlevel < $require_level)
201 return _("Insufficient permissions.");
204 $user = new WikiUser($this->_request, $userid, $authlevel);
208 function PrintLoginForm (&$request, $args, $fail_message = false,
209 $seperate_page = true) {
210 include_once('lib/Template.php');
211 // Call update_locale in case the system's default language is not 'en'.
212 // (We have no user pref for lang at this point yet, no one is logged in.)
213 update_locale(DEFAULT_LANGUAGE);
216 extract($args); // fixme
218 $require_level = max(0, min(WIKIAUTH_ADMIN, (int)$require_level));
220 $pagename = $request->getArg('pagename');
221 $login = new Template('login', $request,
222 compact('pagename', 'userid', 'require_level',
223 'fail_message', 'pass_required'));
224 if ($seperate_page) {
225 $request->discardOutput();
226 $page = $request->getPage($pagename);
227 $revision = $page->getCurrentRevision();
228 return GeneratePage($login,_("Sign In"),$revision);
237 function _pwcheck ($userid, $passwd) {
238 global $WikiNameRegexp;
240 if (!empty($userid) && $userid == ADMIN_USER) {
241 // $this->_authmethod = 'pagedata';
242 if (defined('ENCRYPTED_PASSWD') && ENCRYPTED_PASSWD)
244 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD )
245 return WIKIAUTH_ADMIN;
248 if (!empty($passwd)) {
249 if ($passwd == ADMIN_PASSWD)
250 return WIKIAUTH_ADMIN;
252 // maybe we forgot to enable ENCRYPTED_PASSWD?
253 if ( function_exists('crypt')
254 && crypt($passwd, ADMIN_PASSWD) == ADMIN_PASSWD ) {
255 trigger_error(_("You forgot to set ENCRYPTED_PASSWD to true. Please update your config/config.ini"),
257 return WIKIAUTH_ADMIN;
263 // HTTP Authentication
264 elseif (ALLOW_HTTP_AUTH_LOGIN && !empty($PHP_AUTH_USER)) {
265 // if he ignored the password field, because he is already
266 // authenticated try the previously given password.
268 $passwd = $PHP_AUTH_PW;
271 // WikiDB_User DB/File Authentication from $DBAuthParams
272 // Check if we have the user. If not try other methods.
273 if (ALLOW_USER_LOGIN) { // && !empty($passwd)) {
274 if (!$this->isValidName($userid)) {
275 trigger_error(_("Invalid username."), E_USER_WARNING);
278 $request = $this->_request;
279 // first check if the user is known
280 if ($this->exists($userid)) {
281 $this->_authmethod = 'pagedata';
282 return ($this->checkPassword($passwd)) ? WIKIAUTH_USER : false;
284 // else try others such as LDAP authentication:
285 if (ALLOW_LDAP_LOGIN && defined(LDAP_AUTH_HOST) && !empty($passwd) && !strstr($userid,'*')) {
286 if ($ldap = ldap_connect(LDAP_AUTH_HOST)) { // must be a valid LDAP server!
287 $r = @ldap_bind($ldap); // this is an anonymous bind
288 $st_search = "uid=$userid";
289 // Need to set the right root search information. see ../index.php
290 $sr = ldap_search($ldap, LDAP_BASE_DN,
292 $info = ldap_get_entries($ldap, $sr); // there may be more hits with this userid. try every
293 for ($i = 0; $i < $info["count"]; $i++) {
294 $dn = $info[$i]["dn"];
295 // The password is still plain text.
296 if ($r = @ldap_bind($ldap, $dn, $passwd)) {
297 // ldap_bind will return TRUE if everything matches
299 $this->_authmethod = 'LDAP';
300 return WIKIAUTH_USER;
304 trigger_error("Unable to connect to LDAP server "
305 . LDAP_AUTH_HOST, E_USER_WARNING);
308 // imap authentication. added by limako
309 if (ALLOW_IMAP_LOGIN && !empty($passwd)) {
310 $mbox = @imap_open( "{" . IMAP_AUTH_HOST . "}INBOX",
311 $userid, $passwd, OP_HALFOPEN );
314 $this->_authmethod = 'IMAP';
315 return WIKIAUTH_USER;
320 if ( ALLOW_BOGO_LOGIN
321 && preg_match('/\A' . $WikiNameRegexp . '\z/', $userid) ) {
322 $this->_authmethod = 'BOGO';
323 return WIKIAUTH_BOGO;
328 // Todo: try our WikiDB backends.
329 function getPreferences() {
330 // Restore saved preferences.
332 // I'd rather prefer only to store the UserId in the cookie or
333 // session, and get the preferences from the db or page.
334 if (isset($this->_request)) {
335 if (!($prefs = $this->_request->getCookieVar('WIKI_PREFS2')))
336 $prefs = $this->_request->getSessionVar('wiki_prefs');
339 //if (!$this->_userid && !empty($GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'])) {
340 // $this->_userid = $GLOBALS['HTTP_COOKIE_VARS']['WIKI_ID'];
343 // before we get his prefs we should check if he is signed in
344 if (USE_PREFS_IN_PAGE && $this->homePage()) { // in page metadata
346 if ($pref = $this->_homepage->get('pref')) {
347 //trigger_error("pref=".$pref);//debugging
348 $prefs = unserialize($pref);
351 return new UserPreferences($prefs);
354 // No cookies anymore for all prefs, only the userid. PHP creates
355 // a session cookie in memory, which is much more efficient,
356 // but not persistent. Get persistency with a homepage or DB Prefs
358 // Return the number of changed entries
359 function setPreferences($prefs, $id_only = false) {
360 if (!is_object($prefs)) {
361 $prefs = new UserPreferences($prefs);
363 // update the session and id
364 $this->_request->setSessionVar('wiki_prefs', $prefs);
365 // $this->_request->setCookieVar('WIKI_PREFS2', $this->_prefs, 365);
366 // simple unpacked cookie
367 if ($this->_userid) setcookie(getCookieName(), $this->_userid, 365, '/');
369 // We must ensure that any password is encrypted.
370 // We don't need any plaintext password.
372 if ($this->isSignedIn()) {
373 if ($this->isAdmin())
374 $prefs->set('passwd', '');
375 // already stored in config/config.ini, and it might be
376 // plaintext! well oh well
377 if ($homepage = $this->homePage()) {
378 // check for page revision 0
379 if (! $this->_dbi->isWikiPage($this->_userid)) {
380 trigger_error(_("Your home page has not been created yet so your preferences cannot not be saved."),
384 if ($this->isAdmin() || !$homepage->get('locked')) {
385 $homepage->set('pref', serialize($prefs->_prefs));
386 return sizeof($prefs->_prefs);
389 // An "empty" page could still be
390 // intentionally locked by admin to
391 // prevent its creation.
393 // FIXME: This permission situation should
394 // probably be handled by the DB backend,
395 // once the new WikiUser code has been
397 trigger_error(_("Your home page is locked so your preferences cannot not be saved.")
398 . " " . _("Please contact your PhpWiki administrator for assistance."),
403 trigger_error("No homepage for user found. Creating one...",
405 $this->createHomepage($prefs);
406 //$homepage->set('pref', serialize($prefs->_prefs));
407 return sizeof($prefs->_prefs);
410 trigger_error("you must be signed in", E_USER_WARNING);
416 // check for homepage with user flag.
417 // can be overriden from the auth backends
419 $homepage = $this->homePage();
420 return ($this->_userid && $homepage && $homepage->get('pref'));
423 // doesn't check for existance!!! hmm.
424 // how to store metadata in not existing pages? how about versions?
425 function homePage() {
428 if (!empty($this->_homepage)) {
429 return $this->_homepage;
431 if (empty($this->_dbi)) {
432 if (DEBUG) printSimpleTrace(debug_backtrace());
434 $this->_homepage = $this->_dbi->getPage($this->_userid);
436 return $this->_homepage;
440 function hasHomePage() {
441 return !$this->homePage();
444 // create user by checking his homepage
445 function createUser ($pref, $createDefaultHomepage = true) {
448 if ($createDefaultHomepage) {
449 $this->createHomepage($pref);
452 include "lib/loadsave.php";
453 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
454 'versiondata' => array('author' => $this->_userid),
455 'pagename' => $this->_userid,
456 'content' => _('CategoryHomepage'));
457 SavePage ($this->_request, $pageinfo, false, false);
459 $this->setPreferences($pref);
462 // create user and default user homepage
463 function createHomepage ($pref) {
464 $pagename = $this->_userid;
465 include "lib/loadsave.php";
467 // create default homepage:
468 // properly expanded template and the pref metadata
469 $template = Template('homepage.tmpl', $this->_request);
470 $text = $template->getExpansion();
471 $pageinfo = array('pagedata' => array('pref' => serialize($pref->_pref)),
472 'versiondata' => array('author' => $this->_userid),
473 'pagename' => $pagename,
475 SavePage ($this->_request, $pageinfo, false, false);
478 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Calendar');
479 if (! isWikiPage($pagename)) {
480 $pageinfo = array('pagedata' => array(),
481 'versiondata' => array('author' => $this->_userid),
482 'pagename' => $pagename,
483 'content' => "<?plugin Calendar ?>\n");
484 SavePage ($this->_request, $pageinfo, false, false);
487 // create Preferences
488 $pagename = $this->_userid . SUBPAGE_SEPARATOR . _('Preferences');
489 if (! isWikiPage($pagename)) {
490 $pageinfo = array('pagedata' => array(),
491 'versiondata' => array('author' => $this->_userid),
492 'pagename' => $pagename,
493 'content' => "<?plugin UserPreferences ?>\n");
494 SavePage ($this->_request, $pageinfo, false, false);
498 function tryAuthBackends() {
499 return ''; // crypt('') will never be ''
502 // Auth backends must store the crypted password where?
503 // Not in the preferences.
504 function checkPassword($passwd) {
505 $prefs = $this->getPreferences();
506 $stored_passwd = $prefs->get('passwd'); // crypted
507 if (empty($prefs->_prefs['passwd'])) // not stored in the page
508 // allow empty passwords? At least store a '*' then.
509 // try other backend. hmm.
510 $stored_passwd = $this->tryAuthBackends($this->_userid);
511 if (empty($stored_passwd)) {
512 trigger_error(sprintf(_("Old UserPage %s without stored password updated with empty password. Set a password in your UserPreferences."),
513 $this->_userid), E_USER_NOTICE);
514 $prefs->set('passwd','*');
517 if ($stored_passwd == '*')
520 && crypt($passwd, $stored_passwd) == $stored_passwd )
526 function changePassword($newpasswd, $passwd2 = false) {
527 if (! $this->mayChangePass() ) {
528 trigger_error(sprintf("Attempt to change an external password for '%s'. Not allowed!",
529 $this->_userid), E_USER_ERROR);
532 if ($passwd2 && $passwd2 != $newpasswd) {
533 trigger_error("The second password must be the same as the first to change it",
537 if (!$this->isAuthenticated()) return false;
539 $prefs = $this->getPreferences();
540 if (ENCRYPTED_PASSWD)
541 $prefs->set('passwd', crypt($newpasswd));
543 $prefs->set('passwd', $newpasswd);
544 $this->setPreferences($prefs);
548 function mayChangePass() {
549 // on external DBAuth maybe. on IMAP or LDAP not
550 // on internal DBAuth yes
551 if (in_array($this->_authmethod, array('IMAP', 'LDAP')))
553 if ($this->isAdmin())
555 if ($this->_authmethod == 'pagedata')
557 if ($this->_authmethod == 'authdb')
562 // create user and default user homepage
563 // FIXME: delete this, not used?
565 function createUser ($userid, $pref) {
567 $user = new WikiUser ($request, $userid);
568 $user->createUser($pref);
572 class _UserPreference
574 function _UserPreference ($default_value) {
575 $this->default_value = $default_value;
578 function sanify ($value) {
579 return (string)$value;
582 function update ($value) {
586 class _UserPreference_numeric
587 extends _UserPreference
589 function _UserPreference_numeric ($default, $minval = false,
591 $this->_UserPreference((double)$default);
592 $this->_minval = (double)$minval;
593 $this->_maxval = (double)$maxval;
596 function sanify ($value) {
597 $value = (double)$value;
598 if ($this->_minval !== false && $value < $this->_minval)
599 $value = $this->_minval;
600 if ($this->_maxval !== false && $value > $this->_maxval)
601 $value = $this->_maxval;
606 class _UserPreference_int
607 extends _UserPreference_numeric
609 function _UserPreference_int ($default, $minval = false, $maxval = false) {
610 $this->_UserPreference_numeric((int)$default, (int)$minval,
614 function sanify ($value) {
615 return (int)parent::sanify((int)$value);
619 class _UserPreference_bool
620 extends _UserPreference
622 function _UserPreference_bool ($default = false) {
623 $this->_UserPreference((bool)$default);
626 function sanify ($value) {
627 if (is_array($value)) {
628 /* This allows for constructs like:
630 * <input type="hidden" name="pref[boolPref][]" value="0" />
631 * <input type="checkbox" name="pref[boolPref][]" value="1" />
633 * (If the checkbox is not checked, only the hidden input
634 * gets sent. If the checkbox is sent, both inputs get
637 foreach ($value as $val) {
643 return (bool) $value;
647 class _UserPreference_language
648 extends _UserPreference
650 function _UserPreference_language ($default = DEFAULT_LANGUAGE) {
651 $this->_UserPreference($default);
654 // FIXME: check for valid locale
655 function sanify ($value) {
656 // Revert to DEFAULT_LANGUAGE if user does not specify
657 // language in UserPreferences or chooses <system language>.
658 if ($value == '' or empty($value))
659 $value = DEFAULT_LANGUAGE;
661 return (string) $value;
665 class _UserPreference_theme
666 extends _UserPreference
668 function _UserPreference_theme ($default = THEME) {
669 $this->_UserPreference($default);
672 function sanify ($value) {
673 if (findFile($this->_themefile($value), true))
675 return $this->default_value;
678 function update ($newvalue) {
680 include_once($this->_themefile($newvalue));
681 if (empty($WikiTheme))
682 include_once($this->_themefile(THEME));
685 function _themefile ($theme) {
686 return "themes/$theme/themeinfo.php";
690 // don't save default preferences for efficiency.
691 class UserPreferences {
692 function UserPreferences ($saved_prefs = false) {
693 $this->_prefs = array();
695 if (isa($saved_prefs, 'UserPreferences') && $saved_prefs->_prefs) {
696 foreach ($saved_prefs->_prefs as $name => $value)
697 $this->set($name, $value);
698 } elseif (is_array($saved_prefs)) {
699 foreach ($saved_prefs as $name => $value)
700 $this->set($name, $value);
704 function _getPref ($name) {
705 global $UserPreferences;
706 if (!isset($UserPreferences[$name])) {
707 if ($name == 'passwd2') return false;
708 trigger_error("$name: unknown preference", E_USER_NOTICE);
711 return $UserPreferences[$name];
714 function get ($name) {
715 if (isset($this->_prefs[$name]))
716 return $this->_prefs[$name];
717 if (!($pref = $this->_getPref($name)))
719 return $pref->default_value;
722 function set ($name, $value) {
723 if (!($pref = $this->_getPref($name)))
726 $newvalue = $pref->sanify($value);
727 $oldvalue = $this->get($name);
730 if ($newvalue != $oldvalue)
731 $pref->update($newvalue);
733 // don't set default values to save space (in cookies, db and
735 if ($value == $pref->default_value)
736 unset($this->_prefs[$name]);
738 $this->_prefs[$name] = $newvalue;
741 function pack ($nonpacked) {
742 return serialize($nonpacked);
744 function unpack ($packed) {
747 if (substr($packed,0,2) == "O:") {
748 // Looks like a serialized object
749 return unserialize($packed);
751 //trigger_error("DEBUG: Can't unpack bad UserPreferences",
757 return wikihash($this->_prefs);
765 // c-hanging-comment-ender-p: nil
766 // indent-tabs-mode: nil