2 rcs_id('$Id: main.php,v 1.82 2002-09-16 18:49:17 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'));
147 * Convert (possibly) relative name of subpage to full name.
149 * @param string $relname
152 function fullPagename ($relname) {
153 if ($relname[0] == SUBPAGE_SEPARATOR)
154 return $this->getArg('pagename') . $relname;
159 function _handleAuthRequest ($auth_args) {
160 if (!is_array($auth_args))
163 // Ignore password unless POST'ed.
164 if (!$this->isPost())
165 unset($auth_args['passwd']);
167 $user = $this->_user->AuthCheck($auth_args);
169 if (isa($user, 'WikiUser')) {
170 // Successful login (or logout.)
171 $this->_setUser($user);
174 // Login attempt failed.
175 $fail_message = $user;
176 $auth_args['pass_required'] = true;
177 // If no password was submitted, it's not really
178 // a failure --- just need to prompt for password...
179 if (!isset($auth_args['passwd'])) {
180 //$auth_args['pass_required'] = false;
181 $fail_message = false;
183 $this->_user->PrintLoginForm($this, $auth_args, $fail_message);
184 $this->finish(); //NORETURN
187 // Login request cancelled.
192 * Attempt to sign in (bogo-login).
196 * @param $userid string Userid to attempt to sign in as.
199 function _signIn ($userid) {
200 $user = $this->_user->AuthCheck(array('userid' => $userid));
201 if (isa($user, 'WikiUser')) {
202 $this->_setUser($user); // success!
206 function _setUser ($user) {
207 $this->_user = $user;
208 $this->setCookieVar('WIKI_ID', $user->_userid, 365);
209 $this->setSessionVar('wiki_user', $user);
210 if ($user->isSignedIn())
211 $user->_authhow = 'signin';
213 // Save userid to prefs..
214 $this->_prefs->set('userid',
215 $user->isSignedIn() ? $user->getId() : '');
218 function _notAuthorized ($require_level) {
219 // User does not have required authority. Prompt for login.
220 $what = $this->getActionDescription($this->getArg('action'));
222 if ($require_level >= WIKIAUTH_FORBIDDEN) {
223 $this->finish(fmt("%s is disallowed on this wiki.",
224 $this->getDisallowedActionDescription($this->getArg('action'))));
226 elseif ($require_level == WIKIAUTH_BOGO)
227 $msg = fmt("You must sign in to %s.", $what);
228 elseif ($require_level == WIKIAUTH_USER)
229 $msg = fmt("You must log in to %s.", $what);
231 $msg = fmt("You must be an administrator to %s.", $what);
232 $pass_required = ($require_level >= WIKIAUTH_USER);
234 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
235 $this->finish(); // NORETURN
238 function getActionDescription($action) {
239 static $actionDescriptions;
240 if (! $actionDescriptions) {
242 = array('browse' => _("browse pages in this wiki"),
243 'diff' => _("diff pages in this wiki"),
244 'dumphtml' => _("dump html pages from this wiki"),
245 'dumpserial' => _("dump serial pages from this wiki"),
246 'edit' => _("edit pages in this wiki"),
247 'loadfile' => _("load files into this wiki"),
248 'lock' => _("lock pages in this wiki"),
249 'remove' => _("remove pages from this wiki"),
250 'unlock' => _("unlock pages in this wiki"),
251 'upload' => _("upload a zip dump to this wiki"),
252 'verify' => _("verify the current action"),
253 'viewsource' => _("view the source of pages in this wiki"),
254 'xmlrpc' => _("access this wiki via XML-RPC"),
255 'zip' => _("download a zip dump from this wiki"),
256 'ziphtml' => _("download an html zip dump from this wiki")
259 if (in_array($action, array_keys($actionDescriptions)))
260 return $actionDescriptions[$action];
264 function getDisallowedActionDescription($action) {
265 static $disallowedActionDescriptions;
266 if (! $disallowedActionDescriptions) {
267 $disallowedActionDescriptions
268 = array('browse' => _("Browsing pages"),
269 'diff' => _("Diffing pages"),
270 'dumphtml' => _("Dumping html pages"),
271 'dumpserial' => _("Dumping serial pages"),
272 'edit' => _("Editing pages"),
273 'loadfile' => _("Loading files"),
274 'lock' => _("Locking pages"),
275 'remove' => _("Removing pages"),
276 'unlock' => _("Unlocking pages"),
277 'upload' => _("Uploading zip dumps"),
278 'verify' => _("Verify the current action"),
279 'viewsource' => _("Viewing the source of pages"),
280 'xmlrpc' => _("XML-RPC access"),
281 'zip' => _("Downloading zip dumps"),
282 'ziphtml' => _("Downloading html zip dumps")
285 if (in_array($action, array_keys($disallowedActionDescriptions)))
286 return $disallowedActionDescriptions[$action];
291 function requiredAuthority ($action) {
293 // Todo: Check individual page permissions instead.
300 return WIKIAUTH_ANON;
303 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
304 return WIKIAUTH_ADMIN;
305 return WIKIAUTH_ANON;
308 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
309 return WIKIAUTH_ADMIN;
310 return WIKIAUTH_ANON;
313 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
314 return WIKIAUTH_BOGO;
315 return WIKIAUTH_ANON;
316 // return WIKIAUTH_BOGO;
325 return WIKIAUTH_ADMIN;
327 // Temp workaround for french single-word action pages 'Historique'
328 // Some of this make sense as SubPage actions or buttons.
329 $singleWordActionPages =
330 array("Historique", "Info",
331 _("Preferences"), _("Administration"),
332 _("Today"), _("Help"));
333 if (in_array($action, $singleWordActionPages))
334 return WIKIAUTH_ANON; // ActionPage.
335 global $WikiNameRegexp;
336 if (preg_match("/$WikiNameRegexp\Z/A", $action))
337 return WIKIAUTH_ANON; // ActionPage.
339 return WIKIAUTH_ADMIN;
343 function possiblyDeflowerVirginWiki () {
344 if ($this->getArg('action') != 'browse')
346 if ($this->getArg('pagename') != HOME_PAGE)
349 $page = $this->getPage();
350 $current = $page->getCurrentRevision();
351 if ($current->getVersion() > 0)
352 return; // Homepage exists.
354 include('lib/loadsave.php');
356 $this->finish(); // NORETURN
359 function handleAction () {
360 $action = $this->getArg('action');
361 $method = "action_$action";
362 if (method_exists($this, $method)) {
365 elseif ($this->isActionPage($action)) {
366 $this->actionpage($action);
369 $this->finish(fmt("%s: Bad action", $action));
374 function finish ($errormsg = false) {
378 exit(); // just in case CloseDataBase calls us
381 if (!empty($this->_dbi))
382 $this->_dbi->close();
386 global $ErrorManager;
387 $ErrorManager->flushPostponedErrors();
389 if (!empty($errormsg)) {
392 HTML::h2(_("Fatal PhpWiki Error")),
395 echo "\n</body></html>";
402 function _deducePagename () {
403 if ($this->getArg('pagename'))
404 return $this->getArg('pagename');
407 $pathinfo = $this->get('PATH_INFO');
408 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
410 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
415 $query_string = $this->get('QUERY_STRING');
416 if (preg_match('/^[^&=]+$/', $query_string)) {
417 return urldecode($query_string);
423 function _deduceAction () {
424 if (!($action = $this->getArg('action'))) {
425 // Detect XML-RPC requests
427 && $this->get('CONTENT_TYPE') == 'text/xml') {
428 global $HTTP_RAW_POST_DATA;
429 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
434 return 'browse'; // Default if no action specified.
437 if (method_exists($this, "action_$action"))
440 // Allow for, e.g. action=LikePages
441 if ($this->isActionPage($action))
444 // Check for _('PhpWikiAdministration').'/'._('Remove') actions
445 $pagename = $this->getArg('pagename');
446 if (strstr($pagename,_('PhpWikiAdministration')))
449 trigger_error("$action: Unknown action", E_USER_NOTICE);
453 function _deduceUsername () {
454 if ($userid = $this->getSessionVar('wiki_user')) {
455 if (!empty($this->_user))
456 $this->_user->_authhow = 'session';
459 if ($userid = $this->getCookieVar('WIKI_ID')) {
460 if (!empty($this->_user))
461 $this->_user->authhow = 'cookie';
467 function isActionPage ($pagename) {
468 if (isSubPage($pagename))
469 $subpagename = subPageSlice($pagename,-1); // last element
471 $subpagename = $pagename;
472 // Temp workaround for french single-word action page 'Historique'
473 $singleWordActionPages = array("Historique", "Info", _('Preferences'));
474 if (! in_array($subpagename, $singleWordActionPages)) {
475 // Allow for, e.g. action=LikePages
476 global $WikiNameRegexp;
477 if (!preg_match("/$WikiNameRegexp\\Z/A", $subpagename))
480 $dbi = $this->getDbh();
481 $page = $dbi->getPage($pagename);
482 $rev = $page->getCurrentRevision();
483 // FIXME: more restrictive check for sane plugin?
484 if (strstr($rev->getPackedContent(), '<?plugin'))
486 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
490 function action_browse () {
491 $this->compress_output();
492 include_once("lib/display.php");
496 function action_verify () {
497 $this->action_browse();
500 function actionpage ($action) {
501 $this->compress_output();
502 include_once("lib/display.php");
503 actionPage($this, $action);
506 function action_diff () {
507 $this->compress_output();
508 include_once "lib/diff.php";
512 function action_search () {
513 // This is obsolete: reformulate URL and redirect.
514 // FIXME: this whole section should probably be deleted.
515 if ($this->getArg('searchtype') == 'full') {
516 $search_page = _("FullTextSearch");
519 $search_page = _("TitleSearch");
521 $this->redirect(WikiURL($search_page,
522 array('s' => $this->getArg('searchterm')),
526 function action_edit () {
527 $this->compress_output();
528 include "lib/editpage.php";
529 $e = new PageEditor ($this);
533 function action_viewsource () {
534 $this->compress_output();
535 include "lib/editpage.php";
536 $e = new PageEditor ($this);
540 function action_lock () {
541 $page = $this->getPage();
542 $page->set('locked', true);
543 $this->action_browse();
546 function action_unlock () {
547 // FIXME: This check is redundant.
548 //$user->requireAuth(WIKIAUTH_ADMIN);
549 $page = $this->getPage();
550 $page->set('locked', false);
551 $this->action_browse();
554 function action_remove () {
555 // FIXME: This check is redundant.
556 //$user->requireAuth(WIKIAUTH_ADMIN);
557 $pagename = $this->getArg('pagename');
558 if (strstr($pagename,_('PhpWikiAdministration'))) {
559 $this->action_browse();
561 include('lib/removepage.php');
567 function action_upload () {
568 include_once("lib/loadsave.php");
572 function action_xmlrpc () {
573 include_once("lib/XmlRpcServer.php");
574 $xmlrpc = new XmlRpcServer($this);
578 function action_zip () {
579 include_once("lib/loadsave.php");
581 // I don't think it hurts to add cruft at the end of the zip file.
582 echo "\n========================================================\n";
583 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
586 function action_ziphtml () {
587 include_once("lib/loadsave.php");
588 MakeWikiZipHtml($this);
589 // I don't think it hurts to add cruft at the end of the zip file.
590 echo "\n========================================================\n";
591 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
594 function action_dumpserial () {
595 include_once("lib/loadsave.php");
599 function action_dumphtml () {
600 include_once("lib/loadsave.php");
601 DumpHtmlToDir($this);
604 function action_loadfile () {
605 include_once("lib/loadsave.php");
606 LoadFileOrDir($this);
611 function is_safe_action ($action) {
612 return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
619 $request = new WikiRequest();
620 $request->updateAuthAndPrefs();
622 /* FIXME: is this needed anymore?
623 if (USE_PATH_INFO && ! $request->get('PATH_INFO')
624 && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
625 $request->redirect(SERVER_URL
626 . preg_replace('/(\?|$)/', '/\1',
627 $request->get('REQUEST_URI'),
633 // Enable the output of most of the warning messages.
634 // The warnings will screw up zip files though.
635 global $ErrorManager;
636 if (substr($request->getArg('action'), 0, 3) != 'zip') {
637 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
638 //$ErrorManager->setPostponedErrorMask(0);
642 //if ($user->is_authenticated())
643 // $LogEntry->user = $user->getId();
645 $request->possiblyDeflowerVirginWiki();
646 if(defined('WIKI_XMLRPC')) return;
647 $request->handleAction();
648 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
652 // Used for debugging purposes
653 function getmicrotime(){
654 list($usec, $sec) = explode(" ", microtime());
655 return ((float)$usec + (float)$sec);
657 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
666 // c-hanging-comment-ender-p: nil
667 // indent-tabs-mode: nil