FileCache.php 8.2 KB

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