2 rcs_id('$Id: main.php,v 1.242 2008/02/14 18:27:49 rurban Exp $');
4 Copyright 1999-2007 $ThePhpWikiProgrammingTeam
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 define ('USE_PREFS_IN_PAGE', true);
25 //include "lib/config.php";
26 require_once(dirname(__FILE__)."/stdlib.php");
27 require_once('lib/Request.php');
28 require_once('lib/WikiDB.php');
30 require_once("lib/WikiUserNew.php");
32 require_once("lib/WikiUser.php");
33 require_once("lib/WikiGroup.php");
35 require_once("lib/PagePerm.php");
38 * Check permission per page.
39 * Returns true or false.
41 function mayAccessPage ($access, $pagename) {
43 return _requiredAuthorityForPagename($access, $pagename); // typically [10-20ms per page]
48 class WikiRequest extends Request {
51 function WikiRequest () {
52 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
53 // first mysql request costs [958ms]! [670ms] is mysql_connect()
55 if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
56 // force our local copy, until the pear version is fixed.
57 include_once(dirname(__FILE__)."/pear/File_Passwd.php");
59 if (ENABLE_USER_NEW) {
60 // Preload all necessary userclasses. Otherwise session => __PHP_Incomplete_Class_Name
61 // There's no way to demand-load it later. This way it's much slower, but needs slightly
62 // less memory than loading all.
64 include_once("lib/WikiUser/BogoLogin.php");
65 // UserPreferences POST Update doesn't reach this.
66 foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
67 include_once("lib/WikiUser/$method.php");
69 switch( DATABASE_TYPE ) {
70 case 'SQL' : include_once("lib/WikiUser/PearDb.php"); break;
71 case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break;
72 case 'PDO' : include_once("lib/WikiUser/PdoDb.php"); break;
78 include_once('lib/DbSession.php');
80 $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix')
81 . $dbi->getParam('db_session_table'));
84 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
85 //$x = error_reporting();
87 $this->version = phpwiki_version();
88 $this->Request(); // [90ms]
91 $this->setArg('pagename', $this->_deducePagename());
92 $this->setArg('action', $this->_deduceAction());
94 if ((DEBUG & _DEBUG_SQL)
95 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
96 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
97 if ($this->_dbi->_backend->optimize())
98 trigger_error(_("Optimizing database"), E_USER_NOTICE);
101 // Restore auth state. This doesn't check for proper authorization!
102 $userid = $this->_deduceUsername();
103 if (ENABLE_USER_NEW) {
104 if (isset($this->_user) and
105 !empty($this->_user->_authhow) and
106 $this->_user->_authhow == 'session')
108 // users might switch in a session between the two objects.
109 // restore old auth level here or in updateAuthAndPrefs?
110 //$user = $this->getSessionVar('wiki_user');
111 // revive db handle, because these don't survive sessions
112 if (isset($this->_user) and
113 ( ! isa($this->_user, WikiUserClassname())
114 or (strtolower(get_class($this->_user)) == '_passuser')
115 or (strtolower(get_class($this->_user)) == '_gforgepassuser')))
117 $this->_user = WikiUser($userid, $this->_user->_prefs);
119 // revive other db handle
120 if (isset($this->_user->_prefs->_method)
121 and ($this->_user->_prefs->_method == 'SQL'
122 or $this->_user->_prefs->_method == 'ADODB'
123 or $this->_user->_prefs->_method == 'PDO'
124 or $this->_user->_prefs->_method == 'HomePage')) {
125 $this->_user->_HomePagehandle = $this->getPage($userid);
127 // need to update the lockfile filehandle
128 if ( isa($this->_user, '_FilePassUser')
129 and $this->_user->_file->lockfile
130 and !$this->_user->_file->fplock )
132 //$level = $this->_user->_level;
133 $this->_user = UpgradeUser($this->_user,
134 new _FilePassUser($userid,
135 $this->_user->_prefs,
136 $this->_user->_file->filename));
137 //$this->_user->_level = $level;
139 $this->_prefs = & $this->_user->_prefs;
141 $user = WikiUser($userid);
142 $this->_user = & $user;
143 $this->_prefs = & $this->_user->_prefs;
146 $this->_user = new WikiUser($this, $userid);
147 $this->_prefs = $this->_user->getPreferences();
151 function initializeLang () {
152 // check non-default pref lang
153 $_lang = @$this->_prefs->_prefs['lang'];
154 if (isset($_lang->lang) and $_lang->lang != $GLOBALS['LANG']) {
155 $user_lang = $_lang->lang;
156 //check changed LANG and THEME inside a session.
157 // (e.g. by using another baseurl)
158 if (isset($this->_user->_authhow) and $this->_user->_authhow == 'session')
159 $user_lang = $GLOBALS['LANG'];
160 update_locale($user_lang);
161 FindLocalizedButtonFile(".",'missing_ok','reinit');
165 function initializeTheme ($when = 'default') {
167 // if when = 'default', then first time init (default theme, ...)
168 // if when = 'login', then check some callbacks
169 // and maybe the theme changed (other theme defined in pref)
170 // if when = 'logout', then check other callbacks
171 // and maybe the theme changed (back to default theme)
173 // Load non-default theme (when = login)
174 $_theme = @$this->_prefs->_prefs['theme'];
175 if ($_theme and isset($_theme->theme))
176 $user_theme = $_theme->theme;
178 $user_theme = $this->getPref('theme');
180 //check changed LANG and THEME inside a session.
181 // (e.g. by using another baseurl)
182 if (isset($this->_user->_authhow)
183 and $this->_user->_authhow == 'session'
184 and !isset($_theme->theme)
186 and $user_theme != THEME)
188 include_once("themes/" . THEME . "/themeinfo.php");
190 if (empty($WikiTheme) and isset($user_theme)) {
191 if (strcspn($user_theme,"./\x00]") != strlen($user_theme)) {
192 trigger_error(sprintf("invalid theme '%s': Invalid characters detected", $user_theme),
194 $user_theme = "default";
196 include_once("themes/$user_theme/themeinfo.php");
198 if (empty($WikiTheme) and defined('THEME'))
199 include_once("themes/" . THEME . "/themeinfo.php");
200 if (empty($WikiTheme))
201 include_once("themes/default/themeinfo.php");
202 assert(!empty($WikiTheme));
204 // Do not execute global init code anymore
207 if ($when == 'login') {
208 $WikiTheme->CbUserLogin($this, $this->_user->_userid);
209 if (!$this->_user->hasHomePage()) { // NewUser
210 $WikiTheme->CbNewUserLogin($this, $this->_user->_userid);
211 if (in_array($this->getArg('action'), array('edit','create')))
212 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
215 elseif ($when == 'logout') {
216 $WikiTheme->CbUserLogout($this, $this->_user->_userid);
218 elseif ($when == 'default') {
220 if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser
221 if (in_array($this->getArg('action'), array('edit','create')))
222 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
227 // This really maybe should be part of the constructor, but since it
228 // may involve HTML/template output, the global $request really needs
229 // to be initialized before we do this stuff.
230 // [50ms]: 36ms if wikidb_page::exists
231 function updateAuthAndPrefs () {
233 if (isset($this->_user) and (!isa($this->_user, WikiUserClassname()))) {
234 $this->_user = false;
236 // Handle authentication request, if any.
237 if ($auth_args = $this->getArg('auth')) {
238 $this->setArg('auth', false);
239 $this->_handleAuthRequest($auth_args); // possible NORETURN
241 elseif ( ! $this->_user
242 or (isa($this->_user, WikiUserClassname())
243 and ! $this->_user->isSignedIn())) {
244 // If not auth request, try to sign in as saved user.
245 if (($saved_user = $this->getPref('userid')) != false) {
246 $this->_signIn($saved_user);
250 $action = $this->getArg('action');
252 // Save preferences in session and cookie
253 if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') {
254 if (isset($this->_user) and $this->_user->_userid) {
255 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
256 $this->_user->setPreferences($this->_prefs, true);
259 $this->setSessionVar('wiki_user', $this->_user);
262 // Ensure user has permissions for action
263 // HACK ALERT: We may not set the request arg to create,
264 // since the pageeditor has an ugly logic for action == create.
265 if ($action == 'edit' or $action == 'create') {
266 $page = $this->getPage();
267 if (! $page->exists() )
272 if (! ENABLE_PAGEPERM) { // Bug #1438392 by Matt Brown
273 $require_level = $this->requiredAuthority($action);
274 if (! $this->_user->hasAuthority($require_level))
275 $this->_notAuthorized($require_level); // NORETURN
277 // novatrope patch to let only _AUTHENTICATED view pages.
278 // If there's not enough authority or forbidden, ask for a password,
279 // unless it's explicitly unobtainable. Some bad magic though.
280 if ($this->requiredAuthorityForAction($action) == WIKIAUTH_UNOBTAINABLE) {
281 $require_level = $this->requiredAuthority($action);
282 $this->_notAuthorized($require_level); // NORETURN
287 function & getUser () {
288 if (isset($this->_user))
291 return $GLOBALS['ForbiddenUser'];
294 function & getGroup () {
295 if (isset($this->_user) and isset($this->_user->_group))
296 return $this->_user->_group;
298 // Debug Strict: Only variable references should be returned by reference
299 $this->_user->_group = WikiGroup::getGroup();
300 return $this->_user->_group;
304 function & getPrefs () {
305 return $this->_prefs;
308 // Convenience function:
309 function getPref ($key) {
310 if (isset($this->_prefs)) {
311 return $this->_prefs->get($key);
314 function & getDbh () {
319 * Get requested page from the page database.
320 * By default it will grab the page requested via the URL
322 * This is a convenience function.
323 * @param string $pagename Name of page to get.
324 * @return WikiDB_Page Object with methods to pull data from
325 * database for the page requested.
327 function getPage ($pagename = false) {
328 //if (!isset($this->_dbi)) $this->getDbh();
330 $pagename = $this->getArg('pagename');
331 return $this->_dbi->getPage($pagename);
334 /** Get URL for POST actions.
336 * Officially, we should just use SCRIPT_NAME (or some such),
337 * but that causes problems when we try to issue a redirect, e.g.
338 * after saving a page.
340 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
341 * a redirect from a page to itself.)
343 * So, as a HACK, we include pagename and action as query args in
344 * the URL. (These should be ignored when we receive the POST
347 function getPostURL ($pagename = false) {
348 global $HTTP_GET_VARS;
350 if ($pagename === false)
351 $pagename = $this->getArg('pagename');
352 $action = $this->getArg('action');
353 if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
354 return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
355 elseif ($action == 'edit')
356 return WikiURL($pagename);
358 return WikiURL($pagename, array('action' => $action));
361 function _handleAuthRequest ($auth_args) {
362 if (!is_array($auth_args))
365 // Ignore password unless POST'ed.
366 if (!$this->isPost())
367 unset($auth_args['passwd']);
369 $olduser = $this->_user;
370 $user = $this->_user->AuthCheck($auth_args);
371 if (is_string($user)) {
372 // Login attempt failed.
373 $fail_message = $user;
374 $auth_args['pass_required'] = true;
375 // if clicked just on to the "sign in as:" button dont print invalid username.
376 if (!empty($auth_args['login']) and empty($auth_args['userid']))
378 // If no password was submitted, it's not really
379 // a failure --- just need to prompt for password...
380 if (!ALLOW_USER_PASSWORDS
382 and !isset($auth_args['passwd']))
384 $fail_message = false;
386 $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
387 $this->finish(); //NORETURN
389 elseif (isa($user, WikiUserClassname())) {
390 // Successful login (or logout.)
391 $this->_setUser($user);
394 // Login request cancelled.
399 * Attempt to sign in (bogo-login).
403 * @param $userid string Userid to attempt to sign in as.
406 function _signIn ($userid) {
407 if (ENABLE_USER_NEW) {
409 $this->_user = new _BogoUser($userid);
410 // FIXME: is this always false? shouldn't we try passuser first?
412 $this->_user = new _PassUser($userid);
415 $this->_user = new WikiUser($this, $userid);
417 $user = $this->_user->AuthCheck(array('userid' => $userid));
418 if (isa($user, WikiUserClassname())) {
419 $this->_setUser($user); // success!
423 // login or logout or restore state
424 function _setUser (&$user) {
425 $this->_user =& $user;
426 if (defined('MAIN_setUser')) return; // don't set cookies twice
427 $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(),
428 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
429 $isSignedIn = $user->isSignedIn();
431 $user->_authhow = 'signin';
434 // Save userid to prefs..
435 if ( empty($this->_user->_prefs)) {
436 $this->_user->_prefs = $this->_user->getPreferences();
437 $this->_prefs =& $this->_user->_prefs;
439 $this->_user->_group = $this->getGroup();
440 $this->setSessionVar('wiki_user', $user);
441 $this->_prefs->set('userid',
442 $isSignedIn ? $user->getId() : '');
443 if (!ENABLE_USER_NEW) {
444 if (empty($this->_user->_request))
445 $this->_user->_request =& $this;
446 if (empty($this->_user->_dbi))
447 $this->_user->_dbi =& $this->_dbi;
449 $this->initializeTheme($isSignedIn ? 'login' : 'logout');
450 define('MAIN_setUser', true);
453 /* Permission system */
454 function getLevelDescription($level) {
455 static $levels = false;
456 if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0"
457 $levels = array('x-1' => _("FORBIDDEN"),
462 'x100'=> _("UNOBTAINABLE"));
465 if (!empty($levels["x".$level]))
466 return $levels["x".$level];
471 function _notAuthorized ($require_level) {
472 // Display the authority message in the Wiki's default
473 // language, in case it is not english.
475 // Note that normally a user will not see such an error once
476 // logged in, unless the admin has altered the default
477 // disallowed wikiactions. In that case we should probably
478 // check the user's language prefs too at this point; this
479 // would be a situation which is not really handled with the
481 if (empty($GLOBALS['LANG']))
482 update_locale(DEFAULT_LANGUAGE);
484 // User does not have required authority. Prompt for login.
485 $what = $this->getActionDescription($this->getArg('action'));
486 $pass_required = ($require_level >= WIKIAUTH_USER);
487 if ($require_level == WIKIAUTH_UNOBTAINABLE) {
488 global $DisabledActions;
489 if ($DisabledActions and in_array($action, $DisabledActions)) {
490 $msg = fmt("%s is disallowed on this wiki.",
491 $this->getDisallowedActionDescription($this->getArg('action')));
495 // Is the reason a missing ACL or just wrong user or password?
496 if (class_exists('PagePermission')) {
497 $user =& $this->_user;
498 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
499 $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).",
500 _("Missing PagePermission:"),
501 action2access($this->getArg('action')),
502 $this->getArg('pagename'),
503 $status, $user->getId(), $this->getLevelDescription($user->_level));
504 // TODO: add link to action=setacl
505 $user->PrintLoginForm($this, compact('pass_required'), $msg);
509 $msg = fmt("%s is disallowed on this wiki.",
510 $this->getDisallowedActionDescription($this->getArg('action')));
511 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
516 elseif ($require_level == WIKIAUTH_BOGO)
517 $msg = fmt("You must sign in to %s.", $what);
518 elseif ($require_level == WIKIAUTH_USER) {
519 if (!ALLOW_ANON_USER)
520 $msg = fmt("You must log in first to %s", $what);
522 $msg = fmt("You must log in to %s.", $what);
523 } elseif ($require_level == WIKIAUTH_ANON)
524 $msg = fmt("Access for you is forbidden to %s.", $what);
526 $msg = fmt("You must be an administrator to %s.", $what);
528 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'),
530 if (!$GLOBALS['WikiTheme']->DUMP_MODE)
531 $this->finish(); // NORETURN
534 // Fixme: for PagePermissions we'll need other strings,
535 // relevant to the requested page, not just for the action on the whole wiki.
536 function getActionDescription($action) {
537 static $actionDescriptions;
538 if (! $actionDescriptions) {
540 = array('browse' => _("view this page"),
541 'diff' => _("diff this page"),
542 'dumphtml' => _("dump html pages"),
543 'dumpserial' => _("dump serial pages"),
544 'edit' => _("edit this page"),
545 'rename' => _("rename this page"),
546 'revert' => _("revert to a previous version of this page"),
547 'create' => _("create this page"),
548 'loadfile' => _("load files into this wiki"),
549 'lock' => _("lock this page"),
550 'purge' => _("purge this page"),
551 'remove' => _("remove this page"),
552 'unlock' => _("unlock this page"),
553 'upload' => _("upload a zip dump"),
554 'verify' => _("verify the current action"),
555 'viewsource' => _("view the source of this page"),
556 'xmlrpc' => _("access this wiki via XML-RPC"),
557 'soap' => _("access this wiki via SOAP"),
558 'zip' => _("download a zip dump from this wiki"),
559 'ziphtml' => _("download a html zip dump from this wiki")
562 if (in_array($action, array_keys($actionDescriptions)))
563 return $actionDescriptions[$action];
565 return _("use")." ".$action;
569 TODO: check against these cases:
570 if ($DisabledActions and in_array($action, $DisabledActions))
571 return WIKIAUTH_UNOBTAINABLE;
573 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
574 return requiredAuthorityForPage($action);
576 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
578 function getDisallowedActionDescription($action) {
579 static $disallowedActionDescriptions;
581 if (! $disallowedActionDescriptions) {
582 $disallowedActionDescriptions
583 = array('browse' => _("Browsing pages"),
584 'diff' => _("Diffing pages"),
585 'dumphtml' => _("Dumping html pages"),
586 'dumpserial' => _("Dumping serial pages"),
587 'edit' => _("Editing pages"),
588 'revert' => _("Reverting to a previous version of pages"),
589 'create' => _("Creating pages"),
590 'loadfile' => _("Loading files"),
591 'lock' => _("Locking pages"),
592 'purge' => _("Purging pages"),
593 'remove' => _("Removing pages"),
594 'unlock' => _("Unlocking pages"),
595 'upload' => _("Uploading zip dumps"),
596 'verify' => _("Verify the current action"),
597 'viewsource' => _("Viewing the source of pages"),
598 'xmlrpc' => _("XML-RPC access"),
599 'soap' => _("SOAP access"),
600 'zip' => _("Downloading zip dumps"),
601 'ziphtml' => _("Downloading html zip dumps")
604 if (in_array($action, array_keys($disallowedActionDescriptions)))
605 return $disallowedActionDescriptions[$action];
610 function requiredAuthority ($action) {
611 $auth = $this->requiredAuthorityForAction($action);
612 if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
615 * This is a hook for plugins to require authority
616 * for posting to them.
618 * IMPORTANT: This is not a secure check, so the plugin
619 * may not assume that any POSTs to it are authorized.
620 * All this does is cause PhpWiki to prompt for login
621 * if the user doesn't have the required authority.
623 if ($this->isPost()) {
624 $post_auth = $this->getArg('require_authority_for_post');
625 if ($post_auth !== false)
626 $auth = max($auth, $post_auth);
631 function requiredAuthorityForAction ($action) {
632 global $DisabledActions;
634 if ($DisabledActions and in_array($action, $DisabledActions))
635 return WIKIAUTH_UNOBTAINABLE;
637 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
638 return requiredAuthorityForPage($action);
651 return WIKIAUTH_ANON;
656 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
657 return WIKIAUTH_ADMIN;
658 return WIKIAUTH_ANON;
662 return WIKIAUTH_ADMIN;
663 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
664 return WIKIAUTH_ADMIN;
665 return WIKIAUTH_ANON;
668 if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
669 return WIKIAUTH_ANON;
670 return WIKIAUTH_ADMIN;
674 return WIKIAUTH_ADMIN;
675 return WIKIAUTH_ANON;
680 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
681 return WIKIAUTH_BOGO;
682 return WIKIAUTH_ANON;
683 // return WIKIAUTH_BOGO;
686 $page = $this->getPage();
687 $current = $page->getCurrentRevision();
688 if ($current->hasDefaultContents())
689 return $this->requiredAuthorityForAction('edit');
690 return $this->requiredAuthorityForAction('browse');
701 return WIKIAUTH_ADMIN;
703 /* authcheck occurs only in the plugin.
704 required actionpage RateIt */
707 case 'delete_rating':
708 // Perhaps this should be WIKIAUTH_USER
709 return WIKIAUTH_BOGO;
713 global $WikiNameRegexp;
714 if (preg_match("/$WikiNameRegexp\Z/A", $action))
715 return WIKIAUTH_ANON; // ActionPage.
717 return WIKIAUTH_ADMIN;
721 /* End of Permission system */
723 function possiblyDeflowerVirginWiki () {
724 if ($this->getArg('action') != 'browse')
726 if ($this->getArg('pagename') != HOME_PAGE)
729 $page = $this->getPage();
730 $current = $page->getCurrentRevision();
731 if ($current->getVersion() > 0)
732 return; // Homepage exists.
734 include_once('lib/loadsave.php');
736 $this->finish(); // NORETURN
739 // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
740 function handleAction () {
741 $action = $this->getArg('action');
743 and !$this->_user->isAdmin()
744 and $action != 'browse'
745 and $action != 'wikitohtml'
748 $page = $this->getPage();
749 if ( $page->get('moderation') ) {
750 require_once("lib/WikiPlugin.php");
751 $loader = new WikiPluginLoader();
752 $plugin = $loader->getPlugin("ModeratedPage");
753 if ($plugin->handler($this, $page)) {
756 array('class' => 'wiki-edithelp'),
757 fmt("%s: action forwarded to a moderator.",
760 _("This action requires moderator approval. Please be patient."));
761 if (!empty($plugin->_tokens['CONTENT']))
762 $plugin->_tokens['CONTENT']->pushContent
765 _("You must wait for moderator approval."));
767 $plugin->_tokens['CONTENT'] = $CONTENT;
768 require_once("lib/Template.php");
769 $title = WikiLink($page->getName());
770 $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
771 GeneratePage(Template('browse', $plugin->_tokens),
773 $page->getCurrentRevision());
778 $method = "action_$action";
779 if (method_exists($this, $method)) {
782 elseif ($page = $this->findActionPage($action)) {
783 $this->actionpage($page);
786 $this->finish(fmt("%s: Bad action", $action));
790 function finish ($errormsg = false) {
794 exit(); // just in case CloseDataBase calls us
797 global $ErrorManager;
798 $ErrorManager->flushPostponedErrors();
800 if (!empty($errormsg)) {
803 HTML::h2(_("Fatal PhpWiki Error")),
806 echo "\n</body></html>";
808 if (is_object($this->_user)) {
809 $this->_user->page = $this->getArg('pagename');
810 $this->_user->action = $this->getArg('action');
811 unset($this->_user->_HomePagehandle);
812 unset($this->_user->_auth_dbi);
819 * Generally pagename is rawurlencoded for older browsers or mozilla.
820 * Typing a pagename into the IE bar will utf-8 encode it, so we have to
821 * fix that with fixTitleEncoding().
822 * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
823 * If false, we support either "/index.php?pagename=PageName&arg=value",
824 * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
826 function _deducePagename () {
827 if (trim(rawurldecode($this->getArg('pagename'))))
828 return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
831 $pathinfo = $this->get('PATH_INFO');
832 if (empty($pathinfo)) { // fix for CGI
833 $path = $this->get('REQUEST_URI');
834 $script = $this->get('SCRIPT_NAME');
835 $pathinfo = substr($path,strlen($script));
836 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
838 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
840 if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
841 return fixTitleEncoding($tail);
844 elseif ($this->isPost()) {
846 * In general, for security reasons, HTTP_GET_VARS should be ignored
847 * on POST requests, but we make an exception here (only for pagename).
849 * The justification for this hack is the following
850 * asymmetry: When POSTing with USE_PATH_INFO set, the
851 * pagename can (and should) be communicated through the
852 * request URL via PATH_INFO. When POSTing with
853 * USE_PATH_INFO off, this cannot be done --- the only way
854 * to communicate the pagename through the URL is via
855 * QUERY_ARGS (HTTP_GET_VARS).
857 global $HTTP_GET_VARS;
858 if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) {
859 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
864 * Support for PhpWiki 1.2 style requests.
865 * Strip off "&" args (?PageName&action=...&start_debug,...)
867 $query_string = $this->get('QUERY_STRING');
868 if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
869 return fixTitleEncoding(rawurldecode($m[1]));
872 return fixTitleEncoding(HOME_PAGE);
875 function _deduceAction () {
876 if (!($action = $this->getArg('action'))) {
877 // TODO: improve this SOAP.php hack by letting SOAP use index.php
878 // or any other virtual url as with xmlrpc
879 if (defined('WIKI_SOAP') and WIKI_SOAP)
881 // Detect XML-RPC requests.
883 && ($this->get('CONTENT_TYPE') == 'text/xml'
884 or $this->get('CONTENT_TYPE') == 'application/xml')
885 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>')
890 return 'browse'; // Default if no action specified.
893 if (method_exists($this, "action_$action"))
896 // Allow for, e.g. action=LikePages
897 if ($this->isActionPage($action))
900 // Handle untranslated actionpages in non-english
901 // (people playing with switching languages)
902 if (0 and $GLOBALS['LANG'] != 'en') {
903 require_once("lib/plugin/_WikiTranslation.php");
904 $trans = new WikiPlugin__WikiTranslation();
905 $en_action = $trans->translate($action,'en',$GLOBALS['LANG']);
906 if ($this->isActionPage($en_action))
910 trigger_error("$action: Unknown action", E_USER_NOTICE);
914 function _deduceUsername() {
915 global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
917 if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
918 return $this->args['auth']['userid'];
920 if ($user = $this->getSessionVar('wiki_user')) {
921 // Switched auth between sessions.
922 // Note: There's no way to demandload a missing class-definition
923 // afterwards! Stupid php.
925 // ape: If the user is authentified (PHP_AUTH_USER) do not return the current
926 // user information from session (it may now have new auth rights).
927 if (isa($user, WikiUserClassname()) && empty($HTTP_SERVER_VARS['PHP_AUTH_USER'])) {
928 $this->_user = $user;
929 $this->_user->_authhow = 'session';
930 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
934 // Sessions override http auth
935 if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
936 return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
938 if (!empty($HTTP_SERVER_VARS['REMOTE_USER']))
939 return $HTTP_SERVER_VARS['REMOTE_USER'];
940 if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
941 return $HTTP_ENV_VARS['REMOTE_USER'];
943 if ($userid = $this->getCookieVar(getCookieName())) {
944 if (!empty($userid) and substr($userid,0,2) != 's:') {
945 $this->_user->authhow = 'cookie';
950 if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
951 if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
952 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
953 // wiki.putPage has special otional userid/passwd arguments. check that later.
955 if (isset($HTTP_SERVER_VARS['REMOTE_USER']))
956 $userid = $HTTP_SERVER_VARS['REMOTE_USER'];
957 elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
958 $userid = $HTTP_SERVER_VARS['REMOTE_ADDR'];
959 elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
960 $userid = $HTTP_ENV_VARS['REMOTE_ADDR'];
961 elseif (isset($GLOBALS['REMOTE_ADDR']))
962 $userid = $GLOBALS['REMOTE_ADDR'];
969 function _isActionPage ($pagename, $verbose = true) {
971 global $AllActionPages;
973 return (in_array($pagename, $AllActionPages));
975 // $dbi = $this->getDbh();
976 // $page = $dbi->getPage($pagename);
977 // if (!$page) return false;
978 // $rev = $page->getCurrentRevision();
979 // FIXME: more restrictive check for sane plugin?
980 // if (strstr($rev->getPackedContent(), '<?plugin'))
982 // if ($verbose and !$rev->hasDefaultContents())
983 // trigger_error("$pagename: Does not appear to be an 'action page'", E_USER_NOTICE);
987 function findActionPage ($action) {
989 if (!$action) return false;
991 // check for translated version, as per users preferred language
992 // (or system default in case it is not en)
993 $translation = gettext($action);
995 if (isset($cache) and isset($cache[$translation]))
996 return $cache[$translation];
998 // check for cached translated version
999 if ($translation and $this->_isActionPage($translation, false))
1000 return $cache[$action] = $translation;
1002 // Allow for, e.g. action=LikePages
1003 if (!isWikiWord($action))
1004 return $cache[$action] = false;
1006 // check for translated version (default language)
1008 if ($LANG != "en") {
1009 require_once("lib/WikiPlugin.php");
1010 require_once("lib/plugin/_WikiTranslation.php");
1011 $trans = new WikiPlugin__WikiTranslation();
1012 $trans->lang = $LANG;
1013 $default = $trans->translate_to_en($action, $LANG);
1014 if ($default and $this->_isActionPage($default, false))
1015 return $cache[$action] = $default;
1017 $default = $translation;
1020 // check for english version
1021 if ($action != $translation and $action != $default) {
1022 if ($this->_isActionPage($action))
1023 return $cache[$action] = $action;
1026 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1027 return $cache[$action] = false;
1030 function isActionPage ($pagename) {
1031 return $this->findActionPage($pagename);
1034 function action_browse () {
1035 $this->buffer_output();
1036 include_once("lib/display.php");
1040 function action_verify () {
1041 $this->action_browse();
1044 function actionpage ($action) {
1045 $this->buffer_output();
1046 include_once("lib/display.php");
1047 actionPage($this, $action);
1050 function adminActionSubpage ($subpage) {
1051 $page = _("PhpWikiAdministration")."/".$subpage;
1052 $action = $this->findActionPage($page);
1054 if (!$this->getArg('s'))
1055 $this->setArg('s', $this->getArg('pagename'));
1056 $this->setArg('verify',1);
1057 if ($this->getArg('action') != 'rename')
1058 $this->setArg('action', $action);
1059 $this->actionpage($action);
1061 trigger_error($page.": Cannot find action page", E_USER_WARNING);
1065 function action_chown () {
1066 $this->adminActionSubpage(_("Chown"));
1069 function action_setacl () {
1070 $this->adminActionSubpage(_("SetAcl"));
1073 function action_rename () {
1074 $this->adminActionSubpage(_("Rename"));
1077 function action_dump () {
1078 $action = $this->findActionPage(_("PageDump"));
1080 $this->actionpage($action);
1082 // redirect to action=upgrade if admin?
1083 trigger_error(_("PageDump").": Cannot find action page", E_USER_WARNING);
1087 function action_diff () {
1088 $this->buffer_output();
1089 include_once "lib/diff.php";
1093 function action_search () {
1094 // Decide between title or fulltextsearch (e.g. both buttons available).
1095 // Reformulate URL and redirect.
1096 $searchtype = $this->getArg('searchtype');
1097 $args = array('s' => $this->getArg('searchterm')
1098 ? $this->getArg('searchterm')
1099 : $this->getArg('s'));
1100 if ($searchtype == 'full' or $searchtype == 'fulltext') {
1101 $search_page = _("FullTextSearch");
1103 elseif ($searchtype == 'external') {
1105 $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1106 $this->redirect($link->url);
1109 $search_page = _("TitleSearch");
1110 $args['auto_redirect'] = 1;
1112 $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1115 function action_edit () {
1116 $this->buffer_output();
1117 include "lib/editpage.php";
1118 $e = new PageEditor ($this);
1122 function action_create () {
1123 $this->action_edit();
1126 function action_viewsource () {
1127 $this->buffer_output();
1128 include "lib/editpage.php";
1129 $e = new PageEditor ($this);
1133 function action_lock () {
1134 $page = $this->getPage();
1135 $page->set('locked', true);
1136 $this->_dbi->touch();
1137 // check ModeratedPage hook
1138 if ($moderated = $page->get('moderation')) {
1139 require_once("lib/WikiPlugin.php");
1140 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1141 if ($retval = $plugin->lock_check($this, $page, $moderated))
1142 $this->setArg('errormsg', $retval);
1144 // check if a link to ModeratedPage exists
1145 elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1146 require_once("lib/WikiPlugin.php");
1147 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1148 if ($retval = $plugin->lock_add($this, $page, $action_page))
1149 $this->setArg('errormsg', $retval);
1151 $this->action_browse();
1154 function action_unlock () {
1155 $page = $this->getPage();
1156 $page->set('locked', false);
1157 $this->_dbi->touch();
1158 $this->action_browse();
1161 function action_purge () {
1162 $pagename = $this->getArg('pagename');
1163 if (strstr($pagename, _("PhpWikiAdministration"))) {
1164 $this->action_browse();
1166 include('lib/purgepage.php');
1171 function action_remove () {
1172 // This check is now redundant.
1173 //$user->requireAuth(WIKIAUTH_ADMIN);
1174 $pagename = $this->getArg('pagename');
1175 if (strstr($pagename, _("PhpWikiAdministration"))) {
1176 $this->action_browse();
1178 include('lib/removepage.php');
1183 function action_xmlrpc () {
1184 include_once("lib/XmlRpcServer.php");
1185 $xmlrpc = new XmlRpcServer($this);
1189 function action_soap () {
1190 if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1193 allow VIRTUAL_PATH or action=soap SOAP access
1195 include_once("SOAP.php");
1198 function action_revert () {
1199 include_once "lib/loadsave.php";
1203 function action_zip () {
1204 include_once("lib/loadsave.php");
1206 // I don't think it hurts to add cruft at the end of the zip file.
1207 //echo "\n========================================================\n";
1208 //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1211 function action_ziphtml () {
1212 include_once("lib/loadsave.php");
1213 MakeWikiZipHtml($this);
1214 // I don't think it hurts to add cruft at the end of the zip file.
1215 echo "\n========================================================\n";
1216 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1219 function action_dumpserial () {
1220 include_once("lib/loadsave.php");
1224 function action_dumphtml () {
1225 include_once("lib/loadsave.php");
1226 DumpHtmlToDir($this);
1229 function action_upload () {
1230 include_once("lib/loadsave.php");
1231 LoadPostFile($this);
1234 function action_upgrade () {
1235 include_once("lib/loadsave.php");
1236 include_once("lib/upgrade.php");
1240 function action_loadfile () {
1241 include_once("lib/loadsave.php");
1242 LoadFileOrDir($this);
1245 function action_pdf () {
1246 include_once("lib/pdf.php");
1247 ConvertAndDisplayPdf($this);
1250 function action_captcha () {
1251 include_once "lib/Captcha.php";
1252 $captcha = new Captcha();
1253 $captcha->image ( $captcha->captchaword() );
1256 function action_wikitohtml () {
1257 include_once("lib/WysiwygEdit/Wikiwyg.php");
1258 $wikitohtml = new WikiToHtml( $this->getArg("content") , $this);
1259 $wikitohtml->send();
1262 function action_setpref () {
1263 $what = $this->getArg('pref');
1264 $value = $this->getArg('value');
1265 $prefs =& $this->_user->_prefs;
1266 $prefs->set($what, $value);
1267 $num = $this->_user->setPreferences($prefs);
1271 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1272 function is_safe_action ($action) {
1274 return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1277 function validateSessionPath() {
1278 // Try to defer any session.save_path PHP errors before any html
1279 // is output, which causes some versions of IE to display a blank
1280 // page (due to its strict mode while parsing a page?).
1281 if (! is_writeable(ini_get('session.save_path'))) {
1282 $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1283 if (!is_writeable($tmpdir))
1286 (sprintf(_("%s is not writable."),
1287 _("The session.save_path directory"))
1289 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1290 sprintf(_("the session.save_path directory '%s'"),
1291 ini_get('session.save_path')),
1292 'SESSION_SAVE_PATH')
1294 . sprintf(_("Attempting to use the directory '%s' instead."),
1297 if (! is_writeable($tmpdir)) {
1299 (sprintf(_("%s is not writable."), $tmpdir)
1301 . _("Users will not be able to sign in.")
1305 @ini_set('session.save_path', $tmpdir);
1310 if ( !USE_DB_SESSION )
1311 validateSessionPath();
1314 if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) {
1315 //apd_set_session_trace(9);
1316 apd_set_pprof_trace();
1319 // Postpone warnings
1320 global $ErrorManager;
1321 if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1322 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING|E_STRICT);
1324 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING);
1325 $request = new WikiRequest();
1327 $action = $request->getArg('action');
1328 if (substr($action, 0, 3) != 'zip') {
1329 if ($action == 'pdf')
1330 $ErrorManager->setPostponedErrorMask(-1); // everything
1331 //else // reject postponing of warnings
1332 // $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1336 * Allow for disabling of markup cache.
1337 * (Mostly for debugging ... hopefully.)
1339 * See also <?plugin WikiAdminUtils action=purge-cache ?>
1341 if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1342 if ($request->getArg('nocache')) // 1 or purge
1343 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1345 define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1348 // Initialize with system defaults in case user not logged in.
1349 // Should this go into the constructor?
1350 $request->initializeTheme('default');
1351 $request->updateAuthAndPrefs();
1352 $request->initializeLang();
1355 //if ($user->is_authenticated())
1356 // $LogEntry->user = $user->getId();
1358 // Memory optimization:
1359 // http://www.procata.com/blog/archives/2004/05/27/rephlux-and-php-memory-usage/
1360 // kill the global PEAR _PEAR_destructor_object_list
1361 if (!empty($_PEAR_destructor_object_list))
1362 $_PEAR_destructor_object_list = array();
1363 $request->possiblyDeflowerVirginWiki();
1365 // hack! define proper actions for these.
1366 //if (defined('WIKI_XMLRPC') and WIKI_XMLRPC) return;
1367 //if (defined('WIKI_SOAP') and WIKI_SOAP) return;
1369 $validators = array('wikiname' => WIKI_NAME,
1370 'args' => wikihash($request->getArgs()),
1371 'prefs' => wikihash($request->getPrefs()));
1372 if (CACHE_CONTROL == 'STRICT') {
1373 $dbi = $request->getDbh();
1374 $timestamp = $dbi->getTimestamp();
1375 $validators['mtime'] = $timestamp;
1376 $validators['%mtime'] = (int)$timestamp;
1378 // FIXME: we should try to generate strong validators when possible,
1379 // but for now, our validator is weak, since equal validators do not
1380 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
1382 // (If DEBUG if off, this may be a strong validator, but I'm going
1383 // to go the paranoid route here pending further study and testing.)
1384 // access hits and edit stats in the footer violate strong ETags also.
1386 $validators['%weak'] = true;
1388 $request->setValidators($validators);
1390 $request->handleAction();
1392 if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1396 if (forge_get_config ('installation_purpose') != 'production') {
1397 //$x = error_reporting(); // DEBUG: why is it 1 here? should be E_ALL
1398 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1399 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
1401 error_reporting(E_ALL); // php4
1403 error_reporting(E_ERROR);
1406 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1407 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1413 // c-basic-offset: 4
1414 // c-hanging-comment-ender-p: nil
1415 // indent-tabs-mode: nil