2 rcs_id('$Id: main.php,v 1.91 2003-02-15 02:21:54 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 function _handleAuthRequest ($auth_args) {
166 if (!is_array($auth_args))
169 // Ignore password unless POST'ed.
170 if (!$this->isPost())
171 unset($auth_args['passwd']);
173 $user = $this->_user->AuthCheck($auth_args);
175 if (isa($user, 'WikiUser')) {
176 // Successful login (or logout.)
177 $this->_setUser($user);
180 // Login attempt failed.
181 $fail_message = $user;
182 $auth_args['pass_required'] = true;
183 // If no password was submitted, it's not really
184 // a failure --- just need to prompt for password...
185 if (!isset($auth_args['passwd'])) {
186 //$auth_args['pass_required'] = false;
187 $fail_message = false;
189 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
190 $this->finish(); //NORETURN
193 // Login request cancelled.
198 * Attempt to sign in (bogo-login).
202 * @param $userid string Userid to attempt to sign in as.
205 function _signIn ($userid) {
206 $user = $this->_user->AuthCheck(array('userid' => $userid));
207 if (isa($user, 'WikiUser')) {
208 $this->_setUser($user); // success!
212 function _setUser ($user) {
213 $this->_user = $user;
214 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
215 $this->setSessionVar('wiki_user', $user);
216 if ($user->isSignedIn())
217 $user->_authhow = 'signin';
219 // Save userid to prefs..
220 $this->_prefs->set('userid',
221 $user->isSignedIn() ? $user->getId() : '');
224 function _notAuthorized ($require_level) {
225 // User does not have required authority. Prompt for login.
226 $what = $this->getActionDescription($this->getArg('action'));
228 if ($require_level >= WIKIAUTH_FORBIDDEN) {
229 $this->finish(fmt("%s is disallowed on this wiki.",
230 $this->getDisallowedActionDescription($this->getArg('action'))));
232 elseif ($require_level == WIKIAUTH_BOGO)
233 $msg = fmt("You must sign in to %s.", $what);
234 elseif ($require_level == WIKIAUTH_USER)
235 $msg = fmt("You must log in to %s.", $what);
237 $msg = fmt("You must be an administrator to %s.", $what);
238 $pass_required = ($require_level >= WIKIAUTH_USER);
240 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
241 $this->finish(); // NORETURN
244 function getActionDescription($action) {
245 static $actionDescriptions;
246 if (! $actionDescriptions) {
248 = array('browse' => _("browse pages in this wiki"),
249 'diff' => _("diff pages in this wiki"),
250 'dumphtml' => _("dump html pages from this wiki"),
251 'dumpserial' => _("dump serial pages from this wiki"),
252 'edit' => _("edit pages in this wiki"),
253 'loadfile' => _("load files into this wiki"),
254 'lock' => _("lock pages in this wiki"),
255 'remove' => _("remove pages from this wiki"),
256 'unlock' => _("unlock pages in this wiki"),
257 'upload' => _("upload a zip dump to this wiki"),
258 'verify' => _("verify the current action"),
259 'viewsource' => _("view the source of pages in this wiki"),
260 'xmlrpc' => _("access this wiki via XML-RPC"),
261 'zip' => _("download a zip dump from this wiki"),
262 'ziphtml' => _("download an html zip dump from this wiki")
265 if (in_array($action, array_keys($actionDescriptions)))
266 return $actionDescriptions[$action];
270 function getDisallowedActionDescription($action) {
271 static $disallowedActionDescriptions;
272 if (! $disallowedActionDescriptions) {
273 $disallowedActionDescriptions
274 = array('browse' => _("Browsing pages"),
275 'diff' => _("Diffing pages"),
276 'dumphtml' => _("Dumping html pages"),
277 'dumpserial' => _("Dumping serial pages"),
278 'edit' => _("Editing pages"),
279 'loadfile' => _("Loading files"),
280 'lock' => _("Locking pages"),
281 'remove' => _("Removing pages"),
282 'unlock' => _("Unlocking pages"),
283 'upload' => _("Uploading zip dumps"),
284 'verify' => _("Verify the current action"),
285 'viewsource' => _("Viewing the source of pages"),
286 'xmlrpc' => _("XML-RPC access"),
287 'zip' => _("Downloading zip dumps"),
288 'ziphtml' => _("Downloading html zip dumps")
291 if (in_array($action, array_keys($disallowedActionDescriptions)))
292 return $disallowedActionDescriptions[$action];
297 function requiredAuthority ($action) {
299 // Todo: Check individual page permissions instead.
306 return WIKIAUTH_ANON;
309 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
310 return WIKIAUTH_ADMIN;
311 return WIKIAUTH_ANON;
314 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
315 return WIKIAUTH_ADMIN;
316 return WIKIAUTH_ANON;
319 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
320 return WIKIAUTH_BOGO;
321 return WIKIAUTH_ANON;
322 // return WIKIAUTH_BOGO;
331 return WIKIAUTH_ADMIN;
333 global $WikiNameRegexp;
334 if (preg_match("/$WikiNameRegexp\Z/A", $action))
335 return WIKIAUTH_ANON; // ActionPage.
337 return WIKIAUTH_ADMIN;
341 function possiblyDeflowerVirginWiki () {
342 if ($this->getArg('action') != 'browse')
344 if ($this->getArg('pagename') != HOME_PAGE)
347 $page = $this->getPage();
348 $current = $page->getCurrentRevision();
349 if ($current->getVersion() > 0)
350 return; // Homepage exists.
352 include('lib/loadsave.php');
354 $this->finish(); // NORETURN
357 function handleAction () {
358 $action = $this->getArg('action');
359 $method = "action_$action";
360 if (method_exists($this, $method)) {
363 elseif ($page = $this->findActionPage($action)) {
364 $this->actionpage($page);
367 $this->finish(fmt("%s: Bad action", $action));
372 function finish ($errormsg = false) {
376 exit(); // just in case CloseDataBase calls us
379 if (!empty($this->_dbi))
380 $this->_dbi->close();
384 global $ErrorManager;
385 $ErrorManager->flushPostponedErrors();
387 if (!empty($errormsg)) {
390 HTML::h2(_("Fatal PhpWiki Error")),
393 echo "\n</body></html>";
400 function _deducePagename () {
401 if ($this->getArg('pagename'))
402 return $this->getArg('pagename');
405 $pathinfo = $this->get('PATH_INFO');
406 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
408 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
412 elseif ($this->isPost()) {
414 * In general, for security reasons, HTTP_GET_VARS should be ignored
415 * on POST requests, but we make an exception here (only for pagename).
417 * The justifcation for this hack is the following
418 * asymmetry: When POSTing with USE_PATH_INFO set, the
419 * pagename can (and should) be communicated through the
420 * request URL via PATH_INFO. When POSTing with
421 * USE_PATH_INFO off, this cannot be done --- the only way
422 * to communicate the pagename through the URL is via
423 * QUERY_ARGS (HTTP_GET_VARS).
425 global $HTTP_GET_VARS;
426 if (isset($HTTP_GET_VARS['pagename'])) {
427 return $HTTP_GET_VARS['pagename'];
432 * Support for PhpWiki 1.2 style requests.
434 $query_string = $this->get('QUERY_STRING');
435 if (preg_match('/^[^&=]+$/', $query_string)) {
436 return urldecode($query_string);
442 function _deduceAction () {
443 if (!($action = $this->getArg('action'))) {
444 // Detect XML-RPC requests
446 && $this->get('CONTENT_TYPE') == 'text/xml') {
447 global $HTTP_RAW_POST_DATA;
448 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
453 return 'browse'; // Default if no action specified.
456 if (method_exists($this, "action_$action"))
459 // Allow for, e.g. action=LikePages
460 if ($this->isActionPage($action))
463 // Check for _('PhpWikiAdministration').'/'._('Remove') actions
464 $pagename = $this->getArg('pagename');
465 if (strstr($pagename,_('PhpWikiAdministration')))
468 trigger_error("$action: Unknown action", E_USER_NOTICE);
472 function _deduceUsername () {
473 if ($userid = $this->getSessionVar('wiki_user')) {
474 if (!empty($this->_user))
475 $this->_user->_authhow = 'session';
478 if ($userid = $this->getCookieVar('WIKI_ID')) {
479 if (!empty($this->_user))
480 $this->_user->authhow = 'cookie';
486 function _isActionPage ($pagename) {
487 $dbi = $this->getDbh();
488 $page = $dbi->getPage($pagename);
489 $rev = $page->getCurrentRevision();
490 // FIXME: more restrictive check for sane plugin?
491 if (strstr($rev->getPackedContent(), '<?plugin'))
493 if (!$rev->hasDefaultContents())
494 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
498 function findActionPage ($action) {
501 if (isset($cache) and isset($cache[$action]))
502 return $cache[$action];
504 // Allow for, e.g. action=LikePages
505 global $WikiNameRegexp;
506 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
507 return $cache[$action] = false;
509 // check for translated version (users preferred language)
510 $translation = gettext($action);
511 if ($this->_isActionPage($translation))
512 return $cache[$action] = $translation;
514 // check for translated version (default language)
516 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
518 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
519 update_locale(DEFAULT_LANGUAGE);
520 $default = gettext($action);
521 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
522 update_locale($save_lang);
523 if ($this->_isActionPage($default))
524 return $cache[$action] = $default;
527 $default = $translation;
530 // check for english version
531 if ($action != $translation and $action != $default) {
532 if ($this->_isActionPage($action))
533 return $cache[$action] = $action;
536 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
537 return $cache[$action] = false;
540 function isActionPage ($pagename) {
541 return $this->findActionPage($pagename);
544 function action_browse () {
545 $this->compress_output();
546 include_once("lib/display.php");
550 function action_verify () {
551 $this->action_browse();
554 function actionpage ($action) {
555 $this->compress_output();
556 include_once("lib/display.php");
557 actionPage($this, $action);
560 function action_diff () {
561 $this->compress_output();
562 include_once "lib/diff.php";
566 function action_search () {
567 // This is obsolete: reformulate URL and redirect.
568 // FIXME: this whole section should probably be deleted.
569 if ($this->getArg('searchtype') == 'full') {
570 $search_page = _("FullTextSearch");
573 $search_page = _("TitleSearch");
575 $this->redirect(WikiURL($search_page,
576 array('s' => $this->getArg('searchterm')),
580 function action_edit () {
581 $this->compress_output();
582 include "lib/editpage.php";
583 $e = new PageEditor ($this);
587 function action_viewsource () {
588 $this->compress_output();
589 include "lib/editpage.php";
590 $e = new PageEditor ($this);
594 function action_lock () {
595 $page = $this->getPage();
596 $page->set('locked', true);
597 $this->action_browse();
600 function action_unlock () {
601 // FIXME: This check is redundant.
602 //$user->requireAuth(WIKIAUTH_ADMIN);
603 $page = $this->getPage();
604 $page->set('locked', false);
605 $this->action_browse();
608 function action_remove () {
609 // FIXME: This check is redundant.
610 //$user->requireAuth(WIKIAUTH_ADMIN);
611 $pagename = $this->getArg('pagename');
612 if (strstr($pagename,_('PhpWikiAdministration'))) {
613 $this->action_browse();
615 include('lib/removepage.php');
621 function action_upload () {
622 include_once("lib/loadsave.php");
626 function action_xmlrpc () {
627 include_once("lib/XmlRpcServer.php");
628 $xmlrpc = new XmlRpcServer($this);
632 function action_zip () {
633 include_once("lib/loadsave.php");
635 // I don't think it hurts to add cruft at the end of the zip file.
636 echo "\n========================================================\n";
637 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
640 function action_ziphtml () {
641 include_once("lib/loadsave.php");
642 MakeWikiZipHtml($this);
643 // I don't think it hurts to add cruft at the end of the zip file.
644 echo "\n========================================================\n";
645 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
648 function action_dumpserial () {
649 include_once("lib/loadsave.php");
653 function action_dumphtml () {
654 include_once("lib/loadsave.php");
655 DumpHtmlToDir($this);
658 function action_loadfile () {
659 include_once("lib/loadsave.php");
660 LoadFileOrDir($this);
665 function is_safe_action ($action) {
666 return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
673 $request = new WikiRequest();
674 // Initialize with system defaults in case user not logged in.
675 // Should this go into constructor?
676 $request->initializeTheme();
678 $request->updateAuthAndPrefs();
679 // initialize again with user's prefs
680 $request->initializeTheme();
681 $request->initializeLang();
683 /* FIXME: is this needed anymore?
684 if (USE_PATH_INFO && ! $request->get('PATH_INFO')
685 && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
686 $request->redirect(SERVER_URL
687 . preg_replace('/(\?|$)/', '/\1',
688 $request->get('REQUEST_URI'),
694 // Enable the output of most of the warning messages.
695 // The warnings will screw up zip files though.
696 global $ErrorManager;
697 if (substr($request->getArg('action'), 0, 3) != 'zip') {
698 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
699 //$ErrorManager->setPostponedErrorMask(0);
703 //if ($user->is_authenticated())
704 // $LogEntry->user = $user->getId();
706 $request->possiblyDeflowerVirginWiki();
707 if(defined('WIKI_XMLRPC')) return;
708 $request->handleAction();
709 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
713 // Used for debugging purposes
714 function getmicrotime(){
715 list($usec, $sec) = explode(" ", microtime());
716 return ((float)$usec + (float)$sec);
718 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
727 // c-hanging-comment-ender-p: nil
728 // indent-tabs-mode: nil