Passed
Push — master ( 8a140a...6eed6d )
by Andreas
26:05
created

midcom_services_cache_module_content   F

Complexity

Total Complexity 73

Size/Duplication

Total Lines 607
Duplicated Lines 0 %

Test Coverage

Coverage 60.57%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 228
dl 0
loc 607
ccs 149
cts 246
cp 0.6057
rs 2.56
c 4
b 0
f 0
wmc 73

20 Methods

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

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

365
        $strategy = strtolower(/** @scrutinizer ignore-type */ $this->config->get($name));
Loading history...
366 1
        $allowed = ['no-cache', 'revalidate', 'public', 'private'];
367 1
        if (!in_array($strategy, $allowed)) {
368
            throw new midcom_error($name . ' is not valid, try ' . implode(', ', $allowed));
369
        }
370 1
        return $strategy;
371
    }
372
373
    /**
374
     * Call this, if the currently processed output must not be cached for any
375
     * reason. Dynamic pages with sensitive content are a candidate for this
376
     * function.
377
     *
378
     * Note, that this will prevent <i>any</i> content invalidation related headers
379
     * like E-Tag to be generated automatically, and that the appropriate
380
     * no-store/no-cache headers from HTTP 1.1 and HTTP 1.0 will be sent automatically.
381
     * This means that there will also be no 304 processing.
382
     *
383
     * You should use this only for sensitive content. For simple dynamic output,
384
     * you are strongly encouraged to use the less strict uncached() function.
385
     *
386
     * @see uncached()
387
     */
388 195
    public function no_cache(Response $response = null)
389
    {
390 195
        $settings = 'no-store, no-cache, must-revalidate';
391
        // PONDER: Send expires header (set to long time in past) as well ??
392
393 195
        if ($response) {
394
            $response->headers->set('Cache-Control', $settings);
395 195
        } elseif (!$this->_no_cache) {
396
            if (headers_sent()) {
397
                debug_add('Warning, we should move to no_cache but headers have already been sent, skipping header transmission.', MIDCOM_LOG_ERROR);
398
            } else {
399
                midcom::get()->header('Cache-Control: ' . $settings);
400
            }
401
        }
402 195
        $this->_no_cache = true;
403 195
    }
404
405
    /**
406
     * Call this, if the currently processed output must not be cached for any
407
     * reason. Dynamic pages or form processing results are the usual candidates
408
     * for this mode.
409
     *
410
     * Note, that this will still keep the caching engine active so that it can
411
     * add the usual headers (ETag, Expires ...) in respect to the no_cache flag.
412
     * As well, at the end of the processing, the usual 304 checks are done, so if
413
     * your page doesn't change in respect of E-Tag and Last-Modified, only a 304
414
     * Not Modified reaches the client.
415
     *
416
     * Essentially, no_cache behaves the same way as if the uncached configuration
417
     * directive is set to true, it is just limited to a single request.
418
     *
419
     * If you need a higher level of client side security, to avoid storage of sensitive
420
     * information on the client side, you should use no_cache instead.
421
     *
422
     * @see no_cache()
423
     */
424 3
    public function uncached(bool $uncached = true)
425
    {
426 3
        $this->_uncached = $uncached;
427 3
    }
428
429
    /**
430
     * Sets the content type for the current page. The required HTTP Headers for
431
     * are automatically generated, so, to the contrary of expires, you just have
432
     * to set this header accordingly.
433
     *
434
     * This is usually set automatically by MidCOM for all regular HTML output and
435
     * for all attachment deliveries. You have to adapt it only for things like RSS
436
     * output.
437
     */
438 8
    public function content_type(string $type)
439
    {
440 8
        midcom::get()->header('Content-Type: ' . $type);
441 8
    }
442
443
    /**
444
     * Put the cache into a "live mode". This will disable the
445
     * cache during runtime, correctly flushing the output buffer (if it's not empty)
446
     * and sending cache control headers.
447
     *
448
     * The midcom-exec URL handler of the core will automatically enable live mode.
449
     *
450
     * @see midcom_application::_exec_file()
451
     */
452
    public function enable_live_mode()
453
    {
454
        $this->no_cache();
455
        Response::closeOutputBuffers(0, ob_get_length() > 0);
456
    }
457
458
    /**
459
     * Store a sent header into the cache database, so that it will
460
     * be resent when the cache page is delivered. midcom_application::header()
461
     * will automatically call this function, you need to do this only if you use
462
     * the PHP header function.
463
     */
464 17
    public function register_sent_header(string $header)
465
    {
466 17
        if (str_contains($header, ': ')) {
467 17
            [$header, $value] = explode(': ', $header, 2);
468 17
            $this->_sent_headers[$header] = $value;
469
        }
470 17
    }
471
472
    /**
473
     * Looks for list of content and request identifiers paired with the given guid
474
     * and removes all of those from the caches.
475
     *
476
     * {@inheritDoc}
477
     */
478 303
    public function invalidate(string $guid, $object = null)
479
    {
480 303
        $guidmap = $this->backend->getItem($guid);
481 303
        if (!$guidmap->isHit()) {
482 303
            debug_add("No entry for {$guid} in meta cache, ignoring invalidation request.");
483 303
            return;
484
        }
485
486
        foreach ($guidmap->get() as $content_id) {
487
            $this->backend->delete($content_id);
0 ignored issues
show
Bug introduced by
The method delete() does not exist on Symfony\Component\Cache\Adapter\AdapterInterface. Did you maybe mean deleteItem()? ( Ignorable by Annotation )

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

487
            $this->backend->/** @scrutinizer ignore-call */ 
488
                            delete($content_id);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
488
            $this->_data_cache->delete($content_id);
489
        }
490
    }
491
492
    public function invalidate_all()
493
    {
494
        parent::invalidate_all();
495
        $this->_data_cache->clear();
496
    }
497
498
    /**
499
     * All objects loaded within a request are stored into a list for cache invalidation purposes
500
     */
501 392
    public function register(string $guid)
502
    {
503
        // Check for uncached operation
504 392
        if ($this->_uncached) {
505 392
            return;
506
        }
507
508
        $context = midcom_core_context::get()->id;
509
        if ($context != 0) {
510
            // We're in a dynamic_load, register it for that as well
511
            if (!isset($this->context_guids[$context])) {
512
                $this->context_guids[$context] = [];
513
            }
514
            $this->context_guids[$context][] = $guid;
515
        }
516
517
        // Register all GUIDs also to the root context
518
        if (!isset($this->context_guids[0])) {
519
            $this->context_guids[0] = [];
520
        }
521
        $this->context_guids[0][] = $guid;
522
    }
523
524
    /**
525
     * Writes meta-cache entry from context data using given content id
526
     * Used to be part of on_request, but needed by serve-attachment method in midcom_core_urlmethods as well
527
     */
528 1
    public function write_meta_cache(string $content_id, Request $request, Response $response)
529
    {
530 1
        if (   $this->_uncached
531 1
            || $this->_no_cache) {
532
            return;
533
        }
534
535
        // Construct cache identifier
536 1
        $request_id = $this->generate_request_identifier($request);
537
538 1
        $item = $this->backend->getItem($request_id);
539 1
        $this->backend->save($item->set($content_id));
540 1
        $item2 = $this->backend->getItem($content_id);
541 1
        $this->backend->save($item2->set($response->headers->all()));
542
543
        // Cache where the object have been
544 1
        $context = midcom_core_context::get()->id;
545 1
        $this->store_context_guid_map($context, $content_id, $request_id);
546 1
    }
547
548 1
    private function store_context_guid_map(int $context, string $content_id, string $request_id)
549
    {
550
        // non-existent context
551 1
        if (!array_key_exists($context, $this->context_guids)) {
552 1
            return;
553
        }
554
555
        $maps = $this->backend->getItems($this->context_guids[$context]);
556
        $to_save = [];
557
        foreach ($this->context_guids[$context] as $guid) {
558
            $guidmap = $maps[$guid]->get() ?? [];
559
560
            if (!in_array($content_id, $guidmap)) {
561
                $guidmap[] = $content_id;
562
                $to_save[$guid] = $maps[$guid]->set($guidmap);
563
            }
564
565
            if (!in_array($request_id, $guidmap)) {
566
                $guidmap[] = $request_id;
567
                $to_save[$guid] = $maps[$guid]->set($guidmap);
568
            }
569
        }
570
571
        foreach ($to_save as $item) {
572
            $this->backend->save($item);
573
        }
574
    }
575
576 16
    public function check_dl_hit(Request $request)
577
    {
578 16
        if ($this->_no_cache) {
579 16
            return false;
580
        }
581
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
582
        $dl_content_id = $this->backend->getItem($dl_request_id);
583
        if (!$dl_content_id->isHit()) {
584
            return false;
585
        }
586
587
        return $this->_data_cache->getItem($dl_content_id->get())->get();
588
    }
589
590 4
    public function store_dl_content(int $context, string $dl_cache_data, Request $request)
591
    {
592 4
        if (   $this->_no_cache
593 4
            || $this->_uncached) {
594 4
            return;
595
        }
596
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
597
        $dl_content_id = 'DLC-' . md5($dl_cache_data);
598
599
        $item = $this->backend->getItem($dl_request_id)
600
            ->set($dl_content_id)
601
            ->expiresAfter($this->_default_lifetime);
602
        $this->backend->save($item);
603
        $item = $this->_data_cache->getItem($dl_content_id)
604
            ->set($dl_cache_data)
605
            ->expiresAfter($this->_default_lifetime);
606
        $this->_data_cache->save($item);
607
608
        // Cache where the object have been
609
        $this->store_context_guid_map($context, $dl_content_id, $dl_request_id);
610
    }
611
612
    /**
613
     * This little helper ensures that the headers Content-Length
614
     * and Last-Modified are present. The lastmod timestamp is taken out of the
615
     * component context information if it is populated correctly there; if not, the
616
     * system time is used instead.
617
     *
618
     * To force browsers to revalidate the page on every request (login changes would
619
     * go unnoticed otherwise), the Cache-Control header max-age=0 is added automatically.
620
     */
621 1
    private function complete_sent_headers(Response $response)
622
    {
623 1
        if (!$response->getLastModified()) {
624
            /* Determine Last-Modified using MidCOM's component context,
625
             * Fallback to time() if this fails.
626
             */
627 1
            $time = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_LASTMODIFIED) ?: time();
628 1
            $response->setLastModified(DateTime::createFromFormat('U', (string) $time));
629
        }
630
631
        /* TODO: Doublecheck the way this is handled, now we just don't send it
632
         * if headers_strategy implies caching */
633 1
        if (   !$response->headers->has('Content-Length')
634 1
            && !in_array($this->_headers_strategy, ['public', 'private'])) {
635 1
            $response->headers->set("Content-Length", strlen($response->getContent()));
636
        }
637
638 1
        $this->cache_control_headers($response);
639 1
    }
640
641 1
    public function cache_control_headers(Response $response)
642
    {
643
        // Just to be sure not to mess the headers sent by no_cache in case it was called
644 1
        if ($this->_no_cache) {
645
            $this->no_cache($response);
646
        } else {
647
            // Add Expiration and Cache Control headers
648 1
            $strategy = $this->_headers_strategy;
649 1
            $default_lifetime = $this->_default_lifetime;
650 1
            if (midcom::get()->auth->is_valid_user()) {
651
                $strategy = $this->_headers_strategy_authenticated;
652
                $default_lifetime = $this->_default_lifetime_authenticated;
653
            }
654
655 1
            $now = $expires = time();
656 1
            if ($strategy != 'revalidate') {
657
                $expires += $default_lifetime;
658
                if ($strategy == 'private') {
659
                    $response->setPrivate();
660
                } else {
661
                    $response->setPublic();
662
                }
663
            }
664 1
            $max_age = $expires - $now;
665
666
            $response
667 1
                ->setExpires(DateTime::createFromFormat('U', $expires))
668 1
                ->setMaxAge($max_age);
669 1
            if ($max_age == 0) {
670 1
                $response->headers->addCacheControlDirective('must-revalidate');
671
            }
672
        }
673 1
    }
674
}
675