AbstractFile.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\File
  5. *
  6. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Grav\Framework\File;
  10. use Grav\Framework\File\Interfaces\FileInterface;
  11. use Grav\Framework\Filesystem\Filesystem;
  12. class AbstractFile implements FileInterface
  13. {
  14. /** @var Filesystem */
  15. private $filesystem;
  16. /** @var string */
  17. private $filepath;
  18. /** @var string|null */
  19. private $filename;
  20. /** @var string|null */
  21. private $path;
  22. /** @var string|null */
  23. private $basename;
  24. /** @var string|null */
  25. private $extension;
  26. /** @var resource|null */
  27. private $handle;
  28. /** @var bool */
  29. private $locked = false;
  30. /**
  31. * @param string $filepath
  32. * @param Filesystem|null $filesystem
  33. */
  34. public function __construct(string $filepath, Filesystem $filesystem = null)
  35. {
  36. $this->filesystem = $filesystem ?? Filesystem::getInstance();
  37. $this->setFilepath($filepath);
  38. }
  39. /**
  40. * Unlock file when the object gets destroyed.
  41. */
  42. public function __destruct()
  43. {
  44. if ($this->isLocked()) {
  45. $this->unlock();
  46. }
  47. }
  48. public function __clone()
  49. {
  50. $this->handle = null;
  51. $this->locked = false;
  52. }
  53. /**
  54. * @return string
  55. */
  56. public function serialize(): string
  57. {
  58. return serialize($this->doSerialize());
  59. }
  60. /**
  61. * @param string $serialized
  62. */
  63. public function unserialize($serialized): void
  64. {
  65. $this->doUnserialize(unserialize($serialized, ['allowed_classes' => false]));
  66. }
  67. /**
  68. * {@inheritdoc}
  69. * @see FileInterface::getFilePath()
  70. */
  71. public function getFilePath(): string
  72. {
  73. return $this->filepath;
  74. }
  75. /**
  76. * {@inheritdoc}
  77. * @see FileInterface::getPath()
  78. */
  79. public function getPath(): string
  80. {
  81. if (null === $this->path) {
  82. $this->setPathInfo();
  83. }
  84. return $this->path;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. * @see FileInterface::getFilename()
  89. */
  90. public function getFilename(): string
  91. {
  92. if (null === $this->filename) {
  93. $this->setPathInfo();
  94. }
  95. return $this->filename;
  96. }
  97. /**
  98. * {@inheritdoc}
  99. * @see FileInterface::getBasename()
  100. */
  101. public function getBasename(): string
  102. {
  103. if (null === $this->basename) {
  104. $this->setPathInfo();
  105. }
  106. return $this->basename;
  107. }
  108. /**
  109. * {@inheritdoc}
  110. * @see FileInterface::getExtension()
  111. */
  112. public function getExtension(bool $withDot = false): string
  113. {
  114. if (null === $this->extension) {
  115. $this->setPathInfo();
  116. }
  117. return ($withDot ? '.' : '') . $this->extension;
  118. }
  119. /**
  120. * {@inheritdoc}
  121. * @see FileInterface::exists()
  122. */
  123. public function exists(): bool
  124. {
  125. return is_file($this->filepath);
  126. }
  127. /**
  128. * {@inheritdoc}
  129. * @see FileInterface::getCreationTime()
  130. */
  131. public function getCreationTime(): int
  132. {
  133. return is_file($this->filepath) ? filectime($this->filepath) : time();
  134. }
  135. /**
  136. * {@inheritdoc}
  137. * @see FileInterface::getModificationTime()
  138. */
  139. public function getModificationTime(): int
  140. {
  141. return is_file($this->filepath) ? filemtime($this->filepath) : time();
  142. }
  143. /**
  144. * {@inheritdoc}
  145. * @see FileInterface::lock()
  146. */
  147. public function lock(bool $block = true): bool
  148. {
  149. if (!$this->handle) {
  150. if (!$this->mkdir($this->getPath())) {
  151. throw new \RuntimeException('Creating directory failed for ' . $this->filepath);
  152. }
  153. $this->handle = @fopen($this->filepath, 'cb+');
  154. if (!$this->handle) {
  155. $error = error_get_last();
  156. throw new \RuntimeException("Opening file for writing failed on error {$error['message']}");
  157. }
  158. }
  159. $lock = $block ? LOCK_EX : LOCK_EX | LOCK_NB;
  160. // Some filesystems do not support file locks, only fail if another process holds the lock.
  161. $this->locked = flock($this->handle, $lock, $wouldblock) || !$wouldblock;
  162. return $this->locked;
  163. }
  164. /**
  165. * {@inheritdoc}
  166. * @see FileInterface::unlock()
  167. */
  168. public function unlock(): bool
  169. {
  170. if (!$this->handle) {
  171. return false;
  172. }
  173. if ($this->locked) {
  174. flock($this->handle, LOCK_UN);
  175. $this->locked = false;
  176. }
  177. fclose($this->handle);
  178. $this->handle = null;
  179. return true;
  180. }
  181. /**
  182. * {@inheritdoc}
  183. * @see FileInterface::isLocked()
  184. */
  185. public function isLocked(): bool
  186. {
  187. return $this->locked;
  188. }
  189. /**
  190. * {@inheritdoc}
  191. * @see FileInterface::isReadable()
  192. */
  193. public function isReadable(): bool
  194. {
  195. return is_readable($this->filepath) && is_file($this->filepath);
  196. }
  197. /**
  198. * {@inheritdoc}
  199. * @see FileInterface::isWritable()
  200. */
  201. public function isWritable(): bool
  202. {
  203. if (!file_exists($this->filepath)) {
  204. return $this->isWritablePath($this->getPath());
  205. }
  206. return is_writable($this->filepath) && is_file($this->filepath);
  207. }
  208. /**
  209. * {@inheritdoc}
  210. * @see FileInterface::load()
  211. */
  212. public function load()
  213. {
  214. return file_get_contents($this->filepath);
  215. }
  216. /**
  217. * {@inheritdoc}
  218. * @see FileInterface::save()
  219. */
  220. public function save($data): void
  221. {
  222. $filepath = $this->filepath;
  223. $dir = $this->getPath();
  224. if (!$this->mkdir($dir)) {
  225. throw new \RuntimeException('Creating directory failed for ' . $filepath);
  226. }
  227. try {
  228. if ($this->handle) {
  229. $tmp = true;
  230. // As we are using non-truncating locking, make sure that the file is empty before writing.
  231. if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $data) === false) {
  232. // Writing file failed, throw an error.
  233. $tmp = false;
  234. }
  235. } else {
  236. // Create file with a temporary name and rename it to make the save action atomic.
  237. $tmp = $this->tempname($filepath);
  238. if (@file_put_contents($tmp, $data) === false) {
  239. $tmp = false;
  240. } elseif (@rename($tmp, $filepath) === false) {
  241. @unlink($tmp);
  242. $tmp = false;
  243. }
  244. }
  245. } catch (\Exception $e) {
  246. $tmp = false;
  247. }
  248. if ($tmp === false) {
  249. throw new \RuntimeException('Failed to save file ' . $filepath);
  250. }
  251. // Touch the directory as well, thus marking it modified.
  252. @touch($dir);
  253. }
  254. /**
  255. * {@inheritdoc}
  256. * @see FileInterface::rename()
  257. */
  258. public function rename(string $path): bool
  259. {
  260. if ($this->exists() && !@rename($this->filepath, $path)) {
  261. return false;
  262. }
  263. $this->setFilepath($path);
  264. return true;
  265. }
  266. /**
  267. * {@inheritdoc}
  268. * @see FileInterface::delete()
  269. */
  270. public function delete(): bool
  271. {
  272. return @unlink($this->filepath);
  273. }
  274. /**
  275. * @param string $dir
  276. * @return bool
  277. * @throws \RuntimeException
  278. * @internal
  279. */
  280. protected function mkdir(string $dir): bool
  281. {
  282. // Silence error for open_basedir; should fail in mkdir instead.
  283. if (@is_dir($dir)) {
  284. return true;
  285. }
  286. $success = @mkdir($dir, 0777, true);
  287. if (!$success) {
  288. // Take yet another look, make sure that the folder doesn't exist.
  289. clearstatcache(true, $dir);
  290. if (!@is_dir($dir)) {
  291. return false;
  292. }
  293. }
  294. return true;
  295. }
  296. /**
  297. * @return array
  298. */
  299. protected function doSerialize(): array
  300. {
  301. return [
  302. 'filepath' => $this->filepath
  303. ];
  304. }
  305. /**
  306. * @param array $serialized
  307. */
  308. protected function doUnserialize(array $serialized): void
  309. {
  310. $this->setFilepath($serialized['filepath']);
  311. }
  312. /**
  313. * @param string $filepath
  314. */
  315. protected function setFilepath(string $filepath): void
  316. {
  317. $this->filepath = $filepath;
  318. $this->filename = null;
  319. $this->basename = null;
  320. $this->path = null;
  321. $this->extension = null;
  322. }
  323. protected function setPathInfo(): void
  324. {
  325. $pathInfo = $this->filesystem->pathinfo($this->filepath);
  326. $this->filename = $pathInfo['filename'] ?? null;
  327. $this->basename = $pathInfo['basename'] ?? null;
  328. $this->path = $pathInfo['dirname'] ?? null;
  329. $this->extension = $pathInfo['extension'] ?? null;
  330. }
  331. /**
  332. * @param string $dir
  333. * @return bool
  334. * @internal
  335. */
  336. protected function isWritablePath(string $dir): bool
  337. {
  338. if ($dir === '') {
  339. return false;
  340. }
  341. if (!file_exists($dir)) {
  342. // Recursively look up in the directory tree.
  343. return $this->isWritablePath($this->filesystem->parent($dir));
  344. }
  345. return is_dir($dir) && is_writable($dir);
  346. }
  347. /**
  348. * @param string $filename
  349. * @param int $length
  350. * @return string
  351. */
  352. protected function tempname(string $filename, int $length = 5)
  353. {
  354. do {
  355. $test = $filename . substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
  356. } while (file_exists($test));
  357. return $test;
  358. }
  359. }