function performAction() { global $wgAjaxExportList, $wgOut; if (empty($this->mode)) { return; } wfProfileIn(__METHOD__); if (!in_array($this->func_name, $wgAjaxExportList)) { wfHttpError(400, 'Bad Request', "unknown function " . (string) $this->func_name); } else { try { $result = call_user_func_array($this->func_name, $this->args); if ($result === false || $result === NULL) { wfHttpError(500, 'Internal Error', "{$this->func_name} returned no data"); } else { if (is_string($result)) { $result = new AjaxResponse($result); } $result->sendHeaders(); $result->printText(); } } catch (Exception $e) { if (!headers_sent()) { wfHttpError(500, 'Internal Error', $e->getMessage()); } else { print $e->getMessage(); } } } wfProfileOut(__METHOD__); $wgOut = null; }
public function hRawPageViewBeforeOutput(&$rawpage, &$text) { global $wgUser; if (!$wgUser->isAllowed("raw")) { $text = ''; wfHttpError(403, 'Forbidden', 'Unsufficient access rights.'); return false; } return true; // continue hook-chain. }
/** * Check whether feeds can be used and that $type is a valid feed type * * @param $type String: feed type, as requested by the user * @return Boolean */ public static function checkFeedOutput($type) { global $wgFeed, $wgFeedClasses; if (!$wgFeed) { global $wgOut; $wgOut->addWikiMsg('feed-unavailable'); return false; } if (!isset($wgFeedClasses[$type])) { wfHttpError(500, "Internal Server Error", "Unsupported feed type."); return false; } return true; }
/** * @private */ function rdfSetup() { global $wgOut, $_SERVER; $rdftype = wfNegotiateType(wfAcceptToPrefs(@$_SERVER['HTTP_ACCEPT']), wfAcceptToPrefs(RDF_TYPE_PREFS)); if (!$rdftype) { wfHttpError(406, "Not Acceptable", wfMsg("notacceptable")); return false; } else { $wgOut->disable(); header("Content-type: {$rdftype}"); $wgOut->sendCacheControl(); return true; } }
/** * */ protected function setup() { global $wgOut, $wgRequest; $httpaccept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; $rdftype = wfNegotiateType(wfAcceptToPrefs($httpaccept), wfAcceptToPrefs(self::RDF_TYPE_PREFS)); if (!$rdftype) { wfHttpError(406, 'Not Acceptable', wfMsg('notacceptable')); return false; } else { $wgOut->disable(); $wgRequest->response()->header("Content-type: {$rdftype}; charset=utf-8"); $wgOut->sendCacheControl(); return true; } }
function execute($par) { global $wgOut, $wgOpenIDClientOnly; wfLoadExtensionMessages('OpenID'); # No server functionality if this site is only a client # Note: special page is un-registered if this flag is set, # so it'd be unusual to get here. if ($wgOpenIDClientOnly) { wfHttpError(404, "Not Found", wfMsg('openidclientonlytext')); return; } // XRDS preamble XML. $xml_template = array('<?xml version="1.0" encoding="UTF-8"?' . '>', '<xrds:XRDS', ' xmlns:xrds="xri://\\$xrds"', ' xmlns:openid="http://openid.net/xmlns/1.0"', ' xmlns="xri://$xrd*($v*2.0)">', '<XRD>'); # Check to see if the parameter is really a user name if (!$par) { wfHttpError(404, "Not Found", wfMsg('openidnousername')); return; } $user = User::newFromName($par); if (!$user || $user->getID() == 0) { wfHttpError(404, "Not Found", wfMsg('openidbadusername')); return; } // Generate the user page URL. $user_title = $user->getUserPage(); $user_url = $user_title->getFullURL(); // Generate the OpenID server endpoint URL. $server_title = SpecialPage::getTitleFor('OpenIDServer'); $server_url = $server_title->getFullURL(); // Define array of Yadis services to be included in // the XRDS output. $services = array(array('uri' => $server_url, 'priority' => '0', 'types' => array('http://openid.net/signon/1.0', 'http://openid.net/sreg/1.0', 'http://specs.openid.net/auth/2.0/signon'), 'delegate' => $user_url)); // Generate <Service> elements into $service_text. $service_text = "\n"; foreach ($services as $service) { $types = array(); foreach ($service['types'] as $type_uri) { $types[] = ' <Type>' . $type_uri . '</Type>'; } $service_text .= implode("\n", array(' <Service priority="' . $service['priority'] . '">', ' <URI>' . $server_url . '</URI>', implode("\n", $types), ' </Service>')); } $wgOut->disable(); // Print content-type and XRDS XML. header("Content-Type: application/xrds+xml"); print implode("\n", $xml_template); print $service_text; print implode("\n", array("</XRD>", "</xrds:XRDS>")); }
/** * main() */ public function execute($par) { global $wgContLang, $wgFeedClasses, $wgLanguageCode, $wgMemc, $wgOut, $wgGNSMsmaxage; list($params, $categories, $notCategories) = $this->getParams(); // if there's an error parsing the params, bail out and return if (isset($params['error'])) { wfHttpError(500, 'Internal Server Error', $params['error']); return; } // Check to make sure that feed type is supported. if (FeedUtils::checkFeedOutput($params['feed'])) { $msg = wfMessage('feed-' . $params['feed'])->inContentLanguage(); if ($msg->exists()) { // This seems a little icky since // its re-using another message in a // different context. // uses feed-rss and feed-atom messages. $feedType = $msg->text(); } else { $feedType = $wgContLang->uc($params['feed']); } $feed = new $wgFeedClasses[$params['feed']](wfMsgExt('googlenewssitemap_feedtitle', array('parsemag', 'content'), $wgContLang->getLanguageName($wgLanguageCode), $feedType, $wgLanguageCode), wfMsgExt('tagline', array('parsemag', 'content')), Title::newMainPage()->getFullURL()); } else { // FeedUtils outputs an error if wrong feed type. // So nothing else to do at this point return; } $wgOut->setSquidMaxage($wgGNSMsmaxage); $cacheInvalidationInfo = $this->getCacheInvalidationInfo($params, $categories, $notCategories); $cacheKey = $this->getCacheKey($params, $categories, $notCategories); // The way this does caching is based on ChangesFeed::execute. $cached = $this->getCachedVersion($cacheKey, $cacheInvalidationInfo); if ($cached !== false) { $feed->httpHeaders(); echo $cached; echo "<!-- From cache: {$cacheKey} -->"; } else { wfProfileIn(__METHOD__ . '-not-cached'); $res = $this->getCategories($params, $categories, $notCategories); ob_start(); $this->makeFeed($feed, $res); $output = ob_get_contents(); ob_end_flush(); echo "<!-- Not cached. Saved as: {$cacheKey} -->"; $wgMemc->set($cacheKey, array($cacheInvalidationInfo, $output), $this->maxCacheTime); wfProfileOut(__METHOD__ . '-not-cached'); } }
/** * constructor */ function wfSpecialUserlogoutUCSC() { global $wgUser, $wgOut, $wgRequest; /** * Some satellite ISPs use broken precaching schemes that log people out straight after * they're logged in (bug 17790). Luckily, there's a way to detect such requests. */ if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '&') !== false) { wfDebug("Special:Userlogout request {$_SERVER['REQUEST_URI']} looks suspicious, denying.\n"); wfHttpError(400, wfMsg('loginerror'), wfMsg('suspicious-userlogout')); return; } $oldName = $wgUser->getName(); $wgUser->logout(); $wgOut->setRobotPolicy('noindex,nofollow'); // Hook. $injected_html = ''; wfRunHooks('UserLogoutComplete', array(&$wgUser, &$injected_html, $oldName)); $wgOut->addHTML(wfMsgExt('logouttext', array('parse')) . $injected_html); returnToExternal(true, $wgRequest->getVal('returnto')); }
/** * @param Exception|Throwable $e Original exception * @param integer $mode MWExceptionExposer::AS_* constant * @param Exception|Throwable|null $eNew New exception from attempting to show the first */ public static function output($e, $mode, $eNew = null) { global $wgMimeType; if (defined('MW_API')) { // Unhandled API exception, we can't be sure that format printer is alive self::header('MediaWiki-API-Error: internal_api_error_' . get_class($e)); wfHttpError(500, 'Internal Server Error', self::getText($e)); } elseif (self::isCommandLine()) { self::printError(self::getText($e)); } elseif ($mode === self::AS_PRETTY) { if ($e instanceof DBConnectionError) { self::reportOutageHTML($e); } else { self::statusHeader(500); self::header("Content-Type: {$wgMimeType}; charset=utf-8"); self::reportHTML($e); } } else { if ($eNew) { $message = "MediaWiki internal error.\n\n"; if (self::showBackTrace($e)) { $message .= 'Original exception: ' . MWExceptionHandler::getLogMessage($e) . "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString($e) . "\n\nException caught inside exception handler: " . MWExceptionHandler::getLogMessage($eNew) . "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString($eNew); } else { $message .= "Exception caught inside exception handler.\n\n" . "Set \$wgShowExceptionDetails = true; at the bottom of LocalSettings.php " . "to show detailed debugging information."; } $message .= "\n"; } else { if (self::showBackTrace($e)) { $message = MWExceptionHandler::getLogMessage($e) . "\nBacktrace:\n" . MWExceptionHandler::getRedactedTraceAsString($e) . "\n"; } else { $message = MWExceptionHandler::getPublicLogMessage($e); } } if (self::isCommandLine()) { self::printError($message); } else { echo nl2br(htmlspecialchars($message)) . "\n"; } } }
function execute($par) { global $wgUser, $wgOut; /** * Some satellite ISPs use broken precaching schemes that log people out straight after * they're logged in (bug 17790). Luckily, there's a way to detect such requests. */ if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], '&') !== false) { wfDebug("Special:Userlogout request {$_SERVER['REQUEST_URI']} looks suspicious, denying.\n"); wfHttpError(400, wfMsg('loginerror'), wfMsg('suspicious-userlogout')); return; } $this->setHeaders(); $this->outputHeader(); $oldName = $wgUser->getName(); $wgUser->logout(); $wgOut->addWikiMsg('logouttext'); // Hook. $injected_html = ''; wfRunHooks('UserLogoutComplete', array(&$wgUser, &$injected_html, $oldName)); $wgOut->addHTML($injected_html); $wgOut->returnToMain(); }
// Content-Type if it sees a recognized extension on the URL, such as // might be appended via PATH_INFO after 'api.php'. // // Some data formats can end up containing unfiltered user-provided data // which will end up triggering HTML detection and execution, hence // XSS injection and all that entails. // // Ensure that all access is through the canonical entry point... // if (isset($_SERVER['SCRIPT_URL'])) { $url = $_SERVER['SCRIPT_URL']; } else { $url = $_SERVER['PHP_SELF']; } if (strcmp("{$wgScriptPath}/api{$wgScriptExtension}", $url)) { wfHttpError(403, 'Forbidden', 'API must be accessed through the primary script entry point.'); return; } // Verify that the API has not been disabled if (!$wgEnableAPI) { echo 'MediaWiki API is not enabled for this site. Add the following line to your LocalSettings.php'; echo '<pre><b>$wgEnableAPI=true;</b></pre>'; die(1); } // So extensions can check whether they're running in API mode define('MW_API', true); // Set a dummy $wgTitle, because $wgTitle == null breaks various things // In a perfect world this wouldn't be necessary $wgTitle = Title::newFromText('API'); /* Construct an ApiMain with the arguments passed via the URL. What we get back * is some form of an ApiMain, possibly even one that produces an error message,
/** * Show an error page, if page not found */ protected function showPageNotFound() { wfHttpError(404, $this->msg('mobile-frontend-history-404-title')->text(), $this->msg('mobile-frontend-history-404-desc')->text()); }
ini_set("display_errors", 1); // So extensions (and other code) can check whether they're running in API mode define('MW_API', true); $apiDir = dirname(__FILE__); $globAPIModules = array(); $globAutoloadClasses = array(); require $apiDir . (file_exists($apiDir . '/api.config.php') ? '/api.config.php' : '/api.config.default.php'); // Initialise common code require $apiDir . '/phpapi/WebStart.php'; // URL safety checks // // See RawPage.php for details; summary is that MSIE can override the // Content-Type if it sees a recognized extension on the URL, such as // might be appended via PATH_INFO after 'api.php'. // // Some data formats can end up containing unfiltered user-provided data // which will end up triggering HTML detection and execution, hence // XSS injection and all that entails. // if ($wgRequest->isPathInfoBad()) { // TODO wfHttpError(403, 'Forbidden', 'Invalid file extension found in PATH_INFO. ' . 'The API must be accessed through the primary script entry point.'); return; } /* Construct an ApiMain with the arguments passed via the URL. What we get back * is some form of an ApiMain, possibly even one that produces an error message, * but we don't care here, as that is handled by the ctor. */ $processor = new ApiMain($wgRequest); // Process data & print results $processor->execute();
/** * Perform one of the "standard" actions * * @param $output OutputPage * @param $article Article * @param $title Title * @param $user User * @param $request WebRequest */ function performAction(&$output, &$article, &$title, &$user, &$request) { wfProfileIn(__METHOD__); if (!wfRunHooks('MediaWikiPerformAction', array($output, $article, $title, $user, $request, $this))) { wfProfileOut(__METHOD__); return; } $action = $this->getVal('Action'); if (in_array($action, $this->getVal('DisabledActions', array()))) { /* No such action; this will switch to the default case */ $action = 'nosuchaction'; } // Workaround for bug #20966: inability of IE to provide an action dependent // on which submit button is clicked. if ($action === 'historysubmit') { if ($request->getBool('revisiondelete')) { $action = 'revisiondelete'; } else { $action = 'view'; } } switch ($action) { case 'view': $output->setSquidMaxage($this->getVal('SquidMaxage')); $article->view(); break; case 'raw': // includes JS/CSS wfProfileIn(__METHOD__ . '-raw'); $raw = new RawPage($article); $raw->view(); wfProfileOut(__METHOD__ . '-raw'); break; case 'watch': case 'unwatch': case 'delete': case 'revert': case 'rollback': case 'protect': case 'unprotect': case 'info': case 'markpatrolled': case 'render': case 'deletetrackback': case 'purge': $article->{$action}(); break; case 'print': $article->view(); break; case 'dublincore': if (!$this->getVal('EnableDublinCoreRdf')) { wfHttpError(403, 'Forbidden', wfMsg('nodublincore')); } else { $rdf = new DublinCoreRdf($article); $rdf->show(); } break; case 'creativecommons': if (!$this->getVal('EnableCreativeCommonsRdf')) { wfHttpError(403, 'Forbidden', wfMsg('nocreativecommons')); } else { $rdf = new CreativeCommonsRdf($article); $rdf->show(); } break; case 'credits': Credits::showPage($article); break; case 'submit': if (session_id() == '') { /* Send a cookie so anons get talk message notifications */ wfSetupSession(); } /* Continue... */ /* Continue... */ case 'edit': case 'editredlink': if (wfRunHooks('CustomEditor', array($article, $user))) { $internal = $request->getVal('internaledit'); $external = $request->getVal('externaledit'); $section = $request->getVal('section'); $oldid = $request->getVal('oldid'); if (!$this->getVal('UseExternalEditor') || $action == 'submit' || $internal || $section || $oldid || !$user->getOption('externaleditor') && !$external) { $editor = new EditPage($article); $editor->submit(); } elseif ($this->getVal('UseExternalEditor') && ($external || $user->getOption('externaleditor'))) { $mode = $request->getVal('mode'); $extedit = new ExternalEdit($article, $mode); $extedit->edit(); } } break; case 'history': if ($request->getFullRequestURL() == $title->getInternalURL('action=history')) { $output->setSquidMaxage($this->getVal('SquidMaxage')); } $history = new HistoryPage($article); $history->history(); break; case 'revisiondelete': // For show/hide submission from history page $special = SpecialPage::getPage('Revisiondelete'); $special->execute(''); break; default: if (wfRunHooks('UnknownAction', array($action, $article))) { $output->showErrorPage('nosuchaction', 'nosuchactiontext'); } } wfProfileOut(__METHOD__); }
/** * Stream a contained file directly to HTTP output. * Will throw a 404 if file is missing; 400 if invalid key. * @return true on success, false on failure */ function stream($key) { $path = $this->filePath($key); if ($path === false) { wfHttpError(400, "Bad request", "Invalid or badly-formed filename."); return false; } if (file_exists($path)) { // Set the filename for more convenient save behavior from browsers // FIXME: Is this safe? header('Content-Disposition: inline; filename="' . $key . '"'); require_once 'StreamFile.php'; wfStreamFile($path); } else { return wfHttpError(404, "Not found", "The requested resource does not exist."); } }
function view() { global $wgUser, $wgOut, $wgScript; if (isset($_SERVER['SCRIPT_URL'])) { # Normally we use PHP_SELF to get the URL to the script # as it was called, minus the query string. # # Some sites use Apache rewrite rules to handle subdomains, # and have PHP set up in a weird way that causes PHP_SELF # to contain the rewritten URL instead of the one that the # outside world sees. # # If in this mode, use SCRIPT_URL instead, which mod_rewrite # provides containing the "before" URL. $url = $_SERVER['SCRIPT_URL']; } else { $url = $_SERVER['PHP_SELF']; } if (strcmp($wgScript, $url)) { # Internet Explorer will ignore the Content-Type header if it # thinks it sees a file extension it recognizes. Make sure that # all raw requests are done through the script node, which will # have eg '.php' and should remain safe. # # We used to redirect to a canonical-form URL as a general # backwards-compatibility / good-citizen nice thing. However # a lot of servers are set up in buggy ways, resulting in # redirect loops which hang the browser until the CSS load # times out. # # Just return a 403 Forbidden and get it over with. wfHttpError(403, 'Forbidden', 'Raw pages must be accessed through the primary script entry point.'); return; } header("Content-type: " . $this->mContentType . '; charset=' . $this->mCharset); # allow the client to cache this for 24 hours header('Cache-Control: s-maxage=' . $this->mSmaxage . ', max-age=' . $this->mMaxage); if ($this->mGen) { $sk = $wgUser->getSkin(); $sk->initPage($wgOut); if ($this->mGen == 'css') { echo $sk->getUserStylesheet(); } else { if ($this->mGen == 'js') { echo $sk->getUserJs(); } } } else { echo $this->getrawtext(); } $wgOut->disable(); }
function showImage() { global $wgOut; $wgOut->disable(); $info = $this->retrieveCaptcha(); if ($info) { $timestamp = new MWTimestamp(); $info['viewed'] = $timestamp->getTimestamp(); $this->storeCaptcha($info); $salt = $info['salt']; $hash = $info['hash']; return $this->getBackend()->streamFile(array('src' => $this->imagePath($salt, $hash), 'headers' => array("Cache-Control: private, s-maxage=0, max-age=3600")))->isOK(); } wfHttpError(500, 'Internal Error', 'Requested bogus captcha image'); return false; }
function showImage() { global $wgOut; $wgOut->disable(); $info = $this->retrieveCaptcha(); if ($info) { /* // Be a little less restrictive for now; in at least some circumstances, // Konqueror tries to reload the image even if you haven't navigated // away from the page. if( $info['viewed'] ) { wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." ); return false; } */ $info['viewed'] = wfTimestamp(); $this->storeCaptcha($info); $salt = $info['salt']; $hash = $info['hash']; $file = $this->imagePath($salt, $hash); if (file_exists($file)) { global $IP; require_once "{$IP}/includes/StreamFile.php"; header("Cache-Control: private, s-maxage=0, max-age=3600"); wfStreamFile($file); return true; } } wfHttpError(500, 'Internal Error', 'Requested bogus captcha image'); return false; }
function view() { global $wgOut, $wgScript, $wgRequest; if ($wgRequest->isPathInfoBad()) { # Internet Explorer will ignore the Content-Type header if it # thinks it sees a file extension it recognizes. Make sure that # all raw requests are done through the script node, which will # have eg '.php' and should remain safe. # # We used to redirect to a canonical-form URL as a general # backwards-compatibility / good-citizen nice thing. However # a lot of servers are set up in buggy ways, resulting in # redirect loops which hang the browser until the CSS load # times out. # # Just return a 403 Forbidden and get it over with. wfHttpError(403, 'Forbidden', 'Invalid file extension found in PATH_INFO or QUERY_STRING. ' . 'Raw pages must be accessed through the primary script entry point.'); return; } header("Content-type: " . $this->mContentType . '; charset=' . $this->mCharset); # allow the client to cache this for 24 hours $mode = $this->mPrivateCache ? 'private' : 'public'; header('Cache-Control: ' . $mode . ', s-maxage=' . $this->mSmaxage . ', max-age=' . $this->mMaxage); global $wgUseFileCache; if ($wgUseFileCache and HTMLFileCache::useFileCache()) { $cache = new HTMLFileCache($this->mTitle, 'raw'); if ($cache->isFileCacheGood()) { $cache->loadFromFileCache(); $wgOut->disable(); return; } else { ob_start(array(&$cache, 'saveToFileCache')); } } $text = $this->getRawText(); if (!wfRunHooks('RawPageViewBeforeOutput', array(&$this, &$text))) { wfDebug(__METHOD__ . ": RawPageViewBeforeOutput hook broke raw page output.\n"); } echo $text; $wgOut->disable(); }
function view() { global $wgOut, $wgScript; if (isset($_SERVER['SCRIPT_URL'])) { # Normally we use PHP_SELF to get the URL to the script # as it was called, minus the query string. # # Some sites use Apache rewrite rules to handle subdomains, # and have PHP set up in a weird way that causes PHP_SELF # to contain the rewritten URL instead of the one that the # outside world sees. # # If in this mode, use SCRIPT_URL instead, which mod_rewrite # provides containing the "before" URL. $url = $_SERVER['SCRIPT_URL']; } else { $url = $_SERVER['PHP_SELF']; } if (strcmp($wgScript, $url)) { # Internet Explorer will ignore the Content-Type header if it # thinks it sees a file extension it recognizes. Make sure that # all raw requests are done through the script node, which will # have eg '.php' and should remain safe. # # We used to redirect to a canonical-form URL as a general # backwards-compatibility / good-citizen nice thing. However # a lot of servers are set up in buggy ways, resulting in # redirect loops which hang the browser until the CSS load # times out. # # Just return a 403 Forbidden and get it over with. wfHttpError(403, 'Forbidden', 'Raw pages must be accessed through the primary script entry point.'); return; } header("Content-type: " . $this->mContentType . '; charset=' . $this->mCharset); # allow the client to cache this for 24 hours $mode = $this->mPrivateCache ? 'private' : 'public'; header('Cache-Control: ' . $mode . ', s-maxage=' . $this->mSmaxage . ', max-age=' . $this->mMaxage); if (HTMLFileCache::useFileCache()) { $cache = new HTMLFileCache($this->mTitle, 'raw'); if ($cache->isFileCacheGood()) { $cache->loadFromFileCache(); $wgOut->disable(); return; } else { ob_start(array(&$cache, 'saveToFileCache')); } } $text = $this->getRawText(); if (!wfRunHooks('RawPageViewBeforeOutput', array(&$this, &$text))) { wfDebug(__METHOD__ . ': RawPageViewBeforeOutput hook broke raw page output.'); } echo $text; $wgOut->disable(); }
function wfRdfSpecialPage($par) { global $wgRequest, $wgOut, $_SERVER, $_REQUEST; MwRdf::setup(); $target = $wgRequest->getVal('target'); if (!isset($target) || $target == null) { # no target parameter MwRdf::ShowForm(); return; } if (strlen($target) == 0) { # no target contents MwRdf::ShowForm(wfMsg('badtitle')); return; } $nt = Title::newFromText($target); if ($nt->getArticleID() == 0) { # not an article MwRdf::ShowForm(wfMsg('badtitle')); return; } $format = $wgRequest->getVal('format', 'rdfxml'); $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null; $rdftype = wfNegotiateType(wfAcceptToPrefs($accept), wfAcceptToPrefs(MwRdf::getTypePrefs($format))); if (!$rdftype) { wfHttpError(406, "Not Acceptable", wfMsg("notacceptable")); return false; } $wgOut->disable(); if (!headers_sent()) { header("Content-type: {$rdftype}"); } $wgOut->sendCacheControl(); $mf = MwRdf::ModelingAgent($nt); # Note: WebRequest chokes on arrays here $modelnames = null; if (isset($_REQUEST['modelnames'])) { $modelnames = $_REQUEST['modelnames']; } if (is_null($modelnames)) { $modelnames = $mf->listDefaultModels(); } if (is_string($modelnames)) { $modelnames = explode(',', $modelnames); } if (!$modelnames) { MwRdf::ShowForm(wfMsg('nomodelsselected')); return; } $model = $mf->retrieveModel($modelnames); if (!$model->current()) { $mf->storeAllModels(); $model = $mf->retrieveModel($modelnames); } $ser = MwRdf::Serializer($format); $text = $model->serializeStatements($ser); # XXX: Test Hook: it would be better if we could capture the # print statement below with an output buffer, but that is # disabled for the CLI in PHP 5 if (isset($_SERVER['CONTEXT']) && $_SERVER['CONTEXT'] == 'phpunit test') { return $text; } else { print $text; return true; } }
/** * Get the text that should be returned, or false if the page or revision * was not found. * * @return String|Bool */ public function getRawText() { global $wgParser; # No longer used if ($this->mGen) { return ''; } $text = false; $title = $this->getTitle(); $request = $this->getRequest(); // If it's a MediaWiki message we can just hit the message cache if ($request->getBool('usemsgcache') && $title->getNamespace() == NS_MEDIAWIKI) { // The first "true" is to use the database, the second is to use the content langue // and the last one is to specify the message key already contains the language in it ("/de", etc.) $text = MessageCache::singleton()->get($title->getDBkey(), true, true, true); // If the message doesn't exist, return a blank if ($text === false) { $text = ''; } } else { // Get it from the DB $rev = Revision::newFromTitle($title, $this->getOldId()); if ($rev) { $lastmod = wfTimestamp(TS_RFC2822, $rev->getTimestamp()); $request->response()->header("Last-modified: {$lastmod}"); // Public-only due to cache headers $content = $rev->getContent(); if ($content === null) { // revision not found (or suppressed) $text = false; } elseif (!$content instanceof TextContent) { // non-text content wfHttpError(415, "Unsupported Media Type", "The requested page uses the content model `" . $content->getModel() . "` which is not supported via this interface."); die; } else { // want a section? $section = $request->getIntOrNull('section'); if ($section !== null) { $content = $content->getSection($section); } if ($content === null || $content === false) { // section not found (or section not supported, e.g. for JS and CSS) $text = false; } else { $text = $content->getNativeData(); } } } } if ($text !== false && $text !== '' && $request->getVal('templates') === 'expand') { $text = $wgParser->preprocess($text, $title, ParserOptions::newFromContext($this->getContext())); } return $text; }
$wgArticle->{$action}(); break; case 'print': $wgArticle->view(); break; case 'dublincore': if (!$wgEnableDublinCoreRdf) { wfHttpError(403, 'Forbidden', wfMsg('nodublincore')); } else { require_once 'includes/Metadata.php'; wfDublinCoreRdf($wgArticle); } break; case 'creativecommons': if (!$wgEnableCreativeCommonsRdf) { wfHttpError(403, 'Forbidden', wfMsg('nocreativecommons')); } else { require_once 'includes/Metadata.php'; wfCreativeCommonsRdf($wgArticle); } break; case 'credits': require_once 'includes/Credits.php'; showCreditsPage($wgArticle); break; case 'submit': if (!$wgCommandLineMode && !$wgRequest->checkSessionCookie()) { # Send a cookie so anons get talk message notifications User::SetupSession(); } # Continue...
/** * If file available in stash, cats it out to the client as a simple HTTP response. * n.b. Most sanity checking done in UploadStashLocalFile, so this is straightforward. * * @param $key String: the key of a particular requested file */ public function showUpload($key) { global $wgOut; // prevent callers from doing standard HTML output -- we'll take it from here $wgOut->disable(); try { $params = $this->parseKey($key); if ($params['type'] === 'thumb') { return $this->outputThumbFromStash($params['file'], $params['params']); } else { return $this->outputLocalFile($params['file']); } } catch (UploadStashFileNotFoundException $e) { $code = 404; $message = $e->getMessage(); } catch (UploadStashZeroLengthFileException $e) { $code = 500; $message = $e->getMessage(); } catch (UploadStashBadPathException $e) { $code = 500; $message = $e->getMessage(); } catch (SpecialUploadStashTooLargeException $e) { $code = 500; $message = 'Cannot serve a file larger than ' . self::MAX_SERVE_BYTES . ' bytes. ' . $e->getMessage(); } catch (Exception $e) { $code = 500; $message = $e->getMessage(); } wfHttpError($code, HttpStatus::getMessage($code), $message); return false; }
function rcOutputFeed($rows, $feedFormat, $limit, $hideminor, $lastmod) { global $messageMemc, $wgFeedCacheTimeout; global $wgFeedClasses, $wgTitle, $wgSitename, $wgContLanguageCode; if (!isset($wgFeedClasses[$feedFormat])) { wfHttpError(500, "Internal Server Error", "Unsupported feed type."); return false; } $timekey = wfMemcKey('rcfeed', $feedFormat, 'timestamp'); $key = wfMemcKey('rcfeed', $feedFormat, 'limit', $limit, 'minor', $hideminor); $feedTitle = $wgSitename . ' - ' . wfMsgForContent('recentchanges') . ' [' . $wgContLanguageCode . ']'; $feed = new $wgFeedClasses[$feedFormat]($feedTitle, htmlspecialchars(wfMsgForContent('recentchanges-feed-description')), $wgTitle->getFullUrl()); //purge cache if requested global $wgRequest, $wgUser; $purge = $wgRequest->getVal('action') == 'purge'; if ($purge && $wgUser->isAllowed('purge')) { $messageMemc->delete($timekey); $messageMemc->delete($key); } /** * Bumping around loading up diffs can be pretty slow, so where * possible we want to cache the feed output so the next visitor * gets it quick too. */ $cachedFeed = false; if ($wgFeedCacheTimeout > 0 && ($feedLastmod = $messageMemc->get($timekey))) { /** * If the cached feed was rendered very recently, we may * go ahead and use it even if there have been edits made * since it was rendered. This keeps a swarm of requests * from being too bad on a super-frequently edited wiki. */ if (time() - wfTimestamp(TS_UNIX, $feedLastmod) < $wgFeedCacheTimeout || wfTimestamp(TS_UNIX, $feedLastmod) > wfTimestamp(TS_UNIX, $lastmod)) { wfDebug("RC: loading feed from cache ({$key}; {$feedLastmod}; {$lastmod})...\n"); $cachedFeed = $messageMemc->get($key); } else { wfDebug("RC: cached feed timestamp check failed ({$feedLastmod}; {$lastmod})\n"); } } if (is_string($cachedFeed)) { wfDebug("RC: Outputting cached feed\n"); $feed->httpHeaders(); echo $cachedFeed; } else { wfDebug("RC: rendering new feed and caching it\n"); ob_start(); rcDoOutputFeed($rows, $feed); $cachedFeed = ob_get_contents(); ob_end_flush(); $expire = 3600 * 24; # One day $messageMemc->set($key, $cachedFeed); $messageMemc->set($timekey, wfTimestamp(TS_MW), $expire); } return true; }
/** * Render a resultswitcher page */ protected function handleResultRequest() { //no longer letting people in without these things. If this is //preventing you from doing something, you almost certainly want to be //somewhere else. $deadSession = false; if (!$this->adapter->session_hasDonorData()) { $deadSession = true; } $oid = $this->adapter->getData_Unstaged_Escaped('order_id'); $request = $this->getRequest(); $referrer = $request->getHeader('referer'); $liberated = false; if ($this->adapter->session_getData('order_status', $oid) === 'liberated') { $liberated = true; } // XXX need to know whether we were in an iframe or not. global $wgServer; if ($this->isReturnFramed() && strpos($referrer, $wgServer) === false && !$liberated) { $sessionOrderStatus = $request->getSessionData('order_status'); $sessionOrderStatus[$oid] = 'liberated'; $request->setSessionData('order_status', $sessionOrderStatus); $this->logger->info("Resultswitcher: Popping out of iframe for Order ID " . $oid); $this->getOutput()->allowClickjacking(); $this->getOutput()->addModules('iframe.liberator'); return; } $this->setHeaders(); if ($deadSession) { if ($this->adapter->isReturnProcessingRequired()) { wfHttpError(403, 'Forbidden', wfMessage('donate_interface-error-http-403')->text()); throw new RuntimeException('Resultswitcher: Request forbidden. No active donation in the session. ' . "Adapter Order ID: {$oid}"); } // If it's possible for a donation to go through without our // having to do additional processing in the result switcher, // we don't want to falsely claim it failed just because we // lost the session data. We also don't want to give any // information to scammers hitting this page with no session, // so we always show the thank you page. We don't want to do // any post-processing if we're not sure whether we actually // originated this attempt, so we return right after. $this->logger->warning('Resultswitcher: session is dead, but the ' . 'donor may have made a successful payment.'); $this->displayThankYouPage('dead session'); return; } $this->logger->info("Resultswitcher: OK to process Order ID: " . $oid); if ($this->adapter->checkTokens()) { $this->getOutput()->allowClickjacking(); // FIXME: do we really need this again? $this->getOutput()->addModules('iframe.liberator'); // processResponse expects some data, so let's feed it all the // GET and POST vars $response = $this->getRequest()->getValues(); // TODO: run the whole set of getResponseStatus, getResponseErrors // and getResponseData first. Maybe do_transaction with a // communication_type of 'incoming' and a way to provide the // adapter the GET/POST params harvested here. $this->adapter->processResponse($response); $status = $this->adapter->getFinalStatus(); switch ($status) { case FinalStatus::COMPLETE: case FinalStatus::PENDING: $this->displayThankYouPage($status); return; } $this->logger->info("Displaying fail page for final status {$status}"); } else { $this->logger->error("Resultswitcher: Token Check Failed. Order ID: {$oid}"); } $this->displayFailPage(); }
/** * Perform one of the "standard" actions */ function performAction(&$output, &$article, &$title, &$user, &$request) { wfProfileIn('MediaWiki::performAction'); $action = $this->getVal('Action'); if (in_array($action, $this->getVal('DisabledActions', array()))) { /* No such action; this will switch to the default case */ $action = 'nosuchaction'; } switch ($action) { case 'view': $output->setSquidMaxage($this->getVal('SquidMaxage')); $article->view(); break; case 'watch': case 'unwatch': case 'delete': case 'revert': case 'rollback': case 'protect': case 'unprotect': case 'info': case 'markpatrolled': case 'render': case 'deletetrackback': case 'purge': $article->{$action}(); break; case 'print': $article->view(); break; case 'dublincore': if (!$this->getVal('EnableDublinCoreRdf')) { wfHttpError(403, 'Forbidden', wfMsg('nodublincore')); } else { require_once 'includes/Metadata.php'; wfDublinCoreRdf($article); } break; case 'creativecommons': if (!$this->getVal('EnableCreativeCommonsRdf')) { wfHttpError(403, 'Forbidden', wfMsg('nocreativecommons')); } else { require_once 'includes/Metadata.php'; wfCreativeCommonsRdf($article); } break; case 'credits': require_once 'includes/Credits.php'; showCreditsPage($article); break; case 'submit': if (!$this->getVal('CommandLineMode') && !$request->checkSessionCookie()) { /* Send a cookie so anons get talk message notifications */ User::SetupSession(); } /* Continue... */ /* Continue... */ case 'edit': $internal = $request->getVal('internaledit'); $external = $request->getVal('externaledit'); $section = $request->getVal('section'); $oldid = $request->getVal('oldid'); if (!$this->getVal('UseExternalEditor') || $action == 'submit' || $internal || $section || $oldid || !$user->getOption('externaleditor') && !$external) { $editor = new EditPage($article); $editor->submit(); } elseif ($this->getVal('UseExternalEditor') && ($external || $user->getOption('externaleditor'))) { $mode = $request->getVal('mode'); $extedit = new ExternalEdit($article, $mode); $extedit->edit(); } break; case 'history': if ($_SERVER['REQUEST_URI'] == $title->getInternalURL('action=history')) { $output->setSquidMaxage($this->getVal('SquidMaxage')); } $history = new PageHistory($article); $history->history(); break; case 'raw': $raw = new RawPage($article); $raw->view(); break; default: if (wfRunHooks('UnknownAction', array($action, $article))) { $output->showErrorPage('nosuchaction', 'nosuchactiontext'); } } wfProfileOut('MediaWiki::performAction'); }
function showImage() { global $wgOut, $wgRequest; $wgOut->disable(); $info = $this->retrieveCaptcha(); if ($info) { #echo "noooooo!"; /* // Be a little less restrictive for now; in at least some circumstances, // Konqueror tries to reload the image even if you haven't navigated // away from the page. if( $info['viewed'] ) { wfHttpError( 403, 'Access Forbidden', "Can't view captcha image a second time." ); return false; } */ $info['viewed'] = wfTimestamp(); $this->storeCaptcha($info); $salt = $info['salt']; $hash = $info['hash']; $file = $this->imagePath($salt, $hash); #echo $file; if (file_exists($file)) { global $IP; //require_once "$IP/includes/StreamFile.php"; header("Cache-Control: private, s-maxage=0, max-age=3600"); header('Content-Type: image/png'); $fp = fopen($file, 'r'); fpassthru($fp); return true; } } wfHttpError(401, 'Access Denied', 'Requested bogus captcha image'); return false; }
/** Pass the request to our internal function. * BEWARE! Data are passed as they have been supplied by the user, * they should be carefully handled in the function processing the * request. */ function performAction() { global $wgAjaxExportList, $wgOut, $wgUser; if (empty($this->mode)) { return; } /* * Wikia Change - begin */ Transaction::setEntryPoint(Transaction::ENTRY_POINT_AJAX); Transaction::setAttribute(Transaction::PARAM_FUNCTION, $this->func_name); if (function_exists('newrelic_disable_autorum')) { newrelic_disable_autorum(); } /* * Wikia Change - end */ wfProfileIn(__METHOD__); if (!in_array($this->func_name, $wgAjaxExportList)) { wfDebug(__METHOD__ . ' Bad Request for unknown function ' . $this->func_name . "\n"); wfHttpError(400, 'Bad Request', "unknown function " . (string) $this->func_name); } elseif (!in_array('read', User::getGroupPermissions(array('*')), true) && !$wgUser->isAllowed('read')) { wfHttpError(403, 'Forbidden', 'You must log in to view pages.'); } else { wfDebug(__METHOD__ . ' dispatching ' . $this->func_name . "\n"); if (strpos($this->func_name, '::') !== false) { $func = explode('::', $this->func_name, 2); } else { $func = $this->func_name; } try { $result = call_user_func_array($func, $this->args); if ($result === false || $result === null) { wfDebug(__METHOD__ . ' ERROR while dispatching ' . $this->func_name . "(" . var_export($this->args, true) . "): " . "no data returned\n"); /* Wikia changes start */ //let's avoid falling back to Iowa (500, 503) in this case, //probably someone is asking for a non-existing dynamic method name wfHttpError(501, 'Not Implemented', "{$this->func_name} returned no data"); } else { if (is_string($result)) { $result = new AjaxResponse($result); } $result->sendHeaders(); $result->printText(); wfDebug(__METHOD__ . ' dispatch complete for ' . $this->func_name . "\n"); } } catch (Exception $e) { wfDebug(__METHOD__ . ' ERROR while dispatching ' . $this->func_name . "(" . var_export($this->args, true) . "): " . get_class($e) . ": " . $e->getMessage() . "\n"); if (!headers_sent()) { wfHttpError(500, 'Internal Error', $e->getMessage()); } else { print $e->getMessage(); } } } $wgOut = null; wfProfileOut(__METHOD__); }
/** Pass the request to our internal function. * BEWARE! Data are passed as they have been supplied by the user, * they should be carefully handled in the function processing the * request. */ function performAction() { global $wgAjaxExportList, $wgOut; if (empty($this->mode)) { return; } wfProfileIn(__METHOD__); if (!in_array($this->func_name, $wgAjaxExportList)) { wfDebug(__METHOD__ . ' Bad Request for unknown function ' . $this->func_name . "\n"); wfHttpError(400, 'Bad Request', "unknown function " . (string) $this->func_name); } else { wfDebug(__METHOD__ . ' dispatching ' . $this->func_name . "\n"); if (strpos($this->func_name, '::') !== false) { $func = explode('::', $this->func_name, 2); } else { $func = $this->func_name; } try { $result = call_user_func_array($func, $this->args); if ($result === false || $result === NULL) { wfDebug(__METHOD__ . ' ERROR while dispatching ' . $this->func_name . "(" . var_export($this->args, true) . "): " . "no data returned\n"); wfHttpError(500, 'Internal Error', "{$this->func_name} returned no data"); } else { if (is_string($result)) { $result = new AjaxResponse($result); } $result->sendHeaders(); $result->printText(); wfDebug(__METHOD__ . ' dispatch complete for ' . $this->func_name . "\n"); } } catch (Exception $e) { wfDebug(__METHOD__ . ' ERROR while dispatching ' . $this->func_name . "(" . var_export($this->args, true) . "): " . get_class($e) . ": " . $e->getMessage() . "\n"); if (!headers_sent()) { wfHttpError(500, 'Internal Error', $e->getMessage()); } else { print $e->getMessage(); } } } wfProfileOut(__METHOD__); $wgOut = null; }