Determines if a response can be cached.

@param ResponseInterface $response Response to check

@return bool
165503
public static function canCacheResponse(ResponseInterface $response)
    {
        static $cacheCodes = [200, 203, 300, 301, 410];

        // Check if the response is cacheable based on the code
        if (!in_array((int) $response->getStatusCode(), $cacheCodes)) {
            return false;
        }

        // Make sure a valid body was returned and can be cached
        $body = $response->getBody();
        if ($body && (!$body->isReadable() || !$body->isSeekable())) {
            return false;
        }

        // Never cache no-store resources (this is a private cache, so private
        // can be cached)
        if (self::getDirective($response, 'no-store')) {
            return false;
        }

        // Don't fool with Content-Range requests for now
        if ($response->hasHeader('Content-Range')) {
            return false;
        }

        $freshness = self::getFreshness($response);

        return $freshness === null                    // No freshness info.
            || $freshness >= 0                        // It's fresh
            || $response->hasHeader('ETag')           // Can validate
            || $response->hasHeader('Last-Modified'); // Can validate
    }
1205014
public function read(
        Request $request,
        Response $response
    ) {

        if ($this->bypass === true) {
            return false;
        }

        $name = self::getCacheName($request);
        $cache_object = $this->getCache()
            ->setNamespace(self::$cache_namespace)
            ->get($name);

        if (is_null($cache_object)) {
            return false;
        }

        $response->import($cache_object);
        return true;

    }
587025
protected function store_response($response) {

        set_config('recentfetch', time(), 'core_plugin');
        set_config('recentresponse', $response, 'core_plugin');

        if (defined('CACHE_DISABLE_ALL') and CACHE_DISABLE_ALL) {
            // Very nasty hack to work around cache coherency issues on admin/index.php?cache=0 page,
            // we definitely need to keep caches in sync when writing into DB at all times!
            \cache_helper::purge_all(true);
        }

        $this->restore_response(true);
    }
67382
public function processResponse(ResponseInterface $response)
    {
        if (!$response instanceof Response
            || !$this->getRequest()
        ) {
            return;
        }

        $response = $this->handleResponse($response);
        $this->renderResponse($response);
        $this->terminateApp();
    }
688999
protected function encodeSetCookieHeader(ResponseInterface $response)
    {
        $cookies = CookieCollection::createFromHeader($response->getHeader('Set-Cookie'));
        $header = [];
        foreach ($cookies as $cookie) {
            if (in_array($cookie->getName(), $this->cookieNames, true)) {
                $value = $this->_encrypt($cookie->getValue(), $this->cipherType);
                $cookie = $cookie->withValue($value);
            }
            $header[] = $cookie->toHeaderValue();
        }

        return $response->withHeader('Set-Cookie', $header);
    }
1169005
private function checkPostRateLimit(ResponseInterface $response)
    {
        $postRemaining = $response->getHeaderLine('X-Post-Rate-Limit-Remaining');
        $postLimit = $response->getHeaderLine('X-Post-Rate-Limit-Limit');

        if ('' !== $postRemaining && $postRemaining < 1) {
            // X-Post-Rate-Limit-Reset: Time in seconds until your POST ratelimit is reset
            $resetTime = date('Y-m-d H:i:s', $response->getHeaderLine('X-Post-Rate-Limit-Reset'));

            throw new RateLimitException('No post credits available. The limit is ' . $postLimit . ' and will be reset at ' . $resetTime);
        }
    }
782414
public function cache(RequestInterface $request, ResponseInterface $response)
    {
        $reqCacheControl = new KeyValueHttpHeader($request->getHeader('Cache-Control'));
        if ($reqCacheControl->has('no-store')) {
            // No caching allowed
            return false;
        }

        $cacheObject = $this->getCacheObject($request, $response);
        if ($cacheObject !== null) {
            // store the cache against the URI-only key
            $success = $this->storage->save(
                $this->getCacheKey($request),
                $cacheObject
            );

            $varyHeaders = $cacheObject->getVaryHeaders();

            if (!$varyHeaders->isEmpty()) {
                // also store the cache against the vary headers based key
                $success = $this->storage->save(
                    $this->getCacheKey($request, $varyHeaders),
                    $cacheObject
                );
            }

            return $success;
        }

        return false;
    }
58307
public function getResponseError(ResponseInterface $response)
    {
        if ($this->isError($response)) {
            $error = $this->getError($response);
            if (in_array($error, ['invalid_token', 'not_allowed_ip'], true)) {
                $this->app->user->logout();
                $this->app->response->refresh()->send();
                $this->app->end();
            }

            return $error ?: 'unknown api error';
        }

        if ($response->getRequest()->getQuery()->action === 'search') {
            $this->fixResponse($response);
        }

        return false;
    }
317183
public function isPageCacheable()
    {
        $result = false;
        $pragma = $this->response->getHeader('pragma');

        if ($pragma) {
            $result = $pragma->getFieldValue() === 'cache';
        }

        return $result;
    }
1037313
public static boolean isCacheable(Response response, Request request) {
    // Always go to network for uncacheable response codes (RFC 7231 section 6.1),
    // This implementation doesn't support caching partial content.
    switch (response.code()) {
      case HTTP_OK:
      case HTTP_NOT_AUTHORITATIVE:
      case HTTP_NO_CONTENT:
      case HTTP_MULT_CHOICE:
      case HTTP_MOVED_PERM:
      case HTTP_NOT_FOUND:
      case HTTP_BAD_METHOD:
      case HTTP_GONE:
      case HTTP_REQ_TOO_LONG:
      case HTTP_NOT_IMPLEMENTED:
      case StatusLine.HTTP_PERM_REDIRECT:
        // These codes can be cached unless headers forbid it.
        break;

      case HTTP_MOVED_TEMP:
      case StatusLine.HTTP_TEMP_REDIRECT:
        // These codes can only be cached with the right response headers.
        // http://tools.ietf.org/html/rfc7234#section-3
        // s-maxage is not checked because OkHttp is a private cache that should ignore s-maxage.
        if (response.header("Expires") != null
            || response.cacheControl().maxAgeSeconds() != -1
            || response.cacheControl().isPublic()
            || response.cacheControl().isPrivate()) {
          break;
        }
        // Fall-through.

      default:
        // All other codes cannot be cached.
        return false;
    }

    // A 'no-store' directive on request or response prevents the response from being cached.
    return !response.cacheControl().noStore() && !request.cacheControl().noStore();
  }
1210166
protected function getCacheControlDirective(ResponseInterface $response, string $name)
    {
        foreach ($response->getHeader('Cache-Control') as $header) {
            if (preg_match(sprintf('|%s=?([0-9]+)?|i', $name), $header, $matches)) {
                // return the value for $name if it exists
                if (isset($matches[1])) {
                    return $matches[1];
                }

                return true;
            }
        }

        return false;
    }
995718
private function isCacheable(RequestHandleInterface $handle)
    {
        if(null === $this->cache)
        {
            return false;
        }
        if($handle->getMethod() != self::GET)
        {
            return false;
        }

        return true;
    }
704165
private function isErroneousResponse($response)
    {
        return (isset($response->type) and isset($response->title) and isset($response->status) and isset($response->detail));
    }
405869
public function canResponseSatisfyRequest(RequestInterface $request, Response $response)
    {
        $responseAge = $response->calculateAge();
        $reqc = $request->getHeader('Cache-Control');
        $resc = $response->getHeader('Cache-Control');

        // Check the request's max-age header against the age of the response
        if ($reqc && $reqc->hasDirective('max-age') &&
            $responseAge > $reqc->getDirective('max-age')) {
            return false;
        }

        // Check the response's max-age header
        if ($response->isFresh() === false) {
            $maxStale = $reqc ? $reqc->getDirective('max-stale') : null;
            if (null !== $maxStale) {
                if ($maxStale !== true && $response->getFreshness() < (-1 * $maxStale)) {
                    return false;
                }
            } elseif ($resc && $resc->hasDirective('max-age')
                && $responseAge > $resc->getDirective('max-age')
            ) {
                return false;
            }
        }

        if ($this->revalidation->shouldRevalidate($request, $response)) {
            try {
                return $this->revalidation->revalidate($request, $response);
            } catch (CurlException $e) {
                $request->getParams()->set('cache.hit', 'error');
                return $this->canResponseSatisfyFailedRequest($request, $response);
            }
        }

        return true;
    }
349913
protected function isEmptyResponse(ResponseInterface $response)
    {
        if (method_exists($response, 'isEmpty')) {
            return $response->isEmpty();
        }

        return in_array($response->getStatusCode(), [204, 205, 304]);
    }
167993
private function serializeSession(ResponseInterface $response, SessionInterface $session)
    {
        if ($session->hasChanged()) {
            $serialized = call_user_func([$this->options['session_class'], 'toSerialized'], $session);

            $response = $this->handler->withCookie(
                $response,
                $this->options['cookie_name'],
                $serialized,
                $this->options['lifetime']
            );
        }

        return $response;
    }
251053
protected function _withCacheHeaders($response, $cacheTime, $modifiedTime)
    {
        $expire = strtotime($cacheTime);
        $maxAge = $expire - time();

        return $response
            ->withHeader('Cache-Control', 'public,max-age=' . $maxAge)
            ->withHeader('Date', gmdate('D, j M Y G:i:s \G\M\T', time()))
            ->withHeader('Last-Modified', gmdate('D, j M Y G:i:s \G\M\T', (int)$modifiedTime))
            ->withHeader('Expires', gmdate('D, j M Y G:i:s \G\M\T', $expire));
    }