AbstractFile.php 10 KB

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