Cache.php 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Cache;
  8. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  9. use OC\DB\Exceptions\DbalException;
  10. use OC\DB\QueryBuilder\Sharded\ShardDefinition;
  11. use OC\Files\Search\SearchComparison;
  12. use OC\Files\Search\SearchQuery;
  13. use OC\Files\Storage\Wrapper\Encryption;
  14. use OC\SystemConfig;
  15. use OCP\DB\QueryBuilder\IQueryBuilder;
  16. use OCP\EventDispatcher\IEventDispatcher;
  17. use OCP\Files\Cache\CacheEntryInsertedEvent;
  18. use OCP\Files\Cache\CacheEntryRemovedEvent;
  19. use OCP\Files\Cache\CacheEntryUpdatedEvent;
  20. use OCP\Files\Cache\CacheInsertEvent;
  21. use OCP\Files\Cache\CacheUpdateEvent;
  22. use OCP\Files\Cache\ICache;
  23. use OCP\Files\Cache\ICacheEntry;
  24. use OCP\Files\FileInfo;
  25. use OCP\Files\IMimeTypeLoader;
  26. use OCP\Files\Search\ISearchComparison;
  27. use OCP\Files\Search\ISearchOperator;
  28. use OCP\Files\Search\ISearchQuery;
  29. use OCP\Files\Storage\IStorage;
  30. use OCP\FilesMetadata\IFilesMetadataManager;
  31. use OCP\IDBConnection;
  32. use OCP\Util;
  33. use Psr\Log\LoggerInterface;
  34. /**
  35. * Metadata cache for a storage
  36. *
  37. * The cache stores the metadata for all files and folders in a storage and is kept up to date through the following mechanisms:
  38. *
  39. * - Scanner: scans the storage and updates the cache where needed
  40. * - Watcher: checks for changes made to the filesystem outside of the Nextcloud instance and rescans files and folder when a change is detected
  41. * - Updater: listens to changes made to the filesystem inside of the Nextcloud instance and updates the cache where needed
  42. * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
  43. */
  44. class Cache implements ICache {
  45. use MoveFromCacheTrait {
  46. MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
  47. }
  48. /**
  49. * @var array partial data for the cache
  50. */
  51. protected array $partial = [];
  52. protected string $storageId;
  53. protected Storage $storageCache;
  54. protected IMimeTypeLoader$mimetypeLoader;
  55. protected IDBConnection $connection;
  56. protected SystemConfig $systemConfig;
  57. protected LoggerInterface $logger;
  58. protected QuerySearchHelper $querySearchHelper;
  59. protected IEventDispatcher $eventDispatcher;
  60. protected IFilesMetadataManager $metadataManager;
  61. public function __construct(
  62. private IStorage $storage,
  63. // this constructor is used in to many pleases to easily do proper di
  64. // so instead we group it all together
  65. ?CacheDependencies $dependencies = null,
  66. ) {
  67. $this->storageId = $storage->getId();
  68. if (strlen($this->storageId) > 64) {
  69. $this->storageId = md5($this->storageId);
  70. }
  71. if (!$dependencies) {
  72. $dependencies = \OC::$server->get(CacheDependencies::class);
  73. }
  74. $this->storageCache = new Storage($this->storage, true, $dependencies->getConnection());
  75. $this->mimetypeLoader = $dependencies->getMimeTypeLoader();
  76. $this->connection = $dependencies->getConnection();
  77. $this->systemConfig = $dependencies->getSystemConfig();
  78. $this->logger = $dependencies->getLogger();
  79. $this->querySearchHelper = $dependencies->getQuerySearchHelper();
  80. $this->eventDispatcher = $dependencies->getEventDispatcher();
  81. $this->metadataManager = $dependencies->getMetadataManager();
  82. }
  83. protected function getQueryBuilder() {
  84. return new CacheQueryBuilder(
  85. $this->connection->getQueryBuilder(),
  86. $this->metadataManager,
  87. );
  88. }
  89. public function getStorageCache(): Storage {
  90. return $this->storageCache;
  91. }
  92. /**
  93. * Get the numeric storage id for this cache's storage
  94. *
  95. * @return int
  96. */
  97. public function getNumericStorageId() {
  98. return $this->storageCache->getNumericId();
  99. }
  100. /**
  101. * get the stored metadata of a file or folder
  102. *
  103. * @param string | int $file either the path of a file or folder or the file id for a file or folder
  104. * @return ICacheEntry|false the cache entry as array or false if the file is not found in the cache
  105. */
  106. public function get($file) {
  107. $query = $this->getQueryBuilder();
  108. $query->selectFileCache();
  109. $metadataQuery = $query->selectMetadata();
  110. if (is_string($file) || $file == '') {
  111. // normalize file
  112. $file = $this->normalize($file);
  113. $query->wherePath($file);
  114. } else { //file id
  115. $query->whereFileId($file);
  116. }
  117. $query->whereStorageId($this->getNumericStorageId());
  118. $result = $query->execute();
  119. $data = $result->fetch();
  120. $result->closeCursor();
  121. //merge partial data
  122. if (!$data && is_string($file) && isset($this->partial[$file])) {
  123. return $this->partial[$file];
  124. } elseif (!$data) {
  125. return $data;
  126. } else {
  127. $data['metadata'] = $metadataQuery->extractMetadata($data)->asArray();
  128. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  129. }
  130. }
  131. /**
  132. * Create a CacheEntry from database row
  133. *
  134. * @param array $data
  135. * @param IMimeTypeLoader $mimetypeLoader
  136. * @return CacheEntry
  137. */
  138. public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
  139. //fix types
  140. $data['name'] = (string)$data['name'];
  141. $data['path'] = (string)$data['path'];
  142. $data['fileid'] = (int)$data['fileid'];
  143. $data['parent'] = (int)$data['parent'];
  144. $data['size'] = Util::numericToNumber($data['size']);
  145. $data['unencrypted_size'] = Util::numericToNumber($data['unencrypted_size'] ?? 0);
  146. $data['mtime'] = (int)$data['mtime'];
  147. $data['storage_mtime'] = (int)$data['storage_mtime'];
  148. $data['encryptedVersion'] = (int)$data['encrypted'];
  149. $data['encrypted'] = (bool)$data['encrypted'];
  150. $data['storage_id'] = $data['storage'];
  151. $data['storage'] = (int)$data['storage'];
  152. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  153. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  154. if ($data['storage_mtime'] == 0) {
  155. $data['storage_mtime'] = $data['mtime'];
  156. }
  157. $data['permissions'] = (int)$data['permissions'];
  158. if (isset($data['creation_time'])) {
  159. $data['creation_time'] = (int)$data['creation_time'];
  160. }
  161. if (isset($data['upload_time'])) {
  162. $data['upload_time'] = (int)$data['upload_time'];
  163. }
  164. return new CacheEntry($data);
  165. }
  166. /**
  167. * get the metadata of all files stored in $folder
  168. *
  169. * @param string $folder
  170. * @return ICacheEntry[]
  171. */
  172. public function getFolderContents($folder) {
  173. $fileId = $this->getId($folder);
  174. return $this->getFolderContentsById($fileId);
  175. }
  176. /**
  177. * get the metadata of all files stored in $folder
  178. *
  179. * @param int $fileId the file id of the folder
  180. * @return ICacheEntry[]
  181. */
  182. public function getFolderContentsById($fileId) {
  183. if ($fileId > -1) {
  184. $query = $this->getQueryBuilder();
  185. $query->selectFileCache()
  186. ->whereParent($fileId)
  187. ->whereStorageId($this->getNumericStorageId())
  188. ->orderBy('name', 'ASC');
  189. $metadataQuery = $query->selectMetadata();
  190. $result = $query->execute();
  191. $files = $result->fetchAll();
  192. $result->closeCursor();
  193. return array_map(function (array $data) use ($metadataQuery) {
  194. $data['metadata'] = $metadataQuery->extractMetadata($data)->asArray();
  195. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  196. }, $files);
  197. }
  198. return [];
  199. }
  200. /**
  201. * insert or update meta data for a file or folder
  202. *
  203. * @param string $file
  204. * @param array $data
  205. *
  206. * @return int file id
  207. * @throws \RuntimeException
  208. */
  209. public function put($file, array $data) {
  210. if (($id = $this->getId($file)) > -1) {
  211. $this->update($id, $data);
  212. return $id;
  213. } else {
  214. return $this->insert($file, $data);
  215. }
  216. }
  217. /**
  218. * insert meta data for a new file or folder
  219. *
  220. * @param string $file
  221. * @param array $data
  222. *
  223. * @return int file id
  224. * @throws \RuntimeException
  225. */
  226. public function insert($file, array $data) {
  227. // normalize file
  228. $file = $this->normalize($file);
  229. if (isset($this->partial[$file])) { //add any saved partial data
  230. $data = array_merge($this->partial[$file], $data);
  231. unset($this->partial[$file]);
  232. }
  233. $requiredFields = ['size', 'mtime', 'mimetype'];
  234. foreach ($requiredFields as $field) {
  235. if (!isset($data[$field])) { //data not complete save as partial and return
  236. $this->partial[$file] = $data;
  237. return -1;
  238. }
  239. }
  240. $data['path'] = $file;
  241. if (!isset($data['parent'])) {
  242. $data['parent'] = $this->getParentId($file);
  243. }
  244. $data['name'] = basename($file);
  245. [$values, $extensionValues] = $this->normalizeData($data);
  246. $storageId = $this->getNumericStorageId();
  247. $values['storage'] = $storageId;
  248. try {
  249. $builder = $this->connection->getQueryBuilder();
  250. $builder->insert('filecache');
  251. foreach ($values as $column => $value) {
  252. $builder->setValue($column, $builder->createNamedParameter($value));
  253. }
  254. if ($builder->execute()) {
  255. $fileId = $builder->getLastInsertId();
  256. if (count($extensionValues)) {
  257. $query = $this->getQueryBuilder();
  258. $query->insert('filecache_extended');
  259. $query->hintShardKey('storage', $storageId);
  260. $query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
  261. foreach ($extensionValues as $column => $value) {
  262. $query->setValue($column, $query->createNamedParameter($value));
  263. }
  264. $query->execute();
  265. }
  266. $event = new CacheEntryInsertedEvent($this->storage, $file, $fileId, $storageId);
  267. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  268. $this->eventDispatcher->dispatchTyped($event);
  269. return $fileId;
  270. }
  271. } catch (UniqueConstraintViolationException $e) {
  272. // entry exists already
  273. if ($this->connection->inTransaction()) {
  274. $this->connection->commit();
  275. $this->connection->beginTransaction();
  276. }
  277. }
  278. // The file was created in the mean time
  279. if (($id = $this->getId($file)) > -1) {
  280. $this->update($id, $data);
  281. return $id;
  282. } else {
  283. throw new \RuntimeException('File entry could not be inserted but could also not be selected with getId() in order to perform an update. Please try again.');
  284. }
  285. }
  286. /**
  287. * update the metadata of an existing file or folder in the cache
  288. *
  289. * @param int $id the fileid of the existing file or folder
  290. * @param array $data [$key => $value] the metadata to update, only the fields provided in the array will be updated, non-provided values will remain unchanged
  291. */
  292. public function update($id, array $data) {
  293. if (isset($data['path'])) {
  294. // normalize path
  295. $data['path'] = $this->normalize($data['path']);
  296. }
  297. if (isset($data['name'])) {
  298. // normalize path
  299. $data['name'] = $this->normalize($data['name']);
  300. }
  301. [$values, $extensionValues] = $this->normalizeData($data);
  302. if (count($values)) {
  303. $query = $this->getQueryBuilder();
  304. $query->update('filecache')
  305. ->whereFileId($id)
  306. ->whereStorageId($this->getNumericStorageId())
  307. ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
  308. return $query->expr()->orX(
  309. $query->expr()->neq($key, $query->createNamedParameter($value)),
  310. $query->expr()->isNull($key)
  311. );
  312. }, array_keys($values), array_values($values))));
  313. foreach ($values as $key => $value) {
  314. $query->set($key, $query->createNamedParameter($value));
  315. }
  316. $query->execute();
  317. }
  318. if (count($extensionValues)) {
  319. try {
  320. $query = $this->getQueryBuilder();
  321. $query->insert('filecache_extended');
  322. $query->hintShardKey('storage', $this->getNumericStorageId());
  323. $query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
  324. foreach ($extensionValues as $column => $value) {
  325. $query->setValue($column, $query->createNamedParameter($value));
  326. }
  327. $query->execute();
  328. } catch (UniqueConstraintViolationException $e) {
  329. $query = $this->getQueryBuilder();
  330. $query->update('filecache_extended')
  331. ->whereFileId($id)
  332. ->hintShardKey('storage', $this->getNumericStorageId())
  333. ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
  334. return $query->expr()->orX(
  335. $query->expr()->neq($key, $query->createNamedParameter($value)),
  336. $query->expr()->isNull($key)
  337. );
  338. }, array_keys($extensionValues), array_values($extensionValues))));
  339. foreach ($extensionValues as $key => $value) {
  340. $query->set($key, $query->createNamedParameter($value));
  341. }
  342. $query->execute();
  343. }
  344. }
  345. $path = $this->getPathById($id);
  346. // path can still be null if the file doesn't exist
  347. if ($path !== null) {
  348. $event = new CacheEntryUpdatedEvent($this->storage, $path, $id, $this->getNumericStorageId());
  349. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  350. $this->eventDispatcher->dispatchTyped($event);
  351. }
  352. }
  353. /**
  354. * extract query parts and params array from data array
  355. *
  356. * @param array $data
  357. * @return array
  358. */
  359. protected function normalizeData(array $data): array {
  360. $fields = [
  361. 'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
  362. 'etag', 'permissions', 'checksum', 'storage', 'unencrypted_size'];
  363. $extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
  364. $doNotCopyStorageMTime = false;
  365. if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
  366. // this horrific magic tells it to not copy storage_mtime to mtime
  367. unset($data['mtime']);
  368. $doNotCopyStorageMTime = true;
  369. }
  370. $params = [];
  371. $extensionParams = [];
  372. foreach ($data as $name => $value) {
  373. if (in_array($name, $fields)) {
  374. if ($name === 'path') {
  375. $params['path_hash'] = md5($value);
  376. } elseif ($name === 'mimetype') {
  377. $params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
  378. $value = $this->mimetypeLoader->getId($value);
  379. } elseif ($name === 'storage_mtime') {
  380. if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
  381. $params['mtime'] = $value;
  382. }
  383. } elseif ($name === 'encrypted') {
  384. if (isset($data['encryptedVersion'])) {
  385. $value = $data['encryptedVersion'];
  386. } else {
  387. // Boolean to integer conversion
  388. $value = $value ? 1 : 0;
  389. }
  390. }
  391. $params[$name] = $value;
  392. }
  393. if (in_array($name, $extensionFields)) {
  394. $extensionParams[$name] = $value;
  395. }
  396. }
  397. return [$params, array_filter($extensionParams)];
  398. }
  399. /**
  400. * get the file id for a file
  401. *
  402. * A file id is a numeric id for a file or folder that's unique within an owncloud instance which stays the same for the lifetime of a file
  403. *
  404. * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
  405. *
  406. * @param string $file
  407. * @return int
  408. */
  409. public function getId($file) {
  410. // normalize file
  411. $file = $this->normalize($file);
  412. $query = $this->getQueryBuilder();
  413. $query->select('fileid')
  414. ->from('filecache')
  415. ->whereStorageId($this->getNumericStorageId())
  416. ->wherePath($file);
  417. $result = $query->execute();
  418. $id = $result->fetchOne();
  419. $result->closeCursor();
  420. return $id === false ? -1 : (int)$id;
  421. }
  422. /**
  423. * get the id of the parent folder of a file
  424. *
  425. * @param string $file
  426. * @return int
  427. */
  428. public function getParentId($file) {
  429. if ($file === '') {
  430. return -1;
  431. } else {
  432. $parent = $this->getParentPath($file);
  433. return (int)$this->getId($parent);
  434. }
  435. }
  436. private function getParentPath($path) {
  437. $parent = dirname($path);
  438. if ($parent === '.') {
  439. $parent = '';
  440. }
  441. return $parent;
  442. }
  443. /**
  444. * check if a file is available in the cache
  445. *
  446. * @param string $file
  447. * @return bool
  448. */
  449. public function inCache($file) {
  450. return $this->getId($file) != -1;
  451. }
  452. /**
  453. * remove a file or folder from the cache
  454. *
  455. * when removing a folder from the cache all files and folders inside the folder will be removed as well
  456. *
  457. * @param string $file
  458. */
  459. public function remove($file) {
  460. $entry = $this->get($file);
  461. if ($entry instanceof ICacheEntry) {
  462. $query = $this->getQueryBuilder();
  463. $query->delete('filecache')
  464. ->whereStorageId($this->getNumericStorageId())
  465. ->whereFileId($entry->getId());
  466. $query->execute();
  467. $query = $this->getQueryBuilder();
  468. $query->delete('filecache_extended')
  469. ->whereFileId($entry->getId())
  470. ->hintShardKey('storage', $this->getNumericStorageId());
  471. $query->execute();
  472. if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  473. $this->removeChildren($entry);
  474. }
  475. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $entry->getPath(), $entry->getId(), $this->getNumericStorageId()));
  476. }
  477. }
  478. /**
  479. * Remove all children of a folder
  480. *
  481. * @param ICacheEntry $entry the cache entry of the folder to remove the children of
  482. * @throws \OC\DatabaseException
  483. */
  484. private function removeChildren(ICacheEntry $entry) {
  485. $parentIds = [$entry->getId()];
  486. $queue = [$entry->getId()];
  487. $deletedIds = [];
  488. $deletedPaths = [];
  489. // we walk depth first through the file tree, removing all filecache_extended attributes while we walk
  490. // and collecting all folder ids to later use to delete the filecache entries
  491. while ($entryId = array_pop($queue)) {
  492. $children = $this->getFolderContentsById($entryId);
  493. $childIds = array_map(function (ICacheEntry $cacheEntry) {
  494. return $cacheEntry->getId();
  495. }, $children);
  496. $childPaths = array_map(function (ICacheEntry $cacheEntry) {
  497. return $cacheEntry->getPath();
  498. }, $children);
  499. foreach ($childIds as $childId) {
  500. $deletedIds[] = $childId;
  501. }
  502. foreach ($childPaths as $childPath) {
  503. $deletedPaths[] = $childPath;
  504. }
  505. $query = $this->getQueryBuilder();
  506. $query->delete('filecache_extended')
  507. ->where($query->expr()->in('fileid', $query->createParameter('childIds')))
  508. ->hintShardKey('storage', $this->getNumericStorageId());
  509. foreach (array_chunk($childIds, 1000) as $childIdChunk) {
  510. $query->setParameter('childIds', $childIdChunk, IQueryBuilder::PARAM_INT_ARRAY);
  511. $query->execute();
  512. }
  513. /** @var ICacheEntry[] $childFolders */
  514. $childFolders = [];
  515. foreach ($children as $child) {
  516. if ($child->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  517. $childFolders[] = $child;
  518. }
  519. }
  520. foreach ($childFolders as $folder) {
  521. $parentIds[] = $folder->getId();
  522. $queue[] = $folder->getId();
  523. }
  524. }
  525. $query = $this->getQueryBuilder();
  526. $query->delete('filecache')
  527. ->whereStorageId($this->getNumericStorageId())
  528. ->whereParentInParameter('parentIds');
  529. // Sorting before chunking allows the db to find the entries close to each
  530. // other in the index
  531. sort($parentIds, SORT_NUMERIC);
  532. foreach (array_chunk($parentIds, 1000) as $parentIdChunk) {
  533. $query->setParameter('parentIds', $parentIdChunk, IQueryBuilder::PARAM_INT_ARRAY);
  534. $query->execute();
  535. }
  536. foreach (array_combine($deletedIds, $deletedPaths) as $fileId => $filePath) {
  537. $cacheEntryRemovedEvent = new CacheEntryRemovedEvent(
  538. $this->storage,
  539. $filePath,
  540. $fileId,
  541. $this->getNumericStorageId()
  542. );
  543. $this->eventDispatcher->dispatchTyped($cacheEntryRemovedEvent);
  544. }
  545. }
  546. /**
  547. * Move a file or folder in the cache
  548. *
  549. * @param string $source
  550. * @param string $target
  551. */
  552. public function move($source, $target) {
  553. $this->moveFromCache($this, $source, $target);
  554. }
  555. /**
  556. * Get the storage id and path needed for a move
  557. *
  558. * @param string $path
  559. * @return array [$storageId, $internalPath]
  560. */
  561. protected function getMoveInfo($path) {
  562. return [$this->getNumericStorageId(), $path];
  563. }
  564. protected function hasEncryptionWrapper(): bool {
  565. return $this->storage->instanceOfStorage(Encryption::class);
  566. }
  567. /**
  568. * Move a file or folder in the cache
  569. *
  570. * @param ICache $sourceCache
  571. * @param string $sourcePath
  572. * @param string $targetPath
  573. * @throws \OC\DatabaseException
  574. * @throws \Exception if the given storages have an invalid id
  575. */
  576. public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
  577. if ($sourceCache instanceof Cache) {
  578. // normalize source and target
  579. $sourcePath = $this->normalize($sourcePath);
  580. $targetPath = $this->normalize($targetPath);
  581. $sourceData = $sourceCache->get($sourcePath);
  582. if (!$sourceData) {
  583. throw new \Exception('Invalid source storage path: ' . $sourcePath);
  584. }
  585. $shardDefinition = $this->connection->getShardDefinition('filecache');
  586. if (
  587. $shardDefinition &&
  588. $shardDefinition->getShardForKey($sourceCache->getNumericStorageId()) !== $shardDefinition->getShardForKey($this->getNumericStorageId())
  589. ) {
  590. $this->moveFromStorageSharded($shardDefinition, $sourceCache, $sourceData, $targetPath);
  591. return;
  592. }
  593. $sourceId = $sourceData['fileid'];
  594. $newParentId = $this->getParentId($targetPath);
  595. [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
  596. [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
  597. if (is_null($sourceStorageId) || $sourceStorageId === false) {
  598. throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
  599. }
  600. if (is_null($targetStorageId) || $targetStorageId === false) {
  601. throw new \Exception('Invalid target storage id: ' . $targetStorageId);
  602. }
  603. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  604. //update all child entries
  605. $sourceLength = mb_strlen($sourcePath);
  606. $childIds = $this->getChildIds($sourceStorageId, $sourcePath);
  607. $childChunks = array_chunk($childIds, 1000);
  608. $query = $this->getQueryBuilder();
  609. $fun = $query->func();
  610. $newPathFunction = $fun->concat(
  611. $query->createNamedParameter($targetPath),
  612. $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
  613. );
  614. $query->update('filecache')
  615. ->set('path_hash', $fun->md5($newPathFunction))
  616. ->set('path', $newPathFunction)
  617. ->whereStorageId($sourceStorageId)
  618. ->andWhere($query->expr()->in('fileid', $query->createParameter('files')));
  619. if ($sourceStorageId !== $targetStorageId) {
  620. $query->set('storage', $query->createNamedParameter($targetStorageId), IQueryBuilder::PARAM_INT);
  621. }
  622. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  623. if ($sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  624. $query->set('encrypted', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT));
  625. }
  626. // Retry transaction in case of RetryableException like deadlocks.
  627. // Retry up to 4 times because we should receive up to 4 concurrent requests from the frontend
  628. $retryLimit = 4;
  629. for ($i = 1; $i <= $retryLimit; $i++) {
  630. try {
  631. $this->connection->beginTransaction();
  632. foreach ($childChunks as $chunk) {
  633. $query->setParameter('files', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  634. $query->executeStatement();
  635. }
  636. break;
  637. } catch (\OC\DatabaseException $e) {
  638. $this->connection->rollBack();
  639. throw $e;
  640. } catch (DbalException $e) {
  641. $this->connection->rollBack();
  642. if (!$e->isRetryable()) {
  643. throw $e;
  644. }
  645. // Simply throw if we already retried 4 times.
  646. if ($i === $retryLimit) {
  647. throw $e;
  648. }
  649. // Sleep a bit to give some time to the other transaction to finish.
  650. usleep(100 * 1000 * $i);
  651. }
  652. }
  653. } else {
  654. $this->connection->beginTransaction();
  655. }
  656. $query = $this->getQueryBuilder();
  657. $query->update('filecache')
  658. ->set('path', $query->createNamedParameter($targetPath))
  659. ->set('path_hash', $query->createNamedParameter(md5($targetPath)))
  660. ->set('name', $query->createNamedParameter(basename($targetPath)))
  661. ->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
  662. ->whereStorageId($sourceStorageId)
  663. ->whereFileId($sourceId);
  664. if ($sourceStorageId !== $targetStorageId) {
  665. $query->set('storage', $query->createNamedParameter($targetStorageId), IQueryBuilder::PARAM_INT);
  666. }
  667. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  668. if ($sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  669. $query->set('encrypted', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT));
  670. }
  671. $query->execute();
  672. $this->connection->commit();
  673. if ($sourceCache->getNumericStorageId() !== $this->getNumericStorageId()) {
  674. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $sourcePath, $sourceId, $sourceCache->getNumericStorageId()));
  675. $event = new CacheEntryInsertedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  676. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  677. $this->eventDispatcher->dispatchTyped($event);
  678. } else {
  679. $event = new CacheEntryUpdatedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  680. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  681. $this->eventDispatcher->dispatchTyped($event);
  682. }
  683. } else {
  684. $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
  685. }
  686. }
  687. private function getChildIds(int $storageId, string $path): array {
  688. $query = $this->connection->getQueryBuilder();
  689. $query->select('fileid')
  690. ->from('filecache')
  691. ->where($query->expr()->eq('storage', $query->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
  692. ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($path) . '/%')));
  693. return $query->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
  694. }
  695. /**
  696. * remove all entries for files that are stored on the storage from the cache
  697. */
  698. public function clear() {
  699. $query = $this->getQueryBuilder();
  700. $query->delete('filecache')
  701. ->whereStorageId($this->getNumericStorageId());
  702. $query->execute();
  703. $query = $this->connection->getQueryBuilder();
  704. $query->delete('storages')
  705. ->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
  706. $query->execute();
  707. }
  708. /**
  709. * Get the scan status of a file
  710. *
  711. * - Cache::NOT_FOUND: File is not in the cache
  712. * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
  713. * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
  714. * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
  715. *
  716. * @param string $file
  717. *
  718. * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  719. */
  720. public function getStatus($file) {
  721. // normalize file
  722. $file = $this->normalize($file);
  723. $query = $this->getQueryBuilder();
  724. $query->select('size')
  725. ->from('filecache')
  726. ->whereStorageId($this->getNumericStorageId())
  727. ->wherePath($file);
  728. $result = $query->execute();
  729. $size = $result->fetchOne();
  730. $result->closeCursor();
  731. if ($size !== false) {
  732. if ((int)$size === -1) {
  733. return self::SHALLOW;
  734. } else {
  735. return self::COMPLETE;
  736. }
  737. } else {
  738. if (isset($this->partial[$file])) {
  739. return self::PARTIAL;
  740. } else {
  741. return self::NOT_FOUND;
  742. }
  743. }
  744. }
  745. /**
  746. * search for files matching $pattern
  747. *
  748. * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
  749. * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
  750. */
  751. public function search($pattern) {
  752. $operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', $pattern);
  753. return $this->searchQuery(new SearchQuery($operator, 0, 0, [], null));
  754. }
  755. /**
  756. * search for files by mimetype
  757. *
  758. * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
  759. * where it will search for all mimetypes in the group ('image/*')
  760. * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
  761. */
  762. public function searchByMime($mimetype) {
  763. if (!str_contains($mimetype, '/')) {
  764. $operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%');
  765. } else {
  766. $operator = new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype);
  767. }
  768. return $this->searchQuery(new SearchQuery($operator, 0, 0, [], null));
  769. }
  770. public function searchQuery(ISearchQuery $query) {
  771. return current($this->querySearchHelper->searchInCaches($query, [$this]));
  772. }
  773. /**
  774. * Re-calculate the folder size and the size of all parent folders
  775. *
  776. * @param string|boolean $path
  777. * @param array $data (optional) meta data of the folder
  778. */
  779. public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
  780. $this->calculateFolderSize($path, $data);
  781. if ($path !== '') {
  782. $parent = dirname($path);
  783. if ($parent === '.' || $parent === '/') {
  784. $parent = '';
  785. }
  786. if ($isBackgroundScan) {
  787. $parentData = $this->get($parent);
  788. if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
  789. $this->correctFolderSize($parent, $parentData, $isBackgroundScan);
  790. }
  791. } else {
  792. $this->correctFolderSize($parent);
  793. }
  794. }
  795. }
  796. /**
  797. * get the incomplete count that shares parent $folder
  798. *
  799. * @param int $fileId the file id of the folder
  800. * @return int
  801. */
  802. public function getIncompleteChildrenCount($fileId) {
  803. if ($fileId > -1) {
  804. $query = $this->getQueryBuilder();
  805. $query->select($query->func()->count())
  806. ->from('filecache')
  807. ->whereParent($fileId)
  808. ->whereStorageId($this->getNumericStorageId())
  809. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
  810. $result = $query->execute();
  811. $size = (int)$result->fetchOne();
  812. $result->closeCursor();
  813. return $size;
  814. }
  815. return -1;
  816. }
  817. /**
  818. * calculate the size of a folder and set it in the cache
  819. *
  820. * @param string $path
  821. * @param array|null|ICacheEntry $entry (optional) meta data of the folder
  822. * @return int|float
  823. */
  824. public function calculateFolderSize($path, $entry = null) {
  825. return $this->calculateFolderSizeInner($path, $entry);
  826. }
  827. /**
  828. * inner function because we can't add new params to the public function without breaking any child classes
  829. *
  830. * @param string $path
  831. * @param array|null|ICacheEntry $entry (optional) meta data of the folder
  832. * @param bool $ignoreUnknown don't mark the folder size as unknown if any of it's children are unknown
  833. * @return int|float
  834. */
  835. protected function calculateFolderSizeInner(string $path, $entry = null, bool $ignoreUnknown = false) {
  836. $totalSize = 0;
  837. if (is_null($entry) || !isset($entry['fileid'])) {
  838. $entry = $this->get($path);
  839. }
  840. if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
  841. $id = $entry['fileid'];
  842. $query = $this->getQueryBuilder();
  843. $query->select('size', 'unencrypted_size')
  844. ->from('filecache')
  845. ->whereStorageId($this->getNumericStorageId())
  846. ->whereParent($id);
  847. if ($ignoreUnknown) {
  848. $query->andWhere($query->expr()->gte('size', $query->createNamedParameter(0)));
  849. }
  850. $result = $query->execute();
  851. $rows = $result->fetchAll();
  852. $result->closeCursor();
  853. if ($rows) {
  854. $sizes = array_map(function (array $row) {
  855. return Util::numericToNumber($row['size']);
  856. }, $rows);
  857. $unencryptedOnlySizes = array_map(function (array $row) {
  858. return Util::numericToNumber($row['unencrypted_size']);
  859. }, $rows);
  860. $unencryptedSizes = array_map(function (array $row) {
  861. return Util::numericToNumber(($row['unencrypted_size'] > 0) ? $row['unencrypted_size'] : $row['size']);
  862. }, $rows);
  863. $sum = array_sum($sizes);
  864. $min = min($sizes);
  865. $unencryptedSum = array_sum($unencryptedSizes);
  866. $unencryptedMin = min($unencryptedSizes);
  867. $unencryptedMax = max($unencryptedOnlySizes);
  868. $sum = 0 + $sum;
  869. $min = 0 + $min;
  870. if ($min === -1) {
  871. $totalSize = $min;
  872. } else {
  873. $totalSize = $sum;
  874. }
  875. if ($unencryptedMin === -1 || $min === -1) {
  876. $unencryptedTotal = $unencryptedMin;
  877. } else {
  878. $unencryptedTotal = $unencryptedSum;
  879. }
  880. } else {
  881. $totalSize = 0;
  882. $unencryptedTotal = 0;
  883. $unencryptedMax = 0;
  884. }
  885. // only set unencrypted size for a folder if any child entries have it set, or the folder is empty
  886. $shouldWriteUnEncryptedSize = $unencryptedMax > 0 || $totalSize === 0 || $entry['unencrypted_size'] > 0;
  887. if ($entry['size'] !== $totalSize || ($entry['unencrypted_size'] !== $unencryptedTotal && $shouldWriteUnEncryptedSize)) {
  888. if ($shouldWriteUnEncryptedSize) {
  889. // if all children have an unencrypted size of 0, just set the folder unencrypted size to 0 instead of summing the sizes
  890. if ($unencryptedMax === 0) {
  891. $unencryptedTotal = 0;
  892. }
  893. $this->update($id, [
  894. 'size' => $totalSize,
  895. 'unencrypted_size' => $unencryptedTotal,
  896. ]);
  897. } else {
  898. $this->update($id, [
  899. 'size' => $totalSize,
  900. ]);
  901. }
  902. }
  903. }
  904. return $totalSize;
  905. }
  906. /**
  907. * get all file ids on the files on the storage
  908. *
  909. * @return int[]
  910. */
  911. public function getAll() {
  912. $query = $this->getQueryBuilder();
  913. $query->select('fileid')
  914. ->from('filecache')
  915. ->whereStorageId($this->getNumericStorageId());
  916. $result = $query->execute();
  917. $files = $result->fetchAll(\PDO::FETCH_COLUMN);
  918. $result->closeCursor();
  919. return array_map(function ($id) {
  920. return (int)$id;
  921. }, $files);
  922. }
  923. /**
  924. * find a folder in the cache which has not been fully scanned
  925. *
  926. * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
  927. * use the one with the highest id gives the best result with the background scanner, since that is most
  928. * likely the folder where we stopped scanning previously
  929. *
  930. * @return string|false the path of the folder or false when no folder matched
  931. */
  932. public function getIncomplete() {
  933. // we select the fileid here first instead of directly selecting the path since this helps mariadb/mysql
  934. // to use the correct index.
  935. // The overhead of this should be minimal since the cost of selecting the path by id should be much lower
  936. // than the cost of finding an item with size < 0
  937. $query = $this->getQueryBuilder();
  938. $query->select('fileid')
  939. ->from('filecache')
  940. ->whereStorageId($this->getNumericStorageId())
  941. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
  942. ->orderBy('fileid', 'DESC')
  943. ->setMaxResults(1);
  944. $result = $query->execute();
  945. $id = $result->fetchOne();
  946. $result->closeCursor();
  947. if ($id === false) {
  948. return false;
  949. }
  950. $path = $this->getPathById($id);
  951. return $path ?? false;
  952. }
  953. /**
  954. * get the path of a file on this storage by it's file id
  955. *
  956. * @param int $id the file id of the file or folder to search
  957. * @return string|null the path of the file (relative to the storage) or null if a file with the given id does not exists within this cache
  958. */
  959. public function getPathById($id) {
  960. $query = $this->getQueryBuilder();
  961. $query->select('path')
  962. ->from('filecache')
  963. ->whereStorageId($this->getNumericStorageId())
  964. ->whereFileId($id);
  965. $result = $query->execute();
  966. $path = $result->fetchOne();
  967. $result->closeCursor();
  968. if ($path === false) {
  969. return null;
  970. }
  971. return (string)$path;
  972. }
  973. /**
  974. * get the storage id of the storage for a file and the internal path of the file
  975. * unlike getPathById this does not limit the search to files on this storage and
  976. * instead does a global search in the cache table
  977. *
  978. * @param int $id
  979. * @return array first element holding the storage id, second the path
  980. * @deprecated use getPathById() instead
  981. */
  982. public static function getById($id) {
  983. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  984. $query->select('path', 'storage')
  985. ->from('filecache')
  986. ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  987. $result = $query->execute();
  988. $row = $result->fetch();
  989. $result->closeCursor();
  990. if ($row) {
  991. $numericId = $row['storage'];
  992. $path = $row['path'];
  993. } else {
  994. return null;
  995. }
  996. if ($id = Storage::getStorageId($numericId)) {
  997. return [$id, $path];
  998. } else {
  999. return null;
  1000. }
  1001. }
  1002. /**
  1003. * normalize the given path
  1004. *
  1005. * @param string $path
  1006. * @return string
  1007. */
  1008. public function normalize($path) {
  1009. return trim(\OC_Util::normalizeUnicode($path), '/');
  1010. }
  1011. /**
  1012. * Copy a file or folder in the cache
  1013. *
  1014. * @param ICache $sourceCache
  1015. * @param ICacheEntry $sourceEntry
  1016. * @param string $targetPath
  1017. * @return int fileId of copied entry
  1018. */
  1019. public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int {
  1020. if ($sourceEntry->getId() < 0) {
  1021. throw new \RuntimeException('Invalid source cache entry on copyFromCache');
  1022. }
  1023. $data = $this->cacheEntryToArray($sourceEntry);
  1024. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  1025. if ($sourceCache instanceof Cache && $sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  1026. $data['encrypted'] = 0;
  1027. }
  1028. $fileId = $this->put($targetPath, $data);
  1029. if ($fileId <= 0) {
  1030. throw new \RuntimeException('Failed to copy to ' . $targetPath . ' from cache with source data ' . json_encode($data) . ' ');
  1031. }
  1032. if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  1033. $folderContent = $sourceCache->getFolderContentsById($sourceEntry->getId());
  1034. foreach ($folderContent as $subEntry) {
  1035. $subTargetPath = $targetPath . '/' . $subEntry->getName();
  1036. $this->copyFromCache($sourceCache, $subEntry, $subTargetPath);
  1037. }
  1038. }
  1039. return $fileId;
  1040. }
  1041. private function cacheEntryToArray(ICacheEntry $entry): array {
  1042. return [
  1043. 'size' => $entry->getSize(),
  1044. 'mtime' => $entry->getMTime(),
  1045. 'storage_mtime' => $entry->getStorageMTime(),
  1046. 'mimetype' => $entry->getMimeType(),
  1047. 'mimepart' => $entry->getMimePart(),
  1048. 'etag' => $entry->getEtag(),
  1049. 'permissions' => $entry->getPermissions(),
  1050. 'encrypted' => $entry->isEncrypted(),
  1051. 'creation_time' => $entry->getCreationTime(),
  1052. 'upload_time' => $entry->getUploadTime(),
  1053. 'metadata_etag' => $entry->getMetadataEtag(),
  1054. ];
  1055. }
  1056. public function getQueryFilterForStorage(): ISearchOperator {
  1057. return new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'storage', $this->getNumericStorageId());
  1058. }
  1059. public function getCacheEntryFromSearchResult(ICacheEntry $rawEntry): ?ICacheEntry {
  1060. if ($rawEntry->getStorageId() === $this->getNumericStorageId()) {
  1061. return $rawEntry;
  1062. } else {
  1063. return null;
  1064. }
  1065. }
  1066. private function moveFromStorageSharded(ShardDefinition $shardDefinition, ICache $sourceCache, ICacheEntry $sourceEntry, $targetPath) {
  1067. if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  1068. $fileIds = $this->getChildIds($sourceCache->getNumericStorageId(), $sourceEntry->getPath());
  1069. } else {
  1070. $fileIds = [];
  1071. }
  1072. $fileIds[] = $sourceEntry->getId();
  1073. $helper = $this->connection->getCrossShardMoveHelper();
  1074. $sourceConnection = $helper->getConnection($shardDefinition, $sourceCache->getNumericStorageId());
  1075. $targetConnection = $helper->getConnection($shardDefinition, $this->getNumericStorageId());
  1076. $cacheItems = $helper->loadItems($sourceConnection, 'filecache', 'fileid', $fileIds);
  1077. $extendedItems = $helper->loadItems($sourceConnection, 'filecache_extended', 'fileid', $fileIds);
  1078. $metadataItems = $helper->loadItems($sourceConnection, 'files_metadata', 'file_id', $fileIds);
  1079. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  1080. $removeEncryptedFlag = ($sourceCache instanceof Cache && $sourceCache->hasEncryptionWrapper()) && !$this->hasEncryptionWrapper();
  1081. $sourcePathLength = strlen($sourceEntry->getPath());
  1082. foreach ($cacheItems as &$cacheItem) {
  1083. if ($cacheItem['path'] === $sourceEntry->getPath()) {
  1084. $cacheItem['path'] = $targetPath;
  1085. $cacheItem['parent'] = $this->getParentId($targetPath);
  1086. $cacheItem['name'] = basename($cacheItem['path']);
  1087. } else {
  1088. $cacheItem['path'] = $targetPath . '/' . substr($cacheItem['path'], $sourcePathLength + 1); // +1 for the leading slash
  1089. }
  1090. $cacheItem['path_hash'] = md5($cacheItem['path']);
  1091. $cacheItem['storage'] = $this->getNumericStorageId();
  1092. if ($removeEncryptedFlag) {
  1093. $cacheItem['encrypted'] = 0;
  1094. }
  1095. }
  1096. $targetConnection->beginTransaction();
  1097. try {
  1098. $helper->saveItems($targetConnection, 'filecache', $cacheItems);
  1099. $helper->saveItems($targetConnection, 'filecache_extended', $extendedItems);
  1100. $helper->saveItems($targetConnection, 'files_metadata', $metadataItems);
  1101. } catch (\Exception $e) {
  1102. $targetConnection->rollback();
  1103. throw $e;
  1104. }
  1105. $sourceConnection->beginTransaction();
  1106. try {
  1107. $helper->deleteItems($sourceConnection, 'filecache', 'fileid', $fileIds);
  1108. $helper->deleteItems($sourceConnection, 'filecache_extended', 'fileid', $fileIds);
  1109. $helper->deleteItems($sourceConnection, 'files_metadata', 'file_id', $fileIds);
  1110. } catch (\Exception $e) {
  1111. $targetConnection->rollback();
  1112. $sourceConnection->rollBack();
  1113. throw $e;
  1114. }
  1115. try {
  1116. $sourceConnection->commit();
  1117. } catch (\Exception $e) {
  1118. $targetConnection->rollback();
  1119. throw $e;
  1120. }
  1121. $targetConnection->commit();
  1122. }
  1123. }