Cache.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Florin Peter <github@florin-peter.de>
  8. * @author Jens-Christian Fischer <jens-christian.fischer@switch.ch>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  13. * @author Morris Jobke <hey@morrisjobke.de>
  14. * @author Robin Appelman <robin@icewind.nl>
  15. * @author Robin McCorkell <robin@mccorkell.me.uk>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author TheSFReader <TheSFReader@gmail.com>
  18. * @author Thomas Müller <thomas.mueller@tmit.eu>
  19. * @author Vincent Petry <pvince81@owncloud.com>
  20. * @author Xuanwo <xuanwo@yunify.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\Driver\Statement;
  39. use OCP\Files\Cache\ICache;
  40. use OCP\Files\Cache\ICacheEntry;
  41. use \OCP\Files\IMimeTypeLoader;
  42. use OCP\Files\Search\ISearchQuery;
  43. use OCP\IDBConnection;
  44. /**
  45. * Metadata cache for a storage
  46. *
  47. * The cache stores the metadata for all files and folders in a storage and is kept up to date trough the following mechanisms:
  48. *
  49. * - Scanner: scans the storage and updates the cache where needed
  50. * - Watcher: checks for changes made to the filesystem outside of the ownCloud instance and rescans files and folder when a change is detected
  51. * - Updater: listens to changes made to the filesystem inside of the ownCloud instance and updates the cache where needed
  52. * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
  53. */
  54. class Cache implements ICache {
  55. use MoveFromCacheTrait {
  56. MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
  57. }
  58. /**
  59. * @var array partial data for the cache
  60. */
  61. protected $partial = array();
  62. /**
  63. * @var string
  64. */
  65. protected $storageId;
  66. /**
  67. * @var Storage $storageCache
  68. */
  69. protected $storageCache;
  70. /** @var IMimeTypeLoader */
  71. protected $mimetypeLoader;
  72. /**
  73. * @var IDBConnection
  74. */
  75. protected $connection;
  76. /** @var QuerySearchHelper */
  77. protected $querySearchHelper;
  78. /**
  79. * @param \OC\Files\Storage\Storage|string $storage
  80. */
  81. public function __construct($storage) {
  82. if ($storage instanceof \OC\Files\Storage\Storage) {
  83. $this->storageId = $storage->getId();
  84. } else {
  85. $this->storageId = $storage;
  86. }
  87. if (strlen($this->storageId) > 64) {
  88. $this->storageId = md5($this->storageId);
  89. }
  90. $this->storageCache = new Storage($storage);
  91. $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
  92. $this->connection = \OC::$server->getDatabaseConnection();
  93. $this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
  94. }
  95. /**
  96. * Get the numeric storage id for this cache's storage
  97. *
  98. * @return int
  99. */
  100. public function getNumericStorageId() {
  101. return $this->storageCache->getNumericId();
  102. }
  103. /**
  104. * get the stored metadata of a file or folder
  105. *
  106. * @param string | int $file either the path of a file or folder or the file id for a file or folder
  107. * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
  108. */
  109. public function get($file) {
  110. if (is_string($file) or $file == '') {
  111. // normalize file
  112. $file = $this->normalize($file);
  113. $where = 'WHERE `storage` = ? AND `path_hash` = ?';
  114. $params = array($this->getNumericStorageId(), md5($file));
  115. } else { //file id
  116. $where = 'WHERE `fileid` = ?';
  117. $params = array($file);
  118. }
  119. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
  120. `storage_mtime`, `encrypted`, `etag`, `permissions`, `checksum`
  121. FROM `*PREFIX*filecache` ' . $where;
  122. $result = $this->connection->executeQuery($sql, $params);
  123. $data = $result->fetch();
  124. //FIXME hide this HACK in the next database layer, or just use doctrine and get rid of MDB2 and PDO
  125. //PDO returns false, MDB2 returns null, oracle always uses MDB2, so convert null to false
  126. if ($data === null) {
  127. $data = false;
  128. }
  129. //merge partial data
  130. if (!$data and is_string($file)) {
  131. if (isset($this->partial[$file])) {
  132. $data = $this->partial[$file];
  133. }
  134. return $data;
  135. } else {
  136. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  137. }
  138. }
  139. /**
  140. * Create a CacheEntry from database row
  141. *
  142. * @param array $data
  143. * @param IMimeTypeLoader $mimetypeLoader
  144. * @return CacheEntry
  145. */
  146. public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
  147. //fix types
  148. $data['fileid'] = (int)$data['fileid'];
  149. $data['parent'] = (int)$data['parent'];
  150. $data['size'] = 0 + $data['size'];
  151. $data['mtime'] = (int)$data['mtime'];
  152. $data['storage_mtime'] = (int)$data['storage_mtime'];
  153. $data['encryptedVersion'] = (int)$data['encrypted'];
  154. $data['encrypted'] = (bool)$data['encrypted'];
  155. $data['storage_id'] = $data['storage'];
  156. $data['storage'] = (int)$data['storage'];
  157. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  158. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  159. if ($data['storage_mtime'] == 0) {
  160. $data['storage_mtime'] = $data['mtime'];
  161. }
  162. $data['permissions'] = (int)$data['permissions'];
  163. return new CacheEntry($data);
  164. }
  165. /**
  166. * get the metadata of all files stored in $folder
  167. *
  168. * @param string $folder
  169. * @return ICacheEntry[]
  170. */
  171. public function getFolderContents($folder) {
  172. $fileId = $this->getId($folder);
  173. return $this->getFolderContentsById($fileId);
  174. }
  175. /**
  176. * get the metadata of all files stored in $folder
  177. *
  178. * @param int $fileId the file id of the folder
  179. * @return ICacheEntry[]
  180. */
  181. public function getFolderContentsById($fileId) {
  182. if ($fileId > -1) {
  183. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
  184. `storage_mtime`, `encrypted`, `etag`, `permissions`, `checksum`
  185. FROM `*PREFIX*filecache` WHERE `parent` = ? ORDER BY `name` ASC';
  186. $result = $this->connection->executeQuery($sql, [$fileId]);
  187. $files = $result->fetchAll();
  188. return array_map(function (array $data) {
  189. return self::cacheEntryFromData($data, $this->mimetypeLoader);;
  190. }, $files);
  191. } else {
  192. return array();
  193. }
  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'] = \OC_Util::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');
  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. */
  456. public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
  457. if ($sourceCache instanceof Cache) {
  458. // normalize source and target
  459. $sourcePath = $this->normalize($sourcePath);
  460. $targetPath = $this->normalize($targetPath);
  461. $sourceData = $sourceCache->get($sourcePath);
  462. $sourceId = $sourceData['fileid'];
  463. $newParentId = $this->getParentId($targetPath);
  464. list($sourceStorageId, $sourcePath) = $sourceCache->getMoveInfo($sourcePath);
  465. list($targetStorageId, $targetPath) = $this->getMoveInfo($targetPath);
  466. // sql for final update
  467. $moveSql = 'UPDATE `*PREFIX*filecache` SET `storage` = ?, `path` = ?, `path_hash` = ?, `name` = ?, `parent` =? WHERE `fileid` = ?';
  468. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  469. //find all child entries
  470. $sql = 'SELECT `path`, `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path` LIKE ?';
  471. $result = $this->connection->executeQuery($sql, [$sourceStorageId, $this->connection->escapeLikeParameter($sourcePath) . '/%']);
  472. $childEntries = $result->fetchAll();
  473. $sourceLength = strlen($sourcePath);
  474. $this->connection->beginTransaction();
  475. $query = $this->connection->prepare('UPDATE `*PREFIX*filecache` SET `storage` = ?, `path` = ?, `path_hash` = ? WHERE `fileid` = ?');
  476. foreach ($childEntries as $child) {
  477. $newTargetPath = $targetPath . substr($child['path'], $sourceLength);
  478. $query->execute([$targetStorageId, $newTargetPath, md5($newTargetPath), $child['fileid']]);
  479. }
  480. $this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), basename($targetPath), $newParentId, $sourceId]);
  481. $this->connection->commit();
  482. } else {
  483. $this->connection->executeQuery($moveSql, [$targetStorageId, $targetPath, md5($targetPath), \OC_Util::basename($targetPath), $newParentId, $sourceId]);
  484. }
  485. } else {
  486. $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
  487. }
  488. }
  489. /**
  490. * remove all entries for files that are stored on the storage from the cache
  491. */
  492. public function clear() {
  493. $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?';
  494. $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
  495. $sql = 'DELETE FROM `*PREFIX*storages` WHERE `id` = ?';
  496. $this->connection->executeQuery($sql, array($this->storageId));
  497. }
  498. /**
  499. * Get the scan status of a file
  500. *
  501. * - Cache::NOT_FOUND: File is not in the cache
  502. * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
  503. * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
  504. * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
  505. *
  506. * @param string $file
  507. *
  508. * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  509. */
  510. public function getStatus($file) {
  511. // normalize file
  512. $file = $this->normalize($file);
  513. $pathHash = md5($file);
  514. $sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
  515. $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId(), $pathHash));
  516. if ($row = $result->fetch()) {
  517. if ((int)$row['size'] === -1) {
  518. return self::SHALLOW;
  519. } else {
  520. return self::COMPLETE;
  521. }
  522. } else {
  523. if (isset($this->partial[$file])) {
  524. return self::PARTIAL;
  525. } else {
  526. return self::NOT_FOUND;
  527. }
  528. }
  529. }
  530. /**
  531. * search for files matching $pattern
  532. *
  533. * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
  534. * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
  535. */
  536. public function search($pattern) {
  537. // normalize pattern
  538. $pattern = $this->normalize($pattern);
  539. if ($pattern === '%%') {
  540. return [];
  541. }
  542. $sql = '
  543. SELECT `fileid`, `storage`, `path`, `parent`, `name`,
  544. `mimetype`, `storage_mtime`, `mimepart`, `size`, `mtime`,
  545. `encrypted`, `etag`, `permissions`, `checksum`
  546. FROM `*PREFIX*filecache`
  547. WHERE `storage` = ? AND `name` ILIKE ?';
  548. $result = $this->connection->executeQuery($sql,
  549. [$this->getNumericStorageId(), $pattern]
  550. );
  551. return $this->searchResultToCacheEntries($result);
  552. }
  553. /**
  554. * @param Statement $result
  555. * @return CacheEntry[]
  556. */
  557. private function searchResultToCacheEntries(Statement $result) {
  558. $files = $result->fetchAll();
  559. return array_map(function (array $data) {
  560. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  561. }, $files);
  562. }
  563. /**
  564. * search for files by mimetype
  565. *
  566. * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
  567. * where it will search for all mimetypes in the group ('image/*')
  568. * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
  569. */
  570. public function searchByMime($mimetype) {
  571. if (strpos($mimetype, '/')) {
  572. $where = '`mimetype` = ?';
  573. } else {
  574. $where = '`mimepart` = ?';
  575. }
  576. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `storage_mtime`, `mtime`, `encrypted`, `etag`, `permissions`, `checksum`
  577. FROM `*PREFIX*filecache` WHERE ' . $where . ' AND `storage` = ?';
  578. $mimetype = $this->mimetypeLoader->getId($mimetype);
  579. $result = $this->connection->executeQuery($sql, array($mimetype, $this->getNumericStorageId()));
  580. return $this->searchResultToCacheEntries($result);
  581. }
  582. public function searchQuery(ISearchQuery $searchQuery) {
  583. $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  584. $query = $builder->select(['fileid', 'storage', 'path', 'parent', 'name', 'mimetype', 'mimepart', 'size', 'mtime', 'storage_mtime', 'encrypted', 'etag', 'permissions', 'checksum'])
  585. ->from('filecache', 'file');
  586. $query->where($builder->expr()->eq('storage', $builder->createNamedParameter($this->getNumericStorageId())));
  587. if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
  588. $query
  589. ->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
  590. ->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
  591. $builder->expr()->eq('tagmap.type', 'tag.type'),
  592. $builder->expr()->eq('tagmap.categoryid', 'tag.id')
  593. ))
  594. ->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
  595. ->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($searchQuery->getUser()->getUID())));
  596. }
  597. $query->andWhere($this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation()));
  598. if ($searchQuery->getLimit()) {
  599. $query->setMaxResults($searchQuery->getLimit());
  600. }
  601. if ($searchQuery->getOffset()) {
  602. $query->setFirstResult($searchQuery->getOffset());
  603. }
  604. $result = $query->execute();
  605. return $this->searchResultToCacheEntries($result);
  606. }
  607. /**
  608. * Search for files by tag of a given users.
  609. *
  610. * Note that every user can tag files differently.
  611. *
  612. * @param string|int $tag name or tag id
  613. * @param string $userId owner of the tags
  614. * @return ICacheEntry[] file data
  615. */
  616. public function searchByTag($tag, $userId) {
  617. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, ' .
  618. '`mimetype`, `mimepart`, `size`, `mtime`, `storage_mtime`, ' .
  619. '`encrypted`, `etag`, `permissions`, `checksum` ' .
  620. 'FROM `*PREFIX*filecache` `file`, ' .
  621. '`*PREFIX*vcategory_to_object` `tagmap`, ' .
  622. '`*PREFIX*vcategory` `tag` ' .
  623. // JOIN filecache to vcategory_to_object
  624. 'WHERE `file`.`fileid` = `tagmap`.`objid` ' .
  625. // JOIN vcategory_to_object to vcategory
  626. 'AND `tagmap`.`type` = `tag`.`type` ' .
  627. 'AND `tagmap`.`categoryid` = `tag`.`id` ' .
  628. // conditions
  629. 'AND `file`.`storage` = ? ' .
  630. 'AND `tag`.`type` = \'files\' ' .
  631. 'AND `tag`.`uid` = ? ';
  632. if (is_int($tag)) {
  633. $sql .= 'AND `tag`.`id` = ? ';
  634. } else {
  635. $sql .= 'AND `tag`.`category` = ? ';
  636. }
  637. $result = $this->connection->executeQuery(
  638. $sql,
  639. [
  640. $this->getNumericStorageId(),
  641. $userId,
  642. $tag
  643. ]
  644. );
  645. $files = $result->fetchAll();
  646. return array_map(function (array $data) {
  647. return self::cacheEntryFromData($data, $this->mimetypeLoader);
  648. }, $files);
  649. }
  650. /**
  651. * Re-calculate the folder size and the size of all parent folders
  652. *
  653. * @param string|boolean $path
  654. * @param array $data (optional) meta data of the folder
  655. */
  656. public function correctFolderSize($path, $data = null) {
  657. $this->calculateFolderSize($path, $data);
  658. if ($path !== '') {
  659. $parent = dirname($path);
  660. if ($parent === '.' or $parent === '/') {
  661. $parent = '';
  662. }
  663. $this->correctFolderSize($parent);
  664. }
  665. }
  666. /**
  667. * calculate the size of a folder and set it in the cache
  668. *
  669. * @param string $path
  670. * @param array $entry (optional) meta data of the folder
  671. * @return int
  672. */
  673. public function calculateFolderSize($path, $entry = null) {
  674. $totalSize = 0;
  675. if (is_null($entry) or !isset($entry['fileid'])) {
  676. $entry = $this->get($path);
  677. }
  678. if (isset($entry['mimetype']) && $entry['mimetype'] === 'httpd/unix-directory') {
  679. $id = $entry['fileid'];
  680. $sql = 'SELECT SUM(`size`) AS f1, MIN(`size`) AS f2 ' .
  681. 'FROM `*PREFIX*filecache` ' .
  682. 'WHERE `parent` = ? AND `storage` = ?';
  683. $result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
  684. if ($row = $result->fetch()) {
  685. $result->closeCursor();
  686. list($sum, $min) = array_values($row);
  687. $sum = 0 + $sum;
  688. $min = 0 + $min;
  689. if ($min === -1) {
  690. $totalSize = $min;
  691. } else {
  692. $totalSize = $sum;
  693. }
  694. $update = array();
  695. if ($entry['size'] !== $totalSize) {
  696. $update['size'] = $totalSize;
  697. }
  698. if (count($update) > 0) {
  699. $this->update($id, $update);
  700. }
  701. } else {
  702. $result->closeCursor();
  703. }
  704. }
  705. return $totalSize;
  706. }
  707. /**
  708. * get all file ids on the files on the storage
  709. *
  710. * @return int[]
  711. */
  712. public function getAll() {
  713. $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ?';
  714. $result = $this->connection->executeQuery($sql, array($this->getNumericStorageId()));
  715. $ids = array();
  716. while ($row = $result->fetch()) {
  717. $ids[] = $row['fileid'];
  718. }
  719. return $ids;
  720. }
  721. /**
  722. * find a folder in the cache which has not been fully scanned
  723. *
  724. * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
  725. * use the one with the highest id gives the best result with the background scanner, since that is most
  726. * likely the folder where we stopped scanning previously
  727. *
  728. * @return string|bool the path of the folder or false when no folder matched
  729. */
  730. public function getIncomplete() {
  731. $query = $this->connection->prepare('SELECT `path` FROM `*PREFIX*filecache`'
  732. . ' WHERE `storage` = ? AND `size` = -1 ORDER BY `fileid` DESC', 1);
  733. $query->execute([$this->getNumericStorageId()]);
  734. if ($row = $query->fetch()) {
  735. return $row['path'];
  736. } else {
  737. return false;
  738. }
  739. }
  740. /**
  741. * get the path of a file on this storage by it's file id
  742. *
  743. * @param int $id the file id of the file or folder to search
  744. * @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
  745. */
  746. public function getPathById($id) {
  747. $sql = 'SELECT `path` FROM `*PREFIX*filecache` WHERE `fileid` = ? AND `storage` = ?';
  748. $result = $this->connection->executeQuery($sql, array($id, $this->getNumericStorageId()));
  749. if ($row = $result->fetch()) {
  750. // Oracle stores empty strings as null...
  751. if ($row['path'] === null) {
  752. return '';
  753. }
  754. return $row['path'];
  755. } else {
  756. return null;
  757. }
  758. }
  759. /**
  760. * get the storage id of the storage for a file and the internal path of the file
  761. * unlike getPathById this does not limit the search to files on this storage and
  762. * instead does a global search in the cache table
  763. *
  764. * @param int $id
  765. * @deprecated use getPathById() instead
  766. * @return array first element holding the storage id, second the path
  767. */
  768. static public function getById($id) {
  769. $connection = \OC::$server->getDatabaseConnection();
  770. $sql = 'SELECT `storage`, `path` FROM `*PREFIX*filecache` WHERE `fileid` = ?';
  771. $result = $connection->executeQuery($sql, array($id));
  772. if ($row = $result->fetch()) {
  773. $numericId = $row['storage'];
  774. $path = $row['path'];
  775. } else {
  776. return null;
  777. }
  778. if ($id = Storage::getStorageId($numericId)) {
  779. return array($id, $path);
  780. } else {
  781. return null;
  782. }
  783. }
  784. /**
  785. * normalize the given path
  786. *
  787. * @param string $path
  788. * @return string
  789. */
  790. public function normalize($path) {
  791. return trim(\OC_Util::normalizeUnicode($path), '/');
  792. }
  793. }