2 rcs_id('$Id: main.php,v 1.104 2003-12-26 06:41:16 carstenklapp Exp $');
4 define ('USE_PREFS_IN_PAGE', true);
6 include "lib/config.php";
7 require_once("lib/stdlib.php");
8 require_once('lib/Request.php');
9 require_once("lib/WikiUser.php");
10 require_once('lib/WikiDB.php');
12 class WikiRequest extends Request {
15 function WikiRequest () {
16 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
19 include_once('lib/DB_Session.php');
20 $this->_dbsession = & new DB_Session($this->getDbh(),
21 $GLOBALS['DBParams']['db_session_table']);
27 $this->setArg('pagename', $this->_deducePagename());
28 $this->setArg('action', $this->_deduceAction());
31 $this->_user = new WikiUser($this, $this->_deduceUsername());
32 // $this->_user = new WikiDB_User($this->_user->getId(), $this->getAuthDbh());
33 $this->_prefs = $this->_user->getPreferences();
36 function initializeLang () {
37 if ($user_lang = $this->getPref('lang')) {
38 //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
39 update_locale($user_lang);
43 function initializeTheme () {
47 if ($user_theme = $this->getPref('theme'))
48 include_once("themes/$user_theme/themeinfo.php");
49 if (empty($Theme) and defined ('THEME'))
50 include_once("themes/" . THEME . "/themeinfo.php");
52 include_once("themes/default/themeinfo.php");
53 assert(!empty($Theme));
57 // This really maybe should be part of the constructor, but since it
58 // may involve HTML/template output, the global $request really needs
59 // to be initialized before we do this stuff.
60 function updateAuthAndPrefs () {
62 // Handle preference updates, an authentication requests, if any.
63 if ($new_prefs = $this->getArg('pref')) {
64 $this->setArg('pref', false);
65 if ($this->isPost() and !empty($new_prefs['passwd']) and
66 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
68 $this->_prefs->set('passwd','');
69 // $this->_prefs->set('passwd2',''); // This is not stored anyway
72 foreach ($new_prefs as $key => $val) {
73 if ($key == 'passwd') {
75 $val = crypt('passwd');
77 $this->_prefs->set($key, $val);
81 // FIXME: need to move authentication request processing
82 // up to be before pref request processing, I think,
83 // since logging in may change which preferences
84 // we're talking about...
86 // Handle authentication request, if any.
87 if ($auth_args = $this->getArg('auth')) {
88 $this->setArg('auth', false);
89 $this->_handleAuthRequest($auth_args); // possible NORETURN
91 elseif ( ! $this->_user->isSignedIn() ) {
92 // If not auth request, try to sign in as saved user.
93 if (($saved_user = $this->getPref('userid')) != false) {
94 $this->_signIn($saved_user);
98 // Save preferences in session and cookie
99 // FIXME: hey! what about anonymous users? Can't they have
103 $this->_user->setPreferences($this->_prefs, $id_only);
105 // Ensure user has permissions for action
106 $require_level = $this->requiredAuthority($this->getArg('action'));
107 if (! $this->_user->hasAuthority($require_level))
108 $this->_notAuthorized($require_level); // NORETURN
111 function getUser () {
115 function getPrefs () {
116 return $this->_prefs;
119 // Convenience function:
120 function getPref ($key) {
121 return $this->_prefs->get($key);
128 function getAuthDbh () {
129 global $DBParams, $DBAuthParams;
130 if (!isset($this->_auth_dbi)) {
131 if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
132 $this->_auth_dbi = $this->getDbh(); // use phpwiki database
133 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
134 $this->_auth_dbi = $this->getDbh(); // same phpwiki database
135 else // use external database
136 // needs PHP 4.1. better use $this->_user->...
137 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
139 return $this->_auth_dbi;
143 * Get requested page from the page database.
144 * By default it will grab the page requested via the URL
146 * This is a convenience function.
147 * @param string $pagename Name of page to get.
148 * @return WikiDB_Page Object with methods to pull data from
149 * database for the page requested.
151 function getPage ($pagename = false) {
152 if (!isset($this->_dbi))
155 $pagename = $this->getArg('pagename');
156 return $this->_dbi->getPage($pagename);
159 /** Get URL for POST actions.
161 * Officially, we should just use SCRIPT_NAME (or some such),
162 * but that causes problems when we try to issue a redirect, e.g.
163 * after saving a page.
165 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
166 * a redirect from a page to itself.)
168 * So, as a HACK, we include pagename and action as query args in
169 * the URL. (These should be ignored when we receive the POST
172 function getPostURL ($pagename=false) {
173 if ($pagename === false)
174 $pagename = $this->getArg('pagename');
175 $action = $this->getArg('action');
176 return WikiURL($pagename, array('action' => $action));
179 function _handleAuthRequest ($auth_args) {
180 if (!is_array($auth_args))
183 // Ignore password unless POST'ed.
184 if (!$this->isPost())
185 unset($auth_args['passwd']);
187 $user = $this->_user->AuthCheck($auth_args);
189 if (isa($user, 'WikiUser')) {
190 // Successful login (or logout.)
191 $this->_setUser($user);
194 // Login attempt failed.
195 $fail_message = $user;
196 $auth_args['pass_required'] = true;
197 // If no password was submitted, it's not really
198 // a failure --- just need to prompt for password...
199 if (!isset($auth_args['passwd'])) {
200 //$auth_args['pass_required'] = false;
201 $fail_message = false;
203 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
204 $this->finish(); //NORETURN
207 // Login request cancelled.
212 * Attempt to sign in (bogo-login).
216 * @param $userid string Userid to attempt to sign in as.
219 function _signIn ($userid) {
220 $user = $this->_user->AuthCheck(array('userid' => $userid));
221 if (isa($user, 'WikiUser')) {
222 $this->_setUser($user); // success!
226 function _setUser ($user) {
227 $this->_user = $user;
228 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
229 $this->setSessionVar('wiki_user', $user);
230 if ($user->isSignedIn())
231 $user->_authhow = 'signin';
233 // Save userid to prefs..
234 $this->_prefs = $this->_user->getPreferences();
235 $this->_prefs->set('userid',
236 $user->isSignedIn() ? $user->getId() : '');
239 function _notAuthorized ($require_level) {
240 // Display the authority message in the Wiki's default
241 // language, in case it is not english.
243 // Note that normally a user will not see such an error once
244 // logged in, unless the admin has altered the default
245 // disallowed wikiactions. In that case we should probably
246 // check the user's language prefs too at this point; this
247 // would be a situation which is not really handled with the
249 update_locale(DEFAULT_LANGUAGE);
251 // User does not have required authority. Prompt for login.
252 $what = $this->getActionDescription($this->getArg('action'));
254 if ($require_level >= WIKIAUTH_FORBIDDEN) {
255 $this->finish(fmt("%s is disallowed on this wiki.",
256 $this->getDisallowedActionDescription($this->getArg('action'))));
258 elseif ($require_level == WIKIAUTH_BOGO)
259 $msg = fmt("You must sign in to %s.", $what);
260 elseif ($require_level == WIKIAUTH_USER)
261 $msg = fmt("You must log in to %s.", $what);
263 $msg = fmt("You must be an administrator to %s.", $what);
264 $pass_required = ($require_level >= WIKIAUTH_USER);
266 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
267 $this->finish(); // NORETURN
270 function getActionDescription($action) {
271 static $actionDescriptions;
272 if (! $actionDescriptions) {
274 = array('browse' => _("browse pages in this wiki"),
275 'diff' => _("diff pages in this wiki"),
276 'dumphtml' => _("dump html pages from this wiki"),
277 'dumpserial' => _("dump serial pages from this wiki"),
278 'edit' => _("edit pages in this wiki"),
279 'create' => _("create pages in this wiki"),
280 'loadfile' => _("load files into this wiki"),
281 'lock' => _("lock pages in this wiki"),
282 'remove' => _("remove pages from this wiki"),
283 'unlock' => _("unlock pages in this wiki"),
284 'upload' => _("upload a zip dump to this wiki"),
285 'verify' => _("verify the current action"),
286 'viewsource' => _("view the source of pages in this wiki"),
287 'xmlrpc' => _("access this wiki via XML-RPC"),
288 'zip' => _("download a zip dump from this wiki"),
289 'ziphtml' => _("download an html zip dump from this wiki")
292 if (in_array($action, array_keys($actionDescriptions)))
293 return $actionDescriptions[$action];
297 function getDisallowedActionDescription($action) {
298 static $disallowedActionDescriptions;
299 if (! $disallowedActionDescriptions) {
300 $disallowedActionDescriptions
301 = array('browse' => _("Browsing pages"),
302 'diff' => _("Diffing pages"),
303 'dumphtml' => _("Dumping html pages"),
304 'dumpserial' => _("Dumping serial pages"),
305 'edit' => _("Editing pages"),
306 'create' => _("Creating pages"),
307 'loadfile' => _("Loading files"),
308 'lock' => _("Locking pages"),
309 'remove' => _("Removing pages"),
310 'unlock' => _("Unlocking pages"),
311 'upload' => _("Uploading zip dumps"),
312 'verify' => _("Verify the current action"),
313 'viewsource' => _("Viewing the source of pages"),
314 'xmlrpc' => _("XML-RPC access"),
315 'zip' => _("Downloading zip dumps"),
316 'ziphtml' => _("Downloading html zip dumps")
319 if (in_array($action, array_keys($disallowedActionDescriptions)))
320 return $disallowedActionDescriptions[$action];
325 function requiredAuthority ($action) {
326 $auth = $this->requiredAuthorityForAction($action);
329 * This is a hook for plugins to require authority
330 * for posting to them.
332 * IMPORTANT: this is not a secure check, so the plugin
333 * may not assume that any POSTs to it are authorized.
334 * All this does is cause PhpWiki to prompt for login
335 * if the user doesn't have the required authority.
337 if ($this->isPost()) {
338 $post_auth = $this->getArg('require_authority_for_post');
339 if ($post_auth !== false)
340 $auth = max($auth, $post_auth);
345 function requiredAuthorityForAction ($action) {
347 // Todo: Check individual page permissions instead.
355 return WIKIAUTH_ANON;
359 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
360 return WIKIAUTH_ADMIN;
361 return WIKIAUTH_ANON;
364 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
365 return WIKIAUTH_BOGO;
366 return WIKIAUTH_ANON;
367 // return WIKIAUTH_BOGO;
370 $page = $this->getPage();
371 $current = $page->getCurrentRevision();
372 if ($current->hasDefaultContents())
373 return $this->requiredAuthorityForAction('edit');
374 return $this->requiredAuthorityForAction('browse');
383 return WIKIAUTH_ADMIN;
385 global $WikiNameRegexp;
386 if (preg_match("/$WikiNameRegexp\Z/A", $action))
387 return WIKIAUTH_ANON; // ActionPage.
389 return WIKIAUTH_ADMIN;
393 function possiblyDeflowerVirginWiki () {
394 if ($this->getArg('action') != 'browse')
396 if ($this->getArg('pagename') != HOME_PAGE)
399 $page = $this->getPage();
400 $current = $page->getCurrentRevision();
401 if ($current->getVersion() > 0)
402 return; // Homepage exists.
404 include('lib/loadsave.php');
406 $this->finish(); // NORETURN
409 function handleAction () {
410 $action = $this->getArg('action');
411 $method = "action_$action";
412 if (method_exists($this, $method)) {
415 elseif ($page = $this->findActionPage($action)) {
416 $this->actionpage($page);
419 $this->finish(fmt("%s: Bad action", $action));
423 function finish ($errormsg = false) {
427 exit(); // just in case CloseDataBase calls us
430 if (!empty($this->_dbi))
431 $this->_dbi->close();
435 global $ErrorManager;
436 $ErrorManager->flushPostponedErrors();
438 if (!empty($errormsg)) {
441 HTML::h2(_("Fatal PhpWiki Error")),
444 echo "\n</body></html>";
451 function _deducePagename () {
452 if ($this->getArg('pagename'))
453 return $this->getArg('pagename');
456 $pathinfo = $this->get('PATH_INFO');
457 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
459 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
463 elseif ($this->isPost()) {
465 * In general, for security reasons, HTTP_GET_VARS should be ignored
466 * on POST requests, but we make an exception here (only for pagename).
468 * The justifcation for this hack is the following
469 * asymmetry: When POSTing with USE_PATH_INFO set, the
470 * pagename can (and should) be communicated through the
471 * request URL via PATH_INFO. When POSTing with
472 * USE_PATH_INFO off, this cannot be done --- the only way
473 * to communicate the pagename through the URL is via
474 * QUERY_ARGS (HTTP_GET_VARS).
476 global $HTTP_GET_VARS;
477 if (isset($HTTP_GET_VARS['pagename'])) {
478 return $HTTP_GET_VARS['pagename'];
483 * Support for PhpWiki 1.2 style requests.
485 $query_string = $this->get('QUERY_STRING');
486 if (preg_match('/^[^&=]+$/', $query_string)) {
487 return urldecode($query_string);
493 function _deduceAction () {
494 if (!($action = $this->getArg('action'))) {
495 // Detect XML-RPC requests
497 && $this->get('CONTENT_TYPE') == 'text/xml') {
498 global $HTTP_RAW_POST_DATA;
499 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
504 return 'browse'; // Default if no action specified.
507 if (method_exists($this, "action_$action"))
510 // Allow for, e.g. action=LikePages
511 if ($this->isActionPage($action))
514 trigger_error("$action: Unknown action", E_USER_NOTICE);
518 function _deduceUsername () {
519 if ($userid = $this->getSessionVar('wiki_user')) {
520 if (!empty($this->_user))
521 $this->_user->_authhow = 'session';
524 if ($userid = $this->getCookieVar('WIKI_ID')) {
525 if (!empty($this->_user))
526 $this->_user->authhow = 'cookie';
532 function _isActionPage ($pagename) {
533 $dbi = $this->getDbh();
534 $page = $dbi->getPage($pagename);
535 $rev = $page->getCurrentRevision();
536 // FIXME: more restrictive check for sane plugin?
537 if (strstr($rev->getPackedContent(), '<?plugin'))
539 if (!$rev->hasDefaultContents())
540 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
544 function findActionPage ($action) {
547 // check for translated version, as per users preferred language
548 // (or system default in case it is not en)
549 $translation = gettext($action);
551 if (isset($cache) and isset($cache[$translation]))
552 return $cache[$translation];
554 // check for cached translated version
555 if ($this->_isActionPage($translation))
556 return $cache[$action] = $translation;
558 // Allow for, e.g. action=LikePages
559 global $WikiNameRegexp;
560 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
561 return $cache[$action] = false;
563 // check for translated version (default language)
565 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
567 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
568 update_locale(DEFAULT_LANGUAGE);
569 $default = gettext($action);
570 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
571 update_locale($save_lang);
572 if ($this->_isActionPage($default))
573 return $cache[$action] = $default;
576 $default = $translation;
579 // check for english version
580 if ($action != $translation and $action != $default) {
581 if ($this->_isActionPage($action))
582 return $cache[$action] = $action;
585 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
586 return $cache[$action] = false;
589 function isActionPage ($pagename) {
590 return $this->findActionPage($pagename);
593 function action_browse () {
594 $this->buffer_output();
595 include_once("lib/display.php");
599 function action_verify () {
600 $this->action_browse();
603 function actionpage ($action) {
604 $this->buffer_output();
605 include_once("lib/display.php");
606 actionPage($this, $action);
609 function action_diff () {
610 $this->buffer_output();
611 include_once "lib/diff.php";
615 function action_search () {
616 // This is obsolete: reformulate URL and redirect.
617 // FIXME: this whole section should probably be deleted.
618 if ($this->getArg('searchtype') == 'full') {
619 $search_page = _("FullTextSearch");
622 $search_page = _("TitleSearch");
624 $this->redirect(WikiURL($search_page,
625 array('s' => $this->getArg('searchterm')),
629 function action_edit () {
630 $this->buffer_output();
631 include "lib/editpage.php";
632 $e = new PageEditor ($this);
636 function action_create () {
637 $this->action_edit();
640 function action_viewsource () {
641 $this->buffer_output();
642 include "lib/editpage.php";
643 $e = new PageEditor ($this);
647 function action_lock () {
648 $page = $this->getPage();
649 $page->set('locked', true);
650 $this->action_browse();
653 function action_unlock () {
654 // FIXME: This check is redundant.
655 //$user->requireAuth(WIKIAUTH_ADMIN);
656 $page = $this->getPage();
657 $page->set('locked', false);
658 $this->action_browse();
661 function action_remove () {
662 // FIXME: This check is redundant.
663 //$user->requireAuth(WIKIAUTH_ADMIN);
664 $pagename = $this->getArg('pagename');
665 if (strstr($pagename,_('PhpWikiAdministration'))) {
666 $this->action_browse();
668 include('lib/removepage.php');
674 function action_upload () {
675 include_once("lib/loadsave.php");
679 function action_xmlrpc () {
680 include_once("lib/XmlRpcServer.php");
681 $xmlrpc = new XmlRpcServer($this);
685 function action_zip () {
686 include_once("lib/loadsave.php");
688 // I don't think it hurts to add cruft at the end of the zip file.
689 echo "\n========================================================\n";
690 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
693 function action_ziphtml () {
694 include_once("lib/loadsave.php");
695 MakeWikiZipHtml($this);
696 // I don't think it hurts to add cruft at the end of the zip file.
697 echo "\n========================================================\n";
698 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
701 function action_dumpserial () {
702 include_once("lib/loadsave.php");
706 function action_dumphtml () {
707 include_once("lib/loadsave.php");
708 DumpHtmlToDir($this);
711 function action_loadfile () {
712 include_once("lib/loadsave.php");
713 LoadFileOrDir($this);
718 function is_safe_action ($action) {
719 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
722 function validateSessionPath() {
723 // Try to defer any session.save_path PHP errors before any html
724 // is output, which causes some versions of IE to display a blank
725 // page (due to its strict mode while parsing a page?).
726 if (! is_writeable(ini_get('session.save_path'))) {
729 (sprintf(_("%s is not writable."),
730 _("The session.save_path directory"))
732 . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
733 sprintf(_("the directory '%s'"),
734 ini_get('session.save_path')),
737 . sprintf(_("Attempting to use the directory '%s' instead."),
740 if (! is_writeable($tmpdir)) {
742 (sprintf(_("%s is not writable."), $tmpdir)
744 . _("Users will not be able to sign in.")
748 ini_set('session.save_path', $tmpdir);
753 validateSessionPath();
757 $request = new WikiRequest();
760 * Allow for disabling of markup cache.
761 * (Mostly for debugging ... hopefully.)
763 * See also <?plugin WikiAdminUtils action=purge-cache ?>
765 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
766 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
768 // Initialize with system defaults in case user not logged in.
769 // Should this go into constructor?
770 $request->initializeTheme();
772 $request->updateAuthAndPrefs();
773 // initialize again with user's prefs
774 $request->initializeTheme();
775 $request->initializeLang();
777 // Enable the output of most of the warning messages.
778 // The warnings will screw up zip files though.
779 global $ErrorManager;
780 if (substr($request->getArg('action'), 0, 3) != 'zip') {
781 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
782 //$ErrorManager->setPostponedErrorMask(0);
786 //if ($user->is_authenticated())
787 // $LogEntry->user = $user->getId();
789 $request->possiblyDeflowerVirginWiki();
791 if(defined('WIKI_XMLRPC')) return;
793 $validators = array('wikiname' => WIKI_NAME,
794 'args' => hash($request->getArgs()),
795 'prefs' => hash($request->getPrefs()));
796 if (CACHE_CONTROL == 'STRICT') {
797 $dbi = $request->getDbh();
798 $timestamp = $dbi->getTimestamp();
799 $validators['mtime'] = $timestamp;
800 $validators['%mtime'] = (int)$timestamp;
802 // FIXME: we should try to generate strong validators when possible,
803 // but for now, our validator is weak, since equal validators do not
804 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
806 // (If DEBUG if off, this may be a strong validator, but I'm going
807 // to go the paranoid route here pending further study and testing.)
809 $validators['%weak'] = true;
811 $request->setValidators($validators);
813 $request->handleAction();
815 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
823 // $Log: not supported by cvs2svn $
824 // Revision 1.103 2003/12/02 00:10:00 carstenklapp
825 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
826 // mess: UserPreferences should take effect immediately now upon signing
829 // Revision 1.102 2003/11/25 22:55:32 carstenklapp
830 // Localization bugfix: For wikis where English is not the default system
831 // language, make sure that the authority error message (i.e. "You must
832 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
833 // default language. Previously it would always display in English.
834 // (Added call to update_locale() before displaying any messages prior to
835 // the login prompt.)
837 // Revision 1.101 2003/11/25 21:49:44 carstenklapp
838 // Bugfix: For a non-english wiki or when the user's preference is not
839 // english, the wiki would always use the english ActionPage first if it
840 // was present rather than the appropriate localised variant. (PhpWikis
841 // running only in english or Wikis running ONLY without any english
842 // ActionPages would not notice this bug, only when both english and
843 // localised ActionPages were in the DB.) Now we check for the localised
846 // Revision 1.100 2003/11/18 16:54:18 carstenklapp
847 // Reformatting only: Tabs to spaces, added rcs log.
855 // c-hanging-comment-ender-p: nil
856 // indent-tabs-mode: nil