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
34 * @param string $root The path to the cache directory
36 * @throws \RuntimeException
38 public function __construct($root)
41 if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) {
42 throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root));
44 $this->keyCache = new \SplObjectStorage();
45 $this->locks = array();
51 public function cleanup()
54 foreach ($this->locks as $lock) {
55 flock($lock, LOCK_UN);
59 $this->locks = array();
63 * Tries to lock the cache for a given Request, without blocking.
65 * @param Request $request A Request instance
67 * @return bool|string true if the lock is acquired, the path to the current lock otherwise
69 public function lock(Request $request)
71 $key = $this->getCacheKey($request);
73 if (!isset($this->locks[$key])) {
74 $path = $this->getPath($key);
75 if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
78 $h = fopen($path, 'cb');
79 if (!flock($h, LOCK_EX | LOCK_NB)) {
85 $this->locks[$key] = $h;
92 * Releases the lock for the given Request.
94 * @param Request $request A Request instance
96 * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
98 public function unlock(Request $request)
100 $key = $this->getCacheKey($request);
102 if (isset($this->locks[$key])) {
103 flock($this->locks[$key], LOCK_UN);
104 fclose($this->locks[$key]);
105 unset($this->locks[$key]);
113 public function isLocked(Request $request)
115 $key = $this->getCacheKey($request);
117 if (isset($this->locks[$key])) {
118 return true; // shortcut if lock held by this process
121 if (!file_exists($path = $this->getPath($key))) {
125 $h = fopen($path, 'rb');
126 flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
127 flock($h, LOCK_UN); // release the lock we just acquired
130 return (bool) $wouldBlock;
134 * Locates a cached Response for the Request provided.
136 * @param Request $request A Request instance
138 * @return Response|null A Response instance, or null if no cache entry was found
140 public function lookup(Request $request)
142 $key = $this->getCacheKey($request);
144 if (!$entries = $this->getMetadata($key)) {
148 // find a cached entry that matches the request.
150 foreach ($entries as $entry) {
151 if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) {
158 if (null === $match) {
162 list($req, $headers) = $match;
163 if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
164 return $this->restoreResponse($headers, $body);
167 // TODO the metaStore referenced an entity that doesn't exist in
168 // the entityStore. We definitely want to return nil but we should
169 // also purge the entry from the meta-store when this is detected.
173 * Writes a cache entry to the store for the given Request and Response.
175 * Existing entries are read and any that match the response are removed. This
176 * method calls write with the new list of cache entries.
178 * @param Request $request A Request instance
179 * @param Response $response A Response instance
181 * @return string The key under which the response is stored
183 * @throws \RuntimeException
185 public function write(Request $request, Response $response)
187 $key = $this->getCacheKey($request);
188 $storedEnv = $this->persistRequest($request);
190 // write the response body to the entity store if this is the original response
191 if (!$response->headers->has('X-Content-Digest')) {
192 $digest = $this->generateContentDigest($response);
194 if (false === $this->save($digest, $response->getContent())) {
195 throw new \RuntimeException('Unable to store the entity.');
198 $response->headers->set('X-Content-Digest', $digest);
200 if (!$response->headers->has('Transfer-Encoding')) {
201 $response->headers->set('Content-Length', strlen($response->getContent()));
205 // read existing cache entries, remove non-varying, and add this one to the list
207 $vary = $response->headers->get('vary');
208 foreach ($this->getMetadata($key) as $entry) {
209 if (!isset($entry[1]['vary'][0])) {
210 $entry[1]['vary'] = array('');
213 if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
218 $headers = $this->persistResponse($response);
219 unset($headers['age']);
221 array_unshift($entries, array($storedEnv, $headers));
223 if (false === $this->save($key, serialize($entries))) {
224 throw new \RuntimeException('Unable to store the metadata.');
231 * Returns content digest for $response.
233 * @param Response $response
237 protected function generateContentDigest(Response $response)
239 return 'en'.hash('sha256', $response->getContent());
243 * Invalidates all cache entries that match the request.
245 * @param Request $request A Request instance
247 * @throws \RuntimeException
249 public function invalidate(Request $request)
252 $key = $this->getCacheKey($request);
255 foreach ($this->getMetadata($key) as $entry) {
256 $response = $this->restoreResponse($entry[1]);
257 if ($response->isFresh()) {
260 $entries[] = array($entry[0], $this->persistResponse($response));
266 if ($modified && false === $this->save($key, serialize($entries))) {
267 throw new \RuntimeException('Unable to store the metadata.');
272 * Determines whether two Request HTTP header sets are non-varying based on
273 * the vary response header value provided.
275 * @param string $vary A Response vary header
276 * @param array $env1 A Request HTTP header array
277 * @param array $env2 A Request HTTP header array
279 * @return bool true if the two environments match, false otherwise
281 private function requestsMatch($vary, $env1, $env2)
287 foreach (preg_split('/[\s,]+/', $vary) as $header) {
288 $key = str_replace('_', '-', strtolower($header));
289 $v1 = isset($env1[$key]) ? $env1[$key] : null;
290 $v2 = isset($env2[$key]) ? $env2[$key] : null;
300 * Gets all data associated with the given key.
302 * Use this method only if you know what you are doing.
304 * @param string $key The store key
306 * @return array An array of data associated with the key
308 private function getMetadata($key)
310 if (!$entries = $this->load($key)) {
314 return unserialize($entries);
318 * Purges data for the given URL.
320 * This method purges both the HTTP and the HTTPS version of the cache entry.
322 * @param string $url A URL
324 * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
326 public function purge($url)
328 $http = preg_replace('#^https:#', 'http:', $url);
329 $https = preg_replace('#^http:#', 'https:', $url);
331 $purgedHttp = $this->doPurge($http);
332 $purgedHttps = $this->doPurge($https);
334 return $purgedHttp || $purgedHttps;
338 * Purges data for the given URL.
340 * @param string $url A URL
342 * @return bool true if the URL exists and has been purged, false otherwise
344 private function doPurge($url)
346 $key = $this->getCacheKey(Request::create($url));
347 if (isset($this->locks[$key])) {
348 flock($this->locks[$key], LOCK_UN);
349 fclose($this->locks[$key]);
350 unset($this->locks[$key]);
353 if (file_exists($path = $this->getPath($key))) {
363 * Loads data for the given key.
365 * @param string $key The store key
367 * @return string The data associated with the key
369 private function load($key)
371 $path = $this->getPath($key);
373 return file_exists($path) ? file_get_contents($path) : false;
377 * Save data for the given key.
379 * @param string $key The store key
380 * @param string $data The data to store
384 private function save($key, $data)
386 $path = $this->getPath($key);
388 if (isset($this->locks[$key])) {
389 $fp = $this->locks[$key];
392 $len = @fwrite($fp, $data);
393 if (strlen($data) !== $len) {
399 if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
403 $tmpFile = tempnam(dirname($path), basename($path));
404 if (false === $fp = @fopen($tmpFile, 'wb')) {
410 if ($data != file_get_contents($tmpFile)) {
414 if (false === @rename($tmpFile, $path)) {
419 @chmod($path, 0666 & ~umask());
422 public function getPath($key)
424 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);
428 * Generates a cache key for the given Request.
430 * This method should return a key that must only depend on a
431 * normalized version of the request URI.
433 * If the same URI can have more than one representation, based on some
434 * headers, use a Vary header to indicate them, and each representation will
435 * be stored independently under the same cache key.
437 * @param Request $request A Request instance
439 * @return string A key for the given Request
441 protected function generateCacheKey(Request $request)
443 return 'md'.hash('sha256', $request->getUri());
447 * Returns a cache key for the given Request.
449 * @param Request $request A Request instance
451 * @return string A key for the given Request
453 private function getCacheKey(Request $request)
455 if (isset($this->keyCache[$request])) {
456 return $this->keyCache[$request];
459 return $this->keyCache[$request] = $this->generateCacheKey($request);
463 * Persists the Request HTTP headers.
465 * @param Request $request A Request instance
467 * @return array An array of HTTP headers
469 private function persistRequest(Request $request)
471 return $request->headers->all();
475 * Persists the Response HTTP headers.
477 * @param Response $response A Response instance
479 * @return array An array of HTTP headers
481 private function persistResponse(Response $response)
483 $headers = $response->headers->all();
484 $headers['X-Status'] = array($response->getStatusCode());
490 * Restores a Response from the HTTP headers and body.
492 * @param array $headers An array of HTTP headers for the Response
493 * @param string $body The Response body
497 private function restoreResponse($headers, $body = null)
499 $status = $headers['X-Status'][0];
500 unset($headers['X-Status']);
502 if (null !== $body) {
503 $headers['X-Body-File'] = array($body);
506 return new Response($body, $status, $headers);