c4d961e68f04318d29851bdec8338056a468454d
[yaffs-website] / vendor / symfony / http-kernel / HttpCache / Store.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * This code is partially based on the Rack-Cache library by Ryan Tomayko,
9  * which is released under the MIT license.
10  *
11  * For the full copyright and license information, please view the LICENSE
12  * file that was distributed with this source code.
13  */
14
15 namespace Symfony\Component\HttpKernel\HttpCache;
16
17 use Symfony\Component\HttpFoundation\Request;
18 use Symfony\Component\HttpFoundation\Response;
19
20 /**
21  * Store implements all the logic for storing cache metadata (Request and Response headers).
22  *
23  * @author Fabien Potencier <fabien@symfony.com>
24  */
25 class Store implements StoreInterface
26 {
27     protected $root;
28     private $keyCache;
29     private $locks;
30
31     /**
32      * Constructor.
33      *
34      * @param string $root The path to the cache directory
35      *
36      * @throws \RuntimeException
37      */
38     public function __construct($root)
39     {
40         $this->root = $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));
43         }
44         $this->keyCache = new \SplObjectStorage();
45         $this->locks = array();
46     }
47
48     /**
49      * Cleanups storage.
50      */
51     public function cleanup()
52     {
53         // unlock everything
54         foreach ($this->locks as $lock) {
55             flock($lock, LOCK_UN);
56             fclose($lock);
57         }
58
59         $this->locks = array();
60     }
61
62     /**
63      * Tries to lock the cache for a given Request, without blocking.
64      *
65      * @param Request $request A Request instance
66      *
67      * @return bool|string true if the lock is acquired, the path to the current lock otherwise
68      */
69     public function lock(Request $request)
70     {
71         $key = $this->getCacheKey($request);
72
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))) {
76                 return $path;
77             }
78             $h = fopen($path, 'cb');
79             if (!flock($h, LOCK_EX | LOCK_NB)) {
80                 fclose($h);
81
82                 return $path;
83             }
84
85             $this->locks[$key] = $h;
86         }
87
88         return true;
89     }
90
91     /**
92      * Releases the lock for the given Request.
93      *
94      * @param Request $request A Request instance
95      *
96      * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise
97      */
98     public function unlock(Request $request)
99     {
100         $key = $this->getCacheKey($request);
101
102         if (isset($this->locks[$key])) {
103             flock($this->locks[$key], LOCK_UN);
104             fclose($this->locks[$key]);
105             unset($this->locks[$key]);
106
107             return true;
108         }
109
110         return false;
111     }
112
113     public function isLocked(Request $request)
114     {
115         $key = $this->getCacheKey($request);
116
117         if (isset($this->locks[$key])) {
118             return true; // shortcut if lock held by this process
119         }
120
121         if (!file_exists($path = $this->getPath($key))) {
122             return false;
123         }
124
125         $h = fopen($path, 'rb');
126         flock($h, LOCK_EX | LOCK_NB, $wouldBlock);
127         flock($h, LOCK_UN); // release the lock we just acquired
128         fclose($h);
129
130         return (bool) $wouldBlock;
131     }
132
133     /**
134      * Locates a cached Response for the Request provided.
135      *
136      * @param Request $request A Request instance
137      *
138      * @return Response|null A Response instance, or null if no cache entry was found
139      */
140     public function lookup(Request $request)
141     {
142         $key = $this->getCacheKey($request);
143
144         if (!$entries = $this->getMetadata($key)) {
145             return;
146         }
147
148         // find a cached entry that matches the request.
149         $match = null;
150         foreach ($entries as $entry) {
151             if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) {
152                 $match = $entry;
153
154                 break;
155             }
156         }
157
158         if (null === $match) {
159             return;
160         }
161
162         list($req, $headers) = $match;
163         if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
164             return $this->restoreResponse($headers, $body);
165         }
166
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.
170     }
171
172     /**
173      * Writes a cache entry to the store for the given Request and Response.
174      *
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.
177      *
178      * @param Request  $request  A Request instance
179      * @param Response $response A Response instance
180      *
181      * @return string The key under which the response is stored
182      *
183      * @throws \RuntimeException
184      */
185     public function write(Request $request, Response $response)
186     {
187         $key = $this->getCacheKey($request);
188         $storedEnv = $this->persistRequest($request);
189
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);
193
194             if (false === $this->save($digest, $response->getContent())) {
195                 throw new \RuntimeException('Unable to store the entity.');
196             }
197
198             $response->headers->set('X-Content-Digest', $digest);
199
200             if (!$response->headers->has('Transfer-Encoding')) {
201                 $response->headers->set('Content-Length', strlen($response->getContent()));
202             }
203         }
204
205         // read existing cache entries, remove non-varying, and add this one to the list
206         $entries = array();
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('');
211             }
212
213             if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
214                 $entries[] = $entry;
215             }
216         }
217
218         $headers = $this->persistResponse($response);
219         unset($headers['age']);
220
221         array_unshift($entries, array($storedEnv, $headers));
222
223         if (false === $this->save($key, serialize($entries))) {
224             throw new \RuntimeException('Unable to store the metadata.');
225         }
226
227         return $key;
228     }
229
230     /**
231      * Returns content digest for $response.
232      *
233      * @param Response $response
234      *
235      * @return string
236      */
237     protected function generateContentDigest(Response $response)
238     {
239         return 'en'.hash('sha256', $response->getContent());
240     }
241
242     /**
243      * Invalidates all cache entries that match the request.
244      *
245      * @param Request $request A Request instance
246      *
247      * @throws \RuntimeException
248      */
249     public function invalidate(Request $request)
250     {
251         $modified = false;
252         $key = $this->getCacheKey($request);
253
254         $entries = array();
255         foreach ($this->getMetadata($key) as $entry) {
256             $response = $this->restoreResponse($entry[1]);
257             if ($response->isFresh()) {
258                 $response->expire();
259                 $modified = true;
260                 $entries[] = array($entry[0], $this->persistResponse($response));
261             } else {
262                 $entries[] = $entry;
263             }
264         }
265
266         if ($modified && false === $this->save($key, serialize($entries))) {
267             throw new \RuntimeException('Unable to store the metadata.');
268         }
269     }
270
271     /**
272      * Determines whether two Request HTTP header sets are non-varying based on
273      * the vary response header value provided.
274      *
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
278      *
279      * @return bool true if the two environments match, false otherwise
280      */
281     private function requestsMatch($vary, $env1, $env2)
282     {
283         if (empty($vary)) {
284             return true;
285         }
286
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;
291             if ($v1 !== $v2) {
292                 return false;
293             }
294         }
295
296         return true;
297     }
298
299     /**
300      * Gets all data associated with the given key.
301      *
302      * Use this method only if you know what you are doing.
303      *
304      * @param string $key The store key
305      *
306      * @return array An array of data associated with the key
307      */
308     private function getMetadata($key)
309     {
310         if (!$entries = $this->load($key)) {
311             return array();
312         }
313
314         return unserialize($entries);
315     }
316
317     /**
318      * Purges data for the given URL.
319      *
320      * This method purges both the HTTP and the HTTPS version of the cache entry.
321      *
322      * @param string $url A URL
323      *
324      * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
325      */
326     public function purge($url)
327     {
328         $http = preg_replace('#^https:#', 'http:', $url);
329         $https = preg_replace('#^http:#', 'https:', $url);
330
331         $purgedHttp = $this->doPurge($http);
332         $purgedHttps = $this->doPurge($https);
333
334         return $purgedHttp || $purgedHttps;
335     }
336
337     /**
338      * Purges data for the given URL.
339      *
340      * @param string $url A URL
341      *
342      * @return bool true if the URL exists and has been purged, false otherwise
343      */
344     private function doPurge($url)
345     {
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]);
351         }
352
353         if (file_exists($path = $this->getPath($key))) {
354             unlink($path);
355
356             return true;
357         }
358
359         return false;
360     }
361
362     /**
363      * Loads data for the given key.
364      *
365      * @param string $key The store key
366      *
367      * @return string The data associated with the key
368      */
369     private function load($key)
370     {
371         $path = $this->getPath($key);
372
373         return file_exists($path) ? file_get_contents($path) : false;
374     }
375
376     /**
377      * Save data for the given key.
378      *
379      * @param string $key  The store key
380      * @param string $data The data to store
381      *
382      * @return bool
383      */
384     private function save($key, $data)
385     {
386         $path = $this->getPath($key);
387
388         if (isset($this->locks[$key])) {
389             $fp = $this->locks[$key];
390             @ftruncate($fp, 0);
391             @fseek($fp, 0);
392             $len = @fwrite($fp, $data);
393             if (strlen($data) !== $len) {
394                 @ftruncate($fp, 0);
395
396                 return false;
397             }
398         } else {
399             if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) {
400                 return false;
401             }
402
403             $tmpFile = tempnam(dirname($path), basename($path));
404             if (false === $fp = @fopen($tmpFile, 'wb')) {
405                 return false;
406             }
407             @fwrite($fp, $data);
408             @fclose($fp);
409
410             if ($data != file_get_contents($tmpFile)) {
411                 return false;
412             }
413
414             if (false === @rename($tmpFile, $path)) {
415                 return false;
416             }
417         }
418
419         @chmod($path, 0666 & ~umask());
420     }
421
422     public function getPath($key)
423     {
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);
425     }
426
427     /**
428      * Generates a cache key for the given Request.
429      *
430      * This method should return a key that must only depend on a
431      * normalized version of the request URI.
432      *
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.
436      *
437      * @param Request $request A Request instance
438      *
439      * @return string A key for the given Request
440      */
441     protected function generateCacheKey(Request $request)
442     {
443         return 'md'.hash('sha256', $request->getUri());
444     }
445
446     /**
447      * Returns a cache key for the given Request.
448      *
449      * @param Request $request A Request instance
450      *
451      * @return string A key for the given Request
452      */
453     private function getCacheKey(Request $request)
454     {
455         if (isset($this->keyCache[$request])) {
456             return $this->keyCache[$request];
457         }
458
459         return $this->keyCache[$request] = $this->generateCacheKey($request);
460     }
461
462     /**
463      * Persists the Request HTTP headers.
464      *
465      * @param Request $request A Request instance
466      *
467      * @return array An array of HTTP headers
468      */
469     private function persistRequest(Request $request)
470     {
471         return $request->headers->all();
472     }
473
474     /**
475      * Persists the Response HTTP headers.
476      *
477      * @param Response $response A Response instance
478      *
479      * @return array An array of HTTP headers
480      */
481     private function persistResponse(Response $response)
482     {
483         $headers = $response->headers->all();
484         $headers['X-Status'] = array($response->getStatusCode());
485
486         return $headers;
487     }
488
489     /**
490      * Restores a Response from the HTTP headers and body.
491      *
492      * @param array  $headers An array of HTTP headers for the Response
493      * @param string $body    The Response body
494      *
495      * @return Response
496      */
497     private function restoreResponse($headers, $body = null)
498     {
499         $status = $headers['X-Status'][0];
500         unset($headers['X-Status']);
501
502         if (null !== $body) {
503             $headers['X-Body-File'] = array($body);
504         }
505
506         return new Response($body, $status, $headers);
507     }
508 }