FileCache.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 string[] regular expressions for replacing disallowed characters in file name
  43. */
  44. private $disallowedCharacterPatterns = array(
  45. '/\-/', // replaced to disambiguate original `-` and `-` derived from replacements
  46. '/[^a-zA-Z0-9\-_\[\]]/' // also excludes non-ascii chars (not supported, depending on FS)
  47. );
  48. /**
  49. * @var string[] replacements for disallowed file characters
  50. */
  51. private $replacementCharacters = array('__', '-');
  52. /**
  53. * @var int
  54. */
  55. private $umask;
  56. /**
  57. * @var int
  58. */
  59. private $directoryStringLength;
  60. /**
  61. * @var int
  62. */
  63. private $extensionStringLength;
  64. /**
  65. * @var bool
  66. */
  67. private $isRunningOnWindows;
  68. /**
  69. * Constructor.
  70. *
  71. * @param string $directory The cache directory.
  72. * @param string $extension The cache file extension.
  73. *
  74. * @throws \InvalidArgumentException
  75. */
  76. public function __construct($directory, $extension = '', $umask = 0002)
  77. {
  78. // YES, this needs to be *before* createPathIfNeeded()
  79. if ( ! is_int($umask)) {
  80. throw new \InvalidArgumentException(sprintf(
  81. 'The umask parameter is required to be integer, was: %s',
  82. gettype($umask)
  83. ));
  84. }
  85. $this->umask = $umask;
  86. if ( ! $this->createPathIfNeeded($directory)) {
  87. throw new \InvalidArgumentException(sprintf(
  88. 'The directory "%s" does not exist and could not be created.',
  89. $directory
  90. ));
  91. }
  92. if ( ! is_writable($directory)) {
  93. throw new \InvalidArgumentException(sprintf(
  94. 'The directory "%s" is not writable.',
  95. $directory
  96. ));
  97. }
  98. // YES, this needs to be *after* createPathIfNeeded()
  99. $this->directory = realpath($directory);
  100. $this->extension = (string) $extension;
  101. $this->directoryStringLength = strlen($this->directory);
  102. $this->extensionStringLength = strlen($this->extension);
  103. $this->isRunningOnWindows = defined('PHP_WINDOWS_VERSION_BUILD');
  104. }
  105. /**
  106. * Gets the cache directory.
  107. *
  108. * @return string
  109. */
  110. public function getDirectory()
  111. {
  112. return $this->directory;
  113. }
  114. /**
  115. * Gets the cache file extension.
  116. *
  117. * @return string
  118. */
  119. public function getExtension()
  120. {
  121. return $this->extension;
  122. }
  123. /**
  124. * @param string $id
  125. *
  126. * @return string
  127. */
  128. protected function getFilename($id)
  129. {
  130. return $this->directory
  131. . DIRECTORY_SEPARATOR
  132. . implode(DIRECTORY_SEPARATOR, str_split(hash('sha256', $id), 2))
  133. . DIRECTORY_SEPARATOR
  134. . preg_replace($this->disallowedCharacterPatterns, $this->replacementCharacters, $id)
  135. . $this->extension;
  136. }
  137. /**
  138. * {@inheritdoc}
  139. */
  140. protected function doDelete($id)
  141. {
  142. $filename = $this->getFilename($id);
  143. return @unlink($filename) || ! file_exists($filename);
  144. }
  145. /**
  146. * {@inheritdoc}
  147. */
  148. protected function doFlush()
  149. {
  150. foreach ($this->getIterator() as $name => $file) {
  151. if ($file->isDir()) {
  152. // Remove the intermediate directories which have been created to balance the tree. It only takes effect
  153. // if the directory is empty. If several caches share the same directory but with different file extensions,
  154. // the other ones are not removed.
  155. @rmdir($name);
  156. } elseif ($this->isFilenameEndingWithExtension($name)) {
  157. // If an extension is set, only remove files which end with the given extension.
  158. // If no extension is set, we have no other choice than removing everything.
  159. @unlink($name);
  160. }
  161. }
  162. return true;
  163. }
  164. /**
  165. * {@inheritdoc}
  166. */
  167. protected function doGetStats()
  168. {
  169. $usage = 0;
  170. foreach ($this->getIterator() as $name => $file) {
  171. if (! $file->isDir() && $this->isFilenameEndingWithExtension($name)) {
  172. $usage += $file->getSize();
  173. }
  174. }
  175. $free = disk_free_space($this->directory);
  176. return array(
  177. Cache::STATS_HITS => null,
  178. Cache::STATS_MISSES => null,
  179. Cache::STATS_UPTIME => null,
  180. Cache::STATS_MEMORY_USAGE => $usage,
  181. Cache::STATS_MEMORY_AVAILABLE => $free,
  182. );
  183. }
  184. /**
  185. * Create path if needed.
  186. *
  187. * @param string $path
  188. * @return bool TRUE on success or if path already exists, FALSE if path cannot be created.
  189. */
  190. private function createPathIfNeeded($path)
  191. {
  192. if ( ! is_dir($path)) {
  193. if (false === @mkdir($path, 0777 & (~$this->umask), true) && !is_dir($path)) {
  194. return false;
  195. }
  196. }
  197. return true;
  198. }
  199. /**
  200. * Writes a string content to file in an atomic way.
  201. *
  202. * @param string $filename Path to the file where to write the data.
  203. * @param string $content The content to write
  204. *
  205. * @return bool TRUE on success, FALSE if path cannot be created, if path is not writable or an any other error.
  206. */
  207. protected function writeFile($filename, $content)
  208. {
  209. $filepath = pathinfo($filename, PATHINFO_DIRNAME);
  210. if ( ! $this->createPathIfNeeded($filepath)) {
  211. return false;
  212. }
  213. if ( ! is_writable($filepath)) {
  214. return false;
  215. }
  216. $tmpFile = tempnam($filepath, 'swap');
  217. @chmod($tmpFile, 0666 & (~$this->umask));
  218. if (file_put_contents($tmpFile, $content) !== false) {
  219. if (@rename($tmpFile, $filename)) {
  220. return true;
  221. }
  222. @unlink($tmpFile);
  223. }
  224. return false;
  225. }
  226. /**
  227. * @return \Iterator
  228. */
  229. private function getIterator()
  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. * @return bool
  240. */
  241. private function isFilenameEndingWithExtension($name)
  242. {
  243. return '' === $this->extension
  244. || strrpos($name, $this->extension) === (strlen($name) - $this->extensionStringLength);
  245. }
  246. }