Cache.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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 OCP\DB\QueryBuilder\IQueryBuilder;
  47. use OCP\EventDispatcher\IEventDispatcher;
  48. use OCP\Files\Cache\CacheEntryInsertedEvent;
  49. use OCP\Files\Cache\CacheEntryRemovedEvent;
  50. use OCP\Files\Cache\CacheEntryUpdatedEvent;
  51. use OCP\Files\Cache\CacheInsertEvent;
  52. use OCP\Files\Cache\CacheUpdateEvent;
  53. use OCP\Files\Cache\ICache;
  54. use OCP\Files\Cache\ICacheEntry;
  55. use OCP\Files\FileInfo;
  56. use OCP\Files\IMimeTypeLoader;
  57. use OCP\Files\Search\ISearchComparison;
  58. use OCP\Files\Search\ISearchOperator;
  59. use OCP\Files\Search\ISearchQuery;
  60. use OCP\Files\Storage\IStorage;
  61. use OCP\FilesMetadata\IFilesMetadataManager;
  62. use OCP\IDBConnection;
  63. use OCP\Util;
  64. use Psr\Log\LoggerInterface;
  65. /**
  66. * Metadata cache for a storage
  67. *
  68. * The cache stores the metadata for all files and folders in a storage and is kept up to date through the following mechanisms:
  69. *
  70. * - Scanner: scans the storage and updates the cache where needed
  71. * - Watcher: checks for changes made to the filesystem outside of the Nextcloud instance and rescans files and folder when a change is detected
  72. * - Updater: listens to changes made to the filesystem inside of the Nextcloud instance and updates the cache where needed
  73. * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
  74. */
  75. class Cache implements ICache {
  76. use MoveFromCacheTrait {
  77. MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
  78. }
  79. /**
  80. * @var array partial data for the cache
  81. */
  82. protected $partial = [];
  83. /**
  84. * @var string
  85. */
  86. protected $storageId;
  87. private $storage;
  88. /**
  89. * @var Storage $storageCache
  90. */
  91. protected $storageCache;
  92. /** @var IMimeTypeLoader */
  93. protected $mimetypeLoader;
  94. /**
  95. * @var IDBConnection
  96. */
  97. protected $connection;
  98. /**
  99. * @var IEventDispatcher
  100. */
  101. protected $eventDispatcher;
  102. /** @var QuerySearchHelper */
  103. protected $querySearchHelper;
  104. /**
  105. * @param IStorage $storage
  106. */
  107. public function __construct(IStorage $storage) {
  108. $this->storageId = $storage->getId();
  109. $this->storage = $storage;
  110. if (strlen($this->storageId) > 64) {
  111. $this->storageId = md5($this->storageId);
  112. }
  113. $this->storageCache = new Storage($storage);
  114. $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
  115. $this->connection = \OC::$server->getDatabaseConnection();
  116. $this->eventDispatcher = \OC::$server->get(IEventDispatcher::class);
  117. $this->querySearchHelper = \OCP\Server::get(QuerySearchHelper::class);
  118. }
  119. protected function getQueryBuilder() {
  120. return new CacheQueryBuilder(
  121. $this->connection,
  122. \OC::$server->getSystemConfig(),
  123. \OC::$server->get(LoggerInterface::class),
  124. \OC::$server->get(IFilesMetadataManager::class),
  125. );
  126. }
  127. /**
  128. * Get the numeric storage id for this cache's storage
  129. *
  130. * @return int
  131. */
  132. public function getNumericStorageId() {
  133. return $this->storageCache->getNumericId();
  134. }
  135. /**
  136. * get the stored metadata of a file or folder
  137. *
  138. * @param string | int $file either the path of a file or folder or the file id for a file or folder
  139. * @return ICacheEntry|false the cache entry as array or false if the file is not found in the cache
  140. */
  141. public function get($file) {
  142. $query = $this->getQueryBuilder();
  143. $query->selectFileCache();
  144. $metadataQuery = $query->selectMetadata();
  145. if (is_string($file) || $file == '') {
  146. // normalize file
  147. $file = $this->normalize($file);
  148. $query->whereStorageId($this->getNumericStorageId())
  149. ->wherePath($file);
  150. } else { //file id
  151. $query->whereFileId($file);
  152. }
  153. $result = $query->execute();
  154. $data = $result->fetch();
  155. $result->closeCursor();
  156. //merge partial data
  157. if (!$data && is_string($file) && isset($this->partial[$file])) {
  158. return $this->partial[$file];
  159. } elseif (!$data) {
  160. return $data;
  161. } else {
  162. $data['metadata'] = $metadataQuery?->extractMetadata($data)->asArray() ?? [];
  163. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  164. }
  165. }
  166. /**
  167. * Create a CacheEntry from database row
  168. *
  169. * @param array $data
  170. * @param IMimeTypeLoader $mimetypeLoader
  171. * @return CacheEntry
  172. */
  173. public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
  174. //fix types
  175. $data['name'] = (string)$data['name'];
  176. $data['path'] = (string)$data['path'];
  177. $data['fileid'] = (int)$data['fileid'];
  178. $data['parent'] = (int)$data['parent'];
  179. $data['size'] = Util::numericToNumber($data['size']);
  180. $data['unencrypted_size'] = Util::numericToNumber($data['unencrypted_size'] ?? 0);
  181. $data['mtime'] = (int)$data['mtime'];
  182. $data['storage_mtime'] = (int)$data['storage_mtime'];
  183. $data['encryptedVersion'] = (int)$data['encrypted'];
  184. $data['encrypted'] = (bool)$data['encrypted'];
  185. $data['storage_id'] = $data['storage'];
  186. $data['storage'] = (int)$data['storage'];
  187. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  188. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  189. if ($data['storage_mtime'] == 0) {
  190. $data['storage_mtime'] = $data['mtime'];
  191. }
  192. $data['permissions'] = (int)$data['permissions'];
  193. if (isset($data['creation_time'])) {
  194. $data['creation_time'] = (int)$data['creation_time'];
  195. }
  196. if (isset($data['upload_time'])) {
  197. $data['upload_time'] = (int)$data['upload_time'];
  198. }
  199. return new CacheEntry($data);
  200. }
  201. /**
  202. * get the metadata of all files stored in $folder
  203. *
  204. * @param string $folder
  205. * @return ICacheEntry[]
  206. */
  207. public function getFolderContents($folder) {
  208. $fileId = $this->getId($folder);
  209. return $this->getFolderContentsById($fileId);
  210. }
  211. /**
  212. * get the metadata of all files stored in $folder
  213. *
  214. * @param int $fileId the file id of the folder
  215. * @return ICacheEntry[]
  216. */
  217. public function getFolderContentsById($fileId) {
  218. if ($fileId > -1) {
  219. $query = $this->getQueryBuilder();
  220. $query->selectFileCache()
  221. ->whereParent($fileId)
  222. ->orderBy('name', 'ASC');
  223. $metadataQuery = $query->selectMetadata();
  224. $result = $query->execute();
  225. $files = $result->fetchAll();
  226. $result->closeCursor();
  227. return array_map(function (array $data) use ($metadataQuery) {
  228. $data['metadata'] = $metadataQuery?->extractMetadata($data)->asArray() ?? [];
  229. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  230. }, $files);
  231. }
  232. return [];
  233. }
  234. /**
  235. * insert or update meta data for a file or folder
  236. *
  237. * @param string $file
  238. * @param array $data
  239. *
  240. * @return int file id
  241. * @throws \RuntimeException
  242. */
  243. public function put($file, array $data) {
  244. if (($id = $this->getId($file)) > -1) {
  245. $this->update($id, $data);
  246. return $id;
  247. } else {
  248. return $this->insert($file, $data);
  249. }
  250. }
  251. /**
  252. * insert meta data for a new file or folder
  253. *
  254. * @param string $file
  255. * @param array $data
  256. *
  257. * @return int file id
  258. * @throws \RuntimeException
  259. */
  260. public function insert($file, array $data) {
  261. // normalize file
  262. $file = $this->normalize($file);
  263. if (isset($this->partial[$file])) { //add any saved partial data
  264. $data = array_merge($this->partial[$file], $data);
  265. unset($this->partial[$file]);
  266. }
  267. $requiredFields = ['size', 'mtime', 'mimetype'];
  268. foreach ($requiredFields as $field) {
  269. if (!isset($data[$field])) { //data not complete save as partial and return
  270. $this->partial[$file] = $data;
  271. return -1;
  272. }
  273. }
  274. $data['path'] = $file;
  275. if (!isset($data['parent'])) {
  276. $data['parent'] = $this->getParentId($file);
  277. }
  278. if ($data['parent'] === -1 && $file !== '') {
  279. throw new \Exception('Parent folder not in filecache for ' . $file);
  280. }
  281. $data['name'] = basename($file);
  282. [$values, $extensionValues] = $this->normalizeData($data);
  283. $storageId = $this->getNumericStorageId();
  284. $values['storage'] = $storageId;
  285. try {
  286. $builder = $this->connection->getQueryBuilder();
  287. $builder->insert('filecache');
  288. foreach ($values as $column => $value) {
  289. $builder->setValue($column, $builder->createNamedParameter($value));
  290. }
  291. if ($builder->execute()) {
  292. $fileId = $builder->getLastInsertId();
  293. if (count($extensionValues)) {
  294. $query = $this->getQueryBuilder();
  295. $query->insert('filecache_extended');
  296. $query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
  297. foreach ($extensionValues as $column => $value) {
  298. $query->setValue($column, $query->createNamedParameter($value));
  299. }
  300. $query->execute();
  301. }
  302. $event = new CacheEntryInsertedEvent($this->storage, $file, $fileId, $storageId);
  303. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  304. $this->eventDispatcher->dispatchTyped($event);
  305. return $fileId;
  306. }
  307. } catch (UniqueConstraintViolationException $e) {
  308. // entry exists already
  309. if ($this->connection->inTransaction()) {
  310. $this->connection->commit();
  311. $this->connection->beginTransaction();
  312. }
  313. }
  314. // The file was created in the mean time
  315. if (($id = $this->getId($file)) > -1) {
  316. $this->update($id, $data);
  317. return $id;
  318. } else {
  319. 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.');
  320. }
  321. }
  322. /**
  323. * update the metadata of an existing file or folder in the cache
  324. *
  325. * @param int $id the fileid of the existing file or folder
  326. * @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
  327. */
  328. public function update($id, array $data) {
  329. if (isset($data['path'])) {
  330. // normalize path
  331. $data['path'] = $this->normalize($data['path']);
  332. }
  333. if (isset($data['name'])) {
  334. // normalize path
  335. $data['name'] = $this->normalize($data['name']);
  336. }
  337. [$values, $extensionValues] = $this->normalizeData($data);
  338. if (count($values)) {
  339. $query = $this->getQueryBuilder();
  340. $query->update('filecache')
  341. ->whereFileId($id)
  342. ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
  343. return $query->expr()->orX(
  344. $query->expr()->neq($key, $query->createNamedParameter($value)),
  345. $query->expr()->isNull($key)
  346. );
  347. }, array_keys($values), array_values($values))));
  348. foreach ($values as $key => $value) {
  349. $query->set($key, $query->createNamedParameter($value));
  350. }
  351. $query->execute();
  352. }
  353. if (count($extensionValues)) {
  354. try {
  355. $query = $this->getQueryBuilder();
  356. $query->insert('filecache_extended');
  357. $query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
  358. foreach ($extensionValues as $column => $value) {
  359. $query->setValue($column, $query->createNamedParameter($value));
  360. }
  361. $query->execute();
  362. } catch (UniqueConstraintViolationException $e) {
  363. $query = $this->getQueryBuilder();
  364. $query->update('filecache_extended')
  365. ->whereFileId($id)
  366. ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
  367. return $query->expr()->orX(
  368. $query->expr()->neq($key, $query->createNamedParameter($value)),
  369. $query->expr()->isNull($key)
  370. );
  371. }, array_keys($extensionValues), array_values($extensionValues))));
  372. foreach ($extensionValues as $key => $value) {
  373. $query->set($key, $query->createNamedParameter($value));
  374. }
  375. $query->execute();
  376. }
  377. }
  378. $path = $this->getPathById($id);
  379. // path can still be null if the file doesn't exist
  380. if ($path !== null) {
  381. $event = new CacheEntryUpdatedEvent($this->storage, $path, $id, $this->getNumericStorageId());
  382. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  383. $this->eventDispatcher->dispatchTyped($event);
  384. }
  385. }
  386. /**
  387. * extract query parts and params array from data array
  388. *
  389. * @param array $data
  390. * @return array
  391. */
  392. protected function normalizeData(array $data): array {
  393. $fields = [
  394. 'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
  395. 'etag', 'permissions', 'checksum', 'storage', 'unencrypted_size'];
  396. $extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
  397. $doNotCopyStorageMTime = false;
  398. if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
  399. // this horrific magic tells it to not copy storage_mtime to mtime
  400. unset($data['mtime']);
  401. $doNotCopyStorageMTime = true;
  402. }
  403. $params = [];
  404. $extensionParams = [];
  405. foreach ($data as $name => $value) {
  406. if (in_array($name, $fields)) {
  407. if ($name === 'path') {
  408. $params['path_hash'] = md5($value);
  409. } elseif ($name === 'mimetype') {
  410. $params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
  411. $value = $this->mimetypeLoader->getId($value);
  412. } elseif ($name === 'storage_mtime') {
  413. if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
  414. $params['mtime'] = $value;
  415. }
  416. } elseif ($name === 'encrypted') {
  417. if (isset($data['encryptedVersion'])) {
  418. $value = $data['encryptedVersion'];
  419. } else {
  420. // Boolean to integer conversion
  421. $value = $value ? 1 : 0;
  422. }
  423. }
  424. $params[$name] = $value;
  425. }
  426. if (in_array($name, $extensionFields)) {
  427. $extensionParams[$name] = $value;
  428. }
  429. }
  430. return [$params, array_filter($extensionParams)];
  431. }
  432. /**
  433. * get the file id for a file
  434. *
  435. * 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
  436. *
  437. * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
  438. *
  439. * @param string $file
  440. * @return int
  441. */
  442. public function getId($file) {
  443. // normalize file
  444. $file = $this->normalize($file);
  445. $query = $this->getQueryBuilder();
  446. $query->select('fileid')
  447. ->from('filecache')
  448. ->whereStorageId($this->getNumericStorageId())
  449. ->wherePath($file);
  450. $result = $query->execute();
  451. $id = $result->fetchOne();
  452. $result->closeCursor();
  453. return $id === false ? -1 : (int)$id;
  454. }
  455. /**
  456. * get the id of the parent folder of a file
  457. *
  458. * @param string $file
  459. * @return int
  460. */
  461. public function getParentId($file) {
  462. if ($file === '') {
  463. return -1;
  464. } else {
  465. $parent = $this->getParentPath($file);
  466. return (int)$this->getId($parent);
  467. }
  468. }
  469. private function getParentPath($path) {
  470. $parent = dirname($path);
  471. if ($parent === '.') {
  472. $parent = '';
  473. }
  474. return $parent;
  475. }
  476. /**
  477. * check if a file is available in the cache
  478. *
  479. * @param string $file
  480. * @return bool
  481. */
  482. public function inCache($file) {
  483. return $this->getId($file) != -1;
  484. }
  485. /**
  486. * remove a file or folder from the cache
  487. *
  488. * when removing a folder from the cache all files and folders inside the folder will be removed as well
  489. *
  490. * @param string $file
  491. */
  492. public function remove($file) {
  493. $entry = $this->get($file);
  494. if ($entry instanceof ICacheEntry) {
  495. $query = $this->getQueryBuilder();
  496. $query->delete('filecache')
  497. ->whereFileId($entry->getId());
  498. $query->execute();
  499. $query = $this->getQueryBuilder();
  500. $query->delete('filecache_extended')
  501. ->whereFileId($entry->getId());
  502. $query->execute();
  503. if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  504. $this->removeChildren($entry);
  505. }
  506. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $entry->getPath(), $entry->getId(), $this->getNumericStorageId()));
  507. }
  508. }
  509. /**
  510. * Remove all children of a folder
  511. *
  512. * @param ICacheEntry $entry the cache entry of the folder to remove the children of
  513. * @throws \OC\DatabaseException
  514. */
  515. private function removeChildren(ICacheEntry $entry) {
  516. $parentIds = [$entry->getId()];
  517. $queue = [$entry->getId()];
  518. $deletedIds = [];
  519. $deletedPaths = [];
  520. // we walk depth first through the file tree, removing all filecache_extended attributes while we walk
  521. // and collecting all folder ids to later use to delete the filecache entries
  522. while ($entryId = array_pop($queue)) {
  523. $children = $this->getFolderContentsById($entryId);
  524. $childIds = array_map(function (ICacheEntry $cacheEntry) {
  525. return $cacheEntry->getId();
  526. }, $children);
  527. $childPaths = array_map(function (ICacheEntry $cacheEntry) {
  528. return $cacheEntry->getPath();
  529. }, $children);
  530. $deletedIds = array_merge($deletedIds, $childIds);
  531. $deletedPaths = array_merge($deletedPaths, $childPaths);
  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 $query) {
  783. return current($this->querySearchHelper->searchInCaches($query, [$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. }