/** * Displays an error message if the page has been blacklisted and the action implies parsing and rendering. */ function efSlowPagesBlacklist($oTitle, $unused, $oOutputPage, $oUser, $oWebRequest, $oMediaWiki) { global $wgSlowPagesBlacklist; $sFullUrl = $oTitle->getFullURL(); if (in_array($sFullUrl, $wgSlowPagesBlacklist)) { switch ($oMediaWiki->getAction()) { case 'delete': case 'history': case 'raw': case 'rollback': case 'submit': // Let through. break; case 'edit': // Force text editor since the visual editor implies parsing. if ('source' != $oWebRequest->getVal('useeditor', '')) { $oResponse = $oWebRequest->response(); $iCode = 303; $sMessage = HttpStatus::getMessage($iCode); $oResponse->header("HTTP/1.1 {$iCode} {$sMessage}"); $oResponse->header("Location: {$sFullUrl}?action=edit&useeditor=source"); } break; default: // If a staff user requested forceview, let through. if (!$oUser->isAllowed('forceview') || !$oWebRequest->getInt('forceview')) { throw new ErrorPageError('slowpagesblacklist-title', 'slowpagesblacklist-content'); } break; } } return true; }
public function ServiceException($code, $message = NULL) { if ($message === NULL) { $message = HttpStatus::getMessage($code); } parent::__construct($message, $code); }
/** * Borrowed from \Wikibase\Test\SpecialPageTestBase * * @param string $sub The subpage parameter to call the page with * @param WebRequest $request Web request that may contain URL parameters, etc */ protected function execute($sub = '', WebRequest $request = null, $user = null) { $request = $request === null ? new FauxRequest() : $request; $response = $request->response(); $page = $this->getInstance(); if ($this->store !== null) { $page->setStore($this->store); } $page->setContext($this->makeRequestContext($request, $user, $this->getTitle($page))); $out = $page->getOutput(); ob_start(); $page->execute($sub); if ($out->getRedirect() !== '') { $out->output(); $text = ob_get_contents(); } elseif ($out->isDisabled()) { $text = ob_get_contents(); } else { $text = $out->getHTML(); } ob_end_clean(); $code = $response->getStatusCode(); if ($code > 0) { $response->header("Status: " . $code . ' ' . \HttpStatus::getMessage($code)); } $this->text = $text; $this->response = $response; }
public function sendError() { $message = $this->getMessage(); $code = $this->getStatusCode(); header("HTTP/1.0 " . HttpStatus::getMessage($code)); foreach ($this->getAdditionalHeaders() as $k => $v) { header($k . ': ' . $v, false); } echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; echo '<html>'; echo '<head><title>Error</title></head>'; echo '<body><p>Error ' . httpStatus::getMessage($code) . '</p>'; echo '<p>' . $this->getMessage() . '</p></body>'; echo '</html>'; }
/** * Returns HTML for reporting the HTTP error. * This will be a minimal but complete HTML document. * * @return string HTML */ public function getHTML() { if ($this->header === null) { $header = HttpStatus::getMessage($this->httpCode); } elseif ($this->header instanceof Message) { $header = $this->header->escaped(); } else { $header = htmlspecialchars($this->header); } if ($this->content instanceof Message) { $content = $this->content->escaped(); } else { $content = htmlspecialchars($this->content); } return "<!DOCTYPE html>\n" . "<html><head><title>{$header}</title></head>\n" . "<body><h1>{$header}</h1><p>{$content}</p></body></html>\n"; }
/** * @param SpecialPage $page The special page to execute * @param string $subPage The subpage parameter to call the page with * @param WebRequest|null $request Web request that may contain URL parameters, etc * @param Language|string|null $language The language which should be used in the context * @param User|null $user The user which should be used in the context of this special page * * @throws Exception * @return array( string, WebResponse ) A two-elements array containing the HTML output * generated by the special page as well as the response object. */ public function executeSpecialPage(SpecialPage $page, $subPage = '', WebRequest $request = null, $language = null, User $user = null) { $context = $this->newContext($request, $language, $user); $output = new OutputPage($context); $context->setOutput($output); $page->setContext($context); $output->setTitle($page->getPageTitle()); $html = $this->getHTMLFromSpecialPage($page, $subPage); $response = $context->getRequest()->response(); if ($response instanceof FauxResponse) { $code = $response->getStatusCode(); if ($code > 0) { $response->header('Status: ' . $code . ' ' . HttpStatus::getMessage($code)); } } return [$html, $response]; }
private function getTextForRequestBy($page, $request, $queryParameters) { $response = $request->response(); $page->setContext($this->makeRequestContext($request, new MockSuperUser(), $this->getTitle($page))); $out = $page->getOutput(); ob_start(); $page->execute($queryParameters); if ($out->getRedirect() !== '') { $out->output(); $text = ob_get_contents(); } elseif ($out->isDisabled()) { $text = ob_get_contents(); } else { $text = $out->getHTML(); } ob_end_clean(); $code = $response->getStatusCode(); if ($code > 0) { $response->header("Status: " . $code . ' ' . \HttpStatus::getMessage($code)); } return $text; }
/** * Finally, all the text has been munged and accumulated into * the object, let's actually output it: */ public function output() { global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP, $wgUseAjax, $wgResponsiveImages; if ($this->mDoNothing) { return; } wfProfileIn(__METHOD__); $response = $this->getRequest()->response(); if ($this->mRedirect != '') { # Standards require redirect URLs to be absolute $this->mRedirect = wfExpandUrl($this->mRedirect, PROTO_CURRENT); $redirect = $this->mRedirect; $code = $this->mRedirectCode; if (wfRunHooks("BeforePageRedirect", array($this, &$redirect, &$code))) { if ($code == '301' || $code == '303') { if (!$wgDebugRedirects) { $message = HttpStatus::getMessage($code); $response->header("HTTP/1.1 {$code} {$message}"); } $this->mLastModified = wfTimestamp(TS_RFC2822); } if ($wgVaryOnXFP) { $this->addVaryHeader('X-Forwarded-Proto'); } $this->sendCacheControl(); $response->header("Content-Type: text/html; charset=utf-8"); if ($wgDebugRedirects) { $url = htmlspecialchars($redirect); print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n"; print "<p>Location: <a href=\"{$url}\">{$url}</a></p>\n"; print "</body>\n</html>\n"; } else { $response->header('Location: ' . $redirect); } } wfProfileOut(__METHOD__); return; } elseif ($this->mStatusCode) { $message = HttpStatus::getMessage($this->mStatusCode); if ($message) { $response->header('HTTP/1.1 ' . $this->mStatusCode . ' ' . $message); } } # Buffer output; final headers may depend on later processing ob_start(); $response->header("Content-type: {$wgMimeType}; charset=UTF-8"); $response->header('Content-language: ' . $wgLanguageCode); // Prevent framing, if requested $frameOptions = $this->getFrameOptions(); if ($frameOptions) { $response->header("X-Frame-Options: {$frameOptions}"); } if ($this->mArticleBodyOnly) { echo $this->mBodytext; } else { $sk = $this->getSkin(); // add skin specific modules $modules = $sk->getDefaultModules(); // enforce various default modules for all skins $coreModules = array('mediawiki.page.startup', 'mediawiki.user'); // Support for high-density display images if enabled if ($wgResponsiveImages) { $coreModules[] = 'mediawiki.hidpi'; } $this->addModules($coreModules); foreach ($modules as $group) { $this->addModules($group); } MWDebug::addModules($this); if ($wgUseAjax) { // FIXME: deprecate? - not clear why this is useful wfRunHooks('AjaxAddScript', array(&$this)); } // Hook that allows last minute changes to the output page, e.g. // adding of CSS or Javascript by extensions. wfRunHooks('BeforePageDisplay', array(&$this, &$sk)); wfProfileIn('Output-skin'); $sk->outputPage(); wfProfileOut('Output-skin'); } // This hook allows last minute changes to final overall output by modifying output buffer wfRunHooks('AfterFinalPageOutput', array($this)); $this->sendCacheControl(); ob_end_flush(); wfProfileOut(__METHOD__); }
public function reportHTML() { $httpMessage = HttpStatus::getMessage($this->httpCode); header("Status: {$this->httpCode} {$httpMessage}"); header('Content-type: text/html; charset=utf-8'); if ($this->header === null) { $header = $httpMessage; } elseif ($this->header instanceof Message) { $header = $this->header->escaped(); } else { $header = htmlspecialchars($this->header); } if ($this->content instanceof Message) { $content = $this->content->escaped(); } else { $content = htmlspecialchars($this->content); } print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" . "<html><head><title>{$header}</title></head>\n" . "<body><h1>{$header}</h1><p>{$content}</p></body></html>\n"; }
/** * 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; }
/** * Stream a thumbnail specified by parameters * * @param $params Array * @return void */ function wfStreamThumb(array $params) { global $wgVaryOnXFP; wfProfileIn(__METHOD__); $headers = array(); // HTTP headers to send $fileName = isset($params['f']) ? $params['f'] : ''; unset($params['f']); // Backwards compatibility parameters if (isset($params['w'])) { $params['width'] = $params['w']; unset($params['w']); } if (isset($params['p'])) { $params['page'] = $params['p']; } unset($params['r']); // ignore 'r' because we unconditionally pass File::RENDER // Is this a thumb of an archived file? $isOld = isset($params['archived']) && $params['archived']; unset($params['archived']); // handlers don't care // Is this a thumb of a temp file? $isTemp = isset($params['temp']) && $params['temp']; unset($params['temp']); // handlers don't care // Some basic input validation $fileName = strtr($fileName, '\\/', '__'); // Actually fetch the image. Method depends on whether it is archived or not. if ($isTemp) { $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo(); $img = new UnregisteredLocalFile(null, $repo, $repo->getZonePath('public') . '/' . $repo->getTempHashPath($fileName) . $fileName); } elseif ($isOld) { // Format is <timestamp>!<name> $bits = explode('!', $fileName, 2); if (count($bits) != 2) { wfThumbError(404, wfMessage('badtitletext')->text()); wfProfileOut(__METHOD__); return; } $title = Title::makeTitleSafe(NS_FILE, $bits[1]); if (!$title) { wfThumbError(404, wfMessage('badtitletext')->text()); wfProfileOut(__METHOD__); return; } $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName($title, $fileName); } else { $img = wfLocalFile($fileName); } // Check the source file title if (!$img) { wfThumbError(404, wfMessage('badtitletext')->text()); wfProfileOut(__METHOD__); return; } // Check permissions if there are read restrictions $varyHeader = array(); if (!in_array('read', User::getGroupPermissions(array('*')), true)) { if (!$img->getTitle() || !$img->getTitle()->userCan('read')) { wfThumbError(403, 'Access denied. You do not have permission to access ' . 'the source file.'); wfProfileOut(__METHOD__); return; } $headers[] = 'Cache-Control: private'; $varyHeader[] = 'Cookie'; } // Check the source file storage path if (!$img->exists()) { wfThumbError(404, "The source file '{$fileName}' does not exist."); wfProfileOut(__METHOD__); return; } elseif ($img->getPath() === false) { wfThumbError(500, "The source file '{$fileName}' is not locally accessible."); wfProfileOut(__METHOD__); return; } // Check IMS against the source file // This means that clients can keep a cached copy even after it has been deleted on the server if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { // Fix IE brokenness $imsString = preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]); // Calculate time wfSuppressWarnings(); $imsUnix = strtotime($imsString); wfRestoreWarnings(); if (wfTimestamp(TS_UNIX, $img->getTimestamp()) <= $imsUnix) { header('HTTP/1.1 304 Not Modified'); wfProfileOut(__METHOD__); return; } } // Get the normalized thumbnail name from the parameters... try { $thumbName = $img->thumbName($params); if (!strlen($thumbName)) { // invalid params? wfThumbError(400, 'The specified thumbnail parameters are not valid.'); wfProfileOut(__METHOD__); return; } $thumbName2 = $img->thumbName($params, File::THUMB_FULL_NAME); // b/c; "long" style } catch (MWException $e) { wfThumbError(500, $e->getHTML()); wfProfileOut(__METHOD__); return; } // For 404 handled thumbnails, we only use the the base name of the URI // for the thumb params and the parent directory for the source file name. // Check that the zone relative path matches up so squid caches won't pick // up thumbs that would not be purged on source file deletion (bug 34231). if (isset($params['rel404'])) { // thumbnail was handled via 404 if (rawurldecode($params['rel404']) === $img->getThumbRel($thumbName)) { // Request for the canonical thumbnail name } elseif (rawurldecode($params['rel404']) === $img->getThumbRel($thumbName2)) { // Request for the "long" thumbnail name; redirect to canonical name $response = RequestContext::getMain()->getRequest()->response(); $response->header("HTTP/1.1 301 " . HttpStatus::getMessage(301)); $response->header('Location: ' . wfExpandUrl($img->getThumbUrl($thumbName), PROTO_CURRENT)); $response->header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 7 * 86400) . ' GMT'); if ($wgVaryOnXFP) { $varyHeader[] = 'X-Forwarded-Proto'; } if (count($varyHeader)) { $response->header('Vary: ' . implode(', ', $varyHeader)); } wfProfileOut(__METHOD__); return; } else { wfThumbError(404, "The given path of the specified thumbnail is incorrect;\n\t\t\t\texpected '" . $img->getThumbRel($thumbName) . "' but got '" . rawurldecode($params['rel404']) . "'."); wfProfileOut(__METHOD__); return; } } // Suggest a good name for users downloading this thumbnail $headers[] = "Content-Disposition: {$img->getThumbDisposition($thumbName)}"; if (count($varyHeader)) { $headers[] = 'Vary: ' . implode(', ', $varyHeader); } // Stream the file if it exists already... $thumbPath = $img->getThumbPath($thumbName); if ($img->getRepo()->fileExists($thumbPath)) { $img->getRepo()->streamFile($thumbPath, $headers); wfProfileOut(__METHOD__); return; } // Thumbnail isn't already there, so create the new thumbnail... try { $thumb = $img->transform($params, File::RENDER_NOW); } catch (Exception $ex) { // Tried to select a page on a non-paged file? $thumb = false; } // Check for thumbnail generation errors... $errorMsg = false; $msg = wfMessage('thumbnail_error'); if (!$thumb) { $errorMsg = $msg->rawParams('File::transform() returned false')->escaped(); } elseif ($thumb->isError()) { $errorMsg = $thumb->getHtmlMsg(); } elseif (!$thumb->hasFile()) { $errorMsg = $msg->rawParams('No path supplied in thumbnail object')->escaped(); } elseif ($thumb->fileIsSource()) { $errorMsg = $msg->rawParams('Image was not scaled, is the requested width bigger than the source?')->escaped(); } if ($errorMsg !== false) { wfThumbError(500, $errorMsg); } else { // Stream the file if there were no errors $thumb->streamFile($headers); } wfProfileOut(__METHOD__); }
/** * Finally, all the text has been munged and accumulated into * the object, let's actually output it: */ public function output() { if ($this->mDoNothing) { return; } $response = $this->getRequest()->response(); $config = $this->getConfig(); if ($this->mRedirect != '') { # Standards require redirect URLs to be absolute $this->mRedirect = wfExpandUrl($this->mRedirect, PROTO_CURRENT); $redirect = $this->mRedirect; $code = $this->mRedirectCode; if (Hooks::run("BeforePageRedirect", array($this, &$redirect, &$code))) { if ($code == '301' || $code == '303') { if (!$config->get('DebugRedirects')) { $message = HttpStatus::getMessage($code); $response->header("HTTP/1.1 {$code} {$message}"); } $this->mLastModified = wfTimestamp(TS_RFC2822); } if ($config->get('VaryOnXFP')) { $this->addVaryHeader('X-Forwarded-Proto'); } $this->sendCacheControl(); $response->header("Content-Type: text/html; charset=utf-8"); if ($config->get('DebugRedirects')) { $url = htmlspecialchars($redirect); print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n"; print "<p>Location: <a href=\"{$url}\">{$url}</a></p>\n"; print "</body>\n</html>\n"; } else { $response->header('Location: ' . $redirect); } } return; } elseif ($this->mStatusCode) { $message = HttpStatus::getMessage($this->mStatusCode); if ($message) { $response->header('HTTP/1.1 ' . $this->mStatusCode . ' ' . $message); } } # Buffer output; final headers may depend on later processing ob_start(); $response->header('Content-type: ' . $config->get('MimeType') . '; charset=UTF-8'); $response->header('Content-language: ' . $config->get('LanguageCode')); // Avoid Internet Explorer "compatibility view" in IE 8-10, so that // jQuery etc. can work correctly. $response->header('X-UA-Compatible: IE=Edge'); // Prevent framing, if requested $frameOptions = $this->getFrameOptions(); if ($frameOptions) { $response->header("X-Frame-Options: {$frameOptions}"); } if ($this->mArticleBodyOnly) { echo $this->mBodytext; } else { $sk = $this->getSkin(); // add skin specific modules $modules = $sk->getDefaultModules(); // enforce various default modules for all skins $coreModules = array('mediawiki.page.startup', 'mediawiki.user'); // Support for high-density display images if enabled if ($config->get('ResponsiveImages')) { $coreModules[] = 'mediawiki.hidpi'; } $this->addModules($coreModules); foreach ($modules as $group) { $this->addModules($group); } MWDebug::addModules($this); // Hook that allows last minute changes to the output page, e.g. // adding of CSS or Javascript by extensions. Hooks::run('BeforePageDisplay', array(&$this, &$sk)); $sk->outputPage(); } // This hook allows last minute changes to final overall output by modifying output buffer Hooks::run('AfterFinalPageOutput', array($this)); $this->sendCacheControl(); ob_end_flush(); }
/** * Finally, all the text has been munged and accumulated into * the object, let's actually output it: */ public function output() { global $wgLanguageCode, $wgDebugRedirects, $wgMimeType, $wgVaryOnXFP; if ($this->mDoNothing) { return; } wfProfileIn(__METHOD__); $response = $this->getRequest()->response(); if ($this->mRedirect != '') { # Standards require redirect URLs to be absolute $this->mRedirect = wfExpandUrl($this->mRedirect, PROTO_CURRENT); $redirect = $this->mRedirect; $code = $this->mRedirectCode; if (wfRunHooks("BeforePageRedirect", array($this, &$redirect, &$code))) { if ($code == '301' || $code == '303') { if (!$wgDebugRedirects) { $message = HttpStatus::getMessage($code); $response->header("HTTP/1.1 {$code} {$message}"); } $this->mLastModified = wfTimestamp(TS_RFC2822); } if ($wgVaryOnXFP) { $this->addVaryHeader('X-Forwarded-Proto'); } $this->sendCacheControl(); $response->header("Content-Type: text/html; charset=utf-8"); if ($wgDebugRedirects) { $url = htmlspecialchars($redirect); print "<html>\n<head>\n<title>Redirect</title>\n</head>\n<body>\n"; print "<p>Location: <a href=\"{$url}\">{$url}</a></p>\n"; print "</body>\n</html>\n"; } else { $response->header('Location: ' . $redirect); } } wfProfileOut(__METHOD__); return; } elseif ($this->mStatusCode) { $message = HttpStatus::getMessage($this->mStatusCode); if ($message) { $response->header('HTTP/1.1 ' . $this->mStatusCode . ' ' . $message); } } # Buffer output; final headers may depend on later processing ob_start(); $response->header("Content-type: {$wgMimeType}; charset=UTF-8"); $response->header('Content-language: ' . $wgLanguageCode); // Prevent framing, if requested $frameOptions = $this->getFrameOptions(); if ($frameOptions) { $response->header("X-Frame-Options: {$frameOptions}"); } if ($this->mArticleBodyOnly) { $this->out($this->mBodytext); } else { $this->addDefaultModules(); $sk = $this->getSkin(); // Hook that allows last minute changes to the output page, e.g. // adding of CSS or Javascript by extensions. wfRunHooks('BeforePageDisplay', array(&$this, &$sk)); wfProfileIn('Output-skin'); $sk->outputPage($this); wfProfileOut('Output-skin'); } $this->sendCacheControl(); ob_end_flush(); wfProfileOut(__METHOD__); }
/** * Stream a thumbnail specified by parameters * * @param array $params List of thumbnailing parameters. In addition to parameters * passed to the MediaHandler, this may also includes the keys: * f (for filename), archived (if archived file), temp (if temp file), * w (alias for width), p (alias for page), r (ignored; historical), * rel404 (path for render on 404 to verify hash path correct), * thumbName (thumbnail name to potentially extract more parameters from * e.g. 'lossy-page1-120px-Foo.tiff' would add page, lossy and width * to the parameters) * @return void */ function wfStreamThumb(array $params) { global $wgVaryOnXFP; $headers = array(); // HTTP headers to send $fileName = isset($params['f']) ? $params['f'] : ''; // Backwards compatibility parameters if (isset($params['w'])) { $params['width'] = $params['w']; unset($params['w']); } if (isset($params['width']) && substr($params['width'], -2) == 'px') { // strip the px (pixel) suffix, if found $params['width'] = substr($params['width'], 0, -2); } if (isset($params['p'])) { $params['page'] = $params['p']; } // Is this a thumb of an archived file? $isOld = isset($params['archived']) && $params['archived']; unset($params['archived']); // handlers don't care // Is this a thumb of a temp file? $isTemp = isset($params['temp']) && $params['temp']; unset($params['temp']); // handlers don't care // Some basic input validation $fileName = strtr($fileName, '\\/', '__'); // Actually fetch the image. Method depends on whether it is archived or not. if ($isTemp) { $repo = RepoGroup::singleton()->getLocalRepo()->getTempRepo(); $img = new UnregisteredLocalFile(null, $repo, $repo->getZonePath('public') . '/' . $repo->getTempHashPath($fileName) . $fileName); } elseif ($isOld) { // Format is <timestamp>!<name> $bits = explode('!', $fileName, 2); if (count($bits) != 2) { wfThumbError(404, wfMessage('badtitletext')->parse()); return; } $title = Title::makeTitleSafe(NS_FILE, $bits[1]); if (!$title) { wfThumbError(404, wfMessage('badtitletext')->parse()); return; } $img = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName($title, $fileName); } else { $img = wfLocalFile($fileName); } // Check the source file title if (!$img) { wfThumbError(404, wfMessage('badtitletext')->parse()); return; } // Check permissions if there are read restrictions $varyHeader = array(); if (!in_array('read', User::getGroupPermissions(array('*')), true)) { if (!$img->getTitle() || !$img->getTitle()->userCan('read')) { wfThumbError(403, 'Access denied. You do not have permission to access ' . 'the source file.'); return; } $headers[] = 'Cache-Control: private'; $varyHeader[] = 'Cookie'; } // Check if the file is hidden if ($img->isDeleted(File::DELETED_FILE)) { wfThumbErrorText(404, "The source file '{$fileName}' does not exist."); return; } // Do rendering parameters extraction from thumbnail name. if (isset($params['thumbName'])) { $params = wfExtractThumbParams($img, $params); } if ($params == null) { wfThumbError(400, 'The specified thumbnail parameters are not recognized.'); return; } // Check the source file storage path if (!$img->exists()) { $redirectedLocation = false; if (!$isTemp) { // Check for file redirect // Since redirects are associated with pages, not versions of files, // we look for the most current version to see if its a redirect. $possRedirFile = RepoGroup::singleton()->getLocalRepo()->findFile($img->getName()); if ($possRedirFile && !is_null($possRedirFile->getRedirected())) { $redirTarget = $possRedirFile->getName(); $targetFile = wfLocalFile(Title::makeTitleSafe(NS_FILE, $redirTarget)); if ($targetFile->exists()) { $newThumbName = $targetFile->thumbName($params); if ($isOld) { $newThumbUrl = $targetFile->getArchiveThumbUrl($bits[0] . '!' . $targetFile->getName(), $newThumbName); } else { $newThumbUrl = $targetFile->getThumbUrl($newThumbName); } $redirectedLocation = wfExpandUrl($newThumbUrl, PROTO_CURRENT); } } } if ($redirectedLocation) { // File has been moved. Give redirect. $response = RequestContext::getMain()->getRequest()->response(); $response->header("HTTP/1.1 302 " . HttpStatus::getMessage(302)); $response->header('Location: ' . $redirectedLocation); $response->header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 12 * 3600) . ' GMT'); if ($wgVaryOnXFP) { $varyHeader[] = 'X-Forwarded-Proto'; } if (count($varyHeader)) { $response->header('Vary: ' . implode(', ', $varyHeader)); } return; } // If its not a redirect that has a target as a local file, give 404. wfThumbErrorText(404, "The source file '{$fileName}' does not exist."); return; } elseif ($img->getPath() === false) { wfThumbErrorText(500, "The source file '{$fileName}' is not locally accessible."); return; } // Check IMS against the source file // This means that clients can keep a cached copy even after it has been deleted on the server if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { // Fix IE brokenness $imsString = preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]); // Calculate time wfSuppressWarnings(); $imsUnix = strtotime($imsString); wfRestoreWarnings(); if (wfTimestamp(TS_UNIX, $img->getTimestamp()) <= $imsUnix) { header('HTTP/1.1 304 Not Modified'); return; } } $rel404 = isset($params['rel404']) ? $params['rel404'] : null; unset($params['r']); // ignore 'r' because we unconditionally pass File::RENDER unset($params['f']); // We're done with 'f' parameter. unset($params['rel404']); // moved to $rel404 // Get the normalized thumbnail name from the parameters... try { $thumbName = $img->thumbName($params); if (!strlen($thumbName)) { // invalid params? throw new MediaTransformInvalidParametersException('Empty return from File::thumbName'); } $thumbName2 = $img->thumbName($params, File::THUMB_FULL_NAME); // b/c; "long" style } catch (MediaTransformInvalidParametersException $e) { wfThumbError(400, 'The specified thumbnail parameters are not valid: ' . $e->getMessage()); return; } catch (MWException $e) { wfThumbError(500, $e->getHTML()); return; } // For 404 handled thumbnails, we only use the base name of the URI // for the thumb params and the parent directory for the source file name. // Check that the zone relative path matches up so squid caches won't pick // up thumbs that would not be purged on source file deletion (bug 34231). if ($rel404 !== null) { // thumbnail was handled via 404 if (rawurldecode($rel404) === $img->getThumbRel($thumbName)) { // Request for the canonical thumbnail name } elseif (rawurldecode($rel404) === $img->getThumbRel($thumbName2)) { // Request for the "long" thumbnail name; redirect to canonical name $response = RequestContext::getMain()->getRequest()->response(); $response->header("HTTP/1.1 301 " . HttpStatus::getMessage(301)); $response->header('Location: ' . wfExpandUrl($img->getThumbUrl($thumbName), PROTO_CURRENT)); $response->header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 7 * 86400) . ' GMT'); if ($wgVaryOnXFP) { $varyHeader[] = 'X-Forwarded-Proto'; } if (count($varyHeader)) { $response->header('Vary: ' . implode(', ', $varyHeader)); } return; } else { wfThumbErrorText(404, "The given path of the specified thumbnail is incorrect;\n\t\t\t\texpected '" . $img->getThumbRel($thumbName) . "' but got '" . rawurldecode($rel404) . "'."); return; } } $dispositionType = isset($params['download']) ? 'attachment' : 'inline'; // Suggest a good name for users downloading this thumbnail $headers[] = "Content-Disposition: {$img->getThumbDisposition($thumbName, $dispositionType)}"; if (count($varyHeader)) { $headers[] = 'Vary: ' . implode(', ', $varyHeader); } // Stream the file if it exists already... $thumbPath = $img->getThumbPath($thumbName); if ($img->getRepo()->fileExists($thumbPath)) { $success = $img->getRepo()->streamFile($thumbPath, $headers); if (!$success) { wfThumbError(500, 'Could not stream the file'); } return; } $user = RequestContext::getMain()->getUser(); if (!wfThumbIsStandard($img, $params) && $user->pingLimiter('renderfile-nonstandard')) { wfThumbError(500, wfMessage('actionthrottledtext')->parse()); return; } elseif ($user->pingLimiter('renderfile')) { wfThumbError(500, wfMessage('actionthrottledtext')->parse()); return; } // Actually generate a new thumbnail list($thumb, $errorMsg) = wfGenerateThumbnail($img, $params, $thumbName, $thumbPath); /** @var MediaTransformOutput|bool $thumb */ // Check for thumbnail generation errors... $msg = wfMessage('thumbnail_error'); $errorCode = 500; if (!$thumb) { $errorMsg = $errorMsg ?: $msg->rawParams('File::transform() returned false')->escaped(); } elseif ($thumb->isError()) { $errorMsg = $thumb->getHtmlMsg(); } elseif (!$thumb->hasFile()) { $errorMsg = $msg->rawParams('No path supplied in thumbnail object')->escaped(); } elseif ($thumb->fileIsSource()) { $errorMsg = $msg->rawParams('Image was not scaled, is the requested width bigger than the source?')->escaped(); $errorCode = 400; } if ($errorMsg !== false) { wfThumbError($errorCode, $errorMsg); } else { // Stream the file if there were no errors $success = $thumb->streamFile($headers); if (!$success) { wfThumbError(500, 'Could not stream the file'); } } }
/** * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately. * * If no origin parameter is present, nothing happens. * If an origin parameter is present but doesn't match the Origin header, a 403 status code * is set and false is returned. * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS * headers are set. * http://www.w3.org/TR/cors/#resource-requests * http://www.w3.org/TR/cors/#resource-preflight-requests * * @return bool False if the caller should abort (403 case), true otherwise (all other cases) */ protected function handleCORS() { $originParam = $this->getParameter('origin'); // defaults to null if ($originParam === null) { // No origin parameter, nothing to do return true; } $request = $this->getRequest(); $response = $request->response(); // Origin: header is a space-separated list of origins, check all of them $originHeader = $request->getHeader('Origin'); if ($originHeader === false) { $origins = array(); } else { $originHeader = trim($originHeader); $origins = preg_split('/\\s+/', $originHeader); } if (!in_array($originParam, $origins)) { // origin parameter set but incorrect // Send a 403 response $message = HttpStatus::getMessage(403); $response->header("HTTP/1.1 403 {$message}", true, 403); $response->header('Cache-Control: no-cache'); echo "'origin' parameter does not match Origin header\n"; return false; } $config = $this->getConfig(); $matchOrigin = count($origins) === 1 && self::matchOrigin($originParam, $config->get('CrossSiteAJAXdomains'), $config->get('CrossSiteAJAXdomainExceptions')); if ($matchOrigin) { $requestedMethod = $request->getHeader('Access-Control-Request-Method'); $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false; if ($preflight) { // This is a CORS preflight request if ($requestedMethod !== 'POST' && $requestedMethod !== 'GET') { // If method is not a case-sensitive match, do not set any additional headers and terminate. return true; } // We allow the actual request to send the following headers $requestedHeaders = $request->getHeader('Access-Control-Request-Headers'); if ($requestedHeaders !== false) { if (!self::matchRequestedHeaders($requestedHeaders)) { return true; } $response->header('Access-Control-Allow-Headers: ' . $requestedHeaders); } // We only allow the actual request to be GET or POST $response->header('Access-Control-Allow-Methods: POST, GET'); } $response->header("Access-Control-Allow-Origin: {$originHeader}"); $response->header('Access-Control-Allow-Credentials: true'); $response->header("Timing-Allow-Origin: {$originHeader}"); # http://www.w3.org/TR/resource-timing/#timing-allow-origin if (!$preflight) { $response->header('Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'); } } $this->getOutput()->addVaryHeader('Origin'); return true; }
private function sendResponse() { $httpStatus = $this->response->getHttpStatus(); $httpContentType = $this->response->getContentType(); $charset = $this->response->getCharset(); $content = $this->response->getContent(); $httpStatusHeader = 'HTTP/1.1 ' . $httpStatus . ' '; $httpStatusHeader .= HttpStatus::getMessage($httpStatus); header($httpStatusHeader); header('Content-Type: ' . $httpContentType . ';charset=' . $charset); // Enable cors header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Origin, Accept, Authorization'); header('Access-Control-Allow-Credentials: true'); if (array_key_exists('HTTP_ORIGIN', $_SERVER)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } if ($httpStatus !== 200) { if (!$content) { $content = HttpStatus::getMessage($httpStatus); } // If content type is json, make the message json friendly if ($httpContentType === 'application/json') { echo json_encode((object) array('status' => $httpStatus, 'error' => $content)); } else { echo $httpStatus . ' ' . $content; } } else { echo $content; } ob_flush(); }
/** * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately. * * If no origin parameter is present, nothing happens. * If an origin parameter is present but doesn't match the Origin header, a 403 status code * is set and false is returned. * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS * headers are set. * * @return bool False if the caller should abort (403 case), true otherwise (all other cases) */ protected function handleCORS() { global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions; $originParam = $this->getParameter('origin'); // defaults to null if ($originParam === null) { // No origin parameter, nothing to do return true; } $request = $this->getRequest(); $response = $request->response(); // Origin: header is a space-separated list of origins, check all of them $originHeader = $request->getHeader('Origin'); if ($originHeader === false) { $origins = array(); } else { $origins = explode(' ', $originHeader); } if (!in_array($originParam, $origins)) { // origin parameter set but incorrect // Send a 403 response $message = HttpStatus::getMessage(403); $response->header("HTTP/1.1 403 {$message}", true, 403); $response->header('Cache-Control: no-cache'); echo "'origin' parameter does not match Origin header\n"; return false; } if (self::matchOrigin($originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions)) { $response->header("Access-Control-Allow-Origin: {$originParam}"); $response->header('Access-Control-Allow-Credentials: true'); $this->getOutput()->addVaryHeader('Origin'); } return true; }
<?php putenv('MW_LANG=en'); // notify MWMultiVersion include '/srv/mediawiki/w/MWVersion.php'; include getMediaWiki('includes/WebStart.php'); $code = '302'; $state = ZeroBanner\PageRenderingHooks::getState(); $redirect = $state->getLandingRedirect(); $redirect = filter_var($redirect, FILTER_VALIDATE_URL); if ($redirect === false) { $code = '500'; } $message = HttpStatus::getMessage($code); //$lastmod = gmdate( 'D, j M Y H:i:s', wfTimestamp( TS_UNIX, $wgArticle->getTouched() ) ) . ' GMT'; //header( "Last-modified: $lastmod" ); // note that the following will override any Cache-Control set earlier // in extension code called above header('Cache-Control: public, s-maxage=900, max-age=900'); header("HTTP/1.1 {$code} {$message}"); if ($redirect !== false) { header('Location: ' . $redirect); } header('Vary: X-Forwarded-Proto,X-CS,X-Subdomain,Accept-Language'); header('Content-Type: text/html; charset=utf-8');
private function sendResponse() { $httpStatus = $this->response->getHttpStatus(); $httpContentType = $this->response->getContentType(); $charset = $this->response->getCharset(); $httpStatusHeader = 'HTTP/1.1 ' . $httpStatus . ' '; $httpStatusHeader .= HttpStatus::getMessage($httpStatus); header($httpStatusHeader); header('Content-Type: ' . $httpContentType . ';charset=' . $charset); // Enable cors header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Content-Type, Origin, Accept'); header('Access-Control-Allow-Credentials: true'); if (array_key_exists('HTTP_ORIGIN', $_SERVER)) { header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } if ($httpStatus !== 200) { $str = $httpStatus . ' ' . HttpStatus::getMessage($httpStatus) . "\n"; echo $str; } echo $this->response->getContent(); ob_flush(); }