2 rcs_id('$Id: main.php,v 1.96 2003-02-26 02:55:53 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');
13 include_once('lib/DB_Session.php');
16 class WikiRequest extends Request {
19 function WikiRequest () {
21 $this->_dbi = $this->getDbh();
22 new DB_Session($this->_dbi->_backend->_dbh,
23 $GLOBALS['DBParams']['db_session_table']);
29 $this->setArg('pagename', $this->_deducePagename());
30 $this->setArg('action', $this->_deduceAction());
33 $this->_user = new WikiUser($this, $this->_deduceUsername());
34 // $this->_user = new WikiDB_User($this->_user->getId(), $this->getAuthDbh());
35 $this->_prefs = $this->_user->getPreferences();
38 function initializeLang () {
39 if ($user_lang = $this->getPref('lang')) {
40 //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
41 update_locale($user_lang);
45 function initializeTheme () {
49 if ($user_theme = $this->getPref('theme'))
50 include_once("themes/$user_theme/themeinfo.php");
51 if (empty($Theme) and defined ('THEME'))
52 include_once("themes/" . THEME . "/themeinfo.php");
54 include_once("themes/default/themeinfo.php");
55 assert(!empty($Theme));
59 // This really maybe should be part of the constructor, but since it
60 // may involve HTML/template output, the global $request really needs
61 // to be initialized before we do this stuff.
62 function updateAuthAndPrefs () {
64 // Handle preference updates, an authentication requests, if any.
65 if ($new_prefs = $this->getArg('pref')) {
66 $this->setArg('pref', false);
67 if ($this->isPost() and !empty($new_prefs['passwd']) and
68 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
70 $this->_prefs->set('passwd','');
71 // $this->_prefs->set('passwd2',''); // This is not stored anyway
74 foreach ($new_prefs as $key => $val) {
75 if ($key == 'passwd') {
77 $val = crypt('passwd');
79 $this->_prefs->set($key, $val);
83 // FIXME: need to move authentication request processing
84 // up to be before pref request processing, I think,
85 // since logging in may change which preferences
86 // we're talking about...
88 // Handle authentication request, if any.
89 if ($auth_args = $this->getArg('auth')) {
90 $this->setArg('auth', false);
91 $this->_handleAuthRequest($auth_args); // possible NORETURN
93 elseif ( ! $this->_user->isSignedIn() ) {
94 // If not auth request, try to sign in as saved user.
95 if (($saved_user = $this->getPref('userid')) != false) {
96 $this->_signIn($saved_user);
100 // Save preferences in session and cookie
101 // FIXME: hey! what about anonymous users? Can't they have
105 $this->_user->setPreferences($this->_prefs, $id_only);
107 // Ensure user has permissions for action
108 $require_level = $this->requiredAuthority($this->getArg('action'));
109 if (! $this->_user->hasAuthority($require_level))
110 $this->_notAuthorized($require_level); // NORETURN
113 function getUser () {
117 function getPrefs () {
118 return $this->_prefs;
121 // Convenience function:
122 function getPref ($key) {
123 return $this->_prefs->get($key);
127 if (!isset($this->_dbi)) {
128 // needs PHP 4.1. better use $this->_user->...
129 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
134 function getAuthDbh () {
135 global $DBParams, $DBAuthParams;
136 if (!isset($this->_auth_dbi)) {
137 if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
138 $this->_auth_dbi = $this->getDbh(); // use phpwiki database
139 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
140 $this->_auth_dbi = $this->getDbh(); // same phpwiki database
141 else // use external database
142 // needs PHP 4.1. better use $this->_user->...
143 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
145 return $this->_auth_dbi;
149 * Get requested page from the page database.
150 * By default it will grab the page requested via the URL
152 * This is a convenience function.
153 * @param string $pagename Name of page to get.
154 * @return WikiDB_Page Object with methods to pull data from
155 * database for the page requested.
157 function getPage ($pagename = false) {
158 if (!isset($this->_dbi))
161 $pagename = $this->getArg('pagename');
162 return $this->_dbi->getPage($pagename);
165 /** Get URL for POST actions.
167 * Officially, we should just use SCRIPT_NAME (or some such),
168 * but that causes problems when we try to issue a redirect, e.g.
169 * after saving a page.
171 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
172 * a redirect from a page to itself.)
174 * So, as a HACK, we include pagename and action as query args in
175 * the URL. (These should be ignored when we receive the POST
178 function getPostURL ($pagename=false) {
179 if ($pagename === false)
180 $pagename = $this->getArg('pagename');
181 $action = $this->getArg('action');
182 return WikiURL($pagename, array('action' => $action));
185 function _handleAuthRequest ($auth_args) {
186 if (!is_array($auth_args))
189 // Ignore password unless POST'ed.
190 if (!$this->isPost())
191 unset($auth_args['passwd']);
193 $user = $this->_user->AuthCheck($auth_args);
195 if (isa($user, 'WikiUser')) {
196 // Successful login (or logout.)
197 $this->_setUser($user);
200 // Login attempt failed.
201 $fail_message = $user;
202 $auth_args['pass_required'] = true;
203 // If no password was submitted, it's not really
204 // a failure --- just need to prompt for password...
205 if (!isset($auth_args['passwd'])) {
206 //$auth_args['pass_required'] = false;
207 $fail_message = false;
209 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
210 $this->finish(); //NORETURN
213 // Login request cancelled.
218 * Attempt to sign in (bogo-login).
222 * @param $userid string Userid to attempt to sign in as.
225 function _signIn ($userid) {
226 $user = $this->_user->AuthCheck(array('userid' => $userid));
227 if (isa($user, 'WikiUser')) {
228 $this->_setUser($user); // success!
232 function _setUser ($user) {
233 $this->_user = $user;
234 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
235 $this->setSessionVar('wiki_user', $user);
236 if ($user->isSignedIn())
237 $user->_authhow = 'signin';
239 // Save userid to prefs..
240 $this->_prefs->set('userid',
241 $user->isSignedIn() ? $user->getId() : '');
244 function _notAuthorized ($require_level) {
245 // User does not have required authority. Prompt for login.
246 $what = $this->getActionDescription($this->getArg('action'));
248 if ($require_level >= WIKIAUTH_FORBIDDEN) {
249 $this->finish(fmt("%s is disallowed on this wiki.",
250 $this->getDisallowedActionDescription($this->getArg('action'))));
252 elseif ($require_level == WIKIAUTH_BOGO)
253 $msg = fmt("You must sign in to %s.", $what);
254 elseif ($require_level == WIKIAUTH_USER)
255 $msg = fmt("You must log in to %s.", $what);
257 $msg = fmt("You must be an administrator to %s.", $what);
258 $pass_required = ($require_level >= WIKIAUTH_USER);
260 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
261 $this->finish(); // NORETURN
264 function getActionDescription($action) {
265 static $actionDescriptions;
266 if (! $actionDescriptions) {
268 = array('browse' => _("browse pages in this wiki"),
269 'diff' => _("diff pages in this wiki"),
270 'dumphtml' => _("dump html pages from this wiki"),
271 'dumpserial' => _("dump serial pages from this wiki"),
272 'edit' => _("edit pages in this wiki"),
273 'loadfile' => _("load files into this wiki"),
274 'lock' => _("lock pages in this wiki"),
275 'remove' => _("remove pages from this wiki"),
276 'unlock' => _("unlock pages in this wiki"),
277 'upload' => _("upload a zip dump to this wiki"),
278 'verify' => _("verify the current action"),
279 'viewsource' => _("view the source of pages in this wiki"),
280 'xmlrpc' => _("access this wiki via XML-RPC"),
281 'zip' => _("download a zip dump from this wiki"),
282 'ziphtml' => _("download an html zip dump from this wiki")
285 if (in_array($action, array_keys($actionDescriptions)))
286 return $actionDescriptions[$action];
290 function getDisallowedActionDescription($action) {
291 static $disallowedActionDescriptions;
292 if (! $disallowedActionDescriptions) {
293 $disallowedActionDescriptions
294 = array('browse' => _("Browsing pages"),
295 'diff' => _("Diffing pages"),
296 'dumphtml' => _("Dumping html pages"),
297 'dumpserial' => _("Dumping serial pages"),
298 'edit' => _("Editing pages"),
299 'loadfile' => _("Loading files"),
300 'lock' => _("Locking pages"),
301 'remove' => _("Removing pages"),
302 'unlock' => _("Unlocking pages"),
303 'upload' => _("Uploading zip dumps"),
304 'verify' => _("Verify the current action"),
305 'viewsource' => _("Viewing the source of pages"),
306 'xmlrpc' => _("XML-RPC access"),
307 'zip' => _("Downloading zip dumps"),
308 'ziphtml' => _("Downloading html zip dumps")
311 if (in_array($action, array_keys($disallowedActionDescriptions)))
312 return $disallowedActionDescriptions[$action];
317 function requiredAuthority ($action) {
318 $auth = $this->requiredAuthorityForAction($action);
321 * This is a hook for plugins to require authority
322 * for posting to them.
324 * IMPORTANT: this is not a secure check, so the plugin
325 * may not assume that any POSTs to it are authorized.
326 * All this does is cause PhpWiki to prompt for login
327 * if the user doesn't have the required authority.
329 if ($this->isPost()) {
330 $post_auth = $this->getArg('require_authority_for_post');
331 if ($post_auth !== false)
332 $auth = max($auth, $post_auth);
337 function requiredAuthorityForAction ($action) {
339 // Todo: Check individual page permissions instead.
346 return WIKIAUTH_ANON;
349 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
350 return WIKIAUTH_ADMIN;
351 return WIKIAUTH_ANON;
354 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
355 return WIKIAUTH_ADMIN;
356 return WIKIAUTH_ANON;
359 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
360 return WIKIAUTH_BOGO;
361 return WIKIAUTH_ANON;
362 // return WIKIAUTH_BOGO;
371 return WIKIAUTH_ADMIN;
373 global $WikiNameRegexp;
374 if (preg_match("/$WikiNameRegexp\Z/A", $action))
375 return WIKIAUTH_ANON; // ActionPage.
377 return WIKIAUTH_ADMIN;
381 function possiblyDeflowerVirginWiki () {
382 if ($this->getArg('action') != 'browse')
384 if ($this->getArg('pagename') != HOME_PAGE)
387 $page = $this->getPage();
388 $current = $page->getCurrentRevision();
389 if ($current->getVersion() > 0)
390 return; // Homepage exists.
392 include('lib/loadsave.php');
394 $this->finish(); // NORETURN
397 function handleAction () {
398 $action = $this->getArg('action');
399 $method = "action_$action";
400 if (method_exists($this, $method)) {
403 elseif ($page = $this->findActionPage($action)) {
404 $this->actionpage($page);
407 $this->finish(fmt("%s: Bad action", $action));
411 function finish ($errormsg = false) {
415 exit(); // just in case CloseDataBase calls us
418 if (!empty($this->_dbi))
419 $this->_dbi->close();
423 global $ErrorManager;
424 $ErrorManager->flushPostponedErrors();
426 if (!empty($errormsg)) {
429 HTML::h2(_("Fatal PhpWiki Error")),
432 echo "\n</body></html>";
439 function _deducePagename () {
440 if ($this->getArg('pagename'))
441 return $this->getArg('pagename');
444 $pathinfo = $this->get('PATH_INFO');
445 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
447 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
451 elseif ($this->isPost()) {
453 * In general, for security reasons, HTTP_GET_VARS should be ignored
454 * on POST requests, but we make an exception here (only for pagename).
456 * The justifcation for this hack is the following
457 * asymmetry: When POSTing with USE_PATH_INFO set, the
458 * pagename can (and should) be communicated through the
459 * request URL via PATH_INFO. When POSTing with
460 * USE_PATH_INFO off, this cannot be done --- the only way
461 * to communicate the pagename through the URL is via
462 * QUERY_ARGS (HTTP_GET_VARS).
464 global $HTTP_GET_VARS;
465 if (isset($HTTP_GET_VARS['pagename'])) {
466 return $HTTP_GET_VARS['pagename'];
471 * Support for PhpWiki 1.2 style requests.
473 $query_string = $this->get('QUERY_STRING');
474 if (preg_match('/^[^&=]+$/', $query_string)) {
475 return urldecode($query_string);
481 function _deduceAction () {
482 if (!($action = $this->getArg('action'))) {
483 // Detect XML-RPC requests
485 && $this->get('CONTENT_TYPE') == 'text/xml') {
486 global $HTTP_RAW_POST_DATA;
487 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
492 return 'browse'; // Default if no action specified.
495 if (method_exists($this, "action_$action"))
498 // Allow for, e.g. action=LikePages
499 if ($this->isActionPage($action))
502 trigger_error("$action: Unknown action", E_USER_NOTICE);
506 function _deduceUsername () {
507 if ($userid = $this->getSessionVar('wiki_user')) {
508 if (!empty($this->_user))
509 $this->_user->_authhow = 'session';
512 if ($userid = $this->getCookieVar('WIKI_ID')) {
513 if (!empty($this->_user))
514 $this->_user->authhow = 'cookie';
520 function _isActionPage ($pagename) {
521 $dbi = $this->getDbh();
522 $page = $dbi->getPage($pagename);
523 $rev = $page->getCurrentRevision();
524 // FIXME: more restrictive check for sane plugin?
525 if (strstr($rev->getPackedContent(), '<?plugin'))
527 if (!$rev->hasDefaultContents())
528 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
532 function findActionPage ($action) {
535 if (isset($cache) and isset($cache[$action]))
536 return $cache[$action];
538 // Allow for, e.g. action=LikePages
539 global $WikiNameRegexp;
540 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
541 return $cache[$action] = false;
543 // check for translated version (users preferred language)
544 $translation = gettext($action);
545 if ($this->_isActionPage($translation))
546 return $cache[$action] = $translation;
548 // check for translated version (default language)
550 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
552 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
553 update_locale(DEFAULT_LANGUAGE);
554 $default = gettext($action);
555 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
556 update_locale($save_lang);
557 if ($this->_isActionPage($default))
558 return $cache[$action] = $default;
561 $default = $translation;
564 // check for english version
565 if ($action != $translation and $action != $default) {
566 if ($this->_isActionPage($action))
567 return $cache[$action] = $action;
570 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
571 return $cache[$action] = false;
574 function isActionPage ($pagename) {
575 return $this->findActionPage($pagename);
578 function action_browse () {
579 $this->buffer_output();
580 include_once("lib/display.php");
584 function action_verify () {
585 $this->action_browse();
588 function actionpage ($action) {
589 $this->buffer_output();
590 include_once("lib/display.php");
591 actionPage($this, $action);
594 function action_diff () {
595 $this->buffer_output();
596 include_once "lib/diff.php";
600 function action_search () {
601 // This is obsolete: reformulate URL and redirect.
602 // FIXME: this whole section should probably be deleted.
603 if ($this->getArg('searchtype') == 'full') {
604 $search_page = _("FullTextSearch");
607 $search_page = _("TitleSearch");
609 $this->redirect(WikiURL($search_page,
610 array('s' => $this->getArg('searchterm')),
614 function action_edit () {
615 $this->buffer_output();
616 include "lib/editpage.php";
617 $e = new PageEditor ($this);
621 function action_viewsource () {
622 $this->buffer_output();
623 include "lib/editpage.php";
624 $e = new PageEditor ($this);
628 function action_lock () {
629 $page = $this->getPage();
630 $page->set('locked', true);
631 $this->action_browse();
634 function action_unlock () {
635 // FIXME: This check is redundant.
636 //$user->requireAuth(WIKIAUTH_ADMIN);
637 $page = $this->getPage();
638 $page->set('locked', false);
639 $this->action_browse();
642 function action_remove () {
643 // FIXME: This check is redundant.
644 //$user->requireAuth(WIKIAUTH_ADMIN);
645 $pagename = $this->getArg('pagename');
646 if (strstr($pagename,_('PhpWikiAdministration'))) {
647 $this->action_browse();
649 include('lib/removepage.php');
655 function action_upload () {
656 include_once("lib/loadsave.php");
660 function action_xmlrpc () {
661 include_once("lib/XmlRpcServer.php");
662 $xmlrpc = new XmlRpcServer($this);
666 function action_zip () {
667 include_once("lib/loadsave.php");
669 // I don't think it hurts to add cruft at the end of the zip file.
670 echo "\n========================================================\n";
671 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
674 function action_ziphtml () {
675 include_once("lib/loadsave.php");
676 MakeWikiZipHtml($this);
677 // I don't think it hurts to add cruft at the end of the zip file.
678 echo "\n========================================================\n";
679 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
682 function action_dumpserial () {
683 include_once("lib/loadsave.php");
687 function action_dumphtml () {
688 include_once("lib/loadsave.php");
689 DumpHtmlToDir($this);
692 function action_loadfile () {
693 include_once("lib/loadsave.php");
694 LoadFileOrDir($this);
699 function is_safe_action ($action) {
700 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
707 $request = new WikiRequest();
710 * Allow for disabling of markup cache.
711 * (Mostly for debugging ... hopefully.)
713 * See also <?plugin WikiAdminUtils action=purge-cache ?>
715 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
716 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
718 // Initialize with system defaults in case user not logged in.
719 // Should this go into constructor?
720 $request->initializeTheme();
722 $request->updateAuthAndPrefs();
723 // initialize again with user's prefs
724 $request->initializeTheme();
725 $request->initializeLang();
727 // Enable the output of most of the warning messages.
728 // The warnings will screw up zip files though.
729 global $ErrorManager;
730 if (substr($request->getArg('action'), 0, 3) != 'zip') {
731 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
732 //$ErrorManager->setPostponedErrorMask(0);
736 //if ($user->is_authenticated())
737 // $LogEntry->user = $user->getId();
739 $request->possiblyDeflowerVirginWiki();
741 if(defined('WIKI_XMLRPC')) return;
743 $validators = array('wikiname' => WIKI_NAME,
744 'args' => hash($request->getArgs()),
745 'prefs' => hash($request->getPrefs()));
746 if (CACHE_CONTROL == 'STRICT') {
747 $dbi = $request->getDbh();
748 $timestamp = $dbi->getTimestamp();
749 $validators['mtime'] = $timestamp;
750 $validators['%mtime'] = (int)$timestamp;
753 $request->setValidators($validators);
755 $request->handleAction();
757 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
769 // c-hanging-comment-ender-p: nil
770 // indent-tabs-mode: nil