Cache.php 36 KB

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