2 rcs_id('$Id: main.php,v 1.84 2002-09-18 19:29:43 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 require_once('lib/DB_Session.php');
16 class WikiRequest extends Request {
19 function WikiRequest () {
22 $this->_dbi = $this->getDbh();
23 new DB_Session($this->_dbi->_backend->_dbh, $GLOBALS['DBParams']['db_session_table']);
24 $this->session = new Request_SessionVars;
28 $this->setArg('pagename', $this->_deducePagename());
29 $this->setArg('action', $this->_deduceAction());
32 $this->_user = new WikiUser($this->_deduceUsername());
33 // $this->_user = new WikiDB_User($this->_user->getId(), $this->getAuthDbh());
34 $this->_prefs = $this->_user->getPreferences();
37 // This really maybe should be part of the constructor, but since it
38 // may involve HTML/template output, the global $request really needs
39 // to be initialized before we do this stuff.
40 function updateAuthAndPrefs () {
42 // Handle preference updates, an authentication requests, if any.
43 if ($new_prefs = $this->getArg('pref')) {
44 $this->setArg('pref', false);
45 if ($this->isPost() and !empty($new_prefs['passwd']) and
46 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
47 $this->_prefs->set('passwd','');
48 // $this->_prefs->set('passwd2',''); // This is not stored anyway
49 include_once("themes/" . THEME . "/themeinfo.php");
52 foreach ($new_prefs as $key => $val) {
53 if ($key == 'passwd') {
54 $val = crypt('passwd');
56 $this->_prefs->set($key, $val);
60 // Handle authentication request, if any.
61 if ($auth_args = $this->getArg('auth')) {
62 $this->setArg('auth', false);
63 include_once("themes/" . THEME . "/themeinfo.php");
64 $this->_handleAuthRequest($auth_args); // possible NORETURN
66 elseif ( ! $this->_user->isSignedIn() ) {
67 // If not auth request, try to sign in as saved user.
68 if (($saved_user = $this->getPref('userid')) != false) {
69 include_once("themes/" . THEME . "/themeinfo.php");
70 $this->_signIn($saved_user);
74 // Save preferences in session and cookie
76 $this->_user->setPreferences($this->_prefs, $id_only);
78 if ($theme = $this->getPref('theme') ) {
79 // Load user-defined theme
80 include_once("themes/$theme/themeinfo.php");
83 include_once("themes/" . THEME . "/themeinfo.php");
87 include_once("themes/" . THEME . "/themeinfo.php");
90 include_once("themes/default/themeinfo.php");
92 assert(!empty($Theme));
94 // Ensure user has permissions for action
95 $require_level = $this->requiredAuthority($this->getArg('action'));
96 if (! $this->_user->hasAuthority($require_level))
97 $this->_notAuthorized($require_level); // NORETURN
100 function getUser () {
104 function getPrefs () {
105 return $this->_prefs;
108 // Convenience function:
109 function getPref ($key) {
110 return $this->_prefs->get($key);
114 if (!isset($this->_dbi)) {
115 // needs PHP 4.1. better use $this->_user->...
116 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
121 function getAuthDbh () {
122 global $DBParams, $DBAuthParams;
123 if (!isset($this->_auth_dbi)) {
124 if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
125 $this->_auth_dbi = $this->getDbh(); // use phpwiki database
126 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
127 $this->_auth_dbi = $this->getDbh(); // same phpwiki database
128 else // use external database
129 // needs PHP 4.1. better use $this->_user->...
130 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
132 return $this->_auth_dbi;
136 * Get requested page from the page database.
138 * This is a convenience function.
140 function getPage () {
141 if (!isset($this->_dbi))
143 return $this->_dbi->getPage($this->getArg('pagename'));
146 function _handleAuthRequest ($auth_args) {
147 if (!is_array($auth_args))
150 // Ignore password unless POST'ed.
151 if (!$this->isPost())
152 unset($auth_args['passwd']);
154 $user = $this->_user->AuthCheck($auth_args);
156 if (isa($user, 'WikiUser')) {
157 // Successful login (or logout.)
158 $this->_setUser($user);
161 // Login attempt failed.
162 $fail_message = $user;
163 $auth_args['pass_required'] = true;
164 // If no password was submitted, it's not really
165 // a failure --- just need to prompt for password...
166 if (!isset($auth_args['passwd'])) {
167 //$auth_args['pass_required'] = false;
168 $fail_message = false;
170 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
171 $this->finish(); //NORETURN
174 // Login request cancelled.
179 * Attempt to sign in (bogo-login).
183 * @param $userid string Userid to attempt to sign in as.
186 function _signIn ($userid) {
187 $user = $this->_user->AuthCheck(array('userid' => $userid));
188 if (isa($user, 'WikiUser')) {
189 $this->_setUser($user); // success!
193 function _setUser ($user) {
194 $this->_user = $user;
195 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
196 $this->setSessionVar('wiki_user', $user);
197 if ($user->isSignedIn())
198 $user->_authhow = 'signin';
200 // Save userid to prefs..
201 $this->_prefs->set('userid',
202 $user->isSignedIn() ? $user->getId() : '');
205 function _notAuthorized ($require_level) {
206 // User does not have required authority. Prompt for login.
207 $what = $this->getActionDescription($this->getArg('action'));
209 if ($require_level >= WIKIAUTH_FORBIDDEN) {
210 $this->finish(fmt("%s is disallowed on this wiki.",
211 $this->getDisallowedActionDescription($this->getArg('action'))));
213 elseif ($require_level == WIKIAUTH_BOGO)
214 $msg = fmt("You must sign in to %s.", $what);
215 elseif ($require_level == WIKIAUTH_USER)
216 $msg = fmt("You must log in to %s.", $what);
218 $msg = fmt("You must be an administrator to %s.", $what);
219 $pass_required = ($require_level >= WIKIAUTH_USER);
221 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
222 $this->finish(); // NORETURN
225 function getActionDescription($action) {
226 static $actionDescriptions;
227 if (! $actionDescriptions) {
229 = array('browse' => _("browse pages in this wiki"),
230 'diff' => _("diff pages in this wiki"),
231 'dumphtml' => _("dump html pages from this wiki"),
232 'dumpserial' => _("dump serial pages from this wiki"),
233 'edit' => _("edit pages in this wiki"),
234 'loadfile' => _("load files into this wiki"),
235 'lock' => _("lock pages in this wiki"),
236 'remove' => _("remove pages from this wiki"),
237 'unlock' => _("unlock pages in this wiki"),
238 'upload' => _("upload a zip dump to this wiki"),
239 'verify' => _("verify the current action"),
240 'viewsource' => _("view the source of pages in this wiki"),
241 'xmlrpc' => _("access this wiki via XML-RPC"),
242 'zip' => _("download a zip dump from this wiki"),
243 'ziphtml' => _("download an html zip dump from this wiki")
246 if (in_array($action, array_keys($actionDescriptions)))
247 return $actionDescriptions[$action];
251 function getDisallowedActionDescription($action) {
252 static $disallowedActionDescriptions;
253 if (! $disallowedActionDescriptions) {
254 $disallowedActionDescriptions
255 = array('browse' => _("Browsing pages"),
256 'diff' => _("Diffing pages"),
257 'dumphtml' => _("Dumping html pages"),
258 'dumpserial' => _("Dumping serial pages"),
259 'edit' => _("Editing pages"),
260 'loadfile' => _("Loading files"),
261 'lock' => _("Locking pages"),
262 'remove' => _("Removing pages"),
263 'unlock' => _("Unlocking pages"),
264 'upload' => _("Uploading zip dumps"),
265 'verify' => _("Verify the current action"),
266 'viewsource' => _("Viewing the source of pages"),
267 'xmlrpc' => _("XML-RPC access"),
268 'zip' => _("Downloading zip dumps"),
269 'ziphtml' => _("Downloading html zip dumps")
272 if (in_array($action, array_keys($disallowedActionDescriptions)))
273 return $disallowedActionDescriptions[$action];
278 function requiredAuthority ($action) {
280 // Todo: Check individual page permissions instead.
287 return WIKIAUTH_ANON;
290 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
291 return WIKIAUTH_ADMIN;
292 return WIKIAUTH_ANON;
295 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
296 return WIKIAUTH_ADMIN;
297 return WIKIAUTH_ANON;
300 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
301 return WIKIAUTH_BOGO;
302 return WIKIAUTH_ANON;
303 // return WIKIAUTH_BOGO;
312 return WIKIAUTH_ADMIN;
314 global $WikiNameRegexp;
315 if (preg_match("/$WikiNameRegexp\Z/A", $action))
316 return WIKIAUTH_ANON; // ActionPage.
318 return WIKIAUTH_ADMIN;
322 function possiblyDeflowerVirginWiki () {
323 if ($this->getArg('action') != 'browse')
325 if ($this->getArg('pagename') != HOME_PAGE)
328 $page = $this->getPage();
329 $current = $page->getCurrentRevision();
330 if ($current->getVersion() > 0)
331 return; // Homepage exists.
333 include('lib/loadsave.php');
335 $this->finish(); // NORETURN
338 function handleAction () {
339 $action = $this->getArg('action');
340 $method = "action_$action";
341 if (method_exists($this, $method)) {
344 elseif ($page = $this->findActionPage($action)) {
345 $this->actionpage($page);
348 $this->finish(fmt("%s: Bad action", $action));
353 function finish ($errormsg = false) {
357 exit(); // just in case CloseDataBase calls us
360 if (!empty($this->_dbi))
361 $this->_dbi->close();
365 global $ErrorManager;
366 $ErrorManager->flushPostponedErrors();
368 if (!empty($errormsg)) {
371 HTML::h2(_("Fatal PhpWiki Error")),
374 echo "\n</body></html>";
381 function _deducePagename () {
382 if ($this->getArg('pagename'))
383 return $this->getArg('pagename');
386 $pathinfo = $this->get('PATH_INFO');
387 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
389 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
394 $query_string = $this->get('QUERY_STRING');
395 if (preg_match('/^[^&=]+$/', $query_string)) {
396 return urldecode($query_string);
402 function _deduceAction () {
403 if (!($action = $this->getArg('action'))) {
404 // Detect XML-RPC requests
406 && $this->get('CONTENT_TYPE') == 'text/xml') {
407 global $HTTP_RAW_POST_DATA;
408 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
413 return 'browse'; // Default if no action specified.
416 if (method_exists($this, "action_$action"))
419 // Allow for, e.g. action=LikePages
420 if ($this->isActionPage($action))
423 // Check for _('PhpWikiAdministration').'/'._('Remove') actions
424 $pagename = $this->getArg('pagename');
425 if (strstr($pagename,_('PhpWikiAdministration')))
428 trigger_error("$action: Unknown action", E_USER_NOTICE);
432 function _deduceUsername () {
433 if ($userid = $this->getSessionVar('wiki_user')) {
434 if (!empty($this->_user))
435 $this->_user->_authhow = 'session';
438 if ($userid = $this->getCookieVar('WIKI_ID')) {
439 if (!empty($this->_user))
440 $this->_user->authhow = 'cookie';
446 function _isActionPage ($pagename) {
447 $dbi = $this->getDbh();
448 $page = $dbi->getPage($pagename);
449 $rev = $page->getCurrentRevision();
450 // FIXME: more restrictive check for sane plugin?
451 if (strstr($rev->getPackedContent(), '<?plugin'))
453 if (!$rev->hasDefaultContents())
454 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
458 function findActionPage ($action) {
461 if (isset($cache) and isset($cache[$action]))
462 return $cache[$action];
464 // Allow for, e.g. action=LikePages
465 global $WikiNameRegexp;
466 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
467 return $cache[$action] = false;
469 // check for translated version (users preferred language)
470 $translation = gettext($action);
471 if ($this->_isActionPage($translation))
472 return $cache[$action] = $translation;
474 // check for translated version (default language)
476 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
478 update_locale(DEFAULT_LANGUAGE);
479 $default = gettext($action);
480 update_locale($save_lang);
481 if ($this->_isActionPage($default))
482 return $cache[$action] = $default;
485 $default = $translation;
488 // check for english version
489 if ($action != $translation and $action != $default) {
490 if ($this->_isActionPage($action))
491 return $cache[$action] = $action;
494 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
495 return $cache[$action] = false;
498 function isActionPage ($pagename) {
499 return $this->findActionPage($pagename);
502 function action_browse () {
503 $this->compress_output();
504 include_once("lib/display.php");
508 function action_verify () {
509 $this->action_browse();
512 function actionpage ($action) {
513 $this->compress_output();
514 include_once("lib/display.php");
515 actionPage($this, $action);
518 function action_diff () {
519 $this->compress_output();
520 include_once "lib/diff.php";
524 function action_search () {
525 // This is obsolete: reformulate URL and redirect.
526 // FIXME: this whole section should probably be deleted.
527 if ($this->getArg('searchtype') == 'full') {
528 $search_page = _("FullTextSearch");
531 $search_page = _("TitleSearch");
533 $this->redirect(WikiURL($search_page,
534 array('s' => $this->getArg('searchterm')),
538 function action_edit () {
539 $this->compress_output();
540 include "lib/editpage.php";
541 $e = new PageEditor ($this);
545 function action_viewsource () {
546 $this->compress_output();
547 include "lib/editpage.php";
548 $e = new PageEditor ($this);
552 function action_lock () {
553 $page = $this->getPage();
554 $page->set('locked', true);
555 $this->action_browse();
558 function action_unlock () {
559 // FIXME: This check is redundant.
560 //$user->requireAuth(WIKIAUTH_ADMIN);
561 $page = $this->getPage();
562 $page->set('locked', false);
563 $this->action_browse();
566 function action_remove () {
567 // FIXME: This check is redundant.
568 //$user->requireAuth(WIKIAUTH_ADMIN);
569 $pagename = $this->getArg('pagename');
570 if (strstr($pagename,_('PhpWikiAdministration'))) {
571 $this->action_browse();
573 include('lib/removepage.php');
579 function action_upload () {
580 include_once("lib/loadsave.php");
584 function action_xmlrpc () {
585 include_once("lib/XmlRpcServer.php");
586 $xmlrpc = new XmlRpcServer($this);
590 function action_zip () {
591 include_once("lib/loadsave.php");
593 // I don't think it hurts to add cruft at the end of the zip file.
594 echo "\n========================================================\n";
595 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
598 function action_ziphtml () {
599 include_once("lib/loadsave.php");
600 MakeWikiZipHtml($this);
601 // I don't think it hurts to add cruft at the end of the zip file.
602 echo "\n========================================================\n";
603 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
606 function action_dumpserial () {
607 include_once("lib/loadsave.php");
611 function action_dumphtml () {
612 include_once("lib/loadsave.php");
613 DumpHtmlToDir($this);
616 function action_loadfile () {
617 include_once("lib/loadsave.php");
618 LoadFileOrDir($this);
623 function is_safe_action ($action) {
624 return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
631 $request = new WikiRequest();
632 $request->updateAuthAndPrefs();
634 /* FIXME: is this needed anymore?
635 if (USE_PATH_INFO && ! $request->get('PATH_INFO')
636 && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
637 $request->redirect(SERVER_URL
638 . preg_replace('/(\?|$)/', '/\1',
639 $request->get('REQUEST_URI'),
645 // Enable the output of most of the warning messages.
646 // The warnings will screw up zip files though.
647 global $ErrorManager;
648 if (substr($request->getArg('action'), 0, 3) != 'zip') {
649 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
650 //$ErrorManager->setPostponedErrorMask(0);
654 //if ($user->is_authenticated())
655 // $LogEntry->user = $user->getId();
657 $request->possiblyDeflowerVirginWiki();
658 if(defined('WIKI_XMLRPC')) return;
659 $request->handleAction();
660 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
664 // Used for debugging purposes
665 function getmicrotime(){
666 list($usec, $sec) = explode(" ", microtime());
667 return ((float)$usec + (float)$sec);
669 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
678 // c-hanging-comment-ender-p: nil
679 // indent-tabs-mode: nil