2 rcs_id('$Id: main.php,v 1.97 2003-02-26 03:40:22 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 'create' => _("create pages in this wiki"),
274 'loadfile' => _("load files into this wiki"),
275 'lock' => _("lock pages in this wiki"),
276 'remove' => _("remove pages from this wiki"),
277 'unlock' => _("unlock pages in this wiki"),
278 'upload' => _("upload a zip dump to this wiki"),
279 'verify' => _("verify the current action"),
280 'viewsource' => _("view the source of pages in this wiki"),
281 'xmlrpc' => _("access this wiki via XML-RPC"),
282 'zip' => _("download a zip dump from this wiki"),
283 'ziphtml' => _("download an html zip dump from this wiki")
286 if (in_array($action, array_keys($actionDescriptions)))
287 return $actionDescriptions[$action];
291 function getDisallowedActionDescription($action) {
292 static $disallowedActionDescriptions;
293 if (! $disallowedActionDescriptions) {
294 $disallowedActionDescriptions
295 = array('browse' => _("Browsing pages"),
296 'diff' => _("Diffing pages"),
297 'dumphtml' => _("Dumping html pages"),
298 'dumpserial' => _("Dumping serial pages"),
299 'edit' => _("Editing pages"),
300 'create' => _("Creating pages"),
301 'loadfile' => _("Loading files"),
302 'lock' => _("Locking pages"),
303 'remove' => _("Removing pages"),
304 'unlock' => _("Unlocking pages"),
305 'upload' => _("Uploading zip dumps"),
306 'verify' => _("Verify the current action"),
307 'viewsource' => _("Viewing the source of pages"),
308 'xmlrpc' => _("XML-RPC access"),
309 'zip' => _("Downloading zip dumps"),
310 'ziphtml' => _("Downloading html zip dumps")
313 if (in_array($action, array_keys($disallowedActionDescriptions)))
314 return $disallowedActionDescriptions[$action];
319 function requiredAuthority ($action) {
320 $auth = $this->requiredAuthorityForAction($action);
323 * This is a hook for plugins to require authority
324 * for posting to them.
326 * IMPORTANT: this is not a secure check, so the plugin
327 * may not assume that any POSTs to it are authorized.
328 * All this does is cause PhpWiki to prompt for login
329 * if the user doesn't have the required authority.
331 if ($this->isPost()) {
332 $post_auth = $this->getArg('require_authority_for_post');
333 if ($post_auth !== false)
334 $auth = max($auth, $post_auth);
339 function requiredAuthorityForAction ($action) {
341 // Todo: Check individual page permissions instead.
348 return WIKIAUTH_ANON;
351 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
352 return WIKIAUTH_ADMIN;
353 return WIKIAUTH_ANON;
356 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
357 return WIKIAUTH_ADMIN;
358 return WIKIAUTH_ANON;
361 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
362 return WIKIAUTH_BOGO;
363 return WIKIAUTH_ANON;
364 // return WIKIAUTH_BOGO;
367 $page = $this->getPage();
368 $current = $page->getCurrentRevision();
369 if ($current->hasDefaultContents())
370 return $this->requiredAuthorityForAction('edit');
371 return $this->requiredAuthorityForAction('browse');
380 return WIKIAUTH_ADMIN;
382 global $WikiNameRegexp;
383 if (preg_match("/$WikiNameRegexp\Z/A", $action))
384 return WIKIAUTH_ANON; // ActionPage.
386 return WIKIAUTH_ADMIN;
390 function possiblyDeflowerVirginWiki () {
391 if ($this->getArg('action') != 'browse')
393 if ($this->getArg('pagename') != HOME_PAGE)
396 $page = $this->getPage();
397 $current = $page->getCurrentRevision();
398 if ($current->getVersion() > 0)
399 return; // Homepage exists.
401 include('lib/loadsave.php');
403 $this->finish(); // NORETURN
406 function handleAction () {
407 $action = $this->getArg('action');
408 $method = "action_$action";
409 if (method_exists($this, $method)) {
412 elseif ($page = $this->findActionPage($action)) {
413 $this->actionpage($page);
416 $this->finish(fmt("%s: Bad action", $action));
420 function finish ($errormsg = false) {
424 exit(); // just in case CloseDataBase calls us
427 if (!empty($this->_dbi))
428 $this->_dbi->close();
432 global $ErrorManager;
433 $ErrorManager->flushPostponedErrors();
435 if (!empty($errormsg)) {
438 HTML::h2(_("Fatal PhpWiki Error")),
441 echo "\n</body></html>";
448 function _deducePagename () {
449 if ($this->getArg('pagename'))
450 return $this->getArg('pagename');
453 $pathinfo = $this->get('PATH_INFO');
454 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
456 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
460 elseif ($this->isPost()) {
462 * In general, for security reasons, HTTP_GET_VARS should be ignored
463 * on POST requests, but we make an exception here (only for pagename).
465 * The justifcation for this hack is the following
466 * asymmetry: When POSTing with USE_PATH_INFO set, the
467 * pagename can (and should) be communicated through the
468 * request URL via PATH_INFO. When POSTing with
469 * USE_PATH_INFO off, this cannot be done --- the only way
470 * to communicate the pagename through the URL is via
471 * QUERY_ARGS (HTTP_GET_VARS).
473 global $HTTP_GET_VARS;
474 if (isset($HTTP_GET_VARS['pagename'])) {
475 return $HTTP_GET_VARS['pagename'];
480 * Support for PhpWiki 1.2 style requests.
482 $query_string = $this->get('QUERY_STRING');
483 if (preg_match('/^[^&=]+$/', $query_string)) {
484 return urldecode($query_string);
490 function _deduceAction () {
491 if (!($action = $this->getArg('action'))) {
492 // Detect XML-RPC requests
494 && $this->get('CONTENT_TYPE') == 'text/xml') {
495 global $HTTP_RAW_POST_DATA;
496 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
501 return 'browse'; // Default if no action specified.
504 if (method_exists($this, "action_$action"))
507 // Allow for, e.g. action=LikePages
508 if ($this->isActionPage($action))
511 trigger_error("$action: Unknown action", E_USER_NOTICE);
515 function _deduceUsername () {
516 if ($userid = $this->getSessionVar('wiki_user')) {
517 if (!empty($this->_user))
518 $this->_user->_authhow = 'session';
521 if ($userid = $this->getCookieVar('WIKI_ID')) {
522 if (!empty($this->_user))
523 $this->_user->authhow = 'cookie';
529 function _isActionPage ($pagename) {
530 $dbi = $this->getDbh();
531 $page = $dbi->getPage($pagename);
532 $rev = $page->getCurrentRevision();
533 // FIXME: more restrictive check for sane plugin?
534 if (strstr($rev->getPackedContent(), '<?plugin'))
536 if (!$rev->hasDefaultContents())
537 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
541 function findActionPage ($action) {
544 if (isset($cache) and isset($cache[$action]))
545 return $cache[$action];
547 // Allow for, e.g. action=LikePages
548 global $WikiNameRegexp;
549 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
550 return $cache[$action] = false;
552 // check for translated version (users preferred language)
553 $translation = gettext($action);
554 if ($this->_isActionPage($translation))
555 return $cache[$action] = $translation;
557 // check for translated version (default language)
559 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
561 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
562 update_locale(DEFAULT_LANGUAGE);
563 $default = gettext($action);
564 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
565 update_locale($save_lang);
566 if ($this->_isActionPage($default))
567 return $cache[$action] = $default;
570 $default = $translation;
573 // check for english version
574 if ($action != $translation and $action != $default) {
575 if ($this->_isActionPage($action))
576 return $cache[$action] = $action;
579 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
580 return $cache[$action] = false;
583 function isActionPage ($pagename) {
584 return $this->findActionPage($pagename);
587 function action_browse () {
588 $this->buffer_output();
589 include_once("lib/display.php");
593 function action_verify () {
594 $this->action_browse();
597 function actionpage ($action) {
598 $this->buffer_output();
599 include_once("lib/display.php");
600 actionPage($this, $action);
603 function action_diff () {
604 $this->buffer_output();
605 include_once "lib/diff.php";
609 function action_search () {
610 // This is obsolete: reformulate URL and redirect.
611 // FIXME: this whole section should probably be deleted.
612 if ($this->getArg('searchtype') == 'full') {
613 $search_page = _("FullTextSearch");
616 $search_page = _("TitleSearch");
618 $this->redirect(WikiURL($search_page,
619 array('s' => $this->getArg('searchterm')),
623 function action_edit () {
624 $this->buffer_output();
625 include "lib/editpage.php";
626 $e = new PageEditor ($this);
630 function action_create () {
631 $this->action_edit();
634 function action_viewsource () {
635 $this->buffer_output();
636 include "lib/editpage.php";
637 $e = new PageEditor ($this);
641 function action_lock () {
642 $page = $this->getPage();
643 $page->set('locked', true);
644 $this->action_browse();
647 function action_unlock () {
648 // FIXME: This check is redundant.
649 //$user->requireAuth(WIKIAUTH_ADMIN);
650 $page = $this->getPage();
651 $page->set('locked', false);
652 $this->action_browse();
655 function action_remove () {
656 // FIXME: This check is redundant.
657 //$user->requireAuth(WIKIAUTH_ADMIN);
658 $pagename = $this->getArg('pagename');
659 if (strstr($pagename,_('PhpWikiAdministration'))) {
660 $this->action_browse();
662 include('lib/removepage.php');
668 function action_upload () {
669 include_once("lib/loadsave.php");
673 function action_xmlrpc () {
674 include_once("lib/XmlRpcServer.php");
675 $xmlrpc = new XmlRpcServer($this);
679 function action_zip () {
680 include_once("lib/loadsave.php");
682 // I don't think it hurts to add cruft at the end of the zip file.
683 echo "\n========================================================\n";
684 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
687 function action_ziphtml () {
688 include_once("lib/loadsave.php");
689 MakeWikiZipHtml($this);
690 // I don't think it hurts to add cruft at the end of the zip file.
691 echo "\n========================================================\n";
692 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
695 function action_dumpserial () {
696 include_once("lib/loadsave.php");
700 function action_dumphtml () {
701 include_once("lib/loadsave.php");
702 DumpHtmlToDir($this);
705 function action_loadfile () {
706 include_once("lib/loadsave.php");
707 LoadFileOrDir($this);
712 function is_safe_action ($action) {
713 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
720 $request = new WikiRequest();
723 * Allow for disabling of markup cache.
724 * (Mostly for debugging ... hopefully.)
726 * See also <?plugin WikiAdminUtils action=purge-cache ?>
728 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
729 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
731 // Initialize with system defaults in case user not logged in.
732 // Should this go into constructor?
733 $request->initializeTheme();
735 $request->updateAuthAndPrefs();
736 // initialize again with user's prefs
737 $request->initializeTheme();
738 $request->initializeLang();
740 // Enable the output of most of the warning messages.
741 // The warnings will screw up zip files though.
742 global $ErrorManager;
743 if (substr($request->getArg('action'), 0, 3) != 'zip') {
744 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
745 //$ErrorManager->setPostponedErrorMask(0);
749 //if ($user->is_authenticated())
750 // $LogEntry->user = $user->getId();
752 $request->possiblyDeflowerVirginWiki();
754 if(defined('WIKI_XMLRPC')) return;
756 $validators = array('wikiname' => WIKI_NAME,
757 'args' => hash($request->getArgs()),
758 'prefs' => hash($request->getPrefs()));
759 if (CACHE_CONTROL == 'STRICT') {
760 $dbi = $request->getDbh();
761 $timestamp = $dbi->getTimestamp();
762 $validators['mtime'] = $timestamp;
763 $validators['%mtime'] = (int)$timestamp;
766 $request->setValidators($validators);
768 $request->handleAction();
770 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
782 // c-hanging-comment-ender-p: nil
783 // indent-tabs-mode: nil