Cache.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Artem Kochnev <MrJeos@gmail.com>
  7. * @author Björn Schießle <bjoern@schiessle.org>
  8. * @author Florin Peter <github@florin-peter.de>
  9. * @author Frédéric Fortier <frederic.fortier@oronospolytechnique.com>
  10. * @author Jens-Christian Fischer <jens-christian.fischer@switch.ch>
  11. * @author Joas Schilling <coding@schilljs.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Vincent Petry <pvince81@owncloud.com>
  21. *
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Files\Cache;
  38. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  39. use OCP\DB\QueryBuilder\IQueryBuilder;
  40. use Doctrine\DBAL\Driver\Statement;
  41. use OCP\Files\Cache\ICache;
  42. use OCP\Files\Cache\ICacheEntry;
  43. use \OCP\Files\IMimeTypeLoader;
  44. use OCP\Files\Search\ISearchQuery;
  45. use OCP\IDBConnection;
  46. /**
  47. * Metadata cache for a storage
  48. *
  49. * The cache stores the metadata for all files and folders in a storage and is kept up to date trough the following mechanisms:
  50. *
  51. * - Scanner: scans the storage and updates the cache where needed
  52. * - Watcher: checks for changes made to the filesystem outside of the ownCloud instance and rescans files and folder when a change is detected
  53. * - Updater: listens to changes made to the filesystem inside of the ownCloud instance and updates the cache where needed
  54. * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
  55. */
  56. class Cache implements ICache {
  57. use MoveFromCacheTrait {
  58. MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
  59. }
  60. /**
  61. * @var array partial data for the cache
  62. */
  63. protected $partial = array();
  64. /**
  65. * @var string
  66. */
  67. protected $storageId;
  68. /**
  69. * @var Storage $storageCache
  70. */
  71. protected $storageCache;
  72. /** @var IMimeTypeLoader */
  73. protected $mimetypeLoader;
  74. /**
  75. * @var IDBConnection
  76. */
  77. protected $connection;
  78. /** @var QuerySearchHelper */
  79. protected $querySearchHelper;
  80. /**
  81. * @param \OC\Files\Storage\Storage|string $storage
  82. */
  83. public function __construct($storage) {
  84. if ($storage instanceof \OC\Files\Storage\Storage) {
  85. $this->storageId = $storage->getId();
  86. } else {
  87. $this->storageId = $storage;
  88. }
  89. if (strlen($this->storageId) > 64) {
  90. $this->storageId = md5($this->storageId);
  91. }
  92. $this->storageCache = new Storage($storage);
  93. $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
  94. $this->connection = \OC::$server->getDatabaseConnection();
  95. $this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
  96. }
  97. /**
  98. * Get the numeric storage id for this cache's storage
  99. *
  100. * @return int
  101. */
  102. public function getNumericStorageId() {
  103. return $this->storageCache->getNumericId();
  104. }
  105. /**
  106. * get the stored metadata of a file or folder
  107. *
  108. * @param string | int $file either the path of a file or folder or the file id for a file or folder
  109. * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
  110. */
  111. public function get($file) {
  112. if (is_string($file) or $file == '') {
  113. // normalize file
  114. $file = $this->normalize($file);
  115. $where = 'WHERE `storage` = ? AND `path_hash` = ?';
  116. $params = array($this->getNumericStorageId(), md5($file));
  117. } else { //file id
  118. $where = 'WHERE `fileid` = ?';
  119. $params = array($file);
  120. }
  121. $sql = 'SELECT `fileid`, `storage`, `path`, `path_hash`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
  122. `storage_mtime`, `encrypted`, `etag`, `permissions`, `checksum`
  123. FROM `*PREFIX*filecache` ' . $where;
  124. $result = $this->connection->executeQuery($sql, $params);
  125. $data = $result->fetch();
  126. //FIXME hide this HACK in the next database layer, or just use doctrine and get rid of MDB2 and PDO
  127. //PDO returns false, MDB2 returns null, oracle always uses MDB2, so convert null to false
  128. if ($data === null) {
  129. $data = false;
  130. }
  131. //merge partial data
  132. if (!$data and is_string($file)) {
  133. if (isset($this->partial[$file])) {
  134. $data = $this->partial[$file];
  135. }
  136. return $data;
  137. } else if (!$data) {
  138. return $data;
  139. } else {
  140. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  141. }
  142. }
  143. /**
  144. * Create a CacheEntry from database row
  145. *
  146. * @param array $data
  147. * @param IMimeTypeLoader $mimetypeLoader
  148. * @return CacheEntry
  149. */
  150. public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
  151. //fix types
  152. $data['fileid'] = (int)$data['fileid'];
  153. $data['parent'] = (int)$data['parent'];
  154. $data['size'] = 0 + $data['size'];
  155. $data['mtime'] = (int)$data['mtime'];
  156. $data['storage_mtime'] = (int)$data['storage_mtime'];
  157. $data['encryptedVersion'] = (int)$data['encrypted'];
  158. $data['encrypted'] = (bool)$data['encrypted'];
  159. $data['storage_id'] = $data['storage'];
  160. $data['storage'] = (int)$data['storage'];
  161. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  162. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  163. if ($data['storage_mtime'] == 0) {
  164. $data['storage_mtime'] = $data['mtime'];
  165. }
  166. $data['permissions'] = (int)$data['permissions'];
  167. return new CacheEntry($data);
  168. }
  169. /**
  170. * get the metadata of all files stored in $folder
  171. *
  172. * @param string $folder
  173. * @return ICacheEntry[]
  174. */
  175. public function getFolderContents($folder) {
  176. $fileId = $this->getId($folder);
  177. return $this->getFolderContentsById($fileId);
  178. }
  179. /**
  180. * get the metadata of all files stored in $folder
  181. *
  182. * @param int $fileId the file id of the folder
  183. * @return ICacheEntry[]
  184. */
  185. public function getFolderContentsById($fileId) {
  186. if ($fileId > -1) {
  187. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
  188. `storage_mtime`, `encrypted`, `etag`, `permissions`, `checksum`
  189. FROM `*PREFIX*filecache` WHERE `parent` = ? ORDER BY `name` ASC';
  190. $result = $this->connection->executeQuery($sql, [$fileId]);
  191. $files = $result->fetchAll();
  192. return array_map(function (array $data) {
  193. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  194. }, $files);
  195. }
  196. return [];
  197. }
  198. /**
  199. * insert or update meta data for a file or folder
  200. *
  201. * @param string $file
  202. * @param array $data
  203. *
  204. * @return int file id
  205. * @throws \RuntimeException
  206. */
  207. public function put($file, array $data) {
  208. if (($id = $this->getId($file)) > -1) {
  209. $this->update($id, $data);
  210. return $id;
  211. } else {
  212. return $this->insert($file, $data);
  213. }
  214. }
  215. /**
  216. * insert meta data for a new file or folder
  217. *
  218. * @param string $file
  219. * @param array $data
  220. *
  221. * @return int file id
  222. * @throws \RuntimeException
  223. *
  224. * @suppress SqlInjectionChecker
  225. */
  226. public function insert($file, array $data) {
  227. // normalize file
  228. $file = $this->normalize($file);
  229. if (isset($this->partial[$file])) { //add any saved partial data
  230. $data = array_merge($this->partial[$file], $data);
  231. unset($this->partial[$file]);
  232. }
  233. $requiredFields = array('size', 'mtime', 'mimetype');
  234. foreach ($requiredFields as $field) {
  235. if (!isset($data[$field])) { //data not complete save as partial and return
  236. $this->partial[$file] = $data;
  237. return -1;
  238. }
  239. }
  240. $data['path'] = $file;
  241. $data['parent'] = $this->getParentId($file);
  242. $data['name'] = basename($file);
  243. list($queryParts, $params) = $this->buildParts($data);
  244. $queryParts[] = '`storage`';
  245. $params[] = $this->getNumericStorageId();
  246. $queryParts = array_map(function ($item) {
  247. return trim($item, "`");
  248. }, $queryParts);
  249. $values = array_combine($queryParts, $params);
  250. try {
  251. $builder = $this->connection->getQueryBuilder();
  252. $builder->insert('filecache');
  253. foreach ($values as $column => $value) {
  254. $builder->setValue($column, $builder->createNamedParameter($value));
  255. }
  256. if ($builder->execute()) {
  257. return (int)$this->connection->lastInsertId('*PREFIX*filecache');
  258. }
  259. } catch(UniqueConstraintViolationException $e) {
  260. // entry exists already
  261. }
  262. // The file was created in the mean time
  263. if (($id = $this->getId($file)) > -1) {
  264. $this->update($id, $data);
  265. return $id;
  266. } else {
  267. 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.');
  268. }
  269. }
  270. /**
  271. * update the metadata of an existing file or folder in the cache
  272. *
  273. * @param int $id the fileid of the existing file or folder
  274. * @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
  275. */
  276. public function update($id, array $data) {
  277. if (isset($data['path'])) {
  278. // normalize path
  279. $data['path'] = $this->normalize($data['path']);
  280. }
  281. if (isset($data['name'])) {
  282. // normalize path
  283. $data['name'] = $this->normalize($data['name']);
  284. }
  285. list($queryParts, $params) = $this->buildParts($data);
  286. // duplicate $params because we need the parts twice in the SQL statement
  287. // once for the SET part, once in the WHERE clause
  288. $params = array_merge($params, $params);
  289. $params[] = $id;
  290. // don't update if the data we try to set is the same as the one in the record
  291. // some databases (Postgres) don't like superfluous updates
  292. $sql = 'UPDATE `*PREFIX*filecache` SET ' . implode(' = ?, ', $queryParts) . '=? ' .
  293. 'WHERE (' .
  294. implode(' <> ? OR ', $queryParts) . ' <> ? OR ' .
  295. implode(' IS NULL OR ', $queryParts) . ' IS NULL' .
  296. ') AND `fileid` = ? ';
  297. $this->connection->executeQuery($sql, $params);
  298. }
  299. /**
  300. * extract query parts and params array from data array
  301. *
  302. * @param array $data
  303. * @return array [$queryParts, $params]
  304. * $queryParts: string[], the (escaped) column names to be set in the query
  305. * $params: mixed[], the new values for the columns, to be passed as params to the query
  306. */
  307. protected function buildParts(array $data) {
  308. $fields = array(
  309. 'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
  310. 'etag', 'permissions', 'checksum', 'storage');
  311. $doNotCopyStorageMTime = false;
  312. if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
  313. // this horrific magic tells it to not copy storage_mtime to mtime
  314. unset($data['mtime']);
  315. $doNotCopyStorageMTime = true;
  316. }
  317. $params = array();
  318. $queryParts = array();
  319. foreach ($data as $name => $value) {
  320. if (array_search($name, $fields) !== false) {
  321. if ($name === 'path') {
  322. $params[] = md5($value);
  323. $queryParts[] = '`path_hash`';
  324. } elseif ($name === 'mimetype') {
  325. $params[] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
  326. $queryParts[] = '`mimepart`';
  327. $value = $this->mimetypeLoader->getId($value);
  328. } elseif ($name === 'storage_mtime') {
  329. if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
  330. $params[] = $value;
  331. $queryParts[] = '`mtime`';
  332. }
  333. } elseif ($name === 'encrypted') {
  334. if (isset($data['encryptedVersion'])) {
  335. $value = $data['encryptedVersion'];
  336. } else {
  337. // Boolean to integer conversion
  338. $value = $value ? 1 : 0;
  339. }
  340. }
  341. $params[] = $value;
  342. $queryParts[] = '`' . $name . '`';
  343. }
  344. }
  345. return array($queryParts, $params);
  346. }
  347. /**
  348. * get the file id for a file
  349. *
  350. * 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
  351. *
  352. * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
  353. *
  354. * @param string $file
  355. * @return int
  356. */
  357. public function getId($file) {
  358. // normalize file
  359. $file = $this->normalize($file);
  360. $pathHash = md5($file);
  361. $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
  362. $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
  363. if ($row = $result->fetch()) {
  364. return $row['fileid'];
  365. } else {
  366. return -1;
  367. }
  368. }
  369. /**
  370. * get the id of the parent folder of a file
  371. *
  372. * @param string $file
  373. * @return int
  374. */
  375. public function getParentId($file) {
  376. if ($file === '') {
  377. return -1;
  378. } else {
  379. $parent = $this->getParentPath($file);
  380. return (int)$this->getId($parent);
  381. }
  382. }
  383. private function getParentPath($path) {
  384. $parent = dirname($path);
  385. if ($parent === '.') {
  386. $parent = '';
  387. }
  388. return $parent;
  389. }
  390. /**
  391. * check if a file is available in the cache
  392. *
  393. * @param string $file
  394. * @return bool
  395. */
  396. public function inCache($file) {
  397. return $this->getId($file) != -1;
  398. }
  399. /**
  400. * remove a file or folder from the cache
  401. *
  402. * when removing a folder from the cache all files and folders inside the folder will be removed as well
  403. *
  404. * @param string $file
  405. */
  406. public function remove($file) {
  407. $entry = $this->get($file);
  408. $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `fileid` = ?';
  409. $this->connection->executeQuery($sql, array($entry['fileid']));
  410. if ($entry['mimetype'] === 'httpd/unix-directory') {
  411. $this->removeChildren($entry);
  412. }
  413. }
  414. /**
  415. * Get all sub folders of a folder
  416. *
  417. * @param array $entry the cache entry of the folder to get the subfolders for
  418. * @return array[] the cache entries for the subfolders
  419. */
  420. private function getSubFolders($entry) {
  421. $children = $this->getFolderContentsById($entry['fileid']);
  422. return array_filter($children, function ($child) {
  423. return $child['mimetype'] === 'httpd/unix-directory';
  424. });
  425. }
  426. /**
  427. * Recursively remove all children of a folder
  428. *
  429. * @param array $entry the cache entry of the folder to remove the children of
  430. * @throws \OC\DatabaseException
  431. */
  432. private function removeChildren($entry) {
  433. $subFolders = $this->getSubFolders($entry);
  434. foreach ($subFolders as $folder) {
  435. $this->removeChildren($folder);
  436. }
  437. $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `parent` = ?';
  438. $this->connection->executeQuery($sql, array($entry['fileid']));
  439. }
  440. /**
  441. * Move a file or folder in the cache
  442. *
  443. * @param string $source
  444. * @param string $target
  445. */
  446. public function move($source, $target) {
  447. $this->moveFromCache($this, $source, $target);
  448. }
  449. /**
  450. * Get the storage id and path needed for a move
  451. *
  452. * @param string $path
  453. * @return array [$storageId, $internalPath]
  454. */
  455. protected function getMoveInfo($path) {
  456. return [$this->getNumericStorageId(), $path];
  457. }
  458. /**
  459. * Move a file or folder in the cache
  460. *
  461. * @param \OCP\Files\Cache\ICache $sourceCache
  462. * @param string $sourcePath
  463. * @param string $targetPath
  464. * @throws \OC\DatabaseException
  465. * @throws \Exception if the given storages have an invalid id
  466. * @suppress SqlInjectionChecker
  467. */
  468. public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
  469. if ($sourceCache instanceof Cache) {
  470. // normalize source and target
  471. $sourcePath = $this->normalize($sourcePath);
  472. $targetPath = $this->normalize($targetPath);
  473. $sourceData = $sourceCache->get($sourcePath);
  474. $sourceId = $sourceData['fileid'];
  475. $newParentId = $this->getParentId($targetPath);
  476. list($sourceStorageId, $sourcePath) = $sourceCache->getMoveInfo($sourcePath);
  477. list($targetStorageId, $targetPath) = $this->getMoveInfo($targetPath);
  478. if (is_null($sourceStorageId) || $sourceStorageId === false) {
  479. throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
  480. }
  481. if (is_null($targetStorageId) || $targetStorageId === false) {
  482. throw new \Exception('Invalid target storage id: ' . $targetStorageId);
  483. }
  484. $this->connection->beginTransaction();
  485. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  486. //update all child entries
  487. $sourceLength = mb_strlen($sourcePath);
  488. $query = $this->connection->getQueryBuilder();
  489. $fun = $query->func();
  490. $newPathFunction = $fun->concat(
  491. $query->createNamedParameter($targetPath),
  492. $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
  493. );
  494. $query->update('filecache')
  495. ->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
  496. ->set('path_hash', $fun->md5($newPathFunction))
  497. ->set('path', $newPathFunction)
  498. ->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
  499. ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
  500. try {
  501. $query->execute();
  502. } catch (\OC\DatabaseException $e) {
  503. $this->connection->rollBack();
  504. throw $e;
  505. }
  506. }
  507. $sql = 'UPDATE `*PREFIX*filecache` SET `storage` = ?, `path` = ?, `path_hash` = ?, `name` = ?, `parent` = ? WHERE `fileid` = ?';
  508. $this->connection->executeQuery($sql, array($targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId));
  509. $this->connection->commit();
  510. } else {
  511. $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
  512. }
  513. }
  514. /**
  515. * remove all entries for files that are stored on the storage from the cache
  516. */
  517. public function clear() {
  518. $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?';
  519. $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
  520. $sql = 'DELETE FROM `*PREFIX*storages` WHERE `id` = ?';
  521. $this->connection->executeQuery($sql, array($this->storageId));
  522. }
  523. /**
  524. * Get the scan status of a file
  525. *
  526. * - Cache::NOT_FOUND: File is not in the cache
  527. * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
  528. * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
  529. * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
  530. *
  531. * @param string $file
  532. *
  533. * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  534. */
  535. public function getStatus($file) {
  536. // normalize file
  537. $file = $this->normalize($file);
  538. $pathHash = md5($file);
  539. $sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
  540. $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
  541. if ($row = $result->fetch()) {
  542. if ((int)$row['size'] === -1) {
  543. return self::SHALLOW;
  544. } else {
  545. return self::COMPLETE;
  546. }
  547. } else {
  548. if (isset($this->partial[$file])) {
  549. return self::PARTIAL;
  550. } else {
  551. return self::NOT_FOUND;
  552. }
  553. }
  554. }
  555. /**
  556. * search for files matching $pattern
  557. *
  558. * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
  559. * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
  560. */
  561. public function search($pattern) {
  562. // normalize pattern
  563. $pattern = $this->normalize($pattern);
  564. if ($pattern === '%%') {
  565. return [];
  566. }
  567. $sql = '
  568. SELECT `fileid`, `storage`, `path`, `parent`, `name`,
  569. `mimetype`, `storage_mtime`, `mimepart`, `size`, `mtime`,
  570. `encrypted`, `etag`, `permissions`, `checksum`
  571. FROM `*PREFIX*filecache`
  572. WHERE `storage` = ? AND `name` ILIKE ?';
  573. $result = $this->connection->executeQuery($sql,
  574. [$this->getNumericStorageId(), $pattern]
  575. );
  576. return $this->searchResultToCacheEntries($result);
  577. }
  578. /**
  579. * @param Statement $result
  580. * @return CacheEntry[]
  581. */
  582. private function searchResultToCacheEntries(Statement $result) {
  583. $files = $result->fetchAll();
  584. return array_map(function (array $data) {
  585. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  586. }, $files);
  587. }
  588. /**
  589. * search for files by mimetype
  590. *
  591. * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
  592. * where it will search for all mimetypes in the group ('image/*')
  593. * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
  594. */
  595. public function searchByMime($mimetype) {
  596. if (strpos($mimetype, '/')) {
  597. $where = '`mimetype` = ?';
  598. } else {
  599. $where = '`mimepart` = ?';
  600. }
  601. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `storage_mtime`, `mtime`, `encrypted`, `etag`, `permissions`, `checksum`
  602. FROM `*PREFIX*filecache` WHERE ' . $where . ' AND `storage` = ?';
  603. $mimetype = $this->mimetypeLoader->getId($mimetype);
  604. $result = $this->connection->executeQuery($sql, array($mimetype, $this->getNumericStorageId()));
  605. return $this->searchResultToCacheEntries($result);
  606. }
  607. public function searchQuery(ISearchQuery $searchQuery) {
  608. $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  609. $query = $builder->select(['fileid', 'storage', 'path', 'parent', 'name', 'mimetype', 'mimepart', 'size', 'mtime', 'storage_mtime', 'encrypted', 'etag', 'permissions', 'checksum'])
  610. ->from('filecache', 'file');
  611. $query->where($builder->expr()->eq('storage', $builder->createNamedParameter($this->getNumericStorageId())));
  612. if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
  613. $query
  614. ->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
  615. ->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
  616. $builder->expr()->eq('tagmap.type', 'tag.type'),
  617. $builder->expr()->eq('tagmap.categoryid', 'tag.id')
  618. ))
  619. ->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
  620. ->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($searchQuery->getUser()->getUID())));
  621. }
  622. $query->andWhere($this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation()));
  623. $this->querySearchHelper->addSearchOrdersToQuery($query, $searchQuery->getOrder());
  624. if ($searchQuery->getLimit()) {
  625. $query->setMaxResults($searchQuery->getLimit());
  626. }
  627. if ($searchQuery->getOffset()) {
  628. $query->setFirstResult($searchQuery->getOffset());
  629. }
  630. $result = $query->execute();
  631. return $this->searchResultToCacheEntries($result);
  632. }
  633. /**
  634. * Search for files by tag of a given users.
  635. *
  636. * Note that every user can tag files differently.
  637. *
  638. * @param string|int $tag name or tag id
  639. * @param string $userId owner of the tags
  640. * @return ICacheEntry[] file data
  641. */
  642. public function searchByTag($tag, $userId) {
  643. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, ' .
  644. '`mimetype`, `mimepart`, `size`, `mtime`, `storage_mtime`, ' .
  645. '`encrypted`, `etag`, `permissions`, `checksum` ' .
  646. 'FROM `*PREFIX*filecache` `file`, ' .
  647. '`*PREFIX*vcategory_to_object` `tagmap`, ' .
  648. '`*PREFIX*vcategory` `tag` ' .
  649. // JOIN filecache to vcategory_to_object
  650. 'WHERE `file`.`fileid` = `tagmap`.`objid` ' .
  651. // JOIN vcategory_to_object to vcategory
  652. 'AND `tagmap`.`type` = `tag`.`type` ' .
  653. 'AND `tagmap`.`categoryid` = `tag`.`id` ' .
  654. // conditions
  655. 'AND `file`.`storage` = ? ' .
  656. 'AND `tag`.`type` = \'files\' ' .
  657. 'AND `tag`.`uid` = ? ';
  658. if (is_int($tag)) {
  659. $sql .= 'AND `tag`.`id` = ? ';
  660. } else {
  661. $sql .= 'AND `tag`.`category` = ? ';
  662. }
  663. $result = $this->connection->executeQuery(
  664. $sql,
  665. [
  666. $this->getNumericStorageId(),
  667. $userId,
  668. $tag
  669. ]
  670. );
  671. $files = $result->fetchAll();
  672. return array_map(function (array $data) {
  673. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  674. }, $files);
  675. }
  676. /**
  677. * Re-calculate the folder size and the size of all parent folders
  678. *
  679. * @param string|boolean $path
  680. * @param array $data (optional) meta data of the folder
  681. */
  682. public function correctFolderSize($path, $data = null) {
  683. $this->calculateFolderSize($path, $data);
  684. if ($path !== '') {
  685. $parent = dirname($path);
  686. if ($parent === '.' or $parent === '/') {
  687. $parent = '';
  688. }
  689. $this->correctFolderSize($parent);
  690. }
  691. }
  692. /**
  693. * calculate the size of a folder and set it in the cache
  694. *
  695. * @param string $path
  696. * @param array $entry (optional) meta data of the folder
  697. * @return int
  698. */
  699. public function calculateFolderSize($path, $entry = null) {
  700. $totalSize = 0;
  701. if (is_null($entry) or !isset($entry['fileid'])) {
  702. $entry = $this->get($path);
  703. }
  704. if (isset($entry['mimetype']) && $entry['mimetype'] === 'httpd/unix-directory') {
  705. $id = $entry['fileid'];
  706. $sql = 'SELECT SUM(`size`) AS f1, MIN(`size`) AS f2 ' .
  707. 'FROM `*PREFIX*filecache` ' .
  708. 'WHERE `parent` = ? AND `storage` = ?';
  709. $result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
  710. if ($row = $result->fetch()) {
  711. $result->closeCursor();
  712. list($sum, $min) = array_values($row);
  713. $sum = 0 + $sum;
  714. $min = 0 + $min;
  715. if ($min === -1) {
  716. $totalSize = $min;
  717. } else {
  718. $totalSize = $sum;
  719. }
  720. $update = array();
  721. if ($entry['size'] !== $totalSize) {
  722. $update['size'] = $totalSize;
  723. }
  724. if (count($update) > 0) {
  725. $this->update($id, $update);
  726. }
  727. } else {
  728. $result->closeCursor();
  729. }
  730. }
  731. return $totalSize;
  732. }
  733. /**
  734. * get all file ids on the files on the storage
  735. *
  736. * @return int[]
  737. */
  738. public function getAll() {
  739. $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ?';
  740. $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
  741. $ids = array();
  742. while ($row = $result->fetch()) {
  743. $ids[] = $row['fileid'];
  744. }
  745. return $ids;
  746. }
  747. /**
  748. * find a folder in the cache which has not been fully scanned
  749. *
  750. * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
  751. * use the one with the highest id gives the best result with the background scanner, since that is most
  752. * likely the folder where we stopped scanning previously
  753. *
  754. * @return string|bool the path of the folder or false when no folder matched
  755. */
  756. public function getIncomplete() {
  757. $query = $this->connection->prepare('SELECT `path` FROM `*PREFIX*filecache`'
  758. . ' WHERE `storage` = ? AND `size` = -1 ORDER BY `fileid` DESC', 1);
  759. $query->execute([$this->getNumericStorageId()]);
  760. if ($row = $query->fetch()) {
  761. return $row['path'];
  762. } else {
  763. return false;
  764. }
  765. }
  766. /**
  767. * get the path of a file on this storage by it's file id
  768. *
  769. * @param int $id the file id of the file or folder to search
  770. * @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
  771. */
  772. public function getPathById($id) {
  773. $sql = 'SELECT `path` FROM `*PREFIX*filecache` WHERE `fileid` = ? AND `storage` = ?';
  774. $result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
  775. if ($row = $result->fetch()) {
  776. // Oracle stores empty strings as null...
  777. if ($row['path'] === null) {
  778. return '';
  779. }
  780. return $row['path'];
  781. } else {
  782. return null;
  783. }
  784. }
  785. /**
  786. * get the storage id of the storage for a file and the internal path of the file
  787. * unlike getPathById this does not limit the search to files on this storage and
  788. * instead does a global search in the cache table
  789. *
  790. * @param int $id
  791. * @deprecated use getPathById() instead
  792. * @return array first element holding the storage id, second the path
  793. */
  794. static public function getById($id) {
  795. $connection = \OC::$server->getDatabaseConnection();
  796. $sql = 'SELECT `storage`, `path` FROM `*PREFIX*filecache` WHERE `fileid` = ?';
  797. $result = $connection->executeQuery($sql, array($id));
  798. if ($row = $result->fetch()) {
  799. $numericId = $row['storage'];
  800. $path = $row['path'];
  801. } else {
  802. return null;
  803. }
  804. if ($id = Storage::getStorageId($numericId)) {
  805. return array($id, $path);
  806. } else {
  807. return null;
  808. }
  809. }
  810. /**
  811. * normalize the given path
  812. *
  813. * @param string $path
  814. * @return string
  815. */
  816. public function normalize($path) {
  817. return trim(\OC_Util::normalizeUnicode($path), '/');
  818. }
  819. }