cache.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Björn Schießle <schiessle@owncloud.com>
  5. * @author Christopher Schäpers <kondou@ts.unde.re>
  6. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  7. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <icewind@owncloud.com>
  10. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  11. * @author Scrutinizer Auto-Fixer <auto-fixer@scrutinizer-ci.com>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @copyright Copyright (c) 2015, ownCloud, Inc.
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OC\Files\Cache;
  32. use OCP\Share_Backend_Collection;
  33. /**
  34. * Metadata cache for shared files
  35. *
  36. * don't use this class directly if you need to get metadata, use \OC\Files\Filesystem::getFileInfo instead
  37. */
  38. class Shared_Cache extends Cache {
  39. private $storage;
  40. private $files = array();
  41. /**
  42. * @param \OC\Files\Storage\Shared $storage
  43. */
  44. public function __construct($storage) {
  45. parent::__construct($storage);
  46. $this->storage = $storage;
  47. }
  48. /**
  49. * Get the source cache of a shared file or folder
  50. *
  51. * @param string $target Shared target file path
  52. * @return \OC\Files\Cache\Cache|false
  53. */
  54. private function getSourceCache($target) {
  55. if ($target === false || $target === $this->storage->getMountPoint()) {
  56. $target = '';
  57. }
  58. $source = \OC_Share_Backend_File::getSource($target, $this->storage->getShare());
  59. if (isset($source['path']) && isset($source['fileOwner'])) {
  60. \OC\Files\Filesystem::initMountPoints($source['fileOwner']);
  61. $mounts = \OC\Files\Filesystem::getMountByNumericId($source['storage']);
  62. if (is_array($mounts) and !empty($mounts)) {
  63. $fullPath = $mounts[0]->getMountPoint() . $source['path'];
  64. list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath($fullPath);
  65. if ($storage) {
  66. $this->files[$target] = $internalPath;
  67. $cache = $storage->getCache();
  68. $this->storageId = $storage->getId();
  69. $this->numericId = $cache->getNumericStorageId();
  70. return $cache;
  71. }
  72. }
  73. }
  74. return false;
  75. }
  76. public function getNumericStorageId() {
  77. if (isset($this->numericId)) {
  78. return $this->numericId;
  79. } else {
  80. return false;
  81. }
  82. }
  83. /**
  84. * get the stored metadata of a file or folder
  85. *
  86. * @param string|int $file
  87. * @return array|false
  88. */
  89. public function get($file) {
  90. $mimetypeLoader = \OC::$server->getMimeTypeLoader();
  91. if (is_string($file)) {
  92. $cache = $this->getSourceCache($file);
  93. if ($cache) {
  94. $data = $cache->get($this->files[$file]);
  95. if ($data) {
  96. $data['displayname_owner'] = \OC_User::getDisplayName($this->storage->getSharedFrom());
  97. $data['path'] = $file;
  98. if ($file === '') {
  99. $data['is_share_mount_point'] = true;
  100. }
  101. $data['uid_owner'] = $this->storage->getOwner($file);
  102. if (isset($data['permissions'])) {
  103. $data['permissions'] &= $this->storage->getPermissions($file);
  104. } else {
  105. $data['permissions'] = $this->storage->getPermissions($file);
  106. }
  107. }
  108. return $data;
  109. }
  110. } else {
  111. $sourceId = $file;
  112. // if we are at the root of the mount point we want to return the
  113. // cache information for the source item
  114. if (!is_int($sourceId) || $sourceId === 0) {
  115. $sourceId = $this->storage->getSourceId();
  116. }
  117. $query = \OCP\DB::prepare(
  118. 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`,'
  119. . ' `size`, `mtime`, `encrypted`, `storage_mtime`, `etag`, `permissions`'
  120. . ' FROM `*PREFIX*filecache` WHERE `fileid` = ?');
  121. $result = $query->execute(array($sourceId));
  122. $data = $result->fetchRow();
  123. $data['fileid'] = (int)$data['fileid'];
  124. $data['mtime'] = (int)$data['mtime'];
  125. $data['storage_mtime'] = (int)$data['storage_mtime'];
  126. $data['encrypted'] = (bool)$data['encrypted'];
  127. $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
  128. $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
  129. if ($data['storage_mtime'] === 0) {
  130. $data['storage_mtime'] = $data['mtime'];
  131. }
  132. $data['size'] = (int)$data['size'];
  133. $data['permissions'] = (int)$data['permissions'];
  134. if (!is_int($file) || $file === 0) {
  135. $data['path'] = '';
  136. $data['name'] = basename($this->storage->getMountPoint());
  137. $data['is_share_mount_point'] = true;
  138. }
  139. $data['permissions'] &= $this->storage->getPermissions('');
  140. return $data;
  141. }
  142. return false;
  143. }
  144. /**
  145. * get the metadata of all files stored in $folder
  146. *
  147. * @param string $folderId
  148. * @return array|false
  149. */
  150. public function getFolderContentsById($folderId) {
  151. $cache = $this->getSourceCache('');
  152. if ($cache) {
  153. $owner = $this->storage->getSharedFrom();
  154. $parentPath = $this->getPathById($folderId);
  155. if ($parentPath !== '') {
  156. $parentPath .= '/';
  157. }
  158. $sourceFolderContent = $cache->getFolderContentsById($folderId);
  159. foreach ($sourceFolderContent as &$c) {
  160. $c['path'] = ltrim($parentPath . $c['name'], '/');
  161. $c['uid_owner'] = $owner;
  162. $c['displayname_owner'] = \OC_User::getDisplayName($owner);
  163. $c['permissions'] = $c['permissions'] & $this->storage->getPermissions(false);
  164. }
  165. return $sourceFolderContent;
  166. }
  167. return false;
  168. }
  169. /**
  170. * store meta data for a file or folder
  171. *
  172. * @param string $file
  173. * @param array $data
  174. *
  175. * @return int|false file id
  176. */
  177. public function put($file, array $data) {
  178. $file = ($file === false) ? '' : $file;
  179. if ($cache = $this->getSourceCache($file)) {
  180. return $cache->put($this->files[$file], $data);
  181. }
  182. return false;
  183. }
  184. /**
  185. * get the file id for a file
  186. *
  187. * @param string $file
  188. * @return int
  189. */
  190. public function getId($file) {
  191. if ($file === false) {
  192. return $this->storage->getSourceId();
  193. }
  194. $cache = $this->getSourceCache($file);
  195. if ($cache) {
  196. return $cache->getId($this->files[$file]);
  197. }
  198. return -1;
  199. }
  200. /**
  201. * check if a file is available in the cache
  202. *
  203. * @param string $file
  204. * @return bool
  205. */
  206. public function inCache($file) {
  207. if ($file == '') {
  208. return true;
  209. }
  210. return parent::inCache($file);
  211. }
  212. /**
  213. * remove a file or folder from the cache
  214. *
  215. * @param string $file
  216. */
  217. public function remove($file) {
  218. $file = ($file === false) ? '' : $file;
  219. if ($cache = $this->getSourceCache($file)) {
  220. $cache->remove($this->files[$file]);
  221. }
  222. }
  223. /**
  224. * Get the storage id and path needed for a move
  225. *
  226. * @param string $path
  227. * @return array [$storageId, $internalPath]
  228. */
  229. protected function getMoveInfo($path) {
  230. $cache = $this->getSourceCache($path);
  231. $file = \OC_Share_Backend_File::getSource($path, $this->storage->getShare());
  232. return [$cache->getNumericStorageId(), $file['path']];
  233. }
  234. /**
  235. * remove all entries for files that are stored on the storage from the cache
  236. */
  237. public function clear() {
  238. // Not a valid action for Shared Cache
  239. }
  240. /**
  241. * @param string $file
  242. *
  243. * @return int, Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  244. */
  245. public function getStatus($file) {
  246. if ($file == '') {
  247. return self::COMPLETE;
  248. }
  249. if ($cache = $this->getSourceCache($file)) {
  250. return $cache->getStatus($this->files[$file]);
  251. }
  252. return self::NOT_FOUND;
  253. }
  254. /**
  255. * search for files matching $pattern
  256. *
  257. * @param string $pattern
  258. * @return array of file data
  259. */
  260. public function search($pattern) {
  261. $pattern = trim($pattern, '%');
  262. $normalizedPattern = $this->normalize($pattern);
  263. $result = array();
  264. $exploreDirs = array('');
  265. while (count($exploreDirs) > 0) {
  266. $dir = array_pop($exploreDirs);
  267. $files = $this->getFolderContents($dir);
  268. // no results?
  269. if (!$files) {
  270. // maybe it's a single shared file
  271. $file = $this->get('');
  272. if ($normalizedPattern === '' || stristr($file['name'], $normalizedPattern) !== false) {
  273. $result[] = $file;
  274. }
  275. continue;
  276. }
  277. foreach ($files as $file) {
  278. if ($normalizedPattern === '' || stristr($file['name'], $normalizedPattern) !== false) {
  279. $result[] = $file;
  280. }
  281. if ($file['mimetype'] === 'httpd/unix-directory') {
  282. $exploreDirs[] = ltrim($dir . '/' . $file['name'], '/');
  283. }
  284. }
  285. }
  286. return $result;
  287. }
  288. /**
  289. * search for files by mimetype
  290. *
  291. * @param string $mimetype
  292. * @return array
  293. */
  294. public function searchByMime($mimetype) {
  295. $mimepart = null;
  296. if (strpos($mimetype, '/') === false) {
  297. $mimepart = $mimetype;
  298. $mimetype = null;
  299. }
  300. $result = array();
  301. $exploreDirs = array('');
  302. while (count($exploreDirs) > 0) {
  303. $dir = array_pop($exploreDirs);
  304. $files = $this->getFolderContents($dir);
  305. // no results?
  306. if (!$files) {
  307. // maybe it's a single shared file
  308. $file = $this->get('');
  309. if (($mimepart && $file['mimepart'] === $mimepart) || ($mimetype && $file['mimetype'] === $mimetype)) {
  310. $result[] = $file;
  311. }
  312. continue;
  313. }
  314. foreach ($files as $file) {
  315. if ($file['mimetype'] === 'httpd/unix-directory') {
  316. $exploreDirs[] = ltrim($dir . '/' . $file['name'], '/');
  317. } else if (($mimepart && $file['mimepart'] === $mimepart) || ($mimetype && $file['mimetype'] === $mimetype)) {
  318. $result[] = $file;
  319. }
  320. }
  321. }
  322. return $result;
  323. }
  324. /**
  325. * Checks whether the given file has the given tag.
  326. *
  327. * @param \OCP\ITags $tagger
  328. * @param array $fileData file data
  329. * @param string $tag tag to check for
  330. * @return boolean true if the given file has the expected tag,
  331. * false otherwise
  332. */
  333. private function hasTag($tagger, $fileData, $tag) {
  334. $tags = $tagger->getTagsForObjects(array((int)$fileData['fileid']));
  335. return (!empty($tags) && in_array($tag, current($tags)));
  336. }
  337. /**
  338. * search for files by tag
  339. *
  340. * @param string|int $tag tag to search for
  341. * @param string $userId owner of the tags
  342. * @return array file data
  343. */
  344. public function searchByTag($tag, $userId) {
  345. // TODO: inject this
  346. $tagger = \OC::$server->getTagManager()->load('files', null, null, $userId);
  347. $result = array();
  348. $exploreDirs = array('');
  349. // check if root is tagged
  350. $file = $this->get('');
  351. if ($this->hasTag($tagger, $file, $tag)) {
  352. $result[] = $file;
  353. }
  354. // FIXME: this is so wrong and unefficient, need to replace with actual DB queries
  355. while (count($exploreDirs) > 0) {
  356. $dir = array_pop($exploreDirs);
  357. $files = $this->getFolderContents($dir);
  358. if (!$files) {
  359. continue;
  360. }
  361. foreach ($files as $file) {
  362. if ($this->hasTag($tagger, $file, $tag)) {
  363. $result[] = $file;
  364. }
  365. if ($file['mimetype'] === 'httpd/unix-directory') {
  366. $exploreDirs[] = ltrim($dir . '/' . $file['name'], '/');
  367. }
  368. }
  369. }
  370. return $result;
  371. }
  372. /**
  373. * update the folder size and the size of all parent folders
  374. *
  375. * @param string|boolean $path
  376. * @param array $data (optional) meta data of the folder
  377. */
  378. public function correctFolderSize($path, $data = null) {
  379. $this->calculateFolderSize($path, $data);
  380. if ($path !== '') {
  381. $parent = dirname($path);
  382. if ($parent === '.' or $parent === '/') {
  383. $parent = '';
  384. }
  385. $this->correctFolderSize($parent);
  386. } else {
  387. // bubble up to source cache
  388. $sourceCache = $this->getSourceCache($path);
  389. if (isset($this->files[$path])) {
  390. $parent = dirname($this->files[$path]);
  391. if ($sourceCache) {
  392. $sourceCache->correctFolderSize($parent);
  393. }
  394. }
  395. }
  396. }
  397. /**
  398. * get the size of a folder and set it in the cache
  399. *
  400. * @param string $path
  401. * @param array $entry (optional) meta data of the folder
  402. * @return int
  403. */
  404. public function calculateFolderSize($path, $entry = null) {
  405. $path = ($path === false) ? '' : $path;
  406. if ($cache = $this->getSourceCache($path)) {
  407. return $cache->calculateFolderSize($this->files[$path]);
  408. }
  409. return 0;
  410. }
  411. /**
  412. * get all file ids on the files on the storage
  413. *
  414. * @return int[]
  415. */
  416. public function getAll() {
  417. $ids = \OCP\Share::getItemsSharedWith('file', \OC_Share_Backend_File::FORMAT_GET_ALL);
  418. $folderBackend = \OCP\Share::getBackend('folder');
  419. if ($folderBackend instanceof Share_Backend_Collection) {
  420. foreach ($ids as $file) {
  421. /** @var $folderBackend Share_Backend_Collection */
  422. $children = $folderBackend->getChildren($file);
  423. foreach ($children as $child) {
  424. $ids[] = (int)$child['source'];
  425. }
  426. }
  427. }
  428. return $ids;
  429. }
  430. /**
  431. * find a folder in the cache which has not been fully scanned
  432. *
  433. * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
  434. * use the one with the highest id gives the best result with the background scanner, since that is most
  435. * likely the folder where we stopped scanning previously
  436. *
  437. * @return boolean the path of the folder or false when no folder matched
  438. */
  439. public function getIncomplete() {
  440. return false;
  441. }
  442. /**
  443. * get the path of a file on this storage relative to the mount point by it's id
  444. *
  445. * @param int $id
  446. * @param string $pathEnd (optional) used internally for recursive calls
  447. * @return string|null
  448. */
  449. public function getPathById($id, $pathEnd = '') {
  450. // direct shares are easy
  451. if ($id === $this->storage->getSourceId()) {
  452. return ltrim($pathEnd, '/');
  453. } else {
  454. // if the item is a direct share we try and get the path of the parent and append the name of the item to it
  455. list($parent, $name) = $this->getParentInfo($id);
  456. if ($parent > 0) {
  457. return $this->getPathById($parent, '/' . $name . $pathEnd);
  458. } else {
  459. return null;
  460. }
  461. }
  462. }
  463. /**
  464. * @param integer $id
  465. * @return array
  466. */
  467. private function getParentInfo($id) {
  468. $sql = 'SELECT `parent`, `name` FROM `*PREFIX*filecache` WHERE `fileid` = ?';
  469. $query = \OCP\DB::prepare($sql);
  470. $result = $query->execute(array($id));
  471. if ($row = $result->fetchRow()) {
  472. return array((int)$row['parent'], $row['name']);
  473. } else {
  474. return array(-1, '');
  475. }
  476. }
  477. }