Store.php 11KB

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