-
Notifications
You must be signed in to change notification settings - Fork 231
/
Copy pathResponse.class.php
390 lines (332 loc) · 11.3 KB
/
Response.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
<?php
class Response
{
public const HEADER_STATUS = 'Status';
public const HEADER_LOCATION = 'Location';
public const HEADER_CACHE_CONTROL = 'Cache-Control';
public const HEADER_ETAG = 'Etag';
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';
protected static $metaDescription = '';
protected static $metaTitle = '';
protected static $jsCalls = [];
protected static $assets = [
'js' => [
'/js/jquery-3.4.1.min.js',
'/js/global.js'
],
'css' => ['/css/all.css']
];
protected static $headers = [
'Cache-Control' => 'private, no-cache'
];
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();
public static function setMetaDescription($description)
{
static::$metaDescription = $description;
}
public static function addMetaImage($url)
{
static::$metaImages[] = $url;
}
public static function addMetaImages(array $urls)
{
foreach ($urls as $url) {
static::addMetaImage($url);
}
}
public static function getMetaDescription()
{
return static::$metaDescription ?: 'A Content Revolution';
}
public static function getMetaImages()
{
return static::$metaImages ?: [Request::getHostAndProto() . '/img/og-image.png?_cache=' . date('Y-m-d')];
}
public static function setMetaTitle($title)
{
static::$metaTitle = $title;
}
public static function getMetaTitle()
{
return trim(static::$metaTitle);
}
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') {
return trim($title);
}
}
}
return trim($title);
}
public static function getJsCalls()
{
return static::$jsCalls;
}
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()
{
$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;
}
static::sendHeaders();
if ($sendContent) {
static::sendContent();
}
}
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');
}
echo static::$content;
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([
static::HEADER_CONTENT_TYPE => $type,
static::HEADER_CONTENT_LENGTH => $size ?: null,
static::HEADER_CONTENT_TYPE_OPTIONS => $noSniff ? 'nosniff' : null,
]));
}
//public immutable cache = hard-caching (no server checks) until time limit passes
public static function enablePublicImmutableCache(int $seconds = 300)
{
static::setHeader(static::HEADER_CACHE_CONTROL, 'public, max-age=' . $seconds);
}
//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)
{
static::setHeader(static::HEADER_CACHE_CONTROL, 'public');
static::setHeader(static::HEADER_ETAG, $etag);
}
//always reload and re-execute this resource, disable any local or intermediary caching
public static function disableHttpCache()
{
static::setHeader(static::HEADER_CACHE_CONTROL, 'private, no-cache, no-store');
}
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 = [
'Content-Security-Policy' => "frame-ancestors 'none'",
'X-Frame-Options' => 'DENY',
'X-XSS-Protection' => '1',
];
if (IS_PRODUCTION) {
$defaultHeaders['Strict-Transport-Security'] = 'max-age=31536000';
}
static::setHeaders($defaultHeaders, false);
}
public static function sendHeaders()
{
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;
}
public static function getStatusTextForCode($code)
{
$statusTexts = [
'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',
];
return $statusTexts[$code] ?? null;
}
public static function setFacebookPixelAnalyticsType($type)
{
static::$facebookAnalyticsType = $type;
}
public static function getFacebookPixelAnalyticsType()
{
return static::$facebookAnalyticsType;
}
protected static function normalizeHeaderName($name): string
{
return preg_replace_callback(
'/\-(.)/',
function ($matches) {
return '-' . strtoupper($matches[1]);
},
strtr(ucfirst(strtolower($name)), '_', '-')
);
}
public static function addPostRenderCallback($cb)
{
array_push(static::$PostRenderCallbacks, $cb);
}
public static function invokePostRenderCallbacks()
{
foreach (static::$PostRenderCallbacks as &$cb) {
$cb();
}
}
// public static function addBodyCssClass($classOrClasses)
// {
// static::$bodyCssClasses = array_unique(array_merge(static::$bodyCssClasses, (array)$classOrClasses));
// }
//
// public static function getBodyCssClasses()
// {
// return static::$bodyCssClasses;
// }
}