4 Copyright 1999-2008 $ThePhpWikiProgrammingTeam
6 This file is part of PhpWiki.
8 PhpWiki is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 PhpWiki is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with PhpWiki; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 define ('USE_PREFS_IN_PAGE', true);
25 //include "lib/config.php";
26 require_once(dirname(__FILE__)."/stdlib.php");
27 require_once('lib/Request.php');
28 require_once('lib/WikiDB.php');
30 require_once("lib/WikiUserNew.php");
32 require_once("lib/WikiUser.php");
33 require_once("lib/WikiGroup.php");
35 require_once("lib/PagePerm.php");
38 * Check permission per page.
39 * Returns true or false.
41 function mayAccessPage ($access, $pagename) {
43 return _requiredAuthorityForPagename($access, $pagename); // typically [10-20ms per page]
48 class WikiRequest extends Request {
51 function WikiRequest () {
52 $this->_dbi = WikiDB::open($GLOBALS['DBParams']);
53 // first mysql request costs [958ms]! [670ms] is mysql_connect()
55 if (in_array('File', $this->_dbi->getAuthParam('USER_AUTH_ORDER'))) {
56 // force our local copy, until the pear version is fixed.
57 include_once(dirname(__FILE__)."/pear/File_Passwd.php");
59 if (ENABLE_USER_NEW) {
60 // Preload all necessary userclasses. Otherwise session => __PHP_Incomplete_Class_Name
61 // There's no way to demand-load it later. This way it's much slower, but needs slightly
62 // less memory than loading all.
64 include_once("lib/WikiUser/BogoLogin.php");
65 // UserPreferences POST Update doesn't reach this.
66 foreach ($GLOBALS['USER_AUTH_ORDER'] as $method) {
67 include_once("lib/WikiUser/$method.php");
69 switch( DATABASE_TYPE ) {
70 case 'SQL' : include_once("lib/WikiUser/PearDb.php"); break;
71 case 'ADODB': include_once("lib/WikiUser/AdoDb.php"); break;
72 case 'PDO' : include_once("lib/WikiUser/PdoDb.php"); break;
78 include_once('lib/DbSession.php');
81 $this->_dbsession = new DbSession($dbi, $dbi->getParam('prefix')
82 . $dbi->getParam('db_session_table'));
85 // Fixme: Does pear reset the error mask to 1? We have to find the culprit
86 //$x = error_reporting();
88 $this->version = phpwiki_version();
89 $this->Request(); // [90ms]
92 $this->setArg('pagename', $this->_deducePagename());
93 $this->setArg('action', $this->_deduceAction());
95 if ((DEBUG & _DEBUG_SQL)
96 or (DATABASE_OPTIMISE_FREQUENCY > 0 and
97 (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
98 if ($this->_dbi->_backend->optimize())
99 trigger_error(_("Optimizing database"), E_USER_NOTICE);
102 // Restore auth state. This doesn't check for proper authorization!
103 $userid = $this->_deduceUsername();
104 if (ENABLE_USER_NEW) {
105 if (isset($this->_user) and
106 !empty($this->_user->_authhow) and
107 $this->_user->_authhow == 'session')
109 // users might switch in a session between the two objects.
110 // restore old auth level here or in updateAuthAndPrefs?
111 //$user = $this->getSessionVar('wiki_user');
112 // revive db handle, because these don't survive sessions
113 if (isset($this->_user) and
114 ( ! isa($this->_user, WikiUserClassname())
115 or (strtolower(get_class($this->_user)) == '_passuser')))
117 $this->_user = WikiUser($userid, $this->_user->_prefs);
119 // revive other db handle
120 if (isset($this->_user->_prefs->_method)
121 and ($this->_user->_prefs->_method == 'SQL'
122 or $this->_user->_prefs->_method == 'ADODB'
123 or $this->_user->_prefs->_method == 'PDO'
124 or $this->_user->_prefs->_method == 'HomePage')) {
125 $this->_user->_HomePagehandle = $this->getPage($userid);
127 // need to update the lockfile filehandle
128 if ( isa($this->_user, '_FilePassUser')
129 and $this->_user->_file->lockfile
130 and !$this->_user->_file->fplock )
132 //$level = $this->_user->_level;
133 $this->_user = UpgradeUser($this->_user,
134 new _FilePassUser($userid,
135 $this->_user->_prefs,
136 $this->_user->_file->filename));
137 //$this->_user->_level = $level;
139 $this->_prefs = & $this->_user->_prefs;
141 $user = WikiUser($userid);
142 $this->_user = & $user;
143 $this->_prefs = & $this->_user->_prefs;
146 $this->_user = new WikiUser($this, $userid);
147 $this->_prefs = $this->_user->getPreferences();
151 function initializeLang () {
152 // check non-default pref lang
153 if (empty($this->_prefs->_prefs['lang']))
155 $_lang = $this->_prefs->_prefs['lang'];
156 if (isset($_lang->lang) and $_lang->lang != $GLOBALS['LANG']) {
157 $user_lang = $_lang->lang;
158 //check changed LANG and THEME inside a session.
159 // (e.g. by using another baseurl)
160 if (isset($this->_user->_authhow) and $this->_user->_authhow == 'session')
161 $user_lang = $GLOBALS['LANG'];
162 update_locale($user_lang);
163 FindLocalizedButtonFile(".",'missing_ok','reinit');
165 //if (empty($_lang->lang) and $GLOBALS['LANG'] != $_lang->default_value) ;
168 function initializeTheme ($when = 'default') {
170 // if when = 'default', then first time init (default theme, ...)
171 // if when = 'login', then check some callbacks
172 // and maybe the theme changed (other theme defined in pref)
173 // if when = 'logout', then check other callbacks
174 // and maybe the theme changed (back to default theme)
176 // Load non-default theme (when = login)
177 if (!empty($this->_prefs->_prefs['theme'])) {
178 $_theme = $this->_prefs->_prefs['theme'];
179 if (isset($_theme) and isset($_theme->theme))
180 $user_theme = $_theme->theme;
181 elseif (isset($_theme) and isset($_theme->default_value))
182 $user_theme = $_theme->default_value;
187 $user_theme = $this->getPref('theme');
189 //check changed LANG and THEME inside a session.
190 // (e.g. by using another baseurl)
191 if (isset($this->_user->_authhow)
192 and $this->_user->_authhow == 'session'
193 and !isset($_theme->theme)
195 and $user_theme != THEME)
197 include_once("themes/" . THEME . "/themeinfo.php");
199 if (empty($WikiTheme) and $user_theme) {
200 if (strcspn($user_theme,"./\x00]") != strlen($user_theme)) {
201 trigger_error(sprintf("invalid theme '%s': Invalid characters detected", $user_theme),
203 $user_theme = "default";
205 if (!$user_theme) $user_theme = "default";
206 include_once("themes/$user_theme/themeinfo.php");
208 if (empty($WikiTheme) and defined('THEME'))
209 include_once("themes/" . THEME . "/themeinfo.php");
210 if (empty($WikiTheme))
211 include_once("themes/default/themeinfo.php");
212 assert(!empty($WikiTheme));
214 // Do not execute global init code anymore
216 // WikiTheme callbacks
217 if ($when == 'login') {
218 $WikiTheme->CbUserLogin($this, $this->_user->_userid);
219 if (!$this->_user->hasHomePage()) { // NewUser
220 $WikiTheme->CbNewUserLogin($this, $this->_user->_userid);
221 if (in_array($this->getArg('action'), array('edit','create')))
222 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
225 elseif ($when == 'logout') {
226 $WikiTheme->CbUserLogout($this, $this->_user->_userid);
228 elseif ($when == 'default') {
230 if ($this->_user->_level > 0 and !$this->_user->hasHomePage()) { // NewUser
231 if (in_array($this->getArg('action'), array('edit','create')))
232 $WikiTheme->CbNewUserEdit($this, $this->_user->_userid);
237 // This really maybe should be part of the constructor, but since it
238 // may involve HTML/template output, the global $request really needs
239 // to be initialized before we do this stuff.
240 // [50ms]: 36ms if wikidb_page::exists
241 function updateAuthAndPrefs () {
243 if (isset($this->_user) and (!isa($this->_user, WikiUserClassname()))) {
244 $this->_user = false;
246 // Handle authentication request, if any.
247 if ($auth_args = $this->getArg('auth')) {
248 $this->setArg('auth', false);
249 $this->_handleAuthRequest($auth_args); // possible NORETURN
251 elseif ( ! $this->_user
252 or (isa($this->_user, WikiUserClassname())
253 and ! $this->_user->isSignedIn())) {
254 // If not auth request, try to sign in as saved user.
255 if (($saved_user = $this->getPref('userid')) != false) {
256 $this->_signIn($saved_user);
260 $action = $this->getArg('action');
262 // Save preferences in session and cookie
263 if ((defined('WIKI_XMLRPC') and !WIKI_XMLRPC) or $action != 'xmlrpc') {
264 if (isset($this->_user) and $this->_user->_userid) {
265 if (!isset($this->_user->_authhow) or $this->_user->_authhow != 'session') {
266 $this->_user->setPreferences($this->_prefs, true);
269 $tmpuser = $this->_user; // clone it
270 $this->setSessionVar('wiki_user', $tmpuser);
274 // Ensure user has permissions for action
275 // HACK ALERT: We may not set the request arg to create,
276 // since the pageeditor has an ugly logic for action == create.
277 if ($action == 'edit' or $action == 'create') {
278 $page = $this->getPage();
279 if (! $page->exists() )
284 if (! ENABLE_PAGEPERM) { // Bug #1438392 by Matt Brown
285 $require_level = $this->requiredAuthority($action);
286 if (! $this->_user->hasAuthority($require_level))
287 $this->_notAuthorized($require_level); // NORETURN
289 // novatrope patch to let only _AUTHENTICATED view pages.
290 // If there's not enough authority or forbidden, ask for a password,
291 // unless it's explicitly unobtainable. Some bad magic though.
292 if ($this->requiredAuthorityForAction($action) == WIKIAUTH_UNOBTAINABLE) {
293 $require_level = $this->requiredAuthority($action);
294 $this->_notAuthorized($require_level); // NORETURN
299 function & getUser () {
300 if (isset($this->_user))
303 return $GLOBALS['ForbiddenUser'];
306 function & getGroup () {
307 if (isset($this->_user) and isset($this->_user->_group))
308 return $this->_user->_group;
310 // Debug Strict: Only variable references should be returned by reference
311 $this->_user->_group = WikiGroup::getGroup();
312 return $this->_user->_group;
316 function & getPrefs () {
317 return $this->_prefs;
320 // Convenience function:
321 function getPref ($key) {
322 if (isset($this->_prefs)) {
323 return $this->_prefs->get($key);
326 function & getDbh () {
331 * Get requested page from the page database.
332 * By default it will grab the page requested via the URL
334 * This is a convenience function.
335 * @param string $pagename Name of page to get.
336 * @return WikiDB_Page Object with methods to pull data from
337 * database for the page requested.
339 function getPage ($pagename = false) {
340 //if (!isset($this->_dbi)) $this->getDbh();
342 $pagename = $this->getArg('pagename');
343 return $this->_dbi->getPage($pagename);
346 /** Get URL for POST actions.
348 * Officially, we should just use SCRIPT_NAME (or some such),
349 * but that causes problems when we try to issue a redirect, e.g.
350 * after saving a page.
352 * Some browsers (at least NS4 and Mozilla 0.97 won't accept
353 * a redirect from a page to itself.)
355 * So, as a HACK, we include pagename and action as query args in
356 * the URL. (These should be ignored when we receive the POST
359 function getPostURL ($pagename = false) {
360 global $HTTP_GET_VARS;
362 if ($pagename === false)
363 $pagename = $this->getArg('pagename');
364 $action = $this->getArg('action');
365 if (!empty($HTTP_GET_VARS['start_debug'])) // zend ide support
366 return WikiURL($pagename, array('action' => $action, 'start_debug' => 1));
367 elseif ($action == 'edit')
368 return WikiURL($pagename);
370 return WikiURL($pagename, array('action' => $action));
373 function _handleAuthRequest ($auth_args) {
374 if (!is_array($auth_args))
377 // Ignore password unless POST'ed.
378 if (!$this->isPost())
379 unset($auth_args['passwd']);
381 $olduser = $this->_user;
382 $user = $this->_user->AuthCheck($auth_args);
383 if (is_string($user)) {
384 // Login attempt failed.
385 $fail_message = $user;
386 $auth_args['pass_required'] = true;
387 // if clicked just on to the "sign in as:" button dont print invalid username.
388 if (!empty($auth_args['login']) and empty($auth_args['userid']))
390 // If no password was submitted, it's not really
391 // a failure --- just need to prompt for password...
392 if (!ALLOW_USER_PASSWORDS
394 and !isset($auth_args['passwd']))
396 $fail_message = false;
398 $olduser->PrintLoginForm($this, $auth_args, $fail_message, 'newpage');
399 $this->finish(); //NORETURN
401 elseif (isa($user, WikiUserClassname())) {
402 // Successful login (or logout.)
403 $this->_setUser($user);
406 // Login request cancelled.
411 * Attempt to sign in (bogo-login).
415 * @param $userid string Userid to attempt to sign in as.
418 function _signIn ($userid) {
419 if (ENABLE_USER_NEW) {
421 $this->_user = new _BogoUser($userid);
422 // FIXME: is this always false? shouldn't we try passuser first?
424 $this->_user = new _PassUser($userid);
427 $this->_user = new WikiUser($this, $userid);
429 $user = $this->_user->AuthCheck(array('userid' => $userid));
430 if (isa($user, WikiUserClassname())) {
431 $this->_setUser($user); // success!
435 // login or logout or restore state
436 function _setUser (&$user) {
437 $this->_user =& $user;
438 if (defined('MAIN_setUser')) return; // don't set cookies twice
439 $this->setCookieVar(getCookieName(), $user->getAuthenticatedId(),
440 COOKIE_EXPIRATION_DAYS, COOKIE_DOMAIN);
441 $isSignedIn = $user->isSignedIn();
443 $user->_authhow = 'signin';
446 // Save userid to prefs..
447 if ( empty($this->_user->_prefs)) {
448 $this->_user->_prefs = $this->_user->getPreferences();
449 $this->_prefs =& $this->_user->_prefs;
451 $this->_user->_group = $this->getGroup();
452 $this->setSessionVar('wiki_user', $user);
453 $this->_prefs->set('userid',
454 $isSignedIn ? $user->getId() : '');
455 if (!ENABLE_USER_NEW) {
456 if (empty($this->_user->_request))
457 $this->_user->_request =& $this;
458 if (empty($this->_user->_dbi))
459 $this->_user->_dbi =& $this->_dbi;
461 $this->initializeTheme($isSignedIn ? 'login' : 'logout');
462 define('MAIN_setUser', true);
465 /* Permission system */
466 function getLevelDescription($level) {
467 static $levels = false;
468 if (!$levels) // This looks like a Visual Basic hack. For the very same reason. "0"
469 $levels = array('x-1' => _("FORBIDDEN"),
474 'x100'=> _("UNOBTAINABLE"));
477 if (!empty($levels["x".$level]))
478 return $levels["x".$level];
483 function _notAuthorized ($require_level) {
484 // Display the authority message in the Wiki's default
485 // language, in case it is not english.
487 // Note that normally a user will not see such an error once
488 // logged in, unless the admin has altered the default
489 // disallowed wikiactions. In that case we should probably
490 // check the user's language prefs too at this point; this
491 // would be a situation which is not really handled with the
493 if (empty($GLOBALS['LANG']))
494 update_locale(DEFAULT_LANGUAGE);
496 // User does not have required authority. Prompt for login.
497 $what = $this->getActionDescription($this->getArg('action'));
498 $pass_required = ($require_level >= WIKIAUTH_USER);
499 if ($require_level == WIKIAUTH_UNOBTAINABLE) {
500 global $DisabledActions;
501 if ($DisabledActions and in_array($action, $DisabledActions)) {
502 $msg = fmt("%s is disallowed on this wiki.",
503 $this->getDisallowedActionDescription($this->getArg('action')));
507 // Is the reason a missing ACL or just wrong user or password?
508 if (class_exists('PagePermission')) {
509 $user =& $this->_user;
510 $status = $user->isAuthenticated() ? _("authenticated") : _("not authenticated");
511 $msg = fmt("%s %s %s is disallowed on this wiki for %s user '%s' (level: %s).",
512 _("Missing PagePermission:"),
513 action2access($this->getArg('action')),
514 $this->getArg('pagename'),
515 $status, $user->getId(), $this->getLevelDescription($user->_level));
516 // TODO: add link to action=setacl
517 $user->PrintLoginForm($this, compact('pass_required'), $msg);
521 $msg = fmt("%s is disallowed on this wiki.",
522 $this->getDisallowedActionDescription($this->getArg('action')));
523 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'), $msg);
528 elseif ($require_level == WIKIAUTH_BOGO)
529 $msg = fmt("You must sign in to %s.", $what);
530 elseif ($require_level == WIKIAUTH_USER) {
531 // LoginForm should display the relevant messages...
533 /*if (!ALLOW_ANON_USER)
534 $msg = fmt("You must log in first to %s", $what);
536 $msg = fmt("You must log in to %s.", $what);
538 } elseif ($require_level == WIKIAUTH_ANON)
539 $msg = fmt("Access for you is forbidden to %s.", $what);
541 $msg = fmt("You must be an administrator to %s.", $what);
543 $this->_user->PrintLoginForm($this, compact('require_level','pass_required'),
545 if (!$GLOBALS['WikiTheme']->DUMP_MODE)
546 $this->finish(); // NORETURN
549 // Fixme: for PagePermissions we'll need other strings,
550 // relevant to the requested page, not just for the action on the whole wiki.
551 function getActionDescription($action) {
552 static $actionDescriptions;
553 if (! $actionDescriptions) {
555 = array('browse' => _("view this page"),
556 'diff' => _("diff this page"),
557 'dumphtml' => _("dump html pages"),
558 'dumpserial' => _("dump serial pages"),
559 'edit' => _("edit this page"),
560 'rename' => _("rename this page"),
561 'revert' => _("revert to a previous version of this page"),
562 'create' => _("create this page"),
563 'loadfile' => _("load files into this wiki"),
564 'lock' => _("lock this page"),
565 'purge' => _("purge this page"),
566 'remove' => _("remove this page"),
567 'unlock' => _("unlock this page"),
568 'upload' => _("upload a zip dump"),
569 'verify' => _("verify the current action"),
570 'viewsource' => _("view the source of this page"),
571 'xmlrpc' => _("access this wiki via XML-RPC"),
572 'soap' => _("access this wiki via SOAP"),
573 'zip' => _("download a zip dump from this wiki"),
574 'ziphtml' => _("download a html zip dump from this wiki")
577 if (in_array($action, array_keys($actionDescriptions)))
578 return $actionDescriptions[$action];
580 return _("use")." ".$action;
584 TODO: check against these cases:
585 if ($DisabledActions and in_array($action, $DisabledActions))
586 return WIKIAUTH_UNOBTAINABLE;
588 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
589 return requiredAuthorityForPage($action);
591 => Browsing pages is disallowed on this wiki for authenticated user 'rurban' (level: BOGO).
593 function getDisallowedActionDescription($action) {
594 static $disallowedActionDescriptions;
596 if (! $disallowedActionDescriptions) {
597 $disallowedActionDescriptions
598 = array('browse' => _("Browsing pages"),
599 'diff' => _("Diffing pages"),
600 'dumphtml' => _("Dumping html pages"),
601 'dumpserial' => _("Dumping serial pages"),
602 'edit' => _("Editing pages"),
603 'revert' => _("Reverting to a previous version of pages"),
604 'create' => _("Creating pages"),
605 'loadfile' => _("Loading files"),
606 'lock' => _("Locking pages"),
607 'purge' => _("Purging pages"),
608 'remove' => _("Removing pages"),
609 'unlock' => _("Unlocking pages"),
610 'upload' => _("Uploading zip dumps"),
611 'verify' => _("Verify the current action"),
612 'viewsource' => _("Viewing the source of pages"),
613 'xmlrpc' => _("XML-RPC access"),
614 'soap' => _("SOAP access"),
615 'zip' => _("Downloading zip dumps"),
616 'ziphtml' => _("Downloading html zip dumps")
619 if (in_array($action, array_keys($disallowedActionDescriptions)))
620 return $disallowedActionDescriptions[$action];
625 function requiredAuthority ($action) {
626 $auth = $this->requiredAuthorityForAction($action);
627 if (!ALLOW_ANON_USER) return WIKIAUTH_USER;
630 * This is a hook for plugins to require authority
631 * for posting to them.
633 * IMPORTANT: This is not a secure check, so the plugin
634 * may not assume that any POSTs to it are authorized.
635 * All this does is cause PhpWiki to prompt for login
636 * if the user doesn't have the required authority.
638 if ($this->isPost()) {
639 $post_auth = $this->getArg('require_authority_for_post');
640 if ($post_auth !== false)
641 $auth = max($auth, $post_auth);
646 function requiredAuthorityForAction ($action) {
647 global $DisabledActions;
649 if ($DisabledActions and in_array($action, $DisabledActions))
650 return WIKIAUTH_UNOBTAINABLE;
652 if (ENABLE_PAGEPERM and class_exists("PagePermission")) {
653 return requiredAuthorityForPage($action);
666 return WIKIAUTH_ANON;
671 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
672 return WIKIAUTH_ADMIN;
673 return WIKIAUTH_ANON;
677 return WIKIAUTH_ADMIN;
678 if (INSECURE_ACTIONS_LOCALHOST_ONLY and !is_localhost())
679 return WIKIAUTH_ADMIN;
680 return WIKIAUTH_ANON;
683 if (INSECURE_ACTIONS_LOCALHOST_ONLY and is_localhost())
684 return WIKIAUTH_ANON;
685 return WIKIAUTH_ADMIN;
689 return WIKIAUTH_ADMIN;
690 return WIKIAUTH_ANON;
695 if (defined('REQUIRE_SIGNIN_BEFORE_EDIT') && REQUIRE_SIGNIN_BEFORE_EDIT)
696 return WIKIAUTH_BOGO;
697 return WIKIAUTH_ANON;
698 // return WIKIAUTH_BOGO;
701 $page = $this->getPage();
702 $current = $page->getCurrentRevision();
703 if ($current->hasDefaultContents())
704 return $this->requiredAuthorityForAction('edit');
705 return $this->requiredAuthorityForAction('browse');
716 return WIKIAUTH_ADMIN;
718 /* authcheck occurs only in the plugin.
719 required actionpage RateIt */
722 case 'delete_rating':
723 // Perhaps this should be WIKIAUTH_USER
724 return WIKIAUTH_BOGO;
728 global $WikiNameRegexp;
729 if (preg_match("/$WikiNameRegexp\Z/A", $action))
730 return WIKIAUTH_ANON; // ActionPage.
732 return WIKIAUTH_ADMIN;
736 /* End of Permission system */
738 function possiblyDeflowerVirginWiki () {
739 if ($this->getArg('action') != 'browse')
741 if ($this->getArg('pagename') != HOME_PAGE)
744 $page = $this->getPage();
745 $current = $page->getCurrentRevision();
746 if ($current->getVersion() > 0)
747 return; // Homepage exists.
749 include_once('lib/loadsave.php');
750 $this->setArg('action', 'loadfile');
752 $this->finish(); // NORETURN
755 // [574ms] mainly template:printexpansion: 393ms and template::expandsubtemplate [100+70+60ms]
756 function handleAction () {
757 $action = $this->getArg('action');
759 and !$this->_user->isAdmin()
760 and $action != 'browse'
761 and $action != 'wikitohtml'
764 $page = $this->getPage();
765 if ( $page->get('moderation') ) {
766 require_once("lib/WikiPlugin.php");
767 $loader = new WikiPluginLoader();
768 $plugin = $loader->getPlugin("ModeratedPage");
769 if ($plugin->handler($this, $page)) {
772 array('class' => 'wiki-edithelp'),
773 fmt("%s: action forwarded to a moderator.",
776 _("This action requires moderator approval. Please be patient."));
777 if (!empty($plugin->_tokens['CONTENT']))
778 $plugin->_tokens['CONTENT']->pushContent
781 _("You must wait for moderator approval."));
783 $plugin->_tokens['CONTENT'] = $CONTENT;
784 require_once("lib/Template.php");
785 $title = WikiLink($page->getName());
786 $title->pushContent(' : ', WikiLink(_("ModeratedPage")));
787 GeneratePage(Template('browse', $plugin->_tokens),
789 $page->getCurrentRevision());
794 $method = "action_$action";
795 if (method_exists($this, $method)) {
798 elseif ($page = $this->findActionPage($action)) {
799 $this->actionpage($page);
802 $this->finish(fmt("%s: Bad action", $action));
806 function finish ($errormsg = false) {
810 exit(); // just in case CloseDataBase calls us
813 global $ErrorManager;
814 $ErrorManager->flushPostponedErrors();
816 if (!empty($errormsg)) {
819 HTML::h2(_("Fatal PhpWiki Error")),
822 echo "\n</body></html>";
824 if (is_object($this->_user)) {
825 $this->_user->page = $this->getArg('pagename');
826 $this->_user->action = $this->getArg('action');
827 unset($this->_user->_HomePagehandle);
828 unset($this->_user->_auth_dbi);
829 unset($this->_user->_dbi);
830 unset($this->_user->_request);
837 * Generally pagename is rawurlencoded for older browsers or mozilla.
838 * Typing a pagename into the IE bar will utf-8 encode it, so we have to
839 * fix that with fixTitleEncoding().
840 * If USE_PATH_INFO = true, the pagename is stripped from the "/DATA_PATH/PageName&arg=value" line.
841 * If false, we support either "/index.php?pagename=PageName&arg=value",
842 * or the first arg (1.2.x style): "/index.php?PageName&arg=value"
844 function _deducePagename () {
845 if (trim(rawurldecode($this->getArg('pagename'))))
846 return fixTitleEncoding(rawurldecode($this->getArg('pagename')));
849 $pathinfo = $this->get('PATH_INFO');
850 if (empty($pathinfo)) { // fix for CGI
851 $path = $this->get('REQUEST_URI');
852 $script = $this->get('SCRIPT_NAME');
853 $pathinfo = substr($path,strlen($script));
854 $pathinfo = preg_replace('/\?.+$/','',$pathinfo);
856 $tail = substr($pathinfo, strlen(PATH_INFO_PREFIX));
858 if (trim($tail) != '' and $pathinfo == PATH_INFO_PREFIX . $tail) {
859 return fixTitleEncoding($tail);
862 elseif ($this->isPost()) {
864 * In general, for security reasons, HTTP_GET_VARS should be ignored
865 * on POST requests, but we make an exception here (only for pagename).
867 * The justification for this hack is the following
868 * asymmetry: When POSTing with USE_PATH_INFO set, the
869 * pagename can (and should) be communicated through the
870 * request URL via PATH_INFO. When POSTing with
871 * USE_PATH_INFO off, this cannot be done --- the only way
872 * to communicate the pagename through the URL is via
873 * QUERY_ARGS (HTTP_GET_VARS).
875 global $HTTP_GET_VARS;
876 if (isset($HTTP_GET_VARS['pagename']) and trim($HTTP_GET_VARS['pagename'])) {
877 return fixTitleEncoding(rawurldecode($HTTP_GET_VARS['pagename']));
882 * Support for PhpWiki 1.2 style requests.
883 * Strip off "&" args (?PageName&action=...&start_debug,...)
885 $query_string = $this->get('QUERY_STRING');
886 if (trim(rawurldecode($query_string)) and preg_match('/^([^&=]+)(&.+)?$/', $query_string, $m)) {
887 return fixTitleEncoding(rawurldecode($m[1]));
890 return fixTitleEncoding(HOME_PAGE);
893 function _deduceAction () {
894 if (!($action = $this->getArg('action'))) {
895 // TODO: improve this SOAP.php hack by letting SOAP use index.php
896 // or any other virtual url as with xmlrpc
897 if (defined('WIKI_SOAP') and WIKI_SOAP)
899 // Detect XML-RPC requests.
901 && ($this->get('CONTENT_TYPE') == 'text/xml'
902 or $this->get('CONTENT_TYPE') == 'application/xml')
903 && strstr($GLOBALS['HTTP_RAW_POST_DATA'], '<methodCall>')
908 return 'browse'; // Default if no action specified.
911 if (method_exists($this, "action_$action"))
914 // Allow for, e.g. action=LikePages
915 if ($this->isActionPage($action))
918 // Handle untranslated actionpages in non-english
919 // (people playing with switching languages)
920 if (0 and $GLOBALS['LANG'] != 'en') {
921 require_once("lib/plugin/_WikiTranslation.php");
922 $trans = new WikiPlugin__WikiTranslation();
923 $en_action = $trans->translate($action,'en',$GLOBALS['LANG']);
924 if ($this->isActionPage($en_action))
928 trigger_error("$action: Unknown action", E_USER_NOTICE);
932 function _deduceUsername() {
933 global $HTTP_SERVER_VARS, $HTTP_ENV_VARS;
935 if (!empty($this->args['auth']) and !empty($this->args['auth']['userid']))
936 return $this->args['auth']['userid'];
938 if ($user = $this->getSessionVar('wiki_user')) {
939 // Switched auth between sessions.
940 // Note: There's no way to demandload a missing class-definition
941 // afterwards! Stupid php.
942 if (isa($user, WikiUserClassname())) {
943 $this->_user = $user;
944 $this->_user->_authhow = 'session';
945 return ENABLE_USER_NEW ? $user->UserName() : $this->_user;
949 // Sessions override http auth
950 if (!empty($HTTP_SERVER_VARS['PHP_AUTH_USER']))
951 return $HTTP_SERVER_VARS['PHP_AUTH_USER'];
953 if (!empty($HTTP_SERVER_VARS['REMOTE_USER']))
954 return $HTTP_SERVER_VARS['REMOTE_USER'];
955 if (!empty($HTTP_ENV_VARS['REMOTE_USER']))
956 return $HTTP_ENV_VARS['REMOTE_USER'];
958 if ($userid = $this->getCookieVar(getCookieName())) {
959 if (!empty($userid) and substr($userid,0,2) != 's:') {
960 $this->_user->authhow = 'cookie';
965 if ($this->getArg('action') == 'xmlrpc') { // how about SOAP?
966 if (empty($GLOBALS['HTTP_RAW_POST_DATA']))
967 trigger_error("Wrong always_populate_raw_post_data = Off setting in your php.ini\nCannot use xmlrpc!", E_USER_ERROR);
968 // wiki.putPage has special otional userid/passwd arguments. check that later.
970 if (isset($HTTP_SERVER_VARS['REMOTE_USER']))
971 $userid = $HTTP_SERVER_VARS['REMOTE_USER'];
972 elseif (isset($HTTP_SERVER_VARS['REMOTE_ADDR']))
973 $userid = $HTTP_SERVER_VARS['REMOTE_ADDR'];
974 elseif (isset($HTTP_ENV_VARS['REMOTE_ADDR']))
975 $userid = $HTTP_ENV_VARS['REMOTE_ADDR'];
976 elseif (isset($GLOBALS['REMOTE_ADDR']))
977 $userid = $GLOBALS['REMOTE_ADDR'];
984 function _isActionPage ($pagename, $verbose = true) {
986 global $AllActionPages;
988 return (in_array($pagename, $AllActionPages));
991 function findActionPage ($action) {
993 if (!$action) return false;
995 // check for translated version, as per users preferred language
996 // (or system default in case it is not en)
997 $translation = gettext($action);
999 if (isset($cache) and isset($cache[$translation]))
1000 return $cache[$translation];
1002 // check for cached translated version
1003 if ($translation and $this->_isActionPage($translation, false))
1004 return $cache[$action] = $translation;
1006 // Allow for, e.g. action=LikePages
1007 if (!isWikiWord($action))
1008 return $cache[$action] = false;
1010 // check for translated version (default language)
1012 if ($LANG != "en") {
1013 require_once("lib/WikiPlugin.php");
1014 require_once("lib/plugin/_WikiTranslation.php");
1015 $trans = new WikiPlugin__WikiTranslation();
1016 $trans->lang = $LANG;
1017 $default = $trans->translate_to_en($action, $LANG);
1018 if ($default and $this->_isActionPage($default, false))
1019 return $cache[$action] = $default;
1021 $default = $translation;
1024 // check for english version
1025 if ($action != $translation and $action != $default) {
1026 if ($this->_isActionPage($action))
1027 return $cache[$action] = $action;
1030 trigger_error("$action: Cannot find action page", E_USER_NOTICE);
1031 return $cache[$action] = false;
1034 function isActionPage ($pagename) {
1035 return $this->findActionPage($pagename);
1038 function action_browse () {
1039 $this->buffer_output();
1040 include_once("lib/display.php");
1044 function action_verify () {
1045 $this->action_browse();
1048 function actionpage ($action) {
1049 $this->buffer_output();
1050 include_once("lib/display.php");
1051 actionPage($this, $action);
1054 function adminActionSubpage ($subpage) {
1055 $page = _("PhpWikiAdministration")."/".$subpage;
1056 $action = $this->findActionPage($page);
1058 if (!$this->getArg('s'))
1059 $this->setArg('s', $this->getArg('pagename'));
1060 $this->setArg('verify',1);
1061 if ($this->getArg('action') != 'rename')
1062 $this->setArg('action', $action);
1063 $this->actionpage($action);
1065 trigger_error($page.": Cannot find action page", E_USER_WARNING);
1069 function action_chown () {
1070 $this->adminActionSubpage(_("Chown"));
1073 function action_setacl () {
1074 $this->adminActionSubpage(_("SetAcl"));
1077 function action_rename () {
1078 $this->adminActionSubpage(_("Rename"));
1081 function action_dump () {
1082 $action = $this->findActionPage(_("PageDump"));
1084 $this->actionpage($action);
1086 // redirect to action=upgrade if admin?
1087 trigger_error(_("PageDump").": Cannot find action page", E_USER_WARNING);
1091 function action_diff () {
1092 $this->buffer_output();
1093 include_once "lib/diff.php";
1097 function action_search () {
1098 // Decide between title or fulltextsearch (e.g. both buttons available).
1099 // Reformulate URL and redirect.
1100 $searchtype = $this->getArg('searchtype');
1101 $args = array('s' => $this->getArg('searchterm')
1102 ? $this->getArg('searchterm')
1103 : $this->getArg('s'));
1104 if ($searchtype == 'full' or $searchtype == 'fulltext') {
1105 $search_page = _("FullTextSearch");
1107 elseif ($searchtype == 'external') {
1109 $link = new WikiPageName("Search:$s"); // Expand interwiki url. I use xapian-omega
1110 $this->redirect($link->url);
1113 $search_page = _("TitleSearch");
1114 $args['auto_redirect'] = 1;
1116 $this->redirect(WikiURL($search_page, $args, 'absolute_url'));
1119 function action_edit () {
1120 $this->buffer_output();
1121 include "lib/editpage.php";
1122 $e = new PageEditor ($this);
1126 function action_create () {
1127 $this->action_edit();
1130 function action_viewsource () {
1131 $this->buffer_output();
1132 include "lib/editpage.php";
1133 $e = new PageEditor ($this);
1137 function action_lock () {
1138 $page = $this->getPage();
1139 $page->set('locked', true);
1140 $this->_dbi->touch();
1141 // check ModeratedPage hook
1142 if ($moderated = $page->get('moderation')) {
1143 require_once("lib/WikiPlugin.php");
1144 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1145 if ($retval = $plugin->lock_check($this, $page, $moderated))
1146 $this->setArg('errormsg', $retval);
1148 // check if a link to ModeratedPage exists
1149 elseif ($action_page = $page->existLink(_("ModeratedPage"))) {
1150 require_once("lib/WikiPlugin.php");
1151 $plugin = WikiPluginLoader::getPlugin("ModeratedPage");
1152 if ($retval = $plugin->lock_add($this, $page, $action_page))
1153 $this->setArg('errormsg', $retval);
1155 $this->action_browse();
1158 function action_unlock () {
1159 $page = $this->getPage();
1160 $page->set('locked', false);
1161 $this->_dbi->touch();
1162 $this->action_browse();
1165 function action_purge () {
1166 $pagename = $this->getArg('pagename');
1167 if (strstr($pagename, _("PhpWikiAdministration"))) {
1168 $this->action_browse();
1170 include('lib/purgepage.php');
1175 function action_remove () {
1176 // This check is now redundant.
1177 //$user->requireAuth(WIKIAUTH_ADMIN);
1178 $pagename = $this->getArg('pagename');
1179 if (strstr($pagename, _("PhpWikiAdministration"))) {
1180 $this->action_browse();
1182 include('lib/removepage.php');
1187 function action_xmlrpc () {
1188 include_once("lib/XmlRpcServer.php");
1189 $xmlrpc = new XmlRpcServer($this);
1193 function action_soap () {
1194 if (defined("WIKI_SOAP") and WIKI_SOAP) // already loaded
1197 allow VIRTUAL_PATH or action=soap SOAP access
1199 include_once("SOAP.php");
1202 function action_revert () {
1203 include_once "lib/loadsave.php";
1207 function action_zip () {
1208 include_once("lib/loadsave.php");
1210 // I don't think it hurts to add cruft at the end of the zip file.
1211 //echo "\n========================================================\n";
1212 //echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1215 function action_ziphtml () {
1216 include_once("lib/loadsave.php");
1217 MakeWikiZipHtml($this);
1218 // I don't think it hurts to add cruft at the end of the zip file.
1219 echo "\n========================================================\n";
1220 echo "PhpWiki " . PHPWIKI_VERSION . " source:\n$GLOBALS[RCS_IDS]\n";
1223 function action_dumpserial () {
1224 include_once("lib/loadsave.php");
1228 function action_dumphtml () {
1229 include_once("lib/loadsave.php");
1230 DumpHtmlToDir($this);
1233 function action_upload () {
1234 include_once("lib/loadsave.php");
1235 LoadPostFile($this);
1238 function action_upgrade () {
1239 include_once("lib/loadsave.php");
1240 include_once("lib/upgrade.php");
1244 function action_loadfile () {
1245 include_once("lib/loadsave.php");
1246 LoadFileOrDir($this);
1249 function action_pdf () {
1250 include_once("lib/pdf.php");
1251 ConvertAndDisplayPdf($this);
1254 function action_captcha () {
1255 include_once "lib/Captcha.php";
1256 $captcha = new Captcha();
1257 $captcha->image ( $captcha->captchaword() );
1260 function action_wikitohtml () {
1261 include_once("lib/WysiwygEdit/Wikiwyg.php");
1262 $wikitohtml = new WikiToHtml( $this->getArg("content") , $this);
1263 $wikitohtml->send();
1266 function action_setpref () {
1267 $what = $this->getArg('pref');
1268 $value = $this->getArg('value');
1269 $prefs =& $this->_user->_prefs;
1270 $prefs->set($what, $value);
1271 $num = $this->_user->setPreferences($prefs);
1275 //FIXME: deprecated with ENABLE_PAGEPERM (?)
1276 function is_safe_action ($action) {
1278 return $request->requiredAuthorityForAction($action) < WIKIAUTH_ADMIN;
1281 function validateSessionPath() {
1282 // Try to defer any session.save_path PHP errors before any html
1283 // is output, which causes some versions of IE to display a blank
1284 // page (due to its strict mode while parsing a page?).
1285 if (! is_writeable(ini_get('session.save_path'))) {
1286 $tmpdir = (defined('SESSION_SAVE_PATH') and SESSION_SAVE_PATH) ? SESSION_SAVE_PATH : '/tmp';
1287 if (!is_writeable($tmpdir))
1290 (sprintf(_("%s is not writable."),
1291 _("The session.save_path directory"))
1293 . sprintf(_("Please ensure that %s is writable, or redefine %s in config/config.ini."),
1294 sprintf(_("the session.save_path directory '%s'"),
1295 ini_get('session.save_path')),
1296 'SESSION_SAVE_PATH')
1298 . sprintf(_("Attempting to use the directory '%s' instead."),
1301 if (! is_writeable($tmpdir)) {
1303 (sprintf(_("%s is not writable."), $tmpdir)
1305 . _("Users will not be able to sign in.")
1309 @ini_set('session.save_path', $tmpdir);
1314 if ( !USE_DB_SESSION )
1315 validateSessionPath();
1318 if ((DEBUG & _DEBUG_APD) and extension_loaded("apd")) {
1319 //apd_set_session_trace(9);
1320 apd_set_pprof_trace();
1323 // Postpone warnings
1324 global $ErrorManager;
1325 if (defined('E_STRICT')) // and (E_ALL & E_STRICT)) // strict php5?
1326 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING|E_STRICT);
1328 $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE|E_USER_WARNING|E_WARNING);
1329 $request = new WikiRequest();
1331 $action = $request->getArg('action');
1332 if (substr($action, 0, 3) != 'zip') {
1333 if ($action == 'pdf')
1334 $ErrorManager->setPostponedErrorMask(-1); // everything
1335 //else // reject postponing of warnings
1336 // $ErrorManager->setPostponedErrorMask(E_NOTICE|E_USER_NOTICE);
1340 * Allow for disabling of markup cache.
1341 * (Mostly for debugging ... hopefully.)
1343 * See also <?plugin WikiAdminUtils action=purge-cache ?>
1345 if (!defined('WIKIDB_NOCACHE_MARKUP')) {
1346 if ($request->getArg('nocache')) // 1 or purge
1347 define('WIKIDB_NOCACHE_MARKUP', $request->getArg('nocache'));
1349 define('WIKIDB_NOCACHE_MARKUP', false); // redundant, but explicit
1352 // Initialize with system defaults in case user not logged in.
1353 // Should this go into the constructor?
1354 $request->initializeTheme('default');
1355 $request->updateAuthAndPrefs();
1356 $request->initializeLang();
1359 //if ($user->is_authenticated())
1360 // $LogEntry->user = $user->getId();
1362 // Memory optimization:
1363 // http://www.procata.com/blog/archives/2004/05/27/rephlux-and-php-memory-usage/
1364 // kill the global PEAR _PEAR_destructor_object_list
1365 if (!empty($_PEAR_destructor_object_list))
1366 $_PEAR_destructor_object_list = array();
1367 $request->possiblyDeflowerVirginWiki();
1369 $validators = array('wikiname' => WIKI_NAME,
1370 'args' => wikihash($request->getArgs()),
1371 'prefs' => wikihash($request->getPrefs()));
1372 if (CACHE_CONTROL == 'STRICT') {
1373 $dbi = $request->getDbh();
1374 $timestamp = $dbi->getTimestamp();
1375 $validators['mtime'] = $timestamp;
1376 $validators['%mtime'] = (int)$timestamp;
1378 // FIXME: we should try to generate strong validators when possible,
1379 // but for now, our validator is weak, since equal validators do not
1380 // indicate byte-level equality of content. (Due to DEBUG timing output, etc...)
1382 // (If DEBUG if off, this may be a strong validator, but I'm going
1383 // to go the paranoid route here pending further study and testing.)
1384 // access hits and edit stats in the footer violate strong ETags also.
1386 $validators['%weak'] = true;
1388 $request->setValidators($validators);
1390 $request->handleAction();
1392 if (DEBUG and DEBUG & _DEBUG_INFO) phpinfo(INFO_VARIABLES | INFO_MODULES);
1396 //$x = error_reporting(); // DEBUG: why is it 1 here? should be E_ALL
1397 if (defined('E_STRICT') and (E_ALL & E_STRICT)) // strict php5?
1398 error_reporting(E_ALL & ~E_STRICT); // exclude E_STRICT
1400 error_reporting(E_ALL); // php4
1401 // don't run the main loop for special requests (test, getimg, xmlrpc, soap, ...)
1402 if (!defined('PHPWIKI_NOMAIN') or !PHPWIKI_NOMAIN)
1408 // c-basic-offset: 4
1409 // c-hanging-comment-ender-p: nil
1410 // indent-tabs-mode: nil