PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/files/cache/cache.php

https://github.com/sezuan/core
PHP | 580 lines | 361 code | 60 blank | 159 comment | 63 complexity | fd71b66199001fbfcba66f858376f5ee MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception
  1. <?php
  2. /**
  3. * Copyright (c) 2012 Robin Appelman <icewind@owncloud.com>
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later.
  6. * See the COPYING-README file.
  7. */
  8. namespace OC\Files\Cache;
  9. /**
  10. * Metadata cache for the filesystem
  11. *
  12. * don't use this class directly if you need to get metadata, use \OC\Files\Filesystem::getFileInfo instead
  13. */
  14. class Cache {
  15. const NOT_FOUND = 0;
  16. const PARTIAL = 1; //only partial data available, file not cached in the database
  17. const SHALLOW = 2; //folder in cache, but not all child files are completely scanned
  18. const COMPLETE = 3;
  19. /**
  20. * @var array partial data for the cache
  21. */
  22. private $partial = array();
  23. /**
  24. * @var string
  25. */
  26. private $storageId;
  27. /**
  28. * @var Storage $storageCache
  29. */
  30. private $storageCache;
  31. private $mimetypeIds = array();
  32. private $mimetypes = array();
  33. /**
  34. * @param \OC\Files\Storage\Storage|string $storage
  35. */
  36. public function __construct($storage) {
  37. if ($storage instanceof \OC\Files\Storage\Storage) {
  38. $this->storageId = $storage->getId();
  39. } else {
  40. $this->storageId = $storage;
  41. }
  42. if (strlen($this->storageId) > 64) {
  43. $this->storageId = md5($this->storageId);
  44. }
  45. $this->storageCache = new Storage($storage);
  46. }
  47. public function getNumericStorageId() {
  48. return $this->storageCache->getNumericId();
  49. }
  50. /**
  51. * normalize mimetypes
  52. *
  53. * @param string $mime
  54. * @return int
  55. */
  56. public function getMimetypeId($mime) {
  57. if (!isset($this->mimetypeIds[$mime])) {
  58. $result = \OC_DB::executeAudited('SELECT `id` FROM `*PREFIX*mimetypes` WHERE `mimetype` = ?', array($mime));
  59. if ($row = $result->fetchRow()) {
  60. $this->mimetypeIds[$mime] = $row['id'];
  61. } else {
  62. $result = \OC_DB::executeAudited('INSERT INTO `*PREFIX*mimetypes`(`mimetype`) VALUES(?)', array($mime));
  63. $this->mimetypeIds[$mime] = \OC_DB::insertid('*PREFIX*mimetypes');
  64. }
  65. $this->mimetypes[$this->mimetypeIds[$mime]] = $mime;
  66. }
  67. return $this->mimetypeIds[$mime];
  68. }
  69. public function getMimetype($id) {
  70. if (!isset($this->mimetypes[$id])) {
  71. $sql = 'SELECT `mimetype` FROM `*PREFIX*mimetypes` WHERE `id` = ?';
  72. $result = \OC_DB::executeAudited($sql, array($id));
  73. if ($row = $result->fetchRow()) {
  74. $this->mimetypes[$id] = $row['mimetype'];
  75. } else {
  76. return null;
  77. }
  78. }
  79. return $this->mimetypes[$id];
  80. }
  81. /**
  82. * get the stored metadata of a file or folder
  83. *
  84. * @param string/int $file
  85. * @return array | false
  86. */
  87. public function get($file) {
  88. if (is_string($file) or $file == '') {
  89. // normalize file
  90. $file = $this->normalize($file);
  91. $where = 'WHERE `storage` = ? AND `path_hash` = ?';
  92. $params = array($this->getNumericStorageId(), md5($file));
  93. } else { //file id
  94. $where = 'WHERE `fileid` = ?';
  95. $params = array($file);
  96. }
  97. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
  98. `storage_mtime`, `encrypted`, `unencrypted_size`, `etag`
  99. FROM `*PREFIX*filecache` ' . $where;
  100. $result = \OC_DB::executeAudited($sql, $params);
  101. $data = $result->fetchRow();
  102. //FIXME hide this HACK in the next database layer, or just use doctrine and get rid of MDB2 and PDO
  103. //PDO returns false, MDB2 returns null, oracle always uses MDB2, so convert null to false
  104. if ($data === null) {
  105. $data = false;
  106. }
  107. //merge partial data
  108. if (!$data and is_string($file)) {
  109. if (isset($this->partial[$file])) {
  110. $data = $this->partial[$file];
  111. }
  112. } else {
  113. //fix types
  114. $data['fileid'] = (int)$data['fileid'];
  115. $data['size'] = (int)$data['size'];
  116. $data['mtime'] = (int)$data['mtime'];
  117. $data['encrypted'] = (bool)$data['encrypted'];
  118. $data['unencrypted_size'] = (int)$data['unencrypted_size'];
  119. $data['storage'] = $this->storageId;
  120. $data['mimetype'] = $this->getMimetype($data['mimetype']);
  121. $data['mimepart'] = $this->getMimetype($data['mimepart']);
  122. if ($data['storage_mtime'] == 0) {
  123. $data['storage_mtime'] = $data['mtime'];
  124. }
  125. }
  126. return $data;
  127. }
  128. /**
  129. * get the metadata of all files stored in $folder
  130. *
  131. * @param string $folder
  132. * @return array
  133. */
  134. public function getFolderContents($folder) {
  135. $fileId = $this->getId($folder);
  136. if ($fileId > -1) {
  137. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`,
  138. `storage_mtime`, `encrypted`, `unencrypted_size`, `etag`
  139. FROM `*PREFIX*filecache` WHERE `parent` = ? ORDER BY `name` ASC';
  140. $result = \OC_DB::executeAudited($sql,array($fileId));
  141. $files = $result->fetchAll();
  142. foreach ($files as &$file) {
  143. $file['mimetype'] = $this->getMimetype($file['mimetype']);
  144. $file['mimepart'] = $this->getMimetype($file['mimepart']);
  145. if ($file['storage_mtime'] == 0) {
  146. $file['storage_mtime'] = $file['mtime'];
  147. }
  148. }
  149. return $files;
  150. } else {
  151. return array();
  152. }
  153. }
  154. /**
  155. * store meta data for a file or folder
  156. *
  157. * @param string $file
  158. * @param array $data
  159. *
  160. * @return int file id
  161. */
  162. public function put($file, array $data) {
  163. if (($id = $this->getId($file)) > -1) {
  164. $this->update($id, $data);
  165. return $id;
  166. } else {
  167. // normalize file
  168. $file = $this->normalize($file);
  169. if (isset($this->partial[$file])) { //add any saved partial data
  170. $data = array_merge($this->partial[$file], $data);
  171. unset($this->partial[$file]);
  172. }
  173. $requiredFields = array('size', 'mtime', 'mimetype');
  174. foreach ($requiredFields as $field) {
  175. if (!isset($data[$field])) { //data not complete save as partial and return
  176. $this->partial[$file] = $data;
  177. return -1;
  178. }
  179. }
  180. $data['path'] = $file;
  181. $data['parent'] = $this->getParentId($file);
  182. $data['name'] = basename($file);
  183. $data['encrypted'] = isset($data['encrypted']) ? ((int)$data['encrypted']) : 0;
  184. list($queryParts, $params) = $this->buildParts($data);
  185. $queryParts[] = '`storage`';
  186. $params[] = $this->getNumericStorageId();
  187. $valuesPlaceholder = array_fill(0, count($queryParts), '?');
  188. $sql = 'INSERT INTO `*PREFIX*filecache` (' . implode(', ', $queryParts) . ')'
  189. . ' VALUES (' . implode(', ', $valuesPlaceholder) . ')';
  190. \OC_DB::executeAudited($sql, $params);
  191. return (int)\OC_DB::insertid('*PREFIX*filecache');
  192. }
  193. }
  194. /**
  195. * update the metadata in the cache
  196. *
  197. * @param int $id
  198. * @param array $data
  199. */
  200. public function update($id, array $data) {
  201. if(isset($data['path'])) {
  202. // normalize path
  203. $data['path'] = $this->normalize($data['path']);
  204. }
  205. if(isset($data['name'])) {
  206. // normalize path
  207. $data['name'] = $this->normalize($data['name']);
  208. }
  209. list($queryParts, $params) = $this->buildParts($data);
  210. $params[] = $id;
  211. $sql = 'UPDATE `*PREFIX*filecache` SET ' . implode(' = ?, ', $queryParts) . '=? WHERE `fileid` = ?';
  212. \OC_DB::executeAudited($sql, $params);
  213. }
  214. /**
  215. * extract query parts and params array from data array
  216. *
  217. * @param array $data
  218. * @return array
  219. */
  220. function buildParts(array $data) {
  221. $fields = array('path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted', 'unencrypted_size', 'etag');
  222. $params = array();
  223. $queryParts = array();
  224. foreach ($data as $name => $value) {
  225. if (array_search($name, $fields) !== false) {
  226. if ($name === 'path') {
  227. $params[] = md5($value);
  228. $queryParts[] = '`path_hash`';
  229. } elseif ($name === 'mimetype') {
  230. $params[] = $this->getMimetypeId(substr($value, 0, strpos($value, '/')));
  231. $queryParts[] = '`mimepart`';
  232. $value = $this->getMimetypeId($value);
  233. } elseif ($name === 'storage_mtime') {
  234. if (!isset($data['mtime'])) {
  235. $params[] = $value;
  236. $queryParts[] = '`mtime`';
  237. }
  238. }
  239. $params[] = $value;
  240. $queryParts[] = '`' . $name . '`';
  241. }
  242. }
  243. return array($queryParts, $params);
  244. }
  245. /**
  246. * get the file id for a file
  247. *
  248. * @param string $file
  249. * @return int
  250. */
  251. public function getId($file) {
  252. // normalize file
  253. $file = $this->normalize($file);
  254. $pathHash = md5($file);
  255. $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
  256. $result = \OC_DB::executeAudited($sql, array($this->getNumericStorageId(), $pathHash));
  257. if ($row = $result->fetchRow()) {
  258. return $row['fileid'];
  259. } else {
  260. return -1;
  261. }
  262. }
  263. /**
  264. * get the id of the parent folder of a file
  265. *
  266. * @param string $file
  267. * @return int
  268. */
  269. public function getParentId($file) {
  270. if ($file === '') {
  271. return -1;
  272. } else {
  273. $parent = dirname($file);
  274. if ($parent === '.') {
  275. $parent = '';
  276. }
  277. return $this->getId($parent);
  278. }
  279. }
  280. /**
  281. * check if a file is available in the cache
  282. *
  283. * @param string $file
  284. * @return bool
  285. */
  286. public function inCache($file) {
  287. return $this->getId($file) != -1;
  288. }
  289. /**
  290. * remove a file or folder from the cache
  291. *
  292. * @param string $file
  293. */
  294. public function remove($file) {
  295. $entry = $this->get($file);
  296. if ($entry['mimetype'] === 'httpd/unix-directory') {
  297. $children = $this->getFolderContents($file);
  298. foreach ($children as $child) {
  299. $this->remove($child['path']);
  300. }
  301. }
  302. $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `fileid` = ?';
  303. \OC_DB::executeAudited($sql, array($entry['fileid']));
  304. $permissionsCache = new Permissions($this->storageId);
  305. $permissionsCache->remove($entry['fileid']);
  306. }
  307. /**
  308. * Move a file or folder in the cache
  309. *
  310. * @param string $source
  311. * @param string $target
  312. */
  313. public function move($source, $target) {
  314. // normalize source and target
  315. $source = $this->normalize($source);
  316. $target = $this->normalize($target);
  317. $sourceData = $this->get($source);
  318. $sourceId = $sourceData['fileid'];
  319. $newParentId = $this->getParentId($target);
  320. if ($sourceData['mimetype'] === 'httpd/unix-directory') {
  321. //find all child entries
  322. $sql = 'SELECT `path`, `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path` LIKE ?';
  323. $result = \OC_DB::executeAudited($sql, array($this->getNumericStorageId(), $source . '/%'));
  324. $childEntries = $result->fetchAll();
  325. $sourceLength = strlen($source);
  326. $query = \OC_DB::prepare('UPDATE `*PREFIX*filecache` SET `path` = ?, `path_hash` = ? WHERE `fileid` = ?');
  327. foreach ($childEntries as $child) {
  328. $targetPath = $target . substr($child['path'], $sourceLength);
  329. \OC_DB::executeAudited($query, array($targetPath, md5($targetPath), $child['fileid']));
  330. }
  331. }
  332. $sql = 'UPDATE `*PREFIX*filecache` SET `path` = ?, `path_hash` = ?, `name` = ?, `parent` =? WHERE `fileid` = ?';
  333. \OC_DB::executeAudited($sql, array($target, md5($target), basename($target), $newParentId, $sourceId));
  334. }
  335. /**
  336. * remove all entries for files that are stored on the storage from the cache
  337. */
  338. public function clear() {
  339. $sql = 'DELETE FROM `*PREFIX*filecache` WHERE `storage` = ?';
  340. \OC_DB::executeAudited($sql, array($this->getNumericStorageId()));
  341. $sql = 'DELETE FROM `*PREFIX*storages` WHERE `id` = ?';
  342. \OC_DB::executeAudited($sql, array($this->storageId));
  343. }
  344. /**
  345. * @param string $file
  346. *
  347. * @return int, Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
  348. */
  349. public function getStatus($file) {
  350. // normalize file
  351. $file = $this->normalize($file);
  352. $pathHash = md5($file);
  353. $sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `storage` = ? AND `path_hash` = ?';
  354. $result = \OC_DB::executeAudited($sql, array($this->getNumericStorageId(), $pathHash));
  355. if ($row = $result->fetchRow()) {
  356. if ((int)$row['size'] === -1) {
  357. return self::SHALLOW;
  358. } else {
  359. return self::COMPLETE;
  360. }
  361. } else {
  362. if (isset($this->partial[$file])) {
  363. return self::PARTIAL;
  364. } else {
  365. return self::NOT_FOUND;
  366. }
  367. }
  368. }
  369. /**
  370. * search for files matching $pattern
  371. *
  372. * @param string $pattern
  373. * @return array of file data
  374. */
  375. public function search($pattern) {
  376. // normalize pattern
  377. $pattern = $this->normalize($pattern);
  378. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`, `encrypted`, `unencrypted_size`, `etag`
  379. FROM `*PREFIX*filecache` WHERE `name` LIKE ? AND `storage` = ?';
  380. $result = \OC_DB::executeAudited($sql, array($pattern, $this->getNumericStorageId()));
  381. $files = array();
  382. while ($row = $result->fetchRow()) {
  383. $row['mimetype'] = $this->getMimetype($row['mimetype']);
  384. $row['mimepart'] = $this->getMimetype($row['mimepart']);
  385. $files[] = $row;
  386. }
  387. return $files;
  388. }
  389. /**
  390. * search for files by mimetype
  391. *
  392. * @param string $mimetype
  393. * @return array
  394. */
  395. public function searchByMime($mimetype) {
  396. if (strpos($mimetype, '/')) {
  397. $where = '`mimetype` = ?';
  398. } else {
  399. $where = '`mimepart` = ?';
  400. }
  401. $sql = 'SELECT `fileid`, `storage`, `path`, `parent`, `name`, `mimetype`, `mimepart`, `size`, `mtime`, `encrypted`, `unencrypted_size`, `etag`
  402. FROM `*PREFIX*filecache` WHERE ' . $where . ' AND `storage` = ?';
  403. $mimetype = $this->getMimetypeId($mimetype);
  404. $result = \OC_DB::executeAudited($sql, array($mimetype, $this->getNumericStorageId()));
  405. $files = array();
  406. while ($row = $result->fetchRow()) {
  407. $row['mimetype'] = $this->getMimetype($row['mimetype']);
  408. $row['mimepart'] = $this->getMimetype($row['mimepart']);
  409. $files[] = $row;
  410. }
  411. return $files;
  412. }
  413. /**
  414. * update the folder size and the size of all parent folders
  415. *
  416. * @param $path
  417. */
  418. public function correctFolderSize($path) {
  419. $this->calculateFolderSize($path);
  420. if ($path !== '') {
  421. $parent = dirname($path);
  422. if ($parent === '.' or $parent === '/') {
  423. $parent = '';
  424. }
  425. $this->correctFolderSize($parent);
  426. }
  427. }
  428. /**
  429. * get the size of a folder and set it in the cache
  430. *
  431. * @param string $path
  432. * @return int
  433. */
  434. public function calculateFolderSize($path) {
  435. $id = $this->getId($path);
  436. if ($id === -1) {
  437. return 0;
  438. }
  439. $sql = 'SELECT `size` FROM `*PREFIX*filecache` WHERE `parent` = ? AND `storage` = ?';
  440. $result = \OC_DB::executeAudited($sql, array($id, $this->getNumericStorageId()));
  441. $totalSize = 0;
  442. $hasChilds = 0;
  443. while ($row = $result->fetchRow()) {
  444. $hasChilds = true;
  445. $size = (int)$row['size'];
  446. if ($size === -1) {
  447. $totalSize = -1;
  448. break;
  449. } else {
  450. $totalSize += $size;
  451. }
  452. }
  453. if ($hasChilds) {
  454. $this->update($id, array('size' => $totalSize));
  455. }
  456. return $totalSize;
  457. }
  458. /**
  459. * get all file ids on the files on the storage
  460. *
  461. * @return int[]
  462. */
  463. public function getAll() {
  464. $sql = 'SELECT `fileid` FROM `*PREFIX*filecache` WHERE `storage` = ?';
  465. $result = \OC_DB::executeAudited($sql, array($this->getNumericStorageId()));
  466. $ids = array();
  467. while ($row = $result->fetchRow()) {
  468. $ids[] = $row['fileid'];
  469. }
  470. return $ids;
  471. }
  472. /**
  473. * find a folder in the cache which has not been fully scanned
  474. *
  475. * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
  476. * use the one with the highest id gives the best result with the background scanner, since that is most
  477. * likely the folder where we stopped scanning previously
  478. *
  479. * @return string|bool the path of the folder or false when no folder matched
  480. */
  481. public function getIncomplete() {
  482. $query = \OC_DB::prepare('SELECT `path` FROM `*PREFIX*filecache`'
  483. . ' WHERE `storage` = ? AND `size` = -1 ORDER BY `fileid` DESC',1);
  484. $result = \OC_DB::executeAudited($query, array($this->getNumericStorageId()));
  485. if ($row = $result->fetchRow()) {
  486. return $row['path'];
  487. } else {
  488. return false;
  489. }
  490. }
  491. /**
  492. * get the storage id of the storage for a file and the internal path of the file
  493. *
  494. * @param int $id
  495. * @return array, first element holding the storage id, second the path
  496. */
  497. static public function getById($id) {
  498. $sql = 'SELECT `storage`, `path` FROM `*PREFIX*filecache` WHERE `fileid` = ?';
  499. $result = \OC_DB::executeAudited($sql, array($id));
  500. if ($row = $result->fetchRow()) {
  501. $numericId = $row['storage'];
  502. $path = $row['path'];
  503. } else {
  504. return null;
  505. }
  506. if ($id = Storage::getStorageId($numericId)) {
  507. return array($id, $path);
  508. } else {
  509. return null;
  510. }
  511. }
  512. /**
  513. * normalize the given path
  514. * @param $path
  515. * @return string
  516. */
  517. public function normalize($path) {
  518. return \OC_Util::normalizeUnicode($path);
  519. }
  520. }