1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sunnysideup\SimpleTemplateCaching\Extensions; |
4
|
|
|
|
5
|
|
|
use PhpParser\Node\Scalar\MagicConst\Dir; |
6
|
|
|
use SilverStripe\CMS\Controllers\ContentController; |
7
|
|
|
use SilverStripe\Control\Director; |
8
|
|
|
use SilverStripe\Control\Middleware\HTTPCacheControlMiddleware; |
9
|
|
|
use SilverStripe\Core\Extension; |
10
|
|
|
use SilverStripe\Security\Security; |
11
|
|
|
use SilverStripe\SiteConfig\SiteConfig; |
12
|
|
|
use SilverStripe\Versioned\Versioned; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Class \ControllerExtension. |
16
|
|
|
* |
17
|
|
|
* @property PageController|ControllerExtension $owner |
18
|
|
|
*/ |
19
|
|
|
class ControllerExtension extends Extension |
20
|
|
|
{ |
21
|
|
|
public function onBeforeInit() |
22
|
|
|
{ |
23
|
|
|
//make sure that caching is always https |
24
|
|
|
$owner = $this->getOwner(); |
25
|
|
|
if (Director::isLive()) { |
26
|
|
|
$owner->response->addHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); |
27
|
|
|
} |
28
|
|
|
if (Security::getCurrentUser()) { |
29
|
|
|
return null; |
30
|
|
|
} |
31
|
|
|
if (Versioned::get_reading_mode() !== 'Stage.Live') { |
32
|
|
|
return null; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$sc = SiteConfig::current_site_config(); |
36
|
|
|
if (! $sc->HasCaching) { |
37
|
|
|
return null; |
38
|
|
|
} |
39
|
|
|
/** PageController|ControllerExtension $owner */ |
40
|
|
|
if ($owner instanceof ContentController) { |
41
|
|
|
$dataRecord = $owner->data(); |
42
|
|
|
if (empty($dataRecord)) { |
43
|
|
|
return null; |
44
|
|
|
} |
45
|
|
|
if ($dataRecord->NeverCachePublicly) { |
46
|
|
|
HTTPCacheControlMiddleware::singleton() |
47
|
|
|
->disableCache() |
48
|
|
|
; |
49
|
|
|
return null; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
if ($owner->hasMethod('updateCacheControl')) { |
53
|
|
|
$extend = $owner->extend('updateCacheControl'); |
54
|
|
|
if ($extend) { |
55
|
|
|
return null; |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
$request = $owner->getRequest(); |
60
|
|
|
if ($owner->hasMethod('cacheControlExcludedActions')) { |
61
|
|
|
$excludeActions = $owner->cacheControlExcludedActions(); |
62
|
|
|
if ($request->param('Action') && in_array($request->param('Action'), $excludeActions)) { |
63
|
|
|
return null; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
if ($request->isAjax()) { |
67
|
|
|
return null; |
68
|
|
|
} |
69
|
|
|
if ($request->getVar('flush')) { |
70
|
|
|
return null; |
71
|
|
|
} |
72
|
|
|
if ($request->requestVars()) { |
73
|
|
|
return null; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
|
77
|
|
|
$cacheTime = (int) ($dataRecord->PublicCacheDurationInSeconds ?: $sc->PublicCacheDurationInSeconds); |
78
|
|
|
if ($cacheTime > 0) { |
79
|
|
|
return HTTPCacheControlMiddleware::singleton() |
80
|
|
|
->enableCache() |
81
|
|
|
->setMaxAge($cacheTime) |
82
|
|
|
->publicCache(true) |
83
|
|
|
; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
return null; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|