Completed
Push — master ( 114248...e6666d )
by Andreas
14:02
created

complete_sent_headers()   B

Complexity

Conditions 9
Paths 54

Size

Total Lines 43
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9.648

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 24
nc 54
nop 1
dl 0
loc 43
ccs 20
cts 25
cp 0.8
crap 9.648
rs 8.0555
c 1
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\HttpKernel\Event\GetResponseEvent;
12
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
13
use Symfony\Component\HttpFoundation\BinaryFileResponse;
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
     * The time of the last modification, set during auto-header-completion.
83
     *
84
     * @var int
85
     */
86
    private $_last_modified = 0;
87
88
    /**
89
     * An array storing all HTTP headers registered through register_sent_header().
90
     * They will be sent when a cached page is delivered.
91
     *
92
     * @var array
93
     */
94
    private $_sent_headers = [];
95
96
    /**
97
     * The MIME content-type of the current request. It defaults to text/html, but
98
     * must be set correctly, so that the client gets the correct type delivered
99
     * upon cache deliveries.
100
     *
101
     * @var string
102
     */
103
    private $_content_type = 'text/html';
104
105
    /**
106
     * Set this to true if you want to inhibit storage of the generated pages in
107
     * the cache database. All other headers will be created as usual though, so
108
     * 304 processing will kick in for example.
109
     *
110
     * @var boolean
111
     */
112
    private $_uncached = false;
113
114
    /**
115
     * Controls cache headers strategy
116
     * 'no-cache' activates no-cache mode that actively tries to circumvent all caching
117
     * '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
118
     * 'public' and 'private' enable caching with the cache-control header of the same name, default expiry timestamps are generated using the default_lifetime
119
     *
120
     * @var string
121
     */
122
    private $_headers_strategy = 'revalidate';
123
124
    /**
125
     * Controls cache headers strategy for authenticated users, needed because some proxies store cookies, too,
126
     * making a horrible mess when used by mix of authenticated and non-authenticated users
127
     *
128
     * @see $_headers_strategy
129
     * @var string
130
     */
131
    private $_headers_strategy_authenticated = 'private';
132
133
    /**
134
     * Default lifetime of page for public/private headers strategy
135
     * When generating the default expires header this is added to time().
136
     *
137
     * @var int
138
     */
139
    private $_default_lifetime = 0;
140
141
    /**
142
     * Default lifetime of page for public/private headers strategy for authenticated users
143
     *
144
     * @see $_default_lifetime
145
     * @var int
146
     */
147
    private $_default_lifetime_authenticated = 0;
148
149
    /**
150
     * Cache backend instance.
151
     *
152
     * @var Doctrine\Common\Cache\CacheProvider
153
     */
154
    private $_meta_cache;
155
156
    /**
157
     * A cache backend used to store the actual cached pages.
158
     *
159
     * @var Doctrine\Common\Cache\CacheProvider
160
     */
161
    private $_data_cache;
162
163
    /**
164
     * GUIDs loaded per context in this request
165
     */
166
    private $context_guids = [];
167
168
    /**
169
     * @param GetResponseEvent $event
170
     */
171 338
    public function on_request(GetResponseEvent $event)
172
    {
173 338
        if ($event->isMasterRequest()) {
174 1
            $request = $event->getRequest();
175
            /* Load and start up the cache system, this might already end the request
176
             * on a content cache hit. Note that the cache check hit depends on the i18n and auth code.
177
             */
178 1
            if ($response = $this->_check_hit($request)) {
179 1
                $event->setResponse($response);
180
            }
181
        }
182 338
    }
183
184
    /**
185
     * This function holds the cache hit check mechanism. It searches the requested
186
     * URL in the cache database. If found, it checks, whether the cache page has
187
     * expired. If not, the response is returned. In all other cases this method simply
188
     * returns void.
189
     *
190
     * The midcom-cache URL methods are handled before checking for a cache hit.
191
     *
192
     * Also, any HTTP POST request will automatically circumvent the cache so that
193
     * any component can process the request. It will set no_cache automatically
194
     * to avoid any cache pages being overwritten by, for example, search results.
195
     *
196
     * Note, that HTTP GET is <b>not</b> checked this way, as GET requests can be
197
     * safely distinguished by their URL.
198
     *
199
     * @param Request $request The request object
200
     * @return void|Response
201
     */
202 1
    private function _check_hit(Request $request)
203
    {
204 1
        foreach (midcom_connection::get_url('argv') as $arg) {
205 1
            if (in_array($arg, ["midcom-cache-invalidate", "midcom-cache-nocache"])) {
206
                // Don't cache these.
207
                debug_add("uncached: $arg");
208 1
                return;
209
            }
210
        }
211
212 1
        if (!$request->isMethodCacheable()) {
213
            debug_add('Request method is not cacheable, setting no_cache');
214
            $this->no_cache();
215
            return;
216
        }
217
218
        // Check for uncached operation
219 1
        if ($this->_uncached) {
220
            debug_add("Uncached mode");
221
            return;
222
        }
223
224
        // Check that we have cache for the identifier
225 1
        $request_id = $this->generate_request_identifier($request);
226
        // Load metadata for the content identifier connected to current request
227 1
        $content_id = $this->_meta_cache->fetch($request_id);
228 1
        if ($content_id === false) {
229 1
            debug_add("MISS {$request_id}");
230
            // We have no information about content cached for this request
231 1
            return;
232
        }
233 1
        debug_add("HIT {$request_id}");
234
235 1
        $data = $this->_meta_cache->fetch($content_id);
236 1
        if ($data === false) {
237
            debug_add("MISS meta_cache {$content_id}");
238
            // Content cache data is missing
239
            return;
240
        }
241
242 1
        if (!isset($data['last_modified'])) {
243
            debug_add('Current page is in cache, but has insufficient information', MIDCOM_LOG_INFO);
244
            return;
245
        }
246
247 1
        debug_add("HIT {$content_id}");
248
249 1
        $response = new Response;
250 1
        $this->apply_headers($response, $data['sent_headers']);
251 1
        $response->setEtag($data['etag']);
252 1
        $response->setLastModified(DateTime::createFromFormat('U', $data['last_modified']));
0 ignored issues
show
Bug introduced by
It seems like DateTime::createFromForm...$data['last_modified']) can also be of type false; however, parameter $date of Symfony\Component\HttpFo...onse::setLastModified() does only seem to accept DateTime|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

252
        $response->setLastModified(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $data['last_modified']));
Loading history...
253 1
        if (!$response->isNotModified($request)) {
254 1
            $content = $this->_data_cache->fetch($content_id);
255 1
            if ($content === false) {
256
                debug_add("Current page is in not in the data cache, possible ghost read.", MIDCOM_LOG_WARN);
257
                return;
258
            }
259 1
            $response->setContent($content);
260
        }
261
        // disable cache writing in on_response
262 1
        $this->_no_cache = true;
263 1
        return $response;
264
    }
265
266
    /**
267
     * This completes the output caching, post-processes it and updates the cache databases accordingly.
268
     *
269
     * The first step is to check against _no_cache pages, which will be delivered immediately
270
     * without any further post processing. Afterwards, the system will complete the sent
271
     * headers by adding all missing headers. Note, that E-Tag will be generated always
272
     * automatically, you must not set this in your component.
273
     *
274
     * If the midcom configuration option cache_uncached is set or the corresponding runtime function
275
     * has been called, the cache file will not be written, but the header stuff will be added like
276
     * usual to allow for browser-side caching.
277
     *
278
     * @param FilterResponseEvent $event The request object
279
     */
280 339
    public function on_response(FilterResponseEvent $event)
281
    {
282 339
        if ($this->_no_cache || !$event->isMasterRequest()) {
283 338
            return;
284
        }
285 1
        $response = $event->getResponse();
286 1
        if ($response instanceof BinaryFileResponse) {
287
            return;
288
        }
289
290 1
        $request = $event->getRequest();
291 1
        $cache_data = $response->getContent();
292
293
        // Generate E-Tag header.
294 1
        if (empty($cache_data)) {
295
            $etag = md5(serialize($this->_sent_headers));
296
        } else {
297 1
            $etag = md5($cache_data);
298
        }
299
300 1
        $response->setEtag($etag);
301
302
        // Register additional Headers around the current output request
303
        // It has been sent already during calls to content_type
304 1
        $this->register_sent_header('Content-Type', $this->_content_type);
305 1
        $this->complete_sent_headers($response);
306
307 1
        $response->prepare($request);
308
309
        /**
310
         * WARNING:
311
         *   Stuff below here is executed *after* we have flushed output,
312
         *   so here we should only write out our caches but do nothing else
313
         */
314 1
         if ($this->_uncached) {
315
             debug_add('Not writing cache file, we are in uncached operation mode.');
316
             return;
317
         }
318 1
         $content_id = 'C-' . $etag;
319 1
         $this->write_meta_cache($content_id, $etag, $request);
320 1
         $this->_data_cache->save($content_id, $cache_data);
321 1
    }
322
323
    /**
324
     * Generate a valid cache identifier for a context of the current request
325
     */
326 1
    private function generate_request_identifier(Request $request)
327
    {
328 1
        $context = $request->attributes->get('context')->id;
329
        // Cache the request identifier so that it doesn't change between start and end of request
330 1
        static $identifier_cache = [];
331 1
        if (isset($identifier_cache[$context])) {
332 1
            return $identifier_cache[$context];
333
        }
334
335 1
        $module_name = midcom::get()->config->get('cache_module_content_name');
336 1
        if ($module_name == 'auto') {
337 1
            $module_name = midcom_connection::get_unique_host_name();
338
        }
339 1
        $identifier_source = 'CACHE:' . $module_name;
340
341 1
        $cache_strategy = midcom::get()->config->get('cache_module_content_caching_strategy');
342
343
        switch ($cache_strategy) {
344 1
            case 'memberships':
345
                if (!midcom_connection::get_user()) {
346
                    $identifier_source .= ';USER=ANONYMOUS';
347
                    break;
348
                }
349
                $mc = new midgard_collector('midgard_member', 'uid', midcom_connection::get_user());
350
                $mc->set_key_property('gid');
351
                $mc->execute();
352
                $gids = $mc->list_keys();
353
                $identifier_source .= ';GROUPS=' . implode(',', array_keys($gids));
354
                break;
355 1
            case 'public':
356
                $identifier_source .= ';USER=EVERYONE';
357
                break;
358 1
            case 'user':
359
            default:
360 1
                $identifier_source .= ';USER=' . midcom_connection::get_user();
361 1
                break;
362
        }
363
364 1
        $identifier_source .= ';URL=' . $request->getRequestUri();
365 1
        debug_add("Generating context {$context} request-identifier from: {$identifier_source}");
366
367 1
        $identifier_cache[$context] = 'R-' . md5($identifier_source);
368 1
        return $identifier_cache[$context];
369
    }
370
371
    /**
372
     * Initialize the cache.
373
     *
374
     * The first step is to initialize the cache backends. The names of the
375
     * cache backends used for meta and data storage are derived from the name
376
     * defined for this module (see the 'name' configuration parameter above).
377
     * The name is used directly for the meta data cache, while the actual data
378
     * is stored in a backend postfixed with '_data'.
379
     *
380
     * After core initialization, the module checks for a cache hit (which might
381
     * trigger the delivery of the cached page and exit) and start the output buffer
382
     * afterwards.
383
     */
384 1
    public function _on_initialize()
385
    {
386 1
        $backend_config = midcom::get()->config->get('cache_module_content_backend');
387 1
        if (!isset($backend_config['directory'])) {
388 1
            $backend_config['directory'] = 'content/';
389
        }
390 1
        if (!isset($backend_config['driver'])) {
391
            $backend_config['driver'] = 'null';
392
        }
393
394 1
        $this->_meta_cache = $this->_create_backend('content_meta', $backend_config);
395 1
        $this->_data_cache = $this->_create_backend('content_data', $backend_config);
396
397 1
        $this->_uncached = midcom::get()->config->get('cache_module_content_uncached');
398 1
        $this->_headers_strategy = $this->get_strategy('cache_module_content_headers_strategy');
399 1
        $this->_headers_strategy_authenticated = $this->get_strategy('cache_module_content_headers_strategy_authenticated');
400 1
        $this->_default_lifetime = (int)midcom::get()->config->get('cache_module_content_default_lifetime');
401 1
        $this->_default_lifetime_authenticated = (int)midcom::get()->config->get('cache_module_content_default_lifetime_authenticated');
402
403 1
        if ($this->_headers_strategy == 'no-cache') {
404
            $this->no_cache();
405
        }
406 1
    }
407
408 1
    private function get_strategy($name)
409
    {
410 1
        $strategy = strtolower(midcom::get()->config->get($name));
411 1
        $allowed = ['no-cache', 'revalidate', 'public', 'private'];
412 1
        if (!in_array($strategy, $allowed)) {
413
            throw new midcom_error($name . ' is not valid, try ' . implode(', ', $allowed));
414
        }
415 1
        return $strategy;
416
    }
417
418
    /**
419
     * Call this, if the currently processed output must not be cached for any
420
     * reason. Dynamic pages with sensitive content are a candidate for this
421
     * function.
422
     *
423
     * Note, that this will prevent <i>any</i> content invalidation related headers
424
     * like E-Tag to be generated automatically, and that the appropriate
425
     * no-store/no-cache headers from HTTP 1.1 and HTTP 1.0 will be sent automatically.
426
     * This means that there will also be no 304 processing.
427
     *
428
     * You should use this only for sensitive content. For simple dynamic output,
429
     * you are strongly encouraged to use the less strict uncached() function.
430
     *
431
     * @see uncached()
432
     */
433 191
    public function no_cache(Response $response = null)
434
    {
435 191
        $settings = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0';
436
        // PONDER: Send expires header (set to long time in past) as well ??
437
438 191
        if ($response) {
439
            $response->headers->set('Cache-Control', $settings);
440 191
        } else if (!$this->_no_cache) {
441
            if (_midcom_headers_sent()) {
442
                // Whatever is wrong here, we return.
443
                debug_add('Warning, we should move to no_cache but headers have already been sent, skipping header transmission.', MIDCOM_LOG_ERROR);
444
                return;
445
            }
446
447
            _midcom_header('Cache-Control: ' . $settings);
448
        }
449 191
        $this->_no_cache = true;
450 191
    }
451
452
    /**
453
     * Call this, if the currently processed output must not be cached for any
454
     * reason. Dynamic pages or form processing results are the usual candidates
455
     * for this mode.
456
     *
457
     * Note, that this will still keep the caching engine active so that it can
458
     * add the usual headers (ETag, Expires ...) in respect to the no_cache flag.
459
     * As well, at the end of the processing, the usual 304 checks are done, so if
460
     * your page doesn't change in respect of E-Tag and Last-Modified, only a 304
461
     * Not Modified reaches the client.
462
     *
463
     * Essentially, no_cache behaves the same way as if the uncached configuration
464
     * directive is set to true, it is just limited to a single request.
465
     *
466
     * If you need a higher level of client side security, to avoid storage of sensitive
467
     * information on the client side, you should use no_cache instead.
468
     *
469
     * @see no_cache()
470
     */
471 3
    public function uncached($uncached = true)
472
    {
473 3
        $this->_uncached = $uncached;
474 3
    }
475
476
    /**
477
     * Sets the expiration time of the current page (Unix (GMT) Timestamp).
478
     *
479
     * <b>Note:</B> This generate error call will add browser-side cache control
480
     * headers as well to force a browser to revalidate a page after the set
481
     * expiry.
482
     *
483
     * You should call this at all places where you have timed content in your
484
     * output, so that the page will be regenerated once a certain article has
485
     * expired.
486
     *
487
     * Multiple calls to expires will only save the
488
     * "youngest" timestamp, so you can safely call expires where appropriate
489
     * without respect to other values.
490
     *
491
     * The cache's default (null) will disable the expires header. Note, that once
492
     * an expiry time on a page has been set, it is not possible, to reset it again,
493
     * this is for dynamic_load situation, where one component might depend on a
494
     * set expiry.
495
     *
496
     * @param int $timestamp The UNIX timestamp from which the cached page should be invalidated.
497
     */
498
    public function expires($timestamp)
499
    {
500
        if (   $this->_expires === null
501
            || $this->_expires > $timestamp) {
502
            $this->_expires = $timestamp;
503
        }
504
    }
505
506
    /**
507
     * Sets the content type for the current page. The required HTTP Headers for
508
     * are automatically generated, so, to the contrary of expires, you just have
509
     * to set this header accordingly.
510
     *
511
     * This is usually set automatically by MidCOM for all regular HTML output and
512
     * for all attachment deliveries. You have to adapt it only for things like RSS
513
     * output.
514
     *
515
     * @param string $type    The content type to use.
516
     */
517 10
    public function content_type($type)
518
    {
519 10
        $this->_content_type = $type;
520
521
        // Send header (don't register yet to avoid duplicates, this is done during finish
522
        // caching).
523 10
        $header = "Content-type: " . $this->_content_type;
524 10
        _midcom_header($header);
525 10
    }
526
527
    /**
528
     * Put the cache into a "live mode". This will disable the
529
     * cache during runtime, correctly flushing the output buffer (if it's not empty)
530
     * and sending cache control headers.
531
     *
532
     * The midcom-exec URL handler of the core will automatically enable live mode.
533
     *
534
     * @see midcom_application::_exec_file()
535
     */
536
    public function enable_live_mode()
537
    {
538
        $this->no_cache();
539
        Response::closeOutputBuffers(0, ob_get_length() > 0);
540
    }
541
542
    /**
543
     * Store a sent header into the cache database, so that it will
544
     * be resent when the cache page is delivered. midcom_application::header()
545
     * will automatically call this function, you need to do this only if you use
546
     * the PHP header function.
547
     *
548
     * @param string $header The header that was sent.
549
     * @param string $value
550
     */
551 16
    public function register_sent_header($header, $value = null)
552
    {
553 16
        if ($value === null && strpos($header, ': ') !== false) {
554 14
            $parts = explode(': ', $header, 2);
555 14
            $header = $parts[0];
556 14
            $value = $parts[1];
557
        }
558 16
        $this->_sent_headers[$header] = $value;
559 16
    }
560
561
    /**
562
     * Looks for list of content and request identifiers paired with the given guid
563
     * and removes all of those from the caches.
564
     *
565
     * {@inheritDoc}
566
     */
567 298
    public function invalidate($guid, $object = null)
568
    {
569 298
        $guidmap = $this->_meta_cache->fetch($guid);
570 298
        if ($guidmap === false) {
571 298
            debug_add("No entry for {$guid} in meta cache, ignoring invalidation request.");
572 298
            return;
573
        }
574
575
        foreach ($guidmap as $content_id) {
576
            if ($this->_meta_cache->contains($content_id)) {
577
                $this->_meta_cache->delete($content_id);
578
            }
579
580
            if ($this->_data_cache->contains($content_id)) {
581
                $this->_data_cache->delete($content_id);
582
            }
583
        }
584
    }
585
586
    /**
587
     * All objects loaded within a request are stored into a list for cache invalidation purposes
588
     */
589 424
    public function register($guid)
590
    {
591
        // Check for uncached operation
592 424
        if ($this->_uncached) {
593 424
            return;
594
        }
595
596
        $context = midcom_core_context::get()->id;
597
        if ($context != 0) {
598
            // We're in a dynamic_load, register it for that as well
599
            if (!isset($this->context_guids[$context])) {
600
                $this->context_guids[$context] = [];
601
            }
602
            $this->context_guids[$context][] = $guid;
603
        }
604
605
        // Register all GUIDs also to the root context
606
        if (!isset($this->context_guids[0])) {
607
            $this->context_guids[0] = [];
608
        }
609
        $this->context_guids[0][] = $guid;
610
    }
611
612
    /**
613
     * Writes meta-cache entry from context data using given content id
614
     * Used to be part of on_request, but needed by serve-attachment method in midcom_core_urlmethods as well
615
     */
616 1
    public function write_meta_cache($content_id, $etag, Request $request)
617
    {
618 1
        if (   $this->_uncached
619 1
            || $this->_no_cache) {
620
            return;
621
        }
622
623 1
        if ($this->_expires !== null) {
624
            $lifetime = $this->_expires - time();
625
        } else {
626
            // Use default expiry for cache entry, most components don't bother calling expires() properly
627 1
            $lifetime = $this->_default_lifetime;
628
        }
629
630
        // Construct cache identifier
631 1
        $request_id = $this->generate_request_identifier($request);
632
633
        $entries = [
634 1
            $request_id => $content_id,
635
            $content_id => [
636 1
                'etag' => $etag,
637 1
                'last_modified' => $this->_last_modified,
638 1
                'sent_headers' => $this->_sent_headers
639
            ]
640
        ];
641
642 1
        $this->_meta_cache->saveMultiple($entries, $lifetime);
643
644
        // Cache where the object have been
645 1
        $context = midcom_core_context::get()->id;
646 1
        $this->store_context_guid_map($context, $content_id, $request_id);
647 1
    }
648
649 1
    private function store_context_guid_map($context, $content_id, $request_id)
650
    {
651
        // non-existent context
652 1
        if (!array_key_exists($context, $this->context_guids)) {
653 1
            return;
654
        }
655
656
        $maps = $this->_meta_cache->fetchMultiple($this->context_guids[$context]);
657
        $to_save = [];
658
        foreach ($this->context_guids[$context] as $guid) {
659
            // Getting old map from cache or create new, empty one
660
            $guidmap = (empty($maps[$guid])) ? [] : $maps[$guid];
661
662
            if (!in_array($content_id, $guidmap)) {
663
                $guidmap[] = $content_id;
664
                $to_save[$guid] = $guidmap;
665
            }
666
667
            if (   $content_id !== $request_id
668
                && !in_array($request_id, $guidmap)) {
669
                $guidmap[] = $request_id;
670
                $to_save[$guid] = $guidmap;
671
            }
672
        }
673
674
        $this->_meta_cache->saveMultiple($to_save);
675
    }
676
677 16
    public function check_dl_hit(Request $request)
678
    {
679 16
        if ($this->_no_cache) {
680 16
            return false;
681
        }
682
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
683
        $dl_content_id = $this->_meta_cache->fetch($dl_request_id);
684
        if ($dl_content_id === false) {
685
            return false;
686
        }
687
688
        return $this->_data_cache->fetch($dl_content_id);
689
    }
690
691 4
    public function store_dl_content($context, $dl_cache_data, Request $request)
692
    {
693 4
        if (   $this->_no_cache
694 4
            || $this->_uncached) {
695 4
            return;
696
        }
697
        $dl_request_id = 'DL' . $this->generate_request_identifier($request);
698
        $dl_content_id = 'DLC-' . md5($dl_cache_data);
699
700
        if ($this->_expires !== null) {
701
            $lifetime = $this->_expires - time();
702
        } else {
703
            // Use default expiry for cache entry, most components don't bother calling expires() properly
704
            $lifetime = $this->_default_lifetime;
705
        }
706
        $this->_meta_cache->save($dl_request_id, $dl_content_id, $lifetime);
707
        $this->_data_cache->save($dl_content_id, $dl_cache_data, $lifetime);
708
        // Cache where the object have been
709
        $this->store_context_guid_map($context, $dl_content_id, $dl_request_id);
710
    }
711
712 1
    private function apply_headers(Response $response, array $headers)
713
    {
714 1
        foreach ($headers as $header => $value) {
715 1
            if ($value === null) {
716
                // compat for old-style midcom status setting
717
                _midcom_header($header);
718
            } else {
719 1
                $response->headers->set($header, $value);
720
            }
721
        }
722 1
    }
723
724
    /**
725
     * This little helper ensures that the headers Content-Length
726
     * and Last-Modified are present. The lastmod timestamp is taken out of the
727
     * component context information if it is populated correctly there; if not, the
728
     * system time is used instead.
729
     *
730
     * To force browsers to revalidate the page on every request (login changes would
731
     * go unnoticed otherwise), the Cache-Control header max-age=0 is added automatically.
732
     */
733 1
    private function complete_sent_headers(Response $response)
734
    {
735 1
        $this->apply_headers($response, $this->_sent_headers);
736
737
        // Detected headers flags
738 1
        $size = $response->headers->has('Content-Length');
739 1
        $lastmod = false;
740
741 1
        if ($date = $response->getLastModified()) {
742
            $lastmod = true;
743
            $this->_last_modified = (int) $date->format('U');
744
            if ($this->_last_modified == -1) {
745
                debug_add("Failed to extract the timecode from the last modified header, defaulting to the current time.", MIDCOM_LOG_WARN);
746
                $this->_last_modified = time();
747
            }
748
        }
749
750 1
        if (!$size) {
751
            /* TODO: Doublecheck the way this is handled, now we just don't send it
752
             * if headers_strategy implies caching */
753 1
            if (!in_array($this->_headers_strategy, ['public', 'private'])) {
754 1
                $response->headers->set("Content-Length", strlen($response->getContent()));
755 1
                $this->register_sent_header('Content-Length', $response->headers->get('Content-Length'));
756
            }
757
        }
758
759 1
        if (!$lastmod) {
760
            /* Determine Last-Modified using MidCOM's component context,
761
             * Fallback to time() if this fails.
762
             */
763 1
            $time = midcom_core_context::get()->get_key(MIDCOM_CONTEXT_LASTMODIFIED);
764 1
            if ($time == 0 || !is_numeric($time)) {
765 1
                $time = time();
766
            }
767 1
            $response->setLastModified(DateTime::createFromFormat('U', $time));
0 ignored issues
show
Bug introduced by
It seems like DateTime::createFromFormat('U', $time) can also be of type false; however, parameter $date of Symfony\Component\HttpFo...onse::setLastModified() does only seem to accept DateTime|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

767
            $response->setLastModified(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $time));
Loading history...
768 1
            $this->register_sent_header('Last-Modified', $response->headers->get('Last-Modified'));
769 1
            $this->_last_modified = $time;
770
        }
771
772 1
        $this->cache_control_headers($response);
773 1
        $this->register_sent_header('Cache-Control', $response->headers->get('Cache-Control'));
774 1
        if ($response->getExpires()) {
775 1
            $this->register_sent_header('Expires', $response->headers->get('Expires'));
776
        }
777 1
    }
778
779
    /**
780
     * @param Response $response
781
     */
782 1
    public function cache_control_headers(Response $response)
783
    {
784
        // Just to be sure not to mess the headers sent by no_cache in case it was called
785 1
        if ($this->_no_cache) {
786
            $this->no_cache($response);
787
        } else {
788
            // Add Expiration and Cache Control headers
789 1
            $strategy = $this->_headers_strategy;
790 1
            $default_lifetime = $this->_default_lifetime;
791 1
            if (   midcom::get()->auth->is_valid_user()
792 1
                || midcom_connection::get_user()) {
793
                $strategy = $this->_headers_strategy_authenticated;
794
                $default_lifetime = $this->_default_lifetime_authenticated;
795
            }
796
797 1
            $now = time();
798 1
            if ($strategy == 'revalidate') {
799
                // If expires is not set, we force the client to revalidate every time.
800
                // The timeout of a content cache entry is not affected by this.
801 1
                $expires = $this->_expires ?? $now;
802
            } else {
803
                $expires = $this->_expires ?? $now + $default_lifetime;
804
                if ($strategy == 'private') {
805
                    $response->setPrivate();
806
                } else {
807
                    $response->setPublic();
808
                }
809
            }
810 1
            $max_age = $expires - $now;
811
812
            $response
813 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 DateTime|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

813
                ->setExpires(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $expires))
Loading history...
814 1
                ->setMaxAge($max_age);
815 1
            if ($max_age == 0) {
816 1
                $response->headers->addCacheControlDirective('must-revalidate');
817
            }
818
        }
819 1
    }
820
}
821