Completed
Push — master ( 3b68be...82c80d )
by Andreas
15:59
created

midcom_services_cache_module_content::_check_hit()   B

Complexity

Conditions 10
Paths 17

Size

Total Lines 59
Code Lines 34

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 14.0318

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 10
eloc 34
c 2
b 0
f 0
nc 17
nop 1
dl 0
loc 59
ccs 23
cts 35
cp 0.6571
crap 14.0318
rs 7.6666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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