/
static-cache.php
executable file
·427 lines (359 loc) · 12.9 KB
/
static-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
<?php
/**
* static_cache
*
* @package Semiologic Cache
**/
foreach ( array(
'sem_cache_debug',
'static_cache',
'memory_cache',
) as $const ) {
if ( !defined($const) )
define($const, false);
}
// set for every 24 hours
if ( !defined('cache_timeout') )
define('cache_timeout', 86400);
if ( !defined('DONOTCACHEPAGE') )
define( 'DONOTCACHEPAGE', false );
if ( static_cache && !class_exists('cache_fs') )
include dirname(__FILE__) . '/cache-fs.php';
if ( memory_cache && !class_exists('object_cache') )
include dirname(__FILE__) . '/object-cache.php';
class static_cache {
private static $status_code = 200;
private static $status_header;
private static $static = static_cache;
private static $memory = memory_cache;
private static $nocache = false;
private static $started = false;
private static $host;
/**
* disable()
*
* @param mixed $in
* @return mixed $in
**/
static function disable($in = null) {
self::$nocache = true;
return $in;
} # disable()
/**
* status_header()
*
* @param string $status_header
* @param int $status_code
* @return string $status_header
**/
static function status_header($status_header, $status_code) {
self::$status_code = (int) $status_code;
self::$status_header = $status_header;
return $status_header;
} # status_header()
/**
* wp_redirect_status()
*
* @param int $status_code
* @return int $status_code
**/
static function wp_redirect_status($status_code) {
$text = get_status_header_desc($status_code);
$protocol = $_SERVER["SERVER_PROTOCOL"];
if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
$protocol = 'HTTP/1.0';
$status_header = "$protocol $status_code $text";
if ( function_exists('apply_filters') )
$status_header = apply_filters('status_header', $status_header, $status_code, $text, $protocol);
return $status_code;
} # wp_redirect_status()
/**
* send_headers()
*
* @param array $headers
* @return void
**/
static function send_headers($headers) {
$bail = false;
$server_etag = false;
$client_etag = !empty($_SERVER['HTTP_IF_NONE_MATCH'])
? trim(strip_tags(stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])))
: $req_etag = false;
$server_modified = false;
$client_modified = !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])
? trim($_SERVER['HTTP_IF_MODIFIED_SINCE'])
: '';
if ( $client_etag || $client_modified ) {
foreach ( $headers as $header ) {
list($k, $v) = array_merge( preg_split("/:\s*/", $header), '');
switch ( strtolower($k) ) {
case 'etag':
$server_etag = trim(strip_tags($v));
break;
case 'last-modified':
$server_modified = trim($v);
}
}
}
if ( $client_etag && $server_etag || $client_modified && $server_modified ) {
if ( $client_modified && $server_modified ) {
$client_modified = strtotime($client_modified);
$server_modified = strtotime($server_modified);
}
if ( $client_etag && $server_etag && $client_modified && $server_modified ) {
$bail = ( $client_etag == $server_etag ) && ( $client_modified >= $server_modified );
} elseif ( $client_etag && $server_etag ) {
$bail = ( $client_etag == $server_etag );
} elseif ( $client_modified && $server_modified ) {
$bail = ( $client_modified >= $server_modified );
}
}
foreach ( $headers as $header )
header($header, true);
if ( $bail ) {
$protocol = $_SERVER["SERVER_PROTOCOL"];
if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
$protocol = 'HTTP/1.0';
header("$protocol 304 Not Modified", true, 304);
die;
}
} # send_headers()
/**
* start()
*
* @return void
**/
static function start() {
# some things can be taken care of at all times
switch ( basename($_SERVER['REQUEST_URI']) ) {
case 'favicon.ico':
# bypass WP entirely on favicon.ico
$protocol = $_SERVER["SERVER_PROTOCOL"];
if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
$protocol = 'HTTP/1.0';
$headers = array(
"$protocol 404 Not Found",
'Expires: Wed, 11 Jan 1984 05:00:00 GMT',
'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT',
'Cache-Control: no-cache, must-revalidate, max-age=0',
'Pragma: no-cache',
'Content-Type: image/x-icon',
);
foreach ( $headers as $header )
header($header, true);
die;
case 'sitemap.xml':
case 'sitemap.xml.gz':
case 'sitemap_index.xml':
# let xml sitemap plugins cache themselves
return;
}
global $sem_cache_cookies;
if ( ( !defined('WP_CACHE') || !WP_CACHE )
|| isset($_GET['action']) || isset($_GET['doing_wp_cron'])
|| isset($_GET['debug']) || isset($_GET['preview'])
|| ( defined('WP_INSTALLING') && WP_INSTALLING )
|| ( defined('WP_ADMIN') && WP_ADMIN )
|| ( defined('DOING_CRON') && DOING_CRON )
|| ( defined('DOING_AJAX') && DOING_AJAX )
|| $_POST || !$sem_cache_cookies
|| array_intersect(array_keys($_COOKIE), (array) $sem_cache_cookies)
|| self::$nocache
)
return;
# kill static cache on multisite installs
self::$static &= !( function_exists('is_multisite') && is_multisite() );
if ( self::$started || headers_sent() || !self::$static && !self::$memory )
return;
if ( isset($_SERVER['HTTPS']) && ( 'on' == strtolower($_SERVER['HTTPS']) || '1' == $_SERVER['HTTPS'] ) || isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
self::$host = 'https://' . $_SERVER['HTTP_HOST'];
} else {
self::$host = 'http://' . $_SERVER['HTTP_HOST'];
}
$cache_id = self::$host . preg_replace("/#.*/", '', $_SERVER['REQUEST_URI']);
$cache_id = md5($cache_id);
if ( self::$memory ) {
$headers = wp_cache_get($cache_id, 'cached_headers');
if ( $headers !== false ) {
self::send_headers($headers);
$buffer = wp_cache_get($cache_id, 'cached_buffers');
if ( $buffer )
echo $buffer;
die;
}
} elseif ( !( function_exists('is_multisite') && is_multisite() ) ) {
# poor man's memcached
$headers = '/semi-static/' . $cache_id . '.meta';
if ( cache_fs::exists($headers, cache_timeout) ) {
$headers = unserialize(cache_fs::get_contents($headers));
self::send_headers($headers);
$buffer = '/semi-static/' . $cache_id . '.html';
if ( cache_fs::exists($buffer) )
cache_fs::readfile($buffer);
die;
}
}
self::$started = true;
ob_start(array('static_cache', 'ob_callback'));
} # start()
/**
* ob_callback()
*
* @param string $buffer
* @return string $buffer
**/
static function ob_callback($buffer) {
if ( !class_exists('sem_cache') )
return $buffer;
if ( DONOTCACHEPAGE )
return $buffer;
# some things just shouldn't be cached
if ( self::$nocache && !in_array(self::$status_code, array(301, 302, 404))
|| !in_array(self::$status_code, array(200, 301, 302, 404)) ) {
return $buffer;
}
# sanity check on cookies
global $sem_cache_cookies;
if ( !$sem_cache_cookies || $sem_cache_cookies != sem_cache::get_cookies() )
return $buffer;
# only cache visitor requests
if ( array_intersect(array_keys($_COOKIE), $sem_cache_cookies) )
return $buffer;
# bail on valid but rarely served pages
if ( self::$status_code == 200
&& !(
# post or page
!is_feed() && is_singular()
# first page of blog or category
|| !is_feed() && ( is_home() || is_category() ) && !is_paged()
# blog and category feed
|| is_feed() && ( !is_archive() && !is_singular() /* home feed */ || is_category() )
) ) {
return $buffer;
}
// let's see if this page is excluded
$exclude_pages = get_site_option( 'sem_cache_excluded_pages', '' );
if ( ! empty ( $exclude_pages ) ) {
$exclude_pages = explode( ' ', $exclude_pages );
$request_uri = $_SERVER['REQUEST_URI'];
$request_uri = parse_url( $request_uri, PHP_URL_PATH );
if ( in_array( $request_uri, $exclude_pages) )
return $buffer;
}
// and no point caching querystring requests since htaccess ignores those
/* $request_uri = $_SERVER['REQUEST_URI'];
$querystring = parse_url( $request_uri, PHP_URL_QUERY );
if ( $querystring !== NULL )
return $buffer;
*/
#don't cache a contact form page due to spam prevention techniques
// if ( preg_match("/(\bsem_contact_form\b)/i",$buffer) )
// return $buffer;
#don't cache a page due if a sem_no_cache flag is found. Provide manual way to exclude a page
if ( preg_match("/(\bsem_do_not_cache\b)/i",$buffer) )
return $buffer;
$permalink_structure = get_option('permalink_structure');
# statically cache only when relevant
self::$static &= ( strpos($_SERVER['REQUEST_URI'], './') === false )
&& ( self::$status_code == 200 )
&& !is_feed()
&& empty($_GET)
&& $permalink_structure
&& ( strpos($permalink_structure, "|/index\.php/|") === false );
# sanity check on the base folder
$host = get_option('home');
// check if we're on a dev site
if( strpos( $host, 'localhost') === false ) {
if ( preg_match( "|^([^/]+://[^/]+)/|", $host, $_host ) ) {
$host = end( $_host );
}
if ( $host != self::$host ) {
return $buffer;
}
}
# sanity check on incomplete files
if ( !in_array(self::$status_code, array(301, 302)) && !preg_match("/(?:<\/html>|<\/rss>|<\/feed>)/i",$buffer) )
return $buffer;
# sanity check on mobile users
/* global $sem_mobile_agents;
if ( $sem_mobile_agents != sem_cache::get_mobile_agents() )
return $buffer;
$mobile_agents = $sem_mobile_agents;
// $mobile_agents = array_map('preg_quote', (array) $mobile_agents);
$mobile_agents = implode("|", $mobile_agents);
if ( preg_match("{($mobile_agents)}i", $_SERVER['HTTP_USER_AGENT']) )
return $buffer;
if ( preg_match("/(?=.*?\bandroid\b)(?=.*?\bmobile\b).*$/i", $_SERVER['HTTP_USER_AGENT']) )
return $buffer;
*/
// made it through all the checks. Let's minify the html now
$buffer = self::minify_html( $buffer );
if ( self::$static ) {
$file = preg_replace("/#.*/", '', $_SERVER['REQUEST_URI']);
$file = '/static/' . trim($file, '/');
if ( !preg_match("/\.html$/", $file) ) {
global $wp_rewrite;
if ( $wp_rewrite->use_trailing_slashes )
$file = $file . '/index.html';
else
$file = $file . '.html';
}
cache_fs::put_contents($file, $buffer);
} elseif ( self::$memory ) {
$cache_id = $host . preg_replace("/#.*/", '', $_SERVER['REQUEST_URI']);
$cache_id = md5($cache_id);
$headers = headers_list();
if ( self::$status_header )
array_unshift($headers, self::$status_header);
wp_cache_add($cache_id, $headers, 'cached_headers', cache_timeout);
if ( $buffer && !in_array(self::$status_code, array(301, 302)) )
wp_cache_add($cache_id, $buffer, 'cached_buffers', cache_timeout);
} elseif ( !( function_exists('is_multisite') && is_multisite() ) ) {
# poor man's memcached
$cache_id = $host . preg_replace("/#.*/", '', $_SERVER['REQUEST_URI']);
$cache_id = md5($cache_id);
$file = '/semi-static/' . $cache_id;
$headers = headers_list();
if ( self::$status_header )
array_unshift($headers, self::$status_header);
cache_fs::put_contents($file . '.meta', serialize($headers));
if ( $buffer && !in_array(self::$status_code, array(301, 302)) )
cache_fs::put_contents($file . '.html', $buffer);
}
return $buffer;
} # ob_callback()
/**
* minify_html()
*
* @param string $buffer
* @return string $buffer
**/
static function minify_html($buffer) {
// props: http://stackoverflow.com/questions/5312349/minifying-final-html-output-using-regular-expressions-with-codeigniter
ini_set("pcre.recursion_limit", "524");
$re = '%# Collapse ws everywhere but in blacklisted elements.
(?> # Match all whitespans other than single space.
[^\S ]\s* # Either one [\t\r\n\f\v] and zero or more ws,
| \s{2,} # or two or more consecutive-any-whitespace.
) # Note: The remaining regex consumes no text at all...
(?= # Ensure we are not in a blacklist tag.
(?: # Begin (unnecessary) group.
(?: # Zero or more of...
[^<]++ # Either one or more non-"<"
| < # or a < starting a non-blacklist tag.
(?!/?(?:textarea|pre)\b)
)*+ # (This could be "unroll-the-loop"ified.)
) # End (unnecessary) group.
(?: # Begin alternation group.
< # Either a blacklist start tag.
(?>textarea|pre)\b
| \z # or end of file.
) # End alternation group.
) # If we made it here, we are not in a blacklist tag.
%ix';
$buffer = preg_replace($re, " ", $buffer);
// $buffer = preg_replace("/^\s+/m", "", $buffer);
return $buffer;
} #minify_html()
} # static_cache
static_cache::start();