本文整理汇总了PHP中HttpStatus::getMessage方法的典型用法代码示例。如果您正苦于以下问题:PHP HttpStatus::getMessage方法的具体用法?PHP HttpStatus::getMessage怎么用?PHP HttpStatus::getMessage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类HttpStatus
的用法示例。
在下文中一共展示了HttpStatus::getMessage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: efSlowPagesBlacklist
/**
* 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;
}
示例2: ServiceException
public function ServiceException($code, $message = NULL)
{
if ($message === NULL) {
$message = HttpStatus::getMessage($code);
}
parent::__construct($message, $code);
}
示例3: execute
/**
* 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;
}
示例4: sendError
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>';
}
示例5: getHTML
/**
* 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";
}
示例6: executeSpecialPage
/**
* @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];
}
示例7: getTextForRequestBy
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;
}
示例8: output
/**
* 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__);
}
示例9: reportHTML
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";
}
示例10: showUpload
/**
* 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;
}
示例11: wfStreamThumb
//.........这里部分代码省略.........
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__);
}
示例12: output
/**
* 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();
}
示例13: output
/**
* 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__);
}
示例14: wfStreamThumb
//.........这里部分代码省略.........
// 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;
示例15: handleCORS
/**
* 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;
}