Passed
Push — master ( 7f2659...451fb6 )
by Andreas
19:23
created

invalidate_all()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 Doctrine\Common\Cache\CacheProvider;
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>string cache_module_content_name</i>: The name of the cache database to use. This should usually be tied to the actual
56
 *   MidCOM site to have exactly one cache per site. This is mandatory (and populated by a sensible default
57
 *   by midcom_config, see there for details).
58
 * - <i>boolean cache_module_content_uncached</i>: Set this to true to prevent the saving of cached pages. This is useful
59
 *   for development work, as all other headers (like E-Tag or Last-Modified) are generated
60
 *   normally. See the uncached() and _uncached members.
61
 *
62
 * @package midcom.services
63
 */
64
class midcom_services_cache_module_content extends midcom_services_cache_module
65
{
66
    /**
67
     * Flag, indicating whether the current page may be cached. If
68
     * false, the usual no-cache headers will be generated.
69
     *
70
     * @var boolean
71
     */
72
    private $_no_cache = false;
73
74
    /**
75
     * Page expiration in seconds. If null (unset), the page does
76
     * not expire.
77
     *
78
     * @var int
79
     */
80
    private $_expires;
81
82
    /**
83
     * An array storing all HTTP headers registered through register_sent_header().
84
     * They will be sent when a cached page is delivered.
85
     *
86
     * @var array
87
     */
88
    private $_sent_headers = [];
89
90
    /**
91
     * Set this to true if you want to inhibit storage of the generated pages in
92
     * the cache database. All other headers will be created as usual though, so
93
     * 304 processing will kick in for example.
94
     *
95
     * @var boolean
96
     */
97
    private $_uncached = false;
98
99
    /**
100
     * Controls cache headers strategy
101
     * 'no-cache' activates no-cache mode that actively tries to circumvent all caching
102
     * '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
103
     * 'public' and 'private' enable caching with the cache-control header of the same name, default expiry timestamps are generated using the default_lifetime
104
     *
105
     * @var string
106
     */
107
    private $_headers_strategy = 'revalidate';
108
109
    /**
110
     * Controls cache headers strategy for authenticated users, needed because some proxies store cookies, too,
111
     * making a horrible mess when used by mix of authenticated and non-authenticated users
112
     *
113
     * @see $_headers_strategy
114
     * @var string
115
     */
116
    private $_headers_strategy_authenticated = 'private';
117
118
    /**
119
     * Default lifetime of page for public/private headers strategy
120
     * When generating the default expires header this is added to time().
121
     *
122
     * @var int
123
     */
124
    private $_default_lifetime = 0;
125
126
    /**
127
     * Default lifetime of page for public/private headers strategy for authenticated users
128
     *
129
     * @see $_default_lifetime
130
     * @var int
131
     */
132
    private $_default_lifetime_authenticated = 0;
133
134
    /**
135
     * A cache backend used to store the actual cached pages.
136
     *
137
     * @var Doctrine\Common\Cache\CacheProvider
138
     */
139
    private $_data_cache;
140
141
    /**
142
     * GUIDs loaded per context in this request
143
     */
144
    private $context_guids = [];
145
146
    /**
147
     * @var midcom_config
148
     */
149
    private $config;
150
151
    /**
152
     * Initialize the cache.
153
     *
154
     * The first step is to initialize the cache backends. The names of the
155
     * cache backends used for meta and data storage are derived from the name
156
     * defined for this module (see the 'name' configuration parameter above).
157
     * The name is used directly for the meta data cache, while the actual data
158
     * is stored in a backend postfixed with '_data'.
159
     *
160
     * After core initialization, the module checks for a cache hit (which might
161
     * trigger the delivery of the cached page and exit) and start the output buffer
162
     * afterwards.
163
     */
164 1
    public function __construct(midcom_config $config, CacheProvider $backend, CacheProvider $data_cache)
165
    {
166 1
        parent::__construct($backend);
167 1
        $this->config = $config;
168 1
        $this->_data_cache = $data_cache;
169 1
        $this->_data_cache->setNamespace($backend->getNamespace());
170
171 1
        $this->_uncached = $config->get('cache_module_content_uncached');
172 1
        $this->_headers_strategy = $this->get_strategy('cache_module_content_headers_strategy');
173 1
        $this->_headers_strategy_authenticated = $this->get_strategy('cache_module_content_headers_strategy_authenticated');
174 1
        $this->_default_lifetime = (int)$config->get('cache_module_content_default_lifetime');
175 1
        $this->_default_lifetime_authenticated = (int)$config->get('cache_module_content_default_lifetime_authenticated');
176
177 1
        if ($this->_headers_strategy == 'no-cache') {
178
            // we can't call no_cache() here, because it would try to call back to this class via the global getter
179
            $header = 'Cache-Control: no-store, no-cache, must-revalidate';
180
            $this->register_sent_header($header);
181
            midcom_compat_environment::header($header);
182
            $this->_no_cache = true;
183
        }
184 1
    }
185
186 341
    public function on_request(RequestEvent $event)
187
    {
188 341
        if ($event->isMasterRequest()) {
189 1
            $request = $event->getRequest();
190
            /* Load and start up the cache system, this might already end the request
191
             * on a content cache hit. Note that the cache check hit depends on the i18n and auth code.
192
             */
193 1
            if ($response = $this->_check_hit($request)) {
194 1
                $event->setResponse($response);
195
            }
196
        }
197 341
    }
198
199
    /**
200
     * This function holds the cache hit check mechanism. It searches the requested
201
     * URL in the cache database. If found, it checks, whether the cache page has
202
     * expired. If not, the response is returned. In all other cases this method simply
203
     * returns void.
204
     *
205
     * Also, any HTTP POST request will automatically circumvent the cache so that
206
     * any component can process the request. It will set no_cache automatically
207
     * to avoid any cache pages being overwritten by, for example, search results.
208
     *
209
     * Note, that HTTP GET is <b>not</b> checked this way, as GET requests can be
210
     * safely distinguished by their URL.
211
     *
212
     * @return void|Response
213
     */
214 1
    private function _check_hit(Request $request)
215
    {
216 1
        if (!$request->isMethodCacheable()) {
217
            debug_add('Request method is not cacheable, setting no_cache');
218
            $this->no_cache();
219
            return;
220
        }
221
222
        // Check for uncached operation
223 1
        if ($this->_uncached) {
224
            debug_add("Uncached mode");
225
            return;
226
        }
227
228
        // Check that we have cache for the identifier
229 1
        $request_id = $this->generate_request_identifier($request);
230
        // Load metadata for the content identifier connected to current request
231 1
        $content_id = $this->backend->fetch($request_id);
232 1
        if ($content_id === false) {
233 1
            debug_add("MISS {$request_id}");
234
            // We have no information about content cached for this request
235 1
            return;
236
        }
237 1
        debug_add("HIT {$request_id}");
238
239 1
        $headers = $this->backend->fetch($content_id);
240 1
        if ($headers === false) {
241
            debug_add("MISS meta_cache {$content_id}");
242
            // Content cache data is missing
243
            return;
244
        }
245
246 1
        debug_add("HIT {$content_id}");
247
248 1
        $response = new Response('', Response::HTTP_OK, $headers);
249 1
        if (!$response->isNotModified($request)) {
250 1
            $content = $this->_data_cache->fetch($content_id);
251 1
            if ($content === false) {
252
                debug_add("Current page is in not in the data cache, possible ghost read.", MIDCOM_LOG_WARN);
253
                return;
254
            }
255 1
            $response->setContent($content);
256
        }
257
        // disable cache writing in on_response
258 1
        $this->_no_cache = true;
259 1
        return $response;
260
    }
261
262
    /**
263
     * This completes the output caching, post-processes it and updates the cache databases accordingly.
264
     *
265
     * The first step is to check against _no_cache pages, which will be delivered immediately
266
     * without any further post processing. Afterwards, the system will complete the sent
267
     * headers by adding all missing headers. Note, that E-Tag will be generated always
268
     * automatically, you must not set this in your component.
269
     *
270
     * If the midcom configuration option cache_uncached is set or the corresponding runtime function
271
     * has been called, the cache file will not be written, but the header stuff will be added like
272
     * usual to allow for browser-side caching.
273
     *
274
     * @param ResponseEvent $event The request object
275
     */
276 342
    public function on_response(ResponseEvent $event)
277
    {
278 342
        if (!$event->isMasterRequest()) {
279 341
            return;
280
        }
281 1
        $response = $event->getResponse();
282 1
        if ($response instanceof BinaryFileResponse) {
283
            return;
284
        }
285 1
        foreach ($this->_sent_headers as $header => $value) {
286
            // This can happen in streamed responses which enable_live_mode
287
            if (!headers_sent()) {
288
                header_remove($header);
289
            }
290
            $response->headers->set($header, $value);
291
        }
292 1
        $request = $event->getRequest();
293 1
        if ($this->_no_cache) {
294
            $response->prepare($request);
295
            return;
296
        }
297
298 1
        $cache_data = $response->getContent();
299
300
        // Register additional Headers around the current output request
301 1
        $this->complete_sent_headers($response);
302 1
        $response->prepare($request);
303
304
        // Generate E-Tag header.
305 1
        if (empty($cache_data)) {
306
            $etag = md5(serialize($response->headers->all()));
307
        } else {
308 1
            $etag = md5($cache_data);
309
        }
310 1
        $response->setEtag($etag);
311
312 1
        if ($this->_uncached) {
313
            debug_add('Not writing cache file, we are in uncached operation mode.');
314
            return;
315
        }
316 1
        $content_id = 'C-' . $etag;
317 1
        $this->write_meta_cache($content_id, $request, $response);
318 1
        $this->_data_cache->save($content_id, $cache_data);
319 1
    }
320
321
    /**
322
     * Generate a valid cache identifier for a context of the current request
323
     */
324 1
    private function generate_request_identifier(Request $request) : string
325
    {
326 1
        $context = $request->attributes->get('context')->id;
327
        // Cache the request identifier so that it doesn't change between start and end of request
328 1
        static $identifier_cache = [];
329 1
        if (isset($identifier_cache[$context])) {
330 1
            return $identifier_cache[$context];
331
        }
332
333 1
        $module_name = $this->config->get('cache_module_content_name');
334 1
        if ($module_name == 'auto') {
335 1
            $module_name = midcom_connection::get_unique_host_name();
336
        }
337 1
        $identifier_source = 'CACHE:' . $module_name;
338
339 1
        $cache_strategy = $this->config->get('cache_module_content_caching_strategy');
340
341 1
        switch ($cache_strategy) {
342 1
            case 'memberships':
343
                if (!midcom::get()->auth->is_valid_user()) {
344
                    $identifier_source .= ';USER=ANONYMOUS';
345
                    break;
346
                }
347
348
                $mc = new midgard_collector('midgard_member', 'uid', midcom_connection::get_user());
349
                $mc->set_key_property('gid');
350
                $mc->execute();
351
                $gids = $mc->list_keys();
352
                $identifier_source .= ';GROUPS=' . implode(',', array_keys($gids));
353
                break;
354 1
            case 'public':
355
                $identifier_source .= ';USER=EVERYONE';
356
                break;
357 1
            case 'user':
358
            default:
359 1
                $identifier_source .= ';USER=' . midcom_connection::get_user();
360 1
                break;
361
        }
362
363 1
        $identifier_source .= ';URL=' . $request->getRequestUri();
364 1
        debug_add("Generating context {$context} request-identifier from: {$identifier_source}");
365
366 1
        $identifier_cache[$context] = 'R-' . md5($identifier_source);
367 1
        return $identifier_cache[$context];
368
    }
369
370 1
    private function get_strategy(string $name) : string
371
    {
372 1
        $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

372
        $strategy = strtolower(/** @scrutinizer ignore-type */ $this->config->get($name));
Loading history...
373 1
        $allowed = ['no-cache', 'revalidate', 'public', 'private'];
374 1
        if (!in_array($strategy, $allowed)) {
375
            throw new midcom_error($name . ' is not valid, try ' . implode(', ', $allowed));
376
        }
377 1
        return $strategy;
378
    }
379
380
    /**
381
     * Call this, if the currently processed output must not be cached for any
382
     * reason. Dynamic pages with sensitive content are a candidate for this
383
     * function.
384
     *
385
     * Note, that this will prevent <i>any</i> content invalidation related headers
386
     * like E-Tag to be generated automatically, and that the appropriate
387
     * no-store/no-cache headers from HTTP 1.1 and HTTP 1.0 will be sent automatically.
388
     * This means that there will also be no 304 processing.
389
     *
390
     * You should use this only for sensitive content. For simple dynamic output,
391
     * you are strongly encouraged to use the less strict uncached() function.
392
     *
393
     * @see uncached()
394
     */
395 194
    public function no_cache(Response $response = null)
396
    {
397 194
        $settings = 'no-store, no-cache, must-revalidate';
398
        // PONDER: Send expires header (set to long time in past) as well ??
399
400 194
        if ($response) {
401
            $response->headers->set('Cache-Control', $settings);
402 194
        } elseif (!$this->_no_cache) {
403
            if (headers_sent()) {
404
                debug_add('Warning, we should move to no_cache but headers have already been sent, skipping header transmission.', MIDCOM_LOG_ERROR);
405
            } else {
406
                midcom::get()->header('Cache-Control: ' . $settings);
407
            }
408
        }
409 194
        $this->_no_cache = true;
410 194
    }
411
412
    /**
413
     * Call this, if the currently processed output must not be cached for any
414
     * reason. Dynamic pages or form processing results are the usual candidates
415
     * for this mode.
416
     *
417
     * Note, that this will still keep the caching engine active so that it can
418
     * add the usual headers (ETag, Expires ...) in respect to the no_cache flag.
419
     * As well, at the end of the processing, the usual 304 checks are done, so if
420
     * your page doesn't change in respect of E-Tag and Last-Modified, only a 304
421
     * Not Modified reaches the client.
422
     *
423
     * Essentially, no_cache behaves the same way as if the uncached configuration
424
     * directive is set to true, it is just limited to a single request.
425
     *
426
     * If you need a higher level of client side security, to avoid storage of sensitive
427
     * information on the client side, you should use no_cache instead.
428
     *
429
     * @see no_cache()
430
     */
431 3
    public function uncached(bool $uncached = true)
432
    {
433 3
        $this->_uncached = $uncached;
434 3
    }
435
436
    /**
437
     * Sets the expiration time of the current page (Unix (GMT) Timestamp).
438
     *
439
     * <b>Note:</B> This generate error call will add browser-side cache control
440
     * headers as well to force a browser to revalidate a page after the set
441
     * expiry.
442
     *
443
     * You should call this at all places where you have timed content in your
444
     * output, so that the page will be regenerated once a certain article has
445
     * expired.
446
     *
447
     * Multiple calls to expires will only save the
448
     * "youngest" timestamp, so you can safely call expires where appropriate
449
     * without respect to other values.
450
     *
451
     * The cache's default (null) will disable the expires header. Note, that once
452
     * an expiry time on a page has been set, it is not possible, to reset it again,
453
     * this is for dynamic_load situation, where one component might depend on a
454
     * set expiry.
455
     */
456
    public function expires(int $timestamp)
457
    {
458
        if (   $this->_expires === null
459
            || $this->_expires > $timestamp) {
460
            $this->_expires = $timestamp;
461
        }
462
    }
463
464
    /**
465
     * Sets the content type for the current page. The required HTTP Headers for
466
     * are automatically generated, so, to the contrary of expires, you just have
467
     * to set this header accordingly.
468
     *
469
     * This is usually set automatically by MidCOM for all regular HTML output and
470
     * for all attachment deliveries. You have to adapt it only for things like RSS
471
     * output.
472
     */
473 8
    public function content_type(string $type)
474
    {
475 8
        midcom::get()->header('Content-Type: ' . $type);
476 8
    }
477
478
    /**
479
     * Put the cache into a "live mode". This will disable the
480
     * cache during runtime, correctly flushing the output buffer (if it's not empty)
481
     * and sending cache control headers.
482
     *
483
     * The midcom-exec URL handler of the core will automatically enable live mode.
484
     *
485
     * @see midcom_application::_exec_file()
486
     */
487
    public function enable_live_mode()
488
    {
489
        $this->no_cache();
490
        Response::closeOutputBuffers(0, ob_get_length() > 0);
491
    }
492
493
    /**
494
     * Store a sent header into the cache database, so that it will
495
     * be resent when the cache page is delivered. midcom_application::header()
496
     * will automatically call this function, you need to do this only if you use
497
     * the PHP header function.
498
     */
499 17
    public function register_sent_header(string $header)
500
    {
501 17
        if (str_contains($header, ': ')) {
502 17
            [$header, $value] = explode(': ', $header, 2);
503 17
            $this->_sent_headers[$header] = $value;
504
        }
505 17
    }
506
507
    /**
508
     * Looks for list of content and request identifiers paired with the given guid
509
     * and removes all of those from the caches.
510
     *
511
     * {@inheritDoc}
512
     */
513 303
    public function invalidate(string $guid, $object = null)
514
    {
515 303
        $guidmap = $this->backend->fetch($guid);
516 303
        if ($guidmap === false) {
517 303
            debug_add("No entry for {$guid} in meta cache, ignoring invalidation request.");
518 303
            return;
519
        }
520
521
        foreach ($guidmap as $content_id) {
522
            if ($this->backend->contains($content_id)) {
523
                $this->backend->delete($content_id);
524
            }
525
526
            if ($this->_data_cache->contains($content_id)) {
527
                $this->_data_cache->delete($content_id);
528
            }
529
        }
530
    }
531
532
    public function invalidate_all()
533
    {
534
        parent::invalidate_all();
535
        $this->_data_cache->flushAll();
536
    }
537
538
    /**
539
     * All objects loaded within a request are stored into a list for cache invalidation purposes
540
     */
541 393
    public function register(string $guid)
542
    {
543
        // Check for uncached operation
544 393
        if ($this->_uncached) {
545 393
            return;
546
        }
547
548
        $context = midcom_core_context::get()->id;
549
        if ($context != 0) {
550
            // We're in a dynamic_load, register it for that as well
551
            if (!isset($this->context_guids[$context])) {
552
                $this->context_guids[$context] = [];
553
            }
554
            $this->context_guids[$context][] = $guid;
555
        }
556
557
        // Register all GUIDs also to the root context
558
        if (!isset($this->context_guids[0])) {
559
            $this->context_guids[0] = [];
560
        }
561
        $this->context_guids[0][] = $guid;
562
    }
563
564
    /**
565
     * Writes meta-cache entry from context data using given content id
566
     * Used to be part of on_request, but needed by serve-attachment method in midcom_core_urlmethods as well
567
     */
568 1
    public function write_meta_cache(string $content_id, Request $request, Response $response)
569
    {
570 1
        if (   $this->_uncached
571 1
            || $this->_no_cache) {
572
            return;
573
        }
574
575 1
        if ($this->_expires !== null) {
576
            $lifetime = $this->_expires - time();
577
        } else {
578
            // Use default expiry for cache entry, most components don't bother calling expires() properly
579 1
            $lifetime = $this->_default_lifetime;
580
        }
581
582
        // Construct cache identifier
583 1
        $request_id = $this->generate_request_identifier($request);
584
585
        $entries = [
586 1
            $request_id => $content_id,
587 1
            $content_id => $response->headers->all()
588
        ];
589 1
        $this->backend->saveMultiple($entries, $lifetime);
590
591
        // Cache where the object have been
592 1
        $context = midcom_core_context::get()->id;
593 1
        $this->store_context_guid_map($context, $content_id, $request_id);
594 1
    }
595
596 1
    private function store_context_guid_map(int $context, string $content_id, string $request_id)
597
    {
598
        // non-existent context
599 1
        if (!array_key_exists($context, $this->context_guids)) {
600 1
            return;
601
        }
602
603
        $maps = $this->backend->fetchMultiple($this->context_guids[$context]);
604
        $to_save = [];
605
        foreach ($this->context_guids[$context] as $guid) {
606
            // Getting old map from cache or create new, empty one
607
            $guidmap = $maps[$guid] ?? [];
608
609
            if (!in_array($content_id, $guidmap)) {
610
                $guidmap[] = $content_id;
611
                $to_save[$guid] = $guidmap;
612
            }
613
614
            if (!in_array($request_id, $guidmap)) {
615
                $guidmap[] = $request_id;
616
                $to_save[$guid] = $guidmap;
617
            }
618
        }
619
620
        $this->backend->saveMultiple($to_save);
621
    }
622
623 16
    public function check_dl_hit(Request $request)
624
    {
625 16
        if ($this->_no_cache) {
626 16
            return false;
627
        }
628
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
629
        $dl_content_id = $this->backend->fetch($dl_request_id);
630
        if ($dl_content_id === false) {
631
            return false;
632
        }
633
634
        return $this->_data_cache->fetch($dl_content_id);
635
    }
636
637 4
    public function store_dl_content(int $context, string $dl_cache_data, Request $request)
638
    {
639 4
        if (   $this->_no_cache
640 4
            || $this->_uncached) {
641 4
            return;
642
        }
643
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
644
        $dl_content_id = 'DLC-' . md5($dl_cache_data);
645
646
        if ($this->_expires !== null) {
647
            $lifetime = $this->_expires - time();
648
        } else {
649
            // Use default expiry for cache entry, most components don't bother calling expires() properly
650
            $lifetime = $this->_default_lifetime;
651
        }
652
        $this->backend->save($dl_request_id, $dl_content_id, $lifetime);
653
        $this->_data_cache->save($dl_content_id, $dl_cache_data, $lifetime);
654
        // Cache where the object have been
655
        $this->store_context_guid_map($context, $dl_content_id, $dl_request_id);
656
    }
657
658
    /**
659
     * This little helper ensures that the headers Content-Length
660
     * and Last-Modified are present. The lastmod timestamp is taken out of the
661
     * component context information if it is populated correctly there; if not, the
662
     * system time is used instead.
663
     *
664
     * To force browsers to revalidate the page on every request (login changes would
665
     * go unnoticed otherwise), the Cache-Control header max-age=0 is added automatically.
666
     */
667 1
    private function complete_sent_headers(Response $response)
668
    {
669 1
        if (!$response->getLastModified()) {
670
            /* Determine Last-Modified using MidCOM's component context,
671
             * Fallback to time() if this fails.
672
             */
673 1
            $time = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_LASTMODIFIED) ?: time();
674 1
            $response->setLastModified(DateTime::createFromFormat('U', (string) $time));
675
        }
676
677 1
        if (!$response->headers->has('Content-Length')) {
678
            /* TODO: Doublecheck the way this is handled, now we just don't send it
679
             * if headers_strategy implies caching */
680 1
            if (!in_array($this->_headers_strategy, ['public', 'private'])) {
681 1
                $response->headers->set("Content-Length", strlen($response->getContent()));
682
            }
683
        }
684
685 1
        $this->cache_control_headers($response);
686 1
    }
687
688 1
    public function cache_control_headers(Response $response)
689
    {
690
        // Just to be sure not to mess the headers sent by no_cache in case it was called
691 1
        if ($this->_no_cache) {
692
            $this->no_cache($response);
693
        } else {
694
            // Add Expiration and Cache Control headers
695 1
            $strategy = $this->_headers_strategy;
696 1
            $default_lifetime = $this->_default_lifetime;
697 1
            if (midcom::get()->auth->is_valid_user()) {
698
                $strategy = $this->_headers_strategy_authenticated;
699
                $default_lifetime = $this->_default_lifetime_authenticated;
700
            }
701
702 1
            $now = time();
703 1
            if ($strategy == 'revalidate') {
704
                // If expires is not set, we force the client to revalidate every time.
705
                // The timeout of a content cache entry is not affected by this.
706 1
                $expires = $this->_expires ?? $now;
707
            } else {
708
                $expires = $this->_expires ?? $now + $default_lifetime;
709
                if ($strategy == 'private') {
710
                    $response->setPrivate();
711
                } else {
712
                    $response->setPublic();
713
                }
714
            }
715 1
            $max_age = $expires - $now;
716
717
            $response
718 1
                ->setExpires(DateTime::createFromFormat('U', $expires))
719 1
                ->setMaxAge($max_age);
720 1
            if ($max_age == 0) {
721 1
                $response->headers->addCacheControlDirective('must-revalidate');
722
            }
723
        }
724 1
    }
725
}
726