2 rcs_id('$Id: main.php,v 1.86 2002-10-15 18:42:21 zorloc 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->_deduceUsername());
34 // $this->_user = new WikiDB_User($this->_user->getId(), $this->getAuthDbh());
35 $this->_prefs = $this->_user->getPreferences();
38 function initializeTheme () {
42 if ($user_theme = $this->getPref('theme'))
43 include_once("themes/$user_theme/themeinfo.php");
44 if (empty($Theme) and defined ('THEME'))
45 include_once("themes/" . THEME . "/themeinfo.php");
47 include_once("themes/default/themeinfo.php");
48 assert(!empty($Theme));
52 // This really maybe should be part of the constructor, but since it
53 // may involve HTML/template output, the global $request really needs
54 // to be initialized before we do this stuff.
55 function updateAuthAndPrefs () {
57 // Handle preference updates, an authentication requests, if any.
58 if ($new_prefs = $this->getArg('pref')) {
59 $this->setArg('pref', false);
60 if ($this->isPost() and !empty($new_prefs['passwd']) and
61 ($new_prefs['passwd2'] != $new_prefs['passwd'])) {
63 $this->_prefs->set('passwd','');
64 // $this->_prefs->set('passwd2',''); // This is not stored anyway
67 foreach ($new_prefs as $key => $val) {
68 if ($key == 'passwd') {
70 $val = crypt('passwd');
72 $this->_prefs->set($key, $val);
76 // FIXME: need to move authentication request processing
77 // up to be before pref request processing, I think,
78 // since logging in may change which preferences
79 // we're talking about...
81 // Handle authentication request, if any.
82 if ($auth_args = $this->getArg('auth')) {
83 $this->setArg('auth', false);
84 $this->_handleAuthRequest($auth_args); // possible NORETURN
86 elseif ( ! $this->_user->isSignedIn() ) {
87 // If not auth request, try to sign in as saved user.
88 if (($saved_user = $this->getPref('userid')) != false) {
89 $this->_signIn($saved_user);
93 // Save preferences in session and cookie
94 // FIXME: hey! what about anonymous users? Can't they have
97 $this->_user->setPreferences($this->_prefs, $id_only);
99 // Ensure user has permissions for action
100 $require_level = $this->requiredAuthority($this->getArg('action'));
101 if (! $this->_user->hasAuthority($require_level))
102 $this->_notAuthorized($require_level); // NORETURN
105 function getUser () {
109 function getPrefs () {
110 return $this->_prefs;
113 // Convenience function:
114 function getPref ($key) {
115 return $this->_prefs->get($key);
119 if (!isset($this->_dbi)) {
120 // needs PHP 4.1. better use $this->_user->...
121 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
126 function getAuthDbh () {
127 global $DBParams, $DBAuthParams;
128 if (!isset($this->_auth_dbi)) {
129 if ($DBParams['dbtype'] == 'dba' or empty($DBAuthParams['auth_dsn']))
130 $this->_auth_dbi = $this->getDbh(); // use phpwiki database
131 elseif ($DBAuthParams['auth_dsn'] == $DBParams['dsn'])
132 $this->_auth_dbi = $this->getDbh(); // same phpwiki database
133 else // use external database
134 // needs PHP 4.1. better use $this->_user->...
135 $this->_auth_dbi = WikiDB_User::open($DBAuthParams);
137 return $this->_auth_dbi;
141 * Get requested page from the page database.
142 * By default it will grab the page requested via the URL
144 * This is a convenience function.
145 * @param string $pagename Name of page to get.
146 * @return WikiDB_Page Object with methods to pull data from
147 * database for the page requested.
149 function getPage ($pagename = false) {
150 if (!isset($this->_dbi))
153 $pagename = $this->getArg('pagename');
154 return $this->_dbi->getPage($pagename);
157 function _handleAuthRequest ($auth_args) {
158 if (!is_array($auth_args))
161 // Ignore password unless POST'ed.
162 if (!$this->isPost())
163 unset($auth_args['passwd']);
165 $user = $this->_user->AuthCheck($auth_args);
167 if (isa($user, 'WikiUser')) {
168 // Successful login (or logout.)
169 $this->_setUser($user);
172 // Login attempt failed.
173 $fail_message = $user;
174 $auth_args['pass_required'] = true;
175 // If no password was submitted, it's not really
176 // a failure --- just need to prompt for password...
177 if (!isset($auth_args['passwd'])) {
178 //$auth_args['pass_required'] = false;
179 $fail_message = false;
181 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
182 $this->finish(); //NORETURN
185 // Login request cancelled.
190 * Attempt to sign in (bogo-login).
194 * @param $userid string Userid to attempt to sign in as.
197 function _signIn ($userid) {
198 $user = $this->_user->AuthCheck(array('userid' => $userid));
199 if (isa($user, 'WikiUser')) {
200 $this->_setUser($user); // success!
204 function _setUser ($user) {
205 $this->_user = $user;
206 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
207 $this->setSessionVar('wiki_user', $user);
208 if ($user->isSignedIn())
209 $user->_authhow = 'signin';
211 // Save userid to prefs..
212 $this->_prefs->set('userid',
213 $user->isSignedIn() ? $user->getId() : '');
216 function _notAuthorized ($require_level) {
217 // User does not have required authority. Prompt for login.
218 $what = $this->getActionDescription($this->getArg('action'));
220 if ($require_level >= WIKIAUTH_FORBIDDEN) {
221 $this->finish(fmt("%s is disallowed on this wiki.",
222 $this->getDisallowedActionDescription($this->getArg('action'))));
224 elseif ($require_level == WIKIAUTH_BOGO)
225 $msg = fmt("You must sign in to %s.", $what);
226 elseif ($require_level == WIKIAUTH_USER)
227 $msg = fmt("You must log in to %s.", $what);
229 $msg = fmt("You must be an administrator to %s.", $what);
230 $pass_required = ($require_level >= WIKIAUTH_USER);
232 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
233 $this->finish(); // NORETURN
236 function getActionDescription($action) {
237 static $actionDescriptions;
238 if (! $actionDescriptions) {
240 = array('browse' => _("browse pages in this wiki"),
241 'diff' => _("diff pages in this wiki"),
242 'dumphtml' => _("dump html pages from this wiki"),
243 'dumpserial' => _("dump serial pages from this wiki"),
244 'edit' => _("edit pages in this wiki"),
245 'loadfile' => _("load files into this wiki"),
246 'lock' => _("lock pages in this wiki"),
247 'remove' => _("remove pages from this wiki"),
248 'unlock' => _("unlock pages in this wiki"),
249 'upload' => _("upload a zip dump to this wiki"),
250 'verify' => _("verify the current action"),
251 'viewsource' => _("view the source of pages in this wiki"),
252 'xmlrpc' => _("access this wiki via XML-RPC"),
253 'zip' => _("download a zip dump from this wiki"),
254 'ziphtml' => _("download an html zip dump from this wiki")
257 if (in_array($action, array_keys($actionDescriptions)))
258 return $actionDescriptions[$action];
262 function getDisallowedActionDescription($action) {
263 static $disallowedActionDescriptions;
264 if (! $disallowedActionDescriptions) {
265 $disallowedActionDescriptions
266 = array('browse' => _("Browsing pages"),
267 'diff' => _("Diffing pages"),
268 'dumphtml' => _("Dumping html pages"),
269 'dumpserial' => _("Dumping serial pages"),
270 'edit' => _("Editing pages"),
271 'loadfile' => _("Loading files"),
272 'lock' => _("Locking pages"),
273 'remove' => _("Removing pages"),
274 'unlock' => _("Unlocking pages"),
275 'upload' => _("Uploading zip dumps"),
276 'verify' => _("Verify the current action"),
277 'viewsource' => _("Viewing the source of pages"),
278 'xmlrpc' => _("XML-RPC access"),
279 'zip' => _("Downloading zip dumps"),
280 'ziphtml' => _("Downloading html zip dumps")
283 if (in_array($action, array_keys($disallowedActionDescriptions)))
284 return $disallowedActionDescriptions[$action];
289 function requiredAuthority ($action) {
291 // Todo: Check individual page permissions instead.
298 return WIKIAUTH_ANON;
301 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
302 return WIKIAUTH_ADMIN;
303 return WIKIAUTH_ANON;
306 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
307 return WIKIAUTH_ADMIN;
308 return WIKIAUTH_ANON;
311 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
312 return WIKIAUTH_BOGO;
313 return WIKIAUTH_ANON;
314 // return WIKIAUTH_BOGO;
323 return WIKIAUTH_ADMIN;
325 global $WikiNameRegexp;
326 if (preg_match("/$WikiNameRegexp\Z/A", $action))
327 return WIKIAUTH_ANON; // ActionPage.
329 return WIKIAUTH_ADMIN;
333 function possiblyDeflowerVirginWiki () {
334 if ($this->getArg('action') != 'browse')
336 if ($this->getArg('pagename') != HOME_PAGE)
339 $page = $this->getPage();
340 $current = $page->getCurrentRevision();
341 if ($current->getVersion() > 0)
342 return; // Homepage exists.
344 include('lib/loadsave.php');
346 $this->finish(); // NORETURN
349 function handleAction () {
350 $action = $this->getArg('action');
351 $method = "action_$action";
352 if (method_exists($this, $method)) {
355 elseif ($page = $this->findActionPage($action)) {
356 $this->actionpage($page);
359 $this->finish(fmt("%s: Bad action", $action));
364 function finish ($errormsg = false) {
368 exit(); // just in case CloseDataBase calls us
371 if (!empty($this->_dbi))
372 $this->_dbi->close();
376 global $ErrorManager;
377 $ErrorManager->flushPostponedErrors();
379 if (!empty($errormsg)) {
382 HTML::h2(_("Fatal PhpWiki Error")),
385 echo "\n</body></html>";
392 function _deducePagename () {
393 if ($this->getArg('pagename'))
394 return $this->getArg('pagename');
397 $pathinfo = $this->get('PATH_INFO');
398 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
400 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
405 $query_string = $this->get('QUERY_STRING');
406 if (preg_match('/^[^&=]+$/', $query_string)) {
407 return urldecode($query_string);
413 function _deduceAction () {
414 if (!($action = $this->getArg('action'))) {
415 // Detect XML-RPC requests
417 && $this->get('CONTENT_TYPE') == 'text/xml') {
418 global $HTTP_RAW_POST_DATA;
419 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
424 return 'browse'; // Default if no action specified.
427 if (method_exists($this, "action_$action"))
430 // Allow for, e.g. action=LikePages
431 if ($this->isActionPage($action))
434 // Check for _('PhpWikiAdministration').'/'._('Remove') actions
435 $pagename = $this->getArg('pagename');
436 if (strstr($pagename,_('PhpWikiAdministration')))
439 trigger_error("$action: Unknown action", E_USER_NOTICE);
443 function _deduceUsername () {
444 if ($userid = $this->getSessionVar('wiki_user')) {
445 if (!empty($this->_user))
446 $this->_user->_authhow = 'session';
449 if ($userid = $this->getCookieVar('WIKI_ID')) {
450 if (!empty($this->_user))
451 $this->_user->authhow = 'cookie';
457 function _isActionPage ($pagename) {
458 $dbi = $this->getDbh();
459 $page = $dbi->getPage($pagename);
460 $rev = $page->getCurrentRevision();
461 // FIXME: more restrictive check for sane plugin?
462 if (strstr($rev->getPackedContent(), '<?plugin'))
464 if (!$rev->hasDefaultContents())
465 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
469 function findActionPage ($action) {
472 if (isset($cache) and isset($cache[$action]))
473 return $cache[$action];
475 // Allow for, e.g. action=LikePages
476 global $WikiNameRegexp;
477 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
478 return $cache[$action] = false;
480 // check for translated version (users preferred language)
481 $translation = gettext($action);
482 if ($this->_isActionPage($translation))
483 return $cache[$action] = $translation;
485 // check for translated version (default language)
487 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
489 update_locale(DEFAULT_LANGUAGE);
490 $default = gettext($action);
491 update_locale($save_lang);
492 if ($this->_isActionPage($default))
493 return $cache[$action] = $default;
496 $default = $translation;
499 // check for english version
500 if ($action != $translation and $action != $default) {
501 if ($this->_isActionPage($action))
502 return $cache[$action] = $action;
505 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
506 return $cache[$action] = false;
509 function isActionPage ($pagename) {
510 return $this->findActionPage($pagename);
513 function action_browse () {
514 $this->compress_output();
515 include_once("lib/display.php");
519 function action_verify () {
520 $this->action_browse();
523 function actionpage ($action) {
524 $this->compress_output();
525 include_once("lib/display.php");
526 actionPage($this, $action);
529 function action_diff () {
530 $this->compress_output();
531 include_once "lib/diff.php";
535 function action_search () {
536 // This is obsolete: reformulate URL and redirect.
537 // FIXME: this whole section should probably be deleted.
538 if ($this->getArg('searchtype') == 'full') {
539 $search_page = _("FullTextSearch");
542 $search_page = _("TitleSearch");
544 $this->redirect(WikiURL($search_page,
545 array('s' => $this->getArg('searchterm')),
549 function action_edit () {
550 $this->compress_output();
551 include "lib/editpage.php";
552 $e = new PageEditor ($this);
556 function action_viewsource () {
557 $this->compress_output();
558 include "lib/editpage.php";
559 $e = new PageEditor ($this);
563 function action_lock () {
564 $page = $this->getPage();
565 $page->set('locked', true);
566 $this->action_browse();
569 function action_unlock () {
570 // FIXME: This check is redundant.
571 //$user->requireAuth(WIKIAUTH_ADMIN);
572 $page = $this->getPage();
573 $page->set('locked', false);
574 $this->action_browse();
577 function action_remove () {
578 // FIXME: This check is redundant.
579 //$user->requireAuth(WIKIAUTH_ADMIN);
580 $pagename = $this->getArg('pagename');
581 if (strstr($pagename,_('PhpWikiAdministration'))) {
582 $this->action_browse();
584 include('lib/removepage.php');
590 function action_upload () {
591 include_once("lib/loadsave.php");
595 function action_xmlrpc () {
596 include_once("lib/XmlRpcServer.php");
597 $xmlrpc = new XmlRpcServer($this);
601 function action_zip () {
602 include_once("lib/loadsave.php");
604 // I don't think it hurts to add cruft at the end of the zip file.
605 echo "\n========================================================\n";
606 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
609 function action_ziphtml () {
610 include_once("lib/loadsave.php");
611 MakeWikiZipHtml($this);
612 // I don't think it hurts to add cruft at the end of the zip file.
613 echo "\n========================================================\n";
614 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
617 function action_dumpserial () {
618 include_once("lib/loadsave.php");
622 function action_dumphtml () {
623 include_once("lib/loadsave.php");
624 DumpHtmlToDir($this);
627 function action_loadfile () {
628 include_once("lib/loadsave.php");
629 LoadFileOrDir($this);
634 function is_safe_action ($action) {
635 return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
642 $request = new WikiRequest();
643 $request->initializeTheme();
644 $request->updateAuthAndPrefs();
646 /* FIXME: is this needed anymore?
647 if (USE_PATH_INFO && ! $request->get('PATH_INFO')
648 && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
649 $request->redirect(SERVER_URL
650 . preg_replace('/(\?|$)/', '/\1',
651 $request->get('REQUEST_URI'),
657 // Enable the output of most of the warning messages.
658 // The warnings will screw up zip files though.
659 global $ErrorManager;
660 if (substr($request->getArg('action'), 0, 3) != 'zip') {
661 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
662 //$ErrorManager->setPostponedErrorMask(0);
666 //if ($user->is_authenticated())
667 // $LogEntry->user = $user->getId();
669 $request->possiblyDeflowerVirginWiki();
670 if(defined('WIKI_XMLRPC')) return;
671 $request->handleAction();
672 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
676 // Used for debugging purposes
677 function getmicrotime(){
678 list($usec, $sec) = explode(" ", microtime());
679 return ((float)$usec + (float)$sec);
681 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
690 // c-hanging-comment-ender-p: nil
691 // indent-tabs-mode: nil