forked from caseyrboone/wordpress-file-page-cache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
output-cache.php
560 lines (464 loc) · 17.8 KB
/
output-cache.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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
<?php
namespace O10n;
/**
* File Cache Output Controller
*
* @package optimization
* @subpackage optimization/controllers
* @author Optimization.Team <[email protected]>
*/
if (!defined('ABSPATH')) {
exit;
}
class Filecache_Output
{
// instance
protected static $instance = null;
private $config;
private $stale = false;
/**
* Construct output controller
*/
final public function __construct()
{
if (!defined('O10N_FILECACHE_ADVANCED_OUTPUT')) {
define('O10N_FILECACHE_ADVANCED_OUTPUT', true);
}
}
/**
* Serve cache
*/
final public static function load()
{
// construct controller
self::$instance = new self();
// serve output
self::$instance->output();
}
/**
* Output file cache
*/
final public function output()
{
if (
// optimization disabled
(defined('O10N_DISABLED') && O10N_DISABLED)
// file cache plugin disabled
or (defined('O10N_DISABLED_FILECACHE') && O10N_DISABLED_FILECACHE)
// bypass advanced cache (/wp-content/advanced-cache.php)
or (defined('O10N_BYPASS_ADVANCED_CACHE') && O10N_BYPASS_ADVANCED_CACHE)
// cache disabled
or (defined('O10N_NO_PAGE_CACHE') || isset($_GET['o10n-no-cache']))
) {
return false;
}
// preload request
if (isset($_SERVER['HTTP_X_O10N_FC_FORCE_UPDATE'])) {
return false;
}
// disable cache
if (is_admin() || !isset($_SERVER['REQUEST_METHOD']) || strtoupper($_SERVER['REQUEST_METHOD']) !== 'GET' || (isset($GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php')) {
return false;
}
// start of page cache output process
$start = microtime(true);
// cache directory
$cache_dir = (defined('O10N_CACHE_DIR')) ? self::trailingslashit(O10N_CACHE_DIR) . 'page-cache/' : self::trailingslashit(WP_CONTENT_DIR) . 'cache/o10n/page-cache/';
// load file cache config
$config_file = $cache_dir . 'config.php';
// get config from opcache
$this->config = $this->opcache($config_file);
if (!$this->config) {
return false;
}
// check enabled setting
if (!$this->bool('filecache.enabled')) {
return false;
}
// custom cache hash
$hash_format = false;
if ($this->bool('filecache.hash.enabled')) {
$hash_format = $this->get('filecache.hash.config');
}
// create hash
$cachehash = self::cache_hash($hash_format);
$cache_hash_dir = $cache_dir;
// lowercase
$hash = strtolower($cachehash);
// create 3 levels of 2-char subdirectories, [a-z0-9]
$dir_blocks = array_slice(str_split($hash, 2), 0, 3);
foreach ($dir_blocks as $block) {
$cache_hash_dir .= $block . '/';
}
$cache_hash_filename = substr($cachehash, 6);
$cache_file = $cache_hash_dir . $cache_hash_filename . '.php';
$cache_meta_file = $cache_file . '.meta';
// load cache meta and check if cache exists
$pagemeta = $this->opcache($cache_meta_file);
if ($pagemeta) {
// 0 = timestamp
// 1 = etag
// 2 = PHP opcache
// 3 = expire
// 4 = headers (when opcache is disabled)
// apply meta filter
$pagemeta = apply_filters('o10n_page_cache_meta', $pagemeta);
if (!$pagemeta) {
return false;
}
// expired
if (isset($pagemeta[3]) && ($pagemeta[0] + $pagemeta[3]) < time()) {
// serve stale cache while cache is updated in the background
if ($this->bool('filecache.stale.enabled')) {
$this->stale = (time() - ($pagemeta[0] + $pagemeta[3]));
$max_age = $this->get('filecache.stale.max_age');
if ($max_age && $this->stale > $max_age) {
return false;
}
} else {
return false;
}
}
// get cache from PHP Opcache
$gzipHTML = $responseHeaders = false;
if ($pagemeta[2]) {
$cachedata = $this->opcache($cache_file);
if ($cachedata) {
if (isset($cachedata[0])) {
$gzipHTML = $cachedata[0];
}
if (isset($cachedata[1])) {
$responseHeaders = $cachedata[1];
}
}
} else {
$gzipHTML = file_get_contents($cache_file);
if (isset($pagemeta[4])) {
$responseHeaders = $pagemeta[4];
}
}
// no cache data
if (!$gzipHTML) {
return false;
}
// return preload status
if (isset($_SERVER['HTTP_X_O10N_FC_PRELOAD'])) {
echo json_encode(array(
$pagemeta[0],
$this->stale
));
if ($this->stale) {
$this->mark_stale();
return;
} else {
exit;
}
}
// cached headers
$responseHeaders = apply_filters('o10n_page_cache_headers', $responseHeaders);
// skip custom expire header if the header is removed by config
$no_expire = false;
if ($responseHeaders && !empty($responseHeaders)) {
// add
if (isset($responseHeaders[0]) && !empty($responseHeaders[0])) {
foreach ($responseHeaders[0] as $key => $value) {
// set expire manually
if (isset($pagemeta[3]) && strtolower($key) === 'expires') {
continue;
}
header($key . ":" . $value);
}
}
// remove
if (isset($responseHeaders[1]) && !empty($responseHeaders[1])) {
foreach ($responseHeaders[1] as $name) {
if (strtolower($name) === 'expires') {
$no_expire = true;
}
if (function_exists('header_remove')) {
header_remove($name);
} else {
header(sprintf('%s: ', $name), true);
}
}
}
}
$utf8 = apply_filters('o10n_page_cache_utf8', true);
if ($utf8) {
header("Content-type: text/html; charset=UTF-8");
} else {
header("Content-type: text/html");
}
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $pagemeta[0])." GMT");
if (!$no_expire && isset($pagemeta[3])) {
header("Expires: ".gmdate("D, d M Y H:i:s", $pagemeta[0] + $pagemeta[3])." GMT");
}
header("Etag: " . $pagemeta[1]);
header('Vary: Accept-Encoding');
// verify 304 status
if (function_exists('apache_request_headers')) {
$request = apache_request_headers();
$modified = (isset($request[ 'If-Modified-Since' ])) ? $request[ 'If-Modified-Since' ] : null;
} else {
if (isset($_SERVER[ 'HTTP_IF_MODIFIED_SINCE' ])) {
$modified = $_SERVER[ 'HTTP_IF_MODIFIED_SINCE' ];
} else {
$modified = null;
}
}
$last_modified = gmdate("D, d M Y H:i:s", $pagemeta[0]).' GMT';
if (
($modified && $modified == $last_modified)
|| (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $pagemeta[1])
) {
header("HTTP/1.1 304 Not Modified");
exit;
}
// detect gzip support
if (!isset($_SERVER[ 'HTTP_ACCEPT_ENCODING' ]) || (isset($_SERVER[ 'HTTP_ACCEPT_ENCODING' ]) && strpos($_SERVER[ 'HTTP_ACCEPT_ENCODING' ], 'gzip') === false)) {
// uncompress for browsers that do not support GZIP
$gzipHTML = gzdecode($gzipHTML);
} else {
// disable PHP output compression
ini_set("zlib.output_compression", "Off");
// set gzip output header
header('Content-Encoding: gzip');
}
// add performance timing header
$end = microtime(true);
header('X-O10n-Cache: ' . number_format((($end - $start) * 1000), 5).'ms');
// display opcache status
if (defined('O10N_DEBUG') && O10N_DEBUG) {
if ($pagemeta[2] && function_exists('opcache_is_script_cached')) {
header('X-O10n-Opcache: ' . (opcache_is_script_cached($cache_file) ? 'Yes' : 'Not in cache'));
} else {
header('X-O10n-Opcache: Disabled');
}
}
// add stale cache header
if ($this->stale) {
header('X-O10n-Cache-Stale: ' . $this->stale.'s');
}
header('Content-Length: ' . (function_exists('mb_strlen') ? mb_strlen($gzipHTML, '8bit') : strlen($gzipHTML)));
// output cached HTML
echo $gzipHTML;
if (!$this->stale) {
exit;
} else {
$this->mark_stale();
}
}
}
/**
* Mark stale cache output
*/
final private function mark_stale()
{
// mark stale cache (trigger background update)
define('O10N_FILECACHE_SERVED_STALE', true);
// avoid abortion of PHP process
ignore_user_abort(true);
if (function_exists('session_id') && session_id()) {
session_write_close();
}
// PHP running under FastCGI
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
} else {
if (!headers_sent()) {
header("Connection: close");
}
// flush output
while (ob_get_level()) {
ob_end_flush();
}
flush();
}
// capture output
ob_start();
}
/**
* Get option from config
*
* @param string $key Option key.
* @param string $Default Default value for non existing options.
* @return mixed Option data.
*/
final public function get($key = false, $default = null)
{
// multi query
if (substr($key, -2) === '.*') {
$parent_key = substr($key, 0, -2);
$keys = preg_grep('/'.preg_quote($parent_key).'\..*/', array_keys($this->config));
$result = array();
foreach ($keys as $key) {
if (isset($this->config[$key])) {
$result[str_replace($parent_key.'.', '', $key)] = $this->config[$key];
}
}
return $result;
}
if (isset($this->config[$key])) {
return $this->config[$key];
}
if (!is_null($default)) {
return $default;
}
return;
}
/**
* Get boolean option from config
*
* @param string $key Option key.
* @param string $Default Default value for non existing options.
* @return boolean True/false
*/
final public function bool($keys, $default = false)
{
if (!is_array($keys)) {
$keys = array($keys);
$single = true;
} else {
$single = false;
}
foreach ($keys as $key) {
if (isset($this->config[$key]) && is_bool($this->config[$key])) {
if ($single || $this->config[$key]) {
return $this->config[$key];
}
} elseif (substr($key, -8) !== '.enabled') {
$value = $this->bool($key . '.enabled');
if ($single && is_bool($value)) {
return $value;
} elseif ($value) {
return true;
}
}
}
return $default;
}
/**
* Load PHP Opcache file
*/
final private function opcache($file)
{
// get config from opcache
try {
// do not use file_exists to enable zero file IO (full memory) page cache
$data = @include $file;
} catch (\Exception $err) {
return false;
}
return $data;
}
/**
* Faster trailingslashit
*
* @link https://codex.wordpress.org/Function_Reference/trailingslashit
*
* @param string $path The path to add a trailing slash.
*/
final public static function trailingslashit($path, $separator = DIRECTORY_SEPARATOR)
{
return (substr($path, -1) === $separator) ? $path : $path . $separator;
}
/**
* Calculate cache hash
*
* @param array $hash_format Custom hash format configuration
*/
final public static function cache_hash($hash_format = false, $request_url = false)
{
// load cache hash methods
if ($hash_format && !defined('O10N_CACHE_HASH_METHODS_LOADED')) {
require_once(self::trailingslashit(__DIR__) . 'includes/cache_hash.inc.php');
}
if (!$request_url) {
// environment variables
$ssl = (! empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on');
$sp = strtolower($_SERVER['SERVER_PROTOCOL']);
$protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
$port = $_SERVER['SERVER_PORT'];
$port = ((! $ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':'.$port;
// host name
$use_forwarded_host = apply_filters('o10n_pagecache_use_forwarded_host', false);
$hostname = ($use_forwarded_host && isset($_SERVER['HTTP_X_FORWARDED_HOST'])) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : null);
$hostname = isset($hostname) ? $hostname : $_SERVER['SERVER_NAME'];
$host = $hostname . $port;
// request URL
$request_uri = $_SERVER['REQUEST_URI'];
$request_url = $protocol . '://' . $host . (($port) ? $port : '') . $request_uri;
}
$parsed = parse_url($request_url);
$ssl = (isset($parsed['scheme']) && $parsed['scheme'] == 'https');
if (isset($parsed['port'])) {
$port = ((! $ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':'.$port;
} else {
$port = '';
}
$protocol = (isset($parsed['scheme'])) ? $parsed['scheme'] : '';
$hostname = (isset($parsed['host'])) ? $parsed['host'] : '';
$host = $hostname . $port;
$request_uri = (isset($parsed['path']) ? $parsed['path'] : '') . (isset($parsed['query']) ? '?' . $parsed['query'] : '');
$request_url = $protocol . '://' . $host . (($port) ? $port : '') . $request_uri;
if (!$hash_format || empty($hash_format)) {
$hash_format = array('request_url');
}
// construct cache hash
$cache_hash_components = array();
foreach ($hash_format as $component) {
if (is_string($component)) {
switch ($component) {
case "ssl":
case "protocol":
case "port":
case "hostname":
case "host":
case "request_uri":
case "request_url":
$cache_hash_components[] = $$component;
break;
}
} elseif (is_array($component) && isset($component['method'])) {
if (strpos($component['method'], 'page_cache_') === 0) {
$method = 'O10n\page_cache_hash_no_query_string';
if (function_exists($method)) {
$component['method'] = $method;
// always add URL as first argument
if (!isset($component['attributes']) || !is_array($component['attributes'])) {
$component['attributes'] = array();
}
array_unshift($component['attributes'], $request_url);
}
}
if (function_exists($component['method']) && is_callable($component['method'])) {
$method = $component['method'];
$arguments = (isset($component['attributes'])) ? $component['attributes'] : null;
// call method
if ($arguments === null) {
$result = call_user_func($method);
} else {
$result = call_user_func_array($method, $arguments);
}
if (is_string($result) || is_numeric($result)) {
$cache_hash_components[] = (string)$result;
} else {
$cache_hash_components[] = json_encode($result);
}
}
}
}
return md5(implode(':', $cache_hash_components));
}
/**
* Serve cache
*/
final public static function serve()
{
self::$instance->output();
}
}
// output cache
if (!is_admin()) {
Filecache_Output::load();
}