Example #1
0
 /**
  * Calculates the total Time To Live based on the specification
  * RFC 2616 cache lifetime rules.
  *
  * @param   Response  $response  Response to evaluate
  * @return  mixed  TTL value or false if the response should not be cached
  */
 public function cache_lifetime(Response $response)
 {
     // Get out of here if this cannot be cached
     if (!$this->set_cache($response)) {
         return FALSE;
     }
     // Calculate apparent age
     if ($date = $response->headers('date')) {
         $apparent_age = max(0, $this->_response_time - strtotime((string) $date));
     } else {
         $apparent_age = max(0, $this->_response_time);
     }
     // Calculate corrected received age
     if ($age = $response->headers('age')) {
         $corrected_received_age = max($apparent_age, intval((string) $age));
     } else {
         $corrected_received_age = $apparent_age;
     }
     // Corrected initial age
     $corrected_initial_age = $corrected_received_age + $this->request_execution_time();
     // Resident time
     $resident_time = time() - $this->_response_time;
     // Current age
     $current_age = $corrected_initial_age + $resident_time;
     // Prepare the cache freshness lifetime
     $ttl = NULL;
     // Cache control overrides
     if ($cache_control = $response->headers('cache-control')) {
         // Parse the cache control header
         $cache_control = Response::parse_cache_control((string) $cache_control);
         if (isset($cache_control['max-age'])) {
             $ttl = (int) $cache_control['max-age'];
         }
         if (isset($cache_control['s-maxage']) and isset($cache_control['private']) and $this->_allow_private_cache) {
             $ttl = (int) $cache_control['s-maxage'];
         }
         if (isset($cache_control['max-stale']) and !isset($cache_control['must-revalidate'])) {
             $ttl = $current_age + (int) $cache_control['max-stale'];
         }
     }
     // If we have a TTL at this point, return
     if ($ttl !== NULL) {
         return $ttl;
     }
     if ($expires = $response->headers('expires')) {
         return strtotime((string) $expires) - $current_age;
     }
     return FALSE;
 }