1: <?php
2: namespace Module\StaticCache;
3:
4: 5: 6: 7:
8: function rrmdir($dir) {
9: if (is_dir($dir)) {
10: $objects = scandir($dir);
11:
12: foreach ($objects as $object) {
13: if ($object != "." && $object != "..") {
14: if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
15: }
16: }
17:
18: reset($objects);
19: @rmdir($dir);
20: }
21: }
22:
23: 24: 25: 26: 27: 28:
29: function preprocess() {
30: $dir = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . "cache" . DIRECTORY_SEPARATOR . "normal" . DIRECTORY_SEPARATOR;
31:
32: if (file_exists($dir)) {
33: $created = filemtime($dir);
34: $cleanInterval = 300;
35:
36: if (time() - $created > $cleanInterval) {
37: rrmdir($dir);
38: } else {
39: header("SM-Cache Expires: " . ($cleanInterval - (time() - $created)) . " seconds.");
40: }
41: }
42:
43: ob_start();
44: }
45:
46: 47: 48: 49: 50:
51: function postprocess() {
52: $root = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR;
53: $cachedir = "cache" . DIRECTORY_SEPARATOR . "normal" . DIRECTORY_SEPARATOR;
54: $uri = explode('?', $_SERVER['REQUEST_URI']);
55: $uri = reset($uri);
56: $file = $uri . '_' . $_SERVER['QUERY_STRING'] . '.html';
57: $cachefile = $root . $cachedir . $_SERVER['SERVER_NAME'] . $file;
58:
59: $full_html = ob_get_flush() . "\n<!-- StaticCached -->";
60:
61: if (!is_dir(dirname($cachefile)) && !mkdir(dirname($cachefile), 0777, true)) {
62: throw new \Exception('StaticCache: Cannot make directory.');
63: }
64:
65: if (!$static = fopen($cachefile, "w")) {
66: throw new \Exception("StaticCache: Unable to open file!");
67: }
68:
69: fwrite($static, $full_html);
70: fclose($static);
71: }
72:
73:
74: if (\Sleepy\SM::isLive()) {
75: \Sleepy\Hook::doAction('sleepy_preprocess', '\Module\StaticCache\preprocess' );
76: \Sleepy\Hook::doAction('sleepy_postprocess', '\Module\StaticCache\postprocess');
77: }