FileCache.php 8.0 KB

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