Scanner.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Cache;
  8. use Doctrine\DBAL\Exception;
  9. use OC\Files\Storage\Wrapper\Encryption;
  10. use OC\Files\Storage\Wrapper\Jail;
  11. use OC\Hooks\BasicEmitter;
  12. use OC\SystemConfig;
  13. use OCP\Files\Cache\IScanner;
  14. use OCP\Files\ForbiddenException;
  15. use OCP\Files\NotFoundException;
  16. use OCP\Files\Storage\IReliableEtagStorage;
  17. use OCP\IDBConnection;
  18. use OCP\Lock\ILockingProvider;
  19. use Psr\Log\LoggerInterface;
  20. /**
  21. * Class Scanner
  22. *
  23. * Hooks available in scope \OC\Files\Cache\Scanner:
  24. * - scanFile(string $path, string $storageId)
  25. * - scanFolder(string $path, string $storageId)
  26. * - postScanFile(string $path, string $storageId)
  27. * - postScanFolder(string $path, string $storageId)
  28. *
  29. * @package OC\Files\Cache
  30. */
  31. class Scanner extends BasicEmitter implements IScanner {
  32. /**
  33. * @var \OC\Files\Storage\Storage $storage
  34. */
  35. protected $storage;
  36. /**
  37. * @var string $storageId
  38. */
  39. protected $storageId;
  40. /**
  41. * @var \OC\Files\Cache\Cache $cache
  42. */
  43. protected $cache;
  44. /**
  45. * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
  46. */
  47. protected $cacheActive;
  48. /**
  49. * @var bool $useTransactions whether to use transactions
  50. */
  51. protected $useTransactions = true;
  52. /**
  53. * @var \OCP\Lock\ILockingProvider
  54. */
  55. protected $lockingProvider;
  56. protected IDBConnection $connection;
  57. public function __construct(\OC\Files\Storage\Storage $storage) {
  58. $this->storage = $storage;
  59. $this->storageId = $this->storage->getId();
  60. $this->cache = $storage->getCache();
  61. /** @var SystemConfig $config */
  62. $config = \OC::$server->get(SystemConfig::class);
  63. $this->cacheActive = !$config->getValue('filesystem_cache_readonly', false);
  64. $this->useTransactions = !$config->getValue('filescanner_no_transactions', false);
  65. $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
  66. $this->connection = \OC::$server->get(IDBConnection::class);
  67. }
  68. /**
  69. * Whether to wrap the scanning of a folder in a database transaction
  70. * On default transactions are used
  71. *
  72. * @param bool $useTransactions
  73. */
  74. public function setUseTransactions($useTransactions) {
  75. $this->useTransactions = $useTransactions;
  76. }
  77. /**
  78. * get all the metadata of a file or folder
  79. * *
  80. *
  81. * @param string $path
  82. * @return array|null an array of metadata of the file
  83. */
  84. protected function getData($path) {
  85. $data = $this->storage->getMetaData($path);
  86. if (is_null($data)) {
  87. \OC::$server->get(LoggerInterface::class)->debug("!!! Path '$path' is not accessible or present !!!", ['app' => 'core']);
  88. }
  89. return $data;
  90. }
  91. /**
  92. * scan a single file and store it in the cache
  93. *
  94. * @param string $file
  95. * @param int $reuseExisting
  96. * @param int $parentId
  97. * @param array|null|false $cacheData existing data in the cache for the file to be scanned
  98. * @param bool $lock set to false to disable getting an additional read lock during scanning
  99. * @param null $data the metadata for the file, as returned by the storage
  100. * @return array|null an array of metadata of the scanned file
  101. * @throws \OCP\Lock\LockedException
  102. */
  103. public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true, $data = null) {
  104. if ($file !== '') {
  105. try {
  106. $this->storage->verifyPath(dirname($file), basename($file));
  107. } catch (\Exception $e) {
  108. return null;
  109. }
  110. }
  111. // only proceed if $file is not a partial file, blacklist is handled by the storage
  112. if (!self::isPartialFile($file)) {
  113. // acquire a lock
  114. if ($lock) {
  115. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  116. $this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  117. }
  118. }
  119. try {
  120. $data = $data ?? $this->getData($file);
  121. } catch (ForbiddenException $e) {
  122. if ($lock) {
  123. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  124. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  125. }
  126. }
  127. return null;
  128. }
  129. try {
  130. if ($data) {
  131. // pre-emit only if it was a file. By that we avoid counting/treating folders as files
  132. if ($data['mimetype'] !== 'httpd/unix-directory') {
  133. $this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]);
  134. \OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]);
  135. }
  136. $parent = dirname($file);
  137. if ($parent === '.' || $parent === '/') {
  138. $parent = '';
  139. }
  140. if ($parentId === -1) {
  141. $parentId = $this->cache->getParentId($file);
  142. }
  143. // scan the parent if it's not in the cache (id -1) and the current file is not the root folder
  144. if ($file && $parentId === -1) {
  145. $parentData = $this->scanFile($parent);
  146. if (!$parentData) {
  147. return null;
  148. }
  149. $parentId = $parentData['fileid'];
  150. }
  151. if ($parent) {
  152. $data['parent'] = $parentId;
  153. }
  154. if (is_null($cacheData)) {
  155. /** @var CacheEntry $cacheData */
  156. $cacheData = $this->cache->get($file);
  157. }
  158. if ($cacheData && $reuseExisting && isset($cacheData['fileid'])) {
  159. // prevent empty etag
  160. $etag = empty($cacheData['etag']) ? $data['etag'] : $cacheData['etag'];
  161. $fileId = $cacheData['fileid'];
  162. $data['fileid'] = $fileId;
  163. // only reuse data if the file hasn't explicitly changed
  164. $mtimeUnchanged = isset($data['storage_mtime']) && isset($cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime'];
  165. // if the folder is marked as unscanned, never reuse etags
  166. if ($mtimeUnchanged && $cacheData['size'] !== -1) {
  167. $data['mtime'] = $cacheData['mtime'];
  168. if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
  169. $data['size'] = $cacheData['size'];
  170. }
  171. if ($reuseExisting & self::REUSE_ETAG && !$this->storage->instanceOfStorage(IReliableEtagStorage::class)) {
  172. $data['etag'] = $etag;
  173. }
  174. }
  175. // we only updated unencrypted_size if it's already set
  176. if ($cacheData['unencrypted_size'] === 0) {
  177. unset($data['unencrypted_size']);
  178. }
  179. // Only update metadata that has changed
  180. // i.e. get all the values in $data that are not present in the cache already
  181. $newData = $this->array_diff_assoc_multi($data, $cacheData->getData());
  182. // make it known to the caller that etag has been changed and needs propagation
  183. if (isset($newData['etag'])) {
  184. $data['etag_changed'] = true;
  185. }
  186. } else {
  187. // we only updated unencrypted_size if it's already set
  188. unset($data['unencrypted_size']);
  189. $newData = $data;
  190. $fileId = -1;
  191. }
  192. if (!empty($newData)) {
  193. // Reset the checksum if the data has changed
  194. $newData['checksum'] = '';
  195. $newData['parent'] = $parentId;
  196. $data['fileid'] = $this->addToCache($file, $newData, $fileId);
  197. }
  198. $data['oldSize'] = ($cacheData && isset($cacheData['size'])) ? $cacheData['size'] : 0;
  199. if ($cacheData && isset($cacheData['encrypted'])) {
  200. $data['encrypted'] = $cacheData['encrypted'];
  201. }
  202. // post-emit only if it was a file. By that we avoid counting/treating folders as files
  203. if ($data['mimetype'] !== 'httpd/unix-directory') {
  204. $this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]);
  205. \OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]);
  206. }
  207. } else {
  208. $this->removeFromCache($file);
  209. }
  210. } catch (\Exception $e) {
  211. if ($lock) {
  212. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  213. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  214. }
  215. }
  216. throw $e;
  217. }
  218. // release the acquired lock
  219. if ($lock) {
  220. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  221. $this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  222. }
  223. }
  224. if ($data && !isset($data['encrypted'])) {
  225. $data['encrypted'] = false;
  226. }
  227. return $data;
  228. }
  229. return null;
  230. }
  231. protected function removeFromCache($path) {
  232. \OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]);
  233. $this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]);
  234. if ($this->cacheActive) {
  235. $this->cache->remove($path);
  236. }
  237. }
  238. /**
  239. * @param string $path
  240. * @param array $data
  241. * @param int $fileId
  242. * @return int the id of the added file
  243. */
  244. protected function addToCache($path, $data, $fileId = -1) {
  245. if (isset($data['scan_permissions'])) {
  246. $data['permissions'] = $data['scan_permissions'];
  247. }
  248. \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
  249. $this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data, $fileId]);
  250. if ($this->cacheActive) {
  251. if ($fileId !== -1) {
  252. $this->cache->update($fileId, $data);
  253. return $fileId;
  254. } else {
  255. return $this->cache->insert($path, $data);
  256. }
  257. } else {
  258. return -1;
  259. }
  260. }
  261. /**
  262. * @param string $path
  263. * @param array $data
  264. * @param int $fileId
  265. */
  266. protected function updateCache($path, $data, $fileId = -1) {
  267. \OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
  268. $this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]);
  269. if ($this->cacheActive) {
  270. if ($fileId !== -1) {
  271. $this->cache->update($fileId, $data);
  272. } else {
  273. $this->cache->put($path, $data);
  274. }
  275. }
  276. }
  277. /**
  278. * scan a folder and all it's children
  279. *
  280. * @param string $path
  281. * @param bool $recursive
  282. * @param int $reuse
  283. * @param bool $lock set to false to disable getting an additional read lock during scanning
  284. * @return array|null an array of the meta data of the scanned file or folder
  285. */
  286. public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
  287. if ($reuse === -1) {
  288. $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
  289. }
  290. if ($lock) {
  291. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  292. $this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
  293. $this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  294. }
  295. }
  296. try {
  297. try {
  298. $data = $this->scanFile($path, $reuse, -1, null, $lock);
  299. if ($data && $data['mimetype'] === 'httpd/unix-directory') {
  300. $size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock, $data['size']);
  301. $data['size'] = $size;
  302. }
  303. } catch (NotFoundException $e) {
  304. $this->removeFromCache($path);
  305. return null;
  306. }
  307. } finally {
  308. if ($lock) {
  309. if ($this->storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  310. $this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
  311. $this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
  312. }
  313. }
  314. }
  315. return $data;
  316. }
  317. /**
  318. * Compares $array1 against $array2 and returns all the values in $array1 that are not in $array2
  319. * Note this is a one-way check - i.e. we don't care about things that are in $array2 that aren't in $array1
  320. *
  321. * Supports multi-dimensional arrays
  322. * Also checks keys/indexes
  323. * Comparisons are strict just like array_diff_assoc
  324. * Order of keys/values does not matter
  325. *
  326. * @param array $array1
  327. * @param array $array2
  328. * @return array with the differences between $array1 and $array1
  329. * @throws \InvalidArgumentException if $array1 isn't an actual array
  330. *
  331. */
  332. protected function array_diff_assoc_multi(array $array1, array $array2) {
  333. $result = [];
  334. foreach ($array1 as $key => $value) {
  335. // if $array2 doesn't have the same key, that's a result
  336. if (!array_key_exists($key, $array2)) {
  337. $result[$key] = $value;
  338. continue;
  339. }
  340. // if $array2's value for the same key is different, that's a result
  341. if ($array2[$key] !== $value && !is_array($value)) {
  342. $result[$key] = $value;
  343. continue;
  344. }
  345. if (is_array($value)) {
  346. $nestedDiff = $this->array_diff_assoc_multi($value, $array2[$key]);
  347. if (!empty($nestedDiff)) {
  348. $result[$key] = $nestedDiff;
  349. continue;
  350. }
  351. }
  352. }
  353. return $result;
  354. }
  355. /**
  356. * Get the children currently in the cache
  357. *
  358. * @param int $folderId
  359. * @return array[]
  360. */
  361. protected function getExistingChildren($folderId) {
  362. $existingChildren = [];
  363. $children = $this->cache->getFolderContentsById($folderId);
  364. foreach ($children as $child) {
  365. $existingChildren[$child['name']] = $child;
  366. }
  367. return $existingChildren;
  368. }
  369. /**
  370. * scan all the files and folders in a folder
  371. *
  372. * @param string $path
  373. * @param bool|IScanner::SCAN_RECURSIVE_INCOMPLETE $recursive
  374. * @param int $reuse a combination of self::REUSE_*
  375. * @param int $folderId id for the folder to be scanned
  376. * @param bool $lock set to false to disable getting an additional read lock during scanning
  377. * @param int|float $oldSize the size of the folder before (re)scanning the children
  378. * @return int|float the size of the scanned folder or -1 if the size is unknown at this stage
  379. */
  380. protected function scanChildren(string $path, $recursive, int $reuse, int $folderId, bool $lock, int|float $oldSize, &$etagChanged = false) {
  381. if ($reuse === -1) {
  382. $reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
  383. }
  384. $this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]);
  385. $size = 0;
  386. $childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size, $etagChanged);
  387. foreach ($childQueue as $child => [$childId, $childSize]) {
  388. // "etag changed" propagates up, but not down, so we pass `false` to the children even if we already know that the etag of the current folder changed
  389. $childEtagChanged = false;
  390. $childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock, $childSize, $childEtagChanged);
  391. $etagChanged |= $childEtagChanged;
  392. if ($childSize === -1) {
  393. $size = -1;
  394. } elseif ($size !== -1) {
  395. $size += $childSize;
  396. }
  397. }
  398. // for encrypted storages, we trigger a regular folder size calculation instead of using the calculated size
  399. // to make sure we also updated the unencrypted-size where applicable
  400. if ($this->storage->instanceOfStorage(Encryption::class)) {
  401. $this->cache->calculateFolderSize($path);
  402. } else {
  403. if ($this->cacheActive) {
  404. $updatedData = [];
  405. if ($oldSize !== $size) {
  406. $updatedData['size'] = $size;
  407. }
  408. if ($etagChanged) {
  409. $updatedData['etag'] = uniqid();
  410. }
  411. if ($updatedData) {
  412. $this->cache->update($folderId, $updatedData);
  413. }
  414. }
  415. }
  416. $this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]);
  417. return $size;
  418. }
  419. /**
  420. * @param bool|IScanner::SCAN_RECURSIVE_INCOMPLETE $recursive
  421. */
  422. private function handleChildren(string $path, $recursive, int $reuse, int $folderId, bool $lock, int|float &$size, bool &$etagChanged): array {
  423. // we put this in it's own function so it cleans up the memory before we start recursing
  424. $existingChildren = $this->getExistingChildren($folderId);
  425. $newChildren = iterator_to_array($this->storage->getDirectoryContent($path));
  426. if (count($existingChildren) === 0 && count($newChildren) === 0) {
  427. // no need to do a transaction
  428. return [];
  429. }
  430. if ($this->useTransactions) {
  431. $this->connection->beginTransaction();
  432. }
  433. $exceptionOccurred = false;
  434. $childQueue = [];
  435. $newChildNames = [];
  436. foreach ($newChildren as $fileMeta) {
  437. $permissions = $fileMeta['scan_permissions'] ?? $fileMeta['permissions'];
  438. if ($permissions === 0) {
  439. continue;
  440. }
  441. $originalFile = $fileMeta['name'];
  442. $file = trim(\OC\Files\Filesystem::normalizePath($originalFile), '/');
  443. if (trim($originalFile, '/') !== $file) {
  444. // encoding mismatch, might require compatibility wrapper
  445. \OC::$server->get(LoggerInterface::class)->debug('Scanner: Skipping non-normalized file name "'. $originalFile . '" in path "' . $path . '".', ['app' => 'core']);
  446. $this->emit('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', [$path ? $path . '/' . $originalFile : $originalFile]);
  447. // skip this entry
  448. continue;
  449. }
  450. $newChildNames[] = $file;
  451. $child = $path ? $path . '/' . $file : $file;
  452. try {
  453. $existingData = $existingChildren[$file] ?? false;
  454. $data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock, $fileMeta);
  455. if ($data) {
  456. if ($data['mimetype'] === 'httpd/unix-directory' && $recursive === self::SCAN_RECURSIVE) {
  457. $childQueue[$child] = [$data['fileid'], $data['size']];
  458. } elseif ($data['mimetype'] === 'httpd/unix-directory' && $recursive === self::SCAN_RECURSIVE_INCOMPLETE && $data['size'] === -1) {
  459. // only recurse into folders which aren't fully scanned
  460. $childQueue[$child] = [$data['fileid'], $data['size']];
  461. } elseif ($data['size'] === -1) {
  462. $size = -1;
  463. } elseif ($size !== -1) {
  464. $size += $data['size'];
  465. }
  466. if (isset($data['etag_changed']) && $data['etag_changed']) {
  467. $etagChanged = true;
  468. }
  469. }
  470. } catch (Exception $ex) {
  471. // might happen if inserting duplicate while a scanning
  472. // process is running in parallel
  473. // log and ignore
  474. if ($this->useTransactions) {
  475. $this->connection->rollback();
  476. $this->connection->beginTransaction();
  477. }
  478. \OC::$server->get(LoggerInterface::class)->debug('Exception while scanning file "' . $child . '"', [
  479. 'app' => 'core',
  480. 'exception' => $ex,
  481. ]);
  482. $exceptionOccurred = true;
  483. } catch (\OCP\Lock\LockedException $e) {
  484. if ($this->useTransactions) {
  485. $this->connection->rollback();
  486. }
  487. throw $e;
  488. }
  489. }
  490. $removedChildren = \array_diff(array_keys($existingChildren), $newChildNames);
  491. foreach ($removedChildren as $childName) {
  492. $child = $path ? $path . '/' . $childName : $childName;
  493. $this->removeFromCache($child);
  494. }
  495. if ($this->useTransactions) {
  496. $this->connection->commit();
  497. }
  498. if ($exceptionOccurred) {
  499. // It might happen that the parallel scan process has already
  500. // inserted mimetypes but those weren't available yet inside the transaction
  501. // To make sure to have the updated mime types in such cases,
  502. // we reload them here
  503. \OC::$server->getMimeTypeLoader()->reset();
  504. }
  505. return $childQueue;
  506. }
  507. /**
  508. * check if the file should be ignored when scanning
  509. * NOTE: files with a '.part' extension are ignored as well!
  510. * prevents unfinished put requests to be scanned
  511. *
  512. * @param string $file
  513. * @return boolean
  514. */
  515. public static function isPartialFile($file) {
  516. if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
  517. return true;
  518. }
  519. if (str_contains($file, '.part/')) {
  520. return true;
  521. }
  522. return false;
  523. }
  524. /**
  525. * walk over any folders that are not fully scanned yet and scan them
  526. */
  527. public function backgroundScan() {
  528. if ($this->storage->instanceOfStorage(Jail::class)) {
  529. // for jail storage wrappers (shares, groupfolders) we run the background scan on the source storage
  530. // this is mainly done because the jail wrapper doesn't implement `getIncomplete` (because it would be inefficient).
  531. //
  532. // Running the scan on the source storage might scan more than "needed", but the unscanned files outside the jail will
  533. // have to be scanned at some point anyway.
  534. $unJailedScanner = $this->storage->getUnjailedStorage()->getScanner();
  535. $unJailedScanner->backgroundScan();
  536. } else {
  537. if (!$this->cache->inCache('')) {
  538. // if the storage isn't in the cache yet, just scan the root completely
  539. $this->runBackgroundScanJob(function () {
  540. $this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
  541. }, '');
  542. } else {
  543. $lastPath = null;
  544. // find any path marked as unscanned and run the scanner until no more paths are unscanned (or we get stuck)
  545. while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
  546. $this->runBackgroundScanJob(function () use ($path) {
  547. $this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
  548. }, $path);
  549. // FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
  550. // to make this possible
  551. $lastPath = $path;
  552. }
  553. }
  554. }
  555. }
  556. protected function runBackgroundScanJob(callable $callback, $path) {
  557. try {
  558. $callback();
  559. \OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]);
  560. if ($this->cacheActive && $this->cache instanceof Cache) {
  561. $this->cache->correctFolderSize($path, null, true);
  562. }
  563. } catch (\OCP\Files\StorageInvalidException $e) {
  564. // skip unavailable storages
  565. } catch (\OCP\Files\StorageNotAvailableException $e) {
  566. // skip unavailable storages
  567. } catch (\OCP\Files\ForbiddenException $e) {
  568. // skip forbidden storages
  569. } catch (\OCP\Lock\LockedException $e) {
  570. // skip unavailable storages
  571. }
  572. }
  573. /**
  574. * Set whether the cache is affected by scan operations
  575. *
  576. * @param boolean $active The active state of the cache
  577. */
  578. public function setCacheActive($active) {
  579. $this->cacheActive = $active;
  580. }
  581. }