2 rcs_id('$Id: main.php,v 1.81 2002-09-14 22:28:33 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 // Temp workaround for french single-word action pages 'Historique'
315 // Some of this make sense as SubPage actions or buttons.
316 $singleWordActionPages =
317 array("Historique", "Info",
318 _("Preferences"), _("Administration"),
319 _("Today"), _("Help"));
320 if (in_array($action, $singleWordActionPages))
321 return WIKIAUTH_ANON; // ActionPage.
322 global $WikiNameRegexp;
323 if (preg_match("/$WikiNameRegexp\Z/A", $action))
324 return WIKIAUTH_ANON; // ActionPage.
326 return WIKIAUTH_ADMIN;
330 function possiblyDeflowerVirginWiki () {
331 if ($this->getArg('action') != 'browse')
333 if ($this->getArg('pagename') != HOME_PAGE)
336 $page = $this->getPage();
337 $current = $page->getCurrentRevision();
338 if ($current->getVersion() > 0)
339 return; // Homepage exists.
341 include('lib/loadsave.php');
343 $this->finish(); // NORETURN
346 function handleAction () {
347 $action = $this->getArg('action');
348 $method = "action_$action";
349 if (method_exists($this, $method)) {
352 elseif ($this->isActionPage($action)) {
353 $this->actionpage($action);
356 $this->finish(fmt("%s: Bad action", $action));
361 function finish ($errormsg = false) {
365 exit(); // just in case CloseDataBase calls us
368 if (!empty($this->_dbi))
369 $this->_dbi->close();
373 global $ErrorManager;
374 $ErrorManager->flushPostponedErrors();
376 if (!empty($errormsg)) {
379 HTML::h2(_("Fatal PhpWiki Error")),
382 echo "\n</body></html>";
389 function _deducePagename () {
390 if ($this->getArg('pagename'))
391 return $this->getArg('pagename');
394 $pathinfo = $this->get('PATH_INFO');
395 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
397 if ($tail && $pathinfo == PATH_INFO_PREFIX . $tail) {
402 $query_string = $this->get('QUERY_STRING');
403 if (preg_match('/^[^&=]+$/', $query_string)) {
404 return urldecode($query_string);
410 function _deduceAction () {
411 if (!($action = $this->getArg('action'))) {
412 // Detect XML-RPC requests
414 && $this->get('CONTENT_TYPE') == 'text/xml') {
415 global $HTTP_RAW_POST_DATA;
416 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
421 return 'browse'; // Default if no action specified.
424 if (method_exists($this, "action_$action"))
427 // Allow for, e.g. action=LikePages
428 if ($this->isActionPage($action))
431 // Check for _('PhpWikiAdministration').'/'._('Remove') actions
432 $pagename = $this->getArg('pagename');
433 if (strstr($pagename,_('PhpWikiAdministration')))
436 trigger_error("$action: Unknown action", E_USER_NOTICE);
440 function _deduceUsername () {
441 if ($userid = $this->getSessionVar('wiki_user')) {
442 if (!empty($this->_user))
443 $this->_user->_authhow = 'session';
446 if ($userid = $this->getCookieVar('WIKI_ID')) {
447 if (!empty($this->_user))
448 $this->_user->authhow = 'cookie';
454 function isActionPage ($pagename) {
455 if (isSubPage($pagename))
456 $subpagename = subPageSlice($pagename,-1); // last element
458 $subpagename = $pagename;
459 // Temp workaround for french single-word action page 'Historique'
460 $singleWordActionPages = array("Historique", "Info", _('Preferences'));
461 if (! in_array($subpagename, $singleWordActionPages)) {
462 // Allow for, e.g. action=LikePages
463 global $WikiNameRegexp;
464 if (!preg_match("/$WikiNameRegexp\\Z/A", $subpagename))
467 $dbi = $this->getDbh();
468 $page = $dbi->getPage($pagename);
469 $rev = $page->getCurrentRevision();
470 // FIXME: more restrictive check for sane plugin?
471 if (strstr($rev->getPackedContent(), '<?plugin'))
473 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
477 function action_browse () {
478 $this->compress_output();
479 include_once("lib/display.php");
483 function action_verify () {
484 $this->action_browse();
487 function actionpage ($action) {
488 $this->compress_output();
489 include_once("lib/display.php");
490 actionPage($this, $action);
493 function action_diff () {
494 $this->compress_output();
495 include_once "lib/diff.php";
499 function action_search () {
500 // This is obsolete: reformulate URL and redirect.
501 // FIXME: this whole section should probably be deleted.
502 if ($this->getArg('searchtype') == 'full') {
503 $search_page = _("FullTextSearch");
506 $search_page = _("TitleSearch");
508 $this->redirect(WikiURL($search_page,
509 array('s' => $this->getArg('searchterm')),
513 function action_edit () {
514 $this->compress_output();
515 include "lib/editpage.php";
516 $e = new PageEditor ($this);
520 function action_viewsource () {
521 $this->compress_output();
522 include "lib/editpage.php";
523 $e = new PageEditor ($this);
527 function action_lock () {
528 $page = $this->getPage();
529 $page->set('locked', true);
530 $this->action_browse();
533 function action_unlock () {
534 // FIXME: This check is redundant.
535 //$user->requireAuth(WIKIAUTH_ADMIN);
536 $page = $this->getPage();
537 $page->set('locked', false);
538 $this->action_browse();
541 function action_remove () {
542 // FIXME: This check is redundant.
543 //$user->requireAuth(WIKIAUTH_ADMIN);
544 $pagename = $this->getArg('pagename');
545 if (strstr($pagename,_('PhpWikiAdministration'))) {
546 $this->action_browse();
548 include('lib/removepage.php');
554 function action_upload () {
555 include_once("lib/loadsave.php");
559 function action_xmlrpc () {
560 include_once("lib/XmlRpcServer.php");
561 $xmlrpc = new XmlRpcServer($this);
565 function action_zip () {
566 include_once("lib/loadsave.php");
568 // I don't think it hurts to add cruft at the end of the zip file.
569 echo "\n========================================================\n";
570 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
573 function action_ziphtml () {
574 include_once("lib/loadsave.php");
575 MakeWikiZipHtml($this);
576 // I don't think it hurts to add cruft at the end of the zip file.
577 echo "\n========================================================\n";
578 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
581 function action_dumpserial () {
582 include_once("lib/loadsave.php");
586 function action_dumphtml () {
587 include_once("lib/loadsave.php");
588 DumpHtmlToDir($this);
591 function action_loadfile () {
592 include_once("lib/loadsave.php");
593 LoadFileOrDir($this);
598 function is_safe_action ($action) {
599 return WikiRequest::requiredAuthority($action) < WIKIAUTH_ADMIN;
606 $request = new WikiRequest();
607 $request->updateAuthAndPrefs();
609 /* FIXME: is this needed anymore?
610 if (USE_PATH_INFO && ! $request->get('PATH_INFO')
611 && ! preg_match(',/$,', $request->get('REDIRECT_URL'))) {
612 $request->redirect(SERVER_URL
613 . preg_replace('/(\?|$)/', '/\1',
614 $request->get('REQUEST_URI'),
620 // Enable the output of most of the warning messages.
621 // The warnings will screw up zip files though.
622 global $ErrorManager;
623 if (substr($request->getArg('action'), 0, 3) != 'zip') {
624 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
625 //$ErrorManager->setPostponedErrorMask(0);
629 //if ($user->is_authenticated())
630 // $LogEntry->user = $user->getId();
632 $request->possiblyDeflowerVirginWiki();
633 if(defined('WIKI_XMLRPC')) return;
634 $request->handleAction();
635 if (defined('DEBUG') and DEBUG>1) phpinfo(INFO_VARIABLES);
639 // Used for debugging purposes
640 function getmicrotime(){
641 list($usec, $sec) = explode(" ", microtime());
642 return ((float)$usec + (float)$sec);
644 if (defined('DEBUG')) $GLOBALS['debugclock'] = getmicrotime();
653 // c-hanging-comment-ender-p: nil
654 // indent-tabs-mode: nil