LocalFilesystemAdapter.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. <?php
  2. declare(strict_types=1);
  3. namespace League\Flysystem\Local;
  4. use const DIRECTORY_SEPARATOR;
  5. use const LOCK_EX;
  6. use DirectoryIterator;
  7. use FilesystemIterator;
  8. use Generator;
  9. use League\Flysystem\ChecksumProvider;
  10. use League\Flysystem\Config;
  11. use League\Flysystem\DirectoryAttributes;
  12. use League\Flysystem\FileAttributes;
  13. use League\Flysystem\FilesystemAdapter;
  14. use League\Flysystem\PathPrefixer;
  15. use League\Flysystem\SymbolicLinkEncountered;
  16. use League\Flysystem\UnableToCopyFile;
  17. use League\Flysystem\UnableToCreateDirectory;
  18. use League\Flysystem\UnableToDeleteDirectory;
  19. use League\Flysystem\UnableToDeleteFile;
  20. use League\Flysystem\UnableToMoveFile;
  21. use League\Flysystem\UnableToProvideChecksum;
  22. use League\Flysystem\UnableToReadFile;
  23. use League\Flysystem\UnableToRetrieveMetadata;
  24. use League\Flysystem\UnableToSetVisibility;
  25. use League\Flysystem\UnableToWriteFile;
  26. use League\Flysystem\UnixVisibility\PortableVisibilityConverter;
  27. use League\Flysystem\UnixVisibility\VisibilityConverter;
  28. use League\MimeTypeDetection\FinfoMimeTypeDetector;
  29. use League\MimeTypeDetection\MimeTypeDetector;
  30. use RecursiveDirectoryIterator;
  31. use RecursiveIteratorIterator;
  32. use SplFileInfo;
  33. use Throwable;
  34. use function chmod;
  35. use function clearstatcache;
  36. use function dirname;
  37. use function error_clear_last;
  38. use function error_get_last;
  39. use function file_exists;
  40. use function file_put_contents;
  41. use function hash_file;
  42. use function is_dir;
  43. use function is_file;
  44. use function mkdir;
  45. use function rename;
  46. class LocalFilesystemAdapter implements FilesystemAdapter, ChecksumProvider
  47. {
  48. /**
  49. * @var int
  50. */
  51. public const SKIP_LINKS = 0001;
  52. /**
  53. * @var int
  54. */
  55. public const DISALLOW_LINKS = 0002;
  56. private PathPrefixer $prefixer;
  57. private VisibilityConverter $visibility;
  58. private MimeTypeDetector $mimeTypeDetector;
  59. private string $rootLocation;
  60. /**
  61. * @var bool
  62. */
  63. private $rootLocationIsSetup = false;
  64. public function __construct(
  65. string $location,
  66. ?VisibilityConverter $visibility = null,
  67. private int $writeFlags = LOCK_EX,
  68. private int $linkHandling = self::DISALLOW_LINKS,
  69. ?MimeTypeDetector $mimeTypeDetector = null,
  70. bool $lazyRootCreation = false,
  71. bool $useInconclusiveMimeTypeFallback = false,
  72. ) {
  73. $this->prefixer = new PathPrefixer($location, DIRECTORY_SEPARATOR);
  74. $visibility ??= new PortableVisibilityConverter();
  75. $this->visibility = $visibility;
  76. $this->rootLocation = $location;
  77. $this->mimeTypeDetector = $mimeTypeDetector ?? new FallbackMimeTypeDetector(
  78. detector: new FinfoMimeTypeDetector(),
  79. useInconclusiveMimeTypeFallback: $useInconclusiveMimeTypeFallback,
  80. );
  81. if ( ! $lazyRootCreation) {
  82. $this->ensureRootDirectoryExists();
  83. }
  84. }
  85. private function ensureRootDirectoryExists(): void
  86. {
  87. if ($this->rootLocationIsSetup) {
  88. return;
  89. }
  90. $this->ensureDirectoryExists($this->rootLocation, $this->visibility->defaultForDirectories());
  91. $this->rootLocationIsSetup = true;
  92. }
  93. public function write(string $path, string $contents, Config $config): void
  94. {
  95. $this->writeToFile($path, $contents, $config);
  96. }
  97. public function writeStream(string $path, $contents, Config $config): void
  98. {
  99. $this->writeToFile($path, $contents, $config);
  100. }
  101. /**
  102. * @param resource|string $contents
  103. */
  104. private function writeToFile(string $path, $contents, Config $config): void
  105. {
  106. $prefixedLocation = $this->prefixer->prefixPath($path);
  107. $this->ensureRootDirectoryExists();
  108. $this->ensureDirectoryExists(
  109. dirname($prefixedLocation),
  110. $this->resolveDirectoryVisibility($config->get(Config::OPTION_DIRECTORY_VISIBILITY))
  111. );
  112. error_clear_last();
  113. if (@file_put_contents($prefixedLocation, $contents, $this->writeFlags) === false) {
  114. throw UnableToWriteFile::atLocation($path, error_get_last()['message'] ?? '');
  115. }
  116. if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
  117. $this->setVisibility($path, (string) $visibility);
  118. }
  119. }
  120. public function delete(string $path): void
  121. {
  122. $location = $this->prefixer->prefixPath($path);
  123. if ( ! file_exists($location)) {
  124. return;
  125. }
  126. error_clear_last();
  127. if ( ! @unlink($location)) {
  128. throw UnableToDeleteFile::atLocation($location, error_get_last()['message'] ?? '');
  129. }
  130. }
  131. public function deleteDirectory(string $prefix): void
  132. {
  133. $location = $this->prefixer->prefixPath($prefix);
  134. if ( ! is_dir($location)) {
  135. return;
  136. }
  137. $contents = $this->listDirectoryRecursively($location, RecursiveIteratorIterator::CHILD_FIRST);
  138. /** @var SplFileInfo $file */
  139. foreach ($contents as $file) {
  140. if ( ! $this->deleteFileInfoObject($file)) {
  141. throw UnableToDeleteDirectory::atLocation($prefix, "Unable to delete file at " . $file->getPathname());
  142. }
  143. }
  144. unset($contents);
  145. if ( ! @rmdir($location)) {
  146. throw UnableToDeleteDirectory::atLocation($prefix, error_get_last()['message'] ?? '');
  147. }
  148. }
  149. private function listDirectoryRecursively(
  150. string $path,
  151. int $mode = RecursiveIteratorIterator::SELF_FIRST
  152. ): Generator {
  153. if ( ! is_dir($path)) {
  154. return;
  155. }
  156. yield from new RecursiveIteratorIterator(
  157. new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
  158. $mode
  159. );
  160. }
  161. protected function deleteFileInfoObject(SplFileInfo $file): bool
  162. {
  163. switch ($file->getType()) {
  164. case 'dir':
  165. return @rmdir((string) $file->getRealPath());
  166. case 'link':
  167. return @unlink((string) $file->getPathname());
  168. default:
  169. return @unlink((string) $file->getRealPath());
  170. }
  171. }
  172. public function listContents(string $path, bool $deep): iterable
  173. {
  174. $location = $this->prefixer->prefixPath($path);
  175. if ( ! is_dir($location)) {
  176. return;
  177. }
  178. /** @var SplFileInfo[] $iterator */
  179. $iterator = $deep ? $this->listDirectoryRecursively($location) : $this->listDirectory($location);
  180. foreach ($iterator as $fileInfo) {
  181. $pathName = $fileInfo->getPathname();
  182. try {
  183. if ($fileInfo->isLink()) {
  184. if ($this->linkHandling & self::SKIP_LINKS) {
  185. continue;
  186. }
  187. throw SymbolicLinkEncountered::atLocation($pathName);
  188. }
  189. $path = $this->prefixer->stripPrefix($pathName);
  190. $lastModified = $fileInfo->getMTime();
  191. $isDirectory = $fileInfo->isDir();
  192. $permissions = octdec(substr(sprintf('%o', $fileInfo->getPerms()), -4));
  193. $visibility = $isDirectory ? $this->visibility->inverseForDirectory($permissions) : $this->visibility->inverseForFile($permissions);
  194. yield $isDirectory ? new DirectoryAttributes(str_replace('\\', '/', $path), $visibility, $lastModified) : new FileAttributes(
  195. str_replace('\\', '/', $path),
  196. $fileInfo->getSize(),
  197. $visibility,
  198. $lastModified
  199. );
  200. } catch (Throwable $exception) {
  201. if (file_exists($pathName)) {
  202. throw $exception;
  203. }
  204. }
  205. }
  206. }
  207. public function move(string $source, string $destination, Config $config): void
  208. {
  209. $sourcePath = $this->prefixer->prefixPath($source);
  210. $destinationPath = $this->prefixer->prefixPath($destination);
  211. $this->ensureRootDirectoryExists();
  212. $this->ensureDirectoryExists(
  213. dirname($destinationPath),
  214. $this->resolveDirectoryVisibility($config->get(Config::OPTION_DIRECTORY_VISIBILITY))
  215. );
  216. error_clear_last();
  217. if ( ! @rename($sourcePath, $destinationPath)) {
  218. throw UnableToMoveFile::because(error_get_last()['message'] ?? 'unknown reason', $source, $destination);
  219. }
  220. if ($visibility = $config->get(Config::OPTION_VISIBILITY)) {
  221. $this->setVisibility($destination, (string) $visibility);
  222. }
  223. }
  224. public function copy(string $source, string $destination, Config $config): void
  225. {
  226. $sourcePath = $this->prefixer->prefixPath($source);
  227. $destinationPath = $this->prefixer->prefixPath($destination);
  228. $this->ensureRootDirectoryExists();
  229. $this->ensureDirectoryExists(
  230. dirname($destinationPath),
  231. $this->resolveDirectoryVisibility($config->get(Config::OPTION_DIRECTORY_VISIBILITY))
  232. );
  233. error_clear_last();
  234. if ($sourcePath !== $destinationPath && ! @copy($sourcePath, $destinationPath)) {
  235. throw UnableToCopyFile::because(error_get_last()['message'] ?? 'unknown', $source, $destination);
  236. }
  237. $visibility = $config->get(
  238. Config::OPTION_VISIBILITY,
  239. $config->get(Config::OPTION_RETAIN_VISIBILITY, true)
  240. ? $this->visibility($source)->visibility()
  241. : null,
  242. );
  243. if ($visibility) {
  244. $this->setVisibility($destination, (string) $visibility);
  245. }
  246. }
  247. public function read(string $path): string
  248. {
  249. $location = $this->prefixer->prefixPath($path);
  250. error_clear_last();
  251. $contents = @file_get_contents($location);
  252. if ($contents === false) {
  253. throw UnableToReadFile::fromLocation($path, error_get_last()['message'] ?? '');
  254. }
  255. return $contents;
  256. }
  257. public function readStream(string $path)
  258. {
  259. $location = $this->prefixer->prefixPath($path);
  260. error_clear_last();
  261. $contents = @fopen($location, 'rb');
  262. if ($contents === false) {
  263. throw UnableToReadFile::fromLocation($path, error_get_last()['message'] ?? '');
  264. }
  265. return $contents;
  266. }
  267. protected function ensureDirectoryExists(string $dirname, int $visibility): void
  268. {
  269. if (is_dir($dirname)) {
  270. return;
  271. }
  272. error_clear_last();
  273. if ( ! @mkdir($dirname, $visibility, true)) {
  274. $mkdirError = error_get_last();
  275. }
  276. clearstatcache(true, $dirname);
  277. if ( ! is_dir($dirname)) {
  278. $errorMessage = isset($mkdirError['message']) ? $mkdirError['message'] : '';
  279. throw UnableToCreateDirectory::atLocation($dirname, $errorMessage);
  280. }
  281. }
  282. public function fileExists(string $location): bool
  283. {
  284. $location = $this->prefixer->prefixPath($location);
  285. clearstatcache();
  286. return is_file($location);
  287. }
  288. public function directoryExists(string $location): bool
  289. {
  290. $location = $this->prefixer->prefixPath($location);
  291. clearstatcache();
  292. return is_dir($location);
  293. }
  294. public function createDirectory(string $path, Config $config): void
  295. {
  296. $this->ensureRootDirectoryExists();
  297. $location = $this->prefixer->prefixPath($path);
  298. $visibility = $config->get(Config::OPTION_VISIBILITY, $config->get(Config::OPTION_DIRECTORY_VISIBILITY));
  299. $permissions = $this->resolveDirectoryVisibility($visibility);
  300. if (is_dir($location)) {
  301. $this->setPermissions($location, $permissions);
  302. return;
  303. }
  304. error_clear_last();
  305. if ( ! @mkdir($location, $permissions, true)) {
  306. throw UnableToCreateDirectory::atLocation($path, error_get_last()['message'] ?? '');
  307. }
  308. }
  309. public function setVisibility(string $path, string $visibility): void
  310. {
  311. $path = $this->prefixer->prefixPath($path);
  312. $visibility = is_dir($path) ? $this->visibility->forDirectory($visibility) : $this->visibility->forFile(
  313. $visibility
  314. );
  315. $this->setPermissions($path, $visibility);
  316. }
  317. public function visibility(string $path): FileAttributes
  318. {
  319. $location = $this->prefixer->prefixPath($path);
  320. clearstatcache(false, $location);
  321. error_clear_last();
  322. $fileperms = @fileperms($location);
  323. if ($fileperms === false) {
  324. throw UnableToRetrieveMetadata::visibility($path, error_get_last()['message'] ?? '');
  325. }
  326. $permissions = $fileperms & 0777;
  327. $visibility = $this->visibility->inverseForFile($permissions);
  328. return new FileAttributes($path, null, $visibility);
  329. }
  330. private function resolveDirectoryVisibility(?string $visibility): int
  331. {
  332. return $visibility === null ? $this->visibility->defaultForDirectories() : $this->visibility->forDirectory(
  333. $visibility
  334. );
  335. }
  336. public function mimeType(string $path): FileAttributes
  337. {
  338. $location = $this->prefixer->prefixPath($path);
  339. error_clear_last();
  340. if ( ! is_file($location)) {
  341. throw UnableToRetrieveMetadata::mimeType($location, 'No such file exists.');
  342. }
  343. $mimeType = $this->mimeTypeDetector->detectMimeTypeFromFile($location);
  344. if ($mimeType === null) {
  345. throw UnableToRetrieveMetadata::mimeType($path, error_get_last()['message'] ?? '');
  346. }
  347. return new FileAttributes($path, null, null, null, $mimeType);
  348. }
  349. public function lastModified(string $path): FileAttributes
  350. {
  351. $location = $this->prefixer->prefixPath($path);
  352. clearstatcache();
  353. error_clear_last();
  354. $lastModified = @filemtime($location);
  355. if ($lastModified === false) {
  356. throw UnableToRetrieveMetadata::lastModified($path, error_get_last()['message'] ?? '');
  357. }
  358. return new FileAttributes($path, null, null, $lastModified);
  359. }
  360. public function fileSize(string $path): FileAttributes
  361. {
  362. $location = $this->prefixer->prefixPath($path);
  363. clearstatcache();
  364. error_clear_last();
  365. if (is_file($location) && ($fileSize = @filesize($location)) !== false) {
  366. return new FileAttributes($path, $fileSize);
  367. }
  368. throw UnableToRetrieveMetadata::fileSize($path, error_get_last()['message'] ?? '');
  369. }
  370. public function checksum(string $path, Config $config): string
  371. {
  372. $algo = $config->get('checksum_algo', 'md5');
  373. $location = $this->prefixer->prefixPath($path);
  374. error_clear_last();
  375. $checksum = @hash_file($algo, $location);
  376. if ($checksum === false) {
  377. throw new UnableToProvideChecksum(error_get_last()['message'] ?? '', $path);
  378. }
  379. return $checksum;
  380. }
  381. private function listDirectory(string $location): Generator
  382. {
  383. $iterator = new DirectoryIterator($location);
  384. foreach ($iterator as $item) {
  385. if ($item->isDot()) {
  386. continue;
  387. }
  388. yield $item;
  389. }
  390. }
  391. private function setPermissions(string $location, int $visibility): void
  392. {
  393. error_clear_last();
  394. if ( ! @chmod($location, $visibility)) {
  395. $extraMessage = error_get_last()['message'] ?? '';
  396. throw UnableToSetVisibility::atLocation($this->prefixer->stripPrefix($location), $extraMessage);
  397. }
  398. }
  399. }