FolderStorage.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @package Grav\Framework\Flex
  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\Flex\Storage;
  10. use FilesystemIterator;
  11. use Grav\Common\Filesystem\Folder;
  12. use Grav\Common\Grav;
  13. use Grav\Common\Utils;
  14. use Grav\Framework\Filesystem\Filesystem;
  15. use Grav\Framework\Flex\Interfaces\FlexStorageInterface;
  16. use RocketTheme\Toolbox\File\File;
  17. use InvalidArgumentException;
  18. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  19. use RuntimeException;
  20. use SplFileInfo;
  21. use function array_key_exists;
  22. use function basename;
  23. use function count;
  24. use function is_scalar;
  25. use function is_string;
  26. use function mb_strpos;
  27. use function mb_substr;
  28. /**
  29. * Class FolderStorage
  30. * @package Grav\Framework\Flex\Storage
  31. */
  32. class FolderStorage extends AbstractFilesystemStorage
  33. {
  34. /** @var string Folder where all the data is stored. */
  35. protected $dataFolder;
  36. /** @var string Pattern to access an object. */
  37. protected $dataPattern = '{FOLDER}/{KEY}/{FILE}{EXT}';
  38. /** @var string Filename for the object. */
  39. protected $dataFile;
  40. /** @var string File extension for the object. */
  41. protected $dataExt;
  42. /** @var bool */
  43. protected $prefixed;
  44. /** @var bool */
  45. protected $indexed;
  46. /** @var array */
  47. protected $meta = [];
  48. /**
  49. * {@inheritdoc}
  50. */
  51. public function __construct(array $options)
  52. {
  53. if (!isset($options['folder'])) {
  54. throw new InvalidArgumentException("Argument \$options is missing 'folder'");
  55. }
  56. $this->initDataFormatter($options['formatter'] ?? []);
  57. $this->initOptions($options);
  58. }
  59. /**
  60. * @return bool
  61. */
  62. public function isIndexed(): bool
  63. {
  64. return $this->indexed;
  65. }
  66. /**
  67. * @return void
  68. */
  69. public function clearCache(): void
  70. {
  71. $this->meta = [];
  72. }
  73. /**
  74. * @param string[] $keys
  75. * @param bool $reload
  76. * @return array
  77. */
  78. public function getMetaData(array $keys, bool $reload = false): array
  79. {
  80. $list = [];
  81. foreach ($keys as $key) {
  82. $list[$key] = $this->getObjectMeta((string)$key, $reload);
  83. }
  84. return $list;
  85. }
  86. /**
  87. * {@inheritdoc}
  88. * @see FlexStorageInterface::getExistingKeys()
  89. */
  90. public function getExistingKeys(): array
  91. {
  92. return $this->buildIndex();
  93. }
  94. /**
  95. * {@inheritdoc}
  96. * @see FlexStorageInterface::hasKey()
  97. */
  98. public function hasKey(string $key): bool
  99. {
  100. $meta = $this->getObjectMeta($key);
  101. return array_key_exists('exists', $meta) ? $meta['exists'] : !empty($meta['storage_timestamp']);
  102. }
  103. /**
  104. * {@inheritdoc}
  105. * @see FlexStorageInterface::createRows()
  106. */
  107. public function createRows(array $rows): array
  108. {
  109. $list = [];
  110. foreach ($rows as $key => $row) {
  111. $list[$key] = $this->saveRow('@@', $row);
  112. }
  113. return $list;
  114. }
  115. /**
  116. * {@inheritdoc}
  117. * @see FlexStorageInterface::readRows()
  118. */
  119. public function readRows(array $rows, array &$fetched = null): array
  120. {
  121. $list = [];
  122. foreach ($rows as $key => $row) {
  123. if (null === $row || is_scalar($row)) {
  124. // Only load rows which haven't been loaded before.
  125. $key = (string)$key;
  126. $list[$key] = $this->loadRow($key);
  127. if (null !== $fetched) {
  128. $fetched[$key] = $list[$key];
  129. }
  130. } else {
  131. // Keep the row if it has been loaded.
  132. $list[$key] = $row;
  133. }
  134. }
  135. return $list;
  136. }
  137. /**
  138. * {@inheritdoc}
  139. * @see FlexStorageInterface::updateRows()
  140. */
  141. public function updateRows(array $rows): array
  142. {
  143. $list = [];
  144. foreach ($rows as $key => $row) {
  145. $key = (string)$key;
  146. $list[$key] = $this->hasKey($key) ? $this->saveRow($key, $row) : null;
  147. }
  148. return $list;
  149. }
  150. /**
  151. * {@inheritdoc}
  152. * @see FlexStorageInterface::deleteRows()
  153. */
  154. public function deleteRows(array $rows): array
  155. {
  156. $list = [];
  157. $baseMediaPath = $this->getMediaPath();
  158. foreach ($rows as $key => $row) {
  159. $key = (string)$key;
  160. if (!$this->hasKey($key)) {
  161. $list[$key] = null;
  162. } else {
  163. $path = $this->getPathFromKey($key);
  164. $file = $this->getFile($path);
  165. $list[$key] = $this->deleteFile($file);
  166. if ($this->canDeleteFolder($key)) {
  167. $storagePath = $this->getStoragePath($key);
  168. $mediaPath = $this->getMediaPath($key);
  169. if ($storagePath) {
  170. $this->deleteFolder($storagePath, true);
  171. }
  172. if ($mediaPath && $mediaPath !== $storagePath && $mediaPath !== $baseMediaPath) {
  173. $this->deleteFolder($mediaPath, true);
  174. }
  175. }
  176. }
  177. }
  178. return $list;
  179. }
  180. /**
  181. * {@inheritdoc}
  182. * @see FlexStorageInterface::replaceRows()
  183. */
  184. public function replaceRows(array $rows): array
  185. {
  186. $list = [];
  187. foreach ($rows as $key => $row) {
  188. $key = (string)$key;
  189. $list[$key] = $this->saveRow($key, $row);
  190. }
  191. return $list;
  192. }
  193. /**
  194. * @param string $src
  195. * @param string $dst
  196. * @return bool
  197. */
  198. public function copyRow(string $src, string $dst): bool
  199. {
  200. if ($this->hasKey($dst)) {
  201. throw new RuntimeException("Cannot copy object: key '{$dst}' is already taken");
  202. }
  203. if (!$this->hasKey($src)) {
  204. return false;
  205. }
  206. $srcPath = $this->getStoragePath($src);
  207. $dstPath = $this->getStoragePath($dst);
  208. if (!$srcPath || !$dstPath) {
  209. return false;
  210. }
  211. return $this->copyFolder($srcPath, $dstPath);
  212. }
  213. /**
  214. * {@inheritdoc}
  215. * @see FlexStorageInterface::renameRow()
  216. */
  217. public function renameRow(string $src, string $dst): bool
  218. {
  219. if (!$this->hasKey($src)) {
  220. return false;
  221. }
  222. $srcPath = $this->getStoragePath($src);
  223. $dstPath = $this->getStoragePath($dst);
  224. if (!$srcPath || !$dstPath) {
  225. throw new RuntimeException("Destination path '{$dst}' is empty");
  226. }
  227. if ($srcPath === $dstPath) {
  228. return true;
  229. }
  230. if ($this->hasKey($dst)) {
  231. throw new RuntimeException("Cannot rename object '{$src}': key '{$dst}' is already taken $srcPath $dstPath");
  232. }
  233. return $this->moveFolder($srcPath, $dstPath);
  234. }
  235. /**
  236. * {@inheritdoc}
  237. * @see FlexStorageInterface::getStoragePath()
  238. */
  239. public function getStoragePath(string $key = null): ?string
  240. {
  241. if (null === $key || $key === '') {
  242. $path = $this->dataFolder;
  243. } else {
  244. $parts = $this->parseKey($key, false);
  245. $options = [
  246. $this->dataFolder, // {FOLDER}
  247. $parts['key'], // {KEY}
  248. $parts['key:2'], // {KEY:2}
  249. '***', // {FILE}
  250. '***' // {EXT}
  251. ];
  252. $path = rtrim(explode('***', sprintf($this->dataPattern, ...$options))[0], '/');
  253. }
  254. return $path;
  255. }
  256. /**
  257. * {@inheritdoc}
  258. * @see FlexStorageInterface::getMediaPath()
  259. */
  260. public function getMediaPath(string $key = null): ?string
  261. {
  262. return $this->getStoragePath($key);
  263. }
  264. /**
  265. * Get filesystem path from the key.
  266. *
  267. * @param string $key
  268. * @return string
  269. */
  270. public function getPathFromKey(string $key): string
  271. {
  272. $parts = $this->parseKey($key);
  273. $options = [
  274. $this->dataFolder, // {FOLDER}
  275. $parts['key'], // {KEY}
  276. $parts['key:2'], // {KEY:2}
  277. $parts['file'], // {FILE}
  278. $this->dataExt // {EXT}
  279. ];
  280. return sprintf($this->dataPattern, ...$options);
  281. }
  282. /**
  283. * @param string $key
  284. * @param bool $variations
  285. * @return array
  286. */
  287. public function parseKey(string $key, bool $variations = true): array
  288. {
  289. $keys = [
  290. 'key' => $key,
  291. 'key:2' => mb_substr($key, 0, 2),
  292. ];
  293. if ($variations) {
  294. $keys['file'] = $this->dataFile;
  295. }
  296. return $keys;
  297. }
  298. /**
  299. * Get key from the filesystem path.
  300. *
  301. * @param string $path
  302. * @return string
  303. */
  304. protected function getKeyFromPath(string $path): string
  305. {
  306. return basename($path);
  307. }
  308. /**
  309. * Prepares the row for saving and returns the storage key for the record.
  310. *
  311. * @param array $row
  312. * @return void
  313. */
  314. protected function prepareRow(array &$row): void
  315. {
  316. if (array_key_exists($this->keyField, $row)) {
  317. $key = $row[$this->keyField];
  318. if ($key === $this->normalizeKey($key)) {
  319. unset($row[$this->keyField]);
  320. }
  321. }
  322. }
  323. /**
  324. * @param string $key
  325. * @return array
  326. */
  327. protected function loadRow(string $key): ?array
  328. {
  329. $path = $this->getPathFromKey($key);
  330. $file = $this->getFile($path);
  331. try {
  332. $data = (array)$file->content();
  333. if (isset($data[0])) {
  334. throw new RuntimeException('Broken object file');
  335. }
  336. } catch (RuntimeException $e) {
  337. $data = ['__ERROR' => $e->getMessage()];
  338. } finally {
  339. $file->free();
  340. unset($file);
  341. }
  342. $data['__META'] = $this->getObjectMeta($key);
  343. return $data;
  344. }
  345. /**
  346. * @param string $key
  347. * @param array $row
  348. * @return array
  349. */
  350. protected function saveRow(string $key, array $row): array
  351. {
  352. try {
  353. if (isset($row[$this->keyField])) {
  354. $key = $row[$this->keyField];
  355. }
  356. if (strpos($key, '@@') !== false) {
  357. $key = $this->getNewKey();
  358. }
  359. $key = $this->normalizeKey($key);
  360. // Check if the row already exists and if the key has been changed.
  361. $oldKey = $row['__META']['storage_key'] ?? null;
  362. if (is_string($oldKey) && $oldKey !== $key) {
  363. $isCopy = $row['__META']['copy'] ?? false;
  364. if ($isCopy) {
  365. $this->copyRow($oldKey, $key);
  366. } else {
  367. $this->renameRow($oldKey, $key);
  368. }
  369. }
  370. $this->prepareRow($row);
  371. unset($row['__META'], $row['__ERROR']);
  372. $path = $this->getPathFromKey($key);
  373. $file = $this->getFile($path);
  374. $file->save($row);
  375. } catch (RuntimeException $e) {
  376. throw new RuntimeException(sprintf('Flex saveFile(%s): %s', $path ?? $key, $e->getMessage()));
  377. } finally {
  378. /** @var UniformResourceLocator $locator */
  379. $locator = Grav::instance()['locator'];
  380. $locator->clearCache();
  381. if (isset($file)) {
  382. $file->free();
  383. unset($file);
  384. }
  385. }
  386. $row['__META'] = $this->getObjectMeta($key, true);
  387. return $row;
  388. }
  389. /**
  390. * @param File $file
  391. * @return array|string
  392. */
  393. protected function deleteFile(File $file)
  394. {
  395. $filename = $file->filename();
  396. try {
  397. $data = $file->content();
  398. if ($file->exists()) {
  399. $file->delete();
  400. }
  401. } catch (RuntimeException $e) {
  402. throw new RuntimeException(sprintf('Flex deleteFile(%s): %s', $filename, $e->getMessage()));
  403. } finally {
  404. /** @var UniformResourceLocator $locator */
  405. $locator = Grav::instance()['locator'];
  406. $locator->clearCache();
  407. $file->free();
  408. }
  409. return $data;
  410. }
  411. /**
  412. * @param string $src
  413. * @param string $dst
  414. * @return bool
  415. */
  416. protected function copyFolder(string $src, string $dst): bool
  417. {
  418. try {
  419. Folder::copy($this->resolvePath($src), $this->resolvePath($dst));
  420. } catch (RuntimeException $e) {
  421. throw new RuntimeException(sprintf('Flex copyFolder(%s, %s): %s', $src, $dst, $e->getMessage()));
  422. } finally {
  423. /** @var UniformResourceLocator $locator */
  424. $locator = Grav::instance()['locator'];
  425. $locator->clearCache();
  426. }
  427. return true;
  428. }
  429. /**
  430. * @param string $src
  431. * @param string $dst
  432. * @return bool
  433. */
  434. protected function moveFolder(string $src, string $dst): bool
  435. {
  436. try {
  437. Folder::move($this->resolvePath($src), $this->resolvePath($dst));
  438. } catch (RuntimeException $e) {
  439. throw new RuntimeException(sprintf('Flex moveFolder(%s, %s): %s', $src, $dst, $e->getMessage()));
  440. } finally {
  441. /** @var UniformResourceLocator $locator */
  442. $locator = Grav::instance()['locator'];
  443. $locator->clearCache();
  444. }
  445. return true;
  446. }
  447. /**
  448. * @param string $path
  449. * @param bool $include_target
  450. * @return bool
  451. */
  452. protected function deleteFolder(string $path, bool $include_target = false): bool
  453. {
  454. try {
  455. return Folder::delete($this->resolvePath($path), $include_target);
  456. } catch (RuntimeException $e) {
  457. throw new RuntimeException(sprintf('Flex deleteFolder(%s): %s', $path, $e->getMessage()));
  458. } finally {
  459. /** @var UniformResourceLocator $locator */
  460. $locator = Grav::instance()['locator'];
  461. $locator->clearCache();
  462. }
  463. }
  464. /**
  465. * @param string $key
  466. * @return bool
  467. */
  468. protected function canDeleteFolder(string $key): bool
  469. {
  470. return true;
  471. }
  472. /**
  473. * Returns list of all stored keys in [key => timestamp] pairs.
  474. *
  475. * @return array
  476. */
  477. protected function buildIndex(): array
  478. {
  479. $this->clearCache();
  480. $path = $this->getStoragePath();
  481. if (!$path || !file_exists($path)) {
  482. return [];
  483. }
  484. if ($this->prefixed) {
  485. $list = $this->buildPrefixedIndexFromFilesystem($path);
  486. } else {
  487. $list = $this->buildIndexFromFilesystem($path);
  488. }
  489. ksort($list, SORT_NATURAL | SORT_FLAG_CASE);
  490. return $list;
  491. }
  492. /**
  493. * @param string $key
  494. * @param bool $reload
  495. * @return array
  496. */
  497. protected function getObjectMeta(string $key, bool $reload = false): array
  498. {
  499. if (!$reload && isset($this->meta[$key])) {
  500. return $this->meta[$key];
  501. }
  502. if ($key && strpos($key, '@@') === false) {
  503. $filename = $this->getPathFromKey($key);
  504. $modified = is_file($filename) ? filemtime($filename) : 0;
  505. } else {
  506. $modified = 0;
  507. }
  508. $meta = [
  509. 'storage_key' => $key,
  510. 'storage_timestamp' => $modified
  511. ];
  512. $this->meta[$key] = $meta;
  513. return $meta;
  514. }
  515. /**
  516. * @param string $path
  517. * @return array
  518. */
  519. protected function buildIndexFromFilesystem($path)
  520. {
  521. $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
  522. $iterator = new FilesystemIterator($path, $flags);
  523. $list = [];
  524. /** @var SplFileInfo $info */
  525. foreach ($iterator as $filename => $info) {
  526. if (!$info->isDir() || strpos($info->getFilename(), '.') === 0) {
  527. continue;
  528. }
  529. $key = $this->getKeyFromPath($filename);
  530. $meta = $this->getObjectMeta($key);
  531. if ($meta['storage_timestamp']) {
  532. $list[$key] = $meta;
  533. }
  534. }
  535. return $list;
  536. }
  537. /**
  538. * @param string $path
  539. * @return array
  540. */
  541. protected function buildPrefixedIndexFromFilesystem($path)
  542. {
  543. $flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS;
  544. $iterator = new FilesystemIterator($path, $flags);
  545. $list = [];
  546. /** @var SplFileInfo $info */
  547. foreach ($iterator as $filename => $info) {
  548. if (!$info->isDir() || strpos($info->getFilename(), '.') === 0) {
  549. continue;
  550. }
  551. $list[] = $this->buildIndexFromFilesystem($filename);
  552. }
  553. if (!$list) {
  554. return [];
  555. }
  556. return count($list) > 1 ? array_merge(...$list) : $list[0];
  557. }
  558. /**
  559. * @return string
  560. */
  561. protected function getNewKey(): string
  562. {
  563. // Make sure that the file doesn't exist.
  564. do {
  565. $key = $this->generateKey();
  566. } while (file_exists($this->getPathFromKey($key)));
  567. return $key;
  568. }
  569. /**
  570. * @param array $options
  571. * @return void
  572. */
  573. protected function initOptions(array $options): void
  574. {
  575. $extension = $this->dataFormatter->getDefaultFileExtension();
  576. /** @var string $pattern */
  577. $pattern = !empty($options['pattern']) ? $options['pattern'] : $this->dataPattern;
  578. /** @var UniformResourceLocator $locator */
  579. $locator = Grav::instance()['locator'];
  580. $folder = $options['folder'];
  581. if ($locator->isStream($folder)) {
  582. $folder = $locator->getResource($folder, false);
  583. }
  584. $this->dataFolder = $folder;
  585. $this->dataFile = $options['file'] ?? 'item';
  586. $this->dataExt = $extension;
  587. if (mb_strpos($pattern, '{FILE}') === false && mb_strpos($pattern, '{EXT}') === false) {
  588. if (isset($options['file'])) {
  589. $pattern .= '/{FILE}{EXT}';
  590. } else {
  591. $filesystem = Filesystem::getInstance(true);
  592. $this->dataFile = basename($pattern, $extension);
  593. $pattern = $filesystem->dirname($pattern) . '/{FILE}{EXT}';
  594. }
  595. }
  596. $this->prefixed = (bool)($options['prefixed'] ?? strpos($pattern, '/{KEY:2}/'));
  597. $this->indexed = (bool)($options['indexed'] ?? false);
  598. $this->keyField = $options['key'] ?? 'storage_key';
  599. $this->keyLen = (int)($options['key_len'] ?? 32);
  600. $this->caseSensitive = (bool)($options['case_sensitive'] ?? true);
  601. $variables = ['FOLDER' => '%1$s', 'KEY' => '%2$s', 'KEY:2' => '%3$s', 'FILE' => '%4$s', 'EXT' => '%5$s'];
  602. $pattern = Utils::simpleTemplate($pattern, $variables);
  603. if (!$pattern) {
  604. throw new RuntimeException('Bad storage folder pattern');
  605. }
  606. $this->dataPattern = $pattern;
  607. }
  608. }