Passed
Push — master ( d9761c...9b08f6 )
by Andreas
10:15
created

midcom_services_cache_module_content   F

Complexity

Total Complexity 71

Size/Duplication

Total Lines 585
Duplicated Lines 0 %

Test Coverage

Coverage 73.68%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 225
dl 0
loc 585
ccs 168
cts 228
cp 0.7368
rs 2.7199
c 2
b 0
f 0
wmc 71

20 Methods

Rating   Name   Duplication   Size   Complexity  
A no_cache() 0 15 4
A content_type() 0 3 1
B _check_hit() 0 47 7
A enable_live_mode() 0 4 1
A uncached() 0 3 1
A get_strategy() 0 8 2
A invalidate_all() 0 4 1
B on_response() 0 44 8
A on_request() 0 9 3
A __construct() 0 18 2
B generate_request_identifier() 0 40 6
A invalidate() 0 11 3
A register_sent_header() 0 5 2
A write_meta_cache() 0 18 3
A check_dl_hit() 0 12 3
A complete_sent_headers() 0 18 5
A store_dl_content() 0 20 3
B cache_control_headers() 0 30 6
A register() 0 17 3
B store_context_guid_map() 0 28 7

How to fix   Complexity   

Complex Class

Complex classes like midcom_services_cache_module_content often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use midcom_services_cache_module_content, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @package midcom.services
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\BinaryFileResponse;
12
use Symfony\Component\HttpKernel\Event\ResponseEvent;
13
use Symfony\Component\HttpKernel\Event\RequestEvent;
14
use Symfony\Component\Cache\Adapter\AdapterInterface;
15
16
/**
17
 * This is the Output Caching Engine of MidCOM. It will intercept page output,
18
 * map it using the currently used URL and use the cached output on subsequent
19
 * requests.
20
 *
21
 * <b>Important note for application developers</b>
22
 *
23
 * Please read the documentation of the following functions thoroughly:
24
 *
25
 * - midcom_services_cache_module_content::no_cache();
26
 * - midcom_services_cache_module_content::uncached();
27
 * - midcom_services_cache_module_content::expires();
28
 * - midcom_services_cache_module_content::invalidate_all();
29
 * - midcom_services_cache_module_content::content_type();
30
 * - midcom_services_cache_module_content::enable_live_mode();
31
 *
32
 * You have to use these functions everywhere where it is applicable or the cache
33
 * will not work reliably.
34
 *
35
 * <b>Caching strategy</b>
36
 *
37
 * The cache takes three parameters into account when storing in or retrieving from
38
 * the cache: The current User ID, the current language and the request's URL.
39
 *
40
 * Only on a complete match a cached page is displayed, which should take care of any
41
 * permission checks done on the page. When you change the permissions of users, you
42
 * need to manually invalidate the cache though, as MidCOM currently cannot detect
43
 * changes like this (of course, this is true if and only if you are not using a
44
 * MidCOM to change permissions).
45
 *
46
 * When the HTTP request is not cacheable, the caching engine will automatically and
47
 * transparently go into no_cache mode for that request only. This feature
48
 * does neither invalidate the cache or drop the page that would have been delivered
49
 * normally from the cache. If you change the content, you need to do that yourself.
50
 *
51
 * HTTP 304 Not Modified support is built into this module, and will send a 304 reply if applicable.
52
 *
53
 * <b>Module configuration (see also midcom_config)</b>
54
 *
55
 * - <i>boolean cache_module_content_uncached</i>: Set this to true to prevent the saving of cached pages. This is useful
56
 *   for development work, as all other headers (like E-Tag or Last-Modified) are generated
57
 *   normally. See the uncached() and _uncached members.
58
 *
59
 * @package midcom.services
60
 */
61
class midcom_services_cache_module_content extends midcom_services_cache_module
62
{
63
    /**
64
     * Flag, indicating whether the current page may be cached. If
65
     * false, the usual no-cache headers will be generated.
66
     */
67
    private bool $_no_cache = false;
68
69
    /**
70
     * An array storing all HTTP headers registered through register_sent_header().
71
     * They will be sent when a cached page is delivered.
72
     */
73
    private array $_sent_headers = [];
74
75
    /**
76
     * Set this to true if you want to inhibit storage of the generated pages in
77
     * the cache database. All other headers will be created as usual though, so
78
     * 304 processing will kick in for example.
79
     */
80
    private bool $_uncached = false;
81
82
    /**
83
     * Controls cache headers strategy
84
     * 'no-cache' activates no-cache mode that actively tries to circumvent all caching
85
     * 'revalidate' is the default which sets must-revalidate. Expiry defaults to current time, so this effectively behaves like no-cache if expires() was not called
86
     * 'public' and 'private' enable caching with the cache-control header of the same name, default expiry timestamps are generated using the default_lifetime
87
     */
88
    private string $_headers_strategy = 'revalidate';
89
90
    /**
91
     * Controls cache headers strategy for authenticated users, needed because some proxies store cookies, too,
92
     * making a horrible mess when used by mix of authenticated and non-authenticated users
93
     *
94
     * @see $_headers_strategy
95
     */
96
    private string $_headers_strategy_authenticated = 'private';
97
98
    /**
99
     * Default lifetime of page for public/private headers strategy
100
     * When generating the default expires header this is added to time().
101
     */
102
    private int $_default_lifetime = 0;
103
104
    /**
105
     * Default lifetime of page for public/private headers strategy for authenticated users
106
     *
107
     * @see $_default_lifetime
108
     */
109
    private int $_default_lifetime_authenticated = 0;
110
111
    /**
112
     * A cache backend used to store the actual cached pages.
113
     */
114
    private AdapterInterface $_data_cache;
115
116
    /**
117
     * GUIDs loaded per context in this request
118
     */
119
    private array $context_guids = [];
120
121
    private midcom_config $config;
122
123
    /**
124
     * Initialize the cache.
125
     *
126
     * The first step is to initialize the cache backends. The names of the
127
     * cache backends used for meta and data storage are derived from the name
128
     * defined for this module (see the 'name' configuration parameter above).
129
     * The name is used directly for the meta data cache, while the actual data
130
     * is stored in a backend postfixed with '_data'.
131
     *
132
     * After core initialization, the module checks for a cache hit (which might
133
     * trigger the delivery of the cached page and exit) and start the output buffer
134
     * afterwards.
135
     */
136 2
    public function __construct(midcom_config $config, AdapterInterface $backend, AdapterInterface $data_cache)
137
    {
138 2
        parent::__construct($backend);
139 2
        $this->config = $config;
140 2
        $this->_data_cache = $data_cache;
141
142 2
        $this->_uncached = $config->get('cache_module_content_uncached');
143 2
        $this->_headers_strategy = $this->get_strategy('cache_module_content_headers_strategy');
144 2
        $this->_headers_strategy_authenticated = $this->get_strategy('cache_module_content_headers_strategy_authenticated');
145 2
        $this->_default_lifetime = (int)$config->get('cache_module_content_default_lifetime');
146 2
        $this->_default_lifetime_authenticated = (int)$config->get('cache_module_content_default_lifetime_authenticated');
147
148 2
        if ($this->_headers_strategy == 'no-cache') {
149
            // we can't call no_cache() here, because it would try to call back to this class via the global getter
150
            $header = 'Cache-Control: no-store, no-cache, must-revalidate';
151
            $this->register_sent_header($header);
152
            midcom_compat_environment::header($header);
153
            $this->_no_cache = true;
154
        }
155
    }
156
157 351
    public function on_request(RequestEvent $event)
158
    {
159 351
        if ($event->isMainRequest()) {
160 1
            $request = $event->getRequest();
161
            /* Load and start up the cache system, this might already end the request
162
             * on a content cache hit. Note that the cache check hit depends on the i18n and auth code.
163
             */
164 1
            if ($response = $this->_check_hit($request)) {
165 1
                $event->setResponse($response);
166
            }
167
        }
168
    }
169
170
    /**
171
     * This function holds the cache hit check mechanism. It searches the requested
172
     * URL in the cache database. If found, it checks, whether the cache page has
173
     * expired. If not, the response is returned. In all other cases this method simply
174
     * returns void.
175
     *
176
     * Also, any HTTP POST request will automatically circumvent the cache so that
177
     * any component can process the request. It will set no_cache automatically
178
     * to avoid any cache pages being overwritten by, for example, search results.
179
     *
180
     * Note, that HTTP GET is <b>not</b> checked this way, as GET requests can be
181
     * safely distinguished by their URL.
182
     *
183
     * @return void|Response
184
     */
185 1
    private function _check_hit(Request $request)
186
    {
187 1
        if (!$request->isMethodCacheable()) {
188
            debug_add('Request method is not cacheable, setting no_cache');
189
            $this->no_cache();
190
            return;
191
        }
192
193
        // Check for uncached operation
194 1
        if ($this->_uncached) {
195
            debug_add("Uncached mode");
196
            return;
197
        }
198
199
        // Check that we have cache for the identifier
200 1
        $request_id = $this->generate_request_identifier($request);
201
        // Load metadata for the content identifier connected to current request
202 1
        $content_id = $this->backend->getItem($request_id);
203 1
        if (!$content_id->isHit()) {
204 1
            debug_add("MISS {$request_id}");
205
            // We have no information about content cached for this request
206 1
            return;
207
        }
208 1
        $content_id = $content_id->get();
209 1
        debug_add("HIT {$request_id}");
210
211 1
        $headers = $this->backend->getItem($content_id);
212 1
        if (!$headers->isHit()) {
213
            debug_add("MISS meta_cache {$content_id}");
214
            // Content cache data is missing
215
            return;
216
        }
217
218 1
        debug_add("HIT {$content_id}");
219
220 1
        $response = new Response('', Response::HTTP_OK, $headers->get());
221 1
        if (!$response->isNotModified($request)) {
222 1
            $content = $this->_data_cache->getItem($content_id);
223 1
            if (!$content->isHit()) {
224
                debug_add("Current page is in not in the data cache, possible ghost read.", MIDCOM_LOG_WARN);
225
                return;
226
            }
227 1
            $response->setContent($content->get());
228
        }
229
        // disable cache writing in on_response
230 1
        $this->_no_cache = true;
231 1
        return $response;
232
    }
233
234
    /**
235
     * This completes the output caching, post-processes it and updates the cache databases accordingly.
236
     *
237
     * The first step is to check against _no_cache pages, which will be delivered immediately
238
     * without any further post processing. Afterwards, the system will complete the sent
239
     * headers by adding all missing headers. Note, that E-Tag will be generated always
240
     * automatically, you must not set this in your component.
241
     *
242
     * If the midcom configuration option cache_uncached is set or the corresponding runtime function
243
     * has been called, the cache file will not be written, but the header stuff will be added like
244
     * usual to allow for browser-side caching.
245
     *
246
     * @param ResponseEvent $event The request object
247
     */
248 351
    public function on_response(ResponseEvent $event)
249
    {
250 351
        if (!$event->isMainRequest()) {
251 350
            return;
252
        }
253 1
        $response = $event->getResponse();
254 1
        if ($response instanceof BinaryFileResponse) {
255
            return;
256
        }
257 1
        foreach ($this->_sent_headers as $header => $value) {
258
            // This can happen in streamed responses which enable_live_mode
259
            if (!headers_sent()) {
260
                header_remove($header);
261
            }
262
            $response->headers->set($header, $value);
263
        }
264 1
        $request = $event->getRequest();
265 1
        if ($this->_no_cache) {
266
            $response->prepare($request);
267
            return;
268
        }
269
270 1
        $cache_data = $response->getContent();
271
272
        // Register additional Headers around the current output request
273 1
        $this->complete_sent_headers($response);
274 1
        $response->prepare($request);
275
276
        // Generate E-Tag header.
277 1
        if (empty($cache_data)) {
278
            $etag = md5(serialize($response->headers->all()));
279
        } else {
280 1
            $etag = md5($cache_data);
281
        }
282 1
        $response->setEtag($etag);
283
284 1
        if ($this->_uncached) {
285
            debug_add('Not writing cache file, we are in uncached operation mode.');
286
            return;
287
        }
288 1
        $content_id = 'C-' . $etag;
289 1
        $this->write_meta_cache($content_id, $request, $response);
290 1
        $item = $this->_data_cache->getItem($content_id);
291 1
        $this->_data_cache->save($item->set($cache_data));
292
    }
293
294
    /**
295
     * Generate a valid cache identifier for a context of the current request
296
     */
297 2
    private function generate_request_identifier(Request $request) : string
298
    {
299 2
        $context = $request->attributes->get('context')->id;
300
        // Cache the request identifier so that it doesn't change between start and end of request
301 2
        static $identifier_cache = [];
302 2
        if (isset($identifier_cache[$context])) {
303 1
            return $identifier_cache[$context];
304
        }
305
306 2
        $identifier_source = '';
307
308 2
        $cache_strategy = $this->config->get('cache_module_content_caching_strategy');
309
310
        switch ($cache_strategy) {
311 2
            case 'memberships':
312
                if (!midcom::get()->auth->is_valid_user()) {
313
                    $identifier_source .= 'USER=ANONYMOUS';
314
                    break;
315
                }
316
317
                $mc = new midgard_collector('midgard_member', 'uid', midcom_connection::get_user());
318
                $mc->set_key_property('gid');
319
                $mc->execute();
320
                $gids = $mc->list_keys();
321
                $identifier_source .= 'GROUPS=' . implode(',', array_keys($gids));
322
                break;
323 2
            case 'public':
324
                $identifier_source .= 'USER=EVERYONE';
325
                break;
326 2
            case 'user':
327
            default:
328 2
                $identifier_source .= 'USER=' . midcom_connection::get_user();
329 2
                break;
330
        }
331
332 2
        $identifier_source .= ';URL=' . $request->getUri();
333 2
        debug_add("Generating context {$context} request-identifier from: {$identifier_source}");
334
335 2
        $identifier_cache[$context] = 'R-' . md5($identifier_source);
336 2
        return $identifier_cache[$context];
337
    }
338
339 2
    private function get_strategy(string $name) : string
340
    {
341 2
        $strategy = strtolower($this->config->get($name));
0 ignored issues
show
Bug introduced by
It seems like $this->config->get($name) can also be of type null; however, parameter $string of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

341
        $strategy = strtolower(/** @scrutinizer ignore-type */ $this->config->get($name));
Loading history...
342 2
        $allowed = ['no-cache', 'revalidate', 'public', 'private'];
343 2
        if (!in_array($strategy, $allowed)) {
344
            throw new midcom_error($name . ' is not valid, try ' . implode(', ', $allowed));
345
        }
346 2
        return $strategy;
347
    }
348
349
    /**
350
     * Call this, if the currently processed output must not be cached for any
351
     * reason. Dynamic pages with sensitive content are a candidate for this
352
     * function.
353
     *
354
     * Note, that this will prevent <i>any</i> content invalidation related headers
355
     * like E-Tag to be generated automatically, and that the appropriate
356
     * no-store/no-cache headers from HTTP 1.1 and HTTP 1.0 will be sent automatically.
357
     * This means that there will also be no 304 processing.
358
     *
359
     * You should use this only for sensitive content. For simple dynamic output,
360
     * you are strongly encouraged to use the less strict uncached() function.
361
     *
362
     * @see uncached()
363
     */
364 198
    public function no_cache(Response $response = null)
365
    {
366 198
        $settings = 'no-store, no-cache, must-revalidate';
367
        // PONDER: Send expires header (set to long time in past) as well ??
368
369 198
        if ($response) {
370
            $response->headers->set('Cache-Control', $settings);
371 198
        } elseif (!$this->_no_cache) {
372
            if (headers_sent()) {
373
                debug_add('Warning, we should move to no_cache but headers have already been sent, skipping header transmission.', MIDCOM_LOG_ERROR);
374
            } else {
375
                midcom::get()->header('Cache-Control: ' . $settings);
376
            }
377
        }
378 198
        $this->_no_cache = true;
379
    }
380
381
    /**
382
     * Call this, if the currently processed output must not be cached for any
383
     * reason. Dynamic pages or form processing results are the usual candidates
384
     * for this mode.
385
     *
386
     * Note, that this will still keep the caching engine active so that it can
387
     * add the usual headers (ETag, Expires ...) in respect to the no_cache flag.
388
     * As well, at the end of the processing, the usual 304 checks are done, so if
389
     * your page doesn't change in respect of E-Tag and Last-Modified, only a 304
390
     * Not Modified reaches the client.
391
     *
392
     * Essentially, no_cache behaves the same way as if the uncached configuration
393
     * directive is set to true, it is just limited to a single request.
394
     *
395
     * If you need a higher level of client side security, to avoid storage of sensitive
396
     * information on the client side, you should use no_cache instead.
397
     *
398
     * @see no_cache()
399
     */
400 4
    public function uncached(bool $uncached = true)
401
    {
402 4
        $this->_uncached = $uncached;
403
    }
404
405
    /**
406
     * Sets the content type for the current page. The required HTTP Headers for
407
     * are automatically generated, so, to the contrary of expires, you just have
408
     * to set this header accordingly.
409
     *
410
     * This is usually set automatically by MidCOM for all regular HTML output and
411
     * for all attachment deliveries. You have to adapt it only for things like RSS
412
     * output.
413
     */
414 8
    public function content_type(string $type)
415
    {
416 8
        midcom::get()->header('Content-Type: ' . $type);
417
    }
418
419
    /**
420
     * Put the cache into a "live mode". This will disable the
421
     * cache during runtime, correctly flushing the output buffer (if it's not empty)
422
     * and sending cache control headers.
423
     *
424
     * The midcom-exec URL handler of the core will automatically enable live mode.
425
     *
426
     * @see midcom_application::_exec_file()
427
     */
428
    public function enable_live_mode()
429
    {
430
        $this->no_cache();
431
        Response::closeOutputBuffers(0, ob_get_length() > 0);
432
    }
433
434
    /**
435
     * Store a sent header into the cache database, so that it will
436
     * be resent when the cache page is delivered. midcom_application::header()
437
     * will automatically call this function, you need to do this only if you use
438
     * the PHP header function.
439
     */
440 17
    public function register_sent_header(string $header)
441
    {
442 17
        if (str_contains($header, ': ')) {
443 17
            [$header, $value] = explode(': ', $header, 2);
444 17
            $this->_sent_headers[$header] = $value;
445
        }
446
    }
447
448
    /**
449
     * Looks for list of content and request identifiers paired with the given guid
450
     * and removes all of those from the caches.
451
     *
452
     * {@inheritDoc}
453
     */
454 321
    public function invalidate(string $guid, midcom_core_dbaobject $object = null)
455
    {
456 321
        $guidmap = $this->backend->getItem($guid);
457 321
        if (!$guidmap->isHit()) {
458 321
            debug_add("No entry for {$guid} in meta cache, ignoring invalidation request.");
459 321
            return;
460
        }
461
462
        foreach ($guidmap->get() as $content_id) {
463
            $this->backend->deleteItem($content_id);
464
            $this->_data_cache->deleteItem($content_id);
465
        }
466
    }
467
468
    public function invalidate_all()
469
    {
470
        parent::invalidate_all();
471
        $this->_data_cache->clear();
472
    }
473
474
    /**
475
     * All objects loaded within a request are stored into a list for cache invalidation purposes
476
     */
477 410
    public function register(string $guid)
478
    {
479
        // Check for uncached operation
480 410
        if ($this->_uncached) {
481 409
            return;
482
        }
483
484 1
        $context = midcom_core_context::get()->id;
485 1
        if ($context != 0) {
486
            // We're in a dynamic_load, register it for that as well
487 1
            $this->context_guids[$context] ??= [];
488 1
            $this->context_guids[$context][] = $guid;
489
        }
490
491
        // Register all GUIDs also to the root context
492 1
        $this->context_guids[0] ??= [];
493 1
        $this->context_guids[0][] = $guid;
494
    }
495
496
    /**
497
     * Writes meta-cache entry from context data using given content id
498
     * Used to be part of on_request, but needed by serve-attachment method in midcom_core_urlmethods as well
499
     */
500 1
    public function write_meta_cache(string $content_id, Request $request, Response $response)
501
    {
502 1
        if (   $this->_uncached
503 1
            || $this->_no_cache) {
504
            return;
505
        }
506
507
        // Construct cache identifier
508 1
        $request_id = $this->generate_request_identifier($request);
509
510 1
        $item = $this->backend->getItem($request_id);
511 1
        $this->backend->save($item->set($content_id));
512 1
        $item2 = $this->backend->getItem($content_id);
513 1
        $this->backend->save($item2->set($response->headers->all()));
514
515
        // Cache where the object have been
516 1
        $context = midcom_core_context::get()->id;
517 1
        $this->store_context_guid_map($context, $content_id, $request_id);
518
    }
519
520 2
    private function store_context_guid_map(int $context, string $content_id, string $request_id)
521
    {
522
        // non-existent context
523 2
        if (!array_key_exists($context, $this->context_guids)) {
524 1
            return;
525
        }
526
527 1
        $maps = $this->backend->getItems($this->context_guids[$context]);
528 1
        if ($maps instanceof Traversable) {
529 1
            $maps = iterator_to_array($maps);
530
        }
531 1
        $to_save = [];
532 1
        foreach ($this->context_guids[$context] as $guid) {
533 1
            $guidmap = $maps[$guid]->get() ?? [];
534
535 1
            if (!in_array($content_id, $guidmap)) {
536 1
                $guidmap[] = $content_id;
537 1
                $to_save[$guid] = $maps[$guid]->set($guidmap);
538
            }
539
540 1
            if (!in_array($request_id, $guidmap)) {
541 1
                $guidmap[] = $request_id;
542 1
                $to_save[$guid] = $maps[$guid]->set($guidmap);
543
            }
544
        }
545
546 1
        foreach ($to_save as $item) {
547 1
            $this->backend->save($item);
548
        }
549
    }
550
551 17
    public function check_dl_hit(Request $request)
552
    {
553 17
        if ($this->_no_cache) {
554 17
            return false;
555
        }
556
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
557
        $dl_content_id = $this->backend->getItem($dl_request_id);
558
        if (!$dl_content_id->isHit()) {
559
            return false;
560
        }
561
562
        return $this->_data_cache->getItem($dl_content_id->get())->get();
563
    }
564
565 5
    public function store_dl_content(int $context, string $dl_cache_data, Request $request)
566
    {
567 5
        if (   $this->_no_cache
568 5
            || $this->_uncached) {
569 4
            return;
570
        }
571 1
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
572 1
        $dl_content_id = 'DLC-' . md5($dl_cache_data);
573
574 1
        $item = $this->backend->getItem($dl_request_id)
575 1
            ->set($dl_content_id)
576 1
            ->expiresAfter($this->_default_lifetime);
577 1
        $this->backend->save($item);
578 1
        $item = $this->_data_cache->getItem($dl_content_id)
579 1
            ->set($dl_cache_data)
580 1
            ->expiresAfter($this->_default_lifetime);
581 1
        $this->_data_cache->save($item);
582
583
        // Cache where the object have been
584 1
        $this->store_context_guid_map($context, $dl_content_id, $dl_request_id);
585
    }
586
587
    /**
588
     * This little helper ensures that the headers Content-Length
589
     * and Last-Modified are present. The lastmod timestamp is taken out of the
590
     * component context information if it is populated correctly there; if not, the
591
     * system time is used instead.
592
     *
593
     * To force browsers to revalidate the page on every request (login changes would
594
     * go unnoticed otherwise), the Cache-Control header max-age=0 is added automatically.
595
     */
596 1
    private function complete_sent_headers(Response $response)
597
    {
598 1
        if (!$response->getLastModified()) {
599
            /* Determine Last-Modified using MidCOM's component context,
600
             * Fallback to time() if this fails.
601
             */
602 1
            $time = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_LASTMODIFIED) ?: time();
603 1
            $response->setLastModified(DateTime::createFromFormat('U', (string) $time));
604
        }
605
606
        /* TODO: Doublecheck the way this is handled, now we just don't send it
607
         * if headers_strategy implies caching */
608 1
        if (   !$response->headers->has('Content-Length')
609 1
            && !in_array($this->_headers_strategy, ['public', 'private'])) {
610 1
            $response->headers->set("Content-Length", strlen($response->getContent()));
611
        }
612
613 1
        $this->cache_control_headers($response);
614
    }
615
616 1
    public function cache_control_headers(Response $response)
617
    {
618
        // Just to be sure not to mess the headers sent by no_cache in case it was called
619 1
        if ($this->_no_cache) {
620
            $this->no_cache($response);
621
        } else {
622
            // Add Expiration and Cache Control headers
623 1
            $strategy = $this->_headers_strategy;
624 1
            $default_lifetime = $this->_default_lifetime;
625 1
            if (midcom::get()->auth->is_valid_user()) {
626
                $strategy = $this->_headers_strategy_authenticated;
627
                $default_lifetime = $this->_default_lifetime_authenticated;
628
            }
629
630 1
            $now = $expires = time();
631 1
            if ($strategy != 'revalidate') {
632
                $expires += $default_lifetime;
633
                if ($strategy == 'private') {
634
                    $response->setPrivate();
635
                } else {
636
                    $response->setPublic();
637
                }
638
            }
639 1
            $max_age = $expires - $now;
640
641 1
            $response
642 1
                ->setExpires(DateTime::createFromFormat('U', $expires))
643 1
                ->setMaxAge($max_age);
644 1
            if ($max_age == 0) {
645 1
                $response->headers->addCacheControlDirective('must-revalidate');
646
            }
647
        }
648
    }
649
}
650