2 rcs_id('$Id: main.php,v 1.101 2003-11-25 21:49:44 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->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 // check for translated version, as per users preferred language
536 // (or system default in case it is not en)
537 $translation = gettext($action);
539 if (isset($cache) and isset($cache[$translation]))
540 return $cache[$translation];
542 // check for cached translated version
543 if ($this->_isActionPage($translation))
544 return $cache[$action] = $translation;
546 // Allow for, e.g. action=LikePages
547 global $WikiNameRegexp;
548 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
549 return $cache[$action] = false;
551 // check for translated version (default language)
553 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
555 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
556 update_locale(DEFAULT_LANGUAGE);
557 $default = gettext($action);
558 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
559 update_locale($save_lang);
560 if ($this->_isActionPage($default))
561 return $cache[$action] = $default;
564 $default = $translation;
567 // check for english version
568 if ($action != $translation and $action != $default) {
569 if ($this->_isActionPage($action))
570 return $cache[$action] = $action;
573 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
574 return $cache[$action] = false;
577 function isActionPage ($pagename) {
578 return $this->findActionPage($pagename);
581 function action_browse () {
582 $this->buffer_output();
583 include_once("lib/display.php");
587 function action_verify () {
588 $this->action_browse();
591 function actionpage ($action) {
592 $this->buffer_output();
593 include_once("lib/display.php");
594 actionPage($this, $action);
597 function action_diff () {
598 $this->buffer_output();
599 include_once "lib/diff.php";
603 function action_search () {
604 // This is obsolete: reformulate URL and redirect.
605 // FIXME: this whole section should probably be deleted.
606 if ($this->getArg('searchtype') == 'full') {
607 $search_page = _("FullTextSearch");
610 $search_page = _("TitleSearch");
612 $this->redirect(WikiURL($search_page,
613 array('s' => $this->getArg('searchterm')),
617 function action_edit () {
618 $this->buffer_output();
619 include "lib/editpage.php";
620 $e = new PageEditor ($this);
624 function action_create () {
625 $this->action_edit();
628 function action_viewsource () {
629 $this->buffer_output();
630 include "lib/editpage.php";
631 $e = new PageEditor ($this);
635 function action_lock () {
636 $page = $this->getPage();
637 $page->set('locked', true);
638 $this->action_browse();
641 function action_unlock () {
642 // FIXME: This check is redundant.
643 //$user->requireAuth(WIKIAUTH_ADMIN);
644 $page = $this->getPage();
645 $page->set('locked', false);
646 $this->action_browse();
649 function action_remove () {
650 // FIXME: This check is redundant.
651 //$user->requireAuth(WIKIAUTH_ADMIN);
652 $pagename = $this->getArg('pagename');
653 if (strstr($pagename,_('PhpWikiAdministration'))) {
654 $this->action_browse();
656 include('lib/removepage.php');
662 function action_upload () {
663 include_once("lib/loadsave.php");
667 function action_xmlrpc () {
668 include_once("lib/XmlRpcServer.php");
669 $xmlrpc = new XmlRpcServer($this);
673 function action_zip () {
674 include_once("lib/loadsave.php");
676 // I don't think it hurts to add cruft at the end of the zip file.
677 echo "\n========================================================\n";
678 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
681 function action_ziphtml () {
682 include_once("lib/loadsave.php");
683 MakeWikiZipHtml($this);
684 // I don't think it hurts to add cruft at the end of the zip file.
685 echo "\n========================================================\n";
686 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
689 function action_dumpserial () {
690 include_once("lib/loadsave.php");
694 function action_dumphtml () {
695 include_once("lib/loadsave.php");
696 DumpHtmlToDir($this);
699 function action_loadfile () {
700 include_once("lib/loadsave.php");
701 LoadFileOrDir($this);
706 function is_safe_action ($action) {
707 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
714 $request = new WikiRequest();
717 * Allow for disabling of markup cache.
718 * (Mostly for debugging ... hopefully.)
720 * See also <?plugin WikiAdminUtils action=purge-cache ?>
722 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
723 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
725 // Initialize with system defaults in case user not logged in.
726 // Should this go into constructor?
727 $request->initializeTheme();
729 $request->updateAuthAndPrefs();
730 // initialize again with user's prefs
731 $request->initializeTheme();
732 $request->initializeLang();
734 // Enable the output of most of the warning messages.
735 // The warnings will screw up zip files though.
736 global $ErrorManager;
737 if (substr($request->getArg('action'), 0, 3) != 'zip') {
738 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
739 //$ErrorManager->setPostponedErrorMask(0);
743 //if ($user->is_authenticated())
744 // $LogEntry->user = $user->getId();
746 $request->possiblyDeflowerVirginWiki();
748 if(defined('WIKI_XMLRPC')) return;
750 $validators = array('wikiname' => WIKI_NAME,
751 'args' => hash($request->getArgs()),
752 'prefs' => hash($request->getPrefs()));
753 if (CACHE_CONTROL == 'STRICT') {
754 $dbi = $request->getDbh();
755 $timestamp = $dbi->getTimestamp();
756 $validators['mtime'] = $timestamp;
757 $validators['%mtime'] = (int)$timestamp;
759 // FIXME: we should try to generate strong validators when possible,
760 // but for now, our validator is weak, since equal validators do not
761 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
763 // (If DEBUG if off, this may be a strong validator, but I'm going
764 // to go the paranoid route here pending further study and testing.)
766 $validators['%weak'] = true;
768 $request->setValidators($validators);
770 $request->handleAction();
772 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
780 // $Log: not supported by cvs2svn $
781 // Revision 1.100 2003/11/18 16:54:18 carstenklapp
782 // Reformatting only: Tabs to spaces, added rcs log.
790 // c-hanging-comment-ender-p: nil
791 // indent-tabs-mode: nil