Files

390 lines
11 KiB
PHP
Raw Permalink Normal View History

<?php
2016-09-01 18:48:05 -04:00
class Response
{
2021-05-14 20:10:54 +08:00
public const HEADER_STATUS = 'Status';
public const HEADER_LOCATION = 'Location';
2016-09-01 18:48:05 -04:00
2021-05-14 20:10:54 +08:00
public const HEADER_CACHE_CONTROL = 'Cache-Control';
public const HEADER_ETAG = 'Etag';
2016-09-01 18:48:05 -04:00
2021-05-14 20:10:54 +08:00
public const HEADER_CONTENT_TYPE = 'Content-Type';
public const HEADER_CONTENT_LENGTH = 'Content-Length';
public const HEADER_CONTENT_DISPOSITION = 'Content-Disposition';
public const HEADER_CONTENT_TYPE_OPTIONS = 'X-Content-Type-Options';
public const HEADER_CONTENT_ENCODING = 'Content-Encoding';
public const HEADER_CROSS_ORIGIN = 'Access-Control-Allow-Origin';
2016-09-01 18:48:05 -04:00
2018-05-21 11:49:15 -04:00
protected static $metaDescription = '';
protected static $metaTitle = '';
protected static $jsCalls = [];
protected static $assets = [
2016-09-01 18:48:05 -04:00
'js' => [
2019-05-02 21:32:12 +07:00
'/js/jquery-3.4.1.min.js',
2016-09-01 18:48:05 -04:00
'/js/global.js'
],
2018-02-08 22:34:17 -05:00
'css' => ['/css/all.css']
2018-05-21 11:49:15 -04:00
];
2019-09-22 10:06:46 -04:00
protected static $headers = [
'Cache-Control' => 'private, no-cache'
];
2018-05-21 11:49:15 -04:00
protected static $headersSent = false;
protected static $content = '';
protected static $contentSent = false;
protected static $gzipResponseContent = true;
protected static $metaImages = [];
protected static $facebookAnalyticsType = "PageView";
private static $PostRenderCallbacks = array();
2018-05-21 11:49:15 -04:00
public static function setMetaDescription($description)
2016-07-04 13:07:27 -04:00
{
2018-05-21 11:49:15 -04:00
static::$metaDescription = $description;
2016-07-04 13:07:27 -04:00
}
2018-05-21 11:49:15 -04:00
public static function addMetaImage($url)
{
2018-05-21 11:49:15 -04:00
static::$metaImages[] = $url;
}
public static function addMetaImages(array $urls)
{
foreach ($urls as $url) {
static::addMetaImage($url);
}
}
2018-05-21 11:49:15 -04:00
public static function getMetaDescription()
{
2018-05-21 11:49:15 -04:00
return static::$metaDescription ?: 'A Content Revolution';
}
2018-05-21 11:49:15 -04:00
public static function getMetaImages()
2016-09-01 18:48:05 -04:00
{
2019-11-05 14:44:16 -05:00
return static::$metaImages ?: [Request::getHostAndProto() . '/img/og-image.png?_cache=' . date('Y-m-d')];
2016-09-01 18:48:05 -04:00
}
2018-05-21 11:49:15 -04:00
public static function setMetaTitle($title)
2016-09-01 18:48:05 -04:00
{
2018-05-21 11:49:15 -04:00
static::$metaTitle = $title;
2016-09-01 18:48:05 -04:00
}
2018-05-21 11:49:15 -04:00
public static function getMetaTitle()
{
2019-09-19 12:48:37 -04:00
return trim(static::$metaTitle);
2018-05-21 11:49:15 -04:00
}
2016-09-01 18:48:05 -04:00
2018-05-21 11:49:15 -04:00
public static function guessMetaTitle($content)
{
$title = '';
preg_match_all('/<h(1|2)[^>]*>([^<]+)</', $content, $titleMatches);
foreach ($titleMatches[1] as $matchIndex => $headerValue) {
if ($headerValue == '1' || !$title) {
$title = $titleMatches[2][$matchIndex];
if ($headerValue == '1') {
2019-09-19 12:48:37 -04:00
return trim($title);
2018-05-21 11:49:15 -04:00
}
}
}
2019-09-19 12:48:37 -04:00
return trim($title);
2018-05-21 11:49:15 -04:00
}
2016-09-01 18:48:05 -04:00
2018-05-21 11:49:15 -04:00
public static function getJsCalls()
{
return static::$jsCalls;
}
2016-11-25 16:06:58 -05:00
2018-05-21 11:49:15 -04:00
public static function jsOutputCallback($js)
{
static::$jsCalls[] = $js;
return '';
}
public static function addJsAsset($src)
{
static::$assets['js'][$src] = $src;
}
public static function addCssAsset($src)
{
static::$assets['css'][$src] = $src;
}
public static function getJsAssets()
{
return static::$assets['js'];
}
public static function getCssAssets()
{
return static::$assets['css'];
}
public static function setCssAssets(array $assets = [])
{
static::$assets['css'] = $assets;
}
public static function setGzipResponseContent($gzip = true)
{
static::$gzipResponseContent = $gzip;
}
public static function gzipContentIfNotDisabled()
{
if (static::$gzipResponseContent) {
$content = static::getContent();
if (strlen($content) > 256) { // not worth it for really short content
$compressed = gzencode($content, 1);
static::setContent($compressed);
static::setHeader(static::HEADER_CONTENT_LENGTH, strlen($compressed));
static::setHeader(static::HEADER_CONTENT_ENCODING, 'gzip');
}
}
}
public static function send()
{
2019-09-23 17:13:54 -04:00
$status = static::getHeader(static::HEADER_STATUS);
$sendContent = true;
if ((!$status || $status === 200) &&
static::getHeader(static::HEADER_ETAG) &&
Request::getHttpHeader('If-None-Match', null) === static::getHeader(static::HEADER_ETAG)
) {
static::setHeader(static::HEADER_STATUS, 304);
$sendContent = false;
}
2018-05-21 11:49:15 -04:00
static::sendHeaders();
2019-09-23 17:13:54 -04:00
if ($sendContent) {
static::sendContent();
}
2018-05-21 11:49:15 -04:00
}
public static function setContent(string $content)
{
static::$content = $content;
}
public static function getContent(): string
{
return static::$content;
}
public static function sendContent()
{
if (static::$contentSent) {
throw new LogicException('Content has already been sent. It cannot be sent twice');
}
2019-09-23 17:13:54 -04:00
echo static::$content;
2018-05-21 11:49:15 -04:00
static::$contentSent = true;
}
public static function setDownloadHttpHeaders($name, $type = null, $size = null, $noSniff = true)
{
static::setBinaryHttpHeaders($type, $size, $noSniff);
static::setHeader('Content-Disposition', 'attachment;filename=' . $name);
}
public static function setBinaryHttpHeaders($type, $size = null, $noSniff = true)
{
static::setGzipResponseContent(false); // in case its already compressed
static::setHeaders(array_filter([
2016-11-25 16:06:58 -05:00
static::HEADER_CONTENT_TYPE => $type,
static::HEADER_CONTENT_LENGTH => $size ?: null,
static::HEADER_CONTENT_TYPE_OPTIONS => $noSniff ? 'nosniff' : null,
2016-09-01 18:48:05 -04:00
]));
}
2019-09-22 10:06:46 -04:00
//public immutable cache = hard-caching (no server checks) until time limit passes
public static function enablePublicImmutableCache(int $seconds = 300)
2018-05-21 11:49:15 -04:00
{
2019-09-23 17:13:54 -04:00
static::setHeader(static::HEADER_CACHE_CONTROL, 'public, max-age=' . $seconds);
2018-05-21 11:49:15 -04:00
}
2016-09-01 18:48:05 -04:00
2019-09-22 10:06:46 -04:00
//public mutable cache = soft-caching (requires at least one round trip for headers) as long as etag identifier matches
public static function enablePublicMutableCache(string $etag)
2018-05-21 11:49:15 -04:00
{
2019-09-23 17:13:54 -04:00
static::setHeader(static::HEADER_CACHE_CONTROL, 'public');
static::setHeader(static::HEADER_ETAG, $etag);
2019-09-22 10:06:46 -04:00
}
2016-09-01 18:48:05 -04:00
2019-09-22 10:06:46 -04:00
//always reload and re-execute this resource, disable any local or intermediary caching
public static function disableHttpCache()
{
2019-09-23 17:13:54 -04:00
static::setHeader(static::HEADER_CACHE_CONTROL, 'private, no-cache, no-store');
2018-05-21 11:49:15 -04:00
}
public static function setHeader($name, $value)
{
static::$headers[$name] = $value;
}
public static function setHeaders($headers, $overwrite = true)
{
foreach ($headers as $name => $value) {
if ($overwrite || !static::getHeader($name)) {
static::setHeader($name, $value);
}
}
}
public static function getHeader($name, $default = null)
{
return static::$headers[$name] ?? $default;
}
public static function getHeaders(): array
{
return static::$headers;
}
public static function setStatus($status)
{
static::setHeader(static::HEADER_STATUS, $status);
}
public static function setDefaultSecurityHeaders()
{
$defaultHeaders = [
2020-09-04 13:04:00 -04:00
'Content-Security-Policy' => "frame-ancestors 'none'",
'X-Frame-Options' => 'DENY',
'X-XSS-Protection' => '1',
];
2016-09-01 18:48:05 -04:00
2018-05-21 11:49:15 -04:00
if (IS_PRODUCTION) {
$defaultHeaders['Strict-Transport-Security'] = 'max-age=31536000';
}
static::setHeaders($defaultHeaders, false);
2016-09-01 18:48:05 -04:00
}
2018-05-21 11:49:15 -04:00
public static function sendHeaders()
2016-09-01 18:48:05 -04:00
{
2018-05-21 11:49:15 -04:00
if (static::$headersSent) {
throw new LogicException('Headers have already been sent. They cannot be sent twice');
}
if (!static::getHeader(static::HEADER_CONTENT_TYPE)) {
static::setHeader(static::HEADER_CONTENT_TYPE, 'text/html');
}
$headers = static::getHeaders();
if (isset($headers[static::HEADER_STATUS])) {
$status = 'HTTP/1.0 ' . $headers[static::HEADER_STATUS] . ' ' . static::getStatusTextForCode($headers[static::HEADER_STATUS]);
header($status);
if (substr(php_sapi_name(), 0, 3) == 'cgi') {
// fastcgi servers cannot send this status information because it was sent by them already due to the HTT/1.0 line
// so we can safely unset them. see ticket #3191
unset($headers[static::HEADER_STATUS]);
}
}
foreach ($headers as $name => $value) {
header($name . ': ' . $value);
}
static::$headersSent = true;
2016-09-01 18:48:05 -04:00
}
2018-05-21 11:49:15 -04:00
public static function getStatusTextForCode($code)
2016-09-01 19:37:42 -04:00
{
2018-05-21 11:49:15 -04:00
$statusTexts = [
2016-09-01 18:48:05 -04:00
'100' => 'Continue',
'101' => 'Switching Protocols',
'200' => 'OK',
'201' => 'Created',
'202' => 'Accepted',
'203' => 'Non-Authoritative Information',
'204' => 'No Content',
'205' => 'Reset Content',
'206' => 'Partial Content',
'300' => 'Multiple Choices',
'301' => 'Moved Permanently',
'302' => 'Found',
'303' => 'See Other',
'304' => 'Not Modified',
'305' => 'Use Proxy',
'306' => '(Unused)',
'307' => 'Temporary Redirect',
'400' => 'Bad Request',
'401' => 'Unauthorized',
'402' => 'Payment Required',
'403' => 'Forbidden',
'404' => 'Not Found',
'405' => 'Method Not Allowed',
'406' => 'Not Acceptable',
'407' => 'Proxy Authentication Required',
'408' => 'Request Timeout',
'409' => 'Conflict',
'410' => 'Gone',
'411' => 'Length Required',
'412' => 'Precondition Failed',
'413' => 'Request Entity Too Large',
'414' => 'Request-URI Too Long',
'415' => 'Unsupported Media Type',
'416' => 'Requested Range Not Satisfiable',
'417' => 'Expectation Failed',
'419' => 'Authentication Timeout',
'422' => 'Unprocessable Entity',
'426' => 'Upgrade Required',
'429' => 'Too Many Requests',
'500' => 'Internal Server Error',
'501' => 'Not Implemented',
'502' => 'Bad Gateway',
'503' => 'Service Unavailable',
'504' => 'Gateway Timeout',
'505' => 'HTTP Version Not Supported',
];
2018-05-21 11:49:15 -04:00
return $statusTexts[$code] ?? null;
}
2016-09-01 18:48:05 -04:00
2018-05-21 11:49:15 -04:00
public static function setFacebookPixelAnalyticsType($type)
{
static::$facebookAnalyticsType = $type;
}
2018-03-01 10:32:59 -05:00
2018-05-21 11:49:15 -04:00
public static function getFacebookPixelAnalyticsType()
{
return static::$facebookAnalyticsType;
}
2018-03-01 10:32:59 -05:00
2018-05-21 11:49:15 -04:00
protected static function normalizeHeaderName($name): string
{
return preg_replace_callback(
2021-05-14 20:10:54 +08:00
'/\-(.)/',
function ($matches) {
2018-05-21 11:49:15 -04:00
return '-' . strtoupper($matches[1]);
},
2021-05-14 20:10:54 +08:00
strtr(ucfirst(strtolower($name)), '_', '-')
);
2018-05-21 11:49:15 -04:00
}
2016-09-01 18:48:05 -04:00
2019-04-16 10:01:43 -05:00
public static function addPostRenderCallback($cb)
{
array_push(static::$PostRenderCallbacks, $cb);
}
public static function invokePostRenderCallbacks()
{
2019-04-16 10:01:43 -05:00
foreach (static::$PostRenderCallbacks as &$cb) {
$cb();
}
}
2016-09-01 18:48:05 -04:00
2018-05-21 11:49:15 -04:00
// public static function addBodyCssClass($classOrClasses)
// {
// static::$bodyCssClasses = array_unique(array_merge(static::$bodyCssClasses, (array)$classOrClasses));
// }
//
// public static function getBodyCssClasses()
// {
// return static::$bodyCssClasses;
// }
2017-07-21 14:33:17 -04:00
}