Cache.php 38 KB

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