@see HTTP::add_cache_headers()

@param object $originator
@param HTTPRequest $request
@param HTTPResponse $response
421344
public function applyToResponse($originator, HTTPRequest $request, HTTPResponse $response)
    {
        $cacheAge = $this->getCacheAge();
        $vary = $this->getVary();

        // Allow overriding max-age from the object hooked up to the policed controller.
        if ($originator->hasMethod('getCacheAge')) {
            $extendedCacheAge = $originator->getCacheAge($cacheAge);
            if ($extendedCacheAge !== null) {
                $cacheAge = $extendedCacheAge;
            }
        }

        // Development sites have frequently changing templates; this can get stuffed up by the code
        // below.
        if (Director::isDev() && $this->config()->get('disable_cache_age_in_dev')) {
            $cacheAge = 0;
        }

        // Same for vary, but probably less useful.
        if ($originator->hasMethod('getVary')) {
            $extendedVary = $originator->getVary($vary);
            if ($extendedVary !== null) {
                $vary = $extendedVary;
            }
        }

        // Enable caching via core APIs
        HTTPCacheControlMiddleware::singleton()->enableCache();

        if ($cacheAge > 0) {
            HTTPCacheControlMiddleware::singleton()->setMaxAge($cacheAge);
        }

        // Merge vary into response
        if ($vary) {
            HTTPCacheControlMiddleware::singleton()->addVary($vary);
        }

        // Find out when the URI was last modified. Allows customisation, but fall back HTTP timestamp collector.
        if ($originator->hasMethod('getModificationTimestamp')) {
            $timestamp = $originator->getModificationTimestamp();
        } else {
            $timestamp = HTTP::$modification_date;
        }

        if ($timestamp) {
            $response->addHeader("Last-Modified", self::gmt_date($timestamp));
        }

        $expires = time() + HTTPCacheControlMiddleware::singleton()->getDirective('max-age');
        $response->addHeader("Expires", self::gmt_date($expires));

        // Now that we've generated them, either output them or attach them to the SS_HTTPResponse as appropriate
        HTTPCacheControlMiddleware::singleton()->applyToResponse($response);
    }
588754
public static function augmentState(HTTPRequest $request, HTTPResponse $response)
    {
        // Skip if deprecated API is disabled
        $config = Config::forClass(HTTP::class);
        if ($config->get('ignoreDeprecatedCaching')) {
            return;
        }

        $cacheControlMiddleware = HTTPCacheControlMiddleware::singleton();

        // if http caching is disabled by config, disable it - used on dev environments due to frequently changing
        // templates and other data. will be overridden by forced publicCache(true) or privateCache(true) calls
        if ($config->get('disable_http_cache')) {
            Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultState/.defaultForcingLevel instead');
            $cacheControlMiddleware->disableCache();
        }

        // if no caching ajax requests, disable ajax if is ajax request
        if (!$config->get('cache_ajax_requests') && Director::is_ajax()) {
            Deprecation::notice(
                '5.0',
                'HTTP.cache_ajax_requests config is deprecated. Use HTTPCacheControlMiddleware::disableCache() instead'
            );
            $cacheControlMiddleware->disableCache();
        }

        // Pass vary to middleware
        $configVary = $config->get('vary');
        if ($configVary) {
            Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware.defaultVary instead');
            $cacheControlMiddleware->addVary($configVary);
        }

        // Pass cache_control to middleware
        $configCacheControl = $config->get('cache_control');
        if ($configCacheControl) {
            Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware API instead');

            $supportedDirectives = ['max-age', 'no-cache', 'no-store', 'must-revalidate'];
            if ($foundUnsupported = array_diff(array_keys($configCacheControl), $supportedDirectives)) {
                throw new \LogicException(
                    'Found unsupported legacy directives in HTTP.cache_control: ' .
                    implode(', ', $foundUnsupported) .
                    '. Please use HTTPCacheControlMiddleware API instead'
                );
            }

            if (isset($configCacheControl['max-age'])) {
                $cacheControlMiddleware->setMaxAge($configCacheControl['max-age']);
            }

            if (isset($configCacheControl['no-cache'])) {
                $cacheControlMiddleware->setNoCache((bool)$configCacheControl['no-cache']);
            }

            if (isset($configCacheControl['no-store'])) {
                $cacheControlMiddleware->setNoStore((bool)$configCacheControl['no-store']);
            }

            if (isset($configCacheControl['must-revalidate'])) {
                $cacheControlMiddleware->setMustRevalidate((bool)$configCacheControl['must-revalidate']);
            }
        }

        // Set modification date
        if (self::$modification_date) {
            Deprecation::notice('5.0', 'Use HTTPCacheControlMiddleware::registerModificationDate() instead');
            $cacheControlMiddleware->registerModificationDate(self::$modification_date);
        }

        // Ensure deprecated $etag property is assigned
        if (self::$etag && !$cacheControlMiddleware->hasDirective('no-store') && !$response->getHeader('ETag')) {
            Deprecation::notice('5.0', 'Etag should not be set explicitly');
            $response->addHeader('ETag', self::$etag);
        }
    }
573276
private function createRevalidationRequest(
        RequestInterface $request,
        ResponseInterface $response
    ) {
        $validate = clone $request;
        $validate->getConfig()->set('cache.disable', true);
        $validate->removeHeader('Pragma');
        $validate->removeHeader('Cache-Control');
        $responseDate = $response->getHeader('Last-Modified')
            ?: $response->getHeader('Date');
        $validate->setHeader('If-Modified-Since', $responseDate);

        if ($etag = $response->getHeader('ETag')) {
            $validate->setHeader('If-None-Match', $etag);
        }

        return $validate;
    }
86586
public function generateHeadersFor(HTTPResponse $response)
    {
        return array_filter([
            'Last-Modified' => $this->generateLastModifiedHeader(),
            'Vary' => $this->generateVaryHeader($response),
            'Cache-Control' => $this->generateCacheHeader(),
            'Expires' => $this->generateExpiresHeader(),
        ]);
    }
577301
protected function setHttpCache($response = null)
    {
        $http_cache_config = Lb::app()->getHttpCacheConfig();
        if (isset($http_cache_config['cache_control']) && isset($http_cache_config['offset'])) {
            HttpHelper::setCache($http_cache_config['cache_control'], $http_cache_config['offset'], $response);
        }
    }
616333
private function attachNocacheCacheLimiterHeader(ResponseInterface $response): ResponseInterface
    {
        return $response
            ->withAddedHeader('Expires', self::EXPIRED)
            ->withAddedHeader('Cache-Control', 'no-store, no-cache, must-revalidate')
            ->withAddedHeader('Pragma', 'no-cache');
    }
1121816
protected function addJsonHeaders(JsonResponse $response, $maxAttempts, $remainingAttempts, $retryAfter = null)
    {
        $headers = [
            'X-RateLimit-Limit' => $maxAttempts,
            'X-RateLimit-Remaining' => $remainingAttempts,
        ];

        if (! is_null($retryAfter)) {
            $headers['Retry-After'] = $retryAfter;
        }

        $response->headers->add($headers);

        return $response;
    }
88962
private function addContentRangeHeadersToResponse(Response $response, $collection, $start, $usePagination = true)
    {
        $total = '*';
        if ($collection instanceof Paginator) {
            $resultCount = count($collection->getIterator());
        } else {
            $resultCount = count($collection);
        }

        if ($usePagination) {
            $total = count($collection);
        }

        $lastResult = $start + $resultCount - 1;
        $lastResult = $lastResult < 0 ? 0 : $lastResult;
        $response->headers->set('Content-Range', "$start-$lastResult/".$total);

        return $response;
    }
275520
private void configureCaching(HttpServletResponse response, int seconds) {
		// HTTP 1.0 header
		response.setDateHeader(HTTP_EXPIRES_HEADER, System.currentTimeMillis() + seconds * 1000L);
		if (seconds > 0) {
			// HTTP 1.1 header
			response.setHeader(HTTP_CACHE_CONTROL_HEADER, "max-age=" + seconds);
		} else {
			// HTTP 1.1 header
			response.setHeader(HTTP_CACHE_CONTROL_HEADER, "no-cache");

		}
	}
601852
public static function publicCache(
        ResponseInterface $response,
        /*# int */ $cacheTime = 120
    )/*# : ResponseInterface */ {
        $maxAge = $cacheTime * 60;
        return $response
            ->withAddedHeader('Expires', self::timeStamp($maxAge))
            ->withAddedHeader('Cache-Control', "public, max-age={$maxAge}")
            ->withAddedHeader('Last-Modified', self::timeStamp());
    }
1346628
public function setNoCacheHeaders(Zend_Controller_Response_Http $response) {
        $this->getResponse()
            ->setHeader('Cache-Control', 'no-cache', true)
            ->setHeader('Pragma', 'no-cache', true)
            ->setHeader('Expires', date(DATE_RFC1123, strtotime('-1 year')), true);
    }
1316579
private function cacheVary(
        RequestInterface $request,
        ResponseInterface $response
    ) {
        $key = $this->getVaryKey($request);
        $this->cache->save($key, $this->normalizeVary($response), $this->getTtl($response));
    }
565230
protected function cacheResponse(RequestInterface $request, ResponseInterface $response)
    {
        $cacheItem = $this->createCacheItem($this->createKeyFromRequest($request));
        $value = $response->getBody()->__toString();
        $cacheItem->set($value);

        $this
            ->getCacheItemPool()
            ->save($cacheItem);
    }
569037
public function addCorsHeaders($response, $headers)
    {
        if (empty($headers) === false) {
            foreach ($headers as $field => $value) {
                $response->setHeader($field, $value);
            }
        }
    }
1097944
private static function withExpires(
        ResponseInterface $response,
        CacheUtil $util,
        string $expires
    ): ResponseInterface {
        $expires = new DateTime($expires);
        $cacheControl = ResponseCacheControl::fromString($response->getHeaderLine('Cache-Control'))
            ->withMaxAge($expires->getTimestamp() - time());

        $response = $util->withExpires($response, $expires);

        return $util->withCacheControl($response, $cacheControl);
    }
170872
private function modifyStatusCode(Request $request, Response $response)
    {
        if ($request->headers->has(self::ORIGIN_REQUEST_HEADER)
            && $response->headers->has(self::ORIGIN_RESPONSE_HEADER)
            && !$this->haveSameOrigin($request, $response)
        ) {
            $response->setStatusCode(Response::HTTP_FORBIDDEN);
        }
    }
753589
protected function addCacheDirectory(ContainerInterface $container, SerializerBuilder $builder): void
    {
        $config = $container->get('config');
        $libraryConfig = $config[ConfigKey::PROJECT][ConfigKey::API_CLIENT] ?? [];
        $cacheDir = (string) ($libraryConfig[ConfigKey::CACHE_DIR] ?? '');

        if ($cacheDir !== '') {
            $builder->setCacheDir($cacheDir);
        }
    }