FileCache.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace Doctrine\Common\Cache;
  3. use FilesystemIterator;
  4. use InvalidArgumentException;
  5. use Iterator;
  6. use RecursiveDirectoryIterator;
  7. use RecursiveIteratorIterator;
  8. use const DIRECTORY_SEPARATOR;
  9. use const PATHINFO_DIRNAME;
  10. use function bin2hex;
  11. use function chmod;
  12. use function defined;
  13. use function disk_free_space;
  14. use function file_exists;
  15. use function file_put_contents;
  16. use function gettype;
  17. use function hash;
  18. use function is_dir;
  19. use function is_int;
  20. use function is_writable;
  21. use function mkdir;
  22. use function pathinfo;
  23. use function realpath;
  24. use function rename;
  25. use function rmdir;
  26. use function sprintf;
  27. use function strlen;
  28. use function strrpos;
  29. use function substr;
  30. use function tempnam;
  31. use function unlink;
  32. /**
  33. * Base file cache driver.
  34. */
  35. abstract class FileCache extends CacheProvider
  36. {
  37. /**
  38. * The cache directory.
  39. *
  40. * @var string
  41. */
  42. protected $directory;
  43. /**
  44. * The cache file extension.
  45. *
  46. * @var string
  47. */
  48. private $extension;
  49. /** @var int */
  50. private $umask;
  51. /** @var int */
  52. private $directoryStringLength;
  53. /** @var int */
  54. private $extensionStringLength;
  55. /** @var bool */
  56. private $isRunningOnWindows;
  57. /**
  58. * @param string $directory The cache directory.
  59. * @param string $extension The cache file extension.
  60. *
  61. * @throws InvalidArgumentException
  62. */
  63. public function __construct($directory, $extension = '', $umask = 0002)
  64. {
  65. // YES, this needs to be *before* createPathIfNeeded()
  66. if (! is_int($umask)) {
  67. throw new InvalidArgumentException(sprintf(
  68. 'The umask parameter is required to be integer, was: %s',
  69. gettype($umask)
  70. ));
  71. }
  72. $this->umask = $umask;
  73. if (! $this->createPathIfNeeded($directory)) {
  74. throw new InvalidArgumentException(sprintf(
  75. 'The directory "%s" does not exist and could not be created.',
  76. $directory
  77. ));
  78. }
  79. if (! is_writable($directory)) {
  80. throw new InvalidArgumentException(sprintf(
  81. 'The directory "%s" is not writable.',
  82. $directory
  83. ));
  84. }
  85. // YES, this needs to be *after* createPathIfNeeded()
  86. $this->directory = realpath($directory);
  87. $this->extension = (string) $extension;
  88. $this->directoryStringLength = strlen($this->directory);
  89. $this->extensionStringLength = strlen($this->extension);
  90. $this->isRunningOnWindows = defined('PHP_WINDOWS_VERSION_BUILD');
  91. }
  92. /**
  93. * Gets the cache directory.
  94. *
  95. * @return string
  96. */
  97. public function getDirectory()
  98. {
  99. return $this->directory;
  100. }
  101. /**
  102. * Gets the cache file extension.
  103. *
  104. * @return string
  105. */
  106. public function getExtension()
  107. {
  108. return $this->extension;
  109. }
  110. /**
  111. * @param string $id
  112. *
  113. * @return string
  114. */
  115. protected function getFilename($id)
  116. {
  117. $hash = hash('sha256', $id);
  118. // This ensures that the filename is unique and that there are no invalid chars in it.
  119. if ($id === ''
  120. || ((strlen($id) * 2 + $this->extensionStringLength) > 255)
  121. || ($this->isRunningOnWindows && ($this->directoryStringLength + 4 + strlen($id) * 2 + $this->extensionStringLength) > 258)
  122. ) {
  123. // Most filesystems have a limit of 255 chars for each path component. On Windows the the whole path is limited
  124. // to 260 chars (including terminating null char). Using long UNC ("\\?\" prefix) does not work with the PHP API.
  125. // And there is a bug in PHP (https://bugs.php.net/bug.php?id=70943) with path lengths of 259.
  126. // So if the id in hex representation would surpass the limit, we use the hash instead. The prefix prevents
  127. // collisions between the hash and bin2hex.
  128. $filename = '_' . $hash;
  129. } else {
  130. $filename = bin2hex($id);
  131. }
  132. return $this->directory
  133. . DIRECTORY_SEPARATOR
  134. . substr($hash, 0, 2)
  135. . DIRECTORY_SEPARATOR
  136. . $filename
  137. . $this->extension;
  138. }
  139. /**
  140. * {@inheritdoc}
  141. */
  142. protected function doDelete($id)
  143. {
  144. $filename = $this->getFilename($id);
  145. return @unlink($filename) || ! file_exists($filename);
  146. }
  147. /**
  148. * {@inheritdoc}
  149. */
  150. protected function doFlush()
  151. {
  152. foreach ($this->getIterator() as $name => $file) {
  153. if ($file->isDir()) {
  154. // Remove the intermediate directories which have been created to balance the tree. It only takes effect
  155. // if the directory is empty. If several caches share the same directory but with different file extensions,
  156. // the other ones are not removed.
  157. @rmdir($name);
  158. } elseif ($this->isFilenameEndingWithExtension($name)) {
  159. // If an extension is set, only remove files which end with the given extension.
  160. // If no extension is set, we have no other choice than removing everything.
  161. @unlink($name);
  162. }
  163. }
  164. return true;
  165. }
  166. /**
  167. * {@inheritdoc}
  168. */
  169. protected function doGetStats()
  170. {
  171. $usage = 0;
  172. foreach ($this->getIterator() as $name => $file) {
  173. if ($file->isDir() || ! $this->isFilenameEndingWithExtension($name)) {
  174. continue;
  175. }
  176. $usage += $file->getSize();
  177. }
  178. $free = disk_free_space($this->directory);
  179. return [
  180. Cache::STATS_HITS => null,
  181. Cache::STATS_MISSES => null,
  182. Cache::STATS_UPTIME => null,
  183. Cache::STATS_MEMORY_USAGE => $usage,
  184. Cache::STATS_MEMORY_AVAILABLE => $free,
  185. ];
  186. }
  187. /**
  188. * Create path if needed.
  189. *
  190. * @return bool TRUE on success or if path already exists, FALSE if path cannot be created.
  191. */
  192. private function createPathIfNeeded(string $path) : bool
  193. {
  194. if (! is_dir($path)) {
  195. if (@mkdir($path, 0777 & (~$this->umask), true) === false && ! is_dir($path)) {
  196. return false;
  197. }
  198. }
  199. return true;
  200. }
  201. /**
  202. * Writes a string content to file in an atomic way.
  203. *
  204. * @param string $filename Path to the file where to write the data.
  205. * @param string $content The content to write
  206. *
  207. * @return bool TRUE on success, FALSE if path cannot be created, if path is not writable or an any other error.
  208. */
  209. protected function writeFile(string $filename, string $content) : bool
  210. {
  211. $filepath = pathinfo($filename, PATHINFO_DIRNAME);
  212. if (! $this->createPathIfNeeded($filepath)) {
  213. return false;
  214. }
  215. if (! is_writable($filepath)) {
  216. return false;
  217. }
  218. $tmpFile = tempnam($filepath, 'swap');
  219. @chmod($tmpFile, 0666 & (~$this->umask));
  220. if (file_put_contents($tmpFile, $content) !== false) {
  221. @chmod($tmpFile, 0666 & (~$this->umask));
  222. if (@rename($tmpFile, $filename)) {
  223. return true;
  224. }
  225. @unlink($tmpFile);
  226. }
  227. return false;
  228. }
  229. private function getIterator() : Iterator
  230. {
  231. return new RecursiveIteratorIterator(
  232. new RecursiveDirectoryIterator($this->directory, FilesystemIterator::SKIP_DOTS),
  233. RecursiveIteratorIterator::CHILD_FIRST
  234. );
  235. }
  236. /**
  237. * @param string $name The filename
  238. */
  239. private function isFilenameEndingWithExtension(string $name) : bool
  240. {
  241. return $this->extension === ''
  242. || strrpos($name, $this->extension) === (strlen($name) - $this->extensionStringLength);
  243. }
  244. }