PageRenderTime 54ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/src/vendor/symfony/src/Symfony/Component/HttpKernel/Cache/Store.php

https://github.com/jTownsend/Symfony-2.0
PHP | 405 lines | 213 code | 57 blank | 135 comment | 34 complexity | 13084db24ad3f44c48857a1c6554e5e8 MD5 | raw file
  1. <?php
  2. namespace Symfony\Component\HttpKernel\Cache;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\HeaderBag;
  6. /*
  7. * This file is part of the Symfony framework.
  8. *
  9. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  10. *
  11. * This code is partially based on the Rack-Cache library by Ryan Tomayko,
  12. * which is released under the MIT license.
  13. *
  14. * This source file is subject to the MIT license that is bundled
  15. * with this source code in the file LICENSE.
  16. */
  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
  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. public function __destruct()
  42. {
  43. // unlock everything
  44. foreach ($this->locks as $lock) {
  45. @unlink($lock);
  46. }
  47. $error = error_get_last();
  48. if (1 === $error['type'] && false === headers_sent()) {
  49. // send a 503
  50. header('HTTP/1.0 503 Service Unavailable');
  51. header('Retry-After: 10');
  52. echo '503 Service Unavailable';
  53. }
  54. }
  55. /**
  56. * Locks the cache for a given Request.
  57. *
  58. * @param Request $request A Request instance
  59. *
  60. * @return Boolean|string true if the lock is acquired, the path to the current lock otherwise
  61. */
  62. public function lock(Request $request)
  63. {
  64. if (false !== $lock = @fopen($path = $this->getPath($this->getCacheKey($request).'.lck'), 'x')) {
  65. fclose($lock);
  66. $this->locks[] = $path;
  67. return true;
  68. } else {
  69. return $path;
  70. }
  71. }
  72. /**
  73. * Releases the lock for the given Request.
  74. *
  75. * @param Request $request A Request instance
  76. */
  77. public function unlock(Request $request)
  78. {
  79. return @unlink($this->getPath($this->getCacheKey($request).'.lck'));
  80. }
  81. /**
  82. * Locates a cached Response for the Request provided.
  83. *
  84. * @param Request $request A Request instance
  85. *
  86. * @return Response|null A Response instance, or null if no cache entry was found
  87. */
  88. public function lookup(Request $request)
  89. {
  90. $key = $this->getCacheKey($request);
  91. if (!$entries = $this->getMetadata($key)) {
  92. return null;
  93. }
  94. // find a cached entry that matches the request.
  95. $match = null;
  96. foreach ($entries as $entry) {
  97. if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'][0] : '', $request->headers->all(), $entry[0])) {
  98. $match = $entry;
  99. break;
  100. }
  101. }
  102. if (null === $match) {
  103. return null;
  104. }
  105. list($req, $headers) = $match;
  106. if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
  107. return $this->restoreResponse($headers, $body);
  108. } else {
  109. // TODO the metaStore referenced an entity that doesn't exist in
  110. // the entityStore. We definitely want to return nil but we should
  111. // also purge the entry from the meta-store when this is detected.
  112. return null;
  113. }
  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(sprintf('Unable to store the entity (%s).', $e->getMessage()));
  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'])) {
  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(sprintf('Unable to store the metadata (%s).', $e->getMessage()));
  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. public 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. public 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. * Don't use this method directly, use lookup() instead
  253. *
  254. * @param string $key The store key
  255. *
  256. * @return string The data associated with the key
  257. */
  258. public function load($key)
  259. {
  260. $path = $this->getPath($key);
  261. return file_exists($path) ? file_get_contents($path) : false;
  262. }
  263. /**
  264. * Save data for the given key.
  265. *
  266. * Don't use this method directly, use write() instead
  267. *
  268. * @param string $key The store key
  269. * @param string $data The data to store
  270. */
  271. public function save($key, $data)
  272. {
  273. $path = $this->getPath($key);
  274. if (!is_dir(dirname($path))) {
  275. mkdir(dirname($path), 0777, true);
  276. }
  277. $tmpFile = tempnam(dirname($path), basename($path));
  278. if (false === $fp = @fopen($tmpFile, 'wb')) {
  279. return false;
  280. }
  281. @fwrite($fp, $data);
  282. @fclose($fp);
  283. if ($data != file_get_contents($tmpFile)) {
  284. return false;
  285. }
  286. if (false === @rename($tmpFile, $path)) {
  287. return false;
  288. }
  289. chmod($path, 0644);
  290. }
  291. public function getPath($key)
  292. {
  293. return $this->root.DIRECTORY_SEPARATOR.substr($key, 0, 2).DIRECTORY_SEPARATOR.substr($key, 2, 4).DIRECTORY_SEPARATOR.substr($key, 4);
  294. }
  295. /**
  296. * Returns a cache key for the given Request.
  297. *
  298. * @param Request $request A Request instance
  299. *
  300. * @return string A key for the given Request
  301. */
  302. public function getCacheKey(Request $request)
  303. {
  304. if (isset($this->keyCache[$request])) {
  305. return $this->keyCache[$request];
  306. }
  307. return $this->keyCache[$request] = 'md'.sha1($request->getUri());
  308. }
  309. /**
  310. * Persists the Request HTTP headers.
  311. *
  312. * @param Request $request A Request instance
  313. *
  314. * @return array An array of HTTP headers
  315. */
  316. protected function persistRequest(Request $request)
  317. {
  318. return $request->headers->all();
  319. }
  320. /**
  321. * Persists the Response HTTP headers.
  322. *
  323. * @param Response $response A Response instance
  324. *
  325. * @return array An array of HTTP headers
  326. */
  327. protected function persistResponse(Response $response)
  328. {
  329. $headers = $response->headers->all();
  330. $headers['X-Status'] = array($response->getStatusCode());
  331. return $headers;
  332. }
  333. /**
  334. * Restores a Response from the HTTP headers and body.
  335. *
  336. * @param array $headers An array of HTTP headers for the Response
  337. * @param string $body The Response body
  338. */
  339. protected function restoreResponse($headers, $body = null)
  340. {
  341. $status = $headers['X-Status'][0];
  342. unset($headers['X-Status']);
  343. if (null !== $body) {
  344. $headers['X-Body-File'] = array($body);
  345. }
  346. return new Response($body, $status, $headers);
  347. }
  348. }