You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Cache.php 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176
  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\Files\Search\SearchComparison;
  43. use OC\Files\Search\SearchQuery;
  44. use OC\Files\Storage\Wrapper\Encryption;
  45. use OCP\DB\QueryBuilder\IQueryBuilder;
  46. use OCP\EventDispatcher\IEventDispatcher;
  47. use OCP\Files\Cache\CacheEntryInsertedEvent;
  48. use OCP\Files\Cache\CacheEntryRemovedEvent;
  49. use OCP\Files\Cache\CacheEntryUpdatedEvent;
  50. use OCP\Files\Cache\CacheInsertEvent;
  51. use OCP\Files\Cache\CacheUpdateEvent;
  52. use OCP\Files\Cache\ICache;
  53. use OCP\Files\Cache\ICacheEntry;
  54. use OCP\Files\FileInfo;
  55. use OCP\Files\IMimeTypeLoader;
  56. use OCP\Files\Search\ISearchComparison;
  57. use OCP\Files\Search\ISearchOperator;
  58. use OCP\Files\Search\ISearchQuery;
  59. use OCP\Files\Storage\IStorage;
  60. use OCP\FilesMetadata\IFilesMetadataManager;
  61. use OCP\IDBConnection;
  62. use OCP\Util;
  63. use Psr\Log\LoggerInterface;
  64. /**
  65. * Metadata cache for a storage
  66. *
  67. * The cache stores the metadata for all files and folders in a storage and is kept up to date through the following mechanisms:
  68. *
  69. * - Scanner: scans the storage and updates the cache where needed
  70. * - Watcher: checks for changes made to the filesystem outside of the Nextcloud instance and rescans files and folder when a change is detected
  71. * - Updater: listens to changes made to the filesystem inside of the Nextcloud instance and updates the cache where needed
  72. * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
  73. */
  74. class Cache implements ICache {
  75. use MoveFromCacheTrait {
  76. MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
  77. }
  78. /**
  79. * @var array partial data for the cache
  80. */
  81. protected $partial = [];
  82. /**
  83. * @var string
  84. */
  85. protected $storageId;
  86. private $storage;
  87. /**
  88. * @var Storage $storageCache
  89. */
  90. protected $storageCache;
  91. /** @var IMimeTypeLoader */
  92. protected $mimetypeLoader;
  93. /**
  94. * @var IDBConnection
  95. */
  96. protected $connection;
  97. /**
  98. * @var IEventDispatcher
  99. */
  100. protected $eventDispatcher;
  101. /** @var QuerySearchHelper */
  102. protected $querySearchHelper;
  103. /**
  104. * @param IStorage $storage
  105. */
  106. public function __construct(IStorage $storage) {
  107. $this->storageId = $storage->getId();
  108. $this->storage = $storage;
  109. if (strlen($this->storageId) > 64) {
  110. $this->storageId = md5($this->storageId);
  111. }
  112. $this->storageCache = new Storage($storage);
  113. $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
  114. $this->connection = \OC::$server->getDatabaseConnection();
  115. $this->eventDispatcher = \OC::$server->get(IEventDispatcher::class);
  116. $this->querySearchHelper = \OCP\Server::get(QuerySearchHelper::class);
  117. }
  118. protected function getQueryBuilder() {
  119. return new CacheQueryBuilder(
  120. $this->connection,
  121. \OC::$server->getSystemConfig(),
  122. \OC::$server->get(LoggerInterface::class),
  123. \OC::$server->get(IFilesMetadataManager::class),
  124. );
  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. $deletedIds = array_merge($deletedIds, $childIds);
  527. $deletedPaths = array_merge($deletedPaths, $childPaths);
  528. $query = $this->getQueryBuilder();
  529. $query->delete('filecache_extended')
  530. ->where($query->expr()->in('fileid', $query->createParameter('childIds')));
  531. foreach (array_chunk($childIds, 1000) as $childIdChunk) {
  532. $query->setParameter('childIds', $childIdChunk, IQueryBuilder::PARAM_INT_ARRAY);
  533. $query->execute();
  534. }
  535. /** @var ICacheEntry[] $childFolders */
  536. $childFolders = [];
  537. foreach ($children as $child) {
  538. if ($child->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  539. $childFolders[] = $child;
  540. }
  541. }
  542. foreach ($childFolders as $folder) {
  543. $parentIds[] = $folder->getId();
  544. $queue[] = $folder->getId();
  545. }
  546. }
  547. $query = $this->getQueryBuilder();
  548. $query->delete('filecache')
  549. ->whereParentInParameter('parentIds');
  550. foreach (array_chunk($parentIds, 1000) as $parentIdChunk) {
  551. $query->setParameter('parentIds', $parentIdChunk, IQueryBuilder::PARAM_INT_ARRAY);
  552. $query->execute();
  553. }
  554. foreach (array_combine($deletedIds, $deletedPaths) as $fileId => $filePath) {
  555. $cacheEntryRemovedEvent = new CacheEntryRemovedEvent(
  556. $this->storage,
  557. $filePath,
  558. $fileId,
  559. $this->getNumericStorageId()
  560. );
  561. $this->eventDispatcher->dispatchTyped($cacheEntryRemovedEvent);
  562. }
  563. }
  564. /**
  565. * Move a file or folder in the cache
  566. *
  567. * @param string $source
  568. * @param string $target
  569. */
  570. public function move($source, $target) {
  571. $this->moveFromCache($this, $source, $target);
  572. }
  573. /**
  574. * Get the storage id and path needed for a move
  575. *
  576. * @param string $path
  577. * @return array [$storageId, $internalPath]
  578. */
  579. protected function getMoveInfo($path) {
  580. return [$this->getNumericStorageId(), $path];
  581. }
  582. protected function hasEncryptionWrapper(): bool {
  583. return $this->storage->instanceOfStorage(Encryption::class);
  584. }
  585. /**
  586. * Move a file or folder in the cache
  587. *
  588. * @param ICache $sourceCache
  589. * @param string $sourcePath
  590. * @param string $targetPath
  591. * @throws \OC\DatabaseException
  592. * @throws \Exception if the given storages have an invalid id
  593. */
  594. public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
  595. if ($sourceCache instanceof Cache) {
  596. // normalize source and target
  597. $sourcePath = $this->normalize($sourcePath);
  598. $targetPath = $this->normalize($targetPath);
  599. $sourceData = $sourceCache->get($sourcePath);
  600. if (!$sourceData) {
  601. throw new \Exception('Invalid source storage path: ' . $sourcePath);
  602. }
  603. $sourceId = $sourceData['fileid'];
  604. $newParentId = $this->getParentId($targetPath);
  605. [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
  606. [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
  607. if (is_null($sourceStorageId) || $sourceStorageId === false) {
  608. throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
  609. }
  610. if (is_null($targetStorageId) || $targetStorageId === false) {
  611. throw new \Exception('Invalid target storage id: ' . $targetStorageId);
  612. }
  613. $this->connection->beginTransaction();
  614. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  615. //update all child entries
  616. $sourceLength = mb_strlen($sourcePath);
  617. $query = $this->connection->getQueryBuilder();
  618. $fun = $query->func();
  619. $newPathFunction = $fun->concat(
  620. $query->createNamedParameter($targetPath),
  621. $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
  622. );
  623. $query->update('filecache')
  624. ->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
  625. ->set('path_hash', $fun->md5($newPathFunction))
  626. ->set('path', $newPathFunction)
  627. ->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
  628. ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
  629. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  630. if ($sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  631. $query->set('encrypted', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT));
  632. }
  633. try {
  634. $query->execute();
  635. } catch (\OC\DatabaseException $e) {
  636. $this->connection->rollBack();
  637. throw $e;
  638. }
  639. }
  640. $query = $this->getQueryBuilder();
  641. $query->update('filecache')
  642. ->set('storage', $query->createNamedParameter($targetStorageId))
  643. ->set('path', $query->createNamedParameter($targetPath))
  644. ->set('path_hash', $query->createNamedParameter(md5($targetPath)))
  645. ->set('name', $query->createNamedParameter(basename($targetPath)))
  646. ->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
  647. ->whereFileId($sourceId);
  648. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  649. if ($sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  650. $query->set('encrypted', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT));
  651. }
  652. $query->execute();
  653. $this->connection->commit();
  654. if ($sourceCache->getNumericStorageId() !== $this->getNumericStorageId()) {
  655. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $sourcePath, $sourceId, $sourceCache->getNumericStorageId()));
  656. $event = new CacheEntryInsertedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  657. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  658. $this->eventDispatcher->dispatchTyped($event);
  659. } else {
  660. $event = new CacheEntryUpdatedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  661. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  662. $this->eventDispatcher->dispatchTyped($event);
  663. }
  664. } else {
  665. $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
  666. }
  667. }
  668. /**
  669. * remove all entries for files that are stored on the storage from the cache
  670. */
  671. public function clear() {
  672. $query = $this->getQueryBuilder();
  673. $query->delete('filecache')
  674. ->whereStorageId($this->getNumericStorageId());
  675. $query->execute();
  676. $query = $this->connection->getQueryBuilder();
  677. $query->delete('storages')
  678. ->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
  679. $query->execute();
  680. }
  681. /**
  682. * Get the scan status of a file
  683. *
  684. * - Cache::NOT_FOUND: File is not in the cache
  685. * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
  686. * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
  687. * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
  688. *
  689. * @param string $file
  690. *
  691. * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  692. */
  693. public function getStatus($file) {
  694. // normalize file
  695. $file = $this->normalize($file);
  696. $query = $this->getQueryBuilder();
  697. $query->select('size')
  698. ->from('filecache')
  699. ->whereStorageId($this->getNumericStorageId())
  700. ->wherePath($file);
  701. $result = $query->execute();
  702. $size = $result->fetchOne();
  703. $result->closeCursor();
  704. if ($size !== false) {
  705. if ((int)$size === -1) {
  706. return self::SHALLOW;
  707. } else {
  708. return self::COMPLETE;
  709. }
  710. } else {
  711. if (isset($this->partial[$file])) {
  712. return self::PARTIAL;
  713. } else {
  714. return self::NOT_FOUND;
  715. }
  716. }
  717. }
  718. /**
  719. * search for files matching $pattern
  720. *
  721. * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
  722. * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
  723. */
  724. public function search($pattern) {
  725. $operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', $pattern);
  726. return $this->searchQuery(new SearchQuery($operator, 0, 0, [], null));
  727. }
  728. /**
  729. * search for files by mimetype
  730. *
  731. * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
  732. * where it will search for all mimetypes in the group ('image/*')
  733. * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
  734. */
  735. public function searchByMime($mimetype) {
  736. if (!str_contains($mimetype, '/')) {
  737. $operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%');
  738. } else {
  739. $operator = new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype);
  740. }
  741. return $this->searchQuery(new SearchQuery($operator, 0, 0, [], null));
  742. }
  743. public function searchQuery(ISearchQuery $searchQuery) {
  744. return current($this->querySearchHelper->searchInCaches($searchQuery, [$this]));
  745. }
  746. /**
  747. * Re-calculate the folder size and the size of all parent folders
  748. *
  749. * @param string|boolean $path
  750. * @param array $data (optional) meta data of the folder
  751. */
  752. public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
  753. $this->calculateFolderSize($path, $data);
  754. if ($path !== '') {
  755. $parent = dirname($path);
  756. if ($parent === '.' || $parent === '/') {
  757. $parent = '';
  758. }
  759. if ($isBackgroundScan) {
  760. $parentData = $this->get($parent);
  761. if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
  762. $this->correctFolderSize($parent, $parentData, $isBackgroundScan);
  763. }
  764. } else {
  765. $this->correctFolderSize($parent);
  766. }
  767. }
  768. }
  769. /**
  770. * get the incomplete count that shares parent $folder
  771. *
  772. * @param int $fileId the file id of the folder
  773. * @return int
  774. */
  775. public function getIncompleteChildrenCount($fileId) {
  776. if ($fileId > -1) {
  777. $query = $this->getQueryBuilder();
  778. $query->select($query->func()->count())
  779. ->from('filecache')
  780. ->whereParent($fileId)
  781. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
  782. $result = $query->execute();
  783. $size = (int)$result->fetchOne();
  784. $result->closeCursor();
  785. return $size;
  786. }
  787. return -1;
  788. }
  789. /**
  790. * calculate the size of a folder and set it in the cache
  791. *
  792. * @param string $path
  793. * @param array|null|ICacheEntry $entry (optional) meta data of the folder
  794. * @return int|float
  795. */
  796. public function calculateFolderSize($path, $entry = null) {
  797. return $this->calculateFolderSizeInner($path, $entry);
  798. }
  799. /**
  800. * inner function because we can't add new params to the public function without breaking any child classes
  801. *
  802. * @param string $path
  803. * @param array|null|ICacheEntry $entry (optional) meta data of the folder
  804. * @param bool $ignoreUnknown don't mark the folder size as unknown if any of it's children are unknown
  805. * @return int|float
  806. */
  807. protected function calculateFolderSizeInner(string $path, $entry = null, bool $ignoreUnknown = false) {
  808. $totalSize = 0;
  809. if (is_null($entry) || !isset($entry['fileid'])) {
  810. $entry = $this->get($path);
  811. }
  812. if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
  813. $id = $entry['fileid'];
  814. $query = $this->getQueryBuilder();
  815. $query->select('size', 'unencrypted_size')
  816. ->from('filecache')
  817. ->whereParent($id);
  818. if ($ignoreUnknown) {
  819. $query->andWhere($query->expr()->gte('size', $query->createNamedParameter(0)));
  820. }
  821. $result = $query->execute();
  822. $rows = $result->fetchAll();
  823. $result->closeCursor();
  824. if ($rows) {
  825. $sizes = array_map(function (array $row) {
  826. return Util::numericToNumber($row['size']);
  827. }, $rows);
  828. $unencryptedOnlySizes = array_map(function (array $row) {
  829. return Util::numericToNumber($row['unencrypted_size']);
  830. }, $rows);
  831. $unencryptedSizes = array_map(function (array $row) {
  832. return Util::numericToNumber(($row['unencrypted_size'] > 0) ? $row['unencrypted_size'] : $row['size']);
  833. }, $rows);
  834. $sum = array_sum($sizes);
  835. $min = min($sizes);
  836. $unencryptedSum = array_sum($unencryptedSizes);
  837. $unencryptedMin = min($unencryptedSizes);
  838. $unencryptedMax = max($unencryptedOnlySizes);
  839. $sum = 0 + $sum;
  840. $min = 0 + $min;
  841. if ($min === -1) {
  842. $totalSize = $min;
  843. } else {
  844. $totalSize = $sum;
  845. }
  846. if ($unencryptedMin === -1 || $min === -1) {
  847. $unencryptedTotal = $unencryptedMin;
  848. } else {
  849. $unencryptedTotal = $unencryptedSum;
  850. }
  851. } else {
  852. $totalSize = 0;
  853. $unencryptedTotal = 0;
  854. $unencryptedMax = 0;
  855. }
  856. // only set unencrypted size for a folder if any child entries have it set, or the folder is empty
  857. $shouldWriteUnEncryptedSize = $unencryptedMax > 0 || $totalSize === 0 || $entry['unencrypted_size'] > 0;
  858. if ($entry['size'] !== $totalSize || ($entry['unencrypted_size'] !== $unencryptedTotal && $shouldWriteUnEncryptedSize)) {
  859. if ($shouldWriteUnEncryptedSize) {
  860. // if all children have an unencrypted size of 0, just set the folder unencrypted size to 0 instead of summing the sizes
  861. if ($unencryptedMax === 0) {
  862. $unencryptedTotal = 0;
  863. }
  864. $this->update($id, [
  865. 'size' => $totalSize,
  866. 'unencrypted_size' => $unencryptedTotal,
  867. ]);
  868. } else {
  869. $this->update($id, [
  870. 'size' => $totalSize,
  871. ]);
  872. }
  873. }
  874. }
  875. return $totalSize;
  876. }
  877. /**
  878. * get all file ids on the files on the storage
  879. *
  880. * @return int[]
  881. */
  882. public function getAll() {
  883. $query = $this->getQueryBuilder();
  884. $query->select('fileid')
  885. ->from('filecache')
  886. ->whereStorageId($this->getNumericStorageId());
  887. $result = $query->execute();
  888. $files = $result->fetchAll(\PDO::FETCH_COLUMN);
  889. $result->closeCursor();
  890. return array_map(function ($id) {
  891. return (int)$id;
  892. }, $files);
  893. }
  894. /**
  895. * find a folder in the cache which has not been fully scanned
  896. *
  897. * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
  898. * use the one with the highest id gives the best result with the background scanner, since that is most
  899. * likely the folder where we stopped scanning previously
  900. *
  901. * @return string|false the path of the folder or false when no folder matched
  902. */
  903. public function getIncomplete() {
  904. // we select the fileid here first instead of directly selecting the path since this helps mariadb/mysql
  905. // to use the correct index.
  906. // The overhead of this should be minimal since the cost of selecting the path by id should be much lower
  907. // than the cost of finding an item with size < 0
  908. $query = $this->getQueryBuilder();
  909. $query->select('fileid')
  910. ->from('filecache')
  911. ->whereStorageId($this->getNumericStorageId())
  912. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
  913. ->orderBy('fileid', 'DESC')
  914. ->setMaxResults(1);
  915. $result = $query->execute();
  916. $id = $result->fetchOne();
  917. $result->closeCursor();
  918. if ($id === false) {
  919. return false;
  920. }
  921. $path = $this->getPathById($id);
  922. return $path ?? false;
  923. }
  924. /**
  925. * get the path of a file on this storage by it's file id
  926. *
  927. * @param int $id the file id of the file or folder to search
  928. * @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
  929. */
  930. public function getPathById($id) {
  931. $query = $this->getQueryBuilder();
  932. $query->select('path')
  933. ->from('filecache')
  934. ->whereStorageId($this->getNumericStorageId())
  935. ->whereFileId($id);
  936. $result = $query->execute();
  937. $path = $result->fetchOne();
  938. $result->closeCursor();
  939. if ($path === false) {
  940. return null;
  941. }
  942. return (string)$path;
  943. }
  944. /**
  945. * get the storage id of the storage for a file and the internal path of the file
  946. * unlike getPathById this does not limit the search to files on this storage and
  947. * instead does a global search in the cache table
  948. *
  949. * @param int $id
  950. * @return array first element holding the storage id, second the path
  951. * @deprecated use getPathById() instead
  952. */
  953. public static function getById($id) {
  954. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  955. $query->select('path', 'storage')
  956. ->from('filecache')
  957. ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  958. $result = $query->execute();
  959. $row = $result->fetch();
  960. $result->closeCursor();
  961. if ($row) {
  962. $numericId = $row['storage'];
  963. $path = $row['path'];
  964. } else {
  965. return null;
  966. }
  967. if ($id = Storage::getStorageId($numericId)) {
  968. return [$id, $path];
  969. } else {
  970. return null;
  971. }
  972. }
  973. /**
  974. * normalize the given path
  975. *
  976. * @param string $path
  977. * @return string
  978. */
  979. public function normalize($path) {
  980. return trim(\OC_Util::normalizeUnicode($path), '/');
  981. }
  982. /**
  983. * Copy a file or folder in the cache
  984. *
  985. * @param ICache $sourceCache
  986. * @param ICacheEntry $sourceEntry
  987. * @param string $targetPath
  988. * @return int fileId of copied entry
  989. */
  990. public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int {
  991. if ($sourceEntry->getId() < 0) {
  992. throw new \RuntimeException("Invalid source cache entry on copyFromCache");
  993. }
  994. $data = $this->cacheEntryToArray($sourceEntry);
  995. // when moving from an encrypted storage to a non-encrypted storage remove the `encrypted` mark
  996. if ($sourceCache instanceof Cache && $sourceCache->hasEncryptionWrapper() && !$this->hasEncryptionWrapper()) {
  997. $data['encrypted'] = 0;
  998. }
  999. $fileId = $this->put($targetPath, $data);
  1000. if ($fileId <= 0) {
  1001. throw new \RuntimeException("Failed to copy to " . $targetPath . " from cache with source data " . json_encode($data) . " ");
  1002. }
  1003. if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  1004. $folderContent = $sourceCache->getFolderContentsById($sourceEntry->getId());
  1005. foreach ($folderContent as $subEntry) {
  1006. $subTargetPath = $targetPath . '/' . $subEntry->getName();
  1007. $this->copyFromCache($sourceCache, $subEntry, $subTargetPath);
  1008. }
  1009. }
  1010. return $fileId;
  1011. }
  1012. private function cacheEntryToArray(ICacheEntry $entry): array {
  1013. return [
  1014. 'size' => $entry->getSize(),
  1015. 'mtime' => $entry->getMTime(),
  1016. 'storage_mtime' => $entry->getStorageMTime(),
  1017. 'mimetype' => $entry->getMimeType(),
  1018. 'mimepart' => $entry->getMimePart(),
  1019. 'etag' => $entry->getEtag(),
  1020. 'permissions' => $entry->getPermissions(),
  1021. 'encrypted' => $entry->isEncrypted(),
  1022. 'creation_time' => $entry->getCreationTime(),
  1023. 'upload_time' => $entry->getUploadTime(),
  1024. 'metadata_etag' => $entry->getMetadataEtag(),
  1025. ];
  1026. }
  1027. public function getQueryFilterForStorage(): ISearchOperator {
  1028. return new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'storage', $this->getNumericStorageId());
  1029. }
  1030. public function getCacheEntryFromSearchResult(ICacheEntry $rawEntry): ?ICacheEntry {
  1031. if ($rawEntry->getStorageId() === $this->getNumericStorageId()) {
  1032. return $rawEntry;
  1033. } else {
  1034. return null;
  1035. }
  1036. }
  1037. }