AmazonS3.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author André Gaul <gaul@web-yard.de>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author Christian Berendt <berendt@b1-systems.de>
  8. * @author Christopher T. Johnson <ctjctj@gmail.com>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author enoch <lanxenet@hotmail.com>
  12. * @author Johan Björk <johanimon@gmail.com>
  13. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  14. * @author Julius Härtl <jus@bitgrid.net>
  15. * @author Martin Mattel <martin.mattel@diemattels.at>
  16. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  17. * @author Morris Jobke <hey@morrisjobke.de>
  18. * @author Philipp Kapfer <philipp.kapfer@gmx.at>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Robin McCorkell <robin@mccorkell.me.uk>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Thomas Müller <thomas.mueller@tmit.eu>
  23. * @author Vincent Petry <vincent@nextcloud.com>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OCA\Files_External\Lib\Storage;
  41. use Aws\Result;
  42. use Aws\S3\Exception\S3Exception;
  43. use Aws\S3\S3Client;
  44. use Icewind\Streams\CallbackWrapper;
  45. use Icewind\Streams\IteratorDirectory;
  46. use OCP\Cache\CappedMemoryCache;
  47. use OC\Files\Cache\CacheEntry;
  48. use OC\Files\ObjectStore\S3ConnectionTrait;
  49. use OC\Files\ObjectStore\S3ObjectTrait;
  50. use OCP\Constants;
  51. use OCP\Files\FileInfo;
  52. use OCP\Files\IMimeTypeDetector;
  53. use OCP\ICacheFactory;
  54. use OCP\IMemcache;
  55. use OCP\Server;
  56. use OCP\ICache;
  57. use Psr\Log\LoggerInterface;
  58. class AmazonS3 extends \OC\Files\Storage\Common {
  59. use S3ConnectionTrait;
  60. use S3ObjectTrait;
  61. private LoggerInterface $logger;
  62. public function needsPartFile() {
  63. return false;
  64. }
  65. /** @var CappedMemoryCache<array|false> */
  66. private CappedMemoryCache $objectCache;
  67. /** @var CappedMemoryCache<bool> */
  68. private CappedMemoryCache $directoryCache;
  69. /** @var CappedMemoryCache<array> */
  70. private CappedMemoryCache $filesCache;
  71. private IMimeTypeDetector $mimeDetector;
  72. private ?bool $versioningEnabled = null;
  73. private ICache $memCache;
  74. public function __construct($parameters) {
  75. parent::__construct($parameters);
  76. $this->parseParams($parameters);
  77. $this->id = 'amazon::external::' . md5($this->params['hostname'] . ':' . $this->params['bucket'] . ':' . $this->params['key']);
  78. $this->objectCache = new CappedMemoryCache();
  79. $this->directoryCache = new CappedMemoryCache();
  80. $this->filesCache = new CappedMemoryCache();
  81. $this->mimeDetector = Server::get(IMimeTypeDetector::class);
  82. /** @var ICacheFactory $cacheFactory */
  83. $cacheFactory = Server::get(ICacheFactory::class);
  84. $this->memCache = $cacheFactory->createLocal('s3-external');
  85. $this->logger = Server::get(LoggerInterface::class);
  86. }
  87. /**
  88. * @param string $path
  89. * @return string correctly encoded path
  90. */
  91. private function normalizePath($path) {
  92. $path = trim($path, '/');
  93. if (!$path) {
  94. $path = '.';
  95. }
  96. return $path;
  97. }
  98. private function isRoot($path) {
  99. return $path === '.';
  100. }
  101. private function cleanKey($path) {
  102. if ($this->isRoot($path)) {
  103. return '/';
  104. }
  105. return $path;
  106. }
  107. private function clearCache() {
  108. $this->objectCache = new CappedMemoryCache();
  109. $this->directoryCache = new CappedMemoryCache();
  110. $this->filesCache = new CappedMemoryCache();
  111. }
  112. private function invalidateCache($key) {
  113. unset($this->objectCache[$key]);
  114. $keys = array_keys($this->objectCache->getData());
  115. $keyLength = strlen($key);
  116. foreach ($keys as $existingKey) {
  117. if (substr($existingKey, 0, $keyLength) === $key) {
  118. unset($this->objectCache[$existingKey]);
  119. }
  120. }
  121. unset($this->filesCache[$key]);
  122. $keys = array_keys($this->directoryCache->getData());
  123. $keyLength = strlen($key);
  124. foreach ($keys as $existingKey) {
  125. if (substr($existingKey, 0, $keyLength) === $key) {
  126. unset($this->directoryCache[$existingKey]);
  127. }
  128. }
  129. unset($this->directoryCache[$key]);
  130. }
  131. /**
  132. * @return array|false
  133. */
  134. private function headObject(string $key) {
  135. if (!isset($this->objectCache[$key])) {
  136. try {
  137. $this->objectCache[$key] = $this->getConnection()->headObject([
  138. 'Bucket' => $this->bucket,
  139. 'Key' => $key
  140. ])->toArray();
  141. } catch (S3Exception $e) {
  142. if ($e->getStatusCode() >= 500) {
  143. throw $e;
  144. }
  145. $this->objectCache[$key] = false;
  146. }
  147. }
  148. if (is_array($this->objectCache[$key]) && !isset($this->objectCache[$key]["Key"])) {
  149. /** @psalm-suppress InvalidArgument Psalm doesn't understand nested arrays well */
  150. $this->objectCache[$key]["Key"] = $key;
  151. }
  152. return $this->objectCache[$key];
  153. }
  154. /**
  155. * Return true if directory exists
  156. *
  157. * There are no folders in s3. A folder like structure could be archived
  158. * by prefixing files with the folder name.
  159. *
  160. * Implementation from flysystem-aws-s3-v3:
  161. * https://github.com/thephpleague/flysystem-aws-s3-v3/blob/8241e9cc5b28f981e0d24cdaf9867f14c7498ae4/src/AwsS3Adapter.php#L670-L694
  162. *
  163. * @param $path
  164. * @return bool
  165. * @throws \Exception
  166. */
  167. private function doesDirectoryExist($path) {
  168. if ($path === '.' || $path === '') {
  169. return true;
  170. }
  171. $path = rtrim($path, '/') . '/';
  172. if (isset($this->directoryCache[$path])) {
  173. return $this->directoryCache[$path];
  174. }
  175. try {
  176. // Maybe this isn't an actual key, but a prefix.
  177. // Do a prefix listing of objects to determine.
  178. $result = $this->getConnection()->listObjectsV2([
  179. 'Bucket' => $this->bucket,
  180. 'Prefix' => $path,
  181. 'MaxKeys' => 1,
  182. ]);
  183. if (isset($result['Contents'])) {
  184. $this->directoryCache[$path] = true;
  185. return true;
  186. }
  187. // empty directories have their own object
  188. $object = $this->headObject($path);
  189. if ($object) {
  190. $this->directoryCache[$path] = true;
  191. return true;
  192. }
  193. } catch (S3Exception $e) {
  194. if ($e->getStatusCode() >= 400 && $e->getStatusCode() < 500) {
  195. $this->directoryCache[$path] = false;
  196. }
  197. throw $e;
  198. }
  199. $this->directoryCache[$path] = false;
  200. return false;
  201. }
  202. /**
  203. * Remove a file or folder
  204. *
  205. * @param string $path
  206. * @return bool
  207. */
  208. protected function remove($path) {
  209. // remember fileType to reduce http calls
  210. $fileType = $this->filetype($path);
  211. if ($fileType === 'dir') {
  212. return $this->rmdir($path);
  213. } elseif ($fileType === 'file') {
  214. return $this->unlink($path);
  215. } else {
  216. return false;
  217. }
  218. }
  219. public function mkdir($path) {
  220. $path = $this->normalizePath($path);
  221. if ($this->is_dir($path)) {
  222. return false;
  223. }
  224. try {
  225. $this->getConnection()->putObject([
  226. 'Bucket' => $this->bucket,
  227. 'Key' => $path . '/',
  228. 'Body' => '',
  229. 'ContentType' => FileInfo::MIMETYPE_FOLDER
  230. ]);
  231. $this->testTimeout();
  232. } catch (S3Exception $e) {
  233. $this->logger->error($e->getMessage(), [
  234. 'app' => 'files_external',
  235. 'exception' => $e,
  236. ]);
  237. return false;
  238. }
  239. $this->invalidateCache($path);
  240. return true;
  241. }
  242. public function file_exists($path) {
  243. return $this->filetype($path) !== false;
  244. }
  245. public function rmdir($path) {
  246. $path = $this->normalizePath($path);
  247. if ($this->isRoot($path)) {
  248. return $this->clearBucket();
  249. }
  250. if (!$this->file_exists($path)) {
  251. return false;
  252. }
  253. $this->invalidateCache($path);
  254. return $this->batchDelete($path);
  255. }
  256. protected function clearBucket() {
  257. $this->clearCache();
  258. return $this->batchDelete();
  259. }
  260. private function batchDelete($path = null) {
  261. // TODO explore using https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.BatchDelete.html
  262. $params = [
  263. 'Bucket' => $this->bucket
  264. ];
  265. if ($path !== null) {
  266. $params['Prefix'] = $path . '/';
  267. }
  268. try {
  269. $connection = $this->getConnection();
  270. // Since there are no real directories on S3, we need
  271. // to delete all objects prefixed with the path.
  272. do {
  273. // instead of the iterator, manually loop over the list ...
  274. $objects = $connection->listObjects($params);
  275. // ... so we can delete the files in batches
  276. if (isset($objects['Contents'])) {
  277. $connection->deleteObjects([
  278. 'Bucket' => $this->bucket,
  279. 'Delete' => [
  280. 'Objects' => $objects['Contents']
  281. ]
  282. ]);
  283. $this->testTimeout();
  284. }
  285. // we reached the end when the list is no longer truncated
  286. } while ($objects['IsTruncated']);
  287. if ($path !== '' && $path !== null) {
  288. $this->deleteObject($path);
  289. }
  290. } catch (S3Exception $e) {
  291. $this->logger->error($e->getMessage(), [
  292. 'app' => 'files_external',
  293. 'exception' => $e,
  294. ]);
  295. return false;
  296. }
  297. return true;
  298. }
  299. public function opendir($path) {
  300. try {
  301. $content = iterator_to_array($this->getDirectoryContent($path));
  302. return IteratorDirectory::wrap(array_map(function (array $item) {
  303. return $item['name'];
  304. }, $content));
  305. } catch (S3Exception $e) {
  306. return false;
  307. }
  308. }
  309. public function stat($path) {
  310. $path = $this->normalizePath($path);
  311. if ($this->is_dir($path)) {
  312. $stat = $this->getDirectoryMetaData($path);
  313. } else {
  314. $object = $this->headObject($path);
  315. if ($object === false) {
  316. return false;
  317. }
  318. $stat = $this->objectToMetaData($object);
  319. }
  320. $stat['atime'] = time();
  321. return $stat;
  322. }
  323. /**
  324. * Return content length for object
  325. *
  326. * When the information is already present (e.g. opendir has been called before)
  327. * this value is return. Otherwise a headObject is emitted.
  328. *
  329. * @param $path
  330. * @return int|mixed
  331. */
  332. private function getContentLength($path) {
  333. if (isset($this->filesCache[$path])) {
  334. return (int)$this->filesCache[$path]['ContentLength'];
  335. }
  336. $result = $this->headObject($path);
  337. if (isset($result['ContentLength'])) {
  338. return (int)$result['ContentLength'];
  339. }
  340. return 0;
  341. }
  342. /**
  343. * Return last modified for object
  344. *
  345. * When the information is already present (e.g. opendir has been called before)
  346. * this value is return. Otherwise a headObject is emitted.
  347. *
  348. * @param $path
  349. * @return mixed|string
  350. */
  351. private function getLastModified($path) {
  352. if (isset($this->filesCache[$path])) {
  353. return $this->filesCache[$path]['LastModified'];
  354. }
  355. $result = $this->headObject($path);
  356. if (isset($result['LastModified'])) {
  357. return $result['LastModified'];
  358. }
  359. return 'now';
  360. }
  361. public function is_dir($path) {
  362. $path = $this->normalizePath($path);
  363. if (isset($this->filesCache[$path])) {
  364. return false;
  365. }
  366. try {
  367. return $this->doesDirectoryExist($path);
  368. } catch (S3Exception $e) {
  369. $this->logger->error($e->getMessage(), [
  370. 'app' => 'files_external',
  371. 'exception' => $e,
  372. ]);
  373. return false;
  374. }
  375. }
  376. public function filetype($path) {
  377. $path = $this->normalizePath($path);
  378. if ($this->isRoot($path)) {
  379. return 'dir';
  380. }
  381. try {
  382. if (isset($this->directoryCache[$path]) && $this->directoryCache[$path]) {
  383. return 'dir';
  384. }
  385. if (isset($this->filesCache[$path]) || $this->headObject($path)) {
  386. return 'file';
  387. }
  388. if ($this->doesDirectoryExist($path)) {
  389. return 'dir';
  390. }
  391. } catch (S3Exception $e) {
  392. $this->logger->error($e->getMessage(), [
  393. 'app' => 'files_external',
  394. 'exception' => $e,
  395. ]);
  396. return false;
  397. }
  398. return false;
  399. }
  400. public function getPermissions($path) {
  401. $type = $this->filetype($path);
  402. if (!$type) {
  403. return 0;
  404. }
  405. return $type === 'dir' ? Constants::PERMISSION_ALL : Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
  406. }
  407. public function unlink($path) {
  408. $path = $this->normalizePath($path);
  409. if ($this->is_dir($path)) {
  410. return $this->rmdir($path);
  411. }
  412. try {
  413. $this->deleteObject($path);
  414. $this->invalidateCache($path);
  415. } catch (S3Exception $e) {
  416. $this->logger->error($e->getMessage(), [
  417. 'app' => 'files_external',
  418. 'exception' => $e,
  419. ]);
  420. return false;
  421. }
  422. return true;
  423. }
  424. public function fopen($path, $mode) {
  425. $path = $this->normalizePath($path);
  426. switch ($mode) {
  427. case 'r':
  428. case 'rb':
  429. // Don't try to fetch empty files
  430. $stat = $this->stat($path);
  431. if (is_array($stat) && isset($stat['size']) && $stat['size'] === 0) {
  432. return fopen('php://memory', $mode);
  433. }
  434. try {
  435. return $this->readObject($path);
  436. } catch (\Exception $e) {
  437. $this->logger->error($e->getMessage(), [
  438. 'app' => 'files_external',
  439. 'exception' => $e,
  440. ]);
  441. return false;
  442. }
  443. case 'w':
  444. case 'wb':
  445. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
  446. $handle = fopen($tmpFile, 'w');
  447. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  448. $this->writeBack($tmpFile, $path);
  449. });
  450. case 'a':
  451. case 'ab':
  452. case 'r+':
  453. case 'w+':
  454. case 'wb+':
  455. case 'a+':
  456. case 'x':
  457. case 'x+':
  458. case 'c':
  459. case 'c+':
  460. if (strrpos($path, '.') !== false) {
  461. $ext = substr($path, strrpos($path, '.'));
  462. } else {
  463. $ext = '';
  464. }
  465. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  466. if ($this->file_exists($path)) {
  467. $source = $this->readObject($path);
  468. file_put_contents($tmpFile, $source);
  469. }
  470. $handle = fopen($tmpFile, $mode);
  471. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  472. $this->writeBack($tmpFile, $path);
  473. });
  474. }
  475. return false;
  476. }
  477. public function touch($path, $mtime = null) {
  478. if (is_null($mtime)) {
  479. $mtime = time();
  480. }
  481. $metadata = [
  482. 'lastmodified' => gmdate(\DateTime::RFC1123, $mtime)
  483. ];
  484. try {
  485. if ($this->file_exists($path)) {
  486. return false;
  487. }
  488. $mimeType = $this->mimeDetector->detectPath($path);
  489. $this->getConnection()->putObject([
  490. 'Bucket' => $this->bucket,
  491. 'Key' => $this->cleanKey($path),
  492. 'Metadata' => $metadata,
  493. 'Body' => '',
  494. 'ContentType' => $mimeType,
  495. 'MetadataDirective' => 'REPLACE',
  496. ]);
  497. $this->testTimeout();
  498. } catch (S3Exception $e) {
  499. $this->logger->error($e->getMessage(), [
  500. 'app' => 'files_external',
  501. 'exception' => $e,
  502. ]);
  503. return false;
  504. }
  505. $this->invalidateCache($path);
  506. return true;
  507. }
  508. public function copy($source, $target, $isFile = null) {
  509. $source = $this->normalizePath($source);
  510. $target = $this->normalizePath($target);
  511. if ($isFile === true || $this->is_file($source)) {
  512. try {
  513. $this->copyObject($source, $target, [
  514. 'StorageClass' => $this->storageClass,
  515. ]);
  516. $this->testTimeout();
  517. } catch (S3Exception $e) {
  518. $this->logger->error($e->getMessage(), [
  519. 'app' => 'files_external',
  520. 'exception' => $e,
  521. ]);
  522. return false;
  523. }
  524. } else {
  525. $this->remove($target);
  526. try {
  527. $this->mkdir($target);
  528. $this->testTimeout();
  529. } catch (S3Exception $e) {
  530. $this->logger->error($e->getMessage(), [
  531. 'app' => 'files_external',
  532. 'exception' => $e,
  533. ]);
  534. return false;
  535. }
  536. foreach ($this->getDirectoryContent($source) as $item) {
  537. $childSource = $source . '/' . $item['name'];
  538. $childTarget = $target . '/' . $item['name'];
  539. $this->copy($childSource, $childTarget, $item['mimetype'] !== FileInfo::MIMETYPE_FOLDER);
  540. }
  541. }
  542. $this->invalidateCache($target);
  543. return true;
  544. }
  545. public function rename($source, $target) {
  546. $source = $this->normalizePath($source);
  547. $target = $this->normalizePath($target);
  548. if ($this->is_file($source)) {
  549. if ($this->copy($source, $target) === false) {
  550. return false;
  551. }
  552. if ($this->unlink($source) === false) {
  553. $this->unlink($target);
  554. return false;
  555. }
  556. } else {
  557. if ($this->copy($source, $target) === false) {
  558. return false;
  559. }
  560. if ($this->rmdir($source) === false) {
  561. $this->rmdir($target);
  562. return false;
  563. }
  564. }
  565. return true;
  566. }
  567. public function test() {
  568. $this->getConnection()->headBucket([
  569. 'Bucket' => $this->bucket
  570. ]);
  571. return true;
  572. }
  573. public function getId() {
  574. return $this->id;
  575. }
  576. public function writeBack($tmpFile, $path) {
  577. try {
  578. $source = fopen($tmpFile, 'r');
  579. $this->writeObject($path, $source, $this->mimeDetector->detectPath($path));
  580. $this->invalidateCache($path);
  581. unlink($tmpFile);
  582. return true;
  583. } catch (S3Exception $e) {
  584. $this->logger->error($e->getMessage(), [
  585. 'app' => 'files_external',
  586. 'exception' => $e,
  587. ]);
  588. return false;
  589. }
  590. }
  591. /**
  592. * check if curl is installed
  593. */
  594. public static function checkDependencies() {
  595. return true;
  596. }
  597. public function getDirectoryContent($directory): \Traversable {
  598. $path = $this->normalizePath($directory);
  599. if ($this->isRoot($path)) {
  600. $path = '';
  601. } else {
  602. $path .= '/';
  603. }
  604. $results = $this->getConnection()->getPaginator('ListObjectsV2', [
  605. 'Bucket' => $this->bucket,
  606. 'Delimiter' => '/',
  607. 'Prefix' => $path,
  608. ]);
  609. foreach ($results as $result) {
  610. // sub folders
  611. if (is_array($result['CommonPrefixes'])) {
  612. foreach ($result['CommonPrefixes'] as $prefix) {
  613. $dir = $this->getDirectoryMetaData($prefix['Prefix']);
  614. if ($dir) {
  615. yield $dir;
  616. }
  617. }
  618. }
  619. if (is_array($result['Contents'])) {
  620. foreach ($result['Contents'] as $object) {
  621. $this->objectCache[$object['Key']] = $object;
  622. if ($object['Key'] !== $path) {
  623. yield $this->objectToMetaData($object);
  624. }
  625. }
  626. }
  627. }
  628. }
  629. private function objectToMetaData(array $object): array {
  630. return [
  631. 'name' => basename($object['Key']),
  632. 'mimetype' => $this->mimeDetector->detectPath($object['Key']),
  633. 'mtime' => strtotime($object['LastModified']),
  634. 'storage_mtime' => strtotime($object['LastModified']),
  635. 'etag' => trim($object['ETag'], '"'),
  636. 'permissions' => Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE,
  637. 'size' => (int)($object['Size'] ?? $object['ContentLength']),
  638. ];
  639. }
  640. private function getDirectoryMetaData(string $path): ?array {
  641. $path = trim($path, '/');
  642. // when versioning is enabled, delete markers are returned as part of CommonPrefixes
  643. // resulting in "ghost" folders, verify that each folder actually exists
  644. if ($this->versioningEnabled() && !$this->doesDirectoryExist($path)) {
  645. return null;
  646. }
  647. $cacheEntry = $this->getCache()->get($path);
  648. if ($cacheEntry instanceof CacheEntry) {
  649. return $cacheEntry->getData();
  650. } else {
  651. return [
  652. 'name' => basename($path),
  653. 'mimetype' => FileInfo::MIMETYPE_FOLDER,
  654. 'mtime' => time(),
  655. 'storage_mtime' => time(),
  656. 'etag' => uniqid(),
  657. 'permissions' => Constants::PERMISSION_ALL,
  658. 'size' => -1,
  659. ];
  660. }
  661. }
  662. public function versioningEnabled(): bool {
  663. if ($this->versioningEnabled === null) {
  664. $cached = $this->memCache->get('versioning-enabled::' . $this->getBucket());
  665. if ($cached === null) {
  666. $this->versioningEnabled = $this->getVersioningStatusFromBucket();
  667. $this->memCache->set('versioning-enabled::' . $this->getBucket(), $this->versioningEnabled, 60);
  668. } else {
  669. $this->versioningEnabled = $cached;
  670. }
  671. }
  672. return $this->versioningEnabled;
  673. }
  674. protected function getVersioningStatusFromBucket(): bool {
  675. try {
  676. $result = $this->getConnection()->getBucketVersioning(['Bucket' => $this->getBucket()]);
  677. return $result->get('Status') === 'Enabled';
  678. } catch (S3Exception $s3Exception) {
  679. // This is needed for compatibility with Storj gateway which does not support versioning yet
  680. if ($s3Exception->getAwsErrorCode() === 'NotImplemented' || $s3Exception->getAwsErrorCode() === 'AccessDenied') {
  681. return false;
  682. }
  683. throw $s3Exception;
  684. }
  685. }
  686. public function hasUpdated($path, $time) {
  687. // for files we can get the proper mtime
  688. if ($path !== '' && $object = $this->headObject($path)) {
  689. $stat = $this->objectToMetaData($object);
  690. return $stat['mtime'] > $time;
  691. } else {
  692. // for directories, the only real option we have is to do a prefix listing and iterate over all objects
  693. // however, since this is just as expensive as just re-scanning the directory, we can simply return true
  694. // and have the scanner figure out if anything has actually changed
  695. return true;
  696. }
  697. }
  698. }