Cache.php 36 KB

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