Passed
Push — master ( 671601...c4a055 )
by Andreas
16:47
created

__construct()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 26
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 4.1492

Importance

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

703
            $response->setLastModified(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', (string) $time));
Loading history...
704
        }
705
706 1
        if (!$response->headers->has('Content-Length')) {
707
            /* TODO: Doublecheck the way this is handled, now we just don't send it
708
             * if headers_strategy implies caching */
709 1
            if (!in_array($this->_headers_strategy, ['public', 'private'])) {
710 1
                $response->headers->set("Content-Length", strlen($response->getContent()));
711
            }
712
        }
713
714 1
        $this->cache_control_headers($response);
715 1
    }
716
717
    /**
718
     * @param Response $response
719
     */
720 1
    public function cache_control_headers(Response $response)
721
    {
722
        // Just to be sure not to mess the headers sent by no_cache in case it was called
723 1
        if ($this->_no_cache) {
724
            $this->no_cache($response);
725
        } else {
726
            // Add Expiration and Cache Control headers
727 1
            $strategy = $this->_headers_strategy;
728 1
            $default_lifetime = $this->_default_lifetime;
729 1
            if (   midcom::get()->auth->is_valid_user()
730 1
                || midcom_connection::get_user()) {
731
                $strategy = $this->_headers_strategy_authenticated;
732
                $default_lifetime = $this->_default_lifetime_authenticated;
733
            }
734
735 1
            $now = time();
736 1
            if ($strategy == 'revalidate') {
737
                // If expires is not set, we force the client to revalidate every time.
738
                // The timeout of a content cache entry is not affected by this.
739 1
                $expires = $this->_expires ?? $now;
740
            } else {
741
                $expires = $this->_expires ?? $now + $default_lifetime;
742
                if ($strategy == 'private') {
743
                    $response->setPrivate();
744
                } else {
745
                    $response->setPublic();
746
                }
747
            }
748 1
            $max_age = $expires - $now;
749
750
            $response
751 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

751
                ->setExpires(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $expires))
Loading history...
752 1
                ->setMaxAge($max_age);
753 1
            if ($max_age == 0) {
754 1
                $response->headers->addCacheControlDirective('must-revalidate');
755
            }
756
        }
757 1
    }
758
}
759