Completed
Push — master ( 0005b4...4026f1 )
by Andreas
16:11
created

midcom_services_cache_module_content   F

Complexity

Total Complexity 88

Size/Duplication

Total Lines 736
Duplicated Lines 0 %

Test Coverage

Coverage 63.47%

Importance

Changes 7
Bugs 0 Features 0
Metric Value
eloc 260
c 7
b 0
f 0
dl 0
loc 736
ccs 172
cts 271
cp 0.6347
rs 2
wmc 88

21 Methods

Rating   Name   Duplication   Size   Complexity  
A on_request() 0 9 3
A write_meta_cache() 0 26 4
A no_cache() 0 17 4
A content_type() 0 8 1
A check_dl_hit() 0 12 3
B _check_hit() 0 60 10
A enable_live_mode() 0 4 1
A _on_initialize() 0 21 4
B complete_sent_headers() 0 33 7
A expires() 0 5 3
A store_dl_content() 0 19 4
B cache_control_headers() 0 35 7
A uncached() 0 3 1
A get_strategy() 0 8 2
B on_response() 0 41 6
A register() 0 21 5
B generate_request_identifier() 0 43 7
A invalidate() 0 15 5
A apply_headers() 0 8 3
A register_sent_header() 0 8 3
A store_context_guid_map() 0 25 5

How to fix   Complexity   

Complex Class

Complex classes like midcom_services_cache_module_content often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use midcom_services_cache_module_content, and based on these observations, apply Extract Interface, too.

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

740
            $response->setLastModified(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $time));
Loading history...
741 1
            $this->register_sent_header('Last-Modified', $response->headers->get('Last-Modified'));
742 1
            $this->_last_modified = $time;
743
        }
744
745 1
        if (!$response->headers->has('Content-Length')) {
746
            /* TODO: Doublecheck the way this is handled, now we just don't send it
747
             * if headers_strategy implies caching */
748 1
            if (!in_array($this->_headers_strategy, ['public', 'private'])) {
749 1
                $response->headers->set("Content-Length", strlen($response->getContent()));
750 1
                $this->register_sent_header('Content-Length', $response->headers->get('Content-Length'));
751
            }
752
        }
753
754 1
        $this->cache_control_headers($response);
755 1
        $this->register_sent_header('Cache-Control', $response->headers->get('Cache-Control'));
756 1
        if ($response->getExpires()) {
757 1
            $this->register_sent_header('Expires', $response->headers->get('Expires'));
758
        }
759 1
    }
760
761
    /**
762
     * @param Response $response
763
     */
764 1
    public function cache_control_headers(Response $response)
765
    {
766
        // Just to be sure not to mess the headers sent by no_cache in case it was called
767 1
        if ($this->_no_cache) {
768
            $this->no_cache($response);
769
        } else {
770
            // Add Expiration and Cache Control headers
771 1
            $strategy = $this->_headers_strategy;
772 1
            $default_lifetime = $this->_default_lifetime;
773 1
            if (   midcom::get()->auth->is_valid_user()
774 1
                || midcom_connection::get_user()) {
775
                $strategy = $this->_headers_strategy_authenticated;
776
                $default_lifetime = $this->_default_lifetime_authenticated;
777
            }
778
779 1
            $now = time();
780 1
            if ($strategy == 'revalidate') {
781
                // If expires is not set, we force the client to revalidate every time.
782
                // The timeout of a content cache entry is not affected by this.
783 1
                $expires = $this->_expires ?? $now;
784
            } else {
785
                $expires = $this->_expires ?? $now + $default_lifetime;
786
                if ($strategy == 'private') {
787
                    $response->setPrivate();
788
                } else {
789
                    $response->setPublic();
790
                }
791
            }
792 1
            $max_age = $expires - $now;
793
794
            $response
795 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

795
                ->setExpires(/** @scrutinizer ignore-type */ DateTime::createFromFormat('U', $expires))
Loading history...
796 1
                ->setMaxAge($max_age);
797 1
            if ($max_age == 0) {
798 1
                $response->headers->addCacheControlDirective('must-revalidate');
799
            }
800
        }
801 1
    }
802
}
803