1
0

Cache.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  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\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->getQueryBuilder(),
  85. $this->metadataManager,
  86. );
  87. }
  88. public function getStorageCache(): Storage {
  89. return $this->storageCache;
  90. }
  91. /**
  92. * Get the numeric storage id for this cache's storage
  93. *
  94. * @return int
  95. */
  96. public function getNumericStorageId() {
  97. return $this->storageCache->getNumericId();
  98. }
  99. /**
  100. * get the stored metadata of a file or folder
  101. *
  102. * @param string | int $file either the path of a file or folder or the file id for a file or folder
  103. * @return ICacheEntry|false the cache entry as array or false if the file is not found in the cache
  104. */
  105. public function get($file) {
  106. $query = $this->getQueryBuilder();
  107. $query->selectFileCache();
  108. $metadataQuery = $query->selectMetadata();
  109. if (is_string($file) || $file == '') {
  110. // normalize file
  111. $file = $this->normalize($file);
  112. $query->wherePath($file);
  113. } else { //file id
  114. $query->whereFileId($file);
  115. }
  116. $query->whereStorageId($this->getNumericStorageId());
  117. $result = $query->execute();
  118. $data = $result->fetch();
  119. $result->closeCursor();
  120. //merge partial data
  121. if (!$data && is_string($file) && isset($this->partial[$file])) {
  122. return $this->partial[$file];
  123. } elseif (!$data) {
  124. return $data;
  125. } else {
  126. $data['metadata'] = $metadataQuery->extractMetadata($data)->asArray();
  127. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  128. }
  129. }
  130. /**
  131. * Create a CacheEntry from database row
  132. *
  133. * @param array $data
  134. * @param IMimeTypeLoader $mimetypeLoader
  135. * @return CacheEntry
  136. */
  137. public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
  138. //fix types
  139. $data['name'] = (string)$data['name'];
  140. $data['path'] = (string)$data['path'];
  141. $data['fileid'] = (int)$data['fileid'];
  142. $data['parent'] = (int)$data['parent'];
  143. $data['size'] = Util::numericToNumber($data['size']);
  144. $data['unencrypted_size'] = Util::numericToNumber($data['unencrypted_size'] ?? 0);
  145. $data['mtime'] = (int)$data['mtime'];
  146. $data['storage_mtime'] = (int)$data['storage_mtime'];
  147. $data['encryptedVersion'] = (int)$data['encrypted'];
  148. $data['encrypted'] = (bool)$data['encrypted'];
  149. $data['storage_id'] = $data['storage'];
  150. $data['storage'] = (int)$data['storage'];
  151. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  152. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  153. if ($data['storage_mtime'] == 0) {
  154. $data['storage_mtime'] = $data['mtime'];
  155. }
  156. $data['permissions'] = (int)$data['permissions'];
  157. if (isset($data['creation_time'])) {
  158. $data['creation_time'] = (int)$data['creation_time'];
  159. }
  160. if (isset($data['upload_time'])) {
  161. $data['upload_time'] = (int)$data['upload_time'];
  162. }
  163. return new CacheEntry($data);
  164. }
  165. /**
  166. * get the metadata of all files stored in $folder
  167. *
  168. * @param string $folder
  169. * @return ICacheEntry[]
  170. */
  171. public function getFolderContents($folder) {
  172. $fileId = $this->getId($folder);
  173. return $this->getFolderContentsById($fileId);
  174. }
  175. /**
  176. * get the metadata of all files stored in $folder
  177. *
  178. * @param int $fileId the file id of the folder
  179. * @return ICacheEntry[]
  180. */
  181. public function getFolderContentsById($fileId) {
  182. if ($fileId > -1) {
  183. $query = $this->getQueryBuilder();
  184. $query->selectFileCache()
  185. ->whereParent($fileId)
  186. ->whereStorageId($this->getNumericStorageId())
  187. ->orderBy('name', 'ASC');
  188. $metadataQuery = $query->selectMetadata();
  189. $result = $query->execute();
  190. $files = $result->fetchAll();
  191. $result->closeCursor();
  192. return array_map(function (array $data) use ($metadataQuery) {
  193. $data['metadata'] = $metadataQuery->extractMetadata($data)->asArray();
  194. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  195. }, $files);
  196. }
  197. return [];
  198. }
  199. /**
  200. * insert or update meta data for a file or folder
  201. *
  202. * @param string $file
  203. * @param array $data
  204. *
  205. * @return int file id
  206. * @throws \RuntimeException
  207. */
  208. public function put($file, array $data) {
  209. if (($id = $this->getId($file)) > -1) {
  210. $this->update($id, $data);
  211. return $id;
  212. } else {
  213. return $this->insert($file, $data);
  214. }
  215. }
  216. /**
  217. * insert meta data for a new file or folder
  218. *
  219. * @param string $file
  220. * @param array $data
  221. *
  222. * @return int file id
  223. * @throws \RuntimeException
  224. */
  225. public function insert($file, array $data) {
  226. // normalize file
  227. $file = $this->normalize($file);
  228. if (isset($this->partial[$file])) { //add any saved partial data
  229. $data = array_merge($this->partial[$file], $data);
  230. unset($this->partial[$file]);
  231. }
  232. $requiredFields = ['size', 'mtime', 'mimetype'];
  233. foreach ($requiredFields as $field) {
  234. if (!isset($data[$field])) { //data not complete save as partial and return
  235. $this->partial[$file] = $data;
  236. return -1;
  237. }
  238. }
  239. $data['path'] = $file;
  240. if (!isset($data['parent'])) {
  241. $data['parent'] = $this->getParentId($file);
  242. }
  243. $data['name'] = basename($file);
  244. [$values, $extensionValues] = $this->normalizeData($data);
  245. $storageId = $this->getNumericStorageId();
  246. $values['storage'] = $storageId;
  247. try {
  248. $builder = $this->connection->getQueryBuilder();
  249. $builder->insert('filecache');
  250. foreach ($values as $column => $value) {
  251. $builder->setValue($column, $builder->createNamedParameter($value));
  252. }
  253. if ($builder->execute()) {
  254. $fileId = $builder->getLastInsertId();
  255. if (count($extensionValues)) {
  256. $query = $this->getQueryBuilder();
  257. $query->insert('filecache_extended');
  258. $query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
  259. foreach ($extensionValues as $column => $value) {
  260. $query->setValue($column, $query->createNamedParameter($value));
  261. }
  262. $query->execute();
  263. }
  264. $event = new CacheEntryInsertedEvent($this->storage, $file, $fileId, $storageId);
  265. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  266. $this->eventDispatcher->dispatchTyped($event);
  267. return $fileId;
  268. }
  269. } catch (UniqueConstraintViolationException $e) {
  270. // entry exists already
  271. if ($this->connection->inTransaction()) {
  272. $this->connection->commit();
  273. $this->connection->beginTransaction();
  274. }
  275. }
  276. // The file was created in the mean time
  277. if (($id = $this->getId($file)) > -1) {
  278. $this->update($id, $data);
  279. return $id;
  280. } else {
  281. 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.');
  282. }
  283. }
  284. /**
  285. * update the metadata of an existing file or folder in the cache
  286. *
  287. * @param int $id the fileid of the existing file or folder
  288. * @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
  289. */
  290. public function update($id, array $data) {
  291. if (isset($data['path'])) {
  292. // normalize path
  293. $data['path'] = $this->normalize($data['path']);
  294. }
  295. if (isset($data['name'])) {
  296. // normalize path
  297. $data['name'] = $this->normalize($data['name']);
  298. }
  299. [$values, $extensionValues] = $this->normalizeData($data);
  300. if (count($values)) {
  301. $query = $this->getQueryBuilder();
  302. $query->update('filecache')
  303. ->whereFileId($id)
  304. ->whereStorageId($this->getNumericStorageId())
  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. ->whereStorageId($this->getNumericStorageId())
  461. ->whereFileId($entry->getId());
  462. $query->execute();
  463. $query = $this->getQueryBuilder();
  464. $query->delete('filecache_extended')
  465. ->whereFileId($entry->getId());
  466. $query->execute();
  467. if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  468. $this->removeChildren($entry);
  469. }
  470. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $entry->getPath(), $entry->getId(), $this->getNumericStorageId()));
  471. }
  472. }
  473. /**
  474. * Remove all children of a folder
  475. *
  476. * @param ICacheEntry $entry the cache entry of the folder to remove the children of
  477. * @throws \OC\DatabaseException
  478. */
  479. private function removeChildren(ICacheEntry $entry) {
  480. $parentIds = [$entry->getId()];
  481. $queue = [$entry->getId()];
  482. $deletedIds = [];
  483. $deletedPaths = [];
  484. // we walk depth first through the file tree, removing all filecache_extended attributes while we walk
  485. // and collecting all folder ids to later use to delete the filecache entries
  486. while ($entryId = array_pop($queue)) {
  487. $children = $this->getFolderContentsById($entryId);
  488. $childIds = array_map(function (ICacheEntry $cacheEntry) {
  489. return $cacheEntry->getId();
  490. }, $children);
  491. $childPaths = array_map(function (ICacheEntry $cacheEntry) {
  492. return $cacheEntry->getPath();
  493. }, $children);
  494. foreach ($childIds as $childId) {
  495. $deletedIds[] = $childId;
  496. }
  497. foreach ($childPaths as $childPath) {
  498. $deletedPaths[] = $childPath;
  499. }
  500. $query = $this->getQueryBuilder();
  501. $query->delete('filecache_extended')
  502. ->where($query->expr()->in('fileid', $query->createParameter('childIds')));
  503. foreach (array_chunk($childIds, 1000) as $childIdChunk) {
  504. $query->setParameter('childIds', $childIdChunk, IQueryBuilder::PARAM_INT_ARRAY);
  505. $query->execute();
  506. }
  507. /** @var ICacheEntry[] $childFolders */
  508. $childFolders = [];
  509. foreach ($children as $child) {
  510. if ($child->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  511. $childFolders[] = $child;
  512. }
  513. }
  514. foreach ($childFolders as $folder) {
  515. $parentIds[] = $folder->getId();
  516. $queue[] = $folder->getId();
  517. }
  518. }
  519. $query = $this->getQueryBuilder();
  520. $query->delete('filecache')
  521. ->whereStorageId($this->getNumericStorageId())
  522. ->whereParentInParameter('parentIds');
  523. // Sorting before chunking allows the db to find the entries close to each
  524. // other in the index
  525. sort($parentIds, SORT_NUMERIC);
  526. foreach (array_chunk($parentIds, 1000) as $parentIdChunk) {
  527. $query->setParameter('parentIds', $parentIdChunk, IQueryBuilder::PARAM_INT_ARRAY);
  528. $query->execute();
  529. }
  530. foreach (array_combine($deletedIds, $deletedPaths) as $fileId => $filePath) {
  531. $cacheEntryRemovedEvent = new CacheEntryRemovedEvent(
  532. $this->storage,
  533. $filePath,
  534. $fileId,
  535. $this->getNumericStorageId()
  536. );
  537. $this->eventDispatcher->dispatchTyped($cacheEntryRemovedEvent);
  538. }
  539. }
  540. /**
  541. * Move a file or folder in the cache
  542. *
  543. * @param string $source
  544. * @param string $target
  545. */
  546. public function move($source, $target) {
  547. $this->moveFromCache($this, $source, $target);
  548. }
  549. /**
  550. * Get the storage id and path needed for a move
  551. *
  552. * @param string $path
  553. * @return array [$storageId, $internalPath]
  554. */
  555. protected function getMoveInfo($path) {
  556. return [$this->getNumericStorageId(), $path];
  557. }
  558. protected function hasEncryptionWrapper(): bool {
  559. return $this->storage->instanceOfStorage(Encryption::class);
  560. }
  561. /**
  562. * Move a file or folder in the cache
  563. *
  564. * @param ICache $sourceCache
  565. * @param string $sourcePath
  566. * @param string $targetPath
  567. * @throws \OC\DatabaseException
  568. * @throws \Exception if the given storages have an invalid id
  569. */
  570. public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
  571. if ($sourceCache instanceof Cache) {
  572. // normalize source and target
  573. $sourcePath = $this->normalize($sourcePath);
  574. $targetPath = $this->normalize($targetPath);
  575. $sourceData = $sourceCache->get($sourcePath);
  576. if (!$sourceData) {
  577. throw new \Exception('Invalid source storage path: ' . $sourcePath);
  578. }
  579. $sourceId = $sourceData['fileid'];
  580. $newParentId = $this->getParentId($targetPath);
  581. [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
  582. [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
  583. if (is_null($sourceStorageId) || $sourceStorageId === false) {
  584. throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
  585. }
  586. if (is_null($targetStorageId) || $targetStorageId === false) {
  587. throw new \Exception('Invalid target storage id: ' . $targetStorageId);
  588. }
  589. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  590. //update all child entries
  591. $sourceLength = mb_strlen($sourcePath);
  592. $childIds = $this->getChildIds($sourceStorageId, $sourcePath);
  593. $childChunks = array_chunk($childIds, 1000);
  594. $query = $this->connection->getQueryBuilder();
  595. $fun = $query->func();
  596. $newPathFunction = $fun->concat(
  597. $query->createNamedParameter($targetPath),
  598. $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
  599. );
  600. $query->update('filecache')
  601. ->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
  602. ->set('path_hash', $fun->md5($newPathFunction))
  603. ->set('path', $newPathFunction)
  604. ->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
  605. ->andWhere($query->expr()->in('fileid', $query->createParameter('files')));
  606. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  607. if ($sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  608. $query->set('encrypted', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT));
  609. }
  610. // Retry transaction in case of RetryableException like deadlocks.
  611. // Retry up to 4 times because we should receive up to 4 concurrent requests from the frontend
  612. $retryLimit = 4;
  613. for ($i = 1; $i <= $retryLimit; $i++) {
  614. try {
  615. $this->connection->beginTransaction();
  616. foreach ($childChunks as $chunk) {
  617. $query->setParameter('files', $chunk, IQueryBuilder::PARAM_INT_ARRAY);
  618. $query->executeStatement();
  619. }
  620. break;
  621. } catch (\OC\DatabaseException $e) {
  622. $this->connection->rollBack();
  623. throw $e;
  624. } catch (DbalException $e) {
  625. $this->connection->rollBack();
  626. if (!$e->isRetryable()) {
  627. throw $e;
  628. }
  629. // Simply throw if we already retried 4 times.
  630. if ($i === $retryLimit) {
  631. throw $e;
  632. }
  633. // Sleep a bit to give some time to the other transaction to finish.
  634. usleep(100 * 1000 * $i);
  635. }
  636. }
  637. } else {
  638. $this->connection->beginTransaction();
  639. }
  640. $query = $this->getQueryBuilder();
  641. $query->update('filecache')
  642. ->set('storage', $query->createNamedParameter($targetStorageId))
  643. ->set('path', $query->createNamedParameter($targetPath))
  644. ->set('path_hash', $query->createNamedParameter(md5($targetPath)))
  645. ->set('name', $query->createNamedParameter(basename($targetPath)))
  646. ->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
  647. ->whereFileId($sourceId);
  648. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  649. if ($sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  650. $query->set('encrypted', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT));
  651. }
  652. $query->execute();
  653. $this->connection->commit();
  654. if ($sourceCache->getNumericStorageId() !== $this->getNumericStorageId()) {
  655. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $sourcePath, $sourceId, $sourceCache->getNumericStorageId()));
  656. $event = new CacheEntryInsertedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  657. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  658. $this->eventDispatcher->dispatchTyped($event);
  659. } else {
  660. $event = new CacheEntryUpdatedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  661. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  662. $this->eventDispatcher->dispatchTyped($event);
  663. }
  664. } else {
  665. $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
  666. }
  667. }
  668. private function getChildIds(int $storageId, string $path): array {
  669. $query = $this->connection->getQueryBuilder();
  670. $query->select('fileid')
  671. ->from('filecache')
  672. ->where($query->expr()->eq('storage', $query->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
  673. ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($path) . '/%')));
  674. return $query->executeQuery()->fetchAll(\PDO::FETCH_COLUMN);
  675. }
  676. /**
  677. * remove all entries for files that are stored on the storage from the cache
  678. */
  679. public function clear() {
  680. $query = $this->getQueryBuilder();
  681. $query->delete('filecache')
  682. ->whereStorageId($this->getNumericStorageId());
  683. $query->execute();
  684. $query = $this->connection->getQueryBuilder();
  685. $query->delete('storages')
  686. ->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
  687. $query->execute();
  688. }
  689. /**
  690. * Get the scan status of a file
  691. *
  692. * - Cache::NOT_FOUND: File is not in the cache
  693. * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
  694. * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
  695. * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
  696. *
  697. * @param string $file
  698. *
  699. * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  700. */
  701. public function getStatus($file) {
  702. // normalize file
  703. $file = $this->normalize($file);
  704. $query = $this->getQueryBuilder();
  705. $query->select('size')
  706. ->from('filecache')
  707. ->whereStorageId($this->getNumericStorageId())
  708. ->wherePath($file);
  709. $result = $query->execute();
  710. $size = $result->fetchOne();
  711. $result->closeCursor();
  712. if ($size !== false) {
  713. if ((int)$size === -1) {
  714. return self::SHALLOW;
  715. } else {
  716. return self::COMPLETE;
  717. }
  718. } else {
  719. if (isset($this->partial[$file])) {
  720. return self::PARTIAL;
  721. } else {
  722. return self::NOT_FOUND;
  723. }
  724. }
  725. }
  726. /**
  727. * search for files matching $pattern
  728. *
  729. * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
  730. * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
  731. */
  732. public function search($pattern) {
  733. $operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', $pattern);
  734. return $this->searchQuery(new SearchQuery($operator, 0, 0, [], null));
  735. }
  736. /**
  737. * search for files by mimetype
  738. *
  739. * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
  740. * where it will search for all mimetypes in the group ('image/*')
  741. * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
  742. */
  743. public function searchByMime($mimetype) {
  744. if (!str_contains($mimetype, '/')) {
  745. $operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%');
  746. } else {
  747. $operator = new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype);
  748. }
  749. return $this->searchQuery(new SearchQuery($operator, 0, 0, [], null));
  750. }
  751. public function searchQuery(ISearchQuery $searchQuery) {
  752. return current($this->querySearchHelper->searchInCaches($searchQuery, [$this]));
  753. }
  754. /**
  755. * Re-calculate the folder size and the size of all parent folders
  756. *
  757. * @param string|boolean $path
  758. * @param array $data (optional) meta data of the folder
  759. */
  760. public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
  761. $this->calculateFolderSize($path, $data);
  762. if ($path !== '') {
  763. $parent = dirname($path);
  764. if ($parent === '.' || $parent === '/') {
  765. $parent = '';
  766. }
  767. if ($isBackgroundScan) {
  768. $parentData = $this->get($parent);
  769. if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
  770. $this->correctFolderSize($parent, $parentData, $isBackgroundScan);
  771. }
  772. } else {
  773. $this->correctFolderSize($parent);
  774. }
  775. }
  776. }
  777. /**
  778. * get the incomplete count that shares parent $folder
  779. *
  780. * @param int $fileId the file id of the folder
  781. * @return int
  782. */
  783. public function getIncompleteChildrenCount($fileId) {
  784. if ($fileId > -1) {
  785. $query = $this->getQueryBuilder();
  786. $query->select($query->func()->count())
  787. ->from('filecache')
  788. ->whereParent($fileId)
  789. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
  790. $result = $query->execute();
  791. $size = (int)$result->fetchOne();
  792. $result->closeCursor();
  793. return $size;
  794. }
  795. return -1;
  796. }
  797. /**
  798. * calculate the size of a folder and set it in the cache
  799. *
  800. * @param string $path
  801. * @param array|null|ICacheEntry $entry (optional) meta data of the folder
  802. * @return int|float
  803. */
  804. public function calculateFolderSize($path, $entry = null) {
  805. return $this->calculateFolderSizeInner($path, $entry);
  806. }
  807. /**
  808. * inner function because we can't add new params to the public function without breaking any child classes
  809. *
  810. * @param string $path
  811. * @param array|null|ICacheEntry $entry (optional) meta data of the folder
  812. * @param bool $ignoreUnknown don't mark the folder size as unknown if any of it's children are unknown
  813. * @return int|float
  814. */
  815. protected function calculateFolderSizeInner(string $path, $entry = null, bool $ignoreUnknown = false) {
  816. $totalSize = 0;
  817. if (is_null($entry) || !isset($entry['fileid'])) {
  818. $entry = $this->get($path);
  819. }
  820. if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
  821. $id = $entry['fileid'];
  822. $query = $this->getQueryBuilder();
  823. $query->select('size', 'unencrypted_size')
  824. ->from('filecache')
  825. ->whereStorageId($this->getNumericStorageId())
  826. ->whereParent($id);
  827. if ($ignoreUnknown) {
  828. $query->andWhere($query->expr()->gte('size', $query->createNamedParameter(0)));
  829. }
  830. $result = $query->execute();
  831. $rows = $result->fetchAll();
  832. $result->closeCursor();
  833. if ($rows) {
  834. $sizes = array_map(function (array $row) {
  835. return Util::numericToNumber($row['size']);
  836. }, $rows);
  837. $unencryptedOnlySizes = array_map(function (array $row) {
  838. return Util::numericToNumber($row['unencrypted_size']);
  839. }, $rows);
  840. $unencryptedSizes = array_map(function (array $row) {
  841. return Util::numericToNumber(($row['unencrypted_size'] > 0) ? $row['unencrypted_size'] : $row['size']);
  842. }, $rows);
  843. $sum = array_sum($sizes);
  844. $min = min($sizes);
  845. $unencryptedSum = array_sum($unencryptedSizes);
  846. $unencryptedMin = min($unencryptedSizes);
  847. $unencryptedMax = max($unencryptedOnlySizes);
  848. $sum = 0 + $sum;
  849. $min = 0 + $min;
  850. if ($min === -1) {
  851. $totalSize = $min;
  852. } else {
  853. $totalSize = $sum;
  854. }
  855. if ($unencryptedMin === -1 || $min === -1) {
  856. $unencryptedTotal = $unencryptedMin;
  857. } else {
  858. $unencryptedTotal = $unencryptedSum;
  859. }
  860. } else {
  861. $totalSize = 0;
  862. $unencryptedTotal = 0;
  863. $unencryptedMax = 0;
  864. }
  865. // only set unencrypted size for a folder if any child entries have it set, or the folder is empty
  866. $shouldWriteUnEncryptedSize = $unencryptedMax > 0 || $totalSize === 0 || $entry['unencrypted_size'] > 0;
  867. if ($entry['size'] !== $totalSize || ($entry['unencrypted_size'] !== $unencryptedTotal && $shouldWriteUnEncryptedSize)) {
  868. if ($shouldWriteUnEncryptedSize) {
  869. // if all children have an unencrypted size of 0, just set the folder unencrypted size to 0 instead of summing the sizes
  870. if ($unencryptedMax === 0) {
  871. $unencryptedTotal = 0;
  872. }
  873. $this->update($id, [
  874. 'size' => $totalSize,
  875. 'unencrypted_size' => $unencryptedTotal,
  876. ]);
  877. } else {
  878. $this->update($id, [
  879. 'size' => $totalSize,
  880. ]);
  881. }
  882. }
  883. }
  884. return $totalSize;
  885. }
  886. /**
  887. * get all file ids on the files on the storage
  888. *
  889. * @return int[]
  890. */
  891. public function getAll() {
  892. $query = $this->getQueryBuilder();
  893. $query->select('fileid')
  894. ->from('filecache')
  895. ->whereStorageId($this->getNumericStorageId());
  896. $result = $query->execute();
  897. $files = $result->fetchAll(\PDO::FETCH_COLUMN);
  898. $result->closeCursor();
  899. return array_map(function ($id) {
  900. return (int)$id;
  901. }, $files);
  902. }
  903. /**
  904. * find a folder in the cache which has not been fully scanned
  905. *
  906. * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
  907. * use the one with the highest id gives the best result with the background scanner, since that is most
  908. * likely the folder where we stopped scanning previously
  909. *
  910. * @return string|false the path of the folder or false when no folder matched
  911. */
  912. public function getIncomplete() {
  913. // we select the fileid here first instead of directly selecting the path since this helps mariadb/mysql
  914. // to use the correct index.
  915. // The overhead of this should be minimal since the cost of selecting the path by id should be much lower
  916. // than the cost of finding an item with size < 0
  917. $query = $this->getQueryBuilder();
  918. $query->select('fileid')
  919. ->from('filecache')
  920. ->whereStorageId($this->getNumericStorageId())
  921. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
  922. ->orderBy('fileid', 'DESC')
  923. ->setMaxResults(1);
  924. $result = $query->execute();
  925. $id = $result->fetchOne();
  926. $result->closeCursor();
  927. if ($id === false) {
  928. return false;
  929. }
  930. $path = $this->getPathById($id);
  931. return $path ?? false;
  932. }
  933. /**
  934. * get the path of a file on this storage by it's file id
  935. *
  936. * @param int $id the file id of the file or folder to search
  937. * @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
  938. */
  939. public function getPathById($id) {
  940. $query = $this->getQueryBuilder();
  941. $query->select('path')
  942. ->from('filecache')
  943. ->whereStorageId($this->getNumericStorageId())
  944. ->whereFileId($id);
  945. $result = $query->execute();
  946. $path = $result->fetchOne();
  947. $result->closeCursor();
  948. if ($path === false) {
  949. return null;
  950. }
  951. return (string)$path;
  952. }
  953. /**
  954. * get the storage id of the storage for a file and the internal path of the file
  955. * unlike getPathById this does not limit the search to files on this storage and
  956. * instead does a global search in the cache table
  957. *
  958. * @param int $id
  959. * @return array first element holding the storage id, second the path
  960. * @deprecated use getPathById() instead
  961. */
  962. public static function getById($id) {
  963. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  964. $query->select('path', 'storage')
  965. ->from('filecache')
  966. ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  967. $result = $query->execute();
  968. $row = $result->fetch();
  969. $result->closeCursor();
  970. if ($row) {
  971. $numericId = $row['storage'];
  972. $path = $row['path'];
  973. } else {
  974. return null;
  975. }
  976. if ($id = Storage::getStorageId($numericId)) {
  977. return [$id, $path];
  978. } else {
  979. return null;
  980. }
  981. }
  982. /**
  983. * normalize the given path
  984. *
  985. * @param string $path
  986. * @return string
  987. */
  988. public function normalize($path) {
  989. return trim(\OC_Util::normalizeUnicode($path), '/');
  990. }
  991. /**
  992. * Copy a file or folder in the cache
  993. *
  994. * @param ICache $sourceCache
  995. * @param ICacheEntry $sourceEntry
  996. * @param string $targetPath
  997. * @return int fileId of copied entry
  998. */
  999. public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int {
  1000. if ($sourceEntry->getId() < 0) {
  1001. throw new \RuntimeException("Invalid source cache entry on copyFromCache");
  1002. }
  1003. $data = $this->cacheEntryToArray($sourceEntry);
  1004. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  1005. if ($sourceCache instanceof Cache && $sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  1006. $data['encrypted'] = 0;
  1007. }
  1008. $fileId = $this->put($targetPath, $data);
  1009. if ($fileId <= 0) {
  1010. throw new \RuntimeException("Failed to copy to " . $targetPath . " from cache with source data " . json_encode($data) . " ");
  1011. }
  1012. if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  1013. $folderContent = $sourceCache->getFolderContentsById($sourceEntry->getId());
  1014. foreach ($folderContent as $subEntry) {
  1015. $subTargetPath = $targetPath . '/' . $subEntry->getName();
  1016. $this->copyFromCache($sourceCache, $subEntry, $subTargetPath);
  1017. }
  1018. }
  1019. return $fileId;
  1020. }
  1021. private function cacheEntryToArray(ICacheEntry $entry): array {
  1022. return [
  1023. 'size' => $entry->getSize(),
  1024. 'mtime' => $entry->getMTime(),
  1025. 'storage_mtime' => $entry->getStorageMTime(),
  1026. 'mimetype' => $entry->getMimeType(),
  1027. 'mimepart' => $entry->getMimePart(),
  1028. 'etag' => $entry->getEtag(),
  1029. 'permissions' => $entry->getPermissions(),
  1030. 'encrypted' => $entry->isEncrypted(),
  1031. 'creation_time' => $entry->getCreationTime(),
  1032. 'upload_time' => $entry->getUploadTime(),
  1033. 'metadata_etag' => $entry->getMetadataEtag(),
  1034. ];
  1035. }
  1036. public function getQueryFilterForStorage(): ISearchOperator {
  1037. return new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'storage', $this->getNumericStorageId());
  1038. }
  1039. public function getCacheEntryFromSearchResult(ICacheEntry $rawEntry): ?ICacheEntry {
  1040. if ($rawEntry->getStorageId() === $this->getNumericStorageId()) {
  1041. return $rawEntry;
  1042. } else {
  1043. return null;
  1044. }
  1045. }
  1046. }