FileCache.php 7.7 KB

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