2 rcs_id('$Id: main.php,v 1.98 2003-03-04 05:33:00 dairiki Exp $');
4 define ('USE_PREFS_IN_PAGE', true);
6 include "lib/config.php";
7 include "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 () {
17 include_once('lib/DB_Session.php');
18 $this->_dbi = $this->getDbh();
19 $this->_dbsession = & new DB_Session($this->_dbi,
20 $GLOBALS['DBParams']['db_session_table']);
26 $this->setArg('pagename', $this->_deducePagename());
27 $this->setArg('action', $this->_deduceAction());
30 $this->_user = new WikiUser($this, $this->_deduceUsername());
31 // $this->_user = new WikiDB_User($this->_user->getId(), $this->getAuthDbh());
32 $this->_prefs = $this->_user->getPreferences();
35 function initializeLang () {
36 if ($user_lang = $this->getPref('lang')) {
37 //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
38 update_locale($user_lang);
42 function initializeTheme () {
46 if ($user_theme = $this->getPref('theme'))
47 include_once("themes/$user_theme/themeinfo.php");
48 if (empty($Theme) and defined ('THEME'))
49 include_once("themes/" . THEME . "/themeinfo.php");
51 include_once("themes/default/themeinfo.php");
52 assert(!empty($Theme));
56 // This really maybe should be part of the constructor, but since it
57 // may involve HTML/template output, the global $request really needs
58 // to be initialized before we do this stuff.
59 function updateAuthAndPrefs () {
61 // Handle preference updates, an authentication requests, if any.
62 if ($new_prefs = $this->getArg('pref')) {
63 $this->setArg('pref', false);
64 if ($this->isPost() and !empty($new_prefs['passwd']) and
65 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
67 $this->_prefs->set('passwd','');
68 // $this->_prefs->set('passwd2',''); // This is not stored anyway
71 foreach ($new_prefs as $key => $val) {
72 if ($key == 'passwd') {
74 $val = crypt('passwd');
76 $this->_prefs->set($key, $val);
80 // FIXME: need to move authentication request processing
81 // up to be before pref request processing, I think,
82 // since logging in may change which preferences
83 // we're talking about...
85 // Handle authentication request, if any.
86 if ($auth_args = $this->getArg('auth')) {
87 $this->setArg('auth', false);
88 $this->_handleAuthRequest($auth_args); // possible NORETURN
90 elseif ( ! $this->_user->isSignedIn() ) {
91 // If not auth request, try to sign in as saved user.
92 if (($saved_user = $this->getPref('userid')) != false) {
93 $this->_signIn($saved_user);
97 // Save preferences in session and cookie
98 // FIXME: hey! what about anonymous users? Can't they have
102 $this->_user->setPreferences($this->_prefs, $id_only);
104 // Ensure user has permissions for action
105 $require_level = $this->requiredAuthority($this->getArg('action'));
106 if (! $this->_user->hasAuthority($require_level))
107 $this->_notAuthorized($require_level); // NORETURN
110 function getUser () {
114 function getPrefs () {
115 return $this->_prefs;
118 // Convenience function:
119 function getPref ($key) {
120 return $this->_prefs->get($key);
124 if (!isset($this->_dbi)) {
125 // needs PHP 4.1. better use $this->_user->...
126 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
131 function getAuthDbh () {
132 global $DBParams, $DBAuthParams;
133 if (!isset($this->_auth_dbi)) {
134 if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
135 $this->_auth_dbi = $this->getDbh(); // use phpwiki database
136 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
137 $this->_auth_dbi = $this->getDbh(); // same phpwiki database
138 else // use external database
139 // needs PHP 4.1. better use $this->_user->...
140 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
142 return $this->_auth_dbi;
146 * Get requested page from the page database.
147 * By default it will grab the page requested via the URL
149 * This is a convenience function.
150 * @param string $pagename Name of page to get.
151 * @return WikiDB_Page Object with methods to pull data from
152 * database for the page requested.
154 function getPage ($pagename = false) {
155 if (!isset($this->_dbi))
158 $pagename = $this->getArg('pagename');
159 return $this->_dbi->getPage($pagename);
162 /** Get URL for POST actions.
164 * Officially, we should just use SCRIPT_NAME (or some such),
165 * but that causes problems when we try to issue a redirect, e.g.
166 * after saving a page.
168 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
169 * a redirect from a page to itself.)
171 * So, as a HACK, we include pagename and action as query args in
172 * the URL. (These should be ignored when we receive the POST
175 function getPostURL ($pagename=false) {
176 if ($pagename === false)
177 $pagename = $this->getArg('pagename');
178 $action = $this->getArg('action');
179 return WikiURL($pagename, array('action' => $action));
182 function _handleAuthRequest ($auth_args) {
183 if (!is_array($auth_args))
186 // Ignore password unless POST'ed.
187 if (!$this->isPost())
188 unset($auth_args['passwd']);
190 $user = $this->_user->AuthCheck($auth_args);
192 if (isa($user, 'WikiUser')) {
193 // Successful login (or logout.)
194 $this->_setUser($user);
197 // Login attempt failed.
198 $fail_message = $user;
199 $auth_args['pass_required'] = true;
200 // If no password was submitted, it's not really
201 // a failure --- just need to prompt for password...
202 if (!isset($auth_args['passwd'])) {
203 //$auth_args['pass_required'] = false;
204 $fail_message = false;
206 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
207 $this->finish(); //NORETURN
210 // Login request cancelled.
215 * Attempt to sign in (bogo-login).
219 * @param $userid string Userid to attempt to sign in as.
222 function _signIn ($userid) {
223 $user = $this->_user->AuthCheck(array('userid' => $userid));
224 if (isa($user, 'WikiUser')) {
225 $this->_setUser($user); // success!
229 function _setUser ($user) {
230 $this->_user = $user;
231 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
232 $this->setSessionVar('wiki_user', $user);
233 if ($user->isSignedIn())
234 $user->_authhow = 'signin';
236 // Save userid to prefs..
237 $this->_prefs->set('userid',
238 $user->isSignedIn() ? $user->getId() : '');
241 function _notAuthorized ($require_level) {
242 // User does not have required authority. Prompt for login.
243 $what = $this->getActionDescription($this->getArg('action'));
245 if ($require_level >= WIKIAUTH_FORBIDDEN) {
246 $this->finish(fmt("%s is disallowed on this wiki.",
247 $this->getDisallowedActionDescription($this->getArg('action'))));
249 elseif ($require_level == WIKIAUTH_BOGO)
250 $msg = fmt("You must sign in to %s.", $what);
251 elseif ($require_level == WIKIAUTH_USER)
252 $msg = fmt("You must log in to %s.", $what);
254 $msg = fmt("You must be an administrator to %s.", $what);
255 $pass_required = ($require_level >= WIKIAUTH_USER);
257 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
258 $this->finish(); // NORETURN
261 function getActionDescription($action) {
262 static $actionDescriptions;
263 if (! $actionDescriptions) {
265 = array('browse' => _("browse pages in this wiki"),
266 'diff' => _("diff pages in this wiki"),
267 'dumphtml' => _("dump html pages from this wiki"),
268 'dumpserial' => _("dump serial pages from this wiki"),
269 'edit' => _("edit pages in this wiki"),
270 'create' => _("create pages in this wiki"),
271 'loadfile' => _("load files into this wiki"),
272 'lock' => _("lock pages in this wiki"),
273 'remove' => _("remove pages from this wiki"),
274 'unlock' => _("unlock pages in this wiki"),
275 'upload' => _("upload a zip dump to this wiki"),
276 'verify' => _("verify the current action"),
277 'viewsource' => _("view the source of pages in this wiki"),
278 'xmlrpc' => _("access this wiki via XML-RPC"),
279 'zip' => _("download a zip dump from this wiki"),
280 'ziphtml' => _("download an html zip dump from this wiki")
283 if (in_array($action, array_keys($actionDescriptions)))
284 return $actionDescriptions[$action];
288 function getDisallowedActionDescription($action) {
289 static $disallowedActionDescriptions;
290 if (! $disallowedActionDescriptions) {
291 $disallowedActionDescriptions
292 = array('browse' => _("Browsing pages"),
293 'diff' => _("Diffing pages"),
294 'dumphtml' => _("Dumping html pages"),
295 'dumpserial' => _("Dumping serial pages"),
296 'edit' => _("Editing pages"),
297 'create' => _("Creating pages"),
298 'loadfile' => _("Loading files"),
299 'lock' => _("Locking pages"),
300 'remove' => _("Removing pages"),
301 'unlock' => _("Unlocking pages"),
302 'upload' => _("Uploading zip dumps"),
303 'verify' => _("Verify the current action"),
304 'viewsource' => _("Viewing the source of pages"),
305 'xmlrpc' => _("XML-RPC access"),
306 'zip' => _("Downloading zip dumps"),
307 'ziphtml' => _("Downloading html zip dumps")
310 if (in_array($action, array_keys($disallowedActionDescriptions)))
311 return $disallowedActionDescriptions[$action];
316 function requiredAuthority ($action) {
317 $auth = $this->requiredAuthorityForAction($action);
320 * This is a hook for plugins to require authority
321 * for posting to them.
323 * IMPORTANT: this is not a secure check, so the plugin
324 * may not assume that any POSTs to it are authorized.
325 * All this does is cause PhpWiki to prompt for login
326 * if the user doesn't have the required authority.
328 if ($this->isPost()) {
329 $post_auth = $this->getArg('require_authority_for_post');
330 if ($post_auth !== false)
331 $auth = max($auth, $post_auth);
336 function requiredAuthorityForAction ($action) {
338 // Todo: Check individual page permissions instead.
345 return WIKIAUTH_ANON;
348 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
349 return WIKIAUTH_ADMIN;
350 return WIKIAUTH_ANON;
353 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
354 return WIKIAUTH_ADMIN;
355 return WIKIAUTH_ANON;
358 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
359 return WIKIAUTH_BOGO;
360 return WIKIAUTH_ANON;
361 // return WIKIAUTH_BOGO;
364 $page = $this->getPage();
365 $current = $page->getCurrentRevision();
366 if ($current->hasDefaultContents())
367 return $this->requiredAuthorityForAction('edit');
368 return $this->requiredAuthorityForAction('browse');
377 return WIKIAUTH_ADMIN;
379 global $WikiNameRegexp;
380 if (preg_match("/$WikiNameRegexp\Z/A", $action))
381 return WIKIAUTH_ANON; // ActionPage.
383 return WIKIAUTH_ADMIN;
387 function possiblyDeflowerVirginWiki () {
388 if ($this->getArg('action') != 'browse')
390 if ($this->getArg('pagename') != HOME_PAGE)
393 $page = $this->getPage();
394 $current = $page->getCurrentRevision();
395 if ($current->getVersion() > 0)
396 return; // Homepage exists.
398 include('lib/loadsave.php');
400 $this->finish(); // NORETURN
403 function handleAction () {
404 $action = $this->getArg('action');
405 $method = "action_$action";
406 if (method_exists($this, $method)) {
409 elseif ($page = $this->findActionPage($action)) {
410 $this->actionpage($page);
413 $this->finish(fmt("%s: Bad action", $action));
417 function finish ($errormsg = false) {
421 exit(); // just in case CloseDataBase calls us
424 if (!empty($this->_dbi))
425 $this->_dbi->close();
429 global $ErrorManager;
430 $ErrorManager->flushPostponedErrors();
432 if (!empty($errormsg)) {
435 HTML::h2(_("Fatal PhpWiki Error")),
438 echo "\n</body></html>";
445 function _deducePagename () {
446 if ($this->getArg('pagename'))
447 return $this->getArg('pagename');
450 $pathinfo = $this->get('PATH_INFO');
451 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
453 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
457 elseif ($this->isPost()) {
459 * In general, for security reasons, HTTP_GET_VARS should be ignored
460 * on POST requests, but we make an exception here (only for pagename).
462 * The justifcation for this hack is the following
463 * asymmetry: When POSTing with USE_PATH_INFO set, the
464 * pagename can (and should) be communicated through the
465 * request URL via PATH_INFO. When POSTing with
466 * USE_PATH_INFO off, this cannot be done --- the only way
467 * to communicate the pagename through the URL is via
468 * QUERY_ARGS (HTTP_GET_VARS).
470 global $HTTP_GET_VARS;
471 if (isset($HTTP_GET_VARS['pagename'])) {
472 return $HTTP_GET_VARS['pagename'];
477 * Support for PhpWiki 1.2 style requests.
479 $query_string = $this->get('QUERY_STRING');
480 if (preg_match('/^[^&=]+$/', $query_string)) {
481 return urldecode($query_string);
487 function _deduceAction () {
488 if (!($action = $this->getArg('action'))) {
489 // Detect XML-RPC requests
491 && $this->get('CONTENT_TYPE') == 'text/xml') {
492 global $HTTP_RAW_POST_DATA;
493 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
498 return 'browse'; // Default if no action specified.
501 if (method_exists($this, "action_$action"))
504 // Allow for, e.g. action=LikePages
505 if ($this->isActionPage($action))
508 trigger_error("$action: Unknown action", E_USER_NOTICE);
512 function _deduceUsername () {
513 if ($userid = $this->getSessionVar('wiki_user')) {
514 if (!empty($this->_user))
515 $this->_user->_authhow = 'session';
518 if ($userid = $this->getCookieVar('WIKI_ID')) {
519 if (!empty($this->_user))
520 $this->_user->authhow = 'cookie';
526 function _isActionPage ($pagename) {
527 $dbi = $this->getDbh();
528 $page = $dbi->getPage($pagename);
529 $rev = $page->getCurrentRevision();
530 // FIXME: more restrictive check for sane plugin?
531 if (strstr($rev->getPackedContent(), '<?plugin'))
533 if (!$rev->hasDefaultContents())
534 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
538 function findActionPage ($action) {
541 if (isset($cache) and isset($cache[$action]))
542 return $cache[$action];
544 // Allow for, e.g. action=LikePages
545 global $WikiNameRegexp;
546 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
547 return $cache[$action] = false;
549 // check for translated version (users preferred language)
550 $translation = gettext($action);
551 if ($this->_isActionPage($translation))
552 return $cache[$action] = $translation;
554 // check for translated version (default language)
556 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
558 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
559 update_locale(DEFAULT_LANGUAGE);
560 $default = gettext($action);
561 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
562 update_locale($save_lang);
563 if ($this->_isActionPage($default))
564 return $cache[$action] = $default;
567 $default = $translation;
570 // check for english version
571 if ($action != $translation and $action != $default) {
572 if ($this->_isActionPage($action))
573 return $cache[$action] = $action;
576 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
577 return $cache[$action] = false;
580 function isActionPage ($pagename) {
581 return $this->findActionPage($pagename);
584 function action_browse () {
585 $this->buffer_output();
586 include_once("lib/display.php");
590 function action_verify () {
591 $this->action_browse();
594 function actionpage ($action) {
595 $this->buffer_output();
596 include_once("lib/display.php");
597 actionPage($this, $action);
600 function action_diff () {
601 $this->buffer_output();
602 include_once "lib/diff.php";
606 function action_search () {
607 // This is obsolete: reformulate URL and redirect.
608 // FIXME: this whole section should probably be deleted.
609 if ($this->getArg('searchtype') == 'full') {
610 $search_page = _("FullTextSearch");
613 $search_page = _("TitleSearch");
615 $this->redirect(WikiURL($search_page,
616 array('s' => $this->getArg('searchterm')),
620 function action_edit () {
621 $this->buffer_output();
622 include "lib/editpage.php";
623 $e = new PageEditor ($this);
627 function action_create () {
628 $this->action_edit();
631 function action_viewsource () {
632 $this->buffer_output();
633 include "lib/editpage.php";
634 $e = new PageEditor ($this);
638 function action_lock () {
639 $page = $this->getPage();
640 $page->set('locked', true);
641 $this->action_browse();
644 function action_unlock () {
645 // FIXME: This check is redundant.
646 //$user->requireAuth(WIKIAUTH_ADMIN);
647 $page = $this->getPage();
648 $page->set('locked', false);
649 $this->action_browse();
652 function action_remove () {
653 // FIXME: This check is redundant.
654 //$user->requireAuth(WIKIAUTH_ADMIN);
655 $pagename = $this->getArg('pagename');
656 if (strstr($pagename,_('PhpWikiAdministration'))) {
657 $this->action_browse();
659 include('lib/removepage.php');
665 function action_upload () {
666 include_once("lib/loadsave.php");
670 function action_xmlrpc () {
671 include_once("lib/XmlRpcServer.php");
672 $xmlrpc = new XmlRpcServer($this);
676 function action_zip () {
677 include_once("lib/loadsave.php");
679 // I don't think it hurts to add cruft at the end of the zip file.
680 echo "\n========================================================\n";
681 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
684 function action_ziphtml () {
685 include_once("lib/loadsave.php");
686 MakeWikiZipHtml($this);
687 // I don't think it hurts to add cruft at the end of the zip file.
688 echo "\n========================================================\n";
689 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
692 function action_dumpserial () {
693 include_once("lib/loadsave.php");
697 function action_dumphtml () {
698 include_once("lib/loadsave.php");
699 DumpHtmlToDir($this);
702 function action_loadfile () {
703 include_once("lib/loadsave.php");
704 LoadFileOrDir($this);
709 function is_safe_action ($action) {
710 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
717 $request = new WikiRequest();
720 * Allow for disabling of markup cache.
721 * (Mostly for debugging ... hopefully.)
723 * See also <?plugin WikiAdminUtils action=purge-cache ?>
725 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
726 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
728 // Initialize with system defaults in case user not logged in.
729 // Should this go into constructor?
730 $request->initializeTheme();
732 $request->updateAuthAndPrefs();
733 // initialize again with user's prefs
734 $request->initializeTheme();
735 $request->initializeLang();
737 // Enable the output of most of the warning messages.
738 // The warnings will screw up zip files though.
739 global $ErrorManager;
740 if (substr($request->getArg('action'), 0, 3) != 'zip') {
741 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
742 //$ErrorManager->setPostponedErrorMask(0);
746 //if ($user->is_authenticated())
747 // $LogEntry->user = $user->getId();
749 $request->possiblyDeflowerVirginWiki();
751 if(defined('WIKI_XMLRPC')) return;
753 $validators = array('wikiname' => WIKI_NAME,
754 'args' => hash($request->getArgs()),
755 'prefs' => hash($request->getPrefs()));
756 if (CACHE_CONTROL == 'STRICT') {
757 $dbi = $request->getDbh();
758 $timestamp = $dbi->getTimestamp();
759 $validators['mtime'] = $timestamp;
760 $validators['%mtime'] = (int)$timestamp;
763 $request->setValidators($validators);
765 $request->handleAction();
767 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
779 // c-hanging-comment-ender-p: nil
780 // indent-tabs-mode: nil