2 rcs_id('$Id: main.php,v 1.99 2003-03-07 02:39:47 dairiki 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->set('userid',
235 $user->isSignedIn() ? $user->getId() : '');
238 function _notAuthorized ($require_level) {
239 // User does not have required authority. Prompt for login.
240 $what = $this->getActionDescription($this->getArg('action'));
242 if ($require_level >= WIKIAUTH_FORBIDDEN) {
243 $this->finish(fmt("%s is disallowed on this wiki.",
244 $this->getDisallowedActionDescription($this->getArg('action'))));
246 elseif ($require_level == WIKIAUTH_BOGO)
247 $msg = fmt("You must sign in to %s.", $what);
248 elseif ($require_level == WIKIAUTH_USER)
249 $msg = fmt("You must log in to %s.", $what);
251 $msg = fmt("You must be an administrator to %s.", $what);
252 $pass_required = ($require_level >= WIKIAUTH_USER);
254 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
255 $this->finish(); // NORETURN
258 function getActionDescription($action) {
259 static $actionDescriptions;
260 if (! $actionDescriptions) {
262 = array('browse' => _("browse pages in this wiki"),
263 'diff' => _("diff pages in this wiki"),
264 'dumphtml' => _("dump html pages from this wiki"),
265 'dumpserial' => _("dump serial pages from this wiki"),
266 'edit' => _("edit pages in this wiki"),
267 'create' => _("create pages in this wiki"),
268 'loadfile' => _("load files into this wiki"),
269 'lock' => _("lock pages in this wiki"),
270 'remove' => _("remove pages from this wiki"),
271 'unlock' => _("unlock pages in this wiki"),
272 'upload' => _("upload a zip dump to this wiki"),
273 'verify' => _("verify the current action"),
274 'viewsource' => _("view the source of pages in this wiki"),
275 'xmlrpc' => _("access this wiki via XML-RPC"),
276 'zip' => _("download a zip dump from this wiki"),
277 'ziphtml' => _("download an html zip dump from this wiki")
280 if (in_array($action, array_keys($actionDescriptions)))
281 return $actionDescriptions[$action];
285 function getDisallowedActionDescription($action) {
286 static $disallowedActionDescriptions;
287 if (! $disallowedActionDescriptions) {
288 $disallowedActionDescriptions
289 = array('browse' => _("Browsing pages"),
290 'diff' => _("Diffing pages"),
291 'dumphtml' => _("Dumping html pages"),
292 'dumpserial' => _("Dumping serial pages"),
293 'edit' => _("Editing pages"),
294 'create' => _("Creating pages"),
295 'loadfile' => _("Loading files"),
296 'lock' => _("Locking pages"),
297 'remove' => _("Removing pages"),
298 'unlock' => _("Unlocking pages"),
299 'upload' => _("Uploading zip dumps"),
300 'verify' => _("Verify the current action"),
301 'viewsource' => _("Viewing the source of pages"),
302 'xmlrpc' => _("XML-RPC access"),
303 'zip' => _("Downloading zip dumps"),
304 'ziphtml' => _("Downloading html zip dumps")
307 if (in_array($action, array_keys($disallowedActionDescriptions)))
308 return $disallowedActionDescriptions[$action];
313 function requiredAuthority ($action) {
314 $auth = $this->requiredAuthorityForAction($action);
317 * This is a hook for plugins to require authority
318 * for posting to them.
320 * IMPORTANT: this is not a secure check, so the plugin
321 * may not assume that any POSTs to it are authorized.
322 * All this does is cause PhpWiki to prompt for login
323 * if the user doesn't have the required authority.
325 if ($this->isPost()) {
326 $post_auth = $this->getArg('require_authority_for_post');
327 if ($post_auth !== false)
328 $auth = max($auth, $post_auth);
333 function requiredAuthorityForAction ($action) {
335 // Todo: Check individual page permissions instead.
343 return WIKIAUTH_ANON;
347 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
348 return WIKIAUTH_ADMIN;
349 return WIKIAUTH_ANON;
352 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
353 return WIKIAUTH_BOGO;
354 return WIKIAUTH_ANON;
355 // return WIKIAUTH_BOGO;
358 $page = $this->getPage();
359 $current = $page->getCurrentRevision();
360 if ($current->hasDefaultContents())
361 return $this->requiredAuthorityForAction('edit');
362 return $this->requiredAuthorityForAction('browse');
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_create () {
622 $this->action_edit();
625 function action_viewsource () {
626 $this->buffer_output();
627 include "lib/editpage.php";
628 $e = new PageEditor ($this);
632 function action_lock () {
633 $page = $this->getPage();
634 $page->set('locked', true);
635 $this->action_browse();
638 function action_unlock () {
639 // FIXME: This check is redundant.
640 //$user->requireAuth(WIKIAUTH_ADMIN);
641 $page = $this->getPage();
642 $page->set('locked', false);
643 $this->action_browse();
646 function action_remove () {
647 // FIXME: This check is redundant.
648 //$user->requireAuth(WIKIAUTH_ADMIN);
649 $pagename = $this->getArg('pagename');
650 if (strstr($pagename,_('PhpWikiAdministration'))) {
651 $this->action_browse();
653 include('lib/removepage.php');
659 function action_upload () {
660 include_once("lib/loadsave.php");
664 function action_xmlrpc () {
665 include_once("lib/XmlRpcServer.php");
666 $xmlrpc = new XmlRpcServer($this);
670 function action_zip () {
671 include_once("lib/loadsave.php");
673 // I don't think it hurts to add cruft at the end of the zip file.
674 echo "\n========================================================\n";
675 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
678 function action_ziphtml () {
679 include_once("lib/loadsave.php");
680 MakeWikiZipHtml($this);
681 // I don't think it hurts to add cruft at the end of the zip file.
682 echo "\n========================================================\n";
683 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
686 function action_dumpserial () {
687 include_once("lib/loadsave.php");
691 function action_dumphtml () {
692 include_once("lib/loadsave.php");
693 DumpHtmlToDir($this);
696 function action_loadfile () {
697 include_once("lib/loadsave.php");
698 LoadFileOrDir($this);
703 function is_safe_action ($action) {
704 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
711 $request = new WikiRequest();
714 * Allow for disabling of markup cache.
715 * (Mostly for debugging ... hopefully.)
717 * See also <?plugin WikiAdminUtils action=purge-cache ?>
719 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
720 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
722 // Initialize with system defaults in case user not logged in.
723 // Should this go into constructor?
724 $request->initializeTheme();
726 $request->updateAuthAndPrefs();
727 // initialize again with user's prefs
728 $request->initializeTheme();
729 $request->initializeLang();
731 // Enable the output of most of the warning messages.
732 // The warnings will screw up zip files though.
733 global $ErrorManager;
734 if (substr($request->getArg('action'), 0, 3) != 'zip') {
735 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
736 //$ErrorManager->setPostponedErrorMask(0);
740 //if ($user->is_authenticated())
741 // $LogEntry->user = $user->getId();
743 $request->possiblyDeflowerVirginWiki();
745 if(defined('WIKI_XMLRPC')) return;
747 $validators = array('wikiname' => WIKI_NAME,
748 'args' => hash($request->getArgs()),
749 'prefs' => hash($request->getPrefs()));
750 if (CACHE_CONTROL == 'STRICT') {
751 $dbi = $request->getDbh();
752 $timestamp = $dbi->getTimestamp();
753 $validators['mtime'] = $timestamp;
754 $validators['%mtime'] = (int)$timestamp;
756 // FIXME: we should try to generate strong validators when possible,
757 // but for now, our validator is weak, since equal validators do not
758 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
760 // (If DEBUG if off, this may be a strong validator, but I'm going
761 // to go the paranoid route here pending further study and testing.)
763 $validators['%weak'] = true;
765 $request->setValidators($validators);
767 $request->handleAction();
769 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
781 // c-hanging-comment-ender-p: nil
782 // indent-tabs-mode: nil