FileCache.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. return @unlink($this->getFilename($id));
  127. }
  128. /**
  129. * {@inheritdoc}
  130. */
  131. protected function doFlush()
  132. {
  133. foreach ($this->getIterator() as $name => $file) {
  134. @unlink($name);
  135. }
  136. return true;
  137. }
  138. /**
  139. * {@inheritdoc}
  140. */
  141. protected function doGetStats()
  142. {
  143. $usage = 0;
  144. foreach ($this->getIterator() as $file) {
  145. $usage += $file->getSize();
  146. }
  147. $free = disk_free_space($this->directory);
  148. return array(
  149. Cache::STATS_HITS => null,
  150. Cache::STATS_MISSES => null,
  151. Cache::STATS_UPTIME => null,
  152. Cache::STATS_MEMORY_USAGE => $usage,
  153. Cache::STATS_MEMORY_AVAILABLE => $free,
  154. );
  155. }
  156. /**
  157. * Create path if needed.
  158. *
  159. * @param string $path
  160. * @return bool TRUE on success or if path already exists, FALSE if path cannot be created.
  161. */
  162. private function createPathIfNeeded($path)
  163. {
  164. if ( ! is_dir($path)) {
  165. if (false === @mkdir($path, 0777 & (~$this->umask), true) && !is_dir($path)) {
  166. return false;
  167. }
  168. }
  169. return true;
  170. }
  171. /**
  172. * Writes a string content to file in an atomic way.
  173. *
  174. * @param string $filename Path to the file where to write the data.
  175. * @param string $content The content to write
  176. *
  177. * @return bool TRUE on success, FALSE if path cannot be created, if path is not writable or an any other error.
  178. */
  179. protected function writeFile($filename, $content)
  180. {
  181. $filepath = pathinfo($filename, PATHINFO_DIRNAME);
  182. if ( ! $this->createPathIfNeeded($filepath)) {
  183. return false;
  184. }
  185. if ( ! is_writable($filepath)) {
  186. return false;
  187. }
  188. $tmpFile = tempnam($filepath, 'swap');
  189. @chmod($tmpFile, 0666 & (~$this->umask));
  190. if (file_put_contents($tmpFile, $content) !== false) {
  191. if (@rename($tmpFile, $filename)) {
  192. return true;
  193. }
  194. @unlink($tmpFile);
  195. }
  196. return false;
  197. }
  198. /**
  199. * @return \Iterator
  200. */
  201. private function getIterator()
  202. {
  203. return new \RegexIterator(
  204. new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory)),
  205. '/^.+' . preg_quote($this->extension, '/') . '$/i'
  206. );
  207. }
  208. }