-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathECRedPress.php
More file actions
654 lines (578 loc) · 17.2 KB
/
ECRedPress.php
File metadata and controls
654 lines (578 loc) · 17.2 KB
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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
<?php
require_once __DIR__ . "/vendor/autoload.php";
require_once __DIR__ . "/ECRPException.php";
require_once __DIR__ . "/ECRPLogger.php";
/**
* Class ECRedPress
* @author Raphael Titsworth-Morin
* @see https://github.com/markhilton/redis-http-cache
* @see https://gist.github.com/JimWestergren/3053250#file-index-with-redis-php
* @see http://www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/
*
* Inspired by code and ideas from Jim Westergren, Jeedo Aquino, and Mark Hilton.
*
*/
class ECRedPress
{
/**
* @var \Predis\Client $client Is the Predis client used to interact with Redis.
*/
private $client;
/**
* @var array $custom_config The configuration overrides provided by other code.
*/
private $custom_config = [];
/**
* @var null|ECRedPress $instance The active ECRP instance.
*/
private static $instance = null;
/**
* ECRedPress constructor.
* @param $config
* @throws ECRedPressRedisParamsException
*/
private function __construct($config)
{
if ($config)
$this->custom_config = $config;
self::$instance = $this;
$this->init();
}
/**
* Return this and set config.
* @param array $custom_config
* @return $this
*/
public function set_config($custom_config)
{
if (is_array($custom_config))
$this->custom_config = array_merge($this->custom_config, $custom_config);
return $this;
}
/**
* @param $option
* @param $value
* @throws ECRedPressException
*/
public function set_config_option(string $option, $value)
{
if (!isset($option) || !isset($value)) {
throw new ECRedPressBadConfigException();
}
$this->custom_config[$option] = $value;
}
/**
* @param $option
* @return mixed
* @throws ECRedPressException
*/
public function get_config_option(string $option)
{
return $this->get_config()[$option];
}
/**
* Set expiration time for this object.
* @param int $seconds
* @throws ECRedPressException
*/
public function set_cache_expiration(int $seconds)
{
$this->set_config_option('CACHE_EXPIRATION', $seconds);
}
/**
* Return the config object.
* @return array
* @throws ECRedPressRedisParamsException
*/
public function get_config()
{
return $this->_config();
}
/**
* Gets the current EC RedPress instance or creates one.
* @param array $customConfig
* @return ECRedPress
* @throws ECRedPressRedisParamsException
*/
public static function get_ecrp($customConfig = null)
{
if (self::$instance != null) {
return self::$instance->set_config($customConfig);
} else {
return new ECRedPress($customConfig);
}
}
/**
* Initialize ECRedPress instance.
* @throws ECRedPressRedisParamsException
*/
private function init()
{
$this->init_client();
}
/**
* @param array $override
* @return array
* @throws ECRedPressRedisParamsException
*/
private function _config($override = [])
{
$redisUrl = getenv('ECRP_REDIS_URL');
$redis = $redisUrl ? parse_url($redisUrl) : [];
$config = array_merge([
'REDIS_HOST' => isset($redis['host']) ? $redis['host'] : null,
'REDIS_PORT' => isset($redis['port']) ? $redis['port'] : null,
'REDIS_PASSWORD' => isset($redis['pass']) ? $redis['pass'] : null,
'CURRENT_URL' => $this->_config_build_current_url(),
'CACHEABLE_METHODS' => $this->_config_build_cacheable_methods(),
'CACHE_EXPIRATION' => $this->_config_build_cache_expiration(),
'NOCACHE_REGEX' => $this->_config_build_nocache_regex()
], $this->custom_config, $override);
if (!$config['REDIS_HOST'] || !$config['REDIS_PORT']) {
throw new ECRedPressRedisParamsException();
}
return $config;
}
/**
* Initialize Predis client.
* @throws ECRedPressRedisParamsException
*/
private function init_client()
{
$config = [
'host' => $this->_config()['REDIS_HOST'],
'port' => $this->_config()['REDIS_PORT'],
];
if (isset($this->_config()['REDIS_PASSWORD']))
$config['password'] = $this->_config()['REDIS_PASSWORD'];
$this->client = new Predis\Client($config);
}
/**
* Check if we are logged in.
* @return bool
*/
private function is_logged_in()
{
return !!preg_match("/wordpress_logged_in/", var_export($_COOKIE, true));
}
/**
* Check if we're running from the CLI in which case, bypass the cache.
* @return bool
*/
private function is_cli()
{
return defined('WP_CLI');
}
/**
* Is the cache enabled.
* @return array|false|string
*/
public function is_cache_enabled()
{
return !!getenv('ECRP_ENABLED');
}
/**
* Check if request is a comment submission.
* @return bool
*/
private function is_comment_submission()
{
return (isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0');
}
/**
* Check if request is a comment submission.
* @return bool
*/
private function is_refresh()
{
return (isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] == 'no-cache');
}
/**
* Check if the request method is of a type we want to cache.
* @return bool
* @throws ECRedPressRedisParamsException
*/
private function is_cacheable_method()
{
return in_array($_SERVER['REQUEST_METHOD'], $this->_config()['CACHEABLE_METHODS']);
}
/**
* Checks if this url should be cached.
* @return bool
* @throws ECRedPressRedisParamsException
*/
public function is_cacheable_url()
{
$config = $this->_config();
print_r($config);
foreach ($config['NOCACHE_REGEX'] as $pattern) {
if (preg_match("/$pattern/", $config['CURRENT_URL'])) {
return false;
}
}
return true;
}
/**
* Get the base key for a given url.
* @param null $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_url_key($url = null)
{
if (!$url) {
$url = $this->_config()['CURRENT_URL'];
}
return md5($url);
}
/**
* Builds the current url for config.
* @return string
*/
private function _config_build_current_url()
{
return sprintf(
"%s://%s%s",
$this->get_protocol(),
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
);
}
/**
* Return cacheable methods to config.
* Defaults to ['GET']
* @return array
*/
private function _config_build_cacheable_methods()
{
$methods = null;
if (getenv('ECRP_CACHEABLE_METHODS')) {
$methods = array_map(function ($method) {
return trim(strtoupper($method));
}, explode(',', $methods));
}
if (defined('ECRP_CACHEABLE_METHODS')) {
$methods = ECRP_CACHEABLE_METHODS;
}
return $methods ?: ['GET'];
}
/**
* Build cache expiration time for config.
* Defaults to 900 seconds.
* @return int
*/
private function _config_build_cache_expiration()
{
$cacheExp = null;
if (getenv('ECRP_DEFAULT_EXPIRATION')) {
$cacheExp = (int)(getenv('ECRP_DEFAULT_EXPIRATION'));
}
if (defined('ECRP_DEFAULT_EXPIRATION')) {
$cacheExp = ECRP_DEFAULT_EXPIRATION;
}
return $cacheExp ?: 900;
}
/**
* Build the list of regexes defining things not to cache.
* Defaults to [
* '.*\/wp-admin\/.*',
* '.*\/wp-login\.php$',
* ]
* @return array
*/
private function _config_build_nocache_regex()
{
$regexes = [
'.*\/wp-admin\/.*',
'.*\/wp-login\.php$',
];
if (getenv('ECRP_NOCACHE_REGEX')) {
array_merge($regexes, str_split(getenv('ECRP_NOCACHE_REGEX'), "@@@"));
}
if (defined('ECRP_NOCACHE_REGEX')) {
array_merge($regexes, ECRP_NOCACHE_REGEX);
}
return $regexes;
}
/**
* Returns the protocol, either through X_FORWARDED header if set, or HTTPS.
* @return string
*/
private function get_protocol()
{
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']))
return $_SERVER['HTTP_X_FORWARDED_PROTO'];
else if(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'])
return 'https';
return 'http';
}
/**
* Return sub key for a url (status, headers, etc.)
* @param $sub
* @param null $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_cache_key($sub, $url = null)
{
return sprintf("%s-%s", $this->get_url_key($url), $sub);
}
/**
* Return cache key for the url's status.
* @param $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_status_key($url = null)
{
return $this->get_cache_key('STATUS', $url);
}
/**
* Return cache key for the url's headers.
* @param null $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_headers_key($url = null)
{
return $this->get_cache_key('HEADERS', $url);
}
/**
* Return cache key for the url's page content.
* @param null $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_page_key($url = null)
{
return $this->get_cache_key('PAGE', $url);
}
/**
* Check if we should skip the cache for:
* - NOCACHE GET var
* - Cache Control max-age=0
* @return bool
* @throws ECRedPressRedisParamsException
*/
public function should_skip_cache()
{
$nocacheSet = isset($_GET['NOCACHE']);
$skip = ($nocacheSet or $this->is_comment_submission());
$skip = ($skip or $this->is_refresh());
$skip = ($skip or !$this->is_cacheable_method());
$skip = ($skip or $this->is_logged_in());
$skip = ($skip or defined('DONOTCACHEPAGE'));
$skip = ($skip or $this->is_cli());
return $skip;
}
/**
* Check if we should delete the cache.
* @return bool
*/
private function should_delete_cache()
{
$queryDelete = ($this->is_logged_in() && (isset($_GET['ecrpd']) && $_GET['ecrpd'] == 'true'));
$delete = $queryDelete or $this->is_comment_submission();
return $delete;
}
/**
* Check if the page cache exists.
* @return int
* @throws ECRedPressRedisParamsException
* @throws ECRedPressException
*/
private function does_page_cache_exist()
{
return $this->client->exists($this->get_page_key());
}
/**
* Set Ecrp-Cache header so we know what's going on with the cache.
* @param $status
* @param string $sub
*/
private function set_ecrp_header($status, $sub = '')
{
if (headers_sent()) {
return;
}
if ($sub !== '') {
$sub = '-' . ucfirst($sub);
}
header("Ecrp-Cache$sub: $status");
}
/**
* Get the cached version of the page.
* @param null $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_page_cache($url = null)
{
return $this->client->get($this->get_page_key($url));
}
/**
* Get the cached version of the page's status.
* @param null $url
* @return string
* @throws ECRedPressRedisParamsException
*/
private function get_status_cache($url = null)
{
return $this->client->get($this->get_status_key($url));
}
/**
* Get the cached page headers.
* @param null $url
* @return mixed
* @throws ECRedPressRedisParamsException
*/
private function get_headers_cache($url = null)
{
$headerJSON = $this->client->get($this->get_headers_key($url));
return json_decode($headerJSON);
}
/**
* Get all cached data for a url.
* @param null $url
* @return array
* @throws ECRedPressRedisParamsException
* @throws ECRedPressException
*/
private function get_cache($url = null)
{
return [
'page' => $this->get_page_cache($url),
'status' => $this->get_status_cache($url),
'headers' => $this->get_headers_cache($url),
];
}
/**
* Set the cache for a page.
* @param $content
* @param array $meta
* @throws ECRedPressRedisParamsException
*/
private function set_cache($content, $meta = [])
{
$ttl = $this->_config()['CACHE_EXPIRATION'];
$ttl = $ttl === 0 ? null : $ttl;
$resolution = $ttl ? 'ex' : null;
$meta = array_merge([
'status' => 200,
'headers' => [],
'url' => $this->_config()['CURRENT_URL'],
], $meta);
$this->set_ecrp_header(date(DateTime::ISO8601), 'Generated');
if ($resolution === null) {
$this->set_ecrp_header("Never", "expires");
$this->client->set($this->get_page_key($meta['url']), $content);
$this->client->set($this->get_status_key($meta['url']), $meta['status']);
$this->client->set($this->get_headers_key($meta['url']), json_encode($meta['headers']));
} else {
$this->set_ecrp_header("Seconds until expiry: " . $ttl, "expires");
$this->client->set($this->get_page_key($meta['url']), $content, $resolution, $ttl);
$this->client->set($this->get_status_key($meta['url']), $meta['status'], $resolution, $ttl);
$this->client->set($this->get_headers_key($meta['url']), json_encode($meta['headers']), $resolution, $ttl);
}
}
/**
* Delete the cache for a given url.
* @param null $url
* @throws ECRedPressRedisParamsException
*/
public function delete_cache($url = null)
{
if (!$url) {
$url = $this->_config()['CURRENT_URL'];
}
$url = str_replace("?ecrpd=true&", "?", $url);
$url = str_replace("?ecrpd=true", "", $url);
$url = str_replace("&ecrpd=true", "", $url);
$this->set_ecrp_header("Deleted", "Delete");
$this->client->del([
$this->get_page_key($url),
$this->get_status_key($url),
$this->get_headers_key($url),
]);
}
/**
* Render the page for the current request from the cache.
* @throws ECRedPressRedisParamsException
* @throws ECRedPressException
*/
private function render_from_cache()
{
$cache = $this->get_cache();
http_response_code($cache['status']);
$headers = $cache['headers'];
if (is_array($headers)) {
foreach ($cache['headers'] as $header) {
header($header);
}
}
$this->set_ecrp_header('Hit');
exit($cache['page']);
}
/**
* Start the caching engine (basically begin output buffering).
* @throws ECRedPressRedisParamsException
* @throws ECRedPressException
*/
public function start_cache()
{
if (!$this->is_cache_enabled())
return;
if ($this->should_delete_cache())
$this->delete_cache();
if ($this->does_page_cache_exist() && !$this->should_skip_cache()) {
try {
$this->render_from_cache();
} catch (Exception $e) {
ECRPLogger::get_logger()->engine->error($e->getMessage());
ob_start('ECRedPress::end_buffer');
}
} else {
ob_start('ECRedPress::end_buffer');
}
}
/**
* End the output buffering for the cache.
*
* With help from https://github.com/nextend
*
* @param $buffer
* @param $phase
* @return false|string
* @throws ECRedPressRedisParamsException
*/
public static function end_buffer($buffer, $phase){
if ($phase & PHP_OUTPUT_HANDLER_FINAL || $phase & PHP_OUTPUT_HANDLER_END) {
return self::get_ecrp()->end_cache($buffer);
}
return $buffer;
}
/**
* Complete output buffering and save the output to the cache.
* @param $html
* @return null
* @throws ECRedPressRedisParamsException
*/
public function end_cache($html)
{
if (!$this->is_cache_enabled())
return null;
if (!$this->should_skip_cache()) {
$this->set_cache($html, [
'status' => http_response_code(),
'headers' => headers_list(),
]);
} elseif ($this->should_skip_cache() && !$this->is_logged_in()) {
$this->set_cache($html, [
'status' => http_response_code(),
'headers' => headers_list(),
]);
} else
$this->set_ecrp_header("Skipped");
return $html;
}
}