4 * Copyright 1999-2008 $ThePhpWikiProgrammingTeam
5 * Copyright (C) 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
6 * Copyright (C) 2009 Roger Guignard, Alcatel-Lucent
8 * This file is part of PhpWiki.
10 * PhpWiki is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * PhpWiki is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
25 define ('USE_PREFS_IN_PAGE', true);
27 //include "lib/config.php";
28 require_once 'lib/stdlib.php';
29 require_once 'lib/Request.php';
30 require_once 'lib/WikiDB.php';
31 require_once 'lib/WikiUser.php';
32 require_once 'lib/WikiGroup.php';
33 if (defined('ENABLE_PAGEPERM') and ENABLE_PAGEPERM)
34 require_once 'lib/PagePerm.php';
37 * Check permission per page.
38 * Returns true or false.
40 function mayAccessPage($access, $pagename)
42 if (defined('ENABLE_PAGEPERM') and ENABLE_PAGEPERM)
43 return _requiredAuthorityForPagename($access, $pagename); // typically [10-20ms per page]
48 class WikiRequest extends Request
55 function __construct()
57 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
58 // first mysql request costs [958ms]! [670ms] is mysql_connect()
60 if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
61 // force our local copy, until the pear version is fixed.
62 include_once(dirname(__FILE__) . "/pear/File_Passwd.php");
64 // Preload all necessary userclasses. Otherwise session => __PHP_Incomplete_Class_Name
65 // There's no way to demand-load it later. This way it's much slower, but needs slightly
66 // less memory than loading all.
68 include_once 'lib/WikiUser/BogoLogin.php';
69 // UserPreferences POST Update doesn't reach this.
70 foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
71 include_once("lib/WikiUser/$method.php");
73 switch (DATABASE_TYPE) {
75 include_once 'lib/WikiUser/PearDb.php';
78 include_once 'lib/WikiUser/AdoDb.php';
81 include_once 'lib/WikiUser/PdoDb.php';
87 include_once 'lib/DbSession.php';
89 if (defined('READONLY') and !READONLY) // READONLY might be set later
90 $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix')
91 . $dbi->getParam('db_session_table'));
94 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
95 //$x = error_reporting();
97 $this->version = phpwiki_version();
98 parent::__construct(); // [90ms]
101 $this->setArg('pagename', $this->_deducePagename());
102 $this->setArg('action', $this->_deduceAction());
104 if ((DEBUG & _DEBUG_SQL)
105 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
106 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
108 if ($this->_dbi->_backend->optimize()) {
110 trigger_error(_("Optimizing database"), E_USER_NOTICE);
115 // Restore auth state. This doesn't check for proper authorization!
116 $userid = $this->_deduceUsername();
117 if (isset($this->_user) and
118 !empty($this->_user->_authhow) and
119 $this->_user->_authhow == 'session'
121 // users might switch in a session between the two objects.
122 // restore old auth level here or in updateAuthAndPrefs?
123 //$user = $this->getSessionVar('wiki_user');
124 // revive db handle, because these don't survive sessions
125 if (isset($this->_user) and
126 (!is_a($this->_user, WikiUserClassname())
127 or (strtolower(get_class($this->_user)) == '_passuser')
128 or (strtolower(get_class($this->_user)) == '_fusionforgepassuser'))
130 $this->_user = WikiUser($userid, $this->_user->_prefs);
132 // revive other db handle
133 if (isset($this->_user->_prefs->_method)
134 and ($this->_user->_prefs->_method == 'SQL'
135 or $this->_user->_prefs->_method == 'ADODB'
136 or $this->_user->_prefs->_method == 'PDO'
137 or $this->_user->_prefs->_method == 'HomePage')
139 $this->_user->_HomePagehandle = $this->getPage($userid);
141 // need to update the lockfile filehandle
142 if (is_a($this->_user, '_FilePassUser')
143 and $this->_user->_file->lockfile
144 and !$this->_user->_file->fplock
146 //$level = $this->_user->_level;
147 $this->_user = UpgradeUser($this->_user,
148 new _FilePassUser($userid,
149 $this->_user->_prefs,
150 $this->_user->_file->filename));
151 //$this->_user->_level = $level;
153 $this->_prefs = & $this->_user->_prefs;
155 $user = WikiUser($userid);
156 $this->_user = & $user;
157 $this->_prefs = & $this->_user->_prefs;
161 function initializeLang()
163 // check non-default pref lang
164 if (empty($this->_prefs->_prefs['lang']))
166 $_lang = $this->_prefs->_prefs['lang'];
167 if (isset($_lang->lang) and $_lang->lang != $GLOBALS['LANG']) {
168 $user_lang = $_lang->lang;
169 //check changed LANG and THEME inside a session.
170 // (e.g. by using another baseurl)
171 if (isset($this->_user->_authhow) and $this->_user->_authhow == 'session')
172 $user_lang = $GLOBALS['LANG'];
173 update_locale($user_lang);
174 FindLocalizedButtonFile(".", 'missing_ok', 'reinit');
176 //if (empty($_lang->lang) and $GLOBALS['LANG'] != $_lang->default_value) ;
179 function initializeTheme($when = 'default')
182 // if when = 'default', then first time init (default theme, ...)
183 // if when = 'login', then check some callbacks
184 // and maybe the theme changed (other theme defined in pref)
185 // if when = 'logout', then check other callbacks
186 // and maybe the theme changed (back to default theme)
188 // Load non-default theme (when = login)
189 if (!empty($this->_prefs->_prefs['theme'])) {
190 $_theme = $this->_prefs->_prefs['theme'];
191 if (isset($_theme) and isset($_theme->theme))
192 $user_theme = $_theme->theme;
193 elseif (isset($_theme) and isset($_theme->default_value))
194 $user_theme = $_theme->default_value; else
197 $user_theme = $this->getPref('theme');
199 //check changed LANG and THEME inside a session.
200 // (e.g. by using another baseurl)
201 if (isset($this->_user->_authhow)
202 and $this->_user->_authhow == 'session'
203 and !isset($_theme->theme)
205 and $user_theme != THEME
207 include_once 'themes/'. THEME . '/themeinfo.php';
209 if (empty($WikiTheme) and $user_theme) {
210 if (strcspn($user_theme, "./\x00]") != strlen($user_theme)) {
211 trigger_error(sprintf("invalid theme ā%sā: Invalid characters detected",
214 $user_theme = "default";
216 if (!$user_theme) $user_theme = "default";
217 include_once "themes/$user_theme/themeinfo.php";
219 if (empty($WikiTheme) and defined('THEME'))
220 include_once 'themes/'. THEME . '/themeinfo.php';
221 if (empty($WikiTheme))
222 include_once 'themes/default/themeinfo.php';
223 assert(!empty($WikiTheme));
225 // Do not execute global init code anymore
227 // WikiTheme callbacks
228 if ($when == 'login') {
229 $WikiTheme->CbUserLogin($this, $this->_user->_userid);
230 if (!$this->_user->hasHomePage()) { // NewUser
231 $WikiTheme->CbNewUserLogin($this, $this->_user->_userid);
232 if (in_array($this->getArg('action'), array('edit', 'create')))
233 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
235 } elseif ($when == 'logout') {
236 $WikiTheme->CbUserLogout($this, $this->_user->_userid);
237 } elseif ($when == 'default') {
239 if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser
240 if (in_array($this->getArg('action'), array('edit', 'create')))
241 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
246 // This really maybe should be part of the constructor, but since it
247 // may involve HTML/template output, the global $request really needs
248 // to be initialized before we do this stuff.
249 // [50ms]: 36ms if wikidb_page::exists
250 function updateAuthAndPrefs()
253 if (isset($this->_user) and (!is_a($this->_user, WikiUserClassname()))) {
254 $this->_user = false;
256 // Handle authentication request, if any.
257 if ($auth_args = $this->getArg('auth')) {
258 $this->setArg('auth', false);
259 $this->_handleAuthRequest($auth_args); // possible NORETURN
260 } elseif (!$this->_user
261 or (is_a($this->_user, WikiUserClassname())
262 and !$this->_user->isSignedIn())
264 // If not auth request, try to sign in as saved user.
265 if (($saved_user = $this->getPref('userid')) != false) {
266 $this->_signIn($saved_user);
270 $action = $this->getArg('action');
272 // Save preferences in session and cookie
273 if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') {
274 if (isset($this->_user) and $this->_user->_userid) {
275 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
276 $this->_user->setPreferences($this->_prefs, true);
279 $tmpuser = $this->_user; // clone it
280 $this->setSessionVar('wiki_user', $tmpuser);
284 // Ensure user has permissions for action
285 // HACK ALERT: We may not set the request arg to create,
286 // since the pageeditor has an ugly logic for action == create.
287 if ($action == 'edit' or $action == 'create') {
288 $page = $this->getPage();
289 if (!$page->exists())
294 if (!ENABLE_PAGEPERM) { // Bug #1438392 by Matt Brown
295 $require_level = $this->requiredAuthority($action);
296 if (!$this->_user->hasAuthority($require_level))
297 $this->_notAuthorized($require_level); // NORETURN
299 // novatrope patch to let only _AUTHENTICATED view pages.
300 // If there's not enough authority or forbidden, ask for a password,
301 // unless it's explicitly unobtainable. Some bad magic though.
302 if ($this->requiredAuthorityForAction($action) == WIKIAUTH_UNOBTAINABLE) {
303 $require_level = $this->requiredAuthority($action);
304 $this->_notAuthorized($require_level); // NORETURN
311 if (isset($this->_user))
314 return $GLOBALS['ForbiddenUser'];
317 function & getGroup()
319 if (isset($this->_user) and isset($this->_user->_group))
320 return $this->_user->_group;
322 // Debug Strict: Only variable references should be returned by reference
323 $this->_user->_group = WikiGroup::getGroup();
324 return $this->_user->_group;
328 function & getPrefs()
330 return $this->_prefs;
333 // Convenience function:
334 function getPref($key)
336 if (isset($this->_prefs)) {
337 return $this->_prefs->get($key);
348 * Get requested page from the page database.
349 * By default it will grab the page requested via the URL
351 * This is a convenience function.
352 * @param string $pagename Name of page to get.
353 * @return WikiDB_Page Object with methods to pull data from
354 * database for the page requested.
356 function getPage($pagename = '')
359 $pagename = $this->getArg('pagename');
361 return $this->_dbi->getPage($pagename);
364 /** Get URL for POST actions.
366 * Officially, we should just use SCRIPT_NAME (or some such),
367 * but that causes problems when we try to issue a redirect, e.g.
368 * after saving a page.
370 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
371 * a redirect from a page to itself.)
373 * So, as a HACK, we include pagename and action as query args in
374 * the URL. (These should be ignored when we receive the POST
377 function getPostURL($pagename = false)
379 global $HTTP_GET_VARS;
381 if ($pagename === false)
382 $pagename = $this->getArg('pagename');
383 $action = $this->getArg('action');
384 if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
385 return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
386 elseif ($action == 'edit')
387 return WikiURL($pagename);
389 return WikiURL($pagename, array('action' => $action));
392 function _handleAuthRequest($auth_args)
394 if (!is_array($auth_args))
397 // Ignore password unless POST'ed.
398 if (!$this->isPost())
399 unset($auth_args['passwd']);
401 $olduser = $this->_user;
402 $user = $this->_user->AuthCheck($auth_args);
403 if (is_string($user)) {
404 // Login attempt failed.
405 $fail_message = $user;
406 $auth_args['pass_required'] = true;
407 // if clicked just on to the "sign in as:" button dont print invalid username.
408 if (!empty($auth_args['login']) and empty($auth_args['userid']))
410 // If no password was submitted, it's not really
411 // a failure --- just need to prompt for password...
412 if (!ALLOW_USER_PASSWORDS
414 and !isset($auth_args['passwd'])
416 $fail_message = false;
418 $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
419 $this->finish(); //NORETURN
420 } elseif (is_a($user, WikiUserClassname())) {
421 // Successful login (or logout.)
422 $this->_setUser($user);
424 // Login request cancelled.
429 * Attempt to sign in (bogo-login).
433 * @param $userid string Userid to attempt to sign in as.
435 private function _signIn($userid)
438 $this->_user = new _BogoUser($userid);
439 // FIXME: is this always false? shouldn't we try passuser first?
441 $this->_user = new _PassUser($userid);
442 $user = $this->_user->AuthCheck(array('userid' => $userid));
443 if (is_a($user, WikiUserClassname())) {
444 $this->_setUser($user); // success!
448 // login or logout or restore state
449 function _setUser(&$user)
451 $this->_user =& $user;
452 if (defined('MAIN_setUser')) return; // don't set cookies twice
453 $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(),
454 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
455 $isSignedIn = $user->isSignedIn();
457 $user->_authhow = 'signin';
460 // Save userid to prefs..
461 if (empty($this->_user->_prefs)) {
462 $this->_user->_prefs = $this->_user->getPreferences();
463 $this->_prefs =& $this->_user->_prefs;
465 $this->_user->_group = $this->getGroup();
466 $this->setSessionVar('wiki_user', $user);
467 $this->_prefs->set('userid',
468 $isSignedIn ? $user->getId() : '');
469 $this->initializeTheme($isSignedIn ? 'login' : 'logout');
470 define('MAIN_setUser', true);
473 /* Permission system */
474 function getLevelDescription($level)
476 static $levels = false;
477 if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0"
478 $levels = array('x-1' => _("FORBIDDEN"),
483 'x100' => _("UNOBTAINABLE"));
486 if (!empty($levels["x" . $level]))
487 return $levels["x" . $level];
492 function _notAuthorized($require_level)
494 // Display the authority message in the Wiki's default
495 // language, in case it is not english.
497 // Note that normally a user will not see such an error once
498 // logged in, unless the admin has altered the default
499 // disallowed wikiactions. In that case we should probably
500 // check the user's language prefs too at this point; this
501 // would be a situation which is not really handled with the
503 if (empty($GLOBALS['LANG']))
504 update_locale(DEFAULT_LANGUAGE);
506 // User does not have required authority. Prompt for login.
507 $action = $this->getArg('action');
508 $what = $this->getActionDescription($action);
509 $pass_required = ($require_level >= WIKIAUTH_USER);
510 if ($require_level == WIKIAUTH_UNOBTAINABLE) {
511 global $DisabledActions;
512 if ($DisabledActions and in_array($action, $DisabledActions)) {
513 $msg = fmt("%s is disallowed on this wiki.",
514 $this->getDisallowedActionDescription($this->getArg('action')));
515 $this->_user->PrintLoginForm($this, compact('require_level'), $msg);
519 // Is the reason a missing ACL or just wrong user or password?
520 if (class_exists('PagePermission')) {
521 $user =& $this->_user;
522 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
523 $msg = fmt("%s %s %s is disallowed on this wiki for %s user ā%sā (level: %s).",
524 _("Missing PagePermission:"),
525 action2access($this->getArg('action')),
526 $this->getArg('pagename'),
527 $status, $user->getId(), $this->getLevelDescription($user->_level));
528 // TODO: add link to action=setacl
529 $user->PrintLoginForm($this, compact('pass_required'), $msg);
533 $msg = fmt("%s is disallowed on this wiki.",
534 $this->getDisallowedActionDescription($this->getArg('action')));
535 $this->_user->PrintLoginForm($this, compact('require_level', 'pass_required'), $msg);
539 } elseif ($require_level == WIKIAUTH_BOGO)
540 $msg = fmt("You must sign in to %s.", $what); elseif ($require_level == WIKIAUTH_USER) {
541 // LoginForm should display the relevant messages...
543 /*if (!ALLOW_ANON_USER)
544 $msg = fmt("You must log in first to %s", $what);
546 $msg = fmt("You must log in to %s.", $what);
548 } elseif ($require_level == WIKIAUTH_ANON)
549 $msg = fmt("Access for you is forbidden to %s.", $what); else
550 $msg = fmt("You must be an administrator to %s.", $what);
552 $this->_user->PrintLoginForm($this, compact('require_level', 'pass_required'),
554 if (!$GLOBALS['WikiTheme']->DUMP_MODE)
555 $this->finish(); // NORETURN
558 // Fixme: for PagePermissions we'll need other strings,
559 // relevant to the requested page, not just for the action on the whole wiki.
560 function getActionDescription($action)
562 static $actionDescriptions;
563 if (!$actionDescriptions) {
565 = array('browse' => _("view this page"),
566 'diff' => _("diff this page"),
567 'dumphtml' => _("dump HTML pages"),
568 'dumpserial' => _("dump serial pages"),
569 'edit' => _("edit this page"),
570 'rename' => _("rename this page"),
571 'revert' => _("revert to a previous version of this page"),
572 'create' => _("create this page"),
573 'loadfile' => _("load files into this wiki"),
574 'lock' => _("lock this page"),
575 'purge' => _("purge this page"),
576 'remove' => _("remove this page"),
577 'unlock' => _("unlock this page"),
578 'upload' => _("upload a ZIP dump"),
579 'verify' => _("verify the current action"),
580 'viewsource' => _("view the source of this page"),
581 'xmlrpc' => _("access this wiki via XML-RPC"),
582 'soap' => _("access this wiki via SOAP"),
583 'zip' => _("download a ZIP dump from this wiki"),
584 'ziphtml' => _("download a HTML ZIP dump from this wiki")
587 if (in_array($action, array_keys($actionDescriptions)))
588 return $actionDescriptions[$action];
590 return _("use") . " " . $action;
594 TODO: check against these cases:
595 if ($DisabledActions and in_array($action, $DisabledActions))
596 return WIKIAUTH_UNOBTAINABLE;
598 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
599 return requiredAuthorityForPage($action);
601 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
603 function getDisallowedActionDescription($action)
605 static $disallowedActionDescriptions;
607 if (!$disallowedActionDescriptions) {
608 $disallowedActionDescriptions
609 = array('browse' => _("Browsing pages"),
610 'diff' => _("Diffing pages"),
611 'dumphtml' => _("Dumping HTML pages"),
612 'dumpserial' => _("Dumping serial pages"),
613 'edit' => _("Editing pages"),
614 'revert' => _("Reverting to a previous version of pages"),
615 'create' => _("Creating pages"),
616 'loadfile' => _("Loading files"),
617 'lock' => _("Locking pages"),
618 'purge' => _("Purging pages"),
619 'remove' => _("Removing pages"),
620 'unlock' => _("Unlocking pages"),
621 'upload' => _("Uploading ZIP dumps"),
622 'verify' => _("Verify the current action"),
623 'viewsource' => _("Viewing the source of pages"),
624 'xmlrpc' => _("XML-RPC access"),
625 'soap' => _("SOAP access"),
626 'zip' => _("Downloading ZIP dumps"),
627 'ziphtml' => _("Downloading HTML ZIP dumps")
630 if (in_array($action, array_keys($disallowedActionDescriptions)))
631 return $disallowedActionDescriptions[$action];
636 function requiredAuthority($action)
638 $auth = $this->requiredAuthorityForAction($action);
639 if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
642 * This is a hook for plugins to require authority
643 * for posting to them.
645 * IMPORTANT: This is not a secure check, so the plugin
646 * may not assume that any POSTs to it are authorized.
647 * All this does is cause PhpWiki to prompt for login
648 * if the user doesn't have the required authority.
650 if ($this->isPost()) {
651 $post_auth = $this->getArg('require_authority_for_post');
652 if ($post_auth !== false)
653 $auth = max($auth, $post_auth);
658 function requiredAuthorityForAction($action)
660 global $DisabledActions;
662 if ($DisabledActions and in_array($action, $DisabledActions))
663 return WIKIAUTH_UNOBTAINABLE;
665 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
666 return requiredAuthorityForPage($action);
679 return WIKIAUTH_ANON;
684 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
685 return WIKIAUTH_ADMIN;
686 return WIKIAUTH_ANON;
690 return WIKIAUTH_ADMIN;
691 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
692 return WIKIAUTH_ADMIN;
693 return WIKIAUTH_ANON;
696 if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
697 return WIKIAUTH_ANON;
698 return WIKIAUTH_ADMIN;
702 return WIKIAUTH_ADMIN;
703 return WIKIAUTH_ANON;
708 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
709 return WIKIAUTH_BOGO;
710 return WIKIAUTH_ANON;
711 // return WIKIAUTH_BOGO;
714 $page = $this->getPage();
715 $current = $page->getCurrentRevision();
716 if ($current->hasDefaultContents())
717 return $this->requiredAuthorityForAction('edit');
718 return $this->requiredAuthorityForAction('browse');
731 return WIKIAUTH_ADMIN;
733 /* authcheck occurs only in the plugin.
734 required actionpage RateIt */
737 case 'delete_rating':
738 // Perhaps this should be WIKIAUTH_USER
739 return WIKIAUTH_BOGO;
743 global $WikiNameRegexp;
744 if (preg_match("/$WikiNameRegexp\Z/A", $action))
745 return WIKIAUTH_ANON; // ActionPage.
747 return WIKIAUTH_ADMIN;
752 /* End of Permission system */
754 function possiblyDeflowerVirginWiki()
756 if ($this->getArg('action') != 'browse')
758 if ($this->getArg('pagename') != HOME_PAGE)
761 $page = $this->getPage();
762 $current = $page->getCurrentRevision();
763 if ($current->getVersion() > 0)
764 return; // Homepage exists.
766 include_once 'lib/loadsave.php';
767 $this->setArg('action', 'loadfile');
769 $this->finish(); // NORETURN
772 // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
773 function handleAction()
775 // Check illegal characters in page names: <>[]{}|"
776 require_once 'lib/Template.php';
777 $page = $this->getPage();
778 $pagename = $page->getName();
779 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
780 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH - 1) . 'ā¦';
781 $CONTENT = HTML::div(array('class' => 'error'),
782 _('Page name too long'));
783 GeneratePage($CONTENT, $pagename);
786 if (preg_match("/[<\[\{\|\"\}\]>]/", $pagename, $matches) > 0) {
787 $CONTENT = HTML::div(
788 array('class' => 'error'),
789 sprintf(_("Illegal character ā%sā in page name."),
791 GeneratePage($CONTENT, $pagename);
794 $action = $this->getArg('action');
796 and !$this->_user->isAdmin()
797 and $action != 'browse'
798 and $action != 'wikitohtml'
800 if ($page->get('moderation')) {
801 require_once 'lib/WikiPlugin.php';
802 $loader = new WikiPluginLoader();
803 $plugin = $loader->getPlugin("ModeratedPage");
804 if ($plugin->handler($this, $page)) {
807 array('class' => 'wiki-edithelp'),
808 fmt("%s: action forwarded to a moderator.",
811 _("This action requires moderator approval. Please be patient."));
812 if (!empty($plugin->_tokens['CONTENT']))
813 $plugin->_tokens['CONTENT']->pushContent
816 _("You must wait for moderator approval."));
818 $plugin->_tokens['CONTENT'] = $CONTENT;
819 $title = WikiLink($page->getName());
820 $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
821 GeneratePage(Template('browse', $plugin->_tokens),
823 $page->getCurrentRevision());
828 $method = "action_$action";
829 if (method_exists($this, $method)) {
831 } elseif ($page = $this->findActionPage($action)) {
832 $this->actionpage($page);
834 $this->finish(fmt("%s: Bad action", $action));
838 function finish($errormsg = '')
843 exit(); // just in case CloseDataBase calls us
846 global $ErrorManager;
847 $ErrorManager->flushPostponedErrors();
849 if (!empty($errormsg)) {
852 HTML::h2(_("Fatal PhpWiki Error")),
855 echo "\n</body></html>";
857 if (is_object($this->_user)) {
858 $this->_user->page = $this->getArg('pagename');
859 $this->_user->action = $this->getArg('action');
860 unset($this->_user->_HomePagehandle);
861 unset($this->_user->_auth_dbi);
862 unset($this->_user->_dbi);
863 unset($this->_user->_request);
870 * Generally pagename is rawurlencoded for older browsers or mozilla.
871 * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
872 * If false, we support either "/index.php?pagename=PageName&arg=value",
873 * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
875 function _deducePagename()
877 if (trim(rawurldecode($this->getArg('pagename'))))
878 return rawurldecode($this->getArg('pagename'));
881 $pathinfo = $this->get('PATH_INFO');
882 if (empty($pathinfo)) { // fix for CGI
883 $path = $this->get('REQUEST_URI');
884 $script = $this->get('SCRIPT_NAME');
885 $pathinfo = substr($path, strlen($script));
886 $pathinfo = preg_replace('/\?.+$/', '', $pathinfo);
888 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
890 if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
893 } elseif ($this->isPost()) {
895 * In general, for security reasons, HTTP_GET_VARS should be ignored
896 * on POST requests, but we make an exception here (only for pagename).
898 * The justification for this hack is the following
899 * asymmetry: When POSTing with USE_PATH_INFO set, the
900 * pagename can (and should) be communicated through the
901 * request URL via PATH_INFO. When POSTing with
902 * USE_PATH_INFO off, this cannot be done --- the only way
903 * to communicate the pagename through the URL is via
904 * QUERY_ARGS (HTTP_GET_VARS).
906 global $HTTP_GET_VARS;
907 if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) {
908 return rawurldecode($HTTP_GET_VARS['pagename']);
913 * Support for PhpWiki 1.2 style requests.
914 * Strip off "&" args (?PageName&action=...&start_debug,...)
916 $query_string = $this->get('QUERY_STRING');
917 if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
918 return rawurldecode($m[1]);
924 function _deduceAction()
926 if (!($action = $this->getArg('action'))) {
927 // TODO: improve this SOAP.php hack by letting SOAP use index.php
928 // or any other virtual url as with xmlrpc
929 if (defined('WIKI_SOAP') and WIKI_SOAP)
931 // Detect XML-RPC requests.
933 && ((defined("WIKI_XMLRPC") and WIKI_XMLRPC)
934 or ($this->get('CONTENT_TYPE') == 'text/xml'
935 or $this->get('CONTENT_TYPE') == 'application/xml')
936 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>'))
940 return 'browse'; // Default if no action specified.
943 if (method_exists($this, "action_$action"))
946 // Allow for, e.g. action=LikePages
947 if (isActionPage($action))
950 // Handle untranslated actionpages in non-english
951 // (people playing with switching languages)
952 if (0 and $GLOBALS['LANG'] != 'en') {
953 require_once 'lib/plugin/WikiTranslation.php';
954 $trans = new WikiPlugin_WikiTranslation();
955 $en_action = $trans->translate($action, 'en', $GLOBALS['LANG']);
956 if (isActionPage($en_action))
960 trigger_error("$action: Unknown action", E_USER_NOTICE);
964 function _deduceUsername()
966 global $HTTP_ENV_VARS;
968 if ($this->getArg('auth')) {
969 $auth = $this->getArg('auth');
970 if (isset($auth['userid'])) {
971 return $auth['userid'];
975 if ($user = $this->getSessionVar('wiki_user')) {
976 // Switched auth between sessions.
977 // Note: There's no way to demandload a missing class-definition
978 // afterwards! Stupid php.
979 if (defined('FUSIONFORGE') && FUSIONFORGE) {
980 if (empty($_SERVER['PHP_AUTH_USER'])) {
983 } elseif (is_a($user, WikiUserClassname())) {
984 $this->_user = $user;
985 $this->_user->_authhow = 'session';
986 return $user->UserName();
990 // Sessions override http auth
991 if (!empty($_SERVER['PHP_AUTH_USER']))
992 return $_SERVER['PHP_AUTH_USER'];
994 if (!empty($_SERVER['REMOTE_USER']))
995 return $_SERVER['REMOTE_USER'];
996 if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
997 return $HTTP_ENV_VARS['REMOTE_USER'];
999 if ($userid = $this->getCookieVar(getCookieName())) {
1000 if (!empty($userid) and substr($userid, 0, 2) != 's:') {
1001 $this->_user->authhow = 'cookie';
1006 if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
1007 if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
1008 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
1009 // wiki.putPage has special otional userid/passwd arguments. check that later.
1011 if (isset($_SERVER['REMOTE_USER']))
1012 $userid = $_SERVER['REMOTE_USER'];
1013 elseif (isset($_SERVER['REMOTE_ADDR']))
1014 $userid = $_SERVER['REMOTE_ADDR']; elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
1015 $userid = $HTTP_ENV_VARS['REMOTE_ADDR']; elseif (isset($GLOBALS['REMOTE_ADDR']))
1016 $userid = $GLOBALS['REMOTE_ADDR'];
1023 function findActionPage($action)
1026 if (!$action) return false;
1028 if (isActionPage($action))
1029 return $cache[$action] = $action;
1031 // check for translated version, as per users preferred language
1032 // (or system default in case it is not en)
1033 $translation = gettext($action);
1035 if (isset($cache) and isset($cache[$translation]))
1036 return $cache[$translation];
1038 // check for cached translated version
1039 if ($translation and isActionPage($translation))
1040 return $cache[$action] = $translation;
1042 // Allow for, e.g. action=LikePages
1043 if (!isWikiWord($action))
1044 return $cache[$action] = false;
1046 // check for translated version (default language)
1048 if ($LANG != "en") {
1049 require_once 'lib/WikiPlugin.php';
1050 require_once 'lib/plugin/WikiTranslation.php';
1051 $trans = new WikiPlugin_WikiTranslation();
1052 $trans->lang = $LANG;
1053 $default = $trans->translate_to_en($action, $LANG);
1054 if ($default and isActionPage($default))
1055 return $cache[$action] = $default;
1057 $default = $translation;
1060 // check for english version
1061 if ($action != $translation and $action != $default) {
1062 if (isActionPage($action))
1063 return $cache[$action] = $action;
1066 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1067 return $cache[$action] = false;
1070 function action_browse()
1072 $this->buffer_output();
1073 include_once 'lib/display.php';
1077 function action_verify()
1079 $this->action_browse();
1082 function actionpage($action)
1084 $this->buffer_output();
1085 include_once 'lib/display.php';
1086 actionPage($this, $action);
1089 function adminActionSubpage($subpage)
1091 $page = __("PhpWikiAdministration") . "/" . $subpage;
1092 $action = $this->findActionPage($page);
1094 if (!$this->getArg('s'))
1095 $this->setArg('s', $this->getArg('pagename'));
1096 $this->setArg('verify', 1); // only for POST
1097 if ($this->getArg('action') != 'rename')
1098 $this->setArg('action', $action);
1099 elseif ($this->getArg('to') && !$this->getArg('admin_rename')) {
1100 $this->setArg('admin_rename',
1101 array('from' => $this->getArg('s'),
1102 'to' => $this->getArg('to'),
1103 'action' => 'select'));
1105 $this->actionpage($action);
1107 trigger_error($page . ": Cannot find action page", E_USER_WARNING);
1111 function action_chown()
1113 $this->adminActionSubpage(__("Chown"));
1116 function action_setacl()
1118 $this->adminActionSubpage(__("SetAcl"));
1121 function action_setaclsimple()
1123 $this->adminActionSubpage(__("SetAclSimple"));
1126 function action_deleteacl()
1128 $this->adminActionSubpage(__("DeleteAcl"));
1131 function action_rename()
1133 $this->adminActionSubpage(__("Rename"));
1136 function action_dump()
1138 $action = $this->findActionPage(_("PageDump"));
1140 $this->actionpage($action);
1142 // redirect to action=upgrade if admin?
1143 trigger_error(_("PageDump") . ": Cannot find action page", E_USER_WARNING);
1147 function action_diff()
1149 $this->buffer_output();
1150 include_once 'lib/diff.php';
1154 function action_search()
1156 // Decide between title or fulltextsearch (e.g. both buttons available).
1157 // Reformulate URL and redirect.
1158 $searchtype = $this->getArg('searchtype');
1159 $args = array('s' => $this->getArg('searchterm')
1160 ? $this->getArg('searchterm')
1161 : $this->getArg('s'));
1162 if ($searchtype == 'full' or $searchtype == 'fulltext') {
1163 $search_page = _("FullTextSearch");
1164 } elseif ($searchtype == 'external') {
1166 $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1167 $this->redirect($link->url);
1169 $search_page = _("TitleSearch");
1170 $args['auto_redirect'] = 1;
1172 $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1175 function action_edit()
1177 $this->buffer_output();
1178 include 'lib/editpage.php';
1179 $e = new PageEditor ($this);
1183 function action_create()
1185 $this->action_edit();
1188 function action_viewsource()
1190 $this->buffer_output();
1191 include 'lib/editpage.php';
1192 $e = new PageEditor ($this);
1196 function action_lock()
1198 $page = $this->getPage();
1199 $page->set('locked', true);
1200 $this->_dbi->touch();
1201 // check ModeratedPage hook
1202 if ($moderated = $page->get('moderation')) {
1203 require_once 'lib/WikiPlugin.php';
1204 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1205 if ($retval = $plugin->lock_check($this, $page, $moderated))
1206 $this->setArg('errormsg', $retval);
1207 } // check if a link to ModeratedPage exists
1208 elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1209 require_once 'lib/WikiPlugin.php';
1210 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1211 if ($retval = $plugin->lock_add($this, $page, $action_page))
1212 $this->setArg('errormsg', $retval);
1214 $this->action_browse();
1217 function action_unlock()
1219 $page = $this->getPage();
1220 $page->set('locked', false);
1221 $this->_dbi->touch();
1222 $this->action_browse();
1225 function action_purge()
1227 $pagename = $this->getArg('pagename');
1228 if (strstr($pagename, _("PhpWikiAdministration"))) {
1229 $this->action_browse();
1231 include 'lib/purgepage.php';
1236 function action_remove()
1238 // This check is now redundant.
1239 //$user->requireAuth(WIKIAUTH_ADMIN);
1240 $pagename = $this->getArg('pagename');
1241 if (strstr($pagename, _("PhpWikiAdministration"))) {
1242 $this->action_browse();
1244 include 'lib/removepage.php';
1249 function action_xmlrpc()
1251 include_once 'lib/XmlRpcServer.php';
1252 $xmlrpc = new XmlRpcServer($this);
1256 function action_soap()
1258 if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1261 allow VIRTUAL_PATH or action=soap SOAP access
1263 include_once 'SOAP.php';
1266 function action_revert()
1268 include_once 'lib/loadsave.php';
1272 function action_zip()
1274 include_once 'lib/loadsave.php';
1278 function action_ziphtml()
1280 include_once 'lib/loadsave.php';
1281 MakeWikiZipHtml($this);
1282 // I don't think it hurts to add cruft at the end of the zip file.
1283 echo "\n========================================================\n";
1284 echo "PhpWiki " . PHPWIKI_VERSION . "\n";
1287 function action_dumpserial()
1289 include_once 'lib/loadsave.php';
1293 function action_dumphtml()
1295 include_once 'lib/loadsave.php';
1296 DumpHtmlToDir($this);
1299 function action_upload()
1301 include_once 'lib/loadsave.php';
1302 LoadPostFile($this);
1305 function action_upgrade()
1307 include_once 'lib/loadsave.php';
1308 include_once 'lib/upgrade.php';
1312 function action_loadfile()
1314 include_once 'lib/loadsave.php';
1315 LoadFileOrDir($this);
1318 function action_pdf()
1320 include_once 'lib/pdf.php';
1321 ConvertAndDisplayPdf($this);
1324 function action_captcha()
1326 include_once 'lib/Captcha.php';
1327 $captcha = new Captcha();
1328 $captcha->image($captcha->captchaword());
1331 function action_wikitohtml()
1333 include_once 'lib/WysiwygEdit/Wikiwyg.php';
1334 $wikitohtml = new WikiToHtml($this->getArg("content"), $this);
1335 $wikitohtml->send();
1338 function action_setpref()
1340 $what = $this->getArg('pref');
1341 $value = $this->getArg('value');
1342 $prefs =& $this->_user->_prefs;
1343 $prefs->set($what, $value);
1344 $this->_user->setPreferences($prefs);
1348 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1349 function is_safe_action($action)
1352 return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1355 function validateSessionPath()
1357 // Try to defer any session.save_path PHP errors before any html
1358 // is output, which causes some versions of IE to display a blank
1359 // page (due to its strict mode while parsing a page?).
1360 if (!is_writeable(ini_get('session.save_path'))) {
1361 $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1362 if (!is_writeable($tmpdir))
1365 (sprintf(_("%s is not writable."),
1366 _("The session.save_path directory"))
1368 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1369 sprintf(_("the session.save_path directory ā%sā"),
1370 ini_get('session.save_path')),
1371 'SESSION_SAVE_PATH')
1373 . sprintf(_("Attempting to use the directory ā%sā instead."),
1376 if (!is_writeable($tmpdir)) {
1378 (sprintf(_("%s is not writable."), $tmpdir)
1380 . _("Users will not be able to sign in.")
1383 @ini_set('session.save_path', $tmpdir);
1389 if (version_compare(PHP_VERSION, '5.3', '<')) {
1390 exit(_("Your PHP version is too old. You must have at least PHP 5.3."));
1393 if (!USE_DB_SESSION)
1394 validateSessionPath();
1397 if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) {
1398 //apd_set_session_trace(9);
1399 apd_set_pprof_trace();
1402 // Postpone warnings
1403 global $ErrorManager;
1404 if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1405 $ErrorManager->setPostponedErrorMask(E_NOTICE | E_USER_NOTICE | E_USER_WARNING | E_WARNING | E_STRICT | E_DEPRECATED);
1407 $ErrorManager->setPostponedErrorMask(E_NOTICE | E_USER_NOTICE | E_USER_WARNING | E_WARNING);
1408 $request = new WikiRequest();
1410 $action = $request->getArg('action');
1411 if (substr($action, 0, 3) != 'zip') {
1412 if ($action == 'pdf')
1413 $ErrorManager->setPostponedErrorMask(-1); // everything
1414 //else // reject postponing of warnings
1415 // $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1419 * Allow for disabling of markup cache.
1420 * (Mostly for debugging ... hopefully.)
1422 * See also <<WikiAdminUtils action=purge-cache>>
1424 if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1425 if ($request->getArg('nocache')) // 1 or purge
1426 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1428 define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1431 // Initialize with system defaults in case user not logged in.
1432 // Should this go into the constructor?
1433 $request->initializeTheme('default');
1434 $request->updateAuthAndPrefs();
1435 $request->initializeLang();
1437 $request->possiblyDeflowerVirginWiki();
1439 $validators = array('wikiname' => WIKI_NAME,
1440 'args' => wikihash($request->getArgs()),
1441 'prefs' => wikihash($request->getPrefs()));
1442 if (CACHE_CONTROL == 'STRICT') {
1443 $dbi = $request->getDbh();
1444 $timestamp = $dbi->getTimestamp();
1445 $validators['mtime'] = $timestamp;
1446 $validators['%mtime'] = (int)$timestamp;
1448 // FIXME: we should try to generate strong validators when possible,
1449 // but for now, our validator is weak, since equal validators do not
1450 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
1452 // (If DEBUG if off, this may be a strong validator, but I'm going
1453 // to go the paranoid route here pending further study and testing.)
1454 // access hits and edit stats in the footer violate strong ETags also.
1456 $validators['%weak'] = true;
1458 $request->setValidators($validators);
1460 $request->handleAction();
1462 if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1466 if ((!(defined('FUSIONFORGE') && FUSIONFORGE)) || (forge_get_config('installation_environment') != 'production')) {
1467 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1468 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
1470 error_reporting(E_ALL); // php4
1472 error_reporting(E_ERROR);
1475 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1476 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN) {
1479 // We need the global $request and $WikiTheme
1480 $request = new WikiRequest();
1481 require_once 'lib/WikiTheme.php';
1482 $WikiTheme = new WikiTheme('default');
1488 // c-basic-offset: 4
1489 // c-hanging-comment-ender-p: nil
1490 // indent-tabs-mode: nil