1
0

Cache.php 36 KB

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