-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstaticcache.plugin.php
442 lines (399 loc) · 12.4 KB
/
staticcache.plugin.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
<?php
//namespace Habari;
/**
* @package staticcache
*/
/**
* StaticCache Plugin will cache the HTML output generated by Habari for each page.
*/
class StaticCache extends Plugin
{
const DEBUG = false;
const VERSION = 0.3;
const API_VERSION = 004;
const GZ_COMPRESSION = 4;
const EXPIRE = 86400;
const EXPIRE_STATS = 604800;
const GROUP_NAME = 'staticcache';
const STATS_GROUP_NAME = 'staticcache_stats';
/**
* Set a priority of 1 on action_init so we run first
*
* @return array the priorities for our hooks
*/
public function set_priorities()
{
return array(
'action_init' => 1
);
}
/**
* Create aliases to additional hooks
*
* @return array aliased hooks
*/
public function alias()
{
return array(
'action_post_update_after' => array(
'action_post_insert_after',
'action_post_delete_after'
),
'action_comment_update_after' => array(
'action_comment_insert_after',
'action_comment_delete_after'
)
);
}
/**
* Serves the cache page or starts the output buffer. Ignore URLs matching
* the ignore list, and ignores if there are session messages.
*
* @see StaticCache_ob_end_flush()
*/
public function action_init()
{
/**
* Allows plugins to add to the ignore list. An array of all URLs to ignore
* is passed to the filter.
*
* @filter staticcache_ignore an array of URLs to ignore
*/
$ignore_array = Plugins::filter(
'staticcache_ignore',
explode(',', Options::get('staticcache__ignore_list'))
);
// sanitize the ignore list for preg_match
$ignore_list = implode(
'|',
array_map(
create_function('$a', 'return preg_quote(trim($a), "@");'),
$ignore_array
)
);
$request = Site::get_url('host') . $_SERVER['REQUEST_URI'];
$request_method = $_SERVER['REQUEST_METHOD'];
/* don't cache PUT or POST requests, pages matching ignore list keywords,
* nor pages with session messages, nor loggedin users
*/
if ($request_method == 'PUT' || $request_method == 'POST'
|| preg_match("@.*($ignore_list).*@i", $request) || Session::has_messages() || User::identify()->loggedin
) {
return;
}
$request_id = self::get_request_id();
$query_id = self::get_query_id();
if (Cache::has(array(self::GROUP_NAME, $request_id))) {
$cache = Cache::get(array(self::GROUP_NAME, $request_id));
if (isset($cache[$query_id])) {
global $profile_start;
// send the cached headers
foreach ($cache[$query_id]['headers'] as $header) {
header($header);
}
// check for compression
// @todo directly send compressed data to browser if webserver is not compressing.
if (isset($cache[$query_id]['compressed']) && $cache[$query_id]['compressed'] == true) {
echo gzuncompress($cache[$query_id]['body']);
}
else {
echo $cache[$query_id]['body'];
}
// record hit and profile data
$this->record_stats('hit', $profile_start);
exit;
}
}
// record miss
$this->record_stats('miss');
// register hook
Plugins::register(array('StaticCache', 'store_final_output'), 'filter', 'final_output', 16);
}
/**
* Record StaticCaches stats in the cache itself to avoid DB writes.
* Data includes hits, misses, and avg.
*
* @param string $type type of record, either hit or miss
* @param double $profile_start start of the profiling
*/
protected function record_stats($type, $profile_start = null)
{
switch ($type) {
case 'hit':
// do stats and output profiling
$pagetime = microtime(true) - $profile_start;
$hits = (int)Cache::get(array(self::STATS_GROUP_NAME, 'hits'));
$profile = (double)Cache::get(array(self::STATS_GROUP_NAME, 'avg'));
$avg = ($profile * $hits + $pagetime) / ($hits + 1);
Cache::set(array(self::STATS_GROUP_NAME, 'avg'), $avg, self::EXPIRE_STATS);
Cache::set(array(self::STATS_GROUP_NAME, 'hits'), $hits + 1, self::EXPIRE_STATS);
header('X-StaticCache-Stats: ' . $pagetime);
break;
case 'miss':
Cache::set(array(self::STATS_GROUP_NAME, 'misses'), Cache::get(array(self::STATS_GROUP_NAME, 'misses')) + 1, self::EXPIRE_STATS);
break;
}
}
/**
* Add the Static Cache dashboard module
*
* @param array $modules Available dash modules
* @return array modules array
*/
public function filter_dashboard_block_list($block_list)
{
$block_list['staticcache'] = 'Static Cache';
$this->add_template('dashboard.block.staticcache', dirname(__FILE__) . '/dashboard.block.staticcache.php');
return $block_list;
}
/**
* Filters the static cache dash module to add the theme template output.
*
* @param Block $block the dashboard block
* @param Theme the current theme from the handler
* @return array the modified module structure
*/
public function action_block_content_staticcache(Block $block, Theme $theme)
{
$block->static_cache_average = sprintf('%.4f', Cache::get(array(self::STATS_GROUP_NAME, 'avg')));
$block->static_cache_pages = count(Cache::get_group(self::GROUP_NAME));
$hits = Cache::get(array(self::STATS_GROUP_NAME, 'hits'));
$misses = Cache::get(array(self::STATS_GROUP_NAME, 'misses'));
$total = $hits + $misses;
$block->static_cache_misses_pct = sprintf('%.0f', $total > 0 ? ($misses / $total) * 100 : 0);
$block->static_cache_hits = $hits;
$block->static_cache_misses = $misses;
$block->static_cache_expire = $this->secs_to_human(Options::get('staticcache__expire', StaticCache::EXPIRE));
}
/**
* Convert seconds to human readable text.
*
* @param int the number of seconds to convert
* @return string a human readable time period
*/
public function secs_to_human($secs)
{
$units = array(
"week" => 7 * 24 * 3600,
"day" => 24 * 3600,
"hour" => 3600,
"minute" => 60,
"second" => 1,
);
// specifically handle zero
if ($secs == 0) return "0 seconds";
$s = "";
foreach ($units as $name => $divisor) {
if ($quot = intval($secs / $divisor)) {
$s .= "$quot $name";
$s .= (abs($quot) > 1 ? "s" : "") . ", ";
$secs -= $quot * $divisor;
}
}
return substr($s, 0, -2);
}
/**
* Ajax entry point for the 'clear cache data' action. Clears all stats and cache data
* and outputs a JSON encoded string message.
*/
public function action_auth_ajax_clear_staticcache()
{
foreach (Cache::get_group(self::GROUP_NAME) as $name => $data) {
Cache::expire(array(self::GROUP_NAME, $name));
}
foreach (Cache::get_group(self::STATS_GROUP_NAME) as $name => $data) {
Cache::expire(array(self::STATS_GROUP_NAME, $name));
}
echo json_encode(_t("Cleared Static Cache's cache"));
}
/**
* Invalidates (expires) the cache entries for the give list of URLs.
*
* @param array $urls An array of urls to clear
*/
public function cache_invalidate(array $urls)
{
// account for annonymous user (id=0)
$user_ids = array_map(create_function('$a', 'return $a->id;'), Users::get_all()->getArrayCopy());
array_push($user_ids, "0");
// expire the urls for each user id
foreach ($user_ids as $user_id) {
foreach ($urls as $url) {
$request_id = self::get_request_id($user_id, $url);
if (Cache::has(array(self::GROUP_NAME, $request_id))) {
Cache::expire(array(self::GROUP_NAME, $request_id));
EventLog::log('Clearing request ID: ' . $request_id, 'info', 'plugin', 'StaticCache');
}
}
}
}
/**
* Clears cache for the given post after it's updated. includes all CRUD operations.
*
* @param Post the post object to clear cache for
* @see StaticCache::cache_invalidate()
*/
public function action_post_update_after(Post $post)
{
$urls = array(
$post->comment_feed_link,
$post->permalink,
URL::get('atom_feed', 'index=1'),
Site::get_url('habari')
);
$this->cache_invalidate($urls);
}
/**
* Clears cache for the given comments parent post after it's updated. includes all
* CRUD operations.
*
* @param Comment the comment object to clear cache for it's parent post
* @see StaticCache::cache_invalidate()
*/
public function action_comment_update_after(Comment $comment)
{
$urls = array(
$comment->post->comment_feed_link,
$comment->post->permalink,
URL::get('atom_feed', 'index=1'),
Site::get_url('habari')
);
$this->cache_invalidate($urls);
}
/**
* Setup the initial ignore list on activation. Ignores URLs matching the following:
* /admin, /feedback, /user, /ajax, /auth_ajax, and ?nocache
*/
public function action_plugin_activation()
{
Options::set('staticcache__ignore_list', '/cron,/admin,/feedback,/auth,/ajax,/auth_ajax,?nocache');
}
/**
* Adds a 'configure' action to the pllugin page.
*
* @param array $actions the default plugin actions
* @param strinf $plugin_id the plugins id
* @return array the actions to add
*/
public function filter_plugin_config(array $actions, $plugin_id)
{
if ($plugin_id == $this->plugin_id()) {
$actions[] = _t('Configure', 'staticcache');
}
return $actions;
}
/**
* Adds the configure UI
*
* @todo add invalidate cache button
* @param string $plugin_id the plugins id
* @param string $action the action being performed
*/
public function action_plugin_ui($plugin_id, $action)
{
if ($plugin_id == $this->plugin_id()) {
switch ($action) {
case _t('Configure', 'staticcache') :
$ui = new FormUI('staticcache');
$ignore = $ui->append('textarea', 'ignore', 'staticcache__ignore_list', _t('Do not cache any URI\'s matching these keywords (comma seperated): ', 'staticcache'));
$ignore->add_validator('validate_required');
$expire = $ui->append('text', 'expire', 'staticcache__expire', _t('Cache expiry (in seconds): ', 'staticcache'));
$expire->add_validator('validate_required');
if (extension_loaded('zlib')) {
$compress = $ui->append('checkbox', 'compress', 'staticcache__compress', _t('Compress Cache To Save Space: ', 'staticcache'));
}
$ui->append('submit', 'save', _t('Save', 'staticcache'));
$ui->on_success(array($this, 'save_config_msg'));
$ui->out();
break;
}
}
}
public static function save_config_msg($ui)
{
$ui->save();
Session::notice(_t('Options saved'));
return false;
}
/**
* Adds the plugin to the update check routine.
*/
public function action_update_check()
{
Update::add('StaticCache', '340fb135-e1a1-4351-a81c-dac2f1795169', self::VERSION);
}
/**
* gets a unique id for the current query string requested.
*
* @return string Query ID
*/
public static function get_query_id()
{
return crc32(parse_url(Site::get_url('host') . $_SERVER['REQUEST_URI'], PHP_URL_QUERY));
}
/**
* Gets a unique id for the given request URL and user id.
*
* @param int the users id. Defaults to current users id or 0 for anonymous
* @param string The URL. Defaults to the current REQUEST_URI
* @return string Request ID
*/
public static function get_request_id($user_id = null, $url = null)
{
if (!$user_id) {
$user = User::identify();
$user_id = $user instanceof User ? $user->id : 0;
}
if (!$url) {
$url = Site::get_url('host') . rtrim(parse_url(Site::get_url('host') . $_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');
}
return crc32($user_id . $url);
}
/**
* The output buffer callback used to capture the output and cache it.
*
* @see StaticCache::init()
* @param string $buffer The output buffer contents
* @return string $buffer unchanged
*/
public static function store_final_output($buffer)
{
// prevent caching of 404 responses
if (!URL::get_matched_rule() || URL::get_matched_rule()->name == 'display_404') {
return $buffer;
}
$request_id = StaticCache::get_request_id();
$query_id = StaticCache::get_query_id();
$expire = Options::get('staticcache__expire', StaticCache::EXPIRE);
// get cache if exists
if (Cache::has(array(StaticCache::GROUP_NAME, $request_id))) {
$cache = Cache::get(array(StaticCache::GROUP_NAME, $request_id));
}
else {
$cache = array();
}
// don't cache cookie headers (ie. session cookies)
$headers = headers_list();
foreach ($headers as $i => $head) {
if (stripos($head, 'cookie') !== false) {
unset($headers[$i]);
}
}
// see if we want compression and store cache
$cache[$query_id] = array(
'headers' => $headers,
'request_uri' => Site::get_url('host') . $_SERVER['REQUEST_URI']
);
if (Options::get('staticcache__compress') && extension_loaded('zlib')) {
$cache[$query_id]['body'] = gzcompress($buffer, StaticCache::GZ_COMPRESSION);
$cache[$query_id]['compressed'] = true;
}
else {
$cache[$query_id]['body'] = $buffer;
$cache[$query_id]['compressed'] = false;
}
Cache::set(array(StaticCache::GROUP_NAME, $request_id), $cache, $expire);
return $buffer;
}
}
?>