Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Cache.php 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079
  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 Jörn Friedrich Dreyer <jfd@butonic.de>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Robin Appelman <robin@icewind.nl>
  20. * @author Robin McCorkell <robin@mccorkell.me.uk>
  21. * @author Roeland Jago Douma <roeland@famdouma.nl>
  22. * @author Vincent Petry <vincent@nextcloud.com>
  23. *
  24. * @license AGPL-3.0
  25. *
  26. * This code is free software: you can redistribute it and/or modify
  27. * it under the terms of the GNU Affero General Public License, version 3,
  28. * as published by the Free Software Foundation.
  29. *
  30. * This program is distributed in the hope that it will be useful,
  31. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  33. * GNU Affero General Public License for more details.
  34. *
  35. * You should have received a copy of the GNU Affero General Public License, version 3,
  36. * along with this program. If not, see <http://www.gnu.org/licenses/>
  37. *
  38. */
  39. namespace OC\Files\Cache;
  40. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  41. use OCP\DB\IResult;
  42. use OCP\DB\QueryBuilder\IQueryBuilder;
  43. use OCP\EventDispatcher\IEventDispatcher;
  44. use OCP\Files\Cache\CacheEntryInsertedEvent;
  45. use OCP\Files\Cache\CacheEntryUpdatedEvent;
  46. use OCP\Files\Cache\CacheInsertEvent;
  47. use OCP\Files\Cache\CacheEntryRemovedEvent;
  48. use OCP\Files\Cache\CacheUpdateEvent;
  49. use OCP\Files\Cache\ICache;
  50. use OCP\Files\Cache\ICacheEntry;
  51. use OCP\Files\FileInfo;
  52. use OCP\Files\IMimeTypeLoader;
  53. use OCP\Files\Search\ISearchQuery;
  54. use OCP\Files\Storage\IStorage;
  55. use OCP\IDBConnection;
  56. /**
  57. * Metadata cache for a storage
  58. *
  59. * The cache stores the metadata for all files and folders in a storage and is kept up to date trough the following mechanisms:
  60. *
  61. * - Scanner: scans the storage and updates the cache where needed
  62. * - Watcher: checks for changes made to the filesystem outside of the ownCloud instance and rescans files and folder when a change is detected
  63. * - Updater: listens to changes made to the filesystem inside of the ownCloud instance and updates the cache where needed
  64. * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
  65. */
  66. class Cache implements ICache {
  67. use MoveFromCacheTrait {
  68. MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
  69. }
  70. /**
  71. * @var array partial data for the cache
  72. */
  73. protected $partial = [];
  74. /**
  75. * @var string
  76. */
  77. protected $storageId;
  78. private $storage;
  79. /**
  80. * @var Storage $storageCache
  81. */
  82. protected $storageCache;
  83. /** @var IMimeTypeLoader */
  84. protected $mimetypeLoader;
  85. /**
  86. * @var IDBConnection
  87. */
  88. protected $connection;
  89. /**
  90. * @var IEventDispatcher
  91. */
  92. protected $eventDispatcher;
  93. /** @var QuerySearchHelper */
  94. protected $querySearchHelper;
  95. /**
  96. * @param IStorage $storage
  97. */
  98. public function __construct(IStorage $storage) {
  99. $this->storageId = $storage->getId();
  100. $this->storage = $storage;
  101. if (strlen($this->storageId) > 64) {
  102. $this->storageId = md5($this->storageId);
  103. }
  104. $this->storageCache = new Storage($storage);
  105. $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
  106. $this->connection = \OC::$server->getDatabaseConnection();
  107. $this->eventDispatcher = \OC::$server->get(IEventDispatcher::class);
  108. $this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
  109. }
  110. private function getQueryBuilder() {
  111. return new CacheQueryBuilder(
  112. $this->connection,
  113. \OC::$server->getSystemConfig(),
  114. \OC::$server->getLogger(),
  115. $this
  116. );
  117. }
  118. /**
  119. * Get the numeric storage id for this cache's storage
  120. *
  121. * @return int
  122. */
  123. public function getNumericStorageId() {
  124. return $this->storageCache->getNumericId();
  125. }
  126. /**
  127. * get the stored metadata of a file or folder
  128. *
  129. * @param string | int $file either the path of a file or folder or the file id for a file or folder
  130. * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
  131. */
  132. public function get($file) {
  133. $query = $this->getQueryBuilder();
  134. $query->selectFileCache();
  135. if (is_string($file) or $file == '') {
  136. // normalize file
  137. $file = $this->normalize($file);
  138. $query->whereStorageId()
  139. ->wherePath($file);
  140. } else { //file id
  141. $query->whereFileId($file);
  142. }
  143. $result = $query->execute();
  144. $data = $result->fetch();
  145. $result->closeCursor();
  146. //merge partial data
  147. if (!$data and is_string($file) and isset($this->partial[$file])) {
  148. return $this->partial[$file];
  149. } elseif (!$data) {
  150. return $data;
  151. } else {
  152. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  153. }
  154. }
  155. /**
  156. * Create a CacheEntry from database row
  157. *
  158. * @param array $data
  159. * @param IMimeTypeLoader $mimetypeLoader
  160. * @return CacheEntry
  161. */
  162. public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
  163. //fix types
  164. $data['fileid'] = (int)$data['fileid'];
  165. $data['parent'] = (int)$data['parent'];
  166. $data['size'] = 0 + $data['size'];
  167. $data['mtime'] = (int)$data['mtime'];
  168. $data['storage_mtime'] = (int)$data['storage_mtime'];
  169. $data['encryptedVersion'] = (int)$data['encrypted'];
  170. $data['encrypted'] = (bool)$data['encrypted'];
  171. $data['storage_id'] = $data['storage'];
  172. $data['storage'] = (int)$data['storage'];
  173. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  174. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  175. if ($data['storage_mtime'] == 0) {
  176. $data['storage_mtime'] = $data['mtime'];
  177. }
  178. $data['permissions'] = (int)$data['permissions'];
  179. if (isset($data['creation_time'])) {
  180. $data['creation_time'] = (int) $data['creation_time'];
  181. }
  182. if (isset($data['upload_time'])) {
  183. $data['upload_time'] = (int) $data['upload_time'];
  184. }
  185. return new CacheEntry($data);
  186. }
  187. /**
  188. * get the metadata of all files stored in $folder
  189. *
  190. * @param string $folder
  191. * @return ICacheEntry[]
  192. */
  193. public function getFolderContents($folder) {
  194. $fileId = $this->getId($folder);
  195. return $this->getFolderContentsById($fileId);
  196. }
  197. /**
  198. * get the metadata of all files stored in $folder
  199. *
  200. * @param int $fileId the file id of the folder
  201. * @return ICacheEntry[]
  202. */
  203. public function getFolderContentsById($fileId) {
  204. if ($fileId > -1) {
  205. $query = $this->getQueryBuilder();
  206. $query->selectFileCache()
  207. ->whereParent($fileId)
  208. ->orderBy('name', 'ASC');
  209. $result = $query->execute();
  210. $files = $result->fetchAll();
  211. $result->closeCursor();
  212. return array_map(function (array $data) {
  213. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  214. }, $files);
  215. }
  216. return [];
  217. }
  218. /**
  219. * insert or update meta data for a file or folder
  220. *
  221. * @param string $file
  222. * @param array $data
  223. *
  224. * @return int file id
  225. * @throws \RuntimeException
  226. */
  227. public function put($file, array $data) {
  228. if (($id = $this->getId($file)) > -1) {
  229. $this->update($id, $data);
  230. return $id;
  231. } else {
  232. return $this->insert($file, $data);
  233. }
  234. }
  235. /**
  236. * insert meta data for a new file or folder
  237. *
  238. * @param string $file
  239. * @param array $data
  240. *
  241. * @return int file id
  242. * @throws \RuntimeException
  243. */
  244. public function insert($file, array $data) {
  245. // normalize file
  246. $file = $this->normalize($file);
  247. if (isset($this->partial[$file])) { //add any saved partial data
  248. $data = array_merge($this->partial[$file], $data);
  249. unset($this->partial[$file]);
  250. }
  251. $requiredFields = ['size', 'mtime', 'mimetype'];
  252. foreach ($requiredFields as $field) {
  253. if (!isset($data[$field])) { //data not complete save as partial and return
  254. $this->partial[$file] = $data;
  255. return -1;
  256. }
  257. }
  258. $data['path'] = $file;
  259. if (!isset($data['parent'])) {
  260. $data['parent'] = $this->getParentId($file);
  261. }
  262. $data['name'] = basename($file);
  263. [$values, $extensionValues] = $this->normalizeData($data);
  264. $storageId = $this->getNumericStorageId();
  265. $values['storage'] = $storageId;
  266. try {
  267. $builder = $this->connection->getQueryBuilder();
  268. $builder->insert('filecache');
  269. foreach ($values as $column => $value) {
  270. $builder->setValue($column, $builder->createNamedParameter($value));
  271. }
  272. if ($builder->execute()) {
  273. $fileId = $builder->getLastInsertId();
  274. if (count($extensionValues)) {
  275. $query = $this->getQueryBuilder();
  276. $query->insert('filecache_extended');
  277. $query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
  278. foreach ($extensionValues as $column => $value) {
  279. $query->setValue($column, $query->createNamedParameter($value));
  280. }
  281. $query->execute();
  282. }
  283. $event = new CacheEntryInsertedEvent($this->storage, $file, $fileId, $storageId);
  284. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  285. $this->eventDispatcher->dispatchTyped($event);
  286. return $fileId;
  287. }
  288. } catch (UniqueConstraintViolationException $e) {
  289. // entry exists already
  290. if ($this->connection->inTransaction()) {
  291. $this->connection->commit();
  292. $this->connection->beginTransaction();
  293. }
  294. }
  295. // The file was created in the mean time
  296. if (($id = $this->getId($file)) > -1) {
  297. $this->update($id, $data);
  298. return $id;
  299. } else {
  300. 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.');
  301. }
  302. }
  303. /**
  304. * update the metadata of an existing file or folder in the cache
  305. *
  306. * @param int $id the fileid of the existing file or folder
  307. * @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
  308. */
  309. public function update($id, array $data) {
  310. if (isset($data['path'])) {
  311. // normalize path
  312. $data['path'] = $this->normalize($data['path']);
  313. }
  314. if (isset($data['name'])) {
  315. // normalize path
  316. $data['name'] = $this->normalize($data['name']);
  317. }
  318. [$values, $extensionValues] = $this->normalizeData($data);
  319. if (count($values)) {
  320. $query = $this->getQueryBuilder();
  321. $query->update('filecache')
  322. ->whereFileId($id)
  323. ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
  324. return $query->expr()->orX(
  325. $query->expr()->neq($key, $query->createNamedParameter($value)),
  326. $query->expr()->isNull($key)
  327. );
  328. }, array_keys($values), array_values($values))));
  329. foreach ($values as $key => $value) {
  330. $query->set($key, $query->createNamedParameter($value));
  331. }
  332. $query->execute();
  333. }
  334. if (count($extensionValues)) {
  335. try {
  336. $query = $this->getQueryBuilder();
  337. $query->insert('filecache_extended');
  338. $query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
  339. foreach ($extensionValues as $column => $value) {
  340. $query->setValue($column, $query->createNamedParameter($value));
  341. }
  342. $query->execute();
  343. } catch (UniqueConstraintViolationException $e) {
  344. $query = $this->getQueryBuilder();
  345. $query->update('filecache_extended')
  346. ->whereFileId($id)
  347. ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
  348. return $query->expr()->orX(
  349. $query->expr()->neq($key, $query->createNamedParameter($value)),
  350. $query->expr()->isNull($key)
  351. );
  352. }, array_keys($extensionValues), array_values($extensionValues))));
  353. foreach ($extensionValues as $key => $value) {
  354. $query->set($key, $query->createNamedParameter($value));
  355. }
  356. $query->execute();
  357. }
  358. }
  359. $path = $this->getPathById($id);
  360. // path can still be null if the file doesn't exist
  361. if ($path !== null) {
  362. $event = new CacheEntryUpdatedEvent($this->storage, $path, $id, $this->getNumericStorageId());
  363. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  364. $this->eventDispatcher->dispatchTyped($event);
  365. }
  366. }
  367. /**
  368. * extract query parts and params array from data array
  369. *
  370. * @param array $data
  371. * @return array
  372. */
  373. protected function normalizeData(array $data): array {
  374. $fields = [
  375. 'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
  376. 'etag', 'permissions', 'checksum', 'storage'];
  377. $extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
  378. $doNotCopyStorageMTime = false;
  379. if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
  380. // this horrific magic tells it to not copy storage_mtime to mtime
  381. unset($data['mtime']);
  382. $doNotCopyStorageMTime = true;
  383. }
  384. $params = [];
  385. $extensionParams = [];
  386. foreach ($data as $name => $value) {
  387. if (array_search($name, $fields) !== false) {
  388. if ($name === 'path') {
  389. $params['path_hash'] = md5($value);
  390. } elseif ($name === 'mimetype') {
  391. $params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
  392. $value = $this->mimetypeLoader->getId($value);
  393. } elseif ($name === 'storage_mtime') {
  394. if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
  395. $params['mtime'] = $value;
  396. }
  397. } elseif ($name === 'encrypted') {
  398. if (isset($data['encryptedVersion'])) {
  399. $value = $data['encryptedVersion'];
  400. } else {
  401. // Boolean to integer conversion
  402. $value = $value ? 1 : 0;
  403. }
  404. }
  405. $params[$name] = $value;
  406. }
  407. if (array_search($name, $extensionFields) !== false) {
  408. $extensionParams[$name] = $value;
  409. }
  410. }
  411. return [$params, array_filter($extensionParams)];
  412. }
  413. /**
  414. * get the file id for a file
  415. *
  416. * 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
  417. *
  418. * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
  419. *
  420. * @param string $file
  421. * @return int
  422. */
  423. public function getId($file) {
  424. // normalize file
  425. $file = $this->normalize($file);
  426. $query = $this->getQueryBuilder();
  427. $query->select('fileid')
  428. ->from('filecache')
  429. ->whereStorageId()
  430. ->wherePath($file);
  431. $result = $query->execute();
  432. $id = $result->fetchOne();
  433. $result->closeCursor();
  434. return $id === false ? -1 : (int)$id;
  435. }
  436. /**
  437. * get the id of the parent folder of a file
  438. *
  439. * @param string $file
  440. * @return int
  441. */
  442. public function getParentId($file) {
  443. if ($file === '') {
  444. return -1;
  445. } else {
  446. $parent = $this->getParentPath($file);
  447. return (int)$this->getId($parent);
  448. }
  449. }
  450. private function getParentPath($path) {
  451. $parent = dirname($path);
  452. if ($parent === '.') {
  453. $parent = '';
  454. }
  455. return $parent;
  456. }
  457. /**
  458. * check if a file is available in the cache
  459. *
  460. * @param string $file
  461. * @return bool
  462. */
  463. public function inCache($file) {
  464. return $this->getId($file) != -1;
  465. }
  466. /**
  467. * remove a file or folder from the cache
  468. *
  469. * when removing a folder from the cache all files and folders inside the folder will be removed as well
  470. *
  471. * @param string $file
  472. */
  473. public function remove($file) {
  474. $entry = $this->get($file);
  475. if ($entry) {
  476. $query = $this->getQueryBuilder();
  477. $query->delete('filecache')
  478. ->whereFileId($entry->getId());
  479. $query->execute();
  480. $query = $this->getQueryBuilder();
  481. $query->delete('filecache_extended')
  482. ->whereFileId($entry->getId());
  483. $query->execute();
  484. if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
  485. $this->removeChildren($entry);
  486. }
  487. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $entry->getPath(), $entry->getId(), $this->getNumericStorageId()));
  488. }
  489. }
  490. /**
  491. * Get all sub folders of a folder
  492. *
  493. * @param ICacheEntry $entry the cache entry of the folder to get the subfolders for
  494. * @return ICacheEntry[] the cache entries for the subfolders
  495. */
  496. private function getSubFolders(ICacheEntry $entry) {
  497. $children = $this->getFolderContentsById($entry->getId());
  498. return array_filter($children, function ($child) {
  499. return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
  500. });
  501. }
  502. /**
  503. * Recursively remove all children of a folder
  504. *
  505. * @param ICacheEntry $entry the cache entry of the folder to remove the children of
  506. * @throws \OC\DatabaseException
  507. */
  508. private function removeChildren(ICacheEntry $entry) {
  509. $parentIds = [$entry->getId()];
  510. $queue = [$entry->getId()];
  511. // we walk depth first trough the file tree, removing all filecache_extended attributes while we walk
  512. // and collecting all folder ids to later use to delete the filecache entries
  513. while ($entryId = array_pop($queue)) {
  514. $children = $this->getFolderContentsById($entryId);
  515. $childIds = array_map(function (ICacheEntry $cacheEntry) {
  516. return $cacheEntry->getId();
  517. }, $children);
  518. $query = $this->getQueryBuilder();
  519. $query->delete('filecache_extended')
  520. ->where($query->expr()->in('fileid', $query->createNamedParameter($childIds, IQueryBuilder::PARAM_INT_ARRAY)));
  521. $query->execute();
  522. /** @var ICacheEntry[] $childFolders */
  523. $childFolders = array_filter($children, function ($child) {
  524. return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
  525. });
  526. foreach ($childFolders as $folder) {
  527. $parentIds[] = $folder->getId();
  528. $queue[] = $folder->getId();
  529. }
  530. }
  531. $query = $this->getQueryBuilder();
  532. $query->delete('filecache')
  533. ->whereParentIn($parentIds);
  534. $query->execute();
  535. }
  536. /**
  537. * Move a file or folder in the cache
  538. *
  539. * @param string $source
  540. * @param string $target
  541. */
  542. public function move($source, $target) {
  543. $this->moveFromCache($this, $source, $target);
  544. }
  545. /**
  546. * Get the storage id and path needed for a move
  547. *
  548. * @param string $path
  549. * @return array [$storageId, $internalPath]
  550. */
  551. protected function getMoveInfo($path) {
  552. return [$this->getNumericStorageId(), $path];
  553. }
  554. /**
  555. * Move a file or folder in the cache
  556. *
  557. * @param \OCP\Files\Cache\ICache $sourceCache
  558. * @param string $sourcePath
  559. * @param string $targetPath
  560. * @throws \OC\DatabaseException
  561. * @throws \Exception if the given storages have an invalid id
  562. */
  563. public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
  564. if ($sourceCache instanceof Cache) {
  565. // normalize source and target
  566. $sourcePath = $this->normalize($sourcePath);
  567. $targetPath = $this->normalize($targetPath);
  568. $sourceData = $sourceCache->get($sourcePath);
  569. $sourceId = $sourceData['fileid'];
  570. $newParentId = $this->getParentId($targetPath);
  571. [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
  572. [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
  573. if (is_null($sourceStorageId) || $sourceStorageId === false) {
  574. throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
  575. }
  576. if (is_null($targetStorageId) || $targetStorageId === false) {
  577. throw new \Exception('Invalid target storage id: ' . $targetStorageId);
  578. }
  579. $this->connection->beginTransaction();
  580. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  581. //update all child entries
  582. $sourceLength = mb_strlen($sourcePath);
  583. $query = $this->connection->getQueryBuilder();
  584. $fun = $query->func();
  585. $newPathFunction = $fun->concat(
  586. $query->createNamedParameter($targetPath),
  587. $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
  588. );
  589. $query->update('filecache')
  590. ->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
  591. ->set('path_hash', $fun->md5($newPathFunction))
  592. ->set('path', $newPathFunction)
  593. ->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
  594. ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
  595. try {
  596. $query->execute();
  597. } catch (\OC\DatabaseException $e) {
  598. $this->connection->rollBack();
  599. throw $e;
  600. }
  601. }
  602. $query = $this->getQueryBuilder();
  603. $query->update('filecache')
  604. ->set('storage', $query->createNamedParameter($targetStorageId))
  605. ->set('path', $query->createNamedParameter($targetPath))
  606. ->set('path_hash', $query->createNamedParameter(md5($targetPath)))
  607. ->set('name', $query->createNamedParameter(basename($targetPath)))
  608. ->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
  609. ->whereFileId($sourceId);
  610. $query->execute();
  611. $this->connection->commit();
  612. if ($sourceCache->getNumericStorageId() !== $this->getNumericStorageId()) {
  613. $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $sourcePath, $sourceId, $sourceCache->getNumericStorageId()));
  614. $event = new CacheEntryInsertedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  615. $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
  616. $this->eventDispatcher->dispatchTyped($event);
  617. } else {
  618. $event = new CacheEntryUpdatedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
  619. $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
  620. $this->eventDispatcher->dispatchTyped($event);
  621. }
  622. } else {
  623. $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
  624. }
  625. }
  626. /**
  627. * remove all entries for files that are stored on the storage from the cache
  628. */
  629. public function clear() {
  630. $query = $this->getQueryBuilder();
  631. $query->delete('filecache')
  632. ->whereStorageId();
  633. $query->execute();
  634. $query = $this->connection->getQueryBuilder();
  635. $query->delete('storages')
  636. ->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
  637. $query->execute();
  638. }
  639. /**
  640. * Get the scan status of a file
  641. *
  642. * - Cache::NOT_FOUND: File is not in the cache
  643. * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
  644. * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
  645. * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
  646. *
  647. * @param string $file
  648. *
  649. * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  650. */
  651. public function getStatus($file) {
  652. // normalize file
  653. $file = $this->normalize($file);
  654. $query = $this->getQueryBuilder();
  655. $query->select('size')
  656. ->from('filecache')
  657. ->whereStorageId()
  658. ->wherePath($file);
  659. $result = $query->execute();
  660. $size = $result->fetchOne();
  661. $result->closeCursor();
  662. if ($size !== false) {
  663. if ((int)$size === -1) {
  664. return self::SHALLOW;
  665. } else {
  666. return self::COMPLETE;
  667. }
  668. } else {
  669. if (isset($this->partial[$file])) {
  670. return self::PARTIAL;
  671. } else {
  672. return self::NOT_FOUND;
  673. }
  674. }
  675. }
  676. /**
  677. * search for files matching $pattern
  678. *
  679. * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
  680. * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
  681. */
  682. public function search($pattern) {
  683. // normalize pattern
  684. $pattern = $this->normalize($pattern);
  685. if ($pattern === '%%') {
  686. return [];
  687. }
  688. $query = $this->getQueryBuilder();
  689. $query->selectFileCache()
  690. ->whereStorageId()
  691. ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
  692. $result = $query->execute();
  693. $files = $result->fetchAll();
  694. $result->closeCursor();
  695. return array_map(function (array $data) {
  696. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  697. }, $files);
  698. }
  699. /**
  700. * @param IResult $result
  701. * @return CacheEntry[]
  702. */
  703. private function searchResultToCacheEntries(IResult $result): array {
  704. $files = $result->fetchAll();
  705. return array_map(function (array $data) {
  706. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  707. }, $files);
  708. }
  709. /**
  710. * search for files by mimetype
  711. *
  712. * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
  713. * where it will search for all mimetypes in the group ('image/*')
  714. * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
  715. */
  716. public function searchByMime($mimetype) {
  717. $mimeId = $this->mimetypeLoader->getId($mimetype);
  718. $query = $this->getQueryBuilder();
  719. $query->selectFileCache()
  720. ->whereStorageId();
  721. if (strpos($mimetype, '/')) {
  722. $query->andWhere($query->expr()->eq('mimetype', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
  723. } else {
  724. $query->andWhere($query->expr()->eq('mimepart', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
  725. }
  726. $result = $query->execute();
  727. $files = $result->fetchAll();
  728. $result->closeCursor();
  729. return array_map(function (array $data) {
  730. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  731. }, $files);
  732. }
  733. public function searchQuery(ISearchQuery $searchQuery) {
  734. $builder = $this->getQueryBuilder();
  735. $query = $builder->selectFileCache('file');
  736. $query->whereStorageId();
  737. if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
  738. $query
  739. ->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
  740. ->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
  741. $builder->expr()->eq('tagmap.type', 'tag.type'),
  742. $builder->expr()->eq('tagmap.categoryid', 'tag.id')
  743. ))
  744. ->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
  745. ->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($searchQuery->getUser()->getUID())));
  746. }
  747. $searchExpr = $this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation());
  748. if ($searchExpr) {
  749. $query->andWhere($searchExpr);
  750. }
  751. if ($searchQuery->limitToHome() && ($this instanceof HomeCache)) {
  752. $query->andWhere($builder->expr()->like('path', $query->expr()->literal('files/%')));
  753. }
  754. $this->querySearchHelper->addSearchOrdersToQuery($query, $searchQuery->getOrder());
  755. if ($searchQuery->getLimit()) {
  756. $query->setMaxResults($searchQuery->getLimit());
  757. }
  758. if ($searchQuery->getOffset()) {
  759. $query->setFirstResult($searchQuery->getOffset());
  760. }
  761. $result = $query->execute();
  762. $cacheEntries = $this->searchResultToCacheEntries($result);
  763. $result->closeCursor();
  764. return $cacheEntries;
  765. }
  766. /**
  767. * Re-calculate the folder size and the size of all parent folders
  768. *
  769. * @param string|boolean $path
  770. * @param array $data (optional) meta data of the folder
  771. */
  772. public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
  773. $this->calculateFolderSize($path, $data);
  774. if ($path !== '') {
  775. $parent = dirname($path);
  776. if ($parent === '.' or $parent === '/') {
  777. $parent = '';
  778. }
  779. if ($isBackgroundScan) {
  780. $parentData = $this->get($parent);
  781. if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
  782. $this->correctFolderSize($parent, $parentData, $isBackgroundScan);
  783. }
  784. } else {
  785. $this->correctFolderSize($parent);
  786. }
  787. }
  788. }
  789. /**
  790. * get the incomplete count that shares parent $folder
  791. *
  792. * @param int $fileId the file id of the folder
  793. * @return int
  794. */
  795. public function getIncompleteChildrenCount($fileId) {
  796. if ($fileId > -1) {
  797. $query = $this->getQueryBuilder();
  798. $query->select($query->func()->count())
  799. ->from('filecache')
  800. ->whereParent($fileId)
  801. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
  802. $result = $query->execute();
  803. $size = (int)$result->fetchOne();
  804. $result->closeCursor();
  805. return $size;
  806. }
  807. return -1;
  808. }
  809. /**
  810. * calculate the size of a folder and set it in the cache
  811. *
  812. * @param string $path
  813. * @param array $entry (optional) meta data of the folder
  814. * @return int
  815. */
  816. public function calculateFolderSize($path, $entry = null) {
  817. $totalSize = 0;
  818. if (is_null($entry) or !isset($entry['fileid'])) {
  819. $entry = $this->get($path);
  820. }
  821. if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
  822. $id = $entry['fileid'];
  823. $query = $this->getQueryBuilder();
  824. $query->selectAlias($query->func()->sum('size'), 'f1')
  825. ->selectAlias($query->func()->min('size'), 'f2')
  826. ->from('filecache')
  827. ->whereStorageId()
  828. ->whereParent($id);
  829. $result = $query->execute();
  830. $row = $result->fetch();
  831. $result->closeCursor();
  832. if ($row) {
  833. [$sum, $min] = array_values($row);
  834. $sum = 0 + $sum;
  835. $min = 0 + $min;
  836. if ($min === -1) {
  837. $totalSize = $min;
  838. } else {
  839. $totalSize = $sum;
  840. }
  841. if ($entry['size'] !== $totalSize) {
  842. $this->update($id, ['size' => $totalSize]);
  843. }
  844. }
  845. }
  846. return $totalSize;
  847. }
  848. /**
  849. * get all file ids on the files on the storage
  850. *
  851. * @return int[]
  852. */
  853. public function getAll() {
  854. $query = $this->getQueryBuilder();
  855. $query->select('fileid')
  856. ->from('filecache')
  857. ->whereStorageId();
  858. $result = $query->execute();
  859. $files = $result->fetchAll(\PDO::FETCH_COLUMN);
  860. $result->closeCursor();
  861. return array_map(function ($id) {
  862. return (int)$id;
  863. }, $files);
  864. }
  865. /**
  866. * find a folder in the cache which has not been fully scanned
  867. *
  868. * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
  869. * use the one with the highest id gives the best result with the background scanner, since that is most
  870. * likely the folder where we stopped scanning previously
  871. *
  872. * @return string|bool the path of the folder or false when no folder matched
  873. */
  874. public function getIncomplete() {
  875. $query = $this->getQueryBuilder();
  876. $query->select('path')
  877. ->from('filecache')
  878. ->whereStorageId()
  879. ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
  880. ->orderBy('fileid', 'DESC')
  881. ->setMaxResults(1);
  882. $result = $query->execute();
  883. $path = $result->fetchOne();
  884. $result->closeCursor();
  885. return $path;
  886. }
  887. /**
  888. * get the path of a file on this storage by it's file id
  889. *
  890. * @param int $id the file id of the file or folder to search
  891. * @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
  892. */
  893. public function getPathById($id) {
  894. $query = $this->getQueryBuilder();
  895. $query->select('path')
  896. ->from('filecache')
  897. ->whereStorageId()
  898. ->whereFileId($id);
  899. $result = $query->execute();
  900. $path = $result->fetchOne();
  901. $result->closeCursor();
  902. if ($path === false) {
  903. return null;
  904. }
  905. return (string) $path;
  906. }
  907. /**
  908. * get the storage id of the storage for a file and the internal path of the file
  909. * unlike getPathById this does not limit the search to files on this storage and
  910. * instead does a global search in the cache table
  911. *
  912. * @param int $id
  913. * @return array first element holding the storage id, second the path
  914. * @deprecated use getPathById() instead
  915. */
  916. public static function getById($id) {
  917. $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  918. $query->select('path', 'storage')
  919. ->from('filecache')
  920. ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
  921. $result = $query->execute();
  922. $row = $result->fetch();
  923. $result->closeCursor();
  924. if ($row) {
  925. $numericId = $row['storage'];
  926. $path = $row['path'];
  927. } else {
  928. return null;
  929. }
  930. if ($id = Storage::getStorageId($numericId)) {
  931. return [$id, $path];
  932. } else {
  933. return null;
  934. }
  935. }
  936. /**
  937. * normalize the given path
  938. *
  939. * @param string $path
  940. * @return string
  941. */
  942. public function normalize($path) {
  943. return trim(\OC_Util::normalizeUnicode($path), '/');
  944. }
  945. }