123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425 |
- <?php
- declare(strict_types=1);
- /**
- * @package Grav\Framework\File
- *
- * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
- * @license MIT License; see LICENSE file for details.
- */
- namespace Grav\Framework\File;
- use Grav\Framework\File\Interfaces\FileInterface;
- use Grav\Framework\Filesystem\Filesystem;
- class AbstractFile implements FileInterface
- {
- /** @var Filesystem */
- private $filesystem;
- /** @var string */
- private $filepath;
- /** @var string|null */
- private $filename;
- /** @var string|null */
- private $path;
- /** @var string|null */
- private $basename;
- /** @var string|null */
- private $extension;
- /** @var resource|null */
- private $handle;
- /** @var bool */
- private $locked = false;
- /**
- * @param string $filepath
- * @param Filesystem|null $filesystem
- */
- public function __construct(string $filepath, Filesystem $filesystem = null)
- {
- $this->filesystem = $filesystem ?? Filesystem::getInstance();
- $this->setFilepath($filepath);
- }
- /**
- * Unlock file when the object gets destroyed.
- */
- public function __destruct()
- {
- if ($this->isLocked()) {
- $this->unlock();
- }
- }
- public function __clone()
- {
- $this->handle = null;
- $this->locked = false;
- }
- /**
- * @return string
- */
- public function serialize(): string
- {
- return serialize($this->doSerialize());
- }
- /**
- * @param string $serialized
- */
- public function unserialize($serialized): void
- {
- $this->doUnserialize(unserialize($serialized, ['allowed_classes' => false]));
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getFilePath()
- */
- public function getFilePath(): string
- {
- return $this->filepath;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getPath()
- */
- public function getPath(): string
- {
- if (null === $this->path) {
- $this->setPathInfo();
- }
- return $this->path;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getFilename()
- */
- public function getFilename(): string
- {
- if (null === $this->filename) {
- $this->setPathInfo();
- }
- return $this->filename;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getBasename()
- */
- public function getBasename(): string
- {
- if (null === $this->basename) {
- $this->setPathInfo();
- }
- return $this->basename;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getExtension()
- */
- public function getExtension(bool $withDot = false): string
- {
- if (null === $this->extension) {
- $this->setPathInfo();
- }
- return ($withDot ? '.' : '') . $this->extension;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::exists()
- */
- public function exists(): bool
- {
- return is_file($this->filepath);
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getCreationTime()
- */
- public function getCreationTime(): int
- {
- return is_file($this->filepath) ? filectime($this->filepath) : time();
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::getModificationTime()
- */
- public function getModificationTime(): int
- {
- return is_file($this->filepath) ? filemtime($this->filepath) : time();
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::lock()
- */
- public function lock(bool $block = true): bool
- {
- if (!$this->handle) {
- if (!$this->mkdir($this->getPath())) {
- throw new \RuntimeException('Creating directory failed for ' . $this->filepath);
- }
- $this->handle = @fopen($this->filepath, 'cb+');
- if (!$this->handle) {
- $error = error_get_last();
- throw new \RuntimeException("Opening file for writing failed on error {$error['message']}");
- }
- }
- $lock = $block ? LOCK_EX : LOCK_EX | LOCK_NB;
- // Some filesystems do not support file locks, only fail if another process holds the lock.
- $this->locked = flock($this->handle, $lock, $wouldblock) || !$wouldblock;
- return $this->locked;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::unlock()
- */
- public function unlock(): bool
- {
- if (!$this->handle) {
- return false;
- }
- if ($this->locked) {
- flock($this->handle, LOCK_UN);
- $this->locked = false;
- }
- fclose($this->handle);
- $this->handle = null;
- return true;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::isLocked()
- */
- public function isLocked(): bool
- {
- return $this->locked;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::isReadable()
- */
- public function isReadable(): bool
- {
- return is_readable($this->filepath) && is_file($this->filepath);
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::isWritable()
- */
- public function isWritable(): bool
- {
- if (!file_exists($this->filepath)) {
- return $this->isWritablePath($this->getPath());
- }
- return is_writable($this->filepath) && is_file($this->filepath);
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::load()
- */
- public function load()
- {
- return file_get_contents($this->filepath);
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::save()
- */
- public function save($data): void
- {
- $filepath = $this->filepath;
- $dir = $this->getPath();
- if (!$this->mkdir($dir)) {
- throw new \RuntimeException('Creating directory failed for ' . $filepath);
- }
- try {
- if ($this->handle) {
- $tmp = true;
- // As we are using non-truncating locking, make sure that the file is empty before writing.
- if (@ftruncate($this->handle, 0) === false || @fwrite($this->handle, $data) === false) {
- // Writing file failed, throw an error.
- $tmp = false;
- }
- } else {
- // Create file with a temporary name and rename it to make the save action atomic.
- $tmp = $this->tempname($filepath);
- if (@file_put_contents($tmp, $data) === false) {
- $tmp = false;
- } elseif (@rename($tmp, $filepath) === false) {
- @unlink($tmp);
- $tmp = false;
- }
- }
- } catch (\Exception $e) {
- $tmp = false;
- }
- if ($tmp === false) {
- throw new \RuntimeException('Failed to save file ' . $filepath);
- }
- // Touch the directory as well, thus marking it modified.
- @touch($dir);
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::rename()
- */
- public function rename(string $path): bool
- {
- if ($this->exists() && !@rename($this->filepath, $path)) {
- return false;
- }
- $this->setFilepath($path);
- return true;
- }
- /**
- * {@inheritdoc}
- * @see FileInterface::delete()
- */
- public function delete(): bool
- {
- return @unlink($this->filepath);
- }
- /**
- * @param string $dir
- * @return bool
- * @throws \RuntimeException
- * @internal
- */
- protected function mkdir(string $dir): bool
- {
- // Silence error for open_basedir; should fail in mkdir instead.
- if (@is_dir($dir)) {
- return true;
- }
- $success = @mkdir($dir, 0777, true);
- if (!$success) {
- // Take yet another look, make sure that the folder doesn't exist.
- clearstatcache(true, $dir);
- if (!@is_dir($dir)) {
- return false;
- }
- }
- return true;
- }
- /**
- * @return array
- */
- protected function doSerialize(): array
- {
- return [
- 'filepath' => $this->filepath
- ];
- }
- /**
- * @param array $serialized
- */
- protected function doUnserialize(array $serialized): void
- {
- $this->setFilepath($serialized['filepath']);
- }
- /**
- * @param string $filepath
- */
- protected function setFilepath(string $filepath): void
- {
- $this->filepath = $filepath;
- $this->filename = null;
- $this->basename = null;
- $this->path = null;
- $this->extension = null;
- }
- protected function setPathInfo(): void
- {
- $pathInfo = $this->filesystem->pathinfo($this->filepath);
- $this->filename = $pathInfo['filename'] ?? null;
- $this->basename = $pathInfo['basename'] ?? null;
- $this->path = $pathInfo['dirname'] ?? null;
- $this->extension = $pathInfo['extension'] ?? null;
- }
- /**
- * @param string $dir
- * @return bool
- * @internal
- */
- protected function isWritablePath(string $dir): bool
- {
- if ($dir === '') {
- return false;
- }
- if (!file_exists($dir)) {
- // Recursively look up in the directory tree.
- return $this->isWritablePath($this->filesystem->parent($dir));
- }
- return is_dir($dir) && is_writable($dir);
- }
- /**
- * @param string $filename
- * @param int $length
- * @return string
- */
- protected function tempname(string $filename, int $length = 5)
- {
- do {
- $test = $filename . substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
- } while (file_exists($test));
- return $test;
- }
- }
|