4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * This code is partially based on the Rack-Cache library by Ryan Tomayko,
9 * which is released under the MIT license.
11 * For the full copyright and license information, please view the LICENSE
12 * file that was distributed with this source code.
15 namespace Symfony\Component\HttpKernel\HttpCache;
17 use Symfony\Component\HttpFoundation\Request;
18 use Symfony\Component\HttpFoundation\Response;
21 * Store implements all the logic for storing cache metadata (Request and Response headers).
23 * @author Fabien Potencier <fabien@symfony.com>
25 class Store implements StoreInterface
32 * @param string $root The path to the cache directory
34 * @throws \RuntimeException
36 public function __construct($root)
39 if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
40 throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
42 $this->keyCache = new \SplObjectStorage();
43 $this->locks = array();
49 public function cleanup()
52 foreach ($this->locks as $lock) {
53 flock($lock, LOCK_UN);
57 $this->locks = array();
61 * Tries to lock the cache for a given Request, without blocking.
63 * @return bool|string true if the lock is acquired, the path to the current lock otherwise
65 public function lock(Request $request)
67 $key = $this->getCacheKey($request);
69 if (!isset($this->locks[$key])) {
70 $path = $this->getPath($key);
71 if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
74 $h = fopen($path, 'cb');
75 if (!flock($h, LOCK_EX | LOCK_NB)) {
81 $this->locks[$key] = $h;
88 * Releases the lock for the given Request.
90 * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
92 public function unlock(Request $request)
94 $key = $this->getCacheKey($request);
96 if (isset($this->locks[$key])) {
97 flock($this->locks[$key], LOCK_UN);
98 fclose($this->locks[$key]);
99 unset($this->locks[$key]);
107 public function isLocked(Request $request)
109 $key = $this->getCacheKey($request);
111 if (isset($this->locks[$key])) {
112 return true; // shortcut if lock held by this process
115 if (!file_exists($path = $this->getPath($key))) {
119 $h = fopen($path, 'rb');
120 flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
121 flock($h, LOCK_UN); // release the lock we just acquired
124 return (bool) $wouldBlock;
128 * Locates a cached Response for the Request provided.
130 * @return Response|null A Response instance, or null if no cache entry was found
132 public function lookup(Request $request)
134 $key = $this->getCacheKey($request);
136 if (!$entries = $this->getMetadata($key)) {
140 // find a cached entry that matches the request.
142 foreach ($entries as $entry) {
143 if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) {
150 if (null === $match) {
154 $headers = $match[1];
155 if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
156 return $this->restoreResponse($headers, $body);
159 // TODO the metaStore referenced an entity that doesn't exist in
160 // the entityStore. We definitely want to return nil but we should
161 // also purge the entry from the meta-store when this is detected.
165 * Writes a cache entry to the store for the given Request and Response.
167 * Existing entries are read and any that match the response are removed. This
168 * method calls write with the new list of cache entries.
170 * @return string The key under which the response is stored
172 * @throws \RuntimeException
174 public function write(Request $request, Response $response)
176 $key = $this->getCacheKey($request);
177 $storedEnv = $this->persistRequest($request);
179 // write the response body to the entity store if this is the original response
180 if (!$response->headers->has('X-Content-Digest')) {
181 $digest = $this->generateContentDigest($response);
183 if (false === $this->save($digest, $response->getContent())) {
184 throw new \RuntimeException('Unable to store the entity.');
187 $response->headers->set('X-Content-Digest', $digest);
189 if (!$response->headers->has('Transfer-Encoding')) {
190 $response->headers->set('Content-Length', \strlen($response->getContent()));
194 // read existing cache entries, remove non-varying, and add this one to the list
196 $vary = $response->headers->get('vary');
197 foreach ($this->getMetadata($key) as $entry) {
198 if (!isset($entry[1]['vary'][0])) {
199 $entry[1]['vary'] = array('');
202 if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
207 $headers = $this->persistResponse($response);
208 unset($headers['age']);
210 array_unshift($entries, array($storedEnv, $headers));
212 if (false === $this->save($key, serialize($entries))) {
213 throw new \RuntimeException('Unable to store the metadata.');
220 * Returns content digest for $response.
224 protected function generateContentDigest(Response $response)
226 return 'en'.hash('sha256', $response->getContent());
230 * Invalidates all cache entries that match the request.
232 * @throws \RuntimeException
234 public function invalidate(Request $request)
237 $key = $this->getCacheKey($request);
240 foreach ($this->getMetadata($key) as $entry) {
241 $response = $this->restoreResponse($entry[1]);
242 if ($response->isFresh()) {
245 $entries[] = array($entry[0], $this->persistResponse($response));
251 if ($modified && false === $this->save($key, serialize($entries))) {
252 throw new \RuntimeException('Unable to store the metadata.');
257 * Determines whether two Request HTTP header sets are non-varying based on
258 * the vary response header value provided.
260 * @param string $vary A Response vary header
261 * @param array $env1 A Request HTTP header array
262 * @param array $env2 A Request HTTP header array
264 * @return bool true if the two environments match, false otherwise
266 private function requestsMatch($vary, $env1, $env2)
272 foreach (preg_split('/[\s,]+/', $vary) as $header) {
273 $key = str_replace('_', '-', strtolower($header));
274 $v1 = isset($env1[$key]) ? $env1[$key] : null;
275 $v2 = isset($env2[$key]) ? $env2[$key] : null;
285 * Gets all data associated with the given key.
287 * Use this method only if you know what you are doing.
289 * @param string $key The store key
291 * @return array An array of data associated with the key
293 private function getMetadata($key)
295 if (!$entries = $this->load($key)) {
299 return unserialize($entries);
303 * Purges data for the given URL.
305 * This method purges both the HTTP and the HTTPS version of the cache entry.
307 * @param string $url A URL
309 * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
311 public function purge($url)
313 $http = preg_replace('#^https:#', 'http:', $url);
314 $https = preg_replace('#^http:#', 'https:', $url);
316 $purgedHttp = $this->doPurge($http);
317 $purgedHttps = $this->doPurge($https);
319 return $purgedHttp || $purgedHttps;
323 * Purges data for the given URL.
325 * @param string $url A URL
327 * @return bool true if the URL exists and has been purged, false otherwise
329 private function doPurge($url)
331 $key = $this->getCacheKey(Request::create($url));
332 if (isset($this->locks[$key])) {
333 flock($this->locks[$key], LOCK_UN);
334 fclose($this->locks[$key]);
335 unset($this->locks[$key]);
338 if (file_exists($path = $this->getPath($key))) {
348 * Loads data for the given key.
350 * @param string $key The store key
352 * @return string The data associated with the key
354 private function load($key)
356 $path = $this->getPath($key);
358 return file_exists($path) ? file_get_contents($path) : false;
362 * Save data for the given key.
364 * @param string $key The store key
365 * @param string $data The data to store
369 private function save($key, $data)
371 $path = $this->getPath($key);
373 if (isset($this->locks[$key])) {
374 $fp = $this->locks[$key];
377 $len = @fwrite($fp, $data);
378 if (\strlen($data) !== $len) {
384 if (!file_exists(\dirname($path)) && false === @mkdir(\dirname($path), 0777, true) && !is_dir(\dirname($path))) {
388 $tmpFile = tempnam(\dirname($path), basename($path));
389 if (false === $fp = @fopen($tmpFile, 'wb')) {
397 if ($data != file_get_contents($tmpFile)) {
403 if (false === @rename($tmpFile, $path)) {
410 @chmod($path, 0666 & ~umask());
413 public function getPath($key)
415 return $this->root.\DIRECTORY_SEPARATOR.substr($key, 0, 2).\DIRECTORY_SEPARATOR.substr($key, 2, 2).\DIRECTORY_SEPARATOR.substr($key, 4, 2).\DIRECTORY_SEPARATOR.substr($key, 6);
419 * Generates a cache key for the given Request.
421 * This method should return a key that must only depend on a
422 * normalized version of the request URI.
424 * If the same URI can have more than one representation, based on some
425 * headers, use a Vary header to indicate them, and each representation will
426 * be stored independently under the same cache key.
428 * @return string A key for the given Request
430 protected function generateCacheKey(Request $request)
432 return 'md'.hash('sha256', $request->getUri());
436 * Returns a cache key for the given Request.
438 * @return string A key for the given Request
440 private function getCacheKey(Request $request)
442 if (isset($this->keyCache[$request])) {
443 return $this->keyCache[$request];
446 return $this->keyCache[$request] = $this->generateCacheKey($request);
450 * Persists the Request HTTP headers.
452 * @return array An array of HTTP headers
454 private function persistRequest(Request $request)
456 return $request->headers->all();
460 * Persists the Response HTTP headers.
462 * @return array An array of HTTP headers
464 private function persistResponse(Response $response)
466 $headers = $response->headers->all();
467 $headers['X-Status'] = array($response->getStatusCode());
473 * Restores a Response from the HTTP headers and body.
475 * @param array $headers An array of HTTP headers for the Response
476 * @param string $body The Response body
480 private function restoreResponse($headers, $body = null)
482 $status = $headers['X-Status'][0];
483 unset($headers['X-Status']);
485 if (null !== $body) {
486 $headers['X-Body-File'] = array($body);
489 return new Response($body, $status, $headers);