Completed
Pull Request — master (#32373)
by Piotr
09:13
created

Scanner::setCacheActive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Arthur Schiwon <[email protected]>
4
 * @author Björn Schießle <[email protected]>
5
 * @author Daniel Jagszent <[email protected]>
6
 * @author Jörn Friedrich Dreyer <[email protected]>
7
 * @author Lukas Reschke <[email protected]>
8
 * @author Martin Mattel <[email protected]>
9
 * @author Michael Gapczynski <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author Owen Winkler <[email protected]>
12
 * @author Robin Appelman <[email protected]>
13
 * @author Robin McCorkell <[email protected]>
14
 * @author Roeland Jago Douma <[email protected]>
15
 * @author Thomas Müller <[email protected]>
16
 * @author Vincent Petry <[email protected]>
17
 *
18
 * @copyright Copyright (c) 2018, ownCloud GmbH
19
 * @license AGPL-3.0
20
 *
21
 * This code is free software: you can redistribute it and/or modify
22
 * it under the terms of the GNU Affero General Public License, version 3,
23
 * as published by the Free Software Foundation.
24
 *
25
 * This program is distributed in the hope that it will be useful,
26
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28
 * GNU Affero General Public License for more details.
29
 *
30
 * You should have received a copy of the GNU Affero General Public License, version 3,
31
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
32
 *
33
 */
34
35
namespace OC\Files\Cache;
36
37
use OC\Files\Filesystem;
38
use OC\Hooks\BasicEmitter;
39
use OCA\Files_Sharing\ISharedStorage;
40
use OCP\Files\Cache\IScanner;
41
use OCP\Files\ForbiddenException;
42
use OCP\Files\IHomeStorage;
43
use OCP\Files\Storage\ILockingStorage;
44
use OCP\Lock\ILockingProvider;
45
46
/**
47
 * Class Scanner
48
 *
49
 * Hooks available in scope \OC\Files\Cache\Scanner:
50
 *  - scanFile(string $path, string $storageId)
51
 *  - scanFolder(string $path, string $storageId)
52
 *  - postScanFile(string $path, string $storageId)
53
 *  - postScanFolder(string $path, string $storageId)
54
 *
55
 * @package OC\Files\Cache
56
 */
57
class Scanner extends BasicEmitter implements IScanner {
58
	/**
59
	 * @var \OC\Files\Storage\Storage $storage
60
	 */
61
	protected $storage;
62
63
	/**
64
	 * @var string $storageId
65
	 */
66
	protected $storageId;
67
68
	/**
69
	 * @var \OC\Files\Cache\Cache $cache
70
	 */
71
	protected $cache;
72
73
	/**
74
	 * @var boolean $cacheActive If true, perform cache operations, if false, do not affect cache
75
	 */
76
	protected $cacheActive;
77
78
	/**
79
	 * @var bool $useTransactions whether to use transactions
80
	 */
81
	protected $useTransactions = true;
82
83
	/**
84
	 * @var \OCP\Lock\ILockingProvider
85
	 */
86
	protected $lockingProvider;
87
88
	public function __construct(\OC\Files\Storage\Storage $storage) {
89
		$this->storage = $storage;
90
		$this->storageId = $this->storage->getId();
91
		$this->cache = $storage->getCache();
92
		$this->cacheActive = !\OC::$server->getConfig()->getSystemValue('filesystem_cache_readonly', false);
93
		$this->lockingProvider = \OC::$server->getLockingProvider();
94
	}
95
96
	/**
97
	 * Whether to wrap the scanning of a folder in a database transaction
98
	 * On default transactions are used
99
	 *
100
	 * @param bool $useTransactions
101
	 */
102
	public function setUseTransactions($useTransactions) {
103
		$this->useTransactions = $useTransactions;
104
	}
105
106
	/**
107
	 * get all the metadata of a file or folder
108
	 * *
109
	 *
110
	 * @param string $path
111
	 * @return array an array of metadata of the file
112
	 * @throws \OCP\Files\StorageNotAvailableException
113
	 */
114
	protected function getData($path) {
115
		$data = $this->storage->getMetaData($path);
116
		if ($data === null) {
117
			\OCP\Util::writeLog(Scanner::class, "!!! Path '$path' is not accessible or present !!!", \OCP\Util::DEBUG);
118
			// Last Line of Defence against potential Metadata-loss
119
			if ($this->storage->instanceOfStorage(IHomeStorage::class) && !$this->storage->instanceOfStorage(ISharedStorage::class) && ($path === '' || $path === 'files')) {
120
				\OCP\Util::writeLog(Scanner::class, 'Missing important folder "' . $path . '" in home storage!!! - ' . $this->storageId, \OCP\Util::ERROR);
121
				throw new \OCP\Files\StorageNotAvailableException('Missing important folder "' . $path . '" in home storage - ' . $this->storageId);
122
			}
123
		}
124
		return $data;
125
	}
126
127
	/**
128
	 * scan a single file and store it in the cache
129
	 *
130
	 * @param string $file
131
	 * @param int $reuseExisting
132
	 * @param int $parentId
133
	 * @param array | null $cacheData existing data in the cache for the file to be scanned
134
	 * @param bool $lock set to false to disable getting an additional read lock during scanning
135
	 * @return array an array of metadata of the scanned file
136
	 * @throws \OCP\Files\StorageNotAvailableException
137
	 * @throws \OCP\Lock\LockedException
138
	 * @throws \OC\HintException
139
	 * @throws \OC\ServerNotAvailableException
140
	 */
141
	public function scanFile($file, $reuseExisting = 0, $parentId = -1, $cacheData = null, $lock = true) {
142
143
		// only proceed if $file is not a partial file nor a blacklisted file
144
		if (!self::isPartialFile($file) and !Filesystem::isFileBlacklisted($file)) {
145
146
			//acquire a lock
147 View Code Duplication
			if ($lock && $this->storage->instanceOfStorage(ILockingStorage::class)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
				$this->storage->acquireLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
149
			}
150
151
			try {
152
				$data = $this->getData($file);
153
				if ($data) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
154
155
					// pre-emit only if it was a file. By that we avoid counting/treating folders as files
156 View Code Duplication
					if ($data['mimetype'] !== 'httpd/unix-directory') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
157
						$this->emit('\OC\Files\Cache\Scanner', 'scanFile', [$file, $this->storageId]);
158
						\OC_Hook::emit('\OC\Files\Cache\Scanner', 'scan_file', ['path' => $file, 'storage' => $this->storageId]);
159
					}
160
161
					$parent = \dirname($file);
162
					if ($parent === '.' or $parent === '/') {
163
						$parent = '';
164
					}
165
					if ($parentId === -1) {
166
						$parentId = $this->cache->getId($parent);
167
					}
168
169
					// scan the parent if it's not in the cache (id -1) and the current file is not the root folder
170
					if ($file and $parentId === -1) {
171
						$parentData = $this->scanFile($parent);
172
						$parentId = $parentData['fileid'];
173
					}
174
					if ($parent) {
175
						$data['parent'] = $parentId;
176
					}
177
					if ($cacheData === null) {
178
						/** @var CacheEntry $cacheData */
179
						$cacheData = $this->cache->get($file);
180
					}
181
					if ($cacheData and $reuseExisting and isset($cacheData['fileid'])) {
182
						// prevent empty etag
183
						if (empty($cacheData['etag'])) {
184
							$etag = $data['etag'];
185
						} else {
186
							$etag = $cacheData['etag'];
187
						}
188
						$fileId = $cacheData['fileid'];
189
						$data['fileid'] = $fileId;
190
						// only reuse data if the file hasn't explicitly changed
191
						if (isset($data['storage_mtime'], $cacheData['storage_mtime']) && $data['storage_mtime'] === $cacheData['storage_mtime']) {
192
							$data['mtime'] = $cacheData['mtime'];
193
							if (($reuseExisting & self::REUSE_SIZE) && ($data['size'] === -1)) {
194
								$data['size'] = $cacheData['size'];
195
							}
196
							if ($reuseExisting & self::REUSE_ETAG) {
197
								$data['etag'] = $etag;
198
							}
199
						}
200
						// Only update metadata that has changed
201
						$newData = \array_diff_assoc($data, $cacheData->getData());
202
					} else {
203
						$newData = $data;
204
						$fileId = -1;
205
					}
206
					if (!empty($newData)) {
207
						// Only reset checksum on file change
208
						if ($fileId > 0 && !isset($newData['checksum'])) {
209
							foreach (['size', 'storage_mtime', 'mtime', 'etag'] as $dataKey) {
210
								if (isset($newData[$dataKey])) {
211
									$newData['checksum'] = '';
212
									break;
213
								}
214
							}
215
						}
216
217
						$data['fileid'] = $this->addToCache($file, $newData, $fileId);
218
					}
219
					if (isset($cacheData['size'])) {
220
						$data['oldSize'] = $cacheData['size'];
221
					} else {
222
						$data['oldSize'] = 0;
223
					}
224
225
					if (isset($cacheData['encrypted'])) {
226
						$data['encrypted'] = $cacheData['encrypted'];
227
					}
228
229
					// post-emit only if it was a file. By that we avoid counting/treating folders as files
230 View Code Duplication
					if ($data['mimetype'] !== 'httpd/unix-directory') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
231
						$this->emit('\OC\Files\Cache\Scanner', 'postScanFile', [$file, $this->storageId]);
232
						\OC_Hook::emit('\OC\Files\Cache\Scanner', 'post_scan_file', ['path' => $file, 'storage' => $this->storageId]);
233
					}
234
				} else {
235
					$this->removeFromCache($file);
236
				}
237
238
				if ($data && !isset($data['encrypted'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $data of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
239
					$data['encrypted'] = false;
240
				}
241
				return $data;
242
			} catch (ForbiddenException $e) {
243
				return null;
244
			} finally {
245
				//release the acquired lock
246 View Code Duplication
				if ($lock && $this->storage->instanceOfStorage(ILockingStorage::class)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
247
					$this->storage->releaseLock($file, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
248
				}
249
			}
250
		}
251
252
		return null;
253
	}
254
255
	protected function removeFromCache($path) {
256
		\OC_Hook::emit('Scanner', 'removeFromCache', ['file' => $path]);
257
		$this->emit('\OC\Files\Cache\Scanner', 'removeFromCache', [$path]);
258
		if ($this->cacheActive) {
259
			$this->cache->remove($path);
260
		}
261
	}
262
263
	/**
264
	 * @param string $path
265
	 * @param array $data
266
	 * @param int $fileId
267
	 * @return int the id of the added file
268
	 * @throws \OC\HintException
269
	 * @throws \OC\ServerNotAvailableException
270
	 */
271
	protected function addToCache($path, $data, $fileId = -1) {
272
		\OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
273
		$this->emit('\OC\Files\Cache\Scanner', 'addToCache', [$path, $this->storageId, $data]);
274 View Code Duplication
		if ($this->cacheActive) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
275
			if ($fileId !== -1) {
276
				$this->cache->update($fileId, $data);
277
				return $fileId;
278
			}
279
280
			return $this->cache->put($path, $data);
281
		}
282
283
		return -1;
284
	}
285
286
	/**
287
	 * @param string $path
288
	 * @param array $data
289
	 * @param int $fileId
290
	 * @throws \OC\HintException
291
	 * @throws \OC\ServerNotAvailableException
292
	 */
293
	protected function updateCache($path, $data, $fileId = -1) {
294
		\OC_Hook::emit('Scanner', 'addToCache', ['file' => $path, 'data' => $data]);
295
		$this->emit('\OC\Files\Cache\Scanner', 'updateCache', [$path, $this->storageId, $data]);
296 View Code Duplication
		if ($this->cacheActive) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
297
			if ($fileId !== -1) {
298
				$this->cache->update($fileId, $data);
299
			} else {
300
				$this->cache->put($path, $data);
301
			}
302
		}
303
	}
304
305
	/**
306
	 * scan a folder and all it's children
307
	 *
308
	 * @param string $path
309
	 * @param bool $recursive
310
	 * @param int $reuse
311
	 * @param bool $lock set to false to disable getting an additional read lock during scanning
312
	 * @return array an array of the meta data of the scanned file or folder
313
	 * @throws \OCP\Lock\LockedException
314
	 * @throws \OC\ServerNotAvailableException
315
	 */
316
	public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $lock = true) {
317 View Code Duplication
		if ($reuse === -1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
318
			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
319
		}
320 View Code Duplication
		if ($lock && $this->storage->instanceOfStorage(ILockingStorage::class)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
321
			$this->storage->acquireLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
322
			$this->storage->acquireLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
323
		}
324
		try {
325
			$data = $this->scanFile($path, $reuse, -1, null, $lock);
326
			if ($data and $data['mimetype'] === 'httpd/unix-directory') {
327
				$size = $this->scanChildren($path, $recursive, $reuse, $data['fileid'], $lock);
328
				$data['size'] = $size;
329
			}
330
		} finally {
331 View Code Duplication
			if ($lock && $this->storage->instanceOfStorage(ILockingStorage::class)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
332
				$this->storage->releaseLock($path, ILockingProvider::LOCK_SHARED, $this->lockingProvider);
333
				$this->storage->releaseLock('scanner::' . $path, ILockingProvider::LOCK_EXCLUSIVE, $this->lockingProvider);
334
			}
335
		}
336
		return $data;
337
	}
338
339
	/**
340
	 * Get the children currently in the cache
341
	 *
342
	 * @param int $folderId
343
	 * @return array[]
344
	 */
345
	protected function getExistingChildren($folderId) {
346
		$existingChildren = [];
347
		$children = $this->cache->getFolderContentsById($folderId);
348
		foreach ($children as $child) {
349
			$existingChildren[$child['name']] = $child;
350
		}
351
		return $existingChildren;
352
	}
353
354
	/**
355
	 * Get the children from the storage
356
	 *
357
	 * @param string $folder
358
	 * @return string[]
359
	 */
360
	protected function getNewChildren($folder) {
361
		$children = [];
362
		if ($dh = $this->storage->opendir($folder)) {
363
			if (\is_resource($dh)) {
364
				while (($file = \readdir($dh)) !== false) {
365
					if (!Filesystem::isIgnoredDir($file) && !Filesystem::isForbiddenFileOrDir($file)) {
366
						$children[] = \trim(\OC\Files\Filesystem::normalizePath($file), '/');
367
					}
368
				}
369
			}
370
		}
371
		return $children;
372
	}
373
374
	/**
375
	 * scan all the files and folders in a folder
376
	 *
377
	 * @param string $path
378
	 * @param bool $recursive
379
	 * @param int $reuse
380
	 * @param int $folderId id for the folder to be scanned
381
	 * @param bool $lock set to false to disable getting an additional read lock during scanning
382
	 * @return int the size of the scanned folder or -1 if the size is unknown at this stage
383
	 * @throws \OCP\Lock\LockedException
384
	 */
385
	protected function scanChildren($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $folderId = null, $lock = true) {
386 View Code Duplication
		if ($reuse === -1) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
387
			$reuse = ($recursive === self::SCAN_SHALLOW) ? self::REUSE_ETAG | self::REUSE_SIZE : self::REUSE_ETAG;
388
		}
389
		$this->emit('\OC\Files\Cache\Scanner', 'scanFolder', [$path, $this->storageId]);
390
		$size = 0;
391
		if ($folderId !== null) {
392
			$folderId = $this->cache->getId($path);
393
		}
394
		$childQueue = $this->handleChildren($path, $recursive, $reuse, $folderId, $lock, $size);
395
396
		foreach ($childQueue as $child => $childId) {
397
			$childSize = $this->scanChildren($child, $recursive, $reuse, $childId, $lock);
398
			if ($childSize === -1) {
399
				$size = -1;
400
			} elseif ($size !== -1) {
401
				$size += $childSize;
402
			}
403
		}
404
		if ($this->cacheActive) {
405
			$this->cache->update($folderId, ['size' => $size]);
406
		}
407
		$this->emit('\OC\Files\Cache\Scanner', 'postScanFolder', [$path, $this->storageId]);
408
		return $size;
409
	}
410
411
	private function handleChildren($path, $recursive, $reuse, $folderId, $lock, &$size) {
412
		// we put this in it's own function so it cleans up the memory before we start recursing
413
		$existingChildren = $this->getExistingChildren($folderId);
414
		$newChildren = $this->getNewChildren($path);
415
416
		if ($this->useTransactions) {
417
			\OC::$server->getDatabaseConnection()->beginTransaction();
418
		}
419
420
		$exceptionOccurred = false;
421
		$childQueue = [];
422
		foreach ($newChildren as $file) {
423
			$child = $path ? $path . '/' . $file : $file;
424
			try {
425
				$existingData = isset($existingChildren[$file]) ? $existingChildren[$file] : null;
426
				$data = $this->scanFile($child, $reuse, $folderId, $existingData, $lock);
427
				if ($data) {
428
					if ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE) {
429
						$childQueue[$child] = $data['fileid'];
430
					} elseif ($data['mimetype'] === 'httpd/unix-directory' and $recursive === self::SCAN_RECURSIVE_INCOMPLETE and $data['size'] === -1) {
431
						// only recurse into folders which aren't fully scanned
432
						$childQueue[$child] = $data['fileid'];
433
					} elseif ($data['size'] === -1) {
434
						$size = -1;
435
					} elseif ($size !== -1) {
436
						$size += $data['size'];
437
					}
438
				}
439
			} catch (\Doctrine\DBAL\DBALException $ex) {
440
				// might happen if inserting duplicate while a scanning
441
				// process is running in parallel
442
				// log and ignore
443
				\OCP\Util::writeLog('core', 'Exception while scanning file "' . $child . '": ' . $ex->getMessage(), \OCP\Util::DEBUG);
444
				$exceptionOccurred = true;
445
			} catch (\OCP\Lock\LockedException $e) {
446
				if ($this->useTransactions) {
447
					\OC::$server->getDatabaseConnection()->rollBack();
448
				}
449
				throw $e;
450
			}
451
		}
452
		$removedChildren = \array_diff(\array_keys($existingChildren), $newChildren);
453
		foreach ($removedChildren as $childName) {
454
			$child = $path ? $path . '/' . $childName : $childName;
455
			$this->removeFromCache($child);
456
		}
457
		if ($this->useTransactions) {
458
			\OC::$server->getDatabaseConnection()->commit();
459
		}
460
		if ($exceptionOccurred) {
461
			// It might happen that the parallel scan process has already
462
			// inserted mimetypes but those weren't available yet inside the transaction
463
			// To make sure to have the updated mime types in such cases,
464
			// we reload them here
465
			\OC::$server->getMimeTypeLoader()->reset();
466
		}
467
		return $childQueue;
468
	}
469
470
	/**
471
	 * check if the file should be ignored when scanning
472
	 * NOTE: files with a '.part' extension are ignored as well!
473
	 *       prevents unfinished put requests to be scanned
474
	 *
475
	 * @param string $file
476
	 * @return boolean
477
	 */
478
	public static function isPartialFile($file) {
479
		if (\pathinfo($file, PATHINFO_EXTENSION) === 'part') {
480
			return true;
481
		}
482
		if (\strpos($file, '.part/') !== false) {
483
			return true;
484
		}
485
486
		return false;
487
	}
488
489
	/**
490
	 * walk over any folders that are not fully scanned yet and scan them
491
	 */
492
	public function backgroundScan() {
493
		if (!$this->cache->inCache('')) {
494
			$this->runBackgroundScanJob(function () {
495
				$this->scan('', self::SCAN_RECURSIVE, self::REUSE_ETAG);
496
			}, '');
497
		} else {
498
			$lastPath = null;
499
			while (($path = $this->cache->getIncomplete()) !== false && $path !== $lastPath) {
500
				$this->runBackgroundScanJob(function () use ($path) {
501
					$this->scan($path, self::SCAN_RECURSIVE_INCOMPLETE, self::REUSE_ETAG | self::REUSE_SIZE);
0 ignored issues
show
Bug introduced by
It seems like $path defined by $this->cache->getIncomplete() on line 499 can also be of type boolean; however, OC\Files\Cache\Scanner::scan() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
Documentation introduced by
self::SCAN_RECURSIVE_INCOMPLETE is of type integer, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
502
				}, $path);
503
				// FIXME: this won't proceed with the next item, needs revamping of getIncomplete()
504
				// to make this possible
505
				$lastPath = $path;
506
			}
507
		}
508
	}
509
510
	private function runBackgroundScanJob(callable $callback, $path) {
511
		try {
512
			$callback();
513
			\OC_Hook::emit('Scanner', 'correctFolderSize', ['path' => $path]);
514
			if ($this->cacheActive && $this->cache instanceof Cache) {
515
				$this->cache->correctFolderSize($path);
516
			}
517
		} catch (\OCP\Files\StorageInvalidException $e) {
518
			// skip unavailable storages
519
		} catch (\OCP\Files\StorageNotAvailableException $e) {
520
			// skip unavailable storages
521
		} catch (\OCP\Files\ForbiddenException $e) {
522
			// skip forbidden storages
523
		} catch (\OCP\Lock\LockedException $e) {
524
			// skip unavailable storages
525
		}
526
	}
527
}
528