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 $this->Request(); // [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 (!isa($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 (isa($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 (!isa($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 (isa($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);
344 * Get requested page from the page database.
345 * By default it will grab the page requested via the URL
347 * This is a convenience function.
348 * @param string $pagename Name of page to get.
349 * @return WikiDB_Page Object with methods to pull data from
350 * database for the page requested.
352 function getPage($pagename = '')
355 $pagename = $this->getArg('pagename');
357 return $this->_dbi->getPage($pagename);
360 /** Get URL for POST actions.
362 * Officially, we should just use SCRIPT_NAME (or some such),
363 * but that causes problems when we try to issue a redirect, e.g.
364 * after saving a page.
366 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
367 * a redirect from a page to itself.)
369 * So, as a HACK, we include pagename and action as query args in
370 * the URL. (These should be ignored when we receive the POST
373 function getPostURL($pagename = false)
375 global $HTTP_GET_VARS;
377 if ($pagename === false)
378 $pagename = $this->getArg('pagename');
379 $action = $this->getArg('action');
380 if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
381 return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
382 elseif ($action == 'edit')
383 return WikiURL($pagename);
385 return WikiURL($pagename, array('action' => $action));
388 function _handleAuthRequest($auth_args)
390 if (!is_array($auth_args))
393 // Ignore password unless POST'ed.
394 if (!$this->isPost())
395 unset($auth_args['passwd']);
397 $olduser = $this->_user;
398 $user = $this->_user->AuthCheck($auth_args);
399 if (is_string($user)) {
400 // Login attempt failed.
401 $fail_message = $user;
402 $auth_args['pass_required'] = true;
403 // if clicked just on to the "sign in as:" button dont print invalid username.
404 if (!empty($auth_args['login']) and empty($auth_args['userid']))
406 // If no password was submitted, it's not really
407 // a failure --- just need to prompt for password...
408 if (!ALLOW_USER_PASSWORDS
410 and !isset($auth_args['passwd'])
412 $fail_message = false;
414 $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
415 $this->finish(); //NORETURN
416 } elseif (isa($user, WikiUserClassname())) {
417 // Successful login (or logout.)
418 $this->_setUser($user);
420 // Login request cancelled.
425 * Attempt to sign in (bogo-login).
429 * @param $userid string Userid to attempt to sign in as.
431 private function _signIn($userid)
434 $this->_user = new _BogoUser($userid);
435 // FIXME: is this always false? shouldn't we try passuser first?
437 $this->_user = new _PassUser($userid);
438 $user = $this->_user->AuthCheck(array('userid' => $userid));
439 if (isa($user, WikiUserClassname())) {
440 $this->_setUser($user); // success!
444 // login or logout or restore state
445 function _setUser(&$user)
447 $this->_user =& $user;
448 if (defined('MAIN_setUser')) return; // don't set cookies twice
449 $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(),
450 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
451 $isSignedIn = $user->isSignedIn();
453 $user->_authhow = 'signin';
456 // Save userid to prefs..
457 if (empty($this->_user->_prefs)) {
458 $this->_user->_prefs = $this->_user->getPreferences();
459 $this->_prefs =& $this->_user->_prefs;
461 $this->_user->_group = $this->getGroup();
462 $this->setSessionVar('wiki_user', $user);
463 $this->_prefs->set('userid',
464 $isSignedIn ? $user->getId() : '');
465 $this->initializeTheme($isSignedIn ? 'login' : 'logout');
466 define('MAIN_setUser', true);
469 /* Permission system */
470 function getLevelDescription($level)
472 static $levels = false;
473 if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0"
474 $levels = array('x-1' => _("FORBIDDEN"),
479 'x100' => _("UNOBTAINABLE"));
482 if (!empty($levels["x" . $level]))
483 return $levels["x" . $level];
488 function _notAuthorized($require_level)
490 // Display the authority message in the Wiki's default
491 // language, in case it is not english.
493 // Note that normally a user will not see such an error once
494 // logged in, unless the admin has altered the default
495 // disallowed wikiactions. In that case we should probably
496 // check the user's language prefs too at this point; this
497 // would be a situation which is not really handled with the
499 if (empty($GLOBALS['LANG']))
500 update_locale(DEFAULT_LANGUAGE);
502 // User does not have required authority. Prompt for login.
503 $action = $this->getArg('action');
504 $what = $this->getActionDescription($action);
505 $pass_required = ($require_level >= WIKIAUTH_USER);
506 if ($require_level == WIKIAUTH_UNOBTAINABLE) {
507 global $DisabledActions;
508 if ($DisabledActions and in_array($action, $DisabledActions)) {
509 $msg = fmt("%s is disallowed on this wiki.",
510 $this->getDisallowedActionDescription($this->getArg('action')));
511 $this->_user->PrintLoginForm($this, compact('require_level'), $msg);
515 // Is the reason a missing ACL or just wrong user or password?
516 if (class_exists('PagePermission')) {
517 $user =& $this->_user;
518 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
519 $msg = fmt("%s %s %s is disallowed on this wiki for %s user ā%sā (level: %s).",
520 _("Missing PagePermission:"),
521 action2access($this->getArg('action')),
522 $this->getArg('pagename'),
523 $status, $user->getId(), $this->getLevelDescription($user->_level));
524 // TODO: add link to action=setacl
525 $user->PrintLoginForm($this, compact('pass_required'), $msg);
529 $msg = fmt("%s is disallowed on this wiki.",
530 $this->getDisallowedActionDescription($this->getArg('action')));
531 $this->_user->PrintLoginForm($this, compact('require_level', 'pass_required'), $msg);
535 } elseif ($require_level == WIKIAUTH_BOGO)
536 $msg = fmt("You must sign in to %s.", $what); elseif ($require_level == WIKIAUTH_USER) {
537 // LoginForm should display the relevant messages...
539 /*if (!ALLOW_ANON_USER)
540 $msg = fmt("You must log in first to %s", $what);
542 $msg = fmt("You must log in to %s.", $what);
544 } elseif ($require_level == WIKIAUTH_ANON)
545 $msg = fmt("Access for you is forbidden to %s.", $what); else
546 $msg = fmt("You must be an administrator to %s.", $what);
548 $this->_user->PrintLoginForm($this, compact('require_level', 'pass_required'),
550 if (!$GLOBALS['WikiTheme']->DUMP_MODE)
551 $this->finish(); // NORETURN
554 // Fixme: for PagePermissions we'll need other strings,
555 // relevant to the requested page, not just for the action on the whole wiki.
556 function getActionDescription($action)
558 static $actionDescriptions;
559 if (!$actionDescriptions) {
561 = array('browse' => _("view this page"),
562 'diff' => _("diff this page"),
563 'dumphtml' => _("dump html pages"),
564 'dumpserial' => _("dump serial pages"),
565 'edit' => _("edit this page"),
566 'rename' => _("rename this page"),
567 'revert' => _("revert to a previous version of this page"),
568 'create' => _("create this page"),
569 'loadfile' => _("load files into this wiki"),
570 'lock' => _("lock this page"),
571 'purge' => _("purge this page"),
572 'remove' => _("remove this page"),
573 'unlock' => _("unlock this page"),
574 'upload' => _("upload a zip dump"),
575 'verify' => _("verify the current action"),
576 'viewsource' => _("view the source of this page"),
577 'xmlrpc' => _("access this wiki via XML-RPC"),
578 'soap' => _("access this wiki via SOAP"),
579 'zip' => _("download a zip dump from this wiki"),
580 'ziphtml' => _("download a html zip dump from this wiki")
583 if (in_array($action, array_keys($actionDescriptions)))
584 return $actionDescriptions[$action];
586 return _("use") . " " . $action;
590 TODO: check against these cases:
591 if ($DisabledActions and in_array($action, $DisabledActions))
592 return WIKIAUTH_UNOBTAINABLE;
594 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
595 return requiredAuthorityForPage($action);
597 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
599 function getDisallowedActionDescription($action)
601 static $disallowedActionDescriptions;
603 if (!$disallowedActionDescriptions) {
604 $disallowedActionDescriptions
605 = array('browse' => _("Browsing pages"),
606 'diff' => _("Diffing pages"),
607 'dumphtml' => _("Dumping html pages"),
608 'dumpserial' => _("Dumping serial pages"),
609 'edit' => _("Editing pages"),
610 'revert' => _("Reverting to a previous version of pages"),
611 'create' => _("Creating pages"),
612 'loadfile' => _("Loading files"),
613 'lock' => _("Locking pages"),
614 'purge' => _("Purging pages"),
615 'remove' => _("Removing pages"),
616 'unlock' => _("Unlocking pages"),
617 'upload' => _("Uploading zip dumps"),
618 'verify' => _("Verify the current action"),
619 'viewsource' => _("Viewing the source of pages"),
620 'xmlrpc' => _("XML-RPC access"),
621 'soap' => _("SOAP access"),
622 'zip' => _("Downloading zip dumps"),
623 'ziphtml' => _("Downloading html zip dumps")
626 if (in_array($action, array_keys($disallowedActionDescriptions)))
627 return $disallowedActionDescriptions[$action];
632 function requiredAuthority($action)
634 $auth = $this->requiredAuthorityForAction($action);
635 if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
638 * This is a hook for plugins to require authority
639 * for posting to them.
641 * IMPORTANT: This is not a secure check, so the plugin
642 * may not assume that any POSTs to it are authorized.
643 * All this does is cause PhpWiki to prompt for login
644 * if the user doesn't have the required authority.
646 if ($this->isPost()) {
647 $post_auth = $this->getArg('require_authority_for_post');
648 if ($post_auth !== false)
649 $auth = max($auth, $post_auth);
654 function requiredAuthorityForAction($action)
656 global $DisabledActions;
658 if ($DisabledActions and in_array($action, $DisabledActions))
659 return WIKIAUTH_UNOBTAINABLE;
661 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
662 return requiredAuthorityForPage($action);
675 return WIKIAUTH_ANON;
680 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
681 return WIKIAUTH_ADMIN;
682 return WIKIAUTH_ANON;
686 return WIKIAUTH_ADMIN;
687 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
688 return WIKIAUTH_ADMIN;
689 return WIKIAUTH_ANON;
692 if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
693 return WIKIAUTH_ANON;
694 return WIKIAUTH_ADMIN;
698 return WIKIAUTH_ADMIN;
699 return WIKIAUTH_ANON;
704 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
705 return WIKIAUTH_BOGO;
706 return WIKIAUTH_ANON;
707 // return WIKIAUTH_BOGO;
710 $page = $this->getPage();
711 $current = $page->getCurrentRevision();
712 if ($current->hasDefaultContents())
713 return $this->requiredAuthorityForAction('edit');
714 return $this->requiredAuthorityForAction('browse');
727 return WIKIAUTH_ADMIN;
729 /* authcheck occurs only in the plugin.
730 required actionpage RateIt */
733 case 'delete_rating':
734 // Perhaps this should be WIKIAUTH_USER
735 return WIKIAUTH_BOGO;
739 global $WikiNameRegexp;
740 if (preg_match("/$WikiNameRegexp\Z/A", $action))
741 return WIKIAUTH_ANON; // ActionPage.
743 return WIKIAUTH_ADMIN;
748 /* End of Permission system */
750 function possiblyDeflowerVirginWiki()
752 if ($this->getArg('action') != 'browse')
754 if ($this->getArg('pagename') != HOME_PAGE)
757 $page = $this->getPage();
758 $current = $page->getCurrentRevision();
759 if ($current->getVersion() > 0)
760 return; // Homepage exists.
762 include_once 'lib/loadsave.php';
763 $this->setArg('action', 'loadfile');
765 $this->finish(); // NORETURN
768 // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
769 function handleAction()
771 // Check illegal characters in page names: <>[]{}|"
772 require_once 'lib/Template.php';
773 $page = $this->getPage();
774 $pagename = $page->getName();
775 if (strlen($pagename) > MAX_PAGENAME_LENGTH) {
776 $pagename = substr($pagename, 0, MAX_PAGENAME_LENGTH - 1) . 'ā¦';
777 $CONTENT = HTML::div(array('class' => 'error'),
778 _('Page name too long'));
779 GeneratePage($CONTENT, $pagename);
782 if (preg_match("/[<\[\{\|\"\}\]>]/", $pagename, $matches) > 0) {
783 $CONTENT = HTML::div(
784 array('class' => 'error'),
785 sprintf(_("Illegal character ā%sā in page name."),
787 GeneratePage($CONTENT, $pagename);
790 $action = $this->getArg('action');
792 and !$this->_user->isAdmin()
793 and $action != 'browse'
794 and $action != 'wikitohtml'
796 if ($page->get('moderation')) {
797 require_once 'lib/WikiPlugin.php';
798 $loader = new WikiPluginLoader();
799 $plugin = $loader->getPlugin("ModeratedPage");
800 if ($plugin->handler($this, $page)) {
803 array('class' => 'wiki-edithelp'),
804 fmt("%s: action forwarded to a moderator.",
807 _("This action requires moderator approval. Please be patient."));
808 if (!empty($plugin->_tokens['CONTENT']))
809 $plugin->_tokens['CONTENT']->pushContent
812 _("You must wait for moderator approval."));
814 $plugin->_tokens['CONTENT'] = $CONTENT;
815 $title = WikiLink($page->getName());
816 $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
817 GeneratePage(Template('browse', $plugin->_tokens),
819 $page->getCurrentRevision());
824 $method = "action_$action";
825 if (method_exists($this, $method)) {
827 } elseif ($page = $this->findActionPage($action)) {
828 $this->actionpage($page);
830 $this->finish(fmt("%s: Bad action", $action));
834 function finish($errormsg = false)
839 exit(); // just in case CloseDataBase calls us
842 global $ErrorManager;
843 $ErrorManager->flushPostponedErrors();
845 if (!empty($errormsg)) {
848 HTML::h2(_("Fatal PhpWiki Error")),
851 echo "\n</body></html>";
853 if (is_object($this->_user)) {
854 $this->_user->page = $this->getArg('pagename');
855 $this->_user->action = $this->getArg('action');
856 unset($this->_user->_HomePagehandle);
857 unset($this->_user->_auth_dbi);
858 unset($this->_user->_dbi);
859 unset($this->_user->_request);
866 * Generally pagename is rawurlencoded for older browsers or mozilla.
867 * Typing a pagename into the IE bar will utf-8 encode it, so we have to
868 * fix that with fixTitleEncoding().
869 * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
870 * If false, we support either "/index.php?pagename=PageName&arg=value",
871 * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
873 function _deducePagename()
875 if (trim(rawurldecode($this->getArg('pagename'))))
876 return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
879 $pathinfo = $this->get('PATH_INFO');
880 if (empty($pathinfo)) { // fix for CGI
881 $path = $this->get('REQUEST_URI');
882 $script = $this->get('SCRIPT_NAME');
883 $pathinfo = substr($path, strlen($script));
884 $pathinfo = preg_replace('/\?.+$/', '', $pathinfo);
886 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
888 if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
889 return fixTitleEncoding($tail);
891 } elseif ($this->isPost()) {
893 * In general, for security reasons, HTTP_GET_VARS should be ignored
894 * on POST requests, but we make an exception here (only for pagename).
896 * The justification for this hack is the following
897 * asymmetry: When POSTing with USE_PATH_INFO set, the
898 * pagename can (and should) be communicated through the
899 * request URL via PATH_INFO. When POSTing with
900 * USE_PATH_INFO off, this cannot be done --- the only way
901 * to communicate the pagename through the URL is via
902 * QUERY_ARGS (HTTP_GET_VARS).
904 global $HTTP_GET_VARS;
905 if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) {
906 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
911 * Support for PhpWiki 1.2 style requests.
912 * Strip off "&" args (?PageName&action=...&start_debug,...)
914 $query_string = $this->get('QUERY_STRING');
915 if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
916 return fixTitleEncoding(rawurldecode($m[1]));
919 return fixTitleEncoding(HOME_PAGE);
922 function _deduceAction()
924 if (!($action = $this->getArg('action'))) {
925 // TODO: improve this SOAP.php hack by letting SOAP use index.php
926 // or any other virtual url as with xmlrpc
927 if (defined('WIKI_SOAP') and WIKI_SOAP)
929 // Detect XML-RPC requests.
931 && ((defined("WIKI_XMLRPC") and WIKI_XMLRPC)
932 or ($this->get('CONTENT_TYPE') == 'text/xml'
933 or $this->get('CONTENT_TYPE') == 'application/xml')
934 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>'))
938 return 'browse'; // Default if no action specified.
941 if (method_exists($this, "action_$action"))
944 // Allow for, e.g. action=LikePages
945 if (isActionPage($action))
948 // Handle untranslated actionpages in non-english
949 // (people playing with switching languages)
950 if (0 and $GLOBALS['LANG'] != 'en') {
951 require_once 'lib/plugin/WikiTranslation.php';
952 $trans = new WikiPlugin_WikiTranslation();
953 $en_action = $trans->translate($action, 'en', $GLOBALS['LANG']);
954 if (isActionPage($en_action))
958 trigger_error("$action: Unknown action", E_USER_NOTICE);
962 function _deduceUsername()
964 global $HTTP_ENV_VARS;
966 if ($this->getArg('auth')) {
967 $auth = $this->getArg('auth');
968 if (isset($auth['userid'])) {
969 return $auth['userid'];
973 if ($user = $this->getSessionVar('wiki_user')) {
974 // Switched auth between sessions.
975 // Note: There's no way to demandload a missing class-definition
976 // afterwards! Stupid php.
977 if (defined('FUSIONFORGE') and FUSIONFORGE) {
978 if (empty($_SERVER['PHP_AUTH_USER'])) {
981 } elseif (isa($user, WikiUserClassname())) {
982 $this->_user = $user;
983 $this->_user->_authhow = 'session';
984 return $user->UserName();
988 // Sessions override http auth
989 if (!empty($_SERVER['PHP_AUTH_USER']))
990 return $_SERVER['PHP_AUTH_USER'];
992 if (!empty($_SERVER['REMOTE_USER']))
993 return $_SERVER['REMOTE_USER'];
994 if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
995 return $HTTP_ENV_VARS['REMOTE_USER'];
997 if ($userid = $this->getCookieVar(getCookieName())) {
998 if (!empty($userid) and substr($userid, 0, 2) != 's:') {
999 $this->_user->authhow = 'cookie';
1004 if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
1005 if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
1006 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
1007 // wiki.putPage has special otional userid/passwd arguments. check that later.
1009 if (isset($_SERVER['REMOTE_USER']))
1010 $userid = $_SERVER['REMOTE_USER'];
1011 elseif (isset($_SERVER['REMOTE_ADDR']))
1012 $userid = $_SERVER['REMOTE_ADDR']; elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
1013 $userid = $HTTP_ENV_VARS['REMOTE_ADDR']; elseif (isset($GLOBALS['REMOTE_ADDR']))
1014 $userid = $GLOBALS['REMOTE_ADDR'];
1021 function findActionPage($action)
1024 if (!$action) return false;
1026 if (isActionPage($action))
1027 return $cache[$action] = $action;
1029 // check for translated version, as per users preferred language
1030 // (or system default in case it is not en)
1031 $translation = gettext($action);
1033 if (isset($cache) and isset($cache[$translation]))
1034 return $cache[$translation];
1036 // check for cached translated version
1037 if ($translation and isActionPage($translation))
1038 return $cache[$action] = $translation;
1040 // Allow for, e.g. action=LikePages
1041 if (!isWikiWord($action))
1042 return $cache[$action] = false;
1044 // check for translated version (default language)
1046 if ($LANG != "en") {
1047 require_once 'lib/WikiPlugin.php';
1048 require_once 'lib/plugin/WikiTranslation.php';
1049 $trans = new WikiPlugin_WikiTranslation();
1050 $trans->lang = $LANG;
1051 $default = $trans->translate_to_en($action, $LANG);
1052 if ($default and isActionPage($default))
1053 return $cache[$action] = $default;
1055 $default = $translation;
1058 // check for english version
1059 if ($action != $translation and $action != $default) {
1060 if (isActionPage($action))
1061 return $cache[$action] = $action;
1064 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1065 return $cache[$action] = false;
1068 function action_browse()
1070 $this->buffer_output();
1071 include_once 'lib/display.php';
1075 function action_verify()
1077 $this->action_browse();
1080 function actionpage($action)
1082 $this->buffer_output();
1083 include_once 'lib/display.php';
1084 actionPage($this, $action);
1087 function adminActionSubpage($subpage)
1089 $page = __("PhpWikiAdministration") . "/" . $subpage;
1090 $action = $this->findActionPage($page);
1092 if (!$this->getArg('s'))
1093 $this->setArg('s', $this->getArg('pagename'));
1094 $this->setArg('verify', 1); // only for POST
1095 if ($this->getArg('action') != 'rename')
1096 $this->setArg('action', $action);
1097 elseif ($this->getArg('to') && !$this->getArg('admin_rename')) {
1098 $this->setArg('admin_rename',
1099 array('from' => $this->getArg('s'),
1100 'to' => $this->getArg('to'),
1101 'action' => 'select'));
1103 $this->actionpage($action);
1105 trigger_error($page . ": Cannot find action page", E_USER_WARNING);
1109 function action_chown()
1111 $this->adminActionSubpage(__("Chown"));
1114 function action_setacl()
1116 $this->adminActionSubpage(__("SetAcl"));
1119 function action_setaclsimple()
1121 $this->adminActionSubpage(__("SetAclSimple"));
1124 function action_deleteacl()
1126 $this->adminActionSubpage(__("DeleteAcl"));
1129 function action_rename()
1131 $this->adminActionSubpage(__("Rename"));
1134 function action_dump()
1136 $action = $this->findActionPage(_("PageDump"));
1138 $this->actionpage($action);
1140 // redirect to action=upgrade if admin?
1141 trigger_error(_("PageDump") . ": Cannot find action page", E_USER_WARNING);
1145 function action_diff()
1147 $this->buffer_output();
1148 include_once 'lib/diff.php';
1152 function action_search()
1154 // Decide between title or fulltextsearch (e.g. both buttons available).
1155 // Reformulate URL and redirect.
1156 $searchtype = $this->getArg('searchtype');
1157 $args = array('s' => $this->getArg('searchterm')
1158 ? $this->getArg('searchterm')
1159 : $this->getArg('s'));
1160 if ($searchtype == 'full' or $searchtype == 'fulltext') {
1161 $search_page = _("FullTextSearch");
1162 } elseif ($searchtype == 'external') {
1164 $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1165 $this->redirect($link->url);
1167 $search_page = _("TitleSearch");
1168 $args['auto_redirect'] = 1;
1170 $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1173 function action_edit()
1175 $this->buffer_output();
1176 include 'lib/editpage.php';
1177 $e = new PageEditor ($this);
1181 function action_create()
1183 $this->action_edit();
1186 function action_viewsource()
1188 $this->buffer_output();
1189 include 'lib/editpage.php';
1190 $e = new PageEditor ($this);
1194 function action_lock()
1196 $page = $this->getPage();
1197 $page->set('locked', true);
1198 $this->_dbi->touch();
1199 // check ModeratedPage hook
1200 if ($moderated = $page->get('moderation')) {
1201 require_once 'lib/WikiPlugin.php';
1202 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1203 if ($retval = $plugin->lock_check($this, $page, $moderated))
1204 $this->setArg('errormsg', $retval);
1205 } // check if a link to ModeratedPage exists
1206 elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1207 require_once 'lib/WikiPlugin.php';
1208 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1209 if ($retval = $plugin->lock_add($this, $page, $action_page))
1210 $this->setArg('errormsg', $retval);
1212 $this->action_browse();
1215 function action_unlock()
1217 $page = $this->getPage();
1218 $page->set('locked', false);
1219 $this->_dbi->touch();
1220 $this->action_browse();
1223 function action_purge()
1225 $pagename = $this->getArg('pagename');
1226 if (strstr($pagename, _("PhpWikiAdministration"))) {
1227 $this->action_browse();
1229 include 'lib/purgepage.php';
1234 function action_remove()
1236 // This check is now redundant.
1237 //$user->requireAuth(WIKIAUTH_ADMIN);
1238 $pagename = $this->getArg('pagename');
1239 if (strstr($pagename, _("PhpWikiAdministration"))) {
1240 $this->action_browse();
1242 include 'lib/removepage.php';
1247 function action_xmlrpc()
1249 include_once 'lib/XmlRpcServer.php';
1250 $xmlrpc = new XmlRpcServer($this);
1254 function action_soap()
1256 if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1259 allow VIRTUAL_PATH or action=soap SOAP access
1261 include_once 'SOAP.php';
1264 function action_revert()
1266 include_once 'lib/loadsave.php';
1270 function action_zip()
1272 include_once 'lib/loadsave.php';
1276 function action_ziphtml()
1278 include_once 'lib/loadsave.php';
1279 MakeWikiZipHtml($this);
1280 // I don't think it hurts to add cruft at the end of the zip file.
1281 echo "\n========================================================\n";
1282 echo "PhpWiki " . PHPWIKI_VERSION . "\n";
1285 function action_dumpserial()
1287 include_once 'lib/loadsave.php';
1291 function action_dumphtml()
1293 include_once 'lib/loadsave.php';
1294 DumpHtmlToDir($this);
1297 function action_upload()
1299 include_once 'lib/loadsave.php';
1300 LoadPostFile($this);
1303 function action_upgrade()
1305 include_once 'lib/loadsave.php';
1306 include_once 'lib/upgrade.php';
1310 function action_loadfile()
1312 include_once 'lib/loadsave.php';
1313 LoadFileOrDir($this);
1316 function action_pdf()
1318 include_once 'lib/pdf.php';
1319 ConvertAndDisplayPdf($this);
1322 function action_captcha()
1324 include_once 'lib/Captcha.php';
1325 $captcha = new Captcha();
1326 $captcha->image($captcha->captchaword());
1329 function action_wikitohtml()
1331 include_once 'lib/WysiwygEdit/Wikiwyg.php';
1332 $wikitohtml = new WikiToHtml($this->getArg("content"), $this);
1333 $wikitohtml->send();
1336 function action_setpref()
1338 $what = $this->getArg('pref');
1339 $value = $this->getArg('value');
1340 $prefs =& $this->_user->_prefs;
1341 $prefs->set($what, $value);
1342 $this->_user->setPreferences($prefs);
1346 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1347 function is_safe_action($action)
1350 return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1353 function validateSessionPath()
1355 // Try to defer any session.save_path PHP errors before any html
1356 // is output, which causes some versions of IE to display a blank
1357 // page (due to its strict mode while parsing a page?).
1358 if (!is_writeable(ini_get('session.save_path'))) {
1359 $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1360 if (!is_writeable($tmpdir))
1363 (sprintf(_("%s is not writable."),
1364 _("The session.save_path directory"))
1366 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1367 sprintf(_("the session.save_path directory ā%sā"),
1368 ini_get('session.save_path')),
1369 'SESSION_SAVE_PATH')
1371 . sprintf(_("Attempting to use the directory ā%sā instead."),
1374 if (!is_writeable($tmpdir)) {
1376 (sprintf(_("%s is not writable."), $tmpdir)
1378 . _("Users will not be able to sign in.")
1381 @ini_set('session.save_path', $tmpdir);
1387 if (version_compare(PHP_VERSION, '5.3', '<')) {
1388 exit(_("Your PHP version is too old. You must have at least PHP 5.3."));
1391 if (!USE_DB_SESSION)
1392 validateSessionPath();
1395 if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) {
1396 //apd_set_session_trace(9);
1397 apd_set_pprof_trace();
1400 // Postpone warnings
1401 global $ErrorManager;
1402 if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1403 $ErrorManager->setPostponedErrorMask(E_NOTICE | E_USER_NOTICE | E_USER_WARNING | E_WARNING | E_STRICT | ((check_php_version(5, 3)) ? E_DEPRECATED : 0));
1405 $ErrorManager->setPostponedErrorMask(E_NOTICE | E_USER_NOTICE | E_USER_WARNING | E_WARNING);
1406 $request = new WikiRequest();
1408 $action = $request->getArg('action');
1409 if (substr($action, 0, 3) != 'zip') {
1410 if ($action == 'pdf')
1411 $ErrorManager->setPostponedErrorMask(-1); // everything
1412 //else // reject postponing of warnings
1413 // $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1417 * Allow for disabling of markup cache.
1418 * (Mostly for debugging ... hopefully.)
1420 * See also <<WikiAdminUtils action=purge-cache>>
1422 if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1423 if ($request->getArg('nocache')) // 1 or purge
1424 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1426 define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1429 // Initialize with system defaults in case user not logged in.
1430 // Should this go into the constructor?
1431 $request->initializeTheme('default');
1432 $request->updateAuthAndPrefs();
1433 $request->initializeLang();
1435 $request->possiblyDeflowerVirginWiki();
1437 $validators = array('wikiname' => WIKI_NAME,
1438 'args' => wikihash($request->getArgs()),
1439 'prefs' => wikihash($request->getPrefs()));
1440 if (CACHE_CONTROL == 'STRICT') {
1441 $dbi = $request->getDbh();
1442 $timestamp = $dbi->getTimestamp();
1443 $validators['mtime'] = $timestamp;
1444 $validators['%mtime'] = (int)$timestamp;
1446 // FIXME: we should try to generate strong validators when possible,
1447 // but for now, our validator is weak, since equal validators do not
1448 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
1450 // (If DEBUG if off, this may be a strong validator, but I'm going
1451 // to go the paranoid route here pending further study and testing.)
1452 // access hits and edit stats in the footer violate strong ETags also.
1454 $validators['%weak'] = true;
1456 $request->setValidators($validators);
1458 $request->handleAction();
1460 if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1464 if ((!(defined('FUSIONFORGE') and FUSIONFORGE)) || (forge_get_config('installation_environment') != 'production')) {
1465 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1466 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
1468 error_reporting(E_ALL); // php4
1470 error_reporting(E_ERROR);
1473 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1474 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1480 // c-basic-offset: 4
1481 // c-hanging-comment-ender-p: nil
1482 // indent-tabs-mode: nil