2 rcs_id('$Id: main.php,v 1.153 2004-06-01 15:28:00 rurban Exp $');
4 define ('USE_PREFS_IN_PAGE', true);
6 //include "lib/config.php";
7 require_once(dirname(__FILE__)."/stdlib.php");
8 require_once('lib/Request.php');
9 require_once('lib/WikiDB.php');
11 require_once("lib/WikiUserNew.php");
13 require_once("lib/WikiUser.php");
14 require_once("lib/WikiGroup.php");
15 require_once("lib/PagePerm.php");
17 class WikiRequest extends Request {
20 function WikiRequest () {
21 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
22 if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
23 // force our local copy, until the pear version is fixed.
24 include_once(dirname(__FILE__)."/pear/File_Passwd.php");
27 include_once('lib/DbSession.php');
29 $this->_dbsession = & new DbSession($dbi, $dbi->getParam('prefix') . $dbi->getParam('db_session_table'));
31 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
32 $x = error_reporting();
33 $this->version = phpwiki_version();
37 $this->setArg('pagename', $this->_deducePagename());
38 $this->setArg('action', $this->_deduceAction());
40 // Restore auth state. This doesn't check for proper authorization!
41 if (ENABLE_USER_NEW) {
42 $userid = $this->_deduceUsername();
43 if (isset($this->_user) and
44 !empty($this->_user->_authhow) and
45 $this->_user->_authhow == 'session')
47 // users might switch in a session between the two objects.
48 // restore old auth level here or in updateAuthAndPrefs?
49 //$user = $this->getSessionVar('wiki_user');
50 // revive db handle, because these don't survive sessions
51 if (isset($this->_user) and
52 ( ! isa($this->_user,WikiUserClassname())
53 or (strtolower(get_class($this->_user)) == '_passuser')))
55 $this->_user = WikiUser($userid,$this->_user->_prefs);
57 unset($this->_user->_HomePagehandle);
58 $this->_user->hasHomePage();
59 // update the lockfile filehandle
60 if ( isa($this->_user,'_FilePassUser') and
61 $this->_user->_file->lockfile and
62 !$this->_user->_file->fplock )
64 $this->_user = new _FilePassUser($userid, $this->_user->_prefs, $this->_user->_file->filename);
67 if (!isa($user,WikiUserClassname()) or empty($this->_user->_level)) {
68 $user = UpgradeUser($this->_user,$user);
71 $this->_prefs = & $this->_user->_prefs;
73 $user = WikiUser($userid);
74 $this->_user = & $user;
75 $this->_prefs = & $this->_user->_prefs;
78 $this->_user = new WikiUser($this, $this->_deduceUsername());
79 $this->_prefs = $this->_user->getPreferences();
83 function initializeLang () {
84 if ($user_lang = $this->getPref('lang')) {
85 //trigger_error("DEBUG: initializeLang() ". $user_lang ." calling update_locale()...");
86 update_locale($user_lang);
87 FindLocalizedButtonFile(".",'missing_ok','reinit');
91 function initializeTheme () {
95 if ($user_theme = $this->getPref('theme'))
96 include_once("themes/$user_theme/themeinfo.php");
97 if (empty($Theme) and defined('THEME'))
98 include_once("themes/" . THEME . "/themeinfo.php");
100 include_once("themes/default/themeinfo.php");
101 assert(!empty($Theme));
104 // This really maybe should be part of the constructor, but since it
105 // may involve HTML/template output, the global $request really needs
106 // to be initialized before we do this stuff.
107 function updateAuthAndPrefs () {
109 if (isset($this->_user) and (!isa($this->_user,WikiUserClassname()))) {
110 $this->_user = false;
112 // Handle authentication request, if any.
113 if ($auth_args = $this->getArg('auth')) {
114 $this->setArg('auth', false);
115 $this->_handleAuthRequest($auth_args); // possible NORETURN
117 elseif ( ! $this->_user or
118 (isa($this->_user,WikiUserClassname()) and ! $this->_user->isSignedIn())) {
119 // If not auth request, try to sign in as saved user.
120 if (($saved_user = $this->getPref('userid')) != false) {
121 $this->_signIn($saved_user);
125 // Save preferences in session and cookie
126 if (isset($this->_user) and
127 (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session')) {
129 $this->_user->setPreferences($this->_prefs, $id_only);
131 $this->setSessionVar('wiki_user', $this->_user);
132 //$this->setSessionVar('wiki_prefs', $this->_prefs);
135 // Ensure user has permissions for action
136 $require_level = $this->requiredAuthority($this->getArg('action'));
137 if (! $this->_user->hasAuthority($require_level))
138 $this->_notAuthorized($require_level); // NORETURN
141 function getUser () {
142 if (isset($this->_user))
145 return $GLOBALS['ForbiddenUser'];
148 function getPrefs () {
149 return $this->_prefs;
152 // Convenience function:
153 function getPref ($key) {
154 if (isset($this->_prefs))
155 return $this->_prefs->get($key);
163 * Get requested page from the page database.
164 * By default it will grab the page requested via the URL
166 * This is a convenience function.
167 * @param string $pagename Name of page to get.
168 * @return WikiDB_Page Object with methods to pull data from
169 * database for the page requested.
171 function getPage ($pagename = false) {
172 if (!isset($this->_dbi))
175 $pagename = $this->getArg('pagename');
176 return $this->_dbi->getPage($pagename);
179 /** Get URL for POST actions.
181 * Officially, we should just use SCRIPT_NAME (or some such),
182 * but that causes problems when we try to issue a redirect, e.g.
183 * after saving a page.
185 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
186 * a redirect from a page to itself.)
188 * So, as a HACK, we include pagename and action as query args in
189 * the URL. (These should be ignored when we receive the POST
192 function getPostURL ($pagename=false) {
193 global $HTTP_GET_VARS;
195 if ($pagename === false)
196 $pagename = $this->getArg('pagename');
197 $action = $this->getArg('action');
198 if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
199 return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
201 return WikiURL($pagename, array('action' => $action));
204 function _handleAuthRequest ($auth_args) {
205 if (!is_array($auth_args))
208 // Ignore password unless POST'ed.
209 if (!$this->isPost())
210 unset($auth_args['passwd']);
212 $olduser = $this->_user;
213 $user = $this->_user->AuthCheck($auth_args);
214 if (isa($user,WikiUserClassname())) {
215 // Successful login (or logout.)
216 $this->_setUser($user);
218 elseif (is_string($user)) {
219 // Login attempt failed.
220 $fail_message = $user;
221 $auth_args['pass_required'] = true;
222 // If no password was submitted, it's not really
223 // a failure --- just need to prompt for password...
224 if (!ALLOW_USER_PASSWORDS
226 and !isset($auth_args['passwd']))
228 $fail_message = false;
230 $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
231 $this->finish(); //NORETURN
234 // Login request cancelled.
239 * Attempt to sign in (bogo-login).
243 * @param $userid string Userid to attempt to sign in as.
246 function _signIn ($userid) {
247 if (ENABLE_USER_NEW) {
249 $this->_user = new _BogoUser($userid);
251 $this->_user = new _PassUser($userid);
253 $user = $this->_user->AuthCheck(array('userid' => $userid));
254 if (isa($user,WikiUserClassname())) {
255 $this->_setUser($user); // success!
259 // login or logout or restore state
260 function _setUser ($user) {
261 $this->_user = $user;
262 define('MAIN_setUser',true);
263 $this->setCookieVar('WIKI_ID', $user->getAuthenticatedId(), COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
264 $this->setSessionVar('wiki_user', $user);
265 if ($user->isSignedIn())
266 $user->_authhow = 'signin';
268 // Save userid to prefs..
269 if ( ! $this->_user->_prefs ) {
270 $this->_user->_prefs = $this->_user->getPreferences();
271 $this->_prefs =& $this->_user->_prefs;
273 $this->_prefs->set('userid',
274 $user->isSignedIn() ? $user->getId() : '');
275 $this->initializeTheme();
278 /* Permission system */
279 function getLevelDescription($level) {
280 static $levels = false;
282 $levels = array('-1' => _("FORBIDDEN"),
287 '100'=> _("UNOBTAINABLE"));
288 return $levels[$level];
291 function _notAuthorized ($require_level) {
292 // Display the authority message in the Wiki's default
293 // language, in case it is not english.
295 // Note that normally a user will not see such an error once
296 // logged in, unless the admin has altered the default
297 // disallowed wikiactions. In that case we should probably
298 // check the user's language prefs too at this point; this
299 // would be a situation which is not really handled with the
301 if (empty($GLOBALS['LANG']))
302 update_locale(DEFAULT_LANGUAGE);
304 // User does not have required authority. Prompt for login.
305 $what = $this->getActionDescription($this->getArg('action'));
306 $pass_required = ($require_level >= WIKIAUTH_USER);
307 if ($require_level == WIKIAUTH_UNOBTAINABLE) {
308 if (class_exists('PagePermission')) {
309 $user =& $this->_user;
310 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
311 $msg = fmt("%s is disallowed on this wiki for %s user '%s' (level: %s).",
312 $this->getDisallowedActionDescription($this->getArg('action')),
313 $status, $user->getId(),$this->getLevelDescription($user->_level));
314 $user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
317 $msg = fmt("%s is disallowed on this wiki.",
318 $this->getDisallowedActionDescription($this->getArg('action')));
319 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
323 elseif ($require_level == WIKIAUTH_BOGO)
324 $msg = fmt("You must sign in to %s.", $what);
325 elseif ($require_level == WIKIAUTH_USER)
326 $msg = fmt("You must log in to %s.", $what);
328 $msg = fmt("You must be an administrator to %s.", $what);
330 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
331 $this->finish(); // NORETURN
334 // Fixme: for PagePermissions we'll need other strings,
335 // relevant to the requested page, not just for the action on the whole wiki.
336 function getActionDescription($action) {
337 static $actionDescriptions;
338 if (! $actionDescriptions) {
340 = array('browse' => _("view this page"),
341 'diff' => _("diff this page"),
342 'dumphtml' => _("dump html pages"),
343 'dumpserial' => _("dump serial pages"),
344 'edit' => _("edit this page"),
345 'create' => _("create this page"),
346 'loadfile' => _("load files into this wiki"),
347 'lock' => _("lock this page"),
348 'remove' => _("remove this page"),
349 'unlock' => _("unlock this page"),
350 'upload' => _("upload a zip dump"),
351 'verify' => _("verify the current action"),
352 'viewsource' => _("view the source of this page"),
353 'xmlrpc' => _("access this wiki via XML-RPC"),
354 'soap' => _("access this wiki via SOAP"),
355 'zip' => _("download a zip dump from this wiki"),
356 'ziphtml' => _("download an html zip dump from this wiki")
359 if (in_array($action, array_keys($actionDescriptions)))
360 return $actionDescriptions[$action];
364 function getDisallowedActionDescription($action) {
365 static $disallowedActionDescriptions;
366 if (! $disallowedActionDescriptions) {
367 $disallowedActionDescriptions
368 = array('browse' => _("Browsing pages"),
369 'diff' => _("Diffing pages"),
370 'dumphtml' => _("Dumping html pages"),
371 'dumpserial' => _("Dumping serial pages"),
372 'edit' => _("Editing pages"),
373 'create' => _("Creating pages"),
374 'loadfile' => _("Loading files"),
375 'lock' => _("Locking pages"),
376 'remove' => _("Removing pages"),
377 'unlock' => _("Unlocking pages"),
378 'upload' => _("Uploading zip dumps"),
379 'verify' => _("Verify the current action"),
380 'viewsource' => _("Viewing the source of pages"),
381 'xmlrpc' => _("XML-RPC access"),
382 'soap' => _("SOAP access"),
383 'zip' => _("Downloading zip dumps"),
384 'ziphtml' => _("Downloading html zip dumps")
387 if (in_array($action, array_keys($disallowedActionDescriptions)))
388 return $disallowedActionDescriptions[$action];
393 function requiredAuthority ($action) {
394 $auth = $this->requiredAuthorityForAction($action);
395 if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
398 * This is a hook for plugins to require authority
399 * for posting to them.
401 * IMPORTANT: this is not a secure check, so the plugin
402 * may not assume that any POSTs to it are authorized.
403 * All this does is cause PhpWiki to prompt for login
404 * if the user doesn't have the required authority.
406 if ($this->isPost()) {
407 $post_auth = $this->getArg('require_authority_for_post');
408 if ($post_auth !== false)
409 $auth = max($auth, $post_auth);
414 function requiredAuthorityForAction ($action) {
415 if (class_exists("PagePermission")) {
416 return requiredAuthorityForPage($action);
427 return WIKIAUTH_ANON;
431 if (defined('ZIPDUMP_AUTH') && ZIPDUMP_AUTH)
432 return WIKIAUTH_ADMIN;
433 return WIKIAUTH_ANON;
437 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
438 return WIKIAUTH_BOGO;
439 return WIKIAUTH_ANON;
440 // return WIKIAUTH_BOGO;
443 $page = $this->getPage();
444 $current = $page->getCurrentRevision();
445 if ($current->hasDefaultContents())
446 return $this->requiredAuthorityForAction('edit');
447 return $this->requiredAuthorityForAction('browse');
457 return WIKIAUTH_ADMIN;
459 /* authcheck occurs only in the plugin.
460 required actionpage RateIt */
463 case 'delete_rating':
464 // Perhaps this should be WIKIAUTH_USER
465 return WIKIAUTH_BOGO;
469 global $WikiNameRegexp;
470 if (preg_match("/$WikiNameRegexp\Z/A", $action))
471 return WIKIAUTH_ANON; // ActionPage.
473 return WIKIAUTH_ADMIN;
477 /* End of Permission system */
479 function possiblyDeflowerVirginWiki () {
480 if ($this->getArg('action') != 'browse')
482 if ($this->getArg('pagename') != HOME_PAGE)
485 $page = $this->getPage();
486 $current = $page->getCurrentRevision();
487 if ($current->getVersion() > 0)
488 return; // Homepage exists.
490 include('lib/loadsave.php');
492 $this->finish(); // NORETURN
495 function handleAction () {
496 $action = $this->getArg('action');
497 $method = "action_$action";
498 if (method_exists($this, $method)) {
501 elseif ($page = $this->findActionPage($action)) {
502 $this->actionpage($page);
505 $this->finish(fmt("%s: Bad action", $action));
509 function finish ($errormsg = false) {
513 exit(); // just in case CloseDataBase calls us
516 global $ErrorManager;
517 $ErrorManager->flushPostponedErrors();
519 if (!empty($errormsg)) {
522 HTML::h2(_("Fatal PhpWiki Error")),
525 echo "\n</body></html>";
527 if (is_object($this->_user)) {
528 $this->_user->page = $this->getArg('pagename');
529 $this->_user->action = $this->getArg('action');
530 unset($this->_user->_HomePagehandle);
531 unset($this->_user->_auth_dbi);
533 if (!empty($this->_dbi)) {
534 session_write_close();
535 $this->_dbi->close();
543 * Generally pagename is rawurlencoded for older browsers or mozilla.
544 * Typing a pagename into the IE bar will utf-8 encode it, so we have to
545 * fix that with fixTitleEncoding().
546 * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
547 * If false, we support either "/index.php?pagename=PageName&arg=value",
548 * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
550 function _deducePagename () {
551 if (trim(rawurldecode($this->getArg('pagename'))))
552 return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
555 $pathinfo = $this->get('PATH_INFO');
556 if (empty($pathinfo)) { // fix for CGI
557 $path = $this->get('REQUEST_URI');
558 $script = $this->get('SCRIPT_NAME');
559 $pathinfo = substr($path,strlen($script));
560 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
562 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
564 if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
565 return fixTitleEncoding($tail);
568 elseif ($this->isPost()) {
570 * In general, for security reasons, HTTP_GET_VARS should be ignored
571 * on POST requests, but we make an exception here (only for pagename).
573 * The justification for this hack is the following
574 * asymmetry: When POSTing with USE_PATH_INFO set, the
575 * pagename can (and should) be communicated through the
576 * request URL via PATH_INFO. When POSTing with
577 * USE_PATH_INFO off, this cannot be done --- the only way
578 * to communicate the pagename through the URL is via
579 * QUERY_ARGS (HTTP_GET_VARS).
581 global $HTTP_GET_VARS;
582 if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) {
583 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
588 * Support for PhpWiki 1.2 style requests.
589 * Strip off "&" args (?PageName&action=...&start_debug,...)
591 $query_string = $this->get('QUERY_STRING');
592 if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
593 return fixTitleEncoding(rawurldecode($m[1]));
596 return fixTitleEncoding(HOME_PAGE);
599 function _deduceAction () {
600 if (!($action = $this->getArg('action'))) {
601 // Detect XML-RPC requests
603 && $this->get('CONTENT_TYPE') == 'text/xml') {
604 global $HTTP_RAW_POST_DATA;
605 if (strstr($HTTP_RAW_POST_DATA, '<methodCall>')) {
610 return 'browse'; // Default if no action specified.
613 if (method_exists($this, "action_$action"))
616 // Allow for, e.g. action=LikePages
617 if ($this->isActionPage($action))
620 trigger_error("$action: Unknown action", E_USER_NOTICE);
624 function _deduceUsername() {
625 global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
627 if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
628 return $this->args['auth']['userid'];
630 if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
631 return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
632 if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
633 return $HTTP_ENV_VARS['REMOTE_USER'];
635 if ($user = $this->getSessionVar('wiki_user')) {
636 $this->_user = $user;
637 $this->_user->_authhow = 'session';
638 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
640 if ($userid = $this->getCookieVar('WIKI_ID')) {
641 if (!empty($userid) and substr($userid,0,2) != 's:') {
642 $this->_user->authhow = 'cookie';
649 function _isActionPage ($pagename) {
650 $dbi = $this->getDbh();
651 $page = $dbi->getPage($pagename);
652 $rev = $page->getCurrentRevision();
653 // FIXME: more restrictive check for sane plugin?
654 if (strstr($rev->getPackedContent(), '<?plugin'))
656 if (!$rev->hasDefaultContents())
657 trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
661 function findActionPage ($action) {
664 // check for translated version, as per users preferred language
665 // (or system default in case it is not en)
666 $translation = gettext($action);
668 if (isset($cache) and isset($cache[$translation]))
669 return $cache[$translation];
671 // check for cached translated version
672 if ($this->_isActionPage($translation))
673 return $cache[$action] = $translation;
675 // Allow for, e.g. action=LikePages
676 global $WikiNameRegexp;
677 if (!preg_match("/$WikiNameRegexp\\Z/A", $action))
678 return $cache[$action] = false;
680 // check for translated version (default language)
682 if ($LANG != DEFAULT_LANGUAGE and $LANG != "en") {
684 //trigger_error("DEBUG: findActionPage() ". DEFAULT_LANGUAGE." calling update_locale()...");
685 update_locale(DEFAULT_LANGUAGE);
686 $default = gettext($action);
687 //trigger_error("DEBUG: findActionPage() ". $save_lang." restoring save_lang, calling update_locale()...");
688 update_locale($save_lang);
689 if ($this->_isActionPage($default))
690 return $cache[$action] = $default;
693 $default = $translation;
696 // check for english version
697 if ($action != $translation and $action != $default) {
698 if ($this->_isActionPage($action))
699 return $cache[$action] = $action;
702 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
703 return $cache[$action] = false;
706 function isActionPage ($pagename) {
707 return $this->findActionPage($pagename);
710 function action_browse () {
711 $this->buffer_output();
712 include_once("lib/display.php");
716 function action_verify () {
717 $this->action_browse();
720 function actionpage ($action) {
721 $this->buffer_output();
722 include_once("lib/display.php");
723 actionPage($this, $action);
726 function action_diff () {
727 $this->buffer_output();
728 include_once "lib/diff.php";
732 function action_search () {
733 // This is obsolete: reformulate URL and redirect.
734 // FIXME: this whole section should probably be deleted.
735 if ($this->getArg('searchtype') == 'full') {
736 $search_page = _("FullTextSearch");
739 $search_page = _("TitleSearch");
741 $this->redirect(WikiURL($search_page,
742 array('s' => $this->getArg('searchterm')),
746 function action_edit () {
747 $this->buffer_output();
748 include "lib/editpage.php";
749 $e = new PageEditor ($this);
753 function action_create () {
754 $this->action_edit();
757 function action_viewsource () {
758 $this->buffer_output();
759 include "lib/editpage.php";
760 $e = new PageEditor ($this);
764 function action_lock () {
765 $page = $this->getPage();
766 $page->set('locked', true);
767 $this->_dbi->touch();
768 $this->action_browse();
771 function action_unlock () {
772 // FIXME: This check is redundant.
773 //$user->requireAuth(WIKIAUTH_ADMIN);
774 $page = $this->getPage();
775 $page->set('locked', false);
776 $this->_dbi->touch();
777 $this->action_browse();
780 function action_remove () {
781 // FIXME: This check is redundant.
782 //$user->requireAuth(WIKIAUTH_ADMIN);
783 $pagename = $this->getArg('pagename');
784 if (strstr($pagename,_('PhpWikiAdministration'))) {
785 $this->action_browse();
787 include('lib/removepage.php');
792 function action_xmlrpc () {
793 include_once("lib/XmlRpcServer.php");
794 $xmlrpc = new XmlRpcServer($this);
798 function action_zip () {
799 include_once("lib/loadsave.php");
801 // I don't think it hurts to add cruft at the end of the zip file.
802 //echo "\n========================================================\n";
803 //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
806 function action_ziphtml () {
807 include_once("lib/loadsave.php");
808 MakeWikiZipHtml($this);
809 // I don't think it hurts to add cruft at the end of the zip file.
810 echo "\n========================================================\n";
811 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
814 function action_dumpserial () {
815 include_once("lib/loadsave.php");
819 function action_dumphtml () {
820 include_once("lib/loadsave.php");
821 DumpHtmlToDir($this);
824 function action_upload () {
825 include_once("lib/loadsave.php");
829 function action_upgrade () {
830 include_once("lib/loadsave.php");
831 include_once("lib/upgrade.php");
835 function action_loadfile () {
836 include_once("lib/loadsave.php");
837 LoadFileOrDir($this);
840 function action_pdf () {
841 include_once("lib/pdf.php");
842 ConvertAndDisplayPdf($this);
848 function is_safe_action ($action) {
849 return WikiRequest::requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
852 function validateSessionPath() {
853 // Try to defer any session.save_path PHP errors before any html
854 // is output, which causes some versions of IE to display a blank
855 // page (due to its strict mode while parsing a page?).
856 if (! is_writeable(ini_get('session.save_path'))) {
859 (sprintf(_("%s is not writable."),
860 _("The session.save_path directory"))
862 . sprintf(_("Please ensure that %s is writable, or redefine %s in index.php."),
863 sprintf(_("the directory '%s'"),
864 ini_get('session.save_path')),
867 . sprintf(_("Attempting to use the directory '%s' instead."),
870 if (! is_writeable($tmpdir)) {
872 (sprintf(_("%s is not writable."), $tmpdir)
874 . _("Users will not be able to sign in.")
878 ini_set('session.save_path', $tmpdir);
884 validateSessionPath();
888 if ((DEBUG & 2) and extension_loaded("apd"))
889 apd_set_session_trace(9);
892 global $ErrorManager;
893 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING);
894 $request = new WikiRequest();
896 $action = $request->getArg('action');
897 if (substr($action, 0, 3) != 'zip') {
898 if ($action == 'pdf')
899 $ErrorManager->setPostponedErrorMask(-1);
900 else // reject postponing of warnings
901 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
905 * Allow for disabling of markup cache.
906 * (Mostly for debugging ... hopefully.)
908 * See also <?plugin WikiAdminUtils action=purge-cache ?>
910 if (!defined('WIKIDB_NOCACHE_MARKUP') and $request->getArg('nocache'))
911 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
913 // Initialize with system defaults in case user not logged in.
914 // Should this go into constructor?
915 $request->initializeTheme();
917 $request->updateAuthAndPrefs();
918 $request->initializeLang();
921 //if ($user->is_authenticated())
922 // $LogEntry->user = $user->getId();
924 $request->possiblyDeflowerVirginWiki();
926 if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
927 if (defined('WIKI_SOAP') and WIKI_SOAP) return;
929 $validators = array('wikiname' => WIKI_NAME,
930 'args' => hash($request->getArgs()),
931 'prefs' => hash($request->getPrefs()));
932 if (CACHE_CONTROL == 'STRICT') {
933 $dbi = $request->getDbh();
934 $timestamp = $dbi->getTimestamp();
935 $validators['mtime'] = $timestamp;
936 $validators['%mtime'] = (int)$timestamp;
938 // FIXME: we should try to generate strong validators when possible,
939 // but for now, our validator is weak, since equal validators do not
940 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
942 // (If DEBUG if off, this may be a strong validator, but I'm going
943 // to go the paranoid route here pending further study and testing.)
945 $validators['%weak'] = true;
946 $request->setValidators($validators);
948 $request->handleAction();
950 if (defined('DEBUG') and DEBUG & 4) phpinfo(INFO_VARIABLES);
954 $x = error_reporting(); // why is it 1 here? should be E_ALL
955 error_reporting(E_ALL);
959 // $Log: not supported by cvs2svn $
960 // Revision 1.152 2004/05/27 17:49:06 rurban
961 // renamed DB_Session to DbSession (in CVS also)
962 // added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
963 // remove leading slash in error message
964 // added force_unlock parameter to File_Passwd (no return on stale locks)
965 // fixed adodb session AffectedRows
966 // added FileFinder helpers to unify local filenames and DATA_PATH names
967 // editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
969 // Revision 1.151 2004/05/25 12:40:48 rurban
972 // Revision 1.150 2004/05/25 10:18:44 rurban
973 // Check for UTF-8 URLs; Internet Explorer produces these if you
974 // type non-ASCII chars in the URL bar or follow unescaped links.
975 // Fixes sf.net bug #953949
976 // src: languages/Language.php:checkTitleEncoding() from mediawiki
978 // Revision 1.149 2004/05/18 13:31:19 rurban
979 // hold warnings until headers are sent. new Error-style with collapsed output of repeated messages
981 // Revision 1.148 2004/05/17 17:43:29 rurban
982 // CGI: no PATH_INFO fix
984 // Revision 1.147 2004/05/15 19:48:33 rurban
985 // fix some too loose PagePerms for signed, but not authenticated users
986 // (admin, owner, creator)
987 // no double login page header, better login msg.
988 // moved action_pdf to lib/pdf.php
990 // Revision 1.146 2004/05/15 18:31:01 rurban
991 // some action=pdf Request fixes: With MSIE it works now. Now the work with the page formatting begins.
993 // Revision 1.145 2004/05/12 10:49:55 rurban
994 // require_once fix for those libs which are loaded before FileFinder and
995 // its automatic include_path fix, and where require_once doesn't grok
996 // dirname(__FILE__) != './lib'
997 // upgrade fix with PearDB
998 // navbar.tmpl: remove spaces for IE button alignment
1000 // Revision 1.144 2004/05/06 19:26:16 rurban
1001 // improve stability, trying to find the InlineParser endless loop on sf.net
1003 // remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
1005 // Revision 1.143 2004/05/06 17:30:38 rurban
1006 // CategoryGroup: oops, dos2unix eol
1007 // improved phpwiki_version:
1008 // pre -= .0001 (1.3.10pre: 1030.099)
1009 // -p1 += .001 (1.3.9-p1: 1030.091)
1010 // improved InstallTable for mysql and generic SQL versions and all newer tables so far.
1011 // abstracted more ADODB/PearDB methods for action=upgrade stuff:
1012 // backend->backendType(), backend->database(),
1013 // backend->listOfFields(),
1014 // backend->listOfTables(),
1016 // Revision 1.142 2004/05/04 22:34:25 rurban
1019 // Revision 1.141 2004/05/03 13:16:47 rurban
1020 // fixed UserPreferences update, esp for boolean and int
1022 // Revision 1.140 2004/05/02 21:26:38 rurban
1023 // limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
1024 // because they will not survive db sessions, if too large.
1025 // extended action=upgrade
1026 // some WikiTranslation button work
1027 // revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
1028 // some temp. session debug statements
1030 // Revision 1.139 2004/05/02 15:10:07 rurban
1031 // new finally reliable way to detect if /index.php is called directly
1032 // and if to include lib/main.php
1033 // new global AllActionPages
1034 // SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
1035 // WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
1036 // PageGroupTestOne => subpages
1037 // renamed PhpWikiRss to PhpWikiRecentChanges
1038 // more docs, default configs, ...
1040 // Revision 1.138 2004/05/01 15:59:29 rurban
1041 // more php-4.0.6 compatibility: superglobals
1043 // Revision 1.137 2004/04/29 19:39:44 rurban
1044 // special support for formatted plugins (one-liners)
1045 // like <small><plugin BlaBla ></small>
1046 // iter->asArray() helper for PopularNearby
1047 // db_session for older php's (no &func() allowed)
1049 // Revision 1.136 2004/04/29 17:18:19 zorloc
1050 // Fixes permission failure issues. With PagePermissions and Disabled Actions when user did not have permission WIKIAUTH_FORBIDDEN was returned. In WikiUser this was ok because WIKIAUTH_FORBIDDEN had a value of 11 -- thus no user could perform that action. But WikiUserNew has a WIKIAUTH_FORBIDDEN value of -1 -- thus a user without sufficent permission to do anything. The solution is a new high value permission level (WIKIAUTH_UNOBTAINABLE) to be the default level for access failure.
1052 // Revision 1.135 2004/04/26 12:15:01 rurban
1053 // check default config values
1055 // Revision 1.134 2004/04/23 06:46:37 zorloc
1056 // Leave DB connection open when USE_DB_SESSION is true so that session info can be written to the DB.
1058 // Revision 1.133 2004/04/20 18:10:31 rurban
1059 // config refactoring:
1060 // FileFinder is needed for WikiFarm scripts calling index.php
1061 // config run-time calls moved to lib/IniConfig.php:fix_configs()
1062 // added PHPWIKI_DIR smart-detection code (Theme finder)
1063 // moved FileFind to lib/FileFinder.php
1064 // cleaned lib/config.php
1066 // Revision 1.132 2004/04/19 21:51:41 rurban
1067 // php5 compatibility: it works!
1069 // Revision 1.131 2004/04/19 18:27:45 rurban
1070 // Prevent from some PHP5 warnings (ref args, no :: object init)
1071 // php5 runs now through, just one wrong XmlElement object init missing
1072 // Removed unneccesary UpgradeUser lines
1073 // Changed WikiLink to omit version if current (RecentChanges)
1075 // Revision 1.130 2004/04/18 00:25:53 rurban
1076 // allow "0" pagename
1078 // Revision 1.129 2004/04/07 23:13:19 rurban
1079 // fixed pear/File_Passwd for Windows
1080 // fixed FilePassUser sessions (filehandle revive) and password update
1082 // Revision 1.128 2004/04/02 15:06:55 rurban
1083 // fixed a nasty ADODB_mysql session update bug
1084 // improved UserPreferences layout (tabled hints)
1085 // fixed UserPreferences auth handling
1086 // improved auth stability
1087 // improved old cookie handling: fixed deletion of old cookies with paths
1089 // Revision 1.127 2004/03/25 17:00:31 rurban
1090 // more code to convert old-style pref array to new hash
1092 // Revision 1.126 2004/03/24 19:39:03 rurban
1093 // php5 workaround code (plus some interim debugging code in XmlElement)
1094 // php5 doesn't work yet with the current XmlElement class constructors,
1095 // WikiUserNew does work better than php4.
1096 // rewrote WikiUserNew user upgrading to ease php5 update
1097 // fixed pref handling in WikiUserNew
1098 // added Email Notification
1099 // added simple Email verification
1100 // removed emailVerify userpref subclass: just a email property
1101 // changed pref binary storage layout: numarray => hash of non default values
1102 // print optimize message only if really done.
1103 // forced new cookie policy: delete pref cookies, use only WIKI_ID as plain string.
1104 // prefs should be stored in db or homepage, besides the current session.
1106 // Revision 1.125 2004/03/14 16:30:52 rurban
1107 // db-handle session revivification, dba fixes
1109 // Revision 1.124 2004/03/12 15:48:07 rurban
1110 // fixed explodePageList: wrong sortby argument order in UnfoldSubpages
1111 // simplified lib/stdlib.php:explodePageList
1113 // Revision 1.123 2004/03/10 15:41:27 rurban
1114 // use default pref mysql table
1116 // Revision 1.122 2004/03/08 18:17:09 rurban
1117 // added more WikiGroup::getMembersOf methods, esp. for special groups
1118 // fixed $LDAP_SET_OPTIONS
1119 // fixed _AuthInfo group methods
1121 // Revision 1.121 2004/03/01 13:48:45 rurban
1123 // p[] consistency fix
1125 // Revision 1.120 2004/03/01 10:22:41 rurban
1126 // initializeTheme optimize
1128 // Revision 1.119 2004/02/26 20:45:06 rurban
1129 // check for ALLOW_ANON_USER = false
1131 // Revision 1.118 2004/02/26 01:32:03 rurban
1132 // fixed session login with old WikiUser object. strangely, the errormask gets corruoted to 1, Pear???
1134 // Revision 1.117 2004/02/24 17:19:37 rurban
1135 // debugging helpers only
1137 // Revision 1.116 2004/02/24 15:17:14 rurban
1138 // improved auth errors with individual pages. the fact that you may not browse a certain admin page does not conclude that you may not browse the whole wiki. renamed browse => view
1140 // Revision 1.115 2004/02/15 21:34:37 rurban
1141 // PageList enhanced and improved.
1142 // fixed new WikiAdmin... plugins
1143 // editpage, Theme with exp. htmlarea framework
1144 // (htmlarea yet committed, this is really questionable)
1145 // WikiUser... code with better session handling for prefs
1146 // enhanced UserPreferences (again)
1147 // RecentChanges for show_deleted: how should pages be deleted then?
1149 // Revision 1.114 2004/02/15 17:30:13 rurban
1150 // workaround for lost db connnection handle on session restauration (->_auth_dbi)
1151 // fixed getPreferences() (esp. from sessions)
1152 // fixed setPreferences() (update and set),
1153 // fixed AdoDb DB statements,
1154 // update prefs only at UserPreferences POST (for testing)
1155 // unified db prefs methods (but in external pref classes yet)
1157 // Revision 1.113 2004/02/12 13:05:49 rurban
1158 // Rename functional for PearDB backend
1159 // some other minor changes
1160 // SiteMap comes with a not yet functional feature request: includepages (tbd)
1162 // Revision 1.112 2004/02/09 03:58:12 rurban
1163 // for now default DB_SESSION to false
1165 // * not existing perms will now query the parent, and not
1166 // return the default perm
1167 // * added pagePermissions func which returns the object per page
1168 // * added getAccessDescription
1170 // * added global ->prepare (not yet used) with smart user/pref/member table prefixing.
1171 // * force init of authdbh in the 2 db classes
1173 // * fixed session handling (not triple auth request anymore)
1174 // * don't store cookie prefs with sessions
1175 // stdlib: global obj2hash helper from _AuthInfo, also needed for PagePerm
1177 // Revision 1.111 2004/02/07 10:41:25 rurban
1178 // fixed auth from session (still double code but works)
1180 // fixed DbPassUser upgrade and policy=old
1183 // Revision 1.110 2004/02/03 09:45:39 rurban
1184 // LDAP cleanup, start of new Pref classes
1186 // Revision 1.109 2004/01/30 19:57:58 rurban
1187 // fixed DBAuthParams['pref_select']: wrong _auth_dbi object used.
1189 // Revision 1.108 2004/01/28 14:34:14 rurban
1190 // session table takes the common prefix
1191 // + various minor stuff
1192 // reallow password changing
1194 // Revision 1.107 2004/01/27 23:23:39 rurban
1195 // renamed ->Username => _userid for consistency
1196 // renamed mayCheckPassword => mayCheckPass
1197 // fixed recursion problem in WikiUserNew
1198 // fixed bogo login (but not quite 100% ready yet, password storage)
1200 // Revision 1.106 2004/01/26 09:17:49 rurban
1201 // * changed stored pref representation as before.
1202 // the array of objects is 1) bigger and 2)
1203 // less portable. If we would import packed pref
1204 // objects and the object definition was changed, PHP would fail.
1205 // This doesn't happen with an simple array of non-default values.
1206 // * use $prefs->retrieve and $prefs->store methods, where retrieve
1207 // understands the interim format of array of objects also.
1208 // * simplified $prefs->get() and fixed $prefs->set()
1209 // * added $user->_userid and class '_WikiUser' portability functions
1210 // * fixed $user object ->_level upgrading, mostly using sessions.
1211 // this fixes yesterdays problems with loosing authorization level.
1212 // * fixed WikiUserNew::checkPass to return the _level
1213 // * fixed WikiUserNew::isSignedIn
1214 // * added explodePageList to class PageList, support sortby arg
1215 // * fixed UserPreferences for WikiUserNew
1216 // * fixed WikiPlugin for empty defaults array
1217 // * UnfoldSubpages: added pagename arg, renamed pages arg,
1218 // removed sort arg, support sortby arg
1220 // Revision 1.105 2004/01/25 03:57:15 rurban
1221 // WikiUserNew support (temp. ENABLE_USER_NEW constant)
1223 // Revision 1.104 2003/12/26 06:41:16 carstenklapp
1224 // Bugfix: Try to defer OS errors about session.save_path and ACCESS_LOG,
1225 // so they don't prevent IE from partially (or not at all) rendering the
1226 // page. This should help a little for the IE user who encounters trouble
1227 // when setting up a new PhpWiki for the first time.
1229 // Revision 1.103 2003/12/02 00:10:00 carstenklapp
1230 // Bugfix: Ongoing work to untangle UserPreferences/WikiUser/request code
1231 // mess: UserPreferences should take effect immediately now upon signing
1234 // Revision 1.102 2003/11/25 22:55:32 carstenklapp
1235 // Localization bugfix: For wikis where English is not the default system
1236 // language, make sure that the authority error message (i.e. "You must
1237 // sign in to edit pages in this wiki" etc.) is displayed in the wiki's
1238 // default language. Previously it would always display in English.
1239 // (Added call to update_locale() before displaying any messages prior to
1240 // the login prompt.)
1242 // Revision 1.101 2003/11/25 21:49:44 carstenklapp
1243 // Bugfix: For a non-english wiki or when the user's preference is not
1244 // english, the wiki would always use the english ActionPage first if it
1245 // was present rather than the appropriate localised variant. (PhpWikis
1246 // running only in english or Wikis running ONLY without any english
1247 // ActionPages would not notice this bug, only when both english and
1248 // localised ActionPages were in the DB.) Now we check for the localised
1251 // Revision 1.100 2003/11/18 16:54:18 carstenklapp
1252 // Reformatting only: Tabs to spaces, added rcs log.
1259 // c-basic-offset: 4
1260 // c-hanging-comment-ender-p: nil
1261 // indent-tabs-mode: nil