Store.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * This code is partially based on the Rack-Cache library by Ryan Tomayko,
  8. * which is released under the MIT license.
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  13. namespace Symfony\Component\HttpKernel\HttpCache;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpFoundation\HeaderBag;
  17. /**
  18. * Store implements all the logic for storing cache metadata (Request and Response headers).
  19. *
  20. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  21. */
  22. class Store implements StoreInterface
  23. {
  24. protected $root;
  25. protected $keyCache;
  26. protected $locks;
  27. /**
  28. * Constructor.
  29. *
  30. * @param string $root The path to the cache directory
  31. */
  32. public function __construct($root)
  33. {
  34. $this->root = $root;
  35. if (!is_dir($this->root)) {
  36. mkdir($this->root, 0777, true);
  37. }
  38. $this->keyCache = new \SplObjectStorage();
  39. $this->locks = array();
  40. }
  41. /**
  42. * Cleanups storage.
  43. */
  44. public function cleanup()
  45. {
  46. // unlock everything
  47. foreach ($this->locks as $lock) {
  48. @unlink($lock);
  49. }
  50. $error = error_get_last();
  51. if (1 === $error['type'] && false === headers_sent()) {
  52. // send a 503
  53. header('HTTP/1.0 503 Service Unavailable');
  54. header('Retry-After: 10');
  55. echo '503 Service Unavailable';
  56. }
  57. }
  58. /**
  59. * Locks the cache for a given Request.
  60. *
  61. * @param Request $request A Request instance
  62. *
  63. * @return Boolean|string true if the lock is acquired, the path to the current lock otherwise
  64. */
  65. public function lock(Request $request)
  66. {
  67. if (false !== $lock = @fopen($path = $this->getPath($this->getCacheKey($request).'.lck'), 'x')) {
  68. fclose($lock);
  69. $this->locks[] = $path;
  70. return true;
  71. }
  72. return $path;
  73. }
  74. /**
  75. * Releases the lock for the given Request.
  76. *
  77. * @param Request $request A Request instance
  78. */
  79. public function unlock(Request $request)
  80. {
  81. return @unlink($this->getPath($this->getCacheKey($request).'.lck'));
  82. }
  83. /**
  84. * Locates a cached Response for the Request provided.
  85. *
  86. * @param Request $request A Request instance
  87. *
  88. * @return Response|null A Response instance, or null if no cache entry was found
  89. */
  90. public function lookup(Request $request)
  91. {
  92. $key = $this->getCacheKey($request);
  93. if (!$entries = $this->getMetadata($key)) {
  94. return null;
  95. }
  96. // find a cached entry that matches the request.
  97. $match = null;
  98. foreach ($entries as $entry) {
  99. if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'][0] : '', $request->headers->all(), $entry[0])) {
  100. $match = $entry;
  101. break;
  102. }
  103. }
  104. if (null === $match) {
  105. return null;
  106. }
  107. list($req, $headers) = $match;
  108. if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
  109. return $this->restoreResponse($headers, $body);
  110. }
  111. // TODO the metaStore referenced an entity that doesn't exist in
  112. // the entityStore. We definitely want to return nil but we should
  113. // also purge the entry from the meta-store when this is detected.
  114. return null;
  115. }
  116. /**
  117. * Writes a cache entry to the store for the given Request and Response.
  118. *
  119. * Existing entries are read and any that match the response are removed. This
  120. * method calls write with the new list of cache entries.
  121. *
  122. * @param Request $request A Request instance
  123. * @param Response $response A Response instance
  124. *
  125. * @return string The key under which the response is stored
  126. */
  127. public function write(Request $request, Response $response)
  128. {
  129. $key = $this->getCacheKey($request);
  130. $storedEnv = $this->persistRequest($request);
  131. // write the response body to the entity store if this is the original response
  132. if (!$response->headers->has('X-Content-Digest')) {
  133. $digest = 'en'.sha1($response->getContent());
  134. if (false === $this->save($digest, $response->getContent())) {
  135. throw new \RuntimeException('Unable to store the entity.');
  136. }
  137. $response->headers->set('X-Content-Digest', $digest);
  138. if (!$response->headers->has('Transfer-Encoding')) {
  139. $response->headers->set('Content-Length', strlen($response->getContent()));
  140. }
  141. }
  142. // read existing cache entries, remove non-varying, and add this one to the list
  143. $entries = array();
  144. $vary = $response->headers->get('vary');
  145. foreach ($this->getMetadata($key) as $entry) {
  146. if (!isset($entry[1]['vary'])) {
  147. $entry[1]['vary'] = array('');
  148. }
  149. if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
  150. $entries[] = $entry;
  151. }
  152. }
  153. $headers = $this->persistResponse($response);
  154. unset($headers['age']);
  155. array_unshift($entries, array($storedEnv, $headers));
  156. if (false === $this->save($key, serialize($entries))) {
  157. throw new \RuntimeException('Unable to store the metadata.');
  158. }
  159. return $key;
  160. }
  161. /**
  162. * Invalidates all cache entries that match the request.
  163. *
  164. * @param Request $request A Request instance
  165. */
  166. public function invalidate(Request $request)
  167. {
  168. $modified = false;
  169. $key = $this->getCacheKey($request);
  170. $entries = array();
  171. foreach ($this->getMetadata($key) as $entry) {
  172. $response = $this->restoreResponse($entry[1]);
  173. if ($response->isFresh()) {
  174. $response->expire();
  175. $modified = true;
  176. $entries[] = array($entry[0], $this->persistResponse($response));
  177. } else {
  178. $entries[] = $entry;
  179. }
  180. }
  181. if ($modified) {
  182. if (false === $this->save($key, serialize($entries))) {
  183. throw new \RuntimeException('Unable to store the metadata.');
  184. }
  185. }
  186. // As per the RFC, invalidate Location and Content-Location URLs if present
  187. foreach (array('Location', 'Content-Location') as $header) {
  188. if ($uri = $request->headers->get($header)) {
  189. $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
  190. $this->invalidate($subRequest);
  191. }
  192. }
  193. }
  194. /**
  195. * Determines whether two Request HTTP header sets are non-varying based on
  196. * the vary response header value provided.
  197. *
  198. * @param string $vary A Response vary header
  199. * @param array $env1 A Request HTTP header array
  200. * @param array $env2 A Request HTTP header array
  201. *
  202. * @return Boolean true if the the two environments match, false otherwise
  203. */
  204. protected function requestsMatch($vary, $env1, $env2)
  205. {
  206. if (empty($vary)) {
  207. return true;
  208. }
  209. foreach (preg_split('/[\s,]+/', $vary) as $header) {
  210. $key = strtr(strtolower($header), '_', '-');
  211. $v1 = isset($env1[$key]) ? $env1[$key] : null;
  212. $v2 = isset($env2[$key]) ? $env2[$key] : null;
  213. if ($v1 !== $v2) {
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. /**
  220. * Gets all data associated with the given key.
  221. *
  222. * Use this method only if you know what you are doing.
  223. *
  224. * @param string $key The store key
  225. *
  226. * @return array An array of data associated with the key
  227. */
  228. protected function getMetadata($key)
  229. {
  230. if (false === $entries = $this->load($key)) {
  231. return array();
  232. }
  233. return unserialize($entries);
  234. }
  235. /**
  236. * Purges data for the given URL.
  237. *
  238. * @param string $url A URL
  239. *
  240. * @return Boolean true if the URL exists and has been purged, false otherwise
  241. */
  242. public function purge($url)
  243. {
  244. if (file_exists($path = $this->getPath($this->getCacheKey(Request::create($url))))) {
  245. unlink($path);
  246. return true;
  247. }
  248. return false;
  249. }
  250. /**
  251. * Loads data for the given key.
  252. *
  253. * @param string $key The store key
  254. *
  255. * @return string The data associated with the key
  256. */
  257. protected function load($key)
  258. {
  259. $path = $this->getPath($key);
  260. return file_exists($path) ? file_get_contents($path) : false;
  261. }
  262. /**
  263. * Save data for the given key.
  264. *
  265. * @param string $key The store key
  266. * @param string $data The data to store
  267. */
  268. protected function save($key, $data)
  269. {
  270. $path = $this->getPath($key);
  271. if (!is_dir(dirname($path)) && false === @mkdir(dirname($path), 0777, true)) {
  272. return false;
  273. }
  274. $tmpFile = tempnam(dirname($path), basename($path));
  275. if (false === $fp = @fopen($tmpFile, 'wb')) {
  276. return false;
  277. }
  278. @fwrite($fp, $data);
  279. @fclose($fp);
  280. if ($data != file_get_contents($tmpFile)) {
  281. return false;
  282. }
  283. if (false === @rename($tmpFile, $path)) {
  284. return false;
  285. }
  286. chmod($path, 0644);
  287. }
  288. public function getPath($key)
  289. {
  290. 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);
  291. }
  292. /**
  293. * Returns a cache key for the given Request.
  294. *
  295. * @param Request $request A Request instance
  296. *
  297. * @return string A key for the given Request
  298. */
  299. protected function getCacheKey(Request $request)
  300. {
  301. if (isset($this->keyCache[$request])) {
  302. return $this->keyCache[$request];
  303. }
  304. return $this->keyCache[$request] = 'md'.sha1($request->getUri());
  305. }
  306. /**
  307. * Persists the Request HTTP headers.
  308. *
  309. * @param Request $request A Request instance
  310. *
  311. * @return array An array of HTTP headers
  312. */
  313. protected function persistRequest(Request $request)
  314. {
  315. return $request->headers->all();
  316. }
  317. /**
  318. * Persists the Response HTTP headers.
  319. *
  320. * @param Response $response A Response instance
  321. *
  322. * @return array An array of HTTP headers
  323. */
  324. protected function persistResponse(Response $response)
  325. {
  326. $headers = $response->headers->all();
  327. $headers['X-Status'] = array($response->getStatusCode());
  328. return $headers;
  329. }
  330. /**
  331. * Restores a Response from the HTTP headers and body.
  332. *
  333. * @param array $headers An array of HTTP headers for the Response
  334. * @param string $body The Response body
  335. */
  336. protected function restoreResponse($headers, $body = null)
  337. {
  338. $status = $headers['X-Status'][0];
  339. unset($headers['X-Status']);
  340. if (null !== $body) {
  341. $headers['X-Body-File'] = array($body);
  342. }
  343. return new Response($body, $status, $headers);
  344. }
  345. }