Passed
Push — master ( 35700c...56e7b5 )
by Andreas
16:57
created

midcom_services_cache_module_content::expires()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 2
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
crap 12
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
15
/**
16
 * This is the Output Caching Engine of MidCOM. It will intercept page output,
17
 * map it using the currently used URL and use the cached output on subsequent
18
 * requests.
19
 *
20
 * <b>Important note for application developers</b>
21
 *
22
 * Please read the documentation of the following functions thoroughly:
23
 *
24
 * - midcom_services_cache_module_content::no_cache();
25
 * - midcom_services_cache_module_content::uncached();
26
 * - midcom_services_cache_module_content::expires();
27
 * - midcom_services_cache_module_content::invalidate_all();
28
 * - midcom_services_cache_module_content::content_type();
29
 * - midcom_services_cache_module_content::enable_live_mode();
30
 *
31
 * You have to use these functions everywhere where it is applicable or the cache
32
 * will not work reliably.
33
 *
34
 * <b>Caching strategy</b>
35
 *
36
 * The cache takes three parameters into account when storing in or retrieving from
37
 * the cache: The current User ID, the current language and the request's URL.
38
 *
39
 * Only on a complete match a cached page is displayed, which should take care of any
40
 * permission checks done on the page. When you change the permissions of users, you
41
 * need to manually invalidate the cache though, as MidCOM currently cannot detect
42
 * changes like this (of course, this is true if and only if you are not using a
43
 * MidCOM to change permissions).
44
 *
45
 * When the HTTP request is not cacheable, the caching engine will automatically and
46
 * transparently go into no_cache mode for that request only. This feature
47
 * does neither invalidate the cache or drop the page that would have been delivered
48
 * normally from the cache. If you change the content, you need to do that yourself.
49
 *
50
 * HTTP 304 Not Modified support is built into this module, and will send a 304 reply if applicable.
51
 *
52
 * <b>Module configuration (see also midcom_config)</b>
53
 *
54
 * - <i>string cache_module_content_name</i>: The name of the cache database to use. This should usually be tied to the actual
55
 *   MidCOM site to have exactly one cache per site. This is mandatory (and populated by a sensible default
56
 *   by midcom_config, see there for details).
57
 * - <i>boolean cache_module_content_uncached</i>: Set this to true to prevent the saving of cached pages. This is useful
58
 *   for development work, as all other headers (like E-Tag or Last-Modified) are generated
59
 *   normally. See the uncached() and _uncached members.
60
 *
61
 * @package midcom.services
62
 */
63
class midcom_services_cache_module_content extends midcom_services_cache_module
64
{
65
    /**
66
     * Flag, indicating whether the current page may be cached. If
67
     * false, the usual no-cache headers will be generated.
68
     *
69
     * @var boolean
70
     */
71
    private $_no_cache = false;
72
73
    /**
74
     * Page expiration in seconds. If null (unset), the page does
75
     * not expire.
76
     *
77
     * @var int
78
     */
79
    private $_expires;
80
81
    /**
82
     * An array storing all HTTP headers registered through register_sent_header().
83
     * They will be sent when a cached page is delivered.
84
     *
85
     * @var array
86
     */
87
    private $_sent_headers = [];
88
89
    /**
90
     * Set this to true if you want to inhibit storage of the generated pages in
91
     * the cache database. All other headers will be created as usual though, so
92
     * 304 processing will kick in for example.
93
     *
94
     * @var boolean
95
     */
96
    private $_uncached = false;
97
98
    /**
99
     * Controls cache headers strategy
100
     * 'no-cache' activates no-cache mode that actively tries to circumvent all caching
101
     * '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
102
     * 'public' and 'private' enable caching with the cache-control header of the same name, default expiry timestamps are generated using the default_lifetime
103
     *
104
     * @var string
105
     */
106
    private $_headers_strategy = 'revalidate';
107
108
    /**
109
     * Controls cache headers strategy for authenticated users, needed because some proxies store cookies, too,
110
     * making a horrible mess when used by mix of authenticated and non-authenticated users
111
     *
112
     * @see $_headers_strategy
113
     * @var string
114
     */
115
    private $_headers_strategy_authenticated = 'private';
116
117
    /**
118
     * Default lifetime of page for public/private headers strategy
119
     * When generating the default expires header this is added to time().
120
     *
121
     * @var int
122
     */
123
    private $_default_lifetime = 0;
124
125
    /**
126
     * Default lifetime of page for public/private headers strategy for authenticated users
127
     *
128
     * @see $_default_lifetime
129
     * @var int
130
     */
131
    private $_default_lifetime_authenticated = 0;
132
133
    /**
134
     * Cache backend instance.
135
     *
136
     * @var Doctrine\Common\Cache\CacheProvider
137
     */
138
    private $_meta_cache;
139
140
    /**
141
     * A cache backend used to store the actual cached pages.
142
     *
143
     * @var Doctrine\Common\Cache\CacheProvider
144
     */
145
    private $_data_cache;
146
147
    /**
148
     * GUIDs loaded per context in this request
149
     */
150
    private $context_guids = [];
151
152
    /**
153
     * @var midcom_config
154
     */
155
    private $config;
156
157
    /**
158
     * Initialize the cache.
159
     *
160
     * The first step is to initialize the cache backends. The names of the
161
     * cache backends used for meta and data storage are derived from the name
162
     * defined for this module (see the 'name' configuration parameter above).
163
     * The name is used directly for the meta data cache, while the actual data
164
     * is stored in a backend postfixed with '_data'.
165
     *
166
     * After core initialization, the module checks for a cache hit (which might
167
     * trigger the delivery of the cached page and exit) and start the output buffer
168
     * afterwards.
169
     */
170 1
    public function __construct(midcom_config $config)
171
    {
172 1
        parent::__construct();
173 1
        $this->config = $config;
174 1
        $backend_config = $config->get('cache_module_content_backend');
175 1
        if (!isset($backend_config['directory'])) {
176 1
            $backend_config['directory'] = 'content/';
177
        }
178 1
        if (!isset($backend_config['driver'])) {
179
            $backend_config['driver'] = 'null';
180
        }
181
182 1
        $this->_meta_cache = $this->_create_backend('content_meta', $backend_config);
183 1
        $this->_data_cache = $this->_create_backend('content_data', $backend_config);
184
185 1
        $this->_uncached = $config->get('cache_module_content_uncached');
186 1
        $this->_headers_strategy = $this->get_strategy('cache_module_content_headers_strategy');
187 1
        $this->_headers_strategy_authenticated = $this->get_strategy('cache_module_content_headers_strategy_authenticated');
188 1
        $this->_default_lifetime = (int)$config->get('cache_module_content_default_lifetime');
189 1
        $this->_default_lifetime_authenticated = (int)$config->get('cache_module_content_default_lifetime_authenticated');
190
191 1
        if ($this->_headers_strategy == 'no-cache') {
192
            // we can't call no_cache() here, because it would try to call back to this class via the global getter
193
            $header = 'Cache-Control: no-store, no-cache, must-revalidate';
194
            $this->register_sent_header($header);
195
            midcom_compat_environment::get()->header($header);
196
            $this->_no_cache = true;
197
        }
198 1
    }
199
200
    /**
201
     * @param RequestEvent $event
202
     */
203 338
    public function on_request(RequestEvent $event)
204
    {
205 338
        if ($event->isMasterRequest()) {
206 1
            $request = $event->getRequest();
207
            /* Load and start up the cache system, this might already end the request
208
             * on a content cache hit. Note that the cache check hit depends on the i18n and auth code.
209
             */
210 1
            if ($response = $this->_check_hit($request)) {
211 1
                $event->setResponse($response);
212
            }
213
        }
214 338
    }
215
216
    /**
217
     * This function holds the cache hit check mechanism. It searches the requested
218
     * URL in the cache database. If found, it checks, whether the cache page has
219
     * expired. If not, the response is returned. In all other cases this method simply
220
     * returns void.
221
     *
222
     * The midcom-cache URL methods are handled before checking for a cache hit.
223
     *
224
     * Also, any HTTP POST request will automatically circumvent the cache so that
225
     * any component can process the request. It will set no_cache automatically
226
     * to avoid any cache pages being overwritten by, for example, search results.
227
     *
228
     * Note, that HTTP GET is <b>not</b> checked this way, as GET requests can be
229
     * safely distinguished by their URL.
230
     *
231
     * @param Request $request The request object
232
     * @return void|Response
233
     */
234 1
    private function _check_hit(Request $request)
235
    {
236 1
        foreach (midcom_connection::get_url('argv') as $arg) {
237 1
            if (in_array($arg, ["midcom-cache-invalidate", "midcom-cache-nocache"])) {
238
                // Don't cache these.
239
                debug_add("uncached: $arg");
240
                return;
241
            }
242
        }
243
244 1
        if (!$request->isMethodCacheable()) {
245
            debug_add('Request method is not cacheable, setting no_cache');
246
            $this->no_cache();
247
            return;
248
        }
249
250
        // Check for uncached operation
251 1
        if ($this->_uncached) {
252
            debug_add("Uncached mode");
253
            return;
254
        }
255
256
        // Check that we have cache for the identifier
257 1
        $request_id = $this->generate_request_identifier($request);
258
        // Load metadata for the content identifier connected to current request
259 1
        $content_id = $this->_meta_cache->fetch($request_id);
260 1
        if ($content_id === false) {
261 1
            debug_add("MISS {$request_id}");
262
            // We have no information about content cached for this request
263 1
            return;
264
        }
265 1
        debug_add("HIT {$request_id}");
266
267 1
        $data = $this->_meta_cache->fetch($content_id);
268 1
        if ($data === false) {
269
            debug_add("MISS meta_cache {$content_id}");
270
            // Content cache data is missing
271
            return;
272
        }
273
274 1
        if (!isset($data['last-modified'])) {
275
            debug_add('Current page is in cache, but has insufficient information', MIDCOM_LOG_INFO);
276
            return;
277
        }
278
279 1
        debug_add("HIT {$content_id}");
280
281 1
        $response = new Response('', Response::HTTP_OK, $data);
282 1
        if (!$response->isNotModified($request)) {
283 1
            $content = $this->_data_cache->fetch($content_id);
284 1
            if ($content === false) {
285
                debug_add("Current page is in not in the data cache, possible ghost read.", MIDCOM_LOG_WARN);
286
                return;
287
            }
288 1
            $response->setContent($content);
289
        }
290
        // disable cache writing in on_response
291 1
        $this->_no_cache = true;
292 1
        return $response;
293
    }
294
295
    /**
296
     * This completes the output caching, post-processes it and updates the cache databases accordingly.
297
     *
298
     * The first step is to check against _no_cache pages, which will be delivered immediately
299
     * without any further post processing. Afterwards, the system will complete the sent
300
     * headers by adding all missing headers. Note, that E-Tag will be generated always
301
     * automatically, you must not set this in your component.
302
     *
303
     * If the midcom configuration option cache_uncached is set or the corresponding runtime function
304
     * has been called, the cache file will not be written, but the header stuff will be added like
305
     * usual to allow for browser-side caching.
306
     *
307
     * @param ResponseEvent $event The request object
308
     */
309 339
    public function on_response(ResponseEvent $event)
310
    {
311 339
        if (!$event->isMasterRequest()) {
312 338
            return;
313
        }
314 1
        $response = $event->getResponse();
315 1
        if ($response instanceof BinaryFileResponse) {
316
            return;
317
        }
318 1
        foreach ($this->_sent_headers as $header => $value) {
319
            // This can happen in streamed responses which enable_live_mode
320
            if (!headers_sent()) {
321
                header_remove($header);
322
            }
323
            $response->headers->set($header, $value);
324
        }
325 1
        $request = $event->getRequest();
326 1
        if ($this->_no_cache) {
327
            $response->prepare($request);
328
            return;
329
        }
330
331 1
        $cache_data = $response->getContent();
332
333
        // Register additional Headers around the current output request
334 1
        $this->complete_sent_headers($response);
335 1
        $response->prepare($request);
336
337
        // Generate E-Tag header.
338 1
        if (empty($cache_data)) {
339
            $etag = md5(serialize($response->headers->all()));
340
        } else {
341 1
            $etag = md5($cache_data);
342
        }
343 1
        $response->setEtag($etag);
344
345 1
        if ($this->_uncached) {
346
            debug_add('Not writing cache file, we are in uncached operation mode.');
347
            return;
348
        }
349 1
        $content_id = 'C-' . $etag;
350 1
        $this->write_meta_cache($content_id, $request, $response);
351 1
        $this->_data_cache->save($content_id, $cache_data);
352 1
    }
353
354
    /**
355
     * Generate a valid cache identifier for a context of the current request
356
     */
357 1
    private function generate_request_identifier(Request $request) : string
358
    {
359 1
        $context = $request->attributes->get('context')->id;
360
        // Cache the request identifier so that it doesn't change between start and end of request
361 1
        static $identifier_cache = [];
362 1
        if (isset($identifier_cache[$context])) {
363 1
            return $identifier_cache[$context];
364
        }
365
366 1
        $module_name = $this->config->get('cache_module_content_name');
367 1
        if ($module_name == 'auto') {
368 1
            $module_name = midcom_connection::get_unique_host_name();
369
        }
370 1
        $identifier_source = 'CACHE:' . $module_name;
371
372 1
        $cache_strategy = $this->config->get('cache_module_content_caching_strategy');
373
374 1
        switch ($cache_strategy) {
375 1
            case 'memberships':
376
                if (!midcom_connection::get_user()) {
377
                    $identifier_source .= ';USER=ANONYMOUS';
378
                    break;
379
                }
380
                $mc = new midgard_collector('midgard_member', 'uid', midcom_connection::get_user());
381
                $mc->set_key_property('gid');
382
                $mc->execute();
383
                $gids = $mc->list_keys();
384
                $identifier_source .= ';GROUPS=' . implode(',', array_keys($gids));
385
                break;
386 1
            case 'public':
387
                $identifier_source .= ';USER=EVERYONE';
388
                break;
389 1
            case 'user':
390
            default:
391 1
                $identifier_source .= ';USER=' . midcom_connection::get_user();
392 1
                break;
393
        }
394
395 1
        $identifier_source .= ';URL=' . $request->getRequestUri();
396 1
        debug_add("Generating context {$context} request-identifier from: {$identifier_source}");
397
398 1
        $identifier_cache[$context] = 'R-' . md5($identifier_source);
399 1
        return $identifier_cache[$context];
400
    }
401
402 1
    private function get_strategy(string $name) : string
403
    {
404 1
        $strategy = strtolower($this->config->get($name));
405 1
        $allowed = ['no-cache', 'revalidate', 'public', 'private'];
406 1
        if (!in_array($strategy, $allowed)) {
407
            throw new midcom_error($name . ' is not valid, try ' . implode(', ', $allowed));
408
        }
409 1
        return $strategy;
410
    }
411
412
    /**
413
     * Call this, if the currently processed output must not be cached for any
414
     * reason. Dynamic pages with sensitive content are a candidate for this
415
     * function.
416
     *
417
     * Note, that this will prevent <i>any</i> content invalidation related headers
418
     * like E-Tag to be generated automatically, and that the appropriate
419
     * no-store/no-cache headers from HTTP 1.1 and HTTP 1.0 will be sent automatically.
420
     * This means that there will also be no 304 processing.
421
     *
422
     * You should use this only for sensitive content. For simple dynamic output,
423
     * you are strongly encouraged to use the less strict uncached() function.
424
     *
425
     * @see uncached()
426
     */
427 191
    public function no_cache(Response $response = null)
428
    {
429 191
        $settings = 'no-store, no-cache, must-revalidate';
430
        // PONDER: Send expires header (set to long time in past) as well ??
431
432 191
        if ($response) {
433
            $response->headers->set('Cache-Control', $settings);
434 191
        } elseif (!$this->_no_cache) {
435
            if (headers_sent()) {
436
                debug_add('Warning, we should move to no_cache but headers have already been sent, skipping header transmission.', MIDCOM_LOG_ERROR);
437
            } else {
438
                midcom::get()->header('Cache-Control: ' . $settings);
439
            }
440
        }
441 191
        $this->_no_cache = true;
442 191
    }
443
444
    /**
445
     * Call this, if the currently processed output must not be cached for any
446
     * reason. Dynamic pages or form processing results are the usual candidates
447
     * for this mode.
448
     *
449
     * Note, that this will still keep the caching engine active so that it can
450
     * add the usual headers (ETag, Expires ...) in respect to the no_cache flag.
451
     * As well, at the end of the processing, the usual 304 checks are done, so if
452
     * your page doesn't change in respect of E-Tag and Last-Modified, only a 304
453
     * Not Modified reaches the client.
454
     *
455
     * Essentially, no_cache behaves the same way as if the uncached configuration
456
     * directive is set to true, it is just limited to a single request.
457
     *
458
     * If you need a higher level of client side security, to avoid storage of sensitive
459
     * information on the client side, you should use no_cache instead.
460
     *
461
     * @see no_cache()
462
     */
463 3
    public function uncached(bool $uncached = true)
464
    {
465 3
        $this->_uncached = $uncached;
466 3
    }
467
468
    /**
469
     * Sets the expiration time of the current page (Unix (GMT) Timestamp).
470
     *
471
     * <b>Note:</B> This generate error call will add browser-side cache control
472
     * headers as well to force a browser to revalidate a page after the set
473
     * expiry.
474
     *
475
     * You should call this at all places where you have timed content in your
476
     * output, so that the page will be regenerated once a certain article has
477
     * expired.
478
     *
479
     * Multiple calls to expires will only save the
480
     * "youngest" timestamp, so you can safely call expires where appropriate
481
     * without respect to other values.
482
     *
483
     * The cache's default (null) will disable the expires header. Note, that once
484
     * an expiry time on a page has been set, it is not possible, to reset it again,
485
     * this is for dynamic_load situation, where one component might depend on a
486
     * set expiry.
487
     *
488
     * @param int $timestamp The UNIX timestamp from which the cached page should be invalidated.
489
     */
490
    public function expires($timestamp)
491
    {
492
        if (   $this->_expires === null
493
            || $this->_expires > $timestamp) {
494
            $this->_expires = $timestamp;
495
        }
496
    }
497
498
    /**
499
     * Sets the content type for the current page. The required HTTP Headers for
500
     * are automatically generated, so, to the contrary of expires, you just have
501
     * to set this header accordingly.
502
     *
503
     * This is usually set automatically by MidCOM for all regular HTML output and
504
     * for all attachment deliveries. You have to adapt it only for things like RSS
505
     * output.
506
     *
507
     * @param string $type    The content type to use.
508
     */
509 8
    public function content_type($type)
510
    {
511 8
        midcom::get()->header('Content-Type: ' . $type);
512 8
    }
513
514
    /**
515
     * Put the cache into a "live mode". This will disable the
516
     * cache during runtime, correctly flushing the output buffer (if it's not empty)
517
     * and sending cache control headers.
518
     *
519
     * The midcom-exec URL handler of the core will automatically enable live mode.
520
     *
521
     * @see midcom_application::_exec_file()
522
     */
523
    public function enable_live_mode()
524
    {
525
        $this->no_cache();
526
        Response::closeOutputBuffers(0, ob_get_length() > 0);
527
    }
528
529
    /**
530
     * Store a sent header into the cache database, so that it will
531
     * be resent when the cache page is delivered. midcom_application::header()
532
     * will automatically call this function, you need to do this only if you use
533
     * the PHP header function.
534
     *
535
     * @param string $header The header that was sent.
536
     */
537 17
    public function register_sent_header($header)
538
    {
539 17
        if (strpos($header, ': ') !== false) {
540 17
            list($header, $value) = explode(': ', $header, 2);
541 17
            $this->_sent_headers[$header] = $value;
542
        }
543 17
    }
544
545
    /**
546
     * Looks for list of content and request identifiers paired with the given guid
547
     * and removes all of those from the caches.
548
     *
549
     * {@inheritDoc}
550
     */
551 288
    public function invalidate($guid, $object = null)
552
    {
553 288
        $guidmap = $this->_meta_cache->fetch($guid);
554 288
        if ($guidmap === false) {
555 288
            debug_add("No entry for {$guid} in meta cache, ignoring invalidation request.");
556 288
            return;
557
        }
558
559
        foreach ($guidmap as $content_id) {
560
            if ($this->_meta_cache->contains($content_id)) {
561
                $this->_meta_cache->delete($content_id);
562
            }
563
564
            if ($this->_data_cache->contains($content_id)) {
565
                $this->_data_cache->delete($content_id);
566
            }
567
        }
568
    }
569
570
    /**
571
     * All objects loaded within a request are stored into a list for cache invalidation purposes
572
     */
573 394
    public function register($guid)
574
    {
575
        // Check for uncached operation
576 394
        if ($this->_uncached) {
577 394
            return;
578
        }
579
580
        $context = midcom_core_context::get()->id;
581
        if ($context != 0) {
582
            // We're in a dynamic_load, register it for that as well
583
            if (!isset($this->context_guids[$context])) {
584
                $this->context_guids[$context] = [];
585
            }
586
            $this->context_guids[$context][] = $guid;
587
        }
588
589
        // Register all GUIDs also to the root context
590
        if (!isset($this->context_guids[0])) {
591
            $this->context_guids[0] = [];
592
        }
593
        $this->context_guids[0][] = $guid;
594
    }
595
596
    /**
597
     * Writes meta-cache entry from context data using given content id
598
     * Used to be part of on_request, but needed by serve-attachment method in midcom_core_urlmethods as well
599
     */
600 1
    public function write_meta_cache($content_id, Request $request, Response $response)
601
    {
602 1
        if (   $this->_uncached
603 1
            || $this->_no_cache) {
604
            return;
605
        }
606
607 1
        if ($this->_expires !== null) {
608
            $lifetime = $this->_expires - time();
609
        } else {
610
            // Use default expiry for cache entry, most components don't bother calling expires() properly
611 1
            $lifetime = $this->_default_lifetime;
612
        }
613
614
        // Construct cache identifier
615 1
        $request_id = $this->generate_request_identifier($request);
616
617
        $entries = [
618 1
            $request_id => $content_id,
619 1
            $content_id => $response->headers->all()
620
        ];
621 1
        $this->_meta_cache->saveMultiple($entries, $lifetime);
622
623
        // Cache where the object have been
624 1
        $context = midcom_core_context::get()->id;
625 1
        $this->store_context_guid_map($context, $content_id, $request_id);
626 1
    }
627
628 1
    private function store_context_guid_map($context, string $content_id, string $request_id)
629
    {
630
        // non-existent context
631 1
        if (!array_key_exists($context, $this->context_guids)) {
632 1
            return;
633
        }
634
635
        $maps = $this->_meta_cache->fetchMultiple($this->context_guids[$context]);
636
        $to_save = [];
637
        foreach ($this->context_guids[$context] as $guid) {
638
            // Getting old map from cache or create new, empty one
639
            $guidmap = $maps[$guid] ?? [];
640
641
            if (!in_array($content_id, $guidmap)) {
642
                $guidmap[] = $content_id;
643
                $to_save[$guid] = $guidmap;
644
            }
645
646
            if (!in_array($request_id, $guidmap)) {
647
                $guidmap[] = $request_id;
648
                $to_save[$guid] = $guidmap;
649
            }
650
        }
651
652
        $this->_meta_cache->saveMultiple($to_save);
653
    }
654
655 16
    public function check_dl_hit(Request $request)
656
    {
657 16
        if ($this->_no_cache) {
658 16
            return false;
659
        }
660
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
661
        $dl_content_id = $this->_meta_cache->fetch($dl_request_id);
662
        if ($dl_content_id === false) {
663
            return false;
664
        }
665
666
        return $this->_data_cache->fetch($dl_content_id);
667
    }
668
669 4
    public function store_dl_content($context, $dl_cache_data, Request $request)
670
    {
671 4
        if (   $this->_no_cache
672 4
            || $this->_uncached) {
673 4
            return;
674
        }
675
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
676
        $dl_content_id = 'DLC-' . md5($dl_cache_data);
677
678
        if ($this->_expires !== null) {
679
            $lifetime = $this->_expires - time();
680
        } else {
681
            // Use default expiry for cache entry, most components don't bother calling expires() properly
682
            $lifetime = $this->_default_lifetime;
683
        }
684
        $this->_meta_cache->save($dl_request_id, $dl_content_id, $lifetime);
685
        $this->_data_cache->save($dl_content_id, $dl_cache_data, $lifetime);
686
        // Cache where the object have been
687
        $this->store_context_guid_map($context, $dl_content_id, $dl_request_id);
688
    }
689
690
    /**
691
     * This little helper ensures that the headers Content-Length
692
     * and Last-Modified are present. The lastmod timestamp is taken out of the
693
     * component context information if it is populated correctly there; if not, the
694
     * system time is used instead.
695
     *
696
     * To force browsers to revalidate the page on every request (login changes would
697
     * go unnoticed otherwise), the Cache-Control header max-age=0 is added automatically.
698
     */
699 1
    private function complete_sent_headers(Response $response)
700
    {
701 1
        if ($date = $response->getLastModified()) {
702
            if ((int) $date->format('U') == -1) {
703
                debug_add("Failed to extract the timecode from the last modified header, defaulting to the current time.", MIDCOM_LOG_WARN);
704
                $response->setLastModified(new DateTime);
705
            }
706
        } else {
707
            /* Determine Last-Modified using MidCOM's component context,
708
             * Fallback to time() if this fails.
709
             */
710 1
            $time = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_LASTMODIFIED) ?: time();
711 1
            $response->setLastModified(DateTime::createFromFormat('U', (string) $time));
0 ignored issues
show
Bug introduced by
It seems like DateTime::createFromFormat('U', (string)$time) can also be of type false; however, parameter $date of Symfony\Component\HttpFo...onse::setLastModified() does only seem to accept DateTimeInterface|null, 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

711
            $response->setLastModified(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', (string) $time));
Loading history...
712
        }
713
714 1
        if (!$response->headers->has('Content-Length')) {
715
            /* TODO: Doublecheck the way this is handled, now we just don't send it
716
             * if headers_strategy implies caching */
717 1
            if (!in_array($this->_headers_strategy, ['public', 'private'])) {
718 1
                $response->headers->set("Content-Length", strlen($response->getContent()));
719
            }
720
        }
721
722 1
        $this->cache_control_headers($response);
723 1
    }
724
725
    /**
726
     * @param Response $response
727
     */
728 1
    public function cache_control_headers(Response $response)
729
    {
730
        // Just to be sure not to mess the headers sent by no_cache in case it was called
731 1
        if ($this->_no_cache) {
732
            $this->no_cache($response);
733
        } else {
734
            // Add Expiration and Cache Control headers
735 1
            $strategy = $this->_headers_strategy;
736 1
            $default_lifetime = $this->_default_lifetime;
737 1
            if (   midcom::get()->auth->is_valid_user()
738 1
                || midcom_connection::get_user()) {
739
                $strategy = $this->_headers_strategy_authenticated;
740
                $default_lifetime = $this->_default_lifetime_authenticated;
741
            }
742
743 1
            $now = time();
744 1
            if ($strategy == 'revalidate') {
745
                // If expires is not set, we force the client to revalidate every time.
746
                // The timeout of a content cache entry is not affected by this.
747 1
                $expires = $this->_expires ?? $now;
748
            } else {
749
                $expires = $this->_expires ?? $now + $default_lifetime;
750
                if ($strategy == 'private') {
751
                    $response->setPrivate();
752
                } else {
753
                    $response->setPublic();
754
                }
755
            }
756 1
            $max_age = $expires - $now;
757
758
            $response
759 1
                ->setExpires(DateTime::createFromFormat('U', $expires))
0 ignored issues
show
Bug introduced by
It seems like DateTime::createFromFormat('U', $expires) can also be of type false; however, parameter $date of Symfony\Component\HttpFo...\Response::setExpires() does only seem to accept DateTimeInterface|null, 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

759
                ->setExpires(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $expires))
Loading history...
760 1
                ->setMaxAge($max_age);
761 1
            if ($max_age == 0) {
762 1
                $response->headers->addCacheControlDirective('must-revalidate');
763
            }
764
        }
765 1
    }
766
}
767