public static function createCheckoutRequest(Credentials $credentials, PaymentRequest $paymentRequest) { LogPagSeguro::info("PaymentService.Register(" . $paymentRequest->toString() . ") - begin"); $connectionData = new PagSeguroConnectionData($credentials, self::serviceName); try { $connection = new HttpConnection(); $connection->post(self::buildCheckoutRequestUrl($connectionData), PaymentParser::getData($paymentRequest), $connectionData->getServiceTimeout(), $connectionData->getCharset()); $httpStatus = new HttpStatus($connection->getStatus()); switch ($httpStatus->getType()) { case 'OK': $PaymentParserData = PaymentParser::readSuccessXml($connection->getResponse()); $paymentUrl = self::buildCheckoutUrl($connectionData, $PaymentParserData->getCode()); LogPagSeguro::info("PaymentService.Register(" . $paymentRequest->toString() . ") - end {1}" . $PaymentParserData->getCode()); break; case 'BAD_REQUEST': $errors = PaymentParser::readErrors($connection->getResponse()); $e = new PagSeguroServiceException($httpStatus, $errors); LogPagSeguro::error("PaymentService.Register(" . $paymentRequest->toString() . ") - error " . $e->getOneLineMessage()); throw $e; break; default: $e = new PagSeguroServiceException($httpStatus); LogPagSeguro::error("PaymentService.Register(" . $paymentRequest->toString() . ") - error " . $e->getOneLineMessage()); throw $e; break; } return isset($paymentUrl) ? $paymentUrl : false; } catch (PagSeguroServiceException $e) { throw $e; } catch (Exception $e) { LogPagSeguro::error("Exception: " . $e->getMessage()); throw $e; } }
/** * Returns a transaction from a notification code * * @param Credentials $credentials * @param String $notificationCode * @throws PagSeguroServiceException * @throws Exception * @return a transaction * @see Transaction */ public static function checkTransaction(Credentials $credentials, $notificationCode) { LogPagSeguro::info("NotificationService.CheckTransaction(notificationCode={$notificationCode}) - begin"); $connectionData = new PagSeguroConnectionData($credentials, self::serviceName); try { $connection = new HttpConnection(); $connection->get(self::buildTransactionNotificationUrl($connectionData, $notificationCode), $connectionData->getServiceTimeout(), $connectionData->getCharset()); $httpStatus = new HttpStatus($connection->getStatus()); switch ($httpStatus->getType()) { case 'OK': // parses the transaction $transaction = TransactionParser::readTransaction($connection->getResponse()); LogPagSeguro::info("NotificationService.CheckTransaction(notificationCode={$notificationCode}) - end " . $transaction->toString() . ")"); break; case 'BAD_REQUEST': $errors = TransactionParser::readErrors($connection->getResponse()); $e = new PagSeguroServiceException($httpStatus, $errors); LogPagSeguro::info("NotificationService.CheckTransaction(notificationCode={$notificationCode}) - error " . $e->getOneLineMessage()); throw $e; break; default: $e = new PagSeguroServiceException($httpStatus); LogPagSeguro::info("NotificationService.CheckTransaction(notificationCode={$notificationCode}) - error " . $e->getOneLineMessage()); throw $e; break; } return isset($transaction) ? $transaction : null; } catch (PagSeguroServiceException $e) { throw $e; } catch (Exception $e) { LogPagSeguro::error("Exception: " . $e->getMessage()); throw $e; } }
/** * 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; }
/** * 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 ServiceException($code, $message = NULL) { if ($message === NULL) { $message = HttpStatus::getMessage($code); } parent::__construct($message, $code); }
public function execute($par = '') { $this->getOutput()->disable(); if (wfReadOnly()) { // HTTP 423 Locked HttpStatus::header(423); print 'Wiki is in read-only mode'; return; } elseif (!$this->getRequest()->wasPosted()) { HttpStatus::header(400); print 'Request must be POSTed'; return; } $optional = array('maxjobs' => 0, 'maxtime' => 30, 'type' => false, 'async' => true); $required = array_flip(array('title', 'tasks', 'signature', 'sigexpiry')); $params = array_intersect_key($this->getRequest()->getValues(), $required + $optional); $missing = array_diff_key($required, $params); if (count($missing)) { HttpStatus::header(400); print 'Missing parameters: ' . implode(', ', array_keys($missing)); return; } $squery = $params; unset($squery['signature']); $correctSignature = self::getQuerySignature($squery, $this->getConfig()->get('SecretKey')); $providedSignature = $params['signature']; $verified = is_string($providedSignature) && hash_equals($correctSignature, $providedSignature); if (!$verified || $params['sigexpiry'] < time()) { HttpStatus::header(400); print 'Invalid or stale signature provided'; return; } // Apply any default parameter values $params += $optional; if ($params['async']) { // Client will usually disconnect before checking the response, // but it needs to know when it is safe to disconnect. Until this // reaches ignore_user_abort(), it is not safe as the jobs won't run. ignore_user_abort(true); // jobs may take a bit of time // HTTP 202 Accepted HttpStatus::header(202); ob_flush(); flush(); // Once the client receives this response, it can disconnect } // Do all of the specified tasks... if (in_array('jobs', explode('|', $params['tasks']))) { $runner = new JobRunner(LoggerFactory::getInstance('runJobs')); $response = $runner->run(array('type' => $params['type'], 'maxJobs' => $params['maxjobs'] ? $params['maxjobs'] : 1, 'maxTime' => $params['maxtime'] ? $params['maxjobs'] : 30)); if (!$params['async']) { print FormatJson::encode($response, true); } } }
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; }
/** * Output a thumbnail generation error message * * @param int $status * @param string $msgHtml HTML * @return void */ function wfThumbError($status, $msgHtml) { global $wgShowHostnames; header('Cache-Control: no-cache'); header('Content-Type: text/html; charset=utf-8'); if ($status == 400 || $status == 404 || $status == 429) { HttpStatus::header($status); } elseif ($status == 403) { HttpStatus::header(403); header('Vary: Cookie'); } else { HttpStatus::header(500); } if ($wgShowHostnames) { header('X-MW-Thumbnail-Renderer: ' . wfHostname()); $url = htmlspecialchars(isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''); $hostname = htmlspecialchars(wfHostname()); $debug = "<!-- {$url} -->\n<!-- {$hostname} -->\n"; } else { $debug = ''; } $content = <<<EOT <!DOCTYPE html> <html><head> <meta charset="UTF-8" /> <title>Error generating thumbnail</title> </head> <body> <h1>Error generating thumbnail</h1> <p> {$msgHtml} </p> {$debug} </body> </html> EOT; header('Content-Length: ' . strlen($content)); echo $content; }
/** * 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__); }
/** * Provide a simple HTTP error. * * @param int|string $code * @param string $label * @param string $desc */ function wfHttpError($code, $label, $desc) { global $wgOut; HttpStatus::header($code); if ($wgOut) { $wgOut->disable(); $wgOut->sendCacheControl(); } header('Content-type: text/html; charset=utf-8'); print '<!DOCTYPE html>' . '<html><head><title>' . htmlspecialchars($label) . '</title></head><body><h1>' . htmlspecialchars($label) . '</h1><p>' . nl2br(htmlspecialchars($desc)) . "</p></body></html>\n"; }
/** * 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__); }
/** * 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; }
/** * Issue a standard HTTP 403 Forbidden header ($msg1-a message index, not a message) and an * error message ($msg2, also a message index), (both required) then end the script * subsequent arguments to $msg2 will be passed as parameters only for replacing in $msg2 * @param string $msg1 * @param string $msg2 */ function wfForbidden($msg1, $msg2) { global $wgImgAuthDetails; $args = func_get_args(); array_shift($args); array_shift($args); $args = isset($args[0]) && is_array($args[0]) ? $args[0] : $args; $msgHdr = wfMessage($msg1)->escaped(); $detailMsgKey = $wgImgAuthDetails ? $msg2 : 'badaccess-group0'; $detailMsg = wfMessage($detailMsgKey, $args)->escaped(); wfDebugLog('img_auth', "wfForbidden Hdr: " . wfMessage($msg1)->inLanguage('en')->text() . " Msg: " . wfMessage($msg2, $args)->inLanguage('en')->text()); HttpStatus::header(403); header('Cache-Control: no-cache'); header('Content-Type: text/html; charset=utf-8'); echo <<<ENDS <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>{$msgHdr}</title> </head> <body> <h1>{$msgHdr}</h1> <p>{$detailMsg}</p> </body> </html> ENDS; }
/** * Construct the header and output it */ function sendHeaders() { if ($this->mResponseCode) { // For back-compat, it is supported that mResponseCode be a string like " 200 OK" // (with leading space and the status message after). Cast response code to an integer // to take advantage of PHP's conversion rules which will turn " 200 OK" into 200. // http://php.net/string#language.types.string.conversion $n = intval(trim($this->mResponseCode)); HttpStatus::header($n); } header("Content-Type: " . $this->mContentType); if ($this->mLastModified) { header("Last-Modified: " . $this->mLastModified); } else { header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); } if ($this->mCacheDuration) { # If CDN caches are configured, tell them to cache the response, # and tell the client to always check with the CDN. Otherwise, # tell the client to use a cached copy, without a way to purge it. if ($this->mConfig->get('UseSquid')) { # Expect explicit purge of the proxy cache, but require end user agents # to revalidate against the proxy on each visit. # Surrogate-Control controls our CDN, Cache-Control downstream caches if ($this->mConfig->get('UseESI')) { header('Surrogate-Control: max-age=' . $this->mCacheDuration . ', content="ESI/1.0"'); header('Cache-Control: s-maxage=0, must-revalidate, max-age=0'); } else { header('Cache-Control: s-maxage=' . $this->mCacheDuration . ', must-revalidate, max-age=0'); } } else { # Let the client do the caching. Cache is not purged. header("Expires: " . gmdate("D, d M Y H:i:s", time() + $this->mCacheDuration) . " GMT"); header("Cache-Control: s-maxage={$this->mCacheDuration}," . "public,max-age={$this->mCacheDuration}"); } } else { # always expired, always modified header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Pragma: no-cache"); // HTTP/1.0 } if ($this->mVary) { header("Vary: " . $this->mVary); } }
# big mess. if (ob_get_level() == 0) { require_once "{$IP}/includes/OutputHandler.php"; ob_start('wfOutputHandler'); } if (!defined('MW_NO_SETUP')) { require_once "{$IP}/includes/Setup.php"; } # Multiple DBs or commits might be used; keep the request as transactional as possible if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') { ignore_user_abort(true); } if (!defined('MW_API') && RequestContext::getMain()->getRequest()->getHeader('Promise-Non-Write-API-Action')) { header('Cache-Control: no-cache'); header('Content-Type: text/html; charset=utf-8'); HttpStatus::header(400); $error = wfMessage('nonwrite-api-promise-error')->escaped(); $content = <<<EOT <!DOCTYPE html> <html> <head><meta charset="UTF-8" /></head> <body> {$error} </body> </html> EOT; header('Content-Length: ' . strlen($content)); echo $content; die; }
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; }
/** * 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; }
/** * Call this function used in preparation before streaming a file. * This function does the following: * (a) sends Last-Modified, Content-type, and Content-Disposition headers * (b) cancels any PHP output buffering and automatic gzipping of output * (c) sends Content-Length header based on HTTP_IF_MODIFIED_SINCE check * * @param string $path Storage path or file system path * @param array|bool $info File stat info with 'mtime' and 'size' fields * @param array $headers Additional headers to send * @param bool $sendErrors Send error messages if errors occur (like 404) * @return int|bool READY_STREAM, NOT_MODIFIED, or false on failure */ public static function prepareForStream($path, $info, $headers = array(), $sendErrors = true) { if (!is_array($info)) { if ($sendErrors) { HttpStatus::header(404); header('Cache-Control: no-cache'); header('Content-Type: text/html; charset=utf-8'); $encFile = htmlspecialchars($path); $encScript = htmlspecialchars($_SERVER['SCRIPT_NAME']); echo "<html><body>\n\t\t\t\t\t<h1>File not found</h1>\n\t\t\t\t\t<p>Although this PHP script ({$encScript}) exists, the file requested for output\n\t\t\t\t\t({$encFile}) does not.</p>\n\t\t\t\t\t</body></html>\n\t\t\t\t\t"; } return false; } // Sent Last-Modified HTTP header for client-side caching header('Last-Modified: ' . wfTimestamp(TS_RFC2822, $info['mtime'])); // Cancel output buffering and gzipping if set wfResetOutputBuffers(); $type = self::contentTypeFromPath($path); if ($type && $type != 'unknown/unknown') { header("Content-type: {$type}"); } else { // Send a content type which is not known to Internet Explorer, to // avoid triggering IE's content type detection. Sending a standard // unknown content type here essentially gives IE license to apply // whatever content type it likes. header('Content-type: application/x-wiki'); } // Don't stream it out as text/html if there was a PHP error if (headers_sent()) { echo "Headers already sent, terminating.\n"; return false; } // Send additional headers foreach ($headers as $header) { header($header); } // Don't send if client has up to date cache if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) { $modsince = preg_replace('/;.*$/', '', $_SERVER['HTTP_IF_MODIFIED_SINCE']); if (wfTimestamp(TS_UNIX, $info['mtime']) <= strtotime($modsince)) { ini_set('zlib.output_compression', 0); HttpStatus::header(304); return self::NOT_MODIFIED; // ok } } header('Content-Length: ' . $info['size']); return self::READY_STREAM; // ok }
/** * Respond with HTTP 304 Not Modified if appropiate. * * If there's an If-None-Match header, respond with a 304 appropriately * and clear out the output buffer. If the client cache is too old then do nothing. * * @param ResourceLoaderContext $context * @param string $etag ETag header value * @return bool True if HTTP 304 was sent and output handled */ protected function tryRespondNotModified(ResourceLoaderContext $context, $etag) { // See RFC 2616 § 14.26 If-None-Match // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 $clientKeys = $context->getRequest()->getHeader('If-None-Match', WebRequest::GETHEADER_LIST); // Never send 304s in debug mode if ($clientKeys !== false && !$context->getDebug() && in_array($etag, $clientKeys)) { // There's another bug in ob_gzhandler (see also the comment at // the top of this function) that causes it to gzip even empty // responses, meaning it's impossible to produce a truly empty // response (because the gzip header is always there). This is // a problem because 304 responses have to be completely empty // per the HTTP spec, and Firefox behaves buggily when they're not. // See also http://bugs.php.net/bug.php?id=51579 // To work around this, we tear down all output buffering before // sending the 304. wfResetOutputBuffers(true); HttpStatus::header(304); $this->sendResponseHeaders($context, $etag, false); return true; } return false; }
public function _sendResponse($status = 200, $body = '', $content_type = 'text/html') { $statusMessage = HttpStatus::getStatusMessage($status); // set the status $status_header = 'HTTP/1.1 ' . $status . ' ' . $statusMessage; header($status_header); header('Content-type: ' . $content_type); // pages with body are easy if ($body != '') { // send the body echo CJSON::encode($body); exit; } else { $data = array(); $data['status'] = $status; $data['statusMessage'] = $statusMessage; // create some body messages $data['message'] = HttpStatus::getResponse($status); // servers don't always have a signature turned on // (this is an apache directive "ServerSignature On") $data['signature'] = $_SERVER['SERVER_SIGNATURE'] == '' ? $_SERVER['SERVER_SOFTWARE'] . ' Server at ' . $_SERVER['SERVER_NAME'] . ' Port ' . $_SERVER['SERVER_PORT'] : $_SERVER['SERVER_SIGNATURE']; $this->renderPartial('application.views.http._htmlResponse', array('data' => $data)); exit; } }
/** * Output an HTTP status code header * @since 1.26 * @param int $code Status code */ public function statusHeader($code) { HttpStatus::header($code); }
/** * 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__); }
/** * Handle an error. * * @param int $errorStatus Error status code * @param string $errorMsg Error message * @param string $errorFile Error script file * @param int $errorLine Error script line * @throws ApiException API exception */ public static function handle($errorStatus, $errorMsg, $errorFile, $errorLine) { // Build the complete error message $mailMsg = '<b>--- Spotzi ErrorHandler ---</b>' . PHP_EOL . PHP_EOL; $mailMsg .= 'Date: ' . Date::format() . PHP_EOL; $mailMsg .= 'Error status: ' . $errorStatus . PHP_EOL; $mailMsg .= 'Error message: ' . $errorMsg . PHP_EOL; $mailMsg .= 'Script name: ' . $errorFile . PHP_EOL; $mailMsg .= 'Line number: ' . $errorLine . PHP_EOL; //$mailMsg .= 'Request referer: ' . REQUEST_REFERER . PHP_EOL; //$mailMsg .= 'Request URL: ' . URL_BASE . ltrim(REQUEST_URI, '/') . PHP_EOL; if (isset($_SERVER['HTTP_USER_AGENT'])) { $mailMsg .= 'User agent: ' . $_SERVER['HTTP_USER_AGENT']; } // Determine whether debug mode is active if (debugMode()) { // In case debug mode is active, set the error message as the frontend message debugPrint($mailMsg); } else { // Send the error email when needed if (HttpStatus::emailStatus($errorStatus)) { // Prepare the error mailer Mail::addMailer(EMAIL_HOST, EMAIL_PORT, EMAIL_ERROR_FROM, EMAIL_ERROR_FROM_PASSWORD, BRAND_PRODUCT); // Send the error email Mail::send(EMAIL_ERROR_RECIPIENT, EMAIL_ERROR_FROM, EMAIL_ERROR_SUBJECT, nl2br($mailMsg)); } throw new ApiException($errorStatus, $errorMsg); } }
private static function statusHeader($code) { if (!headers_sent()) { HttpStatus::header($code); } }
function __construct($description = '') { parent::__construct(500, $description); }
function setStatus(HttpStatus $status) { $protocol = $this->request ? $this->request->getProtocol() : 'HTTP/1.0'; header($protocol . ' ' . $status->getValue() . ' ' . $status->getStatusMessage(), true); }