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(dirname(__FILE__) . "/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';
34 require_once 'lib/PagePerm.php';
37 * Check permission per page.
38 * Returns true or false.
40 function mayAccessPage($access, $pagename)
43 return _requiredAuthorityForPagename($access, $pagename); // typically [10-20ms per page]
48 class WikiRequest extends Request
52 function __construct()
54 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
55 // first mysql request costs [958ms]! [670ms] is mysql_connect()
57 if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
58 // force our local copy, until the pear version is fixed.
59 include_once(dirname(__FILE__) . "/pear/File_Passwd.php");
61 // Preload all necessary userclasses. Otherwise session => __PHP_Incomplete_Class_Name
62 // There's no way to demand-load it later. This way it's much slower, but needs slightly
63 // less memory than loading all.
65 include_once 'lib/WikiUser/BogoLogin.php';
66 // UserPreferences POST Update doesn't reach this.
67 foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
68 include_once("lib/WikiUser/$method.php");
70 switch (DATABASE_TYPE) {
72 include_once 'lib/WikiUser/PearDb.php';
75 include_once 'lib/WikiUser/AdoDb.php';
78 include_once 'lib/WikiUser/PdoDb.php';
84 include_once 'lib/DbSession.php';
86 if (defined('READONLY') and !READONLY) // READONLY might be set later
87 $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix')
88 . $dbi->getParam('db_session_table'));
91 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
92 //$x = error_reporting();
94 $this->version = phpwiki_version();
95 parent::__construct(); // [90ms]
98 $this->setArg('pagename', $this->_deducePagename());
99 $this->setArg('action', $this->_deduceAction());
101 if ((DEBUG & _DEBUG_SQL)
102 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
103 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))
105 if ($this->_dbi->_backend->optimize()) {
107 trigger_error(_("Optimizing database"), E_USER_NOTICE);
112 // Restore auth state. This doesn't check for proper authorization!
113 $userid = $this->_deduceUsername();
114 if (isset($this->_user) and
115 !empty($this->_user->_authhow) and
116 $this->_user->_authhow == 'session'
118 // users might switch in a session between the two objects.
119 // restore old auth level here or in updateAuthAndPrefs?
120 //$user = $this->getSessionVar('wiki_user');
121 // revive db handle, because these don't survive sessions
122 if (isset($this->_user) and
123 (!is_a($this->_user, WikiUserClassname())
124 or (strtolower(get_class($this->_user)) == '_passuser')
125 or (strtolower(get_class($this->_user)) == '_fusionforgepassuser'))
127 $this->_user = WikiUser($userid, $this->_user->_prefs);
129 // revive other db handle
130 if (isset($this->_user->_prefs->_method)
131 and ($this->_user->_prefs->_method == 'SQL'
132 or $this->_user->_prefs->_method == 'ADODB'
133 or $this->_user->_prefs->_method == 'PDO'
134 or $this->_user->_prefs->_method == 'HomePage')
136 $this->_user->_HomePagehandle = $this->getPage($userid);
138 // need to update the lockfile filehandle
139 if (is_a($this->_user, '_FilePassUser')
140 and $this->_user->_file->lockfile
141 and !$this->_user->_file->fplock
143 //$level = $this->_user->_level;
144 $this->_user = UpgradeUser($this->_user,
145 new _FilePassUser($userid,
146 $this->_user->_prefs,
147 $this->_user->_file->filename));
148 //$this->_user->_level = $level;
150 $this->_prefs = & $this->_user->_prefs;
152 $user = WikiUser($userid);
153 $this->_user = & $user;
154 $this->_prefs = & $this->_user->_prefs;
158 function initializeLang()
160 // check non-default pref lang
161 if (empty($this->_prefs->_prefs['lang']))
163 $_lang = $this->_prefs->_prefs['lang'];
164 if (isset($_lang->lang) and $_lang->lang != $GLOBALS['LANG']) {
165 $user_lang = $_lang->lang;
166 //check changed LANG and THEME inside a session.
167 // (e.g. by using another baseurl)
168 if (isset($this->_user->_authhow) and $this->_user->_authhow == 'session')
169 $user_lang = $GLOBALS['LANG'];
170 update_locale($user_lang);
171 FindLocalizedButtonFile(".", 'missing_ok', 'reinit');
173 //if (empty($_lang->lang) and $GLOBALS['LANG'] != $_lang->default_value) ;
176 function initializeTheme($when = 'default')
179 // if when = 'default', then first time init (default theme, ...)
180 // if when = 'login', then check some callbacks
181 // and maybe the theme changed (other theme defined in pref)
182 // if when = 'logout', then check other callbacks
183 // and maybe the theme changed (back to default theme)
185 // Load non-default theme (when = login)
186 if (!empty($this->_prefs->_prefs['theme'])) {
187 $_theme = $this->_prefs->_prefs['theme'];
188 if (isset($_theme) and isset($_theme->theme))
189 $user_theme = $_theme->theme;
190 elseif (isset($_theme) and isset($_theme->default_value))
191 $user_theme = $_theme->default_value; else
194 $user_theme = $this->getPref('theme');
196 //check changed LANG and THEME inside a session.
197 // (e.g. by using another baseurl)
198 if (isset($this->_user->_authhow)
199 and $this->_user->_authhow == 'session'
200 and !isset($_theme->theme)
202 and $user_theme != THEME
204 include_once 'themes/'. THEME . '/themeinfo.php';
206 if (empty($WikiTheme) and $user_theme) {
207 if (strcspn($user_theme, "./\x00]") != strlen($user_theme)) {
208 trigger_error(sprintf("invalid theme ā%sā: Invalid characters detected",
211 $user_theme = "default";
213 if (!$user_theme) $user_theme = "default";
214 include_once "themes/$user_theme/themeinfo.php";
216 if (empty($WikiTheme) and defined('THEME'))
217 include_once 'themes/'. THEME . '/themeinfo.php';
218 if (empty($WikiTheme))
219 include_once 'themes/default/themeinfo.php';
220 assert(!empty($WikiTheme));
222 // Do not execute global init code anymore
224 // WikiTheme callbacks
225 if ($when == 'login') {
226 $WikiTheme->CbUserLogin($this, $this->_user->_userid);
227 if (!$this->_user->hasHomePage()) { // NewUser
228 $WikiTheme->CbNewUserLogin($this, $this->_user->_userid);
229 if (in_array($this->getArg('action'), array('edit', 'create')))
230 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
232 } elseif ($when == 'logout') {
233 $WikiTheme->CbUserLogout($this, $this->_user->_userid);
234 } elseif ($when == 'default') {
236 if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser
237 if (in_array($this->getArg('action'), array('edit', 'create')))
238 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
243 // This really maybe should be part of the constructor, but since it
244 // may involve HTML/template output, the global $request really needs
245 // to be initialized before we do this stuff.
246 // [50ms]: 36ms if wikidb_page::exists
247 function updateAuthAndPrefs()
250 if (isset($this->_user) and (!is_a($this->_user, WikiUserClassname()))) {
251 $this->_user = false;
253 // Handle authentication request, if any.
254 if ($auth_args = $this->getArg('auth')) {
255 $this->setArg('auth', false);
256 $this->_handleAuthRequest($auth_args); // possible NORETURN
257 } elseif (!$this->_user
258 or (is_a($this->_user, WikiUserClassname())
259 and !$this->_user->isSignedIn())
261 // If not auth request, try to sign in as saved user.
262 if (($saved_user = $this->getPref('userid')) != false) {
263 $this->_signIn($saved_user);
267 $action = $this->getArg('action');
269 // Save preferences in session and cookie
270 if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') {
271 if (isset($this->_user) and $this->_user->_userid) {
272 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
273 $this->_user->setPreferences($this->_prefs, true);
276 $tmpuser = $this->_user; // clone it
277 $this->setSessionVar('wiki_user', $tmpuser);
281 // Ensure user has permissions for action
282 // HACK ALERT: We may not set the request arg to create,
283 // since the pageeditor has an ugly logic for action == create.
284 if ($action == 'edit' or $action == 'create') {
285 $page = $this->getPage();
286 if (!$page->exists())
291 if (!ENABLE_PAGEPERM) { // Bug #1438392 by Matt Brown
292 $require_level = $this->requiredAuthority($action);
293 if (!$this->_user->hasAuthority($require_level))
294 $this->_notAuthorized($require_level); // NORETURN
296 // novatrope patch to let only _AUTHENTICATED view pages.
297 // If there's not enough authority or forbidden, ask for a password,
298 // unless it's explicitly unobtainable. Some bad magic though.
299 if ($this->requiredAuthorityForAction($action) == WIKIAUTH_UNOBTAINABLE) {
300 $require_level = $this->requiredAuthority($action);
301 $this->_notAuthorized($require_level); // NORETURN
308 if (isset($this->_user))
311 return $GLOBALS['ForbiddenUser'];
314 function & getGroup()
316 if (isset($this->_user) and isset($this->_user->_group))
317 return $this->_user->_group;
319 // Debug Strict: Only variable references should be returned by reference
320 $this->_user->_group = WikiGroup::getGroup();
321 return $this->_user->_group;
325 function & getPrefs()
327 return $this->_prefs;
330 // Convenience function:
331 function getPref($key)
333 if (isset($this->_prefs)) {
334 return $this->_prefs->get($key);
345 * Get requested page from the page database.
346 * By default it will grab the page requested via the URL
348 * This is a convenience function.
349 * @param string $pagename Name of page to get.
350 * @return WikiDB_Page Object with methods to pull data from
351 * database for the page requested.
353 function getPage($pagename = '')
356 $pagename = $this->getArg('pagename');
358 return $this->_dbi->getPage($pagename);
361 /** Get URL for POST actions.
363 * Officially, we should just use SCRIPT_NAME (or some such),
364 * but that causes problems when we try to issue a redirect, e.g.
365 * after saving a page.
367 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
368 * a redirect from a page to itself.)
370 * So, as a HACK, we include pagename and action as query args in
371 * the URL. (These should be ignored when we receive the POST
374 function getPostURL($pagename = false)
376 global $HTTP_GET_VARS;
378 if ($pagename === false)
379 $pagename = $this->getArg('pagename');
380 $action = $this->getArg('action');
381 if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
382 return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
383 elseif ($action == 'edit')
384 return WikiURL($pagename);
386 return WikiURL($pagename, array('action' => $action));
389 function _handleAuthRequest($auth_args)
391 if (!is_array($auth_args))
394 // Ignore password unless POST'ed.
395 if (!$this->isPost())
396 unset($auth_args['passwd']);
398 $olduser = $this->_user;
399 $user = $this->_user->AuthCheck($auth_args);
400 if (is_string($user)) {
401 // Login attempt failed.
402 $fail_message = $user;
403 $auth_args['pass_required'] = true;
404 // if clicked just on to the "sign in as:" button dont print invalid username.
405 if (!empty($auth_args['login']) and empty($auth_args['userid']))
407 // If no password was submitted, it's not really
408 // a failure --- just need to prompt for password...
409 if (!ALLOW_USER_PASSWORDS
411 and !isset($auth_args['passwd'])
413 $fail_message = false;
415 $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
416 $this->finish(); //NORETURN
417 } elseif (is_a($user, WikiUserClassname())) {
418 // Successful login (or logout.)
419 $this->_setUser($user);
421 // Login request cancelled.
426 * Attempt to sign in (bogo-login).
430 * @param $userid string Userid to attempt to sign in as.
432 private function _signIn($userid)
435 $this->_user = new _BogoUser($userid);
436 // FIXME: is this always false? shouldn't we try passuser first?
438 $this->_user = new _PassUser($userid);
439 $user = $this->_user->AuthCheck(array('userid' => $userid));
440 if (is_a($user, WikiUserClassname())) {
441 $this->_setUser($user); // success!
445 // login or logout or restore state
446 function _setUser(&$user)
448 $this->_user =& $user;
449 if (defined('MAIN_setUser')) return; // don't set cookies twice
450 $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(),
451 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
452 $isSignedIn = $user->isSignedIn();
454 $user->_authhow = 'signin';
457 // Save userid to prefs..
458 if (empty($this->_user->_prefs)) {
459 $this->_user->_prefs = $this->_user->getPreferences();
460 $this->_prefs =& $this->_user->_prefs;
462 $this->_user->_group = $this->getGroup();
463 $this->setSessionVar('wiki_user', $user);
464 $this->_prefs->set('userid',
465 $isSignedIn ? $user->getId() : '');
466 $this->initializeTheme($isSignedIn ? 'login' : 'logout');
467 define('MAIN_setUser', true);
470 /* Permission system */
471 function getLevelDescription($level)
473 static $levels = false;
474 if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0"
475 $levels = array('x-1' => _("FORBIDDEN"),
480 'x100' => _("UNOBTAINABLE"));
483 if (!empty($levels["x" . $level]))
484 return $levels["x" . $level];
489 function _notAuthorized($require_level)
491 // Display the authority message in the Wiki's default
492 // language, in case it is not english.
494 // Note that normally a user will not see such an error once
495 // logged in, unless the admin has altered the default
496 // disallowed wikiactions. In that case we should probably
497 // check the user's language prefs too at this point; this
498 // would be a situation which is not really handled with the
500 if (empty($GLOBALS['LANG']))
501 update_locale(DEFAULT_LANGUAGE);
503 // User does not have required authority. Prompt for login.
504 $action = $this->getArg('action');
505 $what = $this->getActionDescription($action);
506 $pass_required = ($require_level >= WIKIAUTH_USER);
507 if ($require_level == WIKIAUTH_UNOBTAINABLE) {
508 global $DisabledActions;
509 if ($DisabledActions and in_array($action, $DisabledActions)) {
510 $msg = fmt("%s is disallowed on this wiki.",
511 $this->getDisallowedActionDescription($this->getArg('action')));
512 $this->_user->PrintLoginForm($this, compact('require_level'), $msg);
516 // Is the reason a missing ACL or just wrong user or password?
517 if (class_exists('PagePermission')) {
518 $user =& $this->_user;
519 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
520 $msg = fmt("%s %s %s is disallowed on this wiki for %s user ā%sā (level: %s).",
521 _("Missing PagePermission:"),
522 action2access($this->getArg('action')),
523 $this->getArg('pagename'),
524 $status, $user->getId(), $this->getLevelDescription($user->_level));
525 // TODO: add link to action=setacl
526 $user->PrintLoginForm($this, compact('pass_required'), $msg);
530 $msg = fmt("%s is disallowed on this wiki.",
531 $this->getDisallowedActionDescription($this->getArg('action')));
532 $this->_user->PrintLoginForm($this, compact('require_level', 'pass_required'), $msg);
536 } elseif ($require_level == WIKIAUTH_BOGO)
537 $msg = fmt("You must sign in to %s.", $what); elseif ($require_level == WIKIAUTH_USER) {
538 // LoginForm should display the relevant messages...
540 /*if (!ALLOW_ANON_USER)
541 $msg = fmt("You must log in first to %s", $what);
543 $msg = fmt("You must log in to %s.", $what);
545 } elseif ($require_level == WIKIAUTH_ANON)
546 $msg = fmt("Access for you is forbidden to %s.", $what); else
547 $msg = fmt("You must be an administrator to %s.", $what);
549 $this->_user->PrintLoginForm($this, compact('require_level', 'pass_required'),
551 if (!$GLOBALS['WikiTheme']->DUMP_MODE)
552 $this->finish(); // NORETURN
555 // Fixme: for PagePermissions we'll need other strings,
556 // relevant to the requested page, not just for the action on the whole wiki.
557 function getActionDescription($action)
559 static $actionDescriptions;
560 if (!$actionDescriptions) {
562 = array('browse' => _("view this page"),
563 'diff' => _("diff this page"),
564 'dumphtml' => _("dump html pages"),
565 'dumpserial' => _("dump serial pages"),
566 'edit' => _("edit this page"),
567 'rename' => _("rename this page"),
568 'revert' => _("revert to a previous version of this page"),
569 'create' => _("create this page"),
570 'loadfile' => _("load files into this wiki"),
571 'lock' => _("lock this page"),
572 'purge' => _("purge this page"),
573 'remove' => _("remove this page"),
574 'unlock' => _("unlock this page"),
575 'upload' => _("upload a zip dump"),
576 'verify' => _("verify the current action"),
577 'viewsource' => _("view the source of this page"),
578 'xmlrpc' => _("access this wiki via XML-RPC"),
579 'soap' => _("access this wiki via SOAP"),
580 'zip' => _("download a zip dump from this wiki"),
581 'ziphtml' => _("download a html zip dump from this wiki")
584 if (in_array($action, array_keys($actionDescriptions)))
585 return $actionDescriptions[$action];
587 return _("use") . " " . $action;
591 TODO: check against these cases:
592 if ($DisabledActions and in_array($action, $DisabledActions))
593 return WIKIAUTH_UNOBTAINABLE;
595 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
596 return requiredAuthorityForPage($action);
598 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
600 function getDisallowedActionDescription($action)
602 static $disallowedActionDescriptions;
604 if (!$disallowedActionDescriptions) {
605 $disallowedActionDescriptions
606 = array('browse' => _("Browsing pages"),
607 'diff' => _("Diffing pages"),
608 'dumphtml' => _("Dumping html pages"),
609 'dumpserial' => _("Dumping serial pages"),
610 'edit' => _("Editing pages"),
611 'revert' => _("Reverting to a previous version of pages"),
612 'create' => _("Creating pages"),
613 'loadfile' => _("Loading files"),
614 'lock' => _("Locking pages"),
615 'purge' => _("Purging pages"),
616 'remove' => _("Removing pages"),
617 'unlock' => _("Unlocking pages"),
618 'upload' => _("Uploading zip dumps"),
619 'verify' => _("Verify the current action"),
620 'viewsource' => _("Viewing the source of pages"),
621 'xmlrpc' => _("XML-RPC access"),
622 'soap' => _("SOAP access"),
623 'zip' => _("Downloading zip dumps"),
624 'ziphtml' => _("Downloading html zip dumps")
627 if (in_array($action, array_keys($disallowedActionDescriptions)))
628 return $disallowedActionDescriptions[$action];
633 function requiredAuthority($action)
635 $auth = $this->requiredAuthorityForAction($action);
636 if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
639 * This is a hook for plugins to require authority
640 * for posting to them.
642 * IMPORTANT: This is not a secure check, so the plugin
643 * may not assume that any POSTs to it are authorized.
644 * All this does is cause PhpWiki to prompt for login
645 * if the user doesn't have the required authority.
647 if ($this->isPost()) {
648 $post_auth = $this->getArg('require_authority_for_post');
649 if ($post_auth !== false)
650 $auth = max($auth, $post_auth);
655 function requiredAuthorityForAction($action)
657 global $DisabledActions;
659 if ($DisabledActions and in_array($action, $DisabledActions))
660 return WIKIAUTH_UNOBTAINABLE;
662 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
663 return requiredAuthorityForPage($action);
676 return WIKIAUTH_ANON;
681 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
682 return WIKIAUTH_ADMIN;
683 return WIKIAUTH_ANON;
687 return WIKIAUTH_ADMIN;
688 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
689 return WIKIAUTH_ADMIN;
690 return WIKIAUTH_ANON;
693 if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
694 return WIKIAUTH_ANON;
695 return WIKIAUTH_ADMIN;
699 return WIKIAUTH_ADMIN;
700 return WIKIAUTH_ANON;
705 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
706 return WIKIAUTH_BOGO;
707 return WIKIAUTH_ANON;
708 // return WIKIAUTH_BOGO;
711 $page = $this->getPage();
712 $current = $page->getCurrentRevision();
713 if ($current->hasDefaultContents())
714 return $this->requiredAuthorityForAction('edit');
715 return $this->requiredAuthorityForAction('browse');
728 return WIKIAUTH_ADMIN;
730 /* authcheck occurs only in the plugin.
731 required actionpage RateIt */
734 case 'delete_rating':
735 // Perhaps this should be WIKIAUTH_USER
736 return WIKIAUTH_BOGO;
740 global $WikiNameRegexp;
741 if (preg_match("/$WikiNameRegexp\Z/A", $action))
742 return WIKIAUTH_ANON; // ActionPage.
744 return WIKIAUTH_ADMIN;
749 /* End of Permission system */
751 function possiblyDeflowerVirginWiki()
753 if ($this->getArg('action') != 'browse')
755 if ($this->getArg('pagename') != HOME_PAGE)
758 $page = $this->getPage();
759 $current = $page->getCurrentRevision();
760 if ($current->getVersion() > 0)
761 return; // Homepage exists.
763 include_once 'lib/loadsave.php';
764 $this->setArg('action', 'loadfile');
766 $this->finish(); // NORETURN
769 // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
770 function handleAction()
772 // Check illegal characters in page names: <>[]{}|"
773 require_once 'lib/Template.php';
774 $page = $this->getPage();
775 $pagename = $page->getName();
776 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
777 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH - 1) . 'ā¦';
778 $CONTENT = HTML::div(array('class' => 'error'),
779 _('Page name too long'));
780 GeneratePage($CONTENT, $pagename);
783 if (preg_match("/[<\[\{\|\"\}\]>]/", $pagename, $matches) > 0) {
784 $CONTENT = HTML::div(
785 array('class' => 'error'),
786 sprintf(_("Illegal character ā%sā in page name."),
788 GeneratePage($CONTENT, $pagename);
791 $action = $this->getArg('action');
793 and !$this->_user->isAdmin()
794 and $action != 'browse'
795 and $action != 'wikitohtml'
797 if ($page->get('moderation')) {
798 require_once 'lib/WikiPlugin.php';
799 $loader = new WikiPluginLoader();
800 $plugin = $loader->getPlugin("ModeratedPage");
801 if ($plugin->handler($this, $page)) {
804 array('class' => 'wiki-edithelp'),
805 fmt("%s: action forwarded to a moderator.",
808 _("This action requires moderator approval. Please be patient."));
809 if (!empty($plugin->_tokens['CONTENT']))
810 $plugin->_tokens['CONTENT']->pushContent
813 _("You must wait for moderator approval."));
815 $plugin->_tokens['CONTENT'] = $CONTENT;
816 $title = WikiLink($page->getName());
817 $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
818 GeneratePage(Template('browse', $plugin->_tokens),
820 $page->getCurrentRevision());
825 $method = "action_$action";
826 if (method_exists($this, $method)) {
828 } elseif ($page = $this->findActionPage($action)) {
829 $this->actionpage($page);
831 $this->finish(fmt("%s: Bad action", $action));
835 function finish($errormsg = '')
840 exit(); // just in case CloseDataBase calls us
843 global $ErrorManager;
844 $ErrorManager->flushPostponedErrors();
846 if (!empty($errormsg)) {
849 HTML::h2(_("Fatal PhpWiki Error")),
852 echo "\n</body></html>";
854 if (is_object($this->_user)) {
855 $this->_user->page = $this->getArg('pagename');
856 $this->_user->action = $this->getArg('action');
857 unset($this->_user->_HomePagehandle);
858 unset($this->_user->_auth_dbi);
859 unset($this->_user->_dbi);
860 unset($this->_user->_request);
867 * Generally pagename is rawurlencoded for older browsers or mozilla.
868 * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
869 * If false, we support either "/index.php?pagename=PageName&arg=value",
870 * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
872 function _deducePagename()
874 if (trim(rawurldecode($this->getArg('pagename'))))
875 return rawurldecode($this->getArg('pagename'));
878 $pathinfo = $this->get('PATH_INFO');
879 if (empty($pathinfo)) { // fix for CGI
880 $path = $this->get('REQUEST_URI');
881 $script = $this->get('SCRIPT_NAME');
882 $pathinfo = substr($path, strlen($script));
883 $pathinfo = preg_replace('/\?.+$/', '', $pathinfo);
885 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
887 if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
890 } elseif ($this->isPost()) {
892 * In general, for security reasons, HTTP_GET_VARS should be ignored
893 * on POST requests, but we make an exception here (only for pagename).
895 * The justification for this hack is the following
896 * asymmetry: When POSTing with USE_PATH_INFO set, the
897 * pagename can (and should) be communicated through the
898 * request URL via PATH_INFO. When POSTing with
899 * USE_PATH_INFO off, this cannot be done --- the only way
900 * to communicate the pagename through the URL is via
901 * QUERY_ARGS (HTTP_GET_VARS).
903 global $HTTP_GET_VARS;
904 if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) {
905 return rawurldecode($HTTP_GET_VARS['pagename']);
910 * Support for PhpWiki 1.2 style requests.
911 * Strip off "&" args (?PageName&action=...&start_debug,...)
913 $query_string = $this->get('QUERY_STRING');
914 if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
915 return rawurldecode($m[1]);
921 function _deduceAction()
923 if (!($action = $this->getArg('action'))) {
924 // TODO: improve this SOAP.php hack by letting SOAP use index.php
925 // or any other virtual url as with xmlrpc
926 if (defined('WIKI_SOAP') and WIKI_SOAP)
928 // Detect XML-RPC requests.
930 && ((defined("WIKI_XMLRPC") and WIKI_XMLRPC)
931 or ($this->get('CONTENT_TYPE') == 'text/xml'
932 or $this->get('CONTENT_TYPE') == 'application/xml')
933 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>'))
937 return 'browse'; // Default if no action specified.
940 if (method_exists($this, "action_$action"))
943 // Allow for, e.g. action=LikePages
944 if (isActionPage($action))
947 // Handle untranslated actionpages in non-english
948 // (people playing with switching languages)
949 if (0 and $GLOBALS['LANG'] != 'en') {
950 require_once 'lib/plugin/WikiTranslation.php';
951 $trans = new WikiPlugin_WikiTranslation();
952 $en_action = $trans->translate($action, 'en', $GLOBALS['LANG']);
953 if (isActionPage($en_action))
957 trigger_error("$action: Unknown action", E_USER_NOTICE);
961 function _deduceUsername()
963 global $HTTP_ENV_VARS;
965 if ($this->getArg('auth')) {
966 $auth = $this->getArg('auth');
967 if (isset($auth['userid'])) {
968 return $auth['userid'];
972 if ($user = $this->getSessionVar('wiki_user')) {
973 // Switched auth between sessions.
974 // Note: There's no way to demandload a missing class-definition
975 // afterwards! Stupid php.
976 if (defined('FUSIONFORGE') and FUSIONFORGE) {
977 if (empty($_SERVER['PHP_AUTH_USER'])) {
980 } elseif (is_a($user, WikiUserClassname())) {
981 $this->_user = $user;
982 $this->_user->_authhow = 'session';
983 return $user->UserName();
987 // Sessions override http auth
988 if (!empty($_SERVER['PHP_AUTH_USER']))
989 return $_SERVER['PHP_AUTH_USER'];
991 if (!empty($_SERVER['REMOTE_USER']))
992 return $_SERVER['REMOTE_USER'];
993 if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
994 return $HTTP_ENV_VARS['REMOTE_USER'];
996 if ($userid = $this->getCookieVar(getCookieName())) {
997 if (!empty($userid) and substr($userid, 0, 2) != 's:') {
998 $this->_user->authhow = 'cookie';
1003 if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
1004 if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
1005 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
1006 // wiki.putPage has special otional userid/passwd arguments. check that later.
1008 if (isset($_SERVER['REMOTE_USER']))
1009 $userid = $_SERVER['REMOTE_USER'];
1010 elseif (isset($_SERVER['REMOTE_ADDR']))
1011 $userid = $_SERVER['REMOTE_ADDR']; elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
1012 $userid = $HTTP_ENV_VARS['REMOTE_ADDR']; elseif (isset($GLOBALS['REMOTE_ADDR']))
1013 $userid = $GLOBALS['REMOTE_ADDR'];
1020 function findActionPage($action)
1023 if (!$action) return false;
1025 if (isActionPage($action))
1026 return $cache[$action] = $action;
1028 // check for translated version, as per users preferred language
1029 // (or system default in case it is not en)
1030 $translation = gettext($action);
1032 if (isset($cache) and isset($cache[$translation]))
1033 return $cache[$translation];
1035 // check for cached translated version
1036 if ($translation and isActionPage($translation))
1037 return $cache[$action] = $translation;
1039 // Allow for, e.g. action=LikePages
1040 if (!isWikiWord($action))
1041 return $cache[$action] = false;
1043 // check for translated version (default language)
1045 if ($LANG != "en") {
1046 require_once 'lib/WikiPlugin.php';
1047 require_once 'lib/plugin/WikiTranslation.php';
1048 $trans = new WikiPlugin_WikiTranslation();
1049 $trans->lang = $LANG;
1050 $default = $trans->translate_to_en($action, $LANG);
1051 if ($default and isActionPage($default))
1052 return $cache[$action] = $default;
1054 $default = $translation;
1057 // check for english version
1058 if ($action != $translation and $action != $default) {
1059 if (isActionPage($action))
1060 return $cache[$action] = $action;
1063 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1064 return $cache[$action] = false;
1067 function action_browse()
1069 $this->buffer_output();
1070 include_once 'lib/display.php';
1074 function action_verify()
1076 $this->action_browse();
1079 function actionpage($action)
1081 $this->buffer_output();
1082 include_once 'lib/display.php';
1083 actionPage($this, $action);
1086 function adminActionSubpage($subpage)
1088 $page = __("PhpWikiAdministration") . "/" . $subpage;
1089 $action = $this->findActionPage($page);
1091 if (!$this->getArg('s'))
1092 $this->setArg('s', $this->getArg('pagename'));
1093 $this->setArg('verify', 1); // only for POST
1094 if ($this->getArg('action') != 'rename')
1095 $this->setArg('action', $action);
1096 elseif ($this->getArg('to') && !$this->getArg('admin_rename')) {
1097 $this->setArg('admin_rename',
1098 array('from' => $this->getArg('s'),
1099 'to' => $this->getArg('to'),
1100 'action' => 'select'));
1102 $this->actionpage($action);
1104 trigger_error($page . ": Cannot find action page", E_USER_WARNING);
1108 function action_chown()
1110 $this->adminActionSubpage(__("Chown"));
1113 function action_setacl()
1115 $this->adminActionSubpage(__("SetAcl"));
1118 function action_setaclsimple()
1120 $this->adminActionSubpage(__("SetAclSimple"));
1123 function action_deleteacl()
1125 $this->adminActionSubpage(__("DeleteAcl"));
1128 function action_rename()
1130 $this->adminActionSubpage(__("Rename"));
1133 function action_dump()
1135 $action = $this->findActionPage(_("PageDump"));
1137 $this->actionpage($action);
1139 // redirect to action=upgrade if admin?
1140 trigger_error(_("PageDump") . ": Cannot find action page", E_USER_WARNING);
1144 function action_diff()
1146 $this->buffer_output();
1147 include_once 'lib/diff.php';
1151 function action_search()
1153 // Decide between title or fulltextsearch (e.g. both buttons available).
1154 // Reformulate URL and redirect.
1155 $searchtype = $this->getArg('searchtype');
1156 $args = array('s' => $this->getArg('searchterm')
1157 ? $this->getArg('searchterm')
1158 : $this->getArg('s'));
1159 if ($searchtype == 'full' or $searchtype == 'fulltext') {
1160 $search_page = _("FullTextSearch");
1161 } elseif ($searchtype == 'external') {
1163 $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1164 $this->redirect($link->url);
1166 $search_page = _("TitleSearch");
1167 $args['auto_redirect'] = 1;
1169 $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1172 function action_edit()
1174 $this->buffer_output();
1175 include 'lib/editpage.php';
1176 $e = new PageEditor ($this);
1180 function action_create()
1182 $this->action_edit();
1185 function action_viewsource()
1187 $this->buffer_output();
1188 include 'lib/editpage.php';
1189 $e = new PageEditor ($this);
1193 function action_lock()
1195 $page = $this->getPage();
1196 $page->set('locked', true);
1197 $this->_dbi->touch();
1198 // check ModeratedPage hook
1199 if ($moderated = $page->get('moderation')) {
1200 require_once 'lib/WikiPlugin.php';
1201 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1202 if ($retval = $plugin->lock_check($this, $page, $moderated))
1203 $this->setArg('errormsg', $retval);
1204 } // check if a link to ModeratedPage exists
1205 elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1206 require_once 'lib/WikiPlugin.php';
1207 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1208 if ($retval = $plugin->lock_add($this, $page, $action_page))
1209 $this->setArg('errormsg', $retval);
1211 $this->action_browse();
1214 function action_unlock()
1216 $page = $this->getPage();
1217 $page->set('locked', false);
1218 $this->_dbi->touch();
1219 $this->action_browse();
1222 function action_purge()
1224 $pagename = $this->getArg('pagename');
1225 if (strstr($pagename, _("PhpWikiAdministration"))) {
1226 $this->action_browse();
1228 include 'lib/purgepage.php';
1233 function action_remove()
1235 // This check is now redundant.
1236 //$user->requireAuth(WIKIAUTH_ADMIN);
1237 $pagename = $this->getArg('pagename');
1238 if (strstr($pagename, _("PhpWikiAdministration"))) {
1239 $this->action_browse();
1241 include 'lib/removepage.php';
1246 function action_xmlrpc()
1248 include_once 'lib/XmlRpcServer.php';
1249 $xmlrpc = new XmlRpcServer($this);
1253 function action_soap()
1255 if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1258 allow VIRTUAL_PATH or action=soap SOAP access
1260 include_once 'SOAP.php';
1263 function action_revert()
1265 include_once 'lib/loadsave.php';
1269 function action_zip()
1271 include_once 'lib/loadsave.php';
1275 function action_ziphtml()
1277 include_once 'lib/loadsave.php';
1278 MakeWikiZipHtml($this);
1279 // I don't think it hurts to add cruft at the end of the zip file.
1280 echo "\n========================================================\n";
1281 echo "PhpWiki " . PHPWIKI_VERSION . "\n";
1284 function action_dumpserial()
1286 include_once 'lib/loadsave.php';
1290 function action_dumphtml()
1292 include_once 'lib/loadsave.php';
1293 DumpHtmlToDir($this);
1296 function action_upload()
1298 include_once 'lib/loadsave.php';
1299 LoadPostFile($this);
1302 function action_upgrade()
1304 include_once 'lib/loadsave.php';
1305 include_once 'lib/upgrade.php';
1309 function action_loadfile()
1311 include_once 'lib/loadsave.php';
1312 LoadFileOrDir($this);
1315 function action_pdf()
1317 include_once 'lib/pdf.php';
1318 ConvertAndDisplayPdf($this);
1321 function action_captcha()
1323 include_once 'lib/Captcha.php';
1324 $captcha = new Captcha();
1325 $captcha->image($captcha->captchaword());
1328 function action_wikitohtml()
1330 include_once 'lib/WysiwygEdit/Wikiwyg.php';
1331 $wikitohtml = new WikiToHtml($this->getArg("content"), $this);
1332 $wikitohtml->send();
1335 function action_setpref()
1337 $what = $this->getArg('pref');
1338 $value = $this->getArg('value');
1339 $prefs =& $this->_user->_prefs;
1340 $prefs->set($what, $value);
1341 $this->_user->setPreferences($prefs);
1345 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1346 function is_safe_action($action)
1349 return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1352 function validateSessionPath()
1354 // Try to defer any session.save_path PHP errors before any html
1355 // is output, which causes some versions of IE to display a blank
1356 // page (due to its strict mode while parsing a page?).
1357 if (!is_writeable(ini_get('session.save_path'))) {
1358 $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1359 if (!is_writeable($tmpdir))
1362 (sprintf(_("%s is not writable."),
1363 _("The session.save_path directory"))
1365 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1366 sprintf(_("the session.save_path directory ā%sā"),
1367 ini_get('session.save_path')),
1368 'SESSION_SAVE_PATH')
1370 . sprintf(_("Attempting to use the directory ā%sā instead."),
1373 if (!is_writeable($tmpdir)) {
1375 (sprintf(_("%s is not writable."), $tmpdir)
1377 . _("Users will not be able to sign in.")
1380 @ini_set('session.save_path', $tmpdir);
1386 if (version_compare(PHP_VERSION, '5.3', '<')) {
1387 exit(_("Your PHP version is too old. You must have at least PHP 5.3."));
1390 if (!USE_DB_SESSION)
1391 validateSessionPath();
1394 if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) {
1395 //apd_set_session_trace(9);
1396 apd_set_pprof_trace();
1399 // Postpone warnings
1400 global $ErrorManager;
1401 if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1402 $ErrorManager->setPostponedErrorMask(E_NOTICE | E_USER_NOTICE | E_USER_WARNING | E_WARNING | E_STRICT | E_DEPRECATED);
1404 $ErrorManager->setPostponedErrorMask(E_NOTICE | E_USER_NOTICE | E_USER_WARNING | E_WARNING);
1405 $request = new WikiRequest();
1407 $action = $request->getArg('action');
1408 if (substr($action, 0, 3) != 'zip') {
1409 if ($action == 'pdf')
1410 $ErrorManager->setPostponedErrorMask(-1); // everything
1411 //else // reject postponing of warnings
1412 // $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1416 * Allow for disabling of markup cache.
1417 * (Mostly for debugging ... hopefully.)
1419 * See also <<WikiAdminUtils action=purge-cache>>
1421 if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1422 if ($request->getArg('nocache')) // 1 or purge
1423 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1425 define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1428 // Initialize with system defaults in case user not logged in.
1429 // Should this go into the constructor?
1430 $request->initializeTheme('default');
1431 $request->updateAuthAndPrefs();
1432 $request->initializeLang();
1434 $request->possiblyDeflowerVirginWiki();
1436 $validators = array('wikiname' => WIKI_NAME,
1437 'args' => wikihash($request->getArgs()),
1438 'prefs' => wikihash($request->getPrefs()));
1439 if (CACHE_CONTROL == 'STRICT') {
1440 $dbi = $request->getDbh();
1441 $timestamp = $dbi->getTimestamp();
1442 $validators['mtime'] = $timestamp;
1443 $validators['%mtime'] = (int)$timestamp;
1445 // FIXME: we should try to generate strong validators when possible,
1446 // but for now, our validator is weak, since equal validators do not
1447 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
1449 // (If DEBUG if off, this may be a strong validator, but I'm going
1450 // to go the paranoid route here pending further study and testing.)
1451 // access hits and edit stats in the footer violate strong ETags also.
1453 $validators['%weak'] = true;
1455 $request->setValidators($validators);
1457 $request->handleAction();
1459 if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1463 if ((!(defined('FUSIONFORGE') and FUSIONFORGE)) || (forge_get_config('installation_environment') != 'production')) {
1464 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1465 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
1467 error_reporting(E_ALL); // php4
1469 error_reporting(E_ERROR);
1472 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1473 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1479 // c-basic-offset: 4
1480 // c-hanging-comment-ender-p: nil
1481 // indent-tabs-mode: nil