AmazonS3.php 20 KB

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