FileCache.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. */
  26. abstract class FileCache extends CacheProvider
  27. {
  28. /**
  29. * The cache directory.
  30. *
  31. * @var string
  32. */
  33. protected $directory;
  34. /**
  35. * The cache file extension.
  36. *
  37. * @var string
  38. */
  39. private $extension;
  40. /**
  41. * @var string[] regular expressions for replacing disallowed characters in file name
  42. */
  43. private $disallowedCharacterPatterns = array(
  44. '/\-/', // replaced to disambiguate original `-` and `-` derived from replacements
  45. '/[^a-zA-Z0-9\-_\[\]]/' // also excludes non-ascii chars (not supported, depending on FS)
  46. );
  47. /**
  48. * @var string[] replacements for disallowed file characters
  49. */
  50. private $replacementCharacters = array('__', '-');
  51. /**
  52. * @var int
  53. */
  54. private $umask;
  55. /**
  56. * Constructor.
  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. }
  89. /**
  90. * Gets the cache directory.
  91. *
  92. * @return string
  93. */
  94. public function getDirectory()
  95. {
  96. return $this->directory;
  97. }
  98. /**
  99. * Gets the cache file extension.
  100. *
  101. * @return string|null
  102. */
  103. public function getExtension()
  104. {
  105. return $this->extension;
  106. }
  107. /**
  108. * @param string $id
  109. *
  110. * @return string
  111. */
  112. protected function getFilename($id)
  113. {
  114. return $this->directory
  115. . DIRECTORY_SEPARATOR
  116. . implode(str_split(hash('sha256', $id), 2), DIRECTORY_SEPARATOR)
  117. . DIRECTORY_SEPARATOR
  118. . preg_replace($this->disallowedCharacterPatterns, $this->replacementCharacters, $id)
  119. . $this->extension;
  120. }
  121. /**
  122. * {@inheritdoc}
  123. */
  124. protected function doDelete($id)
  125. {
  126. $filename = $this->getFilename($id);
  127. return @unlink($filename) || ! file_exists($filename);
  128. }
  129. /**
  130. * {@inheritdoc}
  131. */
  132. protected function doFlush()
  133. {
  134. foreach ($this->getIterator() as $name => $file) {
  135. if ($file->isDir()) {
  136. // Remove the intermediate directories which have been created to balance the tree. It only takes effect
  137. // if the directory is empty. If several caches share the same directory but with different file extensions,
  138. // the other ones are not removed.
  139. @rmdir($name);
  140. } elseif ($this->isFilenameEndingWithExtension($name)) {
  141. // If an extension is set, only remove files which end with the given extension.
  142. // If no extension is set, we have no other choice than removing everything.
  143. @unlink($name);
  144. }
  145. }
  146. return true;
  147. }
  148. /**
  149. * {@inheritdoc}
  150. */
  151. protected function doGetStats()
  152. {
  153. $usage = 0;
  154. foreach ($this->getIterator() as $name => $file) {
  155. if (! $file->isDir() && $this->isFilenameEndingWithExtension($name)) {
  156. $usage += $file->getSize();
  157. }
  158. }
  159. $free = disk_free_space($this->directory);
  160. return array(
  161. Cache::STATS_HITS => null,
  162. Cache::STATS_MISSES => null,
  163. Cache::STATS_UPTIME => null,
  164. Cache::STATS_MEMORY_USAGE => $usage,
  165. Cache::STATS_MEMORY_AVAILABLE => $free,
  166. );
  167. }
  168. /**
  169. * Create path if needed.
  170. *
  171. * @param string $path
  172. * @return bool TRUE on success or if path already exists, FALSE if path cannot be created.
  173. */
  174. private function createPathIfNeeded($path)
  175. {
  176. if ( ! is_dir($path)) {
  177. if (false === @mkdir($path, 0777 & (~$this->umask), true) && !is_dir($path)) {
  178. return false;
  179. }
  180. }
  181. return true;
  182. }
  183. /**
  184. * Writes a string content to file in an atomic way.
  185. *
  186. * @param string $filename Path to the file where to write the data.
  187. * @param string $content The content to write
  188. *
  189. * @return bool TRUE on success, FALSE if path cannot be created, if path is not writable or an any other error.
  190. */
  191. protected function writeFile($filename, $content)
  192. {
  193. $filepath = pathinfo($filename, PATHINFO_DIRNAME);
  194. if ( ! $this->createPathIfNeeded($filepath)) {
  195. return false;
  196. }
  197. if ( ! is_writable($filepath)) {
  198. return false;
  199. }
  200. $tmpFile = tempnam($filepath, 'swap');
  201. @chmod($tmpFile, 0666 & (~$this->umask));
  202. if (file_put_contents($tmpFile, $content) !== false) {
  203. if (@rename($tmpFile, $filename)) {
  204. return true;
  205. }
  206. @unlink($tmpFile);
  207. }
  208. return false;
  209. }
  210. /**
  211. * @return \Iterator
  212. */
  213. private function getIterator()
  214. {
  215. return new \RecursiveIteratorIterator(
  216. new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS),
  217. \RecursiveIteratorIterator::CHILD_FIRST
  218. );
  219. }
  220. /**
  221. * @param string $name The filename
  222. *
  223. * @return bool
  224. */
  225. private function isFilenameEndingWithExtension($name)
  226. {
  227. return '' === $this->extension
  228. || strrpos($name, $this->extension) === (strlen($name) - strlen($this->extension));
  229. }
  230. }