Cache.php 28 KB

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