Passed
Push — master ( 1eb084...1c074e )
by Morris
13:12 queued 11s
created
lib/private/Files/Cache/Cache.php 2 patches
Indentation   +1056 added lines, -1056 removed lines patch added patch discarded remove patch
@@ -67,1060 +67,1060 @@
 block discarded – undo
67 67
  * - ChangePropagator: updates the mtime and etags of parent folders whenever a change to the cache is made to the cache by the updater
68 68
  */
69 69
 class Cache implements ICache {
70
-	use MoveFromCacheTrait {
71
-		MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
72
-	}
73
-
74
-	/**
75
-	 * @var array partial data for the cache
76
-	 */
77
-	protected $partial = [];
78
-
79
-	/**
80
-	 * @var string
81
-	 */
82
-	protected $storageId;
83
-
84
-	private $storage;
85
-
86
-	/**
87
-	 * @var Storage $storageCache
88
-	 */
89
-	protected $storageCache;
90
-
91
-	/** @var IMimeTypeLoader */
92
-	protected $mimetypeLoader;
93
-
94
-	/**
95
-	 * @var IDBConnection
96
-	 */
97
-	protected $connection;
98
-
99
-	/**
100
-	 * @var IEventDispatcher
101
-	 */
102
-	protected $eventDispatcher;
103
-
104
-	/** @var QuerySearchHelper */
105
-	protected $querySearchHelper;
106
-
107
-	/**
108
-	 * @param IStorage $storage
109
-	 */
110
-	public function __construct(IStorage $storage) {
111
-		$this->storageId = $storage->getId();
112
-		$this->storage = $storage;
113
-		if (strlen($this->storageId) > 64) {
114
-			$this->storageId = md5($this->storageId);
115
-		}
116
-
117
-		$this->storageCache = new Storage($storage);
118
-		$this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
119
-		$this->connection = \OC::$server->getDatabaseConnection();
120
-		$this->eventDispatcher = \OC::$server->get(IEventDispatcher::class);
121
-		$this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
122
-	}
123
-
124
-	protected function getQueryBuilder() {
125
-		return new CacheQueryBuilder(
126
-			$this->connection,
127
-			\OC::$server->getSystemConfig(),
128
-			\OC::$server->getLogger(),
129
-			$this
130
-		);
131
-	}
132
-
133
-	/**
134
-	 * Get the numeric storage id for this cache's storage
135
-	 *
136
-	 * @return int
137
-	 */
138
-	public function getNumericStorageId() {
139
-		return $this->storageCache->getNumericId();
140
-	}
141
-
142
-	/**
143
-	 * get the stored metadata of a file or folder
144
-	 *
145
-	 * @param string | int $file either the path of a file or folder or the file id for a file or folder
146
-	 * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
147
-	 */
148
-	public function get($file) {
149
-		$query = $this->getQueryBuilder();
150
-		$query->selectFileCache();
151
-
152
-		if (is_string($file) or $file == '') {
153
-			// normalize file
154
-			$file = $this->normalize($file);
155
-
156
-			$query->whereStorageId()
157
-				->wherePath($file);
158
-		} else { //file id
159
-			$query->whereFileId($file);
160
-		}
161
-
162
-		$result = $query->execute();
163
-		$data = $result->fetch();
164
-		$result->closeCursor();
165
-
166
-		//merge partial data
167
-		if (!$data and is_string($file) and isset($this->partial[$file])) {
168
-			return $this->partial[$file];
169
-		} elseif (!$data) {
170
-			return $data;
171
-		} else {
172
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
173
-		}
174
-	}
175
-
176
-	/**
177
-	 * Create a CacheEntry from database row
178
-	 *
179
-	 * @param array $data
180
-	 * @param IMimeTypeLoader $mimetypeLoader
181
-	 * @return CacheEntry
182
-	 */
183
-	public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
184
-		//fix types
185
-		$data['fileid'] = (int)$data['fileid'];
186
-		$data['parent'] = (int)$data['parent'];
187
-		$data['size'] = 0 + $data['size'];
188
-		$data['mtime'] = (int)$data['mtime'];
189
-		$data['storage_mtime'] = (int)$data['storage_mtime'];
190
-		$data['encryptedVersion'] = (int)$data['encrypted'];
191
-		$data['encrypted'] = (bool)$data['encrypted'];
192
-		$data['storage_id'] = $data['storage'];
193
-		$data['storage'] = (int)$data['storage'];
194
-		$data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
195
-		$data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
196
-		if ($data['storage_mtime'] == 0) {
197
-			$data['storage_mtime'] = $data['mtime'];
198
-		}
199
-		$data['permissions'] = (int)$data['permissions'];
200
-		if (isset($data['creation_time'])) {
201
-			$data['creation_time'] = (int)$data['creation_time'];
202
-		}
203
-		if (isset($data['upload_time'])) {
204
-			$data['upload_time'] = (int)$data['upload_time'];
205
-		}
206
-		return new CacheEntry($data);
207
-	}
208
-
209
-	/**
210
-	 * get the metadata of all files stored in $folder
211
-	 *
212
-	 * @param string $folder
213
-	 * @return ICacheEntry[]
214
-	 */
215
-	public function getFolderContents($folder) {
216
-		$fileId = $this->getId($folder);
217
-		return $this->getFolderContentsById($fileId);
218
-	}
219
-
220
-	/**
221
-	 * get the metadata of all files stored in $folder
222
-	 *
223
-	 * @param int $fileId the file id of the folder
224
-	 * @return ICacheEntry[]
225
-	 */
226
-	public function getFolderContentsById($fileId) {
227
-		if ($fileId > -1) {
228
-			$query = $this->getQueryBuilder();
229
-			$query->selectFileCache()
230
-				->whereParent($fileId)
231
-				->orderBy('name', 'ASC');
232
-
233
-			$result = $query->execute();
234
-			$files = $result->fetchAll();
235
-			$result->closeCursor();
236
-
237
-			return array_map(function (array $data) {
238
-				return self::cacheEntryFromData($data, $this->mimetypeLoader);
239
-			}, $files);
240
-		}
241
-		return [];
242
-	}
243
-
244
-	/**
245
-	 * insert or update meta data for a file or folder
246
-	 *
247
-	 * @param string $file
248
-	 * @param array $data
249
-	 *
250
-	 * @return int file id
251
-	 * @throws \RuntimeException
252
-	 */
253
-	public function put($file, array $data) {
254
-		if (($id = $this->getId($file)) > -1) {
255
-			$this->update($id, $data);
256
-			return $id;
257
-		} else {
258
-			return $this->insert($file, $data);
259
-		}
260
-	}
261
-
262
-	/**
263
-	 * insert meta data for a new file or folder
264
-	 *
265
-	 * @param string $file
266
-	 * @param array $data
267
-	 *
268
-	 * @return int file id
269
-	 * @throws \RuntimeException
270
-	 */
271
-	public function insert($file, array $data) {
272
-		// normalize file
273
-		$file = $this->normalize($file);
274
-
275
-		if (isset($this->partial[$file])) { //add any saved partial data
276
-			$data = array_merge($this->partial[$file], $data);
277
-			unset($this->partial[$file]);
278
-		}
279
-
280
-		$requiredFields = ['size', 'mtime', 'mimetype'];
281
-		foreach ($requiredFields as $field) {
282
-			if (!isset($data[$field])) { //data not complete save as partial and return
283
-				$this->partial[$file] = $data;
284
-				return -1;
285
-			}
286
-		}
287
-
288
-		$data['path'] = $file;
289
-		if (!isset($data['parent'])) {
290
-			$data['parent'] = $this->getParentId($file);
291
-		}
292
-		$data['name'] = basename($file);
293
-
294
-		[$values, $extensionValues] = $this->normalizeData($data);
295
-		$storageId = $this->getNumericStorageId();
296
-		$values['storage'] = $storageId;
297
-
298
-		try {
299
-			$builder = $this->connection->getQueryBuilder();
300
-			$builder->insert('filecache');
301
-
302
-			foreach ($values as $column => $value) {
303
-				$builder->setValue($column, $builder->createNamedParameter($value));
304
-			}
305
-
306
-			if ($builder->execute()) {
307
-				$fileId = $builder->getLastInsertId();
308
-
309
-				if (count($extensionValues)) {
310
-					$query = $this->getQueryBuilder();
311
-					$query->insert('filecache_extended');
312
-
313
-					$query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
314
-					foreach ($extensionValues as $column => $value) {
315
-						$query->setValue($column, $query->createNamedParameter($value));
316
-					}
317
-					$query->execute();
318
-				}
319
-
320
-				$event = new CacheEntryInsertedEvent($this->storage, $file, $fileId, $storageId);
321
-				$this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
322
-				$this->eventDispatcher->dispatchTyped($event);
323
-				return $fileId;
324
-			}
325
-		} catch (UniqueConstraintViolationException $e) {
326
-			// entry exists already
327
-			if ($this->connection->inTransaction()) {
328
-				$this->connection->commit();
329
-				$this->connection->beginTransaction();
330
-			}
331
-		}
332
-
333
-		// The file was created in the mean time
334
-		if (($id = $this->getId($file)) > -1) {
335
-			$this->update($id, $data);
336
-			return $id;
337
-		} else {
338
-			throw new \RuntimeException('File entry could not be inserted but could also not be selected with getId() in order to perform an update. Please try again.');
339
-		}
340
-	}
341
-
342
-	/**
343
-	 * update the metadata of an existing file or folder in the cache
344
-	 *
345
-	 * @param int $id the fileid of the existing file or folder
346
-	 * @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
347
-	 */
348
-	public function update($id, array $data) {
349
-		if (isset($data['path'])) {
350
-			// normalize path
351
-			$data['path'] = $this->normalize($data['path']);
352
-		}
353
-
354
-		if (isset($data['name'])) {
355
-			// normalize path
356
-			$data['name'] = $this->normalize($data['name']);
357
-		}
358
-
359
-		[$values, $extensionValues] = $this->normalizeData($data);
360
-
361
-		if (count($values)) {
362
-			$query = $this->getQueryBuilder();
363
-
364
-			$query->update('filecache')
365
-				->whereFileId($id)
366
-				->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
367
-					return $query->expr()->orX(
368
-						$query->expr()->neq($key, $query->createNamedParameter($value)),
369
-						$query->expr()->isNull($key)
370
-					);
371
-				}, array_keys($values), array_values($values))));
372
-
373
-			foreach ($values as $key => $value) {
374
-				$query->set($key, $query->createNamedParameter($value));
375
-			}
376
-
377
-			$query->execute();
378
-		}
379
-
380
-		if (count($extensionValues)) {
381
-			try {
382
-				$query = $this->getQueryBuilder();
383
-				$query->insert('filecache_extended');
384
-
385
-				$query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
386
-				foreach ($extensionValues as $column => $value) {
387
-					$query->setValue($column, $query->createNamedParameter($value));
388
-				}
389
-
390
-				$query->execute();
391
-			} catch (UniqueConstraintViolationException $e) {
392
-				$query = $this->getQueryBuilder();
393
-				$query->update('filecache_extended')
394
-					->whereFileId($id)
395
-					->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
396
-						return $query->expr()->orX(
397
-							$query->expr()->neq($key, $query->createNamedParameter($value)),
398
-							$query->expr()->isNull($key)
399
-						);
400
-					}, array_keys($extensionValues), array_values($extensionValues))));
401
-
402
-				foreach ($extensionValues as $key => $value) {
403
-					$query->set($key, $query->createNamedParameter($value));
404
-				}
405
-
406
-				$query->execute();
407
-			}
408
-		}
409
-
410
-		$path = $this->getPathById($id);
411
-		// path can still be null if the file doesn't exist
412
-		if ($path !== null) {
413
-			$event = new CacheEntryUpdatedEvent($this->storage, $path, $id, $this->getNumericStorageId());
414
-			$this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
415
-			$this->eventDispatcher->dispatchTyped($event);
416
-		}
417
-	}
418
-
419
-	/**
420
-	 * extract query parts and params array from data array
421
-	 *
422
-	 * @param array $data
423
-	 * @return array
424
-	 */
425
-	protected function normalizeData(array $data): array {
426
-		$fields = [
427
-			'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
428
-			'etag', 'permissions', 'checksum', 'storage'];
429
-		$extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
430
-
431
-		$doNotCopyStorageMTime = false;
432
-		if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
433
-			// this horrific magic tells it to not copy storage_mtime to mtime
434
-			unset($data['mtime']);
435
-			$doNotCopyStorageMTime = true;
436
-		}
437
-
438
-		$params = [];
439
-		$extensionParams = [];
440
-		foreach ($data as $name => $value) {
441
-			if (array_search($name, $fields) !== false) {
442
-				if ($name === 'path') {
443
-					$params['path_hash'] = md5($value);
444
-				} elseif ($name === 'mimetype') {
445
-					$params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
446
-					$value = $this->mimetypeLoader->getId($value);
447
-				} elseif ($name === 'storage_mtime') {
448
-					if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
449
-						$params['mtime'] = $value;
450
-					}
451
-				} elseif ($name === 'encrypted') {
452
-					if (isset($data['encryptedVersion'])) {
453
-						$value = $data['encryptedVersion'];
454
-					} else {
455
-						// Boolean to integer conversion
456
-						$value = $value ? 1 : 0;
457
-					}
458
-				}
459
-				$params[$name] = $value;
460
-			}
461
-			if (array_search($name, $extensionFields) !== false) {
462
-				$extensionParams[$name] = $value;
463
-			}
464
-		}
465
-		return [$params, array_filter($extensionParams)];
466
-	}
467
-
468
-	/**
469
-	 * get the file id for a file
470
-	 *
471
-	 * 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
472
-	 *
473
-	 * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
474
-	 *
475
-	 * @param string $file
476
-	 * @return int
477
-	 */
478
-	public function getId($file) {
479
-		// normalize file
480
-		$file = $this->normalize($file);
481
-
482
-		$query = $this->getQueryBuilder();
483
-		$query->select('fileid')
484
-			->from('filecache')
485
-			->whereStorageId()
486
-			->wherePath($file);
487
-
488
-		$result = $query->execute();
489
-		$id = $result->fetchOne();
490
-		$result->closeCursor();
491
-
492
-		return $id === false ? -1 : (int)$id;
493
-	}
494
-
495
-	/**
496
-	 * get the id of the parent folder of a file
497
-	 *
498
-	 * @param string $file
499
-	 * @return int
500
-	 */
501
-	public function getParentId($file) {
502
-		if ($file === '') {
503
-			return -1;
504
-		} else {
505
-			$parent = $this->getParentPath($file);
506
-			return (int)$this->getId($parent);
507
-		}
508
-	}
509
-
510
-	private function getParentPath($path) {
511
-		$parent = dirname($path);
512
-		if ($parent === '.') {
513
-			$parent = '';
514
-		}
515
-		return $parent;
516
-	}
517
-
518
-	/**
519
-	 * check if a file is available in the cache
520
-	 *
521
-	 * @param string $file
522
-	 * @return bool
523
-	 */
524
-	public function inCache($file) {
525
-		return $this->getId($file) != -1;
526
-	}
527
-
528
-	/**
529
-	 * remove a file or folder from the cache
530
-	 *
531
-	 * when removing a folder from the cache all files and folders inside the folder will be removed as well
532
-	 *
533
-	 * @param string $file
534
-	 */
535
-	public function remove($file) {
536
-		$entry = $this->get($file);
537
-
538
-		if ($entry) {
539
-			$query = $this->getQueryBuilder();
540
-			$query->delete('filecache')
541
-				->whereFileId($entry->getId());
542
-			$query->execute();
543
-
544
-			$query = $this->getQueryBuilder();
545
-			$query->delete('filecache_extended')
546
-				->whereFileId($entry->getId());
547
-			$query->execute();
548
-
549
-			if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
550
-				$this->removeChildren($entry);
551
-			}
552
-
553
-			$this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $entry->getPath(), $entry->getId(), $this->getNumericStorageId()));
554
-		}
555
-	}
556
-
557
-	/**
558
-	 * Get all sub folders of a folder
559
-	 *
560
-	 * @param ICacheEntry $entry the cache entry of the folder to get the subfolders for
561
-	 * @return ICacheEntry[] the cache entries for the subfolders
562
-	 */
563
-	private function getSubFolders(ICacheEntry $entry) {
564
-		$children = $this->getFolderContentsById($entry->getId());
565
-		return array_filter($children, function ($child) {
566
-			return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
567
-		});
568
-	}
569
-
570
-	/**
571
-	 * Recursively remove all children of a folder
572
-	 *
573
-	 * @param ICacheEntry $entry the cache entry of the folder to remove the children of
574
-	 * @throws \OC\DatabaseException
575
-	 */
576
-	private function removeChildren(ICacheEntry $entry) {
577
-		$parentIds = [$entry->getId()];
578
-		$queue = [$entry->getId()];
579
-
580
-		// we walk depth first trough the file tree, removing all filecache_extended attributes while we walk
581
-		// and collecting all folder ids to later use to delete the filecache entries
582
-		while ($entryId = array_pop($queue)) {
583
-			$children = $this->getFolderContentsById($entryId);
584
-			$childIds = array_map(function (ICacheEntry $cacheEntry) {
585
-				return $cacheEntry->getId();
586
-			}, $children);
587
-
588
-			$query = $this->getQueryBuilder();
589
-			$query->delete('filecache_extended')
590
-				->where($query->expr()->in('fileid', $query->createNamedParameter($childIds, IQueryBuilder::PARAM_INT_ARRAY)));
591
-			$query->execute();
592
-
593
-			/** @var ICacheEntry[] $childFolders */
594
-			$childFolders = array_filter($children, function ($child) {
595
-				return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
596
-			});
597
-			foreach ($childFolders as $folder) {
598
-				$parentIds[] = $folder->getId();
599
-				$queue[] = $folder->getId();
600
-			}
601
-		}
602
-
603
-		$query = $this->getQueryBuilder();
604
-		$query->delete('filecache')
605
-			->whereParentIn($parentIds);
606
-		$query->execute();
607
-	}
608
-
609
-	/**
610
-	 * Move a file or folder in the cache
611
-	 *
612
-	 * @param string $source
613
-	 * @param string $target
614
-	 */
615
-	public function move($source, $target) {
616
-		$this->moveFromCache($this, $source, $target);
617
-	}
618
-
619
-	/**
620
-	 * Get the storage id and path needed for a move
621
-	 *
622
-	 * @param string $path
623
-	 * @return array [$storageId, $internalPath]
624
-	 */
625
-	protected function getMoveInfo($path) {
626
-		return [$this->getNumericStorageId(), $path];
627
-	}
628
-
629
-	/**
630
-	 * Move a file or folder in the cache
631
-	 *
632
-	 * @param ICache $sourceCache
633
-	 * @param string $sourcePath
634
-	 * @param string $targetPath
635
-	 * @throws \OC\DatabaseException
636
-	 * @throws \Exception if the given storages have an invalid id
637
-	 */
638
-	public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
639
-		if ($sourceCache instanceof Cache) {
640
-			// normalize source and target
641
-			$sourcePath = $this->normalize($sourcePath);
642
-			$targetPath = $this->normalize($targetPath);
643
-
644
-			$sourceData = $sourceCache->get($sourcePath);
645
-			$sourceId = $sourceData['fileid'];
646
-			$newParentId = $this->getParentId($targetPath);
647
-
648
-			[$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
649
-			[$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
650
-
651
-			if (is_null($sourceStorageId) || $sourceStorageId === false) {
652
-				throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
653
-			}
654
-			if (is_null($targetStorageId) || $targetStorageId === false) {
655
-				throw new \Exception('Invalid target storage id: ' . $targetStorageId);
656
-			}
657
-
658
-			$this->connection->beginTransaction();
659
-			if ($sourceData['mimetype'] === 'httpd/unix-directory') {
660
-				//update all child entries
661
-				$sourceLength = mb_strlen($sourcePath);
662
-				$query = $this->connection->getQueryBuilder();
663
-
664
-				$fun = $query->func();
665
-				$newPathFunction = $fun->concat(
666
-					$query->createNamedParameter($targetPath),
667
-					$fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
668
-				);
669
-				$query->update('filecache')
670
-					->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
671
-					->set('path_hash', $fun->md5($newPathFunction))
672
-					->set('path', $newPathFunction)
673
-					->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
674
-					->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
675
-
676
-				try {
677
-					$query->execute();
678
-				} catch (\OC\DatabaseException $e) {
679
-					$this->connection->rollBack();
680
-					throw $e;
681
-				}
682
-			}
683
-
684
-			$query = $this->getQueryBuilder();
685
-			$query->update('filecache')
686
-				->set('storage', $query->createNamedParameter($targetStorageId))
687
-				->set('path', $query->createNamedParameter($targetPath))
688
-				->set('path_hash', $query->createNamedParameter(md5($targetPath)))
689
-				->set('name', $query->createNamedParameter(basename($targetPath)))
690
-				->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
691
-				->whereFileId($sourceId);
692
-			$query->execute();
693
-
694
-			$this->connection->commit();
695
-
696
-			if ($sourceCache->getNumericStorageId() !== $this->getNumericStorageId()) {
697
-				$this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $sourcePath, $sourceId, $sourceCache->getNumericStorageId()));
698
-				$event = new CacheEntryInsertedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
699
-				$this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
700
-				$this->eventDispatcher->dispatchTyped($event);
701
-			} else {
702
-				$event = new CacheEntryUpdatedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
703
-				$this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
704
-				$this->eventDispatcher->dispatchTyped($event);
705
-			}
706
-		} else {
707
-			$this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * remove all entries for files that are stored on the storage from the cache
713
-	 */
714
-	public function clear() {
715
-		$query = $this->getQueryBuilder();
716
-		$query->delete('filecache')
717
-			->whereStorageId();
718
-		$query->execute();
719
-
720
-		$query = $this->connection->getQueryBuilder();
721
-		$query->delete('storages')
722
-			->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
723
-		$query->execute();
724
-	}
725
-
726
-	/**
727
-	 * Get the scan status of a file
728
-	 *
729
-	 * - Cache::NOT_FOUND: File is not in the cache
730
-	 * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
731
-	 * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
732
-	 * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
733
-	 *
734
-	 * @param string $file
735
-	 *
736
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
737
-	 */
738
-	public function getStatus($file) {
739
-		// normalize file
740
-		$file = $this->normalize($file);
741
-
742
-		$query = $this->getQueryBuilder();
743
-		$query->select('size')
744
-			->from('filecache')
745
-			->whereStorageId()
746
-			->wherePath($file);
747
-
748
-		$result = $query->execute();
749
-		$size = $result->fetchOne();
750
-		$result->closeCursor();
751
-
752
-		if ($size !== false) {
753
-			if ((int)$size === -1) {
754
-				return self::SHALLOW;
755
-			} else {
756
-				return self::COMPLETE;
757
-			}
758
-		} else {
759
-			if (isset($this->partial[$file])) {
760
-				return self::PARTIAL;
761
-			} else {
762
-				return self::NOT_FOUND;
763
-			}
764
-		}
765
-	}
766
-
767
-	/**
768
-	 * search for files matching $pattern
769
-	 *
770
-	 * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
771
-	 * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
772
-	 */
773
-	public function search($pattern) {
774
-		// normalize pattern
775
-		$pattern = $this->normalize($pattern);
776
-
777
-		if ($pattern === '%%') {
778
-			return [];
779
-		}
780
-
781
-		$query = $this->getQueryBuilder();
782
-		$query->selectFileCache()
783
-			->whereStorageId()
784
-			->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
785
-
786
-		$result = $query->execute();
787
-		$files = $result->fetchAll();
788
-		$result->closeCursor();
789
-
790
-		return array_map(function (array $data) {
791
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
792
-		}, $files);
793
-	}
794
-
795
-	/**
796
-	 * @param IResult $result
797
-	 * @return CacheEntry[]
798
-	 */
799
-	private function searchResultToCacheEntries(IResult $result): array {
800
-		$files = $result->fetchAll();
801
-
802
-		return array_map(function (array $data) {
803
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
804
-		}, $files);
805
-	}
806
-
807
-	/**
808
-	 * search for files by mimetype
809
-	 *
810
-	 * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
811
-	 *        where it will search for all mimetypes in the group ('image/*')
812
-	 * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
813
-	 */
814
-	public function searchByMime($mimetype) {
815
-		$mimeId = $this->mimetypeLoader->getId($mimetype);
816
-
817
-		$query = $this->getQueryBuilder();
818
-		$query->selectFileCache()
819
-			->whereStorageId();
820
-
821
-		if (strpos($mimetype, '/')) {
822
-			$query->andWhere($query->expr()->eq('mimetype', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
823
-		} else {
824
-			$query->andWhere($query->expr()->eq('mimepart', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
825
-		}
826
-
827
-		$result = $query->execute();
828
-		$files = $result->fetchAll();
829
-		$result->closeCursor();
830
-
831
-		return array_map(function (array $data) {
832
-			return self::cacheEntryFromData($data, $this->mimetypeLoader);
833
-		}, $files);
834
-	}
835
-
836
-	public function searchQuery(ISearchQuery $searchQuery) {
837
-		$builder = $this->getQueryBuilder();
838
-
839
-		$query = $builder->selectFileCache('file');
840
-
841
-		$query->whereStorageId();
842
-
843
-		if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
844
-			$user = $searchQuery->getUser();
845
-			if ($user === null) {
846
-				throw new \InvalidArgumentException("Searching by tag requires the user to be set in the query");
847
-			}
848
-			$query
849
-				->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
850
-				->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
851
-					$builder->expr()->eq('tagmap.type', 'tag.type'),
852
-					$builder->expr()->eq('tagmap.categoryid', 'tag.id')
853
-				))
854
-				->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
855
-				->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($user->getUID())));
856
-		}
857
-
858
-		$searchExpr = $this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation());
859
-		if ($searchExpr) {
860
-			$query->andWhere($searchExpr);
861
-		}
862
-
863
-		if ($searchQuery->limitToHome() && ($this instanceof HomeCache)) {
864
-			$query->andWhere($builder->expr()->like('path', $query->expr()->literal('files/%')));
865
-		}
866
-
867
-		$this->querySearchHelper->addSearchOrdersToQuery($query, $searchQuery->getOrder());
868
-
869
-		if ($searchQuery->getLimit()) {
870
-			$query->setMaxResults($searchQuery->getLimit());
871
-		}
872
-		if ($searchQuery->getOffset()) {
873
-			$query->setFirstResult($searchQuery->getOffset());
874
-		}
875
-
876
-		$result = $query->execute();
877
-		$cacheEntries = $this->searchResultToCacheEntries($result);
878
-		$result->closeCursor();
879
-		return $cacheEntries;
880
-	}
881
-
882
-	/**
883
-	 * Re-calculate the folder size and the size of all parent folders
884
-	 *
885
-	 * @param string|boolean $path
886
-	 * @param array $data (optional) meta data of the folder
887
-	 */
888
-	public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
889
-		$this->calculateFolderSize($path, $data);
890
-		if ($path !== '') {
891
-			$parent = dirname($path);
892
-			if ($parent === '.' or $parent === '/') {
893
-				$parent = '';
894
-			}
895
-			if ($isBackgroundScan) {
896
-				$parentData = $this->get($parent);
897
-				if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
898
-					$this->correctFolderSize($parent, $parentData, $isBackgroundScan);
899
-				}
900
-			} else {
901
-				$this->correctFolderSize($parent);
902
-			}
903
-		}
904
-	}
905
-
906
-	/**
907
-	 * get the incomplete count that shares parent $folder
908
-	 *
909
-	 * @param int $fileId the file id of the folder
910
-	 * @return int
911
-	 */
912
-	public function getIncompleteChildrenCount($fileId) {
913
-		if ($fileId > -1) {
914
-			$query = $this->getQueryBuilder();
915
-			$query->select($query->func()->count())
916
-				->from('filecache')
917
-				->whereParent($fileId)
918
-				->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
919
-
920
-			$result = $query->execute();
921
-			$size = (int)$result->fetchOne();
922
-			$result->closeCursor();
923
-
924
-			return $size;
925
-		}
926
-		return -1;
927
-	}
928
-
929
-	/**
930
-	 * calculate the size of a folder and set it in the cache
931
-	 *
932
-	 * @param string $path
933
-	 * @param array $entry (optional) meta data of the folder
934
-	 * @return int
935
-	 */
936
-	public function calculateFolderSize($path, $entry = null) {
937
-		$totalSize = 0;
938
-		if (is_null($entry) or !isset($entry['fileid'])) {
939
-			$entry = $this->get($path);
940
-		}
941
-		if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
942
-			$id = $entry['fileid'];
943
-
944
-			$query = $this->getQueryBuilder();
945
-			$query->selectAlias($query->func()->sum('size'), 'f1')
946
-				->selectAlias($query->func()->min('size'), 'f2')
947
-				->from('filecache')
948
-				->whereStorageId()
949
-				->whereParent($id);
950
-
951
-			$result = $query->execute();
952
-			$row = $result->fetch();
953
-			$result->closeCursor();
954
-
955
-			if ($row) {
956
-				[$sum, $min] = array_values($row);
957
-				$sum = 0 + $sum;
958
-				$min = 0 + $min;
959
-				if ($min === -1) {
960
-					$totalSize = $min;
961
-				} else {
962
-					$totalSize = $sum;
963
-				}
964
-				if ($entry['size'] !== $totalSize) {
965
-					$this->update($id, ['size' => $totalSize]);
966
-				}
967
-			}
968
-		}
969
-		return $totalSize;
970
-	}
971
-
972
-	/**
973
-	 * get all file ids on the files on the storage
974
-	 *
975
-	 * @return int[]
976
-	 */
977
-	public function getAll() {
978
-		$query = $this->getQueryBuilder();
979
-		$query->select('fileid')
980
-			->from('filecache')
981
-			->whereStorageId();
982
-
983
-		$result = $query->execute();
984
-		$files = $result->fetchAll(\PDO::FETCH_COLUMN);
985
-		$result->closeCursor();
986
-
987
-		return array_map(function ($id) {
988
-			return (int)$id;
989
-		}, $files);
990
-	}
991
-
992
-	/**
993
-	 * find a folder in the cache which has not been fully scanned
994
-	 *
995
-	 * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
996
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
997
-	 * likely the folder where we stopped scanning previously
998
-	 *
999
-	 * @return string|bool the path of the folder or false when no folder matched
1000
-	 */
1001
-	public function getIncomplete() {
1002
-		$query = $this->getQueryBuilder();
1003
-		$query->select('path')
1004
-			->from('filecache')
1005
-			->whereStorageId()
1006
-			->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
1007
-			->orderBy('fileid', 'DESC')
1008
-			->setMaxResults(1);
1009
-
1010
-		$result = $query->execute();
1011
-		$path = $result->fetchOne();
1012
-		$result->closeCursor();
1013
-
1014
-		return $path;
1015
-	}
1016
-
1017
-	/**
1018
-	 * get the path of a file on this storage by it's file id
1019
-	 *
1020
-	 * @param int $id the file id of the file or folder to search
1021
-	 * @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
1022
-	 */
1023
-	public function getPathById($id) {
1024
-		$query = $this->getQueryBuilder();
1025
-		$query->select('path')
1026
-			->from('filecache')
1027
-			->whereStorageId()
1028
-			->whereFileId($id);
1029
-
1030
-		$result = $query->execute();
1031
-		$path = $result->fetchOne();
1032
-		$result->closeCursor();
1033
-
1034
-		if ($path === false) {
1035
-			return null;
1036
-		}
1037
-
1038
-		return (string)$path;
1039
-	}
1040
-
1041
-	/**
1042
-	 * get the storage id of the storage for a file and the internal path of the file
1043
-	 * unlike getPathById this does not limit the search to files on this storage and
1044
-	 * instead does a global search in the cache table
1045
-	 *
1046
-	 * @param int $id
1047
-	 * @return array first element holding the storage id, second the path
1048
-	 * @deprecated use getPathById() instead
1049
-	 */
1050
-	public static function getById($id) {
1051
-		$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
1052
-		$query->select('path', 'storage')
1053
-			->from('filecache')
1054
-			->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
1055
-
1056
-		$result = $query->execute();
1057
-		$row = $result->fetch();
1058
-		$result->closeCursor();
1059
-
1060
-		if ($row) {
1061
-			$numericId = $row['storage'];
1062
-			$path = $row['path'];
1063
-		} else {
1064
-			return null;
1065
-		}
1066
-
1067
-		if ($id = Storage::getStorageId($numericId)) {
1068
-			return [$id, $path];
1069
-		} else {
1070
-			return null;
1071
-		}
1072
-	}
1073
-
1074
-	/**
1075
-	 * normalize the given path
1076
-	 *
1077
-	 * @param string $path
1078
-	 * @return string
1079
-	 */
1080
-	public function normalize($path) {
1081
-		return trim(\OC_Util::normalizeUnicode($path), '/');
1082
-	}
1083
-
1084
-	/**
1085
-	 * Copy a file or folder in the cache
1086
-	 *
1087
-	 * @param ICache $sourceCache
1088
-	 * @param ICacheEntry $sourceEntry
1089
-	 * @param string $targetPath
1090
-	 * @return int fileid of copied entry
1091
-	 */
1092
-	public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int {
1093
-		if ($sourceEntry->getId() < 0) {
1094
-			throw new \RuntimeException("Invalid source cache entry on copyFromCache");
1095
-		}
1096
-		$data = $this->cacheEntryToArray($sourceEntry);
1097
-		$fileId = $this->put($targetPath, $data);
1098
-		if ($fileId <= 0) {
1099
-			throw new \RuntimeException("Failed to copy to " . $targetPath . " from cache with source data " . json_encode($data) . " ");
1100
-		}
1101
-		if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
1102
-			$folderContent = $sourceCache->getFolderContentsById($sourceEntry->getId());
1103
-			foreach ($folderContent as $subEntry) {
1104
-				$subTargetPath = $targetPath . '/' . $subEntry->getName();
1105
-				$this->copyFromCache($sourceCache, $subEntry, $subTargetPath);
1106
-			}
1107
-		}
1108
-		return $fileId;
1109
-	}
1110
-
1111
-	private function cacheEntryToArray(ICacheEntry $entry): array {
1112
-		return [
1113
-			'size' => $entry->getSize(),
1114
-			'mtime' => $entry->getMTime(),
1115
-			'storage_mtime' => $entry->getStorageMTime(),
1116
-			'mimetype' => $entry->getMimeType(),
1117
-			'mimepart' => $entry->getMimePart(),
1118
-			'etag' => $entry->getEtag(),
1119
-			'permissions' => $entry->getPermissions(),
1120
-			'encrypted' => $entry->isEncrypted(),
1121
-			'creation_time' => $entry->getCreationTime(),
1122
-			'upload_time' => $entry->getUploadTime(),
1123
-			'metadata_etag' => $entry->getMetadataEtag(),
1124
-		];
1125
-	}
70
+    use MoveFromCacheTrait {
71
+        MoveFromCacheTrait::moveFromCache as moveFromCacheFallback;
72
+    }
73
+
74
+    /**
75
+     * @var array partial data for the cache
76
+     */
77
+    protected $partial = [];
78
+
79
+    /**
80
+     * @var string
81
+     */
82
+    protected $storageId;
83
+
84
+    private $storage;
85
+
86
+    /**
87
+     * @var Storage $storageCache
88
+     */
89
+    protected $storageCache;
90
+
91
+    /** @var IMimeTypeLoader */
92
+    protected $mimetypeLoader;
93
+
94
+    /**
95
+     * @var IDBConnection
96
+     */
97
+    protected $connection;
98
+
99
+    /**
100
+     * @var IEventDispatcher
101
+     */
102
+    protected $eventDispatcher;
103
+
104
+    /** @var QuerySearchHelper */
105
+    protected $querySearchHelper;
106
+
107
+    /**
108
+     * @param IStorage $storage
109
+     */
110
+    public function __construct(IStorage $storage) {
111
+        $this->storageId = $storage->getId();
112
+        $this->storage = $storage;
113
+        if (strlen($this->storageId) > 64) {
114
+            $this->storageId = md5($this->storageId);
115
+        }
116
+
117
+        $this->storageCache = new Storage($storage);
118
+        $this->mimetypeLoader = \OC::$server->getMimeTypeLoader();
119
+        $this->connection = \OC::$server->getDatabaseConnection();
120
+        $this->eventDispatcher = \OC::$server->get(IEventDispatcher::class);
121
+        $this->querySearchHelper = new QuerySearchHelper($this->mimetypeLoader);
122
+    }
123
+
124
+    protected function getQueryBuilder() {
125
+        return new CacheQueryBuilder(
126
+            $this->connection,
127
+            \OC::$server->getSystemConfig(),
128
+            \OC::$server->getLogger(),
129
+            $this
130
+        );
131
+    }
132
+
133
+    /**
134
+     * Get the numeric storage id for this cache's storage
135
+     *
136
+     * @return int
137
+     */
138
+    public function getNumericStorageId() {
139
+        return $this->storageCache->getNumericId();
140
+    }
141
+
142
+    /**
143
+     * get the stored metadata of a file or folder
144
+     *
145
+     * @param string | int $file either the path of a file or folder or the file id for a file or folder
146
+     * @return ICacheEntry|false the cache entry as array of false if the file is not found in the cache
147
+     */
148
+    public function get($file) {
149
+        $query = $this->getQueryBuilder();
150
+        $query->selectFileCache();
151
+
152
+        if (is_string($file) or $file == '') {
153
+            // normalize file
154
+            $file = $this->normalize($file);
155
+
156
+            $query->whereStorageId()
157
+                ->wherePath($file);
158
+        } else { //file id
159
+            $query->whereFileId($file);
160
+        }
161
+
162
+        $result = $query->execute();
163
+        $data = $result->fetch();
164
+        $result->closeCursor();
165
+
166
+        //merge partial data
167
+        if (!$data and is_string($file) and isset($this->partial[$file])) {
168
+            return $this->partial[$file];
169
+        } elseif (!$data) {
170
+            return $data;
171
+        } else {
172
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
173
+        }
174
+    }
175
+
176
+    /**
177
+     * Create a CacheEntry from database row
178
+     *
179
+     * @param array $data
180
+     * @param IMimeTypeLoader $mimetypeLoader
181
+     * @return CacheEntry
182
+     */
183
+    public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
184
+        //fix types
185
+        $data['fileid'] = (int)$data['fileid'];
186
+        $data['parent'] = (int)$data['parent'];
187
+        $data['size'] = 0 + $data['size'];
188
+        $data['mtime'] = (int)$data['mtime'];
189
+        $data['storage_mtime'] = (int)$data['storage_mtime'];
190
+        $data['encryptedVersion'] = (int)$data['encrypted'];
191
+        $data['encrypted'] = (bool)$data['encrypted'];
192
+        $data['storage_id'] = $data['storage'];
193
+        $data['storage'] = (int)$data['storage'];
194
+        $data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
195
+        $data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
196
+        if ($data['storage_mtime'] == 0) {
197
+            $data['storage_mtime'] = $data['mtime'];
198
+        }
199
+        $data['permissions'] = (int)$data['permissions'];
200
+        if (isset($data['creation_time'])) {
201
+            $data['creation_time'] = (int)$data['creation_time'];
202
+        }
203
+        if (isset($data['upload_time'])) {
204
+            $data['upload_time'] = (int)$data['upload_time'];
205
+        }
206
+        return new CacheEntry($data);
207
+    }
208
+
209
+    /**
210
+     * get the metadata of all files stored in $folder
211
+     *
212
+     * @param string $folder
213
+     * @return ICacheEntry[]
214
+     */
215
+    public function getFolderContents($folder) {
216
+        $fileId = $this->getId($folder);
217
+        return $this->getFolderContentsById($fileId);
218
+    }
219
+
220
+    /**
221
+     * get the metadata of all files stored in $folder
222
+     *
223
+     * @param int $fileId the file id of the folder
224
+     * @return ICacheEntry[]
225
+     */
226
+    public function getFolderContentsById($fileId) {
227
+        if ($fileId > -1) {
228
+            $query = $this->getQueryBuilder();
229
+            $query->selectFileCache()
230
+                ->whereParent($fileId)
231
+                ->orderBy('name', 'ASC');
232
+
233
+            $result = $query->execute();
234
+            $files = $result->fetchAll();
235
+            $result->closeCursor();
236
+
237
+            return array_map(function (array $data) {
238
+                return self::cacheEntryFromData($data, $this->mimetypeLoader);
239
+            }, $files);
240
+        }
241
+        return [];
242
+    }
243
+
244
+    /**
245
+     * insert or update meta data for a file or folder
246
+     *
247
+     * @param string $file
248
+     * @param array $data
249
+     *
250
+     * @return int file id
251
+     * @throws \RuntimeException
252
+     */
253
+    public function put($file, array $data) {
254
+        if (($id = $this->getId($file)) > -1) {
255
+            $this->update($id, $data);
256
+            return $id;
257
+        } else {
258
+            return $this->insert($file, $data);
259
+        }
260
+    }
261
+
262
+    /**
263
+     * insert meta data for a new file or folder
264
+     *
265
+     * @param string $file
266
+     * @param array $data
267
+     *
268
+     * @return int file id
269
+     * @throws \RuntimeException
270
+     */
271
+    public function insert($file, array $data) {
272
+        // normalize file
273
+        $file = $this->normalize($file);
274
+
275
+        if (isset($this->partial[$file])) { //add any saved partial data
276
+            $data = array_merge($this->partial[$file], $data);
277
+            unset($this->partial[$file]);
278
+        }
279
+
280
+        $requiredFields = ['size', 'mtime', 'mimetype'];
281
+        foreach ($requiredFields as $field) {
282
+            if (!isset($data[$field])) { //data not complete save as partial and return
283
+                $this->partial[$file] = $data;
284
+                return -1;
285
+            }
286
+        }
287
+
288
+        $data['path'] = $file;
289
+        if (!isset($data['parent'])) {
290
+            $data['parent'] = $this->getParentId($file);
291
+        }
292
+        $data['name'] = basename($file);
293
+
294
+        [$values, $extensionValues] = $this->normalizeData($data);
295
+        $storageId = $this->getNumericStorageId();
296
+        $values['storage'] = $storageId;
297
+
298
+        try {
299
+            $builder = $this->connection->getQueryBuilder();
300
+            $builder->insert('filecache');
301
+
302
+            foreach ($values as $column => $value) {
303
+                $builder->setValue($column, $builder->createNamedParameter($value));
304
+            }
305
+
306
+            if ($builder->execute()) {
307
+                $fileId = $builder->getLastInsertId();
308
+
309
+                if (count($extensionValues)) {
310
+                    $query = $this->getQueryBuilder();
311
+                    $query->insert('filecache_extended');
312
+
313
+                    $query->setValue('fileid', $query->createNamedParameter($fileId, IQueryBuilder::PARAM_INT));
314
+                    foreach ($extensionValues as $column => $value) {
315
+                        $query->setValue($column, $query->createNamedParameter($value));
316
+                    }
317
+                    $query->execute();
318
+                }
319
+
320
+                $event = new CacheEntryInsertedEvent($this->storage, $file, $fileId, $storageId);
321
+                $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
322
+                $this->eventDispatcher->dispatchTyped($event);
323
+                return $fileId;
324
+            }
325
+        } catch (UniqueConstraintViolationException $e) {
326
+            // entry exists already
327
+            if ($this->connection->inTransaction()) {
328
+                $this->connection->commit();
329
+                $this->connection->beginTransaction();
330
+            }
331
+        }
332
+
333
+        // The file was created in the mean time
334
+        if (($id = $this->getId($file)) > -1) {
335
+            $this->update($id, $data);
336
+            return $id;
337
+        } else {
338
+            throw new \RuntimeException('File entry could not be inserted but could also not be selected with getId() in order to perform an update. Please try again.');
339
+        }
340
+    }
341
+
342
+    /**
343
+     * update the metadata of an existing file or folder in the cache
344
+     *
345
+     * @param int $id the fileid of the existing file or folder
346
+     * @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
347
+     */
348
+    public function update($id, array $data) {
349
+        if (isset($data['path'])) {
350
+            // normalize path
351
+            $data['path'] = $this->normalize($data['path']);
352
+        }
353
+
354
+        if (isset($data['name'])) {
355
+            // normalize path
356
+            $data['name'] = $this->normalize($data['name']);
357
+        }
358
+
359
+        [$values, $extensionValues] = $this->normalizeData($data);
360
+
361
+        if (count($values)) {
362
+            $query = $this->getQueryBuilder();
363
+
364
+            $query->update('filecache')
365
+                ->whereFileId($id)
366
+                ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
367
+                    return $query->expr()->orX(
368
+                        $query->expr()->neq($key, $query->createNamedParameter($value)),
369
+                        $query->expr()->isNull($key)
370
+                    );
371
+                }, array_keys($values), array_values($values))));
372
+
373
+            foreach ($values as $key => $value) {
374
+                $query->set($key, $query->createNamedParameter($value));
375
+            }
376
+
377
+            $query->execute();
378
+        }
379
+
380
+        if (count($extensionValues)) {
381
+            try {
382
+                $query = $this->getQueryBuilder();
383
+                $query->insert('filecache_extended');
384
+
385
+                $query->setValue('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT));
386
+                foreach ($extensionValues as $column => $value) {
387
+                    $query->setValue($column, $query->createNamedParameter($value));
388
+                }
389
+
390
+                $query->execute();
391
+            } catch (UniqueConstraintViolationException $e) {
392
+                $query = $this->getQueryBuilder();
393
+                $query->update('filecache_extended')
394
+                    ->whereFileId($id)
395
+                    ->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
396
+                        return $query->expr()->orX(
397
+                            $query->expr()->neq($key, $query->createNamedParameter($value)),
398
+                            $query->expr()->isNull($key)
399
+                        );
400
+                    }, array_keys($extensionValues), array_values($extensionValues))));
401
+
402
+                foreach ($extensionValues as $key => $value) {
403
+                    $query->set($key, $query->createNamedParameter($value));
404
+                }
405
+
406
+                $query->execute();
407
+            }
408
+        }
409
+
410
+        $path = $this->getPathById($id);
411
+        // path can still be null if the file doesn't exist
412
+        if ($path !== null) {
413
+            $event = new CacheEntryUpdatedEvent($this->storage, $path, $id, $this->getNumericStorageId());
414
+            $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
415
+            $this->eventDispatcher->dispatchTyped($event);
416
+        }
417
+    }
418
+
419
+    /**
420
+     * extract query parts and params array from data array
421
+     *
422
+     * @param array $data
423
+     * @return array
424
+     */
425
+    protected function normalizeData(array $data): array {
426
+        $fields = [
427
+            'path', 'parent', 'name', 'mimetype', 'size', 'mtime', 'storage_mtime', 'encrypted',
428
+            'etag', 'permissions', 'checksum', 'storage'];
429
+        $extensionFields = ['metadata_etag', 'creation_time', 'upload_time'];
430
+
431
+        $doNotCopyStorageMTime = false;
432
+        if (array_key_exists('mtime', $data) && $data['mtime'] === null) {
433
+            // this horrific magic tells it to not copy storage_mtime to mtime
434
+            unset($data['mtime']);
435
+            $doNotCopyStorageMTime = true;
436
+        }
437
+
438
+        $params = [];
439
+        $extensionParams = [];
440
+        foreach ($data as $name => $value) {
441
+            if (array_search($name, $fields) !== false) {
442
+                if ($name === 'path') {
443
+                    $params['path_hash'] = md5($value);
444
+                } elseif ($name === 'mimetype') {
445
+                    $params['mimepart'] = $this->mimetypeLoader->getId(substr($value, 0, strpos($value, '/')));
446
+                    $value = $this->mimetypeLoader->getId($value);
447
+                } elseif ($name === 'storage_mtime') {
448
+                    if (!$doNotCopyStorageMTime && !isset($data['mtime'])) {
449
+                        $params['mtime'] = $value;
450
+                    }
451
+                } elseif ($name === 'encrypted') {
452
+                    if (isset($data['encryptedVersion'])) {
453
+                        $value = $data['encryptedVersion'];
454
+                    } else {
455
+                        // Boolean to integer conversion
456
+                        $value = $value ? 1 : 0;
457
+                    }
458
+                }
459
+                $params[$name] = $value;
460
+            }
461
+            if (array_search($name, $extensionFields) !== false) {
462
+                $extensionParams[$name] = $value;
463
+            }
464
+        }
465
+        return [$params, array_filter($extensionParams)];
466
+    }
467
+
468
+    /**
469
+     * get the file id for a file
470
+     *
471
+     * 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
472
+     *
473
+     * File ids are easiest way for apps to store references to a file since unlike paths they are not affected by renames or sharing
474
+     *
475
+     * @param string $file
476
+     * @return int
477
+     */
478
+    public function getId($file) {
479
+        // normalize file
480
+        $file = $this->normalize($file);
481
+
482
+        $query = $this->getQueryBuilder();
483
+        $query->select('fileid')
484
+            ->from('filecache')
485
+            ->whereStorageId()
486
+            ->wherePath($file);
487
+
488
+        $result = $query->execute();
489
+        $id = $result->fetchOne();
490
+        $result->closeCursor();
491
+
492
+        return $id === false ? -1 : (int)$id;
493
+    }
494
+
495
+    /**
496
+     * get the id of the parent folder of a file
497
+     *
498
+     * @param string $file
499
+     * @return int
500
+     */
501
+    public function getParentId($file) {
502
+        if ($file === '') {
503
+            return -1;
504
+        } else {
505
+            $parent = $this->getParentPath($file);
506
+            return (int)$this->getId($parent);
507
+        }
508
+    }
509
+
510
+    private function getParentPath($path) {
511
+        $parent = dirname($path);
512
+        if ($parent === '.') {
513
+            $parent = '';
514
+        }
515
+        return $parent;
516
+    }
517
+
518
+    /**
519
+     * check if a file is available in the cache
520
+     *
521
+     * @param string $file
522
+     * @return bool
523
+     */
524
+    public function inCache($file) {
525
+        return $this->getId($file) != -1;
526
+    }
527
+
528
+    /**
529
+     * remove a file or folder from the cache
530
+     *
531
+     * when removing a folder from the cache all files and folders inside the folder will be removed as well
532
+     *
533
+     * @param string $file
534
+     */
535
+    public function remove($file) {
536
+        $entry = $this->get($file);
537
+
538
+        if ($entry) {
539
+            $query = $this->getQueryBuilder();
540
+            $query->delete('filecache')
541
+                ->whereFileId($entry->getId());
542
+            $query->execute();
543
+
544
+            $query = $this->getQueryBuilder();
545
+            $query->delete('filecache_extended')
546
+                ->whereFileId($entry->getId());
547
+            $query->execute();
548
+
549
+            if ($entry->getMimeType() == FileInfo::MIMETYPE_FOLDER) {
550
+                $this->removeChildren($entry);
551
+            }
552
+
553
+            $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $entry->getPath(), $entry->getId(), $this->getNumericStorageId()));
554
+        }
555
+    }
556
+
557
+    /**
558
+     * Get all sub folders of a folder
559
+     *
560
+     * @param ICacheEntry $entry the cache entry of the folder to get the subfolders for
561
+     * @return ICacheEntry[] the cache entries for the subfolders
562
+     */
563
+    private function getSubFolders(ICacheEntry $entry) {
564
+        $children = $this->getFolderContentsById($entry->getId());
565
+        return array_filter($children, function ($child) {
566
+            return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
567
+        });
568
+    }
569
+
570
+    /**
571
+     * Recursively remove all children of a folder
572
+     *
573
+     * @param ICacheEntry $entry the cache entry of the folder to remove the children of
574
+     * @throws \OC\DatabaseException
575
+     */
576
+    private function removeChildren(ICacheEntry $entry) {
577
+        $parentIds = [$entry->getId()];
578
+        $queue = [$entry->getId()];
579
+
580
+        // we walk depth first trough the file tree, removing all filecache_extended attributes while we walk
581
+        // and collecting all folder ids to later use to delete the filecache entries
582
+        while ($entryId = array_pop($queue)) {
583
+            $children = $this->getFolderContentsById($entryId);
584
+            $childIds = array_map(function (ICacheEntry $cacheEntry) {
585
+                return $cacheEntry->getId();
586
+            }, $children);
587
+
588
+            $query = $this->getQueryBuilder();
589
+            $query->delete('filecache_extended')
590
+                ->where($query->expr()->in('fileid', $query->createNamedParameter($childIds, IQueryBuilder::PARAM_INT_ARRAY)));
591
+            $query->execute();
592
+
593
+            /** @var ICacheEntry[] $childFolders */
594
+            $childFolders = array_filter($children, function ($child) {
595
+                return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
596
+            });
597
+            foreach ($childFolders as $folder) {
598
+                $parentIds[] = $folder->getId();
599
+                $queue[] = $folder->getId();
600
+            }
601
+        }
602
+
603
+        $query = $this->getQueryBuilder();
604
+        $query->delete('filecache')
605
+            ->whereParentIn($parentIds);
606
+        $query->execute();
607
+    }
608
+
609
+    /**
610
+     * Move a file or folder in the cache
611
+     *
612
+     * @param string $source
613
+     * @param string $target
614
+     */
615
+    public function move($source, $target) {
616
+        $this->moveFromCache($this, $source, $target);
617
+    }
618
+
619
+    /**
620
+     * Get the storage id and path needed for a move
621
+     *
622
+     * @param string $path
623
+     * @return array [$storageId, $internalPath]
624
+     */
625
+    protected function getMoveInfo($path) {
626
+        return [$this->getNumericStorageId(), $path];
627
+    }
628
+
629
+    /**
630
+     * Move a file or folder in the cache
631
+     *
632
+     * @param ICache $sourceCache
633
+     * @param string $sourcePath
634
+     * @param string $targetPath
635
+     * @throws \OC\DatabaseException
636
+     * @throws \Exception if the given storages have an invalid id
637
+     */
638
+    public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {
639
+        if ($sourceCache instanceof Cache) {
640
+            // normalize source and target
641
+            $sourcePath = $this->normalize($sourcePath);
642
+            $targetPath = $this->normalize($targetPath);
643
+
644
+            $sourceData = $sourceCache->get($sourcePath);
645
+            $sourceId = $sourceData['fileid'];
646
+            $newParentId = $this->getParentId($targetPath);
647
+
648
+            [$sourceStorageId, $sourcePath] = $sourceCache->getMoveInfo($sourcePath);
649
+            [$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
650
+
651
+            if (is_null($sourceStorageId) || $sourceStorageId === false) {
652
+                throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
653
+            }
654
+            if (is_null($targetStorageId) || $targetStorageId === false) {
655
+                throw new \Exception('Invalid target storage id: ' . $targetStorageId);
656
+            }
657
+
658
+            $this->connection->beginTransaction();
659
+            if ($sourceData['mimetype'] === 'httpd/unix-directory') {
660
+                //update all child entries
661
+                $sourceLength = mb_strlen($sourcePath);
662
+                $query = $this->connection->getQueryBuilder();
663
+
664
+                $fun = $query->func();
665
+                $newPathFunction = $fun->concat(
666
+                    $query->createNamedParameter($targetPath),
667
+                    $fun->substring('path', $query->createNamedParameter($sourceLength + 1, IQueryBuilder::PARAM_INT))// +1 for the leading slash
668
+                );
669
+                $query->update('filecache')
670
+                    ->set('storage', $query->createNamedParameter($targetStorageId, IQueryBuilder::PARAM_INT))
671
+                    ->set('path_hash', $fun->md5($newPathFunction))
672
+                    ->set('path', $newPathFunction)
673
+                    ->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
674
+                    ->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
675
+
676
+                try {
677
+                    $query->execute();
678
+                } catch (\OC\DatabaseException $e) {
679
+                    $this->connection->rollBack();
680
+                    throw $e;
681
+                }
682
+            }
683
+
684
+            $query = $this->getQueryBuilder();
685
+            $query->update('filecache')
686
+                ->set('storage', $query->createNamedParameter($targetStorageId))
687
+                ->set('path', $query->createNamedParameter($targetPath))
688
+                ->set('path_hash', $query->createNamedParameter(md5($targetPath)))
689
+                ->set('name', $query->createNamedParameter(basename($targetPath)))
690
+                ->set('parent', $query->createNamedParameter($newParentId, IQueryBuilder::PARAM_INT))
691
+                ->whereFileId($sourceId);
692
+            $query->execute();
693
+
694
+            $this->connection->commit();
695
+
696
+            if ($sourceCache->getNumericStorageId() !== $this->getNumericStorageId()) {
697
+                $this->eventDispatcher->dispatchTyped(new CacheEntryRemovedEvent($this->storage, $sourcePath, $sourceId, $sourceCache->getNumericStorageId()));
698
+                $event = new CacheEntryInsertedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
699
+                $this->eventDispatcher->dispatch(CacheInsertEvent::class, $event);
700
+                $this->eventDispatcher->dispatchTyped($event);
701
+            } else {
702
+                $event = new CacheEntryUpdatedEvent($this->storage, $targetPath, $sourceId, $this->getNumericStorageId());
703
+                $this->eventDispatcher->dispatch(CacheUpdateEvent::class, $event);
704
+                $this->eventDispatcher->dispatchTyped($event);
705
+            }
706
+        } else {
707
+            $this->moveFromCacheFallback($sourceCache, $sourcePath, $targetPath);
708
+        }
709
+    }
710
+
711
+    /**
712
+     * remove all entries for files that are stored on the storage from the cache
713
+     */
714
+    public function clear() {
715
+        $query = $this->getQueryBuilder();
716
+        $query->delete('filecache')
717
+            ->whereStorageId();
718
+        $query->execute();
719
+
720
+        $query = $this->connection->getQueryBuilder();
721
+        $query->delete('storages')
722
+            ->where($query->expr()->eq('id', $query->createNamedParameter($this->storageId)));
723
+        $query->execute();
724
+    }
725
+
726
+    /**
727
+     * Get the scan status of a file
728
+     *
729
+     * - Cache::NOT_FOUND: File is not in the cache
730
+     * - Cache::PARTIAL: File is not stored in the cache but some incomplete data is known
731
+     * - Cache::SHALLOW: The folder and it's direct children are in the cache but not all sub folders are fully scanned
732
+     * - Cache::COMPLETE: The file or folder, with all it's children) are fully scanned
733
+     *
734
+     * @param string $file
735
+     *
736
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
737
+     */
738
+    public function getStatus($file) {
739
+        // normalize file
740
+        $file = $this->normalize($file);
741
+
742
+        $query = $this->getQueryBuilder();
743
+        $query->select('size')
744
+            ->from('filecache')
745
+            ->whereStorageId()
746
+            ->wherePath($file);
747
+
748
+        $result = $query->execute();
749
+        $size = $result->fetchOne();
750
+        $result->closeCursor();
751
+
752
+        if ($size !== false) {
753
+            if ((int)$size === -1) {
754
+                return self::SHALLOW;
755
+            } else {
756
+                return self::COMPLETE;
757
+            }
758
+        } else {
759
+            if (isset($this->partial[$file])) {
760
+                return self::PARTIAL;
761
+            } else {
762
+                return self::NOT_FOUND;
763
+            }
764
+        }
765
+    }
766
+
767
+    /**
768
+     * search for files matching $pattern
769
+     *
770
+     * @param string $pattern the search pattern using SQL search syntax (e.g. '%searchstring%')
771
+     * @return ICacheEntry[] an array of cache entries where the name matches the search pattern
772
+     */
773
+    public function search($pattern) {
774
+        // normalize pattern
775
+        $pattern = $this->normalize($pattern);
776
+
777
+        if ($pattern === '%%') {
778
+            return [];
779
+        }
780
+
781
+        $query = $this->getQueryBuilder();
782
+        $query->selectFileCache()
783
+            ->whereStorageId()
784
+            ->andWhere($query->expr()->iLike('name', $query->createNamedParameter($pattern)));
785
+
786
+        $result = $query->execute();
787
+        $files = $result->fetchAll();
788
+        $result->closeCursor();
789
+
790
+        return array_map(function (array $data) {
791
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
792
+        }, $files);
793
+    }
794
+
795
+    /**
796
+     * @param IResult $result
797
+     * @return CacheEntry[]
798
+     */
799
+    private function searchResultToCacheEntries(IResult $result): array {
800
+        $files = $result->fetchAll();
801
+
802
+        return array_map(function (array $data) {
803
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
804
+        }, $files);
805
+    }
806
+
807
+    /**
808
+     * search for files by mimetype
809
+     *
810
+     * @param string $mimetype either a full mimetype to search ('text/plain') or only the first part of a mimetype ('image')
811
+     *        where it will search for all mimetypes in the group ('image/*')
812
+     * @return ICacheEntry[] an array of cache entries where the mimetype matches the search
813
+     */
814
+    public function searchByMime($mimetype) {
815
+        $mimeId = $this->mimetypeLoader->getId($mimetype);
816
+
817
+        $query = $this->getQueryBuilder();
818
+        $query->selectFileCache()
819
+            ->whereStorageId();
820
+
821
+        if (strpos($mimetype, '/')) {
822
+            $query->andWhere($query->expr()->eq('mimetype', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
823
+        } else {
824
+            $query->andWhere($query->expr()->eq('mimepart', $query->createNamedParameter($mimeId, IQueryBuilder::PARAM_INT)));
825
+        }
826
+
827
+        $result = $query->execute();
828
+        $files = $result->fetchAll();
829
+        $result->closeCursor();
830
+
831
+        return array_map(function (array $data) {
832
+            return self::cacheEntryFromData($data, $this->mimetypeLoader);
833
+        }, $files);
834
+    }
835
+
836
+    public function searchQuery(ISearchQuery $searchQuery) {
837
+        $builder = $this->getQueryBuilder();
838
+
839
+        $query = $builder->selectFileCache('file');
840
+
841
+        $query->whereStorageId();
842
+
843
+        if ($this->querySearchHelper->shouldJoinTags($searchQuery->getSearchOperation())) {
844
+            $user = $searchQuery->getUser();
845
+            if ($user === null) {
846
+                throw new \InvalidArgumentException("Searching by tag requires the user to be set in the query");
847
+            }
848
+            $query
849
+                ->innerJoin('file', 'vcategory_to_object', 'tagmap', $builder->expr()->eq('file.fileid', 'tagmap.objid'))
850
+                ->innerJoin('tagmap', 'vcategory', 'tag', $builder->expr()->andX(
851
+                    $builder->expr()->eq('tagmap.type', 'tag.type'),
852
+                    $builder->expr()->eq('tagmap.categoryid', 'tag.id')
853
+                ))
854
+                ->andWhere($builder->expr()->eq('tag.type', $builder->createNamedParameter('files')))
855
+                ->andWhere($builder->expr()->eq('tag.uid', $builder->createNamedParameter($user->getUID())));
856
+        }
857
+
858
+        $searchExpr = $this->querySearchHelper->searchOperatorToDBExpr($builder, $searchQuery->getSearchOperation());
859
+        if ($searchExpr) {
860
+            $query->andWhere($searchExpr);
861
+        }
862
+
863
+        if ($searchQuery->limitToHome() && ($this instanceof HomeCache)) {
864
+            $query->andWhere($builder->expr()->like('path', $query->expr()->literal('files/%')));
865
+        }
866
+
867
+        $this->querySearchHelper->addSearchOrdersToQuery($query, $searchQuery->getOrder());
868
+
869
+        if ($searchQuery->getLimit()) {
870
+            $query->setMaxResults($searchQuery->getLimit());
871
+        }
872
+        if ($searchQuery->getOffset()) {
873
+            $query->setFirstResult($searchQuery->getOffset());
874
+        }
875
+
876
+        $result = $query->execute();
877
+        $cacheEntries = $this->searchResultToCacheEntries($result);
878
+        $result->closeCursor();
879
+        return $cacheEntries;
880
+    }
881
+
882
+    /**
883
+     * Re-calculate the folder size and the size of all parent folders
884
+     *
885
+     * @param string|boolean $path
886
+     * @param array $data (optional) meta data of the folder
887
+     */
888
+    public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {
889
+        $this->calculateFolderSize($path, $data);
890
+        if ($path !== '') {
891
+            $parent = dirname($path);
892
+            if ($parent === '.' or $parent === '/') {
893
+                $parent = '';
894
+            }
895
+            if ($isBackgroundScan) {
896
+                $parentData = $this->get($parent);
897
+                if ($parentData['size'] !== -1 && $this->getIncompleteChildrenCount($parentData['fileid']) === 0) {
898
+                    $this->correctFolderSize($parent, $parentData, $isBackgroundScan);
899
+                }
900
+            } else {
901
+                $this->correctFolderSize($parent);
902
+            }
903
+        }
904
+    }
905
+
906
+    /**
907
+     * get the incomplete count that shares parent $folder
908
+     *
909
+     * @param int $fileId the file id of the folder
910
+     * @return int
911
+     */
912
+    public function getIncompleteChildrenCount($fileId) {
913
+        if ($fileId > -1) {
914
+            $query = $this->getQueryBuilder();
915
+            $query->select($query->func()->count())
916
+                ->from('filecache')
917
+                ->whereParent($fileId)
918
+                ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
919
+
920
+            $result = $query->execute();
921
+            $size = (int)$result->fetchOne();
922
+            $result->closeCursor();
923
+
924
+            return $size;
925
+        }
926
+        return -1;
927
+    }
928
+
929
+    /**
930
+     * calculate the size of a folder and set it in the cache
931
+     *
932
+     * @param string $path
933
+     * @param array $entry (optional) meta data of the folder
934
+     * @return int
935
+     */
936
+    public function calculateFolderSize($path, $entry = null) {
937
+        $totalSize = 0;
938
+        if (is_null($entry) or !isset($entry['fileid'])) {
939
+            $entry = $this->get($path);
940
+        }
941
+        if (isset($entry['mimetype']) && $entry['mimetype'] === FileInfo::MIMETYPE_FOLDER) {
942
+            $id = $entry['fileid'];
943
+
944
+            $query = $this->getQueryBuilder();
945
+            $query->selectAlias($query->func()->sum('size'), 'f1')
946
+                ->selectAlias($query->func()->min('size'), 'f2')
947
+                ->from('filecache')
948
+                ->whereStorageId()
949
+                ->whereParent($id);
950
+
951
+            $result = $query->execute();
952
+            $row = $result->fetch();
953
+            $result->closeCursor();
954
+
955
+            if ($row) {
956
+                [$sum, $min] = array_values($row);
957
+                $sum = 0 + $sum;
958
+                $min = 0 + $min;
959
+                if ($min === -1) {
960
+                    $totalSize = $min;
961
+                } else {
962
+                    $totalSize = $sum;
963
+                }
964
+                if ($entry['size'] !== $totalSize) {
965
+                    $this->update($id, ['size' => $totalSize]);
966
+                }
967
+            }
968
+        }
969
+        return $totalSize;
970
+    }
971
+
972
+    /**
973
+     * get all file ids on the files on the storage
974
+     *
975
+     * @return int[]
976
+     */
977
+    public function getAll() {
978
+        $query = $this->getQueryBuilder();
979
+        $query->select('fileid')
980
+            ->from('filecache')
981
+            ->whereStorageId();
982
+
983
+        $result = $query->execute();
984
+        $files = $result->fetchAll(\PDO::FETCH_COLUMN);
985
+        $result->closeCursor();
986
+
987
+        return array_map(function ($id) {
988
+            return (int)$id;
989
+        }, $files);
990
+    }
991
+
992
+    /**
993
+     * find a folder in the cache which has not been fully scanned
994
+     *
995
+     * If multiple incomplete folders are in the cache, the one with the highest id will be returned,
996
+     * use the one with the highest id gives the best result with the background scanner, since that is most
997
+     * likely the folder where we stopped scanning previously
998
+     *
999
+     * @return string|bool the path of the folder or false when no folder matched
1000
+     */
1001
+    public function getIncomplete() {
1002
+        $query = $this->getQueryBuilder();
1003
+        $query->select('path')
1004
+            ->from('filecache')
1005
+            ->whereStorageId()
1006
+            ->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)))
1007
+            ->orderBy('fileid', 'DESC')
1008
+            ->setMaxResults(1);
1009
+
1010
+        $result = $query->execute();
1011
+        $path = $result->fetchOne();
1012
+        $result->closeCursor();
1013
+
1014
+        return $path;
1015
+    }
1016
+
1017
+    /**
1018
+     * get the path of a file on this storage by it's file id
1019
+     *
1020
+     * @param int $id the file id of the file or folder to search
1021
+     * @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
1022
+     */
1023
+    public function getPathById($id) {
1024
+        $query = $this->getQueryBuilder();
1025
+        $query->select('path')
1026
+            ->from('filecache')
1027
+            ->whereStorageId()
1028
+            ->whereFileId($id);
1029
+
1030
+        $result = $query->execute();
1031
+        $path = $result->fetchOne();
1032
+        $result->closeCursor();
1033
+
1034
+        if ($path === false) {
1035
+            return null;
1036
+        }
1037
+
1038
+        return (string)$path;
1039
+    }
1040
+
1041
+    /**
1042
+     * get the storage id of the storage for a file and the internal path of the file
1043
+     * unlike getPathById this does not limit the search to files on this storage and
1044
+     * instead does a global search in the cache table
1045
+     *
1046
+     * @param int $id
1047
+     * @return array first element holding the storage id, second the path
1048
+     * @deprecated use getPathById() instead
1049
+     */
1050
+    public static function getById($id) {
1051
+        $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
1052
+        $query->select('path', 'storage')
1053
+            ->from('filecache')
1054
+            ->where($query->expr()->eq('fileid', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
1055
+
1056
+        $result = $query->execute();
1057
+        $row = $result->fetch();
1058
+        $result->closeCursor();
1059
+
1060
+        if ($row) {
1061
+            $numericId = $row['storage'];
1062
+            $path = $row['path'];
1063
+        } else {
1064
+            return null;
1065
+        }
1066
+
1067
+        if ($id = Storage::getStorageId($numericId)) {
1068
+            return [$id, $path];
1069
+        } else {
1070
+            return null;
1071
+        }
1072
+    }
1073
+
1074
+    /**
1075
+     * normalize the given path
1076
+     *
1077
+     * @param string $path
1078
+     * @return string
1079
+     */
1080
+    public function normalize($path) {
1081
+        return trim(\OC_Util::normalizeUnicode($path), '/');
1082
+    }
1083
+
1084
+    /**
1085
+     * Copy a file or folder in the cache
1086
+     *
1087
+     * @param ICache $sourceCache
1088
+     * @param ICacheEntry $sourceEntry
1089
+     * @param string $targetPath
1090
+     * @return int fileid of copied entry
1091
+     */
1092
+    public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int {
1093
+        if ($sourceEntry->getId() < 0) {
1094
+            throw new \RuntimeException("Invalid source cache entry on copyFromCache");
1095
+        }
1096
+        $data = $this->cacheEntryToArray($sourceEntry);
1097
+        $fileId = $this->put($targetPath, $data);
1098
+        if ($fileId <= 0) {
1099
+            throw new \RuntimeException("Failed to copy to " . $targetPath . " from cache with source data " . json_encode($data) . " ");
1100
+        }
1101
+        if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
1102
+            $folderContent = $sourceCache->getFolderContentsById($sourceEntry->getId());
1103
+            foreach ($folderContent as $subEntry) {
1104
+                $subTargetPath = $targetPath . '/' . $subEntry->getName();
1105
+                $this->copyFromCache($sourceCache, $subEntry, $subTargetPath);
1106
+            }
1107
+        }
1108
+        return $fileId;
1109
+    }
1110
+
1111
+    private function cacheEntryToArray(ICacheEntry $entry): array {
1112
+        return [
1113
+            'size' => $entry->getSize(),
1114
+            'mtime' => $entry->getMTime(),
1115
+            'storage_mtime' => $entry->getStorageMTime(),
1116
+            'mimetype' => $entry->getMimeType(),
1117
+            'mimepart' => $entry->getMimePart(),
1118
+            'etag' => $entry->getEtag(),
1119
+            'permissions' => $entry->getPermissions(),
1120
+            'encrypted' => $entry->isEncrypted(),
1121
+            'creation_time' => $entry->getCreationTime(),
1122
+            'upload_time' => $entry->getUploadTime(),
1123
+            'metadata_etag' => $entry->getMetadataEtag(),
1124
+        ];
1125
+    }
1126 1126
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -182,26 +182,26 @@  discard block
 block discarded – undo
182 182
 	 */
183 183
 	public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader) {
184 184
 		//fix types
185
-		$data['fileid'] = (int)$data['fileid'];
186
-		$data['parent'] = (int)$data['parent'];
185
+		$data['fileid'] = (int) $data['fileid'];
186
+		$data['parent'] = (int) $data['parent'];
187 187
 		$data['size'] = 0 + $data['size'];
188
-		$data['mtime'] = (int)$data['mtime'];
189
-		$data['storage_mtime'] = (int)$data['storage_mtime'];
190
-		$data['encryptedVersion'] = (int)$data['encrypted'];
191
-		$data['encrypted'] = (bool)$data['encrypted'];
188
+		$data['mtime'] = (int) $data['mtime'];
189
+		$data['storage_mtime'] = (int) $data['storage_mtime'];
190
+		$data['encryptedVersion'] = (int) $data['encrypted'];
191
+		$data['encrypted'] = (bool) $data['encrypted'];
192 192
 		$data['storage_id'] = $data['storage'];
193
-		$data['storage'] = (int)$data['storage'];
193
+		$data['storage'] = (int) $data['storage'];
194 194
 		$data['mimetype'] = $mimetypeLoader->getMimetypeById($data['mimetype']);
195 195
 		$data['mimepart'] = $mimetypeLoader->getMimetypeById($data['mimepart']);
196 196
 		if ($data['storage_mtime'] == 0) {
197 197
 			$data['storage_mtime'] = $data['mtime'];
198 198
 		}
199
-		$data['permissions'] = (int)$data['permissions'];
199
+		$data['permissions'] = (int) $data['permissions'];
200 200
 		if (isset($data['creation_time'])) {
201
-			$data['creation_time'] = (int)$data['creation_time'];
201
+			$data['creation_time'] = (int) $data['creation_time'];
202 202
 		}
203 203
 		if (isset($data['upload_time'])) {
204
-			$data['upload_time'] = (int)$data['upload_time'];
204
+			$data['upload_time'] = (int) $data['upload_time'];
205 205
 		}
206 206
 		return new CacheEntry($data);
207 207
 	}
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
 			$files = $result->fetchAll();
235 235
 			$result->closeCursor();
236 236
 
237
-			return array_map(function (array $data) {
237
+			return array_map(function(array $data) {
238 238
 				return self::cacheEntryFromData($data, $this->mimetypeLoader);
239 239
 			}, $files);
240 240
 		}
@@ -363,7 +363,7 @@  discard block
 block discarded – undo
363 363
 
364 364
 			$query->update('filecache')
365 365
 				->whereFileId($id)
366
-				->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
366
+				->andWhere($query->expr()->orX(...array_map(function($key, $value) use ($query) {
367 367
 					return $query->expr()->orX(
368 368
 						$query->expr()->neq($key, $query->createNamedParameter($value)),
369 369
 						$query->expr()->isNull($key)
@@ -392,7 +392,7 @@  discard block
 block discarded – undo
392 392
 				$query = $this->getQueryBuilder();
393 393
 				$query->update('filecache_extended')
394 394
 					->whereFileId($id)
395
-					->andWhere($query->expr()->orX(...array_map(function ($key, $value) use ($query) {
395
+					->andWhere($query->expr()->orX(...array_map(function($key, $value) use ($query) {
396 396
 						return $query->expr()->orX(
397 397
 							$query->expr()->neq($key, $query->createNamedParameter($value)),
398 398
 							$query->expr()->isNull($key)
@@ -489,7 +489,7 @@  discard block
 block discarded – undo
489 489
 		$id = $result->fetchOne();
490 490
 		$result->closeCursor();
491 491
 
492
-		return $id === false ? -1 : (int)$id;
492
+		return $id === false ? -1 : (int) $id;
493 493
 	}
494 494
 
495 495
 	/**
@@ -503,7 +503,7 @@  discard block
 block discarded – undo
503 503
 			return -1;
504 504
 		} else {
505 505
 			$parent = $this->getParentPath($file);
506
-			return (int)$this->getId($parent);
506
+			return (int) $this->getId($parent);
507 507
 		}
508 508
 	}
509 509
 
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
 	 */
563 563
 	private function getSubFolders(ICacheEntry $entry) {
564 564
 		$children = $this->getFolderContentsById($entry->getId());
565
-		return array_filter($children, function ($child) {
565
+		return array_filter($children, function($child) {
566 566
 			return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
567 567
 		});
568 568
 	}
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 		// and collecting all folder ids to later use to delete the filecache entries
582 582
 		while ($entryId = array_pop($queue)) {
583 583
 			$children = $this->getFolderContentsById($entryId);
584
-			$childIds = array_map(function (ICacheEntry $cacheEntry) {
584
+			$childIds = array_map(function(ICacheEntry $cacheEntry) {
585 585
 				return $cacheEntry->getId();
586 586
 			}, $children);
587 587
 
@@ -591,7 +591,7 @@  discard block
 block discarded – undo
591 591
 			$query->execute();
592 592
 
593 593
 			/** @var ICacheEntry[] $childFolders */
594
-			$childFolders = array_filter($children, function ($child) {
594
+			$childFolders = array_filter($children, function($child) {
595 595
 				return $child->getMimeType() == FileInfo::MIMETYPE_FOLDER;
596 596
 			});
597 597
 			foreach ($childFolders as $folder) {
@@ -649,10 +649,10 @@  discard block
 block discarded – undo
649 649
 			[$targetStorageId, $targetPath] = $this->getMoveInfo($targetPath);
650 650
 
651 651
 			if (is_null($sourceStorageId) || $sourceStorageId === false) {
652
-				throw new \Exception('Invalid source storage id: ' . $sourceStorageId);
652
+				throw new \Exception('Invalid source storage id: '.$sourceStorageId);
653 653
 			}
654 654
 			if (is_null($targetStorageId) || $targetStorageId === false) {
655
-				throw new \Exception('Invalid target storage id: ' . $targetStorageId);
655
+				throw new \Exception('Invalid target storage id: '.$targetStorageId);
656 656
 			}
657 657
 
658 658
 			$this->connection->beginTransaction();
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 					->set('path_hash', $fun->md5($newPathFunction))
672 672
 					->set('path', $newPathFunction)
673 673
 					->where($query->expr()->eq('storage', $query->createNamedParameter($sourceStorageId, IQueryBuilder::PARAM_INT)))
674
-					->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath) . '/%')));
674
+					->andWhere($query->expr()->like('path', $query->createNamedParameter($this->connection->escapeLikeParameter($sourcePath).'/%')));
675 675
 
676 676
 				try {
677 677
 					$query->execute();
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 		$result->closeCursor();
751 751
 
752 752
 		if ($size !== false) {
753
-			if ((int)$size === -1) {
753
+			if ((int) $size === -1) {
754 754
 				return self::SHALLOW;
755 755
 			} else {
756 756
 				return self::COMPLETE;
@@ -787,7 +787,7 @@  discard block
 block discarded – undo
787 787
 		$files = $result->fetchAll();
788 788
 		$result->closeCursor();
789 789
 
790
-		return array_map(function (array $data) {
790
+		return array_map(function(array $data) {
791 791
 			return self::cacheEntryFromData($data, $this->mimetypeLoader);
792 792
 		}, $files);
793 793
 	}
@@ -799,7 +799,7 @@  discard block
 block discarded – undo
799 799
 	private function searchResultToCacheEntries(IResult $result): array {
800 800
 		$files = $result->fetchAll();
801 801
 
802
-		return array_map(function (array $data) {
802
+		return array_map(function(array $data) {
803 803
 			return self::cacheEntryFromData($data, $this->mimetypeLoader);
804 804
 		}, $files);
805 805
 	}
@@ -828,7 +828,7 @@  discard block
 block discarded – undo
828 828
 		$files = $result->fetchAll();
829 829
 		$result->closeCursor();
830 830
 
831
-		return array_map(function (array $data) {
831
+		return array_map(function(array $data) {
832 832
 			return self::cacheEntryFromData($data, $this->mimetypeLoader);
833 833
 		}, $files);
834 834
 	}
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
 				->andWhere($query->expr()->lt('size', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT)));
919 919
 
920 920
 			$result = $query->execute();
921
-			$size = (int)$result->fetchOne();
921
+			$size = (int) $result->fetchOne();
922 922
 			$result->closeCursor();
923 923
 
924 924
 			return $size;
@@ -984,8 +984,8 @@  discard block
 block discarded – undo
984 984
 		$files = $result->fetchAll(\PDO::FETCH_COLUMN);
985 985
 		$result->closeCursor();
986 986
 
987
-		return array_map(function ($id) {
988
-			return (int)$id;
987
+		return array_map(function($id) {
988
+			return (int) $id;
989 989
 		}, $files);
990 990
 	}
991 991
 
@@ -1035,7 +1035,7 @@  discard block
 block discarded – undo
1035 1035
 			return null;
1036 1036
 		}
1037 1037
 
1038
-		return (string)$path;
1038
+		return (string) $path;
1039 1039
 	}
1040 1040
 
1041 1041
 	/**
@@ -1096,12 +1096,12 @@  discard block
 block discarded – undo
1096 1096
 		$data = $this->cacheEntryToArray($sourceEntry);
1097 1097
 		$fileId = $this->put($targetPath, $data);
1098 1098
 		if ($fileId <= 0) {
1099
-			throw new \RuntimeException("Failed to copy to " . $targetPath . " from cache with source data " . json_encode($data) . " ");
1099
+			throw new \RuntimeException("Failed to copy to ".$targetPath." from cache with source data ".json_encode($data)." ");
1100 1100
 		}
1101 1101
 		if ($sourceEntry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
1102 1102
 			$folderContent = $sourceCache->getFolderContentsById($sourceEntry->getId());
1103 1103
 			foreach ($folderContent as $subEntry) {
1104
-				$subTargetPath = $targetPath . '/' . $subEntry->getName();
1104
+				$subTargetPath = $targetPath.'/'.$subEntry->getName();
1105 1105
 				$this->copyFromCache($sourceCache, $subEntry, $subTargetPath);
1106 1106
 			}
1107 1107
 		}
Please login to merge, or discard this patch.
lib/private/Files/Node/Folder.php 2 patches
Indentation   +584 added lines, -584 removed lines patch added patch discarded remove patch
@@ -52,595 +52,595 @@
 block discarded – undo
52 52
 use OCP\IUserManager;
53 53
 
54 54
 class Folder extends Node implements \OCP\Files\Folder {
55
-	/**
56
-	 * Creates a Folder that represents a non-existing path
57
-	 *
58
-	 * @param string $path path
59
-	 * @return string non-existing node class
60
-	 */
61
-	protected function createNonExistingNode($path) {
62
-		return new NonExistingFolder($this->root, $this->view, $path);
63
-	}
64
-
65
-	/**
66
-	 * @param string $path path relative to the folder
67
-	 * @return string
68
-	 * @throws \OCP\Files\NotPermittedException
69
-	 */
70
-	public function getFullPath($path) {
71
-		if (!$this->isValidPath($path)) {
72
-			throw new NotPermittedException('Invalid path');
73
-		}
74
-		return $this->path . $this->normalizePath($path);
75
-	}
76
-
77
-	/**
78
-	 * @param string $path
79
-	 * @return string
80
-	 */
81
-	public function getRelativePath($path) {
82
-		if ($this->path === '' or $this->path === '/') {
83
-			return $this->normalizePath($path);
84
-		}
85
-		if ($path === $this->path) {
86
-			return '/';
87
-		} elseif (strpos($path, $this->path . '/') !== 0) {
88
-			return null;
89
-		} else {
90
-			$path = substr($path, strlen($this->path));
91
-			return $this->normalizePath($path);
92
-		}
93
-	}
94
-
95
-	/**
96
-	 * check if a node is a (grand-)child of the folder
97
-	 *
98
-	 * @param \OC\Files\Node\Node $node
99
-	 * @return bool
100
-	 */
101
-	public function isSubNode($node) {
102
-		return strpos($node->getPath(), $this->path . '/') === 0;
103
-	}
104
-
105
-	/**
106
-	 * get the content of this directory
107
-	 *
108
-	 * @return Node[]
109
-	 * @throws \OCP\Files\NotFoundException
110
-	 */
111
-	public function getDirectoryListing() {
112
-		$folderContent = $this->view->getDirectoryContent($this->path);
113
-
114
-		return array_map(function (FileInfo $info) {
115
-			if ($info->getMimetype() === 'httpd/unix-directory') {
116
-				return new Folder($this->root, $this->view, $info->getPath(), $info);
117
-			} else {
118
-				return new File($this->root, $this->view, $info->getPath(), $info);
119
-			}
120
-		}, $folderContent);
121
-	}
122
-
123
-	/**
124
-	 * @param string $path
125
-	 * @param FileInfo $info
126
-	 * @return File|Folder
127
-	 */
128
-	protected function createNode($path, FileInfo $info = null) {
129
-		if (is_null($info)) {
130
-			$isDir = $this->view->is_dir($path);
131
-		} else {
132
-			$isDir = $info->getType() === FileInfo::TYPE_FOLDER;
133
-		}
134
-		if ($isDir) {
135
-			return new Folder($this->root, $this->view, $path, $info);
136
-		} else {
137
-			return new File($this->root, $this->view, $path, $info);
138
-		}
139
-	}
140
-
141
-	/**
142
-	 * Get the node at $path
143
-	 *
144
-	 * @param string $path
145
-	 * @return \OC\Files\Node\Node
146
-	 * @throws \OCP\Files\NotFoundException
147
-	 */
148
-	public function get($path) {
149
-		return $this->root->get($this->getFullPath($path));
150
-	}
151
-
152
-	/**
153
-	 * @param string $path
154
-	 * @return bool
155
-	 */
156
-	public function nodeExists($path) {
157
-		try {
158
-			$this->get($path);
159
-			return true;
160
-		} catch (NotFoundException $e) {
161
-			return false;
162
-		}
163
-	}
164
-
165
-	/**
166
-	 * @param string $path
167
-	 * @return \OC\Files\Node\Folder
168
-	 * @throws \OCP\Files\NotPermittedException
169
-	 */
170
-	public function newFolder($path) {
171
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
172
-			$fullPath = $this->getFullPath($path);
173
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
174
-			$this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]);
175
-			if (!$this->view->mkdir($fullPath)) {
176
-				throw new NotPermittedException('Could not create folder');
177
-			}
178
-			$node = new Folder($this->root, $this->view, $fullPath);
179
-			$this->sendHooks(['postWrite', 'postCreate'], [$node]);
180
-			return $node;
181
-		} else {
182
-			throw new NotPermittedException('No create permission for folder');
183
-		}
184
-	}
185
-
186
-	/**
187
-	 * @param string $path
188
-	 * @param string | resource | null $content
189
-	 * @return \OC\Files\Node\File
190
-	 * @throws \OCP\Files\NotPermittedException
191
-	 */
192
-	public function newFile($path, $content = null) {
193
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
194
-			$fullPath = $this->getFullPath($path);
195
-			$nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
196
-			$this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]);
197
-			if ($content !== null) {
198
-				$result = $this->view->file_put_contents($fullPath, $content);
199
-			} else {
200
-				$result = $this->view->touch($fullPath);
201
-			}
202
-			if ($result === false) {
203
-				throw new NotPermittedException('Could not create path');
204
-			}
205
-			$node = new File($this->root, $this->view, $fullPath);
206
-			$this->sendHooks(['postWrite', 'postCreate'], [$node]);
207
-			return $node;
208
-		}
209
-		throw new NotPermittedException('No create permission for path');
210
-	}
211
-
212
-	private function queryFromOperator(ISearchOperator $operator, string $uid = null): ISearchQuery {
213
-		if ($uid === null) {
214
-			$user = null;
215
-		} else {
216
-			/** @var IUserManager $userManager */
217
-			$userManager = \OC::$server->query(IUserManager::class);
218
-			$user = $userManager->get($uid);
219
-		}
220
-		return new SearchQuery($operator, 0, 0, [], $user);
221
-	}
222
-
223
-	/**
224
-	 * search for files with the name matching $query
225
-	 *
226
-	 * @param string|ISearchQuery $query
227
-	 * @return \OC\Files\Node\Node[]
228
-	 */
229
-	public function search($query) {
230
-		if (is_string($query)) {
231
-			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'));
232
-		}
233
-
234
-		// Limit+offset for queries with ordering
235
-		//
236
-		// Because we currently can't do ordering between the results from different storages in sql
237
-		// The only way to do ordering is requesting the $limit number of entries from all storages
238
-		// sorting them and returning the first $limit entries.
239
-		//
240
-		// For offset we have the same problem, we don't know how many entries from each storage should be skipped
241
-		// by a given $offset, so instead we query $offset + $limit from each storage and return entries $offset..($offset+$limit)
242
-		// after merging and sorting them.
243
-		//
244
-		// This is suboptimal but because limit and offset tend to be fairly small in real world use cases it should
245
-		// still be significantly better than disabling paging altogether
246
-
247
-		$limitToHome = $query->limitToHome();
248
-		if ($limitToHome && count(explode('/', $this->path)) !== 3) {
249
-			throw new \InvalidArgumentException('searching by owner is only allows on the users home folder');
250
-		}
251
-
252
-		$rootLength = strlen($this->path);
253
-		$mount = $this->root->getMount($this->path);
254
-		$storage = $mount->getStorage();
255
-		$internalPath = $mount->getInternalPath($this->path);
256
-		$internalPath = rtrim($internalPath, '/');
257
-		if ($internalPath !== '') {
258
-			$internalPath = $internalPath . '/';
259
-		}
260
-
261
-		$subQueryLimit = $query->getLimit() > 0 ? $query->getLimit() + $query->getOffset() : 0;
262
-		$rootQuery = new SearchQuery(
263
-			new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
264
-				new SearchComparison(ISearchComparison::COMPARE_LIKE, 'path', $internalPath . '%'),
265
-				$query->getSearchOperation(),
266
-			]
267
-			),
268
-			$subQueryLimit,
269
-			0,
270
-			$query->getOrder(),
271
-			$query->getUser()
272
-		);
273
-
274
-		$files = [];
275
-
276
-		$cache = $storage->getCache('');
277
-
278
-		$results = $cache->searchQuery($rootQuery);
279
-		foreach ($results as $result) {
280
-			$files[] = $this->cacheEntryToFileInfo($mount, '', $internalPath, $result);
281
-		}
282
-
283
-		if (!$limitToHome) {
284
-			$mounts = $this->root->getMountsIn($this->path);
285
-			foreach ($mounts as $mount) {
286
-				$subQuery = new SearchQuery(
287
-					$query->getSearchOperation(),
288
-					$subQueryLimit,
289
-					0,
290
-					$query->getOrder(),
291
-					$query->getUser()
292
-				);
293
-
294
-				$storage = $mount->getStorage();
295
-				if ($storage) {
296
-					$cache = $storage->getCache('');
297
-
298
-					$relativeMountPoint = ltrim(substr($mount->getMountPoint(), $rootLength), '/');
299
-					$results = $cache->searchQuery($subQuery);
300
-					foreach ($results as $result) {
301
-						$files[] = $this->cacheEntryToFileInfo($mount, $relativeMountPoint, '', $result);
302
-					}
303
-				}
304
-			}
305
-		}
306
-
307
-		$order = $query->getOrder();
308
-		if ($order) {
309
-			usort($files, function (FileInfo $a,FileInfo  $b) use ($order) {
310
-				foreach ($order as $orderField) {
311
-					$cmp = $orderField->sortFileInfo($a, $b);
312
-					if ($cmp !== 0) {
313
-						return $cmp;
314
-					}
315
-				}
316
-				return 0;
317
-			});
318
-		}
319
-		$files = array_values(array_slice($files, $query->getOffset(), $query->getLimit() > 0 ? $query->getLimit() : null));
320
-
321
-		return array_map(function (FileInfo $file) {
322
-			return $this->createNode($file->getPath(), $file);
323
-		}, $files);
324
-	}
325
-
326
-	private function cacheEntryToFileInfo(IMountPoint $mount, string $appendRoot, string $trimRoot, ICacheEntry $cacheEntry): FileInfo {
327
-		$trimLength = strlen($trimRoot);
328
-		$cacheEntry['internalPath'] = $cacheEntry['path'];
329
-		$cacheEntry['path'] = $appendRoot . substr($cacheEntry['path'], $trimLength);
330
-		return new \OC\Files\FileInfo($this->path . '/' . $cacheEntry['path'], $mount->getStorage(), $cacheEntry['internalPath'], $cacheEntry, $mount);
331
-	}
332
-
333
-	/**
334
-	 * search for files by mimetype
335
-	 *
336
-	 * @param string $mimetype
337
-	 * @return Node[]
338
-	 */
339
-	public function searchByMime($mimetype) {
340
-		if (strpos($mimetype, '/') === false) {
341
-			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%'));
342
-		} else {
343
-			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype));
344
-		}
345
-		return $this->search($query);
346
-	}
347
-
348
-	/**
349
-	 * search for files by tag
350
-	 *
351
-	 * @param string|int $tag name or tag id
352
-	 * @param string $userId owner of the tags
353
-	 * @return Node[]
354
-	 */
355
-	public function searchByTag($tag, $userId) {
356
-		$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'tagname', $tag), $userId);
357
-		return $this->search($query);
358
-	}
359
-
360
-	/**
361
-	 * @param int $id
362
-	 * @return \OC\Files\Node\Node[]
363
-	 */
364
-	public function getById($id) {
365
-		$mountCache = $this->root->getUserMountCache();
366
-		if (strpos($this->getPath(), '/', 1) > 0) {
367
-			[, $user] = explode('/', $this->getPath());
368
-		} else {
369
-			$user = null;
370
-		}
371
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
372
-		$mounts = $this->root->getMountsIn($this->path);
373
-		$mounts[] = $this->root->getMount($this->path);
374
-		/** @var IMountPoint[] $folderMounts */
375
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
376
-			return $mountPoint->getMountPoint();
377
-		}, $mounts), $mounts);
378
-
379
-		/** @var ICachedMountInfo[] $mountsContainingFile */
380
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
381
-			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
382
-		}));
383
-
384
-		if (count($mountsContainingFile) === 0) {
385
-			if ($user === $this->getAppDataDirectoryName()) {
386
-				return $this->getByIdInRootMount((int)$id);
387
-			}
388
-			return [];
389
-		}
390
-
391
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
392
-			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
393
-			$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
394
-			if (!$cacheEntry) {
395
-				return null;
396
-			}
397
-
398
-			// cache jails will hide the "true" internal path
399
-			$internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
400
-			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
401
-			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
402
-			$absolutePath = rtrim($cachedMountInfo->getMountPoint() . $pathRelativeToMount, '/');
403
-			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
404
-				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
405
-				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
406
-			));
407
-		}, $mountsContainingFile);
408
-
409
-		$nodes = array_filter($nodes);
410
-
411
-		return array_filter($nodes, function (Node $node) {
412
-			return $this->getRelativePath($node->getPath());
413
-		});
414
-	}
415
-
416
-	protected function getAppDataDirectoryName(): string {
417
-		$instanceId = \OC::$server->getConfig()->getSystemValueString('instanceid');
418
-		return 'appdata_' . $instanceId;
419
-	}
420
-
421
-	/**
422
-	 * In case the path we are currently in is inside the appdata_* folder,
423
-	 * the original getById method does not work, because it can only look inside
424
-	 * the user's mount points. But the user has no mount point for the root storage.
425
-	 *
426
-	 * So in that case we directly check the mount of the root if it contains
427
-	 * the id. If it does we check if the path is inside the path we are working
428
-	 * in.
429
-	 *
430
-	 * @param int $id
431
-	 * @return array
432
-	 */
433
-	protected function getByIdInRootMount(int $id): array {
434
-		$mount = $this->root->getMount('');
435
-		$cacheEntry = $mount->getStorage()->getCache($this->path)->get($id);
436
-		if (!$cacheEntry) {
437
-			return [];
438
-		}
439
-
440
-		$absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
441
-		$currentPath = rtrim($this->path, '/') . '/';
442
-
443
-		if (strpos($absolutePath, $currentPath) !== 0) {
444
-			return [];
445
-		}
446
-
447
-		return [$this->root->createNode(
448
-			$absolutePath, new \OC\Files\FileInfo(
449
-			$absolutePath,
450
-			$mount->getStorage(),
451
-			$cacheEntry->getPath(),
452
-			$cacheEntry,
453
-			$mount
454
-		))];
455
-	}
456
-
457
-	public function getFreeSpace() {
458
-		return $this->view->free_space($this->path);
459
-	}
460
-
461
-	public function delete() {
462
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
463
-			$this->sendHooks(['preDelete']);
464
-			$fileInfo = $this->getFileInfo();
465
-			$this->view->rmdir($this->path);
466
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
467
-			$this->sendHooks(['postDelete'], [$nonExisting]);
468
-			$this->exists = false;
469
-		} else {
470
-			throw new NotPermittedException('No delete permission for path');
471
-		}
472
-	}
473
-
474
-	/**
475
-	 * Add a suffix to the name in case the file exists
476
-	 *
477
-	 * @param string $name
478
-	 * @return string
479
-	 * @throws NotPermittedException
480
-	 */
481
-	public function getNonExistingName($name) {
482
-		$uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
483
-		return trim($this->getRelativePath($uniqueName), '/');
484
-	}
485
-
486
-	/**
487
-	 * @param int $limit
488
-	 * @param int $offset
489
-	 * @return \OCP\Files\Node[]
490
-	 */
491
-	public function getRecent($limit, $offset = 0) {
492
-		$mimetypeLoader = \OC::$server->getMimeTypeLoader();
493
-		$mounts = $this->root->getMountsIn($this->path);
494
-		$mounts[] = $this->getMountPoint();
495
-
496
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
497
-			return $mount->getStorage();
498
-		});
499
-		$storageIds = array_map(function (IMountPoint $mount) {
500
-			return $mount->getStorage()->getCache()->getNumericStorageId();
501
-		}, $mounts);
502
-		/** @var IMountPoint[] $mountMap */
503
-		$mountMap = array_combine($storageIds, $mounts);
504
-		$folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
505
-
506
-		/*
55
+    /**
56
+     * Creates a Folder that represents a non-existing path
57
+     *
58
+     * @param string $path path
59
+     * @return string non-existing node class
60
+     */
61
+    protected function createNonExistingNode($path) {
62
+        return new NonExistingFolder($this->root, $this->view, $path);
63
+    }
64
+
65
+    /**
66
+     * @param string $path path relative to the folder
67
+     * @return string
68
+     * @throws \OCP\Files\NotPermittedException
69
+     */
70
+    public function getFullPath($path) {
71
+        if (!$this->isValidPath($path)) {
72
+            throw new NotPermittedException('Invalid path');
73
+        }
74
+        return $this->path . $this->normalizePath($path);
75
+    }
76
+
77
+    /**
78
+     * @param string $path
79
+     * @return string
80
+     */
81
+    public function getRelativePath($path) {
82
+        if ($this->path === '' or $this->path === '/') {
83
+            return $this->normalizePath($path);
84
+        }
85
+        if ($path === $this->path) {
86
+            return '/';
87
+        } elseif (strpos($path, $this->path . '/') !== 0) {
88
+            return null;
89
+        } else {
90
+            $path = substr($path, strlen($this->path));
91
+            return $this->normalizePath($path);
92
+        }
93
+    }
94
+
95
+    /**
96
+     * check if a node is a (grand-)child of the folder
97
+     *
98
+     * @param \OC\Files\Node\Node $node
99
+     * @return bool
100
+     */
101
+    public function isSubNode($node) {
102
+        return strpos($node->getPath(), $this->path . '/') === 0;
103
+    }
104
+
105
+    /**
106
+     * get the content of this directory
107
+     *
108
+     * @return Node[]
109
+     * @throws \OCP\Files\NotFoundException
110
+     */
111
+    public function getDirectoryListing() {
112
+        $folderContent = $this->view->getDirectoryContent($this->path);
113
+
114
+        return array_map(function (FileInfo $info) {
115
+            if ($info->getMimetype() === 'httpd/unix-directory') {
116
+                return new Folder($this->root, $this->view, $info->getPath(), $info);
117
+            } else {
118
+                return new File($this->root, $this->view, $info->getPath(), $info);
119
+            }
120
+        }, $folderContent);
121
+    }
122
+
123
+    /**
124
+     * @param string $path
125
+     * @param FileInfo $info
126
+     * @return File|Folder
127
+     */
128
+    protected function createNode($path, FileInfo $info = null) {
129
+        if (is_null($info)) {
130
+            $isDir = $this->view->is_dir($path);
131
+        } else {
132
+            $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
133
+        }
134
+        if ($isDir) {
135
+            return new Folder($this->root, $this->view, $path, $info);
136
+        } else {
137
+            return new File($this->root, $this->view, $path, $info);
138
+        }
139
+    }
140
+
141
+    /**
142
+     * Get the node at $path
143
+     *
144
+     * @param string $path
145
+     * @return \OC\Files\Node\Node
146
+     * @throws \OCP\Files\NotFoundException
147
+     */
148
+    public function get($path) {
149
+        return $this->root->get($this->getFullPath($path));
150
+    }
151
+
152
+    /**
153
+     * @param string $path
154
+     * @return bool
155
+     */
156
+    public function nodeExists($path) {
157
+        try {
158
+            $this->get($path);
159
+            return true;
160
+        } catch (NotFoundException $e) {
161
+            return false;
162
+        }
163
+    }
164
+
165
+    /**
166
+     * @param string $path
167
+     * @return \OC\Files\Node\Folder
168
+     * @throws \OCP\Files\NotPermittedException
169
+     */
170
+    public function newFolder($path) {
171
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
172
+            $fullPath = $this->getFullPath($path);
173
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
174
+            $this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]);
175
+            if (!$this->view->mkdir($fullPath)) {
176
+                throw new NotPermittedException('Could not create folder');
177
+            }
178
+            $node = new Folder($this->root, $this->view, $fullPath);
179
+            $this->sendHooks(['postWrite', 'postCreate'], [$node]);
180
+            return $node;
181
+        } else {
182
+            throw new NotPermittedException('No create permission for folder');
183
+        }
184
+    }
185
+
186
+    /**
187
+     * @param string $path
188
+     * @param string | resource | null $content
189
+     * @return \OC\Files\Node\File
190
+     * @throws \OCP\Files\NotPermittedException
191
+     */
192
+    public function newFile($path, $content = null) {
193
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
194
+            $fullPath = $this->getFullPath($path);
195
+            $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
196
+            $this->sendHooks(['preWrite', 'preCreate'], [$nonExisting]);
197
+            if ($content !== null) {
198
+                $result = $this->view->file_put_contents($fullPath, $content);
199
+            } else {
200
+                $result = $this->view->touch($fullPath);
201
+            }
202
+            if ($result === false) {
203
+                throw new NotPermittedException('Could not create path');
204
+            }
205
+            $node = new File($this->root, $this->view, $fullPath);
206
+            $this->sendHooks(['postWrite', 'postCreate'], [$node]);
207
+            return $node;
208
+        }
209
+        throw new NotPermittedException('No create permission for path');
210
+    }
211
+
212
+    private function queryFromOperator(ISearchOperator $operator, string $uid = null): ISearchQuery {
213
+        if ($uid === null) {
214
+            $user = null;
215
+        } else {
216
+            /** @var IUserManager $userManager */
217
+            $userManager = \OC::$server->query(IUserManager::class);
218
+            $user = $userManager->get($uid);
219
+        }
220
+        return new SearchQuery($operator, 0, 0, [], $user);
221
+    }
222
+
223
+    /**
224
+     * search for files with the name matching $query
225
+     *
226
+     * @param string|ISearchQuery $query
227
+     * @return \OC\Files\Node\Node[]
228
+     */
229
+    public function search($query) {
230
+        if (is_string($query)) {
231
+            $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'));
232
+        }
233
+
234
+        // Limit+offset for queries with ordering
235
+        //
236
+        // Because we currently can't do ordering between the results from different storages in sql
237
+        // The only way to do ordering is requesting the $limit number of entries from all storages
238
+        // sorting them and returning the first $limit entries.
239
+        //
240
+        // For offset we have the same problem, we don't know how many entries from each storage should be skipped
241
+        // by a given $offset, so instead we query $offset + $limit from each storage and return entries $offset..($offset+$limit)
242
+        // after merging and sorting them.
243
+        //
244
+        // This is suboptimal but because limit and offset tend to be fairly small in real world use cases it should
245
+        // still be significantly better than disabling paging altogether
246
+
247
+        $limitToHome = $query->limitToHome();
248
+        if ($limitToHome && count(explode('/', $this->path)) !== 3) {
249
+            throw new \InvalidArgumentException('searching by owner is only allows on the users home folder');
250
+        }
251
+
252
+        $rootLength = strlen($this->path);
253
+        $mount = $this->root->getMount($this->path);
254
+        $storage = $mount->getStorage();
255
+        $internalPath = $mount->getInternalPath($this->path);
256
+        $internalPath = rtrim($internalPath, '/');
257
+        if ($internalPath !== '') {
258
+            $internalPath = $internalPath . '/';
259
+        }
260
+
261
+        $subQueryLimit = $query->getLimit() > 0 ? $query->getLimit() + $query->getOffset() : 0;
262
+        $rootQuery = new SearchQuery(
263
+            new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
264
+                new SearchComparison(ISearchComparison::COMPARE_LIKE, 'path', $internalPath . '%'),
265
+                $query->getSearchOperation(),
266
+            ]
267
+            ),
268
+            $subQueryLimit,
269
+            0,
270
+            $query->getOrder(),
271
+            $query->getUser()
272
+        );
273
+
274
+        $files = [];
275
+
276
+        $cache = $storage->getCache('');
277
+
278
+        $results = $cache->searchQuery($rootQuery);
279
+        foreach ($results as $result) {
280
+            $files[] = $this->cacheEntryToFileInfo($mount, '', $internalPath, $result);
281
+        }
282
+
283
+        if (!$limitToHome) {
284
+            $mounts = $this->root->getMountsIn($this->path);
285
+            foreach ($mounts as $mount) {
286
+                $subQuery = new SearchQuery(
287
+                    $query->getSearchOperation(),
288
+                    $subQueryLimit,
289
+                    0,
290
+                    $query->getOrder(),
291
+                    $query->getUser()
292
+                );
293
+
294
+                $storage = $mount->getStorage();
295
+                if ($storage) {
296
+                    $cache = $storage->getCache('');
297
+
298
+                    $relativeMountPoint = ltrim(substr($mount->getMountPoint(), $rootLength), '/');
299
+                    $results = $cache->searchQuery($subQuery);
300
+                    foreach ($results as $result) {
301
+                        $files[] = $this->cacheEntryToFileInfo($mount, $relativeMountPoint, '', $result);
302
+                    }
303
+                }
304
+            }
305
+        }
306
+
307
+        $order = $query->getOrder();
308
+        if ($order) {
309
+            usort($files, function (FileInfo $a,FileInfo  $b) use ($order) {
310
+                foreach ($order as $orderField) {
311
+                    $cmp = $orderField->sortFileInfo($a, $b);
312
+                    if ($cmp !== 0) {
313
+                        return $cmp;
314
+                    }
315
+                }
316
+                return 0;
317
+            });
318
+        }
319
+        $files = array_values(array_slice($files, $query->getOffset(), $query->getLimit() > 0 ? $query->getLimit() : null));
320
+
321
+        return array_map(function (FileInfo $file) {
322
+            return $this->createNode($file->getPath(), $file);
323
+        }, $files);
324
+    }
325
+
326
+    private function cacheEntryToFileInfo(IMountPoint $mount, string $appendRoot, string $trimRoot, ICacheEntry $cacheEntry): FileInfo {
327
+        $trimLength = strlen($trimRoot);
328
+        $cacheEntry['internalPath'] = $cacheEntry['path'];
329
+        $cacheEntry['path'] = $appendRoot . substr($cacheEntry['path'], $trimLength);
330
+        return new \OC\Files\FileInfo($this->path . '/' . $cacheEntry['path'], $mount->getStorage(), $cacheEntry['internalPath'], $cacheEntry, $mount);
331
+    }
332
+
333
+    /**
334
+     * search for files by mimetype
335
+     *
336
+     * @param string $mimetype
337
+     * @return Node[]
338
+     */
339
+    public function searchByMime($mimetype) {
340
+        if (strpos($mimetype, '/') === false) {
341
+            $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%'));
342
+        } else {
343
+            $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype));
344
+        }
345
+        return $this->search($query);
346
+    }
347
+
348
+    /**
349
+     * search for files by tag
350
+     *
351
+     * @param string|int $tag name or tag id
352
+     * @param string $userId owner of the tags
353
+     * @return Node[]
354
+     */
355
+    public function searchByTag($tag, $userId) {
356
+        $query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'tagname', $tag), $userId);
357
+        return $this->search($query);
358
+    }
359
+
360
+    /**
361
+     * @param int $id
362
+     * @return \OC\Files\Node\Node[]
363
+     */
364
+    public function getById($id) {
365
+        $mountCache = $this->root->getUserMountCache();
366
+        if (strpos($this->getPath(), '/', 1) > 0) {
367
+            [, $user] = explode('/', $this->getPath());
368
+        } else {
369
+            $user = null;
370
+        }
371
+        $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
372
+        $mounts = $this->root->getMountsIn($this->path);
373
+        $mounts[] = $this->root->getMount($this->path);
374
+        /** @var IMountPoint[] $folderMounts */
375
+        $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
376
+            return $mountPoint->getMountPoint();
377
+        }, $mounts), $mounts);
378
+
379
+        /** @var ICachedMountInfo[] $mountsContainingFile */
380
+        $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
381
+            return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
382
+        }));
383
+
384
+        if (count($mountsContainingFile) === 0) {
385
+            if ($user === $this->getAppDataDirectoryName()) {
386
+                return $this->getByIdInRootMount((int)$id);
387
+            }
388
+            return [];
389
+        }
390
+
391
+        $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
392
+            $mount = $folderMounts[$cachedMountInfo->getMountPoint()];
393
+            $cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
394
+            if (!$cacheEntry) {
395
+                return null;
396
+            }
397
+
398
+            // cache jails will hide the "true" internal path
399
+            $internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
400
+            $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
401
+            $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
402
+            $absolutePath = rtrim($cachedMountInfo->getMountPoint() . $pathRelativeToMount, '/');
403
+            return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
404
+                $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
405
+                \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
406
+            ));
407
+        }, $mountsContainingFile);
408
+
409
+        $nodes = array_filter($nodes);
410
+
411
+        return array_filter($nodes, function (Node $node) {
412
+            return $this->getRelativePath($node->getPath());
413
+        });
414
+    }
415
+
416
+    protected function getAppDataDirectoryName(): string {
417
+        $instanceId = \OC::$server->getConfig()->getSystemValueString('instanceid');
418
+        return 'appdata_' . $instanceId;
419
+    }
420
+
421
+    /**
422
+     * In case the path we are currently in is inside the appdata_* folder,
423
+     * the original getById method does not work, because it can only look inside
424
+     * the user's mount points. But the user has no mount point for the root storage.
425
+     *
426
+     * So in that case we directly check the mount of the root if it contains
427
+     * the id. If it does we check if the path is inside the path we are working
428
+     * in.
429
+     *
430
+     * @param int $id
431
+     * @return array
432
+     */
433
+    protected function getByIdInRootMount(int $id): array {
434
+        $mount = $this->root->getMount('');
435
+        $cacheEntry = $mount->getStorage()->getCache($this->path)->get($id);
436
+        if (!$cacheEntry) {
437
+            return [];
438
+        }
439
+
440
+        $absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
441
+        $currentPath = rtrim($this->path, '/') . '/';
442
+
443
+        if (strpos($absolutePath, $currentPath) !== 0) {
444
+            return [];
445
+        }
446
+
447
+        return [$this->root->createNode(
448
+            $absolutePath, new \OC\Files\FileInfo(
449
+            $absolutePath,
450
+            $mount->getStorage(),
451
+            $cacheEntry->getPath(),
452
+            $cacheEntry,
453
+            $mount
454
+        ))];
455
+    }
456
+
457
+    public function getFreeSpace() {
458
+        return $this->view->free_space($this->path);
459
+    }
460
+
461
+    public function delete() {
462
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
463
+            $this->sendHooks(['preDelete']);
464
+            $fileInfo = $this->getFileInfo();
465
+            $this->view->rmdir($this->path);
466
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
467
+            $this->sendHooks(['postDelete'], [$nonExisting]);
468
+            $this->exists = false;
469
+        } else {
470
+            throw new NotPermittedException('No delete permission for path');
471
+        }
472
+    }
473
+
474
+    /**
475
+     * Add a suffix to the name in case the file exists
476
+     *
477
+     * @param string $name
478
+     * @return string
479
+     * @throws NotPermittedException
480
+     */
481
+    public function getNonExistingName($name) {
482
+        $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
483
+        return trim($this->getRelativePath($uniqueName), '/');
484
+    }
485
+
486
+    /**
487
+     * @param int $limit
488
+     * @param int $offset
489
+     * @return \OCP\Files\Node[]
490
+     */
491
+    public function getRecent($limit, $offset = 0) {
492
+        $mimetypeLoader = \OC::$server->getMimeTypeLoader();
493
+        $mounts = $this->root->getMountsIn($this->path);
494
+        $mounts[] = $this->getMountPoint();
495
+
496
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
497
+            return $mount->getStorage();
498
+        });
499
+        $storageIds = array_map(function (IMountPoint $mount) {
500
+            return $mount->getStorage()->getCache()->getNumericStorageId();
501
+        }, $mounts);
502
+        /** @var IMountPoint[] $mountMap */
503
+        $mountMap = array_combine($storageIds, $mounts);
504
+        $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
505
+
506
+        /*
507 507
 		 * Construct an array of the storage id with their prefix path
508 508
 		 * This helps us to filter in the final query
509 509
 		 */
510
-		$filters = array_map(function (IMountPoint $mount) {
511
-			$storage = $mount->getStorage();
512
-
513
-			$storageId = $storage->getCache()->getNumericStorageId();
514
-			$prefix = '';
515
-
516
-			if ($storage->instanceOfStorage(Jail::class)) {
517
-				$prefix = $storage->getUnJailedPath('');
518
-			}
519
-
520
-			return [
521
-				'storageId' => $storageId,
522
-				'pathPrefix' => $prefix,
523
-			];
524
-		}, $mounts);
525
-
526
-		// Search in batches of 500 entries
527
-		$searchLimit = 500;
528
-		$results = [];
529
-		$searchResultCount = 0;
530
-		$count = 0;
531
-		do {
532
-			$searchResult = $this->recentSearch($searchLimit, $offset, $folderMimetype, $filters);
533
-
534
-			// Exit condition if there are no more results
535
-			if (count($searchResult) === 0) {
536
-				break;
537
-			}
538
-
539
-			$searchResultCount += count($searchResult);
540
-
541
-			$parseResult = $this->recentParse($searchResult, $mountMap, $mimetypeLoader);
542
-
543
-			foreach ($parseResult as $result) {
544
-				$results[] = $result;
545
-			}
546
-
547
-			$offset += $searchLimit;
548
-			$count++;
549
-		} while (count($results) < $limit && ($searchResultCount < (3 * $limit) || $count < 5));
550
-
551
-		return array_slice($results, 0, $limit);
552
-	}
553
-
554
-	private function recentSearch($limit, $offset, $folderMimetype, $filters) {
555
-		$dbconn = \OC::$server->getDatabaseConnection();
556
-		$builder = $dbconn->getQueryBuilder();
557
-		$query = $builder
558
-			->select('f.*')
559
-			->from('filecache', 'f');
560
-
561
-		/*
510
+        $filters = array_map(function (IMountPoint $mount) {
511
+            $storage = $mount->getStorage();
512
+
513
+            $storageId = $storage->getCache()->getNumericStorageId();
514
+            $prefix = '';
515
+
516
+            if ($storage->instanceOfStorage(Jail::class)) {
517
+                $prefix = $storage->getUnJailedPath('');
518
+            }
519
+
520
+            return [
521
+                'storageId' => $storageId,
522
+                'pathPrefix' => $prefix,
523
+            ];
524
+        }, $mounts);
525
+
526
+        // Search in batches of 500 entries
527
+        $searchLimit = 500;
528
+        $results = [];
529
+        $searchResultCount = 0;
530
+        $count = 0;
531
+        do {
532
+            $searchResult = $this->recentSearch($searchLimit, $offset, $folderMimetype, $filters);
533
+
534
+            // Exit condition if there are no more results
535
+            if (count($searchResult) === 0) {
536
+                break;
537
+            }
538
+
539
+            $searchResultCount += count($searchResult);
540
+
541
+            $parseResult = $this->recentParse($searchResult, $mountMap, $mimetypeLoader);
542
+
543
+            foreach ($parseResult as $result) {
544
+                $results[] = $result;
545
+            }
546
+
547
+            $offset += $searchLimit;
548
+            $count++;
549
+        } while (count($results) < $limit && ($searchResultCount < (3 * $limit) || $count < 5));
550
+
551
+        return array_slice($results, 0, $limit);
552
+    }
553
+
554
+    private function recentSearch($limit, $offset, $folderMimetype, $filters) {
555
+        $dbconn = \OC::$server->getDatabaseConnection();
556
+        $builder = $dbconn->getQueryBuilder();
557
+        $query = $builder
558
+            ->select('f.*')
559
+            ->from('filecache', 'f');
560
+
561
+        /*
562 562
 		 * Here is where we construct the filtering.
563 563
 		 * Note that this is expensive filtering as it is a lot of like queries.
564 564
 		 * However the alternative is we do this filtering and parsing later in php with the risk of looping endlessly
565 565
 		 */
566
-		$storageFilters = $builder->expr()->orX();
567
-		foreach ($filters as $filter) {
568
-			$storageFilter = $builder->expr()->andX(
569
-				$builder->expr()->eq('f.storage', $builder->createNamedParameter($filter['storageId']))
570
-			);
571
-
572
-			if ($filter['pathPrefix'] !== '') {
573
-				$storageFilter->add(
574
-					$builder->expr()->like('f.path', $builder->createNamedParameter($dbconn->escapeLikeParameter($filter['pathPrefix']) . '/%'))
575
-				);
576
-			}
577
-
578
-			$storageFilters->add($storageFilter);
579
-		}
580
-
581
-		$query->andWhere($storageFilters);
582
-
583
-		$query->andWhere($builder->expr()->orX(
584
-		// handle non empty folders separate
585
-			$builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
586
-			$builder->expr()->eq('f.size', new Literal(0))
587
-		))
588
-			->andWhere($builder->expr()->notLike('f.path', $builder->createNamedParameter('files_versions/%')))
589
-			->andWhere($builder->expr()->notLike('f.path', $builder->createNamedParameter('files_trashbin/%')))
590
-			->orderBy('f.mtime', 'DESC')
591
-			->setMaxResults($limit)
592
-			->setFirstResult($offset);
593
-
594
-		$result = $query->execute();
595
-		$rows = $result->fetchAll();
596
-		$result->closeCursor();
597
-
598
-		return $rows;
599
-	}
600
-
601
-	private function recentParse($result, $mountMap, $mimetypeLoader) {
602
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
603
-			$mount = $mountMap[$entry['storage']];
604
-			$entry['internalPath'] = $entry['path'];
605
-			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
606
-			$entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
607
-			$path = $this->getAbsolutePath($mount, $entry['path']);
608
-			if (is_null($path)) {
609
-				return null;
610
-			}
611
-			$fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
612
-			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
613
-		}, $result));
614
-
615
-		return array_values(array_filter($files, function (Node $node) {
616
-			$cacheEntry = $node->getMountPoint()->getStorage()->getCache()->get($node->getId());
617
-			if (!$cacheEntry) {
618
-				return false;
619
-			}
620
-			$relative = $this->getRelativePath($node->getPath());
621
-			return $relative !== null && $relative !== '/'
622
-				&& ($cacheEntry->getPermissions() & \OCP\Constants::PERMISSION_READ) === \OCP\Constants::PERMISSION_READ;
623
-		}));
624
-	}
625
-
626
-	private function getAbsolutePath(IMountPoint $mount, $path) {
627
-		$storage = $mount->getStorage();
628
-		if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
629
-			if ($storage->instanceOfStorage(SharedStorage::class)) {
630
-				$storage->getSourceStorage();
631
-			}
632
-			/** @var \OC\Files\Storage\Wrapper\Jail $storage */
633
-			$jailRoot = $storage->getUnjailedPath('');
634
-			$rootLength = strlen($jailRoot) + 1;
635
-			if ($path === $jailRoot) {
636
-				return $mount->getMountPoint();
637
-			} elseif (substr($path, 0, $rootLength) === $jailRoot . '/') {
638
-				return $mount->getMountPoint() . substr($path, $rootLength);
639
-			} else {
640
-				return null;
641
-			}
642
-		} else {
643
-			return $mount->getMountPoint() . $path;
644
-		}
645
-	}
566
+        $storageFilters = $builder->expr()->orX();
567
+        foreach ($filters as $filter) {
568
+            $storageFilter = $builder->expr()->andX(
569
+                $builder->expr()->eq('f.storage', $builder->createNamedParameter($filter['storageId']))
570
+            );
571
+
572
+            if ($filter['pathPrefix'] !== '') {
573
+                $storageFilter->add(
574
+                    $builder->expr()->like('f.path', $builder->createNamedParameter($dbconn->escapeLikeParameter($filter['pathPrefix']) . '/%'))
575
+                );
576
+            }
577
+
578
+            $storageFilters->add($storageFilter);
579
+        }
580
+
581
+        $query->andWhere($storageFilters);
582
+
583
+        $query->andWhere($builder->expr()->orX(
584
+        // handle non empty folders separate
585
+            $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
586
+            $builder->expr()->eq('f.size', new Literal(0))
587
+        ))
588
+            ->andWhere($builder->expr()->notLike('f.path', $builder->createNamedParameter('files_versions/%')))
589
+            ->andWhere($builder->expr()->notLike('f.path', $builder->createNamedParameter('files_trashbin/%')))
590
+            ->orderBy('f.mtime', 'DESC')
591
+            ->setMaxResults($limit)
592
+            ->setFirstResult($offset);
593
+
594
+        $result = $query->execute();
595
+        $rows = $result->fetchAll();
596
+        $result->closeCursor();
597
+
598
+        return $rows;
599
+    }
600
+
601
+    private function recentParse($result, $mountMap, $mimetypeLoader) {
602
+        $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
603
+            $mount = $mountMap[$entry['storage']];
604
+            $entry['internalPath'] = $entry['path'];
605
+            $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
606
+            $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
607
+            $path = $this->getAbsolutePath($mount, $entry['path']);
608
+            if (is_null($path)) {
609
+                return null;
610
+            }
611
+            $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
612
+            return $this->root->createNode($fileInfo->getPath(), $fileInfo);
613
+        }, $result));
614
+
615
+        return array_values(array_filter($files, function (Node $node) {
616
+            $cacheEntry = $node->getMountPoint()->getStorage()->getCache()->get($node->getId());
617
+            if (!$cacheEntry) {
618
+                return false;
619
+            }
620
+            $relative = $this->getRelativePath($node->getPath());
621
+            return $relative !== null && $relative !== '/'
622
+                && ($cacheEntry->getPermissions() & \OCP\Constants::PERMISSION_READ) === \OCP\Constants::PERMISSION_READ;
623
+        }));
624
+    }
625
+
626
+    private function getAbsolutePath(IMountPoint $mount, $path) {
627
+        $storage = $mount->getStorage();
628
+        if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
629
+            if ($storage->instanceOfStorage(SharedStorage::class)) {
630
+                $storage->getSourceStorage();
631
+            }
632
+            /** @var \OC\Files\Storage\Wrapper\Jail $storage */
633
+            $jailRoot = $storage->getUnjailedPath('');
634
+            $rootLength = strlen($jailRoot) + 1;
635
+            if ($path === $jailRoot) {
636
+                return $mount->getMountPoint();
637
+            } elseif (substr($path, 0, $rootLength) === $jailRoot . '/') {
638
+                return $mount->getMountPoint() . substr($path, $rootLength);
639
+            } else {
640
+                return null;
641
+            }
642
+        } else {
643
+            return $mount->getMountPoint() . $path;
644
+        }
645
+    }
646 646
 }
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 		if (!$this->isValidPath($path)) {
72 72
 			throw new NotPermittedException('Invalid path');
73 73
 		}
74
-		return $this->path . $this->normalizePath($path);
74
+		return $this->path.$this->normalizePath($path);
75 75
 	}
76 76
 
77 77
 	/**
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
 		}
85 85
 		if ($path === $this->path) {
86 86
 			return '/';
87
-		} elseif (strpos($path, $this->path . '/') !== 0) {
87
+		} elseif (strpos($path, $this->path.'/') !== 0) {
88 88
 			return null;
89 89
 		} else {
90 90
 			$path = substr($path, strlen($this->path));
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 	 * @return bool
100 100
 	 */
101 101
 	public function isSubNode($node) {
102
-		return strpos($node->getPath(), $this->path . '/') === 0;
102
+		return strpos($node->getPath(), $this->path.'/') === 0;
103 103
 	}
104 104
 
105 105
 	/**
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 	public function getDirectoryListing() {
112 112
 		$folderContent = $this->view->getDirectoryContent($this->path);
113 113
 
114
-		return array_map(function (FileInfo $info) {
114
+		return array_map(function(FileInfo $info) {
115 115
 			if ($info->getMimetype() === 'httpd/unix-directory') {
116 116
 				return new Folder($this->root, $this->view, $info->getPath(), $info);
117 117
 			} else {
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	 */
229 229
 	public function search($query) {
230 230
 		if (is_string($query)) {
231
-			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'));
231
+			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%'.$query.'%'));
232 232
 		}
233 233
 
234 234
 		// Limit+offset for queries with ordering
@@ -255,13 +255,13 @@  discard block
 block discarded – undo
255 255
 		$internalPath = $mount->getInternalPath($this->path);
256 256
 		$internalPath = rtrim($internalPath, '/');
257 257
 		if ($internalPath !== '') {
258
-			$internalPath = $internalPath . '/';
258
+			$internalPath = $internalPath.'/';
259 259
 		}
260 260
 
261 261
 		$subQueryLimit = $query->getLimit() > 0 ? $query->getLimit() + $query->getOffset() : 0;
262 262
 		$rootQuery = new SearchQuery(
263 263
 			new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_AND, [
264
-				new SearchComparison(ISearchComparison::COMPARE_LIKE, 'path', $internalPath . '%'),
264
+				new SearchComparison(ISearchComparison::COMPARE_LIKE, 'path', $internalPath.'%'),
265 265
 				$query->getSearchOperation(),
266 266
 			]
267 267
 			),
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
 
307 307
 		$order = $query->getOrder();
308 308
 		if ($order) {
309
-			usort($files, function (FileInfo $a,FileInfo  $b) use ($order) {
309
+			usort($files, function(FileInfo $a, FileInfo  $b) use ($order) {
310 310
 				foreach ($order as $orderField) {
311 311
 					$cmp = $orderField->sortFileInfo($a, $b);
312 312
 					if ($cmp !== 0) {
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 		}
319 319
 		$files = array_values(array_slice($files, $query->getOffset(), $query->getLimit() > 0 ? $query->getLimit() : null));
320 320
 
321
-		return array_map(function (FileInfo $file) {
321
+		return array_map(function(FileInfo $file) {
322 322
 			return $this->createNode($file->getPath(), $file);
323 323
 		}, $files);
324 324
 	}
@@ -326,8 +326,8 @@  discard block
 block discarded – undo
326 326
 	private function cacheEntryToFileInfo(IMountPoint $mount, string $appendRoot, string $trimRoot, ICacheEntry $cacheEntry): FileInfo {
327 327
 		$trimLength = strlen($trimRoot);
328 328
 		$cacheEntry['internalPath'] = $cacheEntry['path'];
329
-		$cacheEntry['path'] = $appendRoot . substr($cacheEntry['path'], $trimLength);
330
-		return new \OC\Files\FileInfo($this->path . '/' . $cacheEntry['path'], $mount->getStorage(), $cacheEntry['internalPath'], $cacheEntry, $mount);
329
+		$cacheEntry['path'] = $appendRoot.substr($cacheEntry['path'], $trimLength);
330
+		return new \OC\Files\FileInfo($this->path.'/'.$cacheEntry['path'], $mount->getStorage(), $cacheEntry['internalPath'], $cacheEntry, $mount);
331 331
 	}
332 332
 
333 333
 	/**
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
 	 */
339 339
 	public function searchByMime($mimetype) {
340 340
 		if (strpos($mimetype, '/') === false) {
341
-			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%'));
341
+			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype.'/%'));
342 342
 		} else {
343 343
 			$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype));
344 344
 		}
@@ -368,38 +368,38 @@  discard block
 block discarded – undo
368 368
 		} else {
369 369
 			$user = null;
370 370
 		}
371
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
371
+		$mountsContainingFile = $mountCache->getMountsForFileId((int) $id, $user);
372 372
 		$mounts = $this->root->getMountsIn($this->path);
373 373
 		$mounts[] = $this->root->getMount($this->path);
374 374
 		/** @var IMountPoint[] $folderMounts */
375
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
375
+		$folderMounts = array_combine(array_map(function(IMountPoint $mountPoint) {
376 376
 			return $mountPoint->getMountPoint();
377 377
 		}, $mounts), $mounts);
378 378
 
379 379
 		/** @var ICachedMountInfo[] $mountsContainingFile */
380
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
380
+		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function(ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
381 381
 			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
382 382
 		}));
383 383
 
384 384
 		if (count($mountsContainingFile) === 0) {
385 385
 			if ($user === $this->getAppDataDirectoryName()) {
386
-				return $this->getByIdInRootMount((int)$id);
386
+				return $this->getByIdInRootMount((int) $id);
387 387
 			}
388 388
 			return [];
389 389
 		}
390 390
 
391
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
391
+		$nodes = array_map(function(ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
392 392
 			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
393
-			$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
393
+			$cacheEntry = $mount->getStorage()->getCache()->get((int) $id);
394 394
 			if (!$cacheEntry) {
395 395
 				return null;
396 396
 			}
397 397
 
398 398
 			// cache jails will hide the "true" internal path
399
-			$internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
399
+			$internalPath = ltrim($cachedMountInfo->getRootInternalPath().'/'.$cacheEntry->getPath(), '/');
400 400
 			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
401 401
 			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
402
-			$absolutePath = rtrim($cachedMountInfo->getMountPoint() . $pathRelativeToMount, '/');
402
+			$absolutePath = rtrim($cachedMountInfo->getMountPoint().$pathRelativeToMount, '/');
403 403
 			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
404 404
 				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
405 405
 				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
@@ -408,14 +408,14 @@  discard block
 block discarded – undo
408 408
 
409 409
 		$nodes = array_filter($nodes);
410 410
 
411
-		return array_filter($nodes, function (Node $node) {
411
+		return array_filter($nodes, function(Node $node) {
412 412
 			return $this->getRelativePath($node->getPath());
413 413
 		});
414 414
 	}
415 415
 
416 416
 	protected function getAppDataDirectoryName(): string {
417 417
 		$instanceId = \OC::$server->getConfig()->getSystemValueString('instanceid');
418
-		return 'appdata_' . $instanceId;
418
+		return 'appdata_'.$instanceId;
419 419
 	}
420 420
 
421 421
 	/**
@@ -437,8 +437,8 @@  discard block
 block discarded – undo
437 437
 			return [];
438 438
 		}
439 439
 
440
-		$absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
441
-		$currentPath = rtrim($this->path, '/') . '/';
440
+		$absolutePath = '/'.ltrim($cacheEntry->getPath(), '/');
441
+		$currentPath = rtrim($this->path, '/').'/';
442 442
 
443 443
 		if (strpos($absolutePath, $currentPath) !== 0) {
444 444
 			return [];
@@ -493,10 +493,10 @@  discard block
 block discarded – undo
493 493
 		$mounts = $this->root->getMountsIn($this->path);
494 494
 		$mounts[] = $this->getMountPoint();
495 495
 
496
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
496
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
497 497
 			return $mount->getStorage();
498 498
 		});
499
-		$storageIds = array_map(function (IMountPoint $mount) {
499
+		$storageIds = array_map(function(IMountPoint $mount) {
500 500
 			return $mount->getStorage()->getCache()->getNumericStorageId();
501 501
 		}, $mounts);
502 502
 		/** @var IMountPoint[] $mountMap */
@@ -507,7 +507,7 @@  discard block
 block discarded – undo
507 507
 		 * Construct an array of the storage id with their prefix path
508 508
 		 * This helps us to filter in the final query
509 509
 		 */
510
-		$filters = array_map(function (IMountPoint $mount) {
510
+		$filters = array_map(function(IMountPoint $mount) {
511 511
 			$storage = $mount->getStorage();
512 512
 
513 513
 			$storageId = $storage->getCache()->getNumericStorageId();
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
 
572 572
 			if ($filter['pathPrefix'] !== '') {
573 573
 				$storageFilter->add(
574
-					$builder->expr()->like('f.path', $builder->createNamedParameter($dbconn->escapeLikeParameter($filter['pathPrefix']) . '/%'))
574
+					$builder->expr()->like('f.path', $builder->createNamedParameter($dbconn->escapeLikeParameter($filter['pathPrefix']).'/%'))
575 575
 				);
576 576
 			}
577 577
 
@@ -599,7 +599,7 @@  discard block
 block discarded – undo
599 599
 	}
600 600
 
601 601
 	private function recentParse($result, $mountMap, $mimetypeLoader) {
602
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
602
+		$files = array_filter(array_map(function(array $entry) use ($mountMap, $mimetypeLoader) {
603 603
 			$mount = $mountMap[$entry['storage']];
604 604
 			$entry['internalPath'] = $entry['path'];
605 605
 			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
 			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
613 613
 		}, $result));
614 614
 
615
-		return array_values(array_filter($files, function (Node $node) {
615
+		return array_values(array_filter($files, function(Node $node) {
616 616
 			$cacheEntry = $node->getMountPoint()->getStorage()->getCache()->get($node->getId());
617 617
 			if (!$cacheEntry) {
618 618
 				return false;
@@ -634,13 +634,13 @@  discard block
 block discarded – undo
634 634
 			$rootLength = strlen($jailRoot) + 1;
635 635
 			if ($path === $jailRoot) {
636 636
 				return $mount->getMountPoint();
637
-			} elseif (substr($path, 0, $rootLength) === $jailRoot . '/') {
638
-				return $mount->getMountPoint() . substr($path, $rootLength);
637
+			} elseif (substr($path, 0, $rootLength) === $jailRoot.'/') {
638
+				return $mount->getMountPoint().substr($path, $rootLength);
639 639
 			} else {
640 640
 				return null;
641 641
 			}
642 642
 		} else {
643
-			return $mount->getMountPoint() . $path;
643
+			return $mount->getMountPoint().$path;
644 644
 		}
645 645
 	}
646 646
 }
Please login to merge, or discard this patch.
lib/private/Files/Search/SearchQuery.php 1 patch
Indentation   +69 added lines, -69 removed lines patch added patch discarded remove patch
@@ -29,80 +29,80 @@
 block discarded – undo
29 29
 use OCP\IUser;
30 30
 
31 31
 class SearchQuery implements ISearchQuery {
32
-	/** @var  ISearchOperator */
33
-	private $searchOperation;
34
-	/** @var  integer */
35
-	private $limit;
36
-	/** @var  integer */
37
-	private $offset;
38
-	/** @var  ISearchOrder[] */
39
-	private $order;
40
-	/** @var ?IUser */
41
-	private $user;
42
-	private $limitToHome;
32
+    /** @var  ISearchOperator */
33
+    private $searchOperation;
34
+    /** @var  integer */
35
+    private $limit;
36
+    /** @var  integer */
37
+    private $offset;
38
+    /** @var  ISearchOrder[] */
39
+    private $order;
40
+    /** @var ?IUser */
41
+    private $user;
42
+    private $limitToHome;
43 43
 
44
-	/**
45
-	 * SearchQuery constructor.
46
-	 *
47
-	 * @param ISearchOperator $searchOperation
48
-	 * @param int $limit
49
-	 * @param int $offset
50
-	 * @param array $order
51
-	 * @param ?IUser $user
52
-	 * @param bool $limitToHome
53
-	 */
54
-	public function __construct(
55
-		ISearchOperator $searchOperation,
56
-		int $limit,
57
-		int $offset,
58
-		array $order,
59
-		?IUser $user = null,
60
-		bool $limitToHome = false
61
-	) {
62
-		$this->searchOperation = $searchOperation;
63
-		$this->limit = $limit;
64
-		$this->offset = $offset;
65
-		$this->order = $order;
66
-		$this->user = $user;
67
-		$this->limitToHome = $limitToHome;
68
-	}
44
+    /**
45
+     * SearchQuery constructor.
46
+     *
47
+     * @param ISearchOperator $searchOperation
48
+     * @param int $limit
49
+     * @param int $offset
50
+     * @param array $order
51
+     * @param ?IUser $user
52
+     * @param bool $limitToHome
53
+     */
54
+    public function __construct(
55
+        ISearchOperator $searchOperation,
56
+        int $limit,
57
+        int $offset,
58
+        array $order,
59
+        ?IUser $user = null,
60
+        bool $limitToHome = false
61
+    ) {
62
+        $this->searchOperation = $searchOperation;
63
+        $this->limit = $limit;
64
+        $this->offset = $offset;
65
+        $this->order = $order;
66
+        $this->user = $user;
67
+        $this->limitToHome = $limitToHome;
68
+    }
69 69
 
70
-	/**
71
-	 * @return ISearchOperator
72
-	 */
73
-	public function getSearchOperation() {
74
-		return $this->searchOperation;
75
-	}
70
+    /**
71
+     * @return ISearchOperator
72
+     */
73
+    public function getSearchOperation() {
74
+        return $this->searchOperation;
75
+    }
76 76
 
77
-	/**
78
-	 * @return int
79
-	 */
80
-	public function getLimit() {
81
-		return $this->limit;
82
-	}
77
+    /**
78
+     * @return int
79
+     */
80
+    public function getLimit() {
81
+        return $this->limit;
82
+    }
83 83
 
84
-	/**
85
-	 * @return int
86
-	 */
87
-	public function getOffset() {
88
-		return $this->offset;
89
-	}
84
+    /**
85
+     * @return int
86
+     */
87
+    public function getOffset() {
88
+        return $this->offset;
89
+    }
90 90
 
91
-	/**
92
-	 * @return ISearchOrder[]
93
-	 */
94
-	public function getOrder() {
95
-		return $this->order;
96
-	}
91
+    /**
92
+     * @return ISearchOrder[]
93
+     */
94
+    public function getOrder() {
95
+        return $this->order;
96
+    }
97 97
 
98
-	/**
99
-	 * @return ?IUser
100
-	 */
101
-	public function getUser() {
102
-		return $this->user;
103
-	}
98
+    /**
99
+     * @return ?IUser
100
+     */
101
+    public function getUser() {
102
+        return $this->user;
103
+    }
104 104
 
105
-	public function limitToHome(): bool {
106
-		return $this->limitToHome;
107
-	}
105
+    public function limitToHome(): bool {
106
+        return $this->limitToHome;
107
+    }
108 108
 }
Please login to merge, or discard this patch.
lib/private/Files/Search/SearchOrder.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -27,57 +27,57 @@
 block discarded – undo
27 27
 use OCP\Files\Search\ISearchOrder;
28 28
 
29 29
 class SearchOrder implements ISearchOrder {
30
-	/** @var  string */
31
-	private $direction;
32
-	/** @var  string */
33
-	private $field;
30
+    /** @var  string */
31
+    private $direction;
32
+    /** @var  string */
33
+    private $field;
34 34
 
35
-	/**
36
-	 * SearchOrder constructor.
37
-	 *
38
-	 * @param string $direction
39
-	 * @param string $field
40
-	 */
41
-	public function __construct($direction, $field) {
42
-		$this->direction = $direction;
43
-		$this->field = $field;
44
-	}
35
+    /**
36
+     * SearchOrder constructor.
37
+     *
38
+     * @param string $direction
39
+     * @param string $field
40
+     */
41
+    public function __construct($direction, $field) {
42
+        $this->direction = $direction;
43
+        $this->field = $field;
44
+    }
45 45
 
46
-	/**
47
-	 * @return string
48
-	 */
49
-	public function getDirection() {
50
-		return $this->direction;
51
-	}
46
+    /**
47
+     * @return string
48
+     */
49
+    public function getDirection() {
50
+        return $this->direction;
51
+    }
52 52
 
53
-	/**
54
-	 * @return string
55
-	 */
56
-	public function getField() {
57
-		return $this->field;
58
-	}
53
+    /**
54
+     * @return string
55
+     */
56
+    public function getField() {
57
+        return $this->field;
58
+    }
59 59
 
60
-	public function sortFileInfo(FileInfo $a, FileInfo $b): int {
61
-		$cmp = $this->sortFileInfoNoDirection($a, $b);
62
-		return $cmp * ($this->direction === ISearchOrder::DIRECTION_ASCENDING ? 1 : -1);
63
-	}
60
+    public function sortFileInfo(FileInfo $a, FileInfo $b): int {
61
+        $cmp = $this->sortFileInfoNoDirection($a, $b);
62
+        return $cmp * ($this->direction === ISearchOrder::DIRECTION_ASCENDING ? 1 : -1);
63
+    }
64 64
 
65
-	private function sortFileInfoNoDirection(FileInfo $a, FileInfo $b): int {
66
-		switch ($this->field) {
67
-			case 'name':
68
-				return $a->getName() <=> $b->getName();
69
-			case 'mimetype':
70
-				return $a->getMimetype() <=> $b->getMimetype();
71
-			case 'mtime':
72
-				return $a->getMtime() <=> $b->getMtime();
73
-			case 'size':
74
-				return $a->getSize() <=> $b->getSize();
75
-			case 'fileid':
76
-				return $a->getId() <=> $b->getId();
77
-			case 'permissions':
78
-				return $a->getPermissions() <=> $b->getPermissions();
79
-			default:
80
-				return 0;
81
-		}
82
-	}
65
+    private function sortFileInfoNoDirection(FileInfo $a, FileInfo $b): int {
66
+        switch ($this->field) {
67
+            case 'name':
68
+                return $a->getName() <=> $b->getName();
69
+            case 'mimetype':
70
+                return $a->getMimetype() <=> $b->getMimetype();
71
+            case 'mtime':
72
+                return $a->getMtime() <=> $b->getMtime();
73
+            case 'size':
74
+                return $a->getSize() <=> $b->getSize();
75
+            case 'fileid':
76
+                return $a->getId() <=> $b->getId();
77
+            case 'permissions':
78
+                return $a->getPermissions() <=> $b->getPermissions();
79
+            default:
80
+                return 0;
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.
lib/private/Search/Result/File.php 1 patch
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -38,112 +38,112 @@
 block discarded – undo
38 38
  */
39 39
 class File extends \OCP\Search\Result {
40 40
 
41
-	/**
42
-	 * Type name; translated in templates
43
-	 * @var string
44
-	 * @deprecated 20.0.0
45
-	 */
46
-	public $type = 'file';
41
+    /**
42
+     * Type name; translated in templates
43
+     * @var string
44
+     * @deprecated 20.0.0
45
+     */
46
+    public $type = 'file';
47 47
 
48
-	/**
49
-	 * Path to file
50
-	 * @var string
51
-	 * @deprecated 20.0.0
52
-	 */
53
-	public $path;
48
+    /**
49
+     * Path to file
50
+     * @var string
51
+     * @deprecated 20.0.0
52
+     */
53
+    public $path;
54 54
 
55
-	/**
56
-	 * Size, in bytes
57
-	 * @var int
58
-	 * @deprecated 20.0.0
59
-	 */
60
-	public $size;
55
+    /**
56
+     * Size, in bytes
57
+     * @var int
58
+     * @deprecated 20.0.0
59
+     */
60
+    public $size;
61 61
 
62
-	/**
63
-	 * Date modified, in human readable form
64
-	 * @var string
65
-	 * @deprecated 20.0.0
66
-	 */
67
-	public $modified;
62
+    /**
63
+     * Date modified, in human readable form
64
+     * @var string
65
+     * @deprecated 20.0.0
66
+     */
67
+    public $modified;
68 68
 
69
-	/**
70
-	 * File mime type
71
-	 * @var string
72
-	 * @deprecated 20.0.0
73
-	 */
74
-	public $mime_type;
69
+    /**
70
+     * File mime type
71
+     * @var string
72
+     * @deprecated 20.0.0
73
+     */
74
+    public $mime_type;
75 75
 
76
-	/**
77
-	 * File permissions:
78
-	 *
79
-	 * @var string
80
-	 * @deprecated 20.0.0
81
-	 */
82
-	public $permissions;
76
+    /**
77
+     * File permissions:
78
+     *
79
+     * @var string
80
+     * @deprecated 20.0.0
81
+     */
82
+    public $permissions;
83 83
 
84
-	/**
85
-	 * Has a preview
86
-	 *
87
-	 * @var string
88
-	 * @deprecated 20.0.0
89
-	 */
90
-	public $has_preview;
84
+    /**
85
+     * Has a preview
86
+     *
87
+     * @var string
88
+     * @deprecated 20.0.0
89
+     */
90
+    public $has_preview;
91 91
 
92
-	/**
93
-	 * Create a new file search result
94
-	 * @param FileInfo $data file data given by provider
95
-	 * @deprecated 20.0.0
96
-	 */
97
-	public function __construct(FileInfo $data) {
98
-		$path = $this->getRelativePath($data->getPath());
92
+    /**
93
+     * Create a new file search result
94
+     * @param FileInfo $data file data given by provider
95
+     * @deprecated 20.0.0
96
+     */
97
+    public function __construct(FileInfo $data) {
98
+        $path = $this->getRelativePath($data->getPath());
99 99
 
100
-		$this->id = $data->getId();
101
-		$this->name = $data->getName();
102
-		$this->link = \OC::$server->getURLGenerator()->linkToRoute(
103
-			'files.view.index',
104
-			[
105
-				'dir' => dirname($path),
106
-				'scrollto' => $data->getName(),
107
-			]
108
-		);
109
-		$this->permissions = $data->getPermissions();
110
-		$this->path = $path;
111
-		$this->size = $data->getSize();
112
-		$this->modified = $data->getMtime();
113
-		$this->mime_type = $data->getMimetype();
114
-		$this->has_preview = $this->hasPreview($data);
115
-	}
100
+        $this->id = $data->getId();
101
+        $this->name = $data->getName();
102
+        $this->link = \OC::$server->getURLGenerator()->linkToRoute(
103
+            'files.view.index',
104
+            [
105
+                'dir' => dirname($path),
106
+                'scrollto' => $data->getName(),
107
+            ]
108
+        );
109
+        $this->permissions = $data->getPermissions();
110
+        $this->path = $path;
111
+        $this->size = $data->getSize();
112
+        $this->modified = $data->getMtime();
113
+        $this->mime_type = $data->getMimetype();
114
+        $this->has_preview = $this->hasPreview($data);
115
+    }
116 116
 
117
-	/**
118
-	 * @var Folder $userFolderCache
119
-	 * @deprecated 20.0.0
120
-	 */
121
-	protected static $userFolderCache = null;
117
+    /**
118
+     * @var Folder $userFolderCache
119
+     * @deprecated 20.0.0
120
+     */
121
+    protected static $userFolderCache = null;
122 122
 
123
-	/**
124
-	 * converts a path relative to the users files folder
125
-	 * eg /user/files/foo.txt -> /foo.txt
126
-	 * @param string $path
127
-	 * @return string relative path
128
-	 * @deprecated 20.0.0
129
-	 */
130
-	protected function getRelativePath($path) {
131
-		if (!isset(self::$userFolderCache)) {
132
-			$userSession = \OC::$server->get(IUserSession::class);
133
-			$userID = $userSession->getUser()->getUID();
134
-			self::$userFolderCache = \OC::$server->getUserFolder($userID);
135
-		}
136
-		return self::$userFolderCache->getRelativePath($path);
137
-	}
123
+    /**
124
+     * converts a path relative to the users files folder
125
+     * eg /user/files/foo.txt -> /foo.txt
126
+     * @param string $path
127
+     * @return string relative path
128
+     * @deprecated 20.0.0
129
+     */
130
+    protected function getRelativePath($path) {
131
+        if (!isset(self::$userFolderCache)) {
132
+            $userSession = \OC::$server->get(IUserSession::class);
133
+            $userID = $userSession->getUser()->getUID();
134
+            self::$userFolderCache = \OC::$server->getUserFolder($userID);
135
+        }
136
+        return self::$userFolderCache->getRelativePath($path);
137
+    }
138 138
 
139
-	/**
140
-	 * Is the preview available
141
-	 * @param FileInfo $data
142
-	 * @return bool
143
-	 * @deprecated 20.0.0
144
-	 */
145
-	protected function hasPreview($data) {
146
-		$previewManager = \OC::$server->get(IPreview::class);
147
-		return $previewManager->isAvailable($data);
148
-	}
139
+    /**
140
+     * Is the preview available
141
+     * @param FileInfo $data
142
+     * @return bool
143
+     * @deprecated 20.0.0
144
+     */
145
+    protected function hasPreview($data) {
146
+        $previewManager = \OC::$server->get(IPreview::class);
147
+        return $previewManager->isAvailable($data);
148
+    }
149 149
 }
Please login to merge, or discard this patch.
lib/private/Search/Provider/File.php 2 patches
Indentation   +61 added lines, -61 removed lines patch added patch discarded remove patch
@@ -45,66 +45,66 @@
 block discarded – undo
45 45
  */
46 46
 class File extends PagedProvider {
47 47
 
48
-	/**
49
-	 * Search for files and folders matching the given query
50
-	 *
51
-	 * @param string $query
52
-	 * @param int|null $limit
53
-	 * @param int|null $offset
54
-	 * @return \OCP\Search\Result[]
55
-	 * @deprecated 20.0.0
56
-	 */
57
-	public function search($query, int $limit = null, int $offset = null) {
58
-		/** @var IRootFolder $rootFolder */
59
-		$rootFolder = \OC::$server->query(IRootFolder::class);
60
-		/** @var IUserSession $userSession */
61
-		$userSession = \OC::$server->query(IUserSession::class);
62
-		$user = $userSession->getUser();
63
-		if (!$user) {
64
-			return [];
65
-		}
66
-		$userFolder = $rootFolder->getUserFolder($user->getUID());
67
-		$fileQuery = new SearchQuery(
68
-			new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'),
69
-			(int)$limit,
70
-			(int)$offset,
71
-			[
72
-				new SearchOrder(ISearchOrder::DIRECTION_DESCENDING, 'mtime'),
73
-			],
74
-			$user
75
-		);
76
-		$files = $userFolder->search($fileQuery);
77
-		$results = [];
78
-		// edit results
79
-		foreach ($files as $fileData) {
80
-			// create audio result
81
-			if ($fileData->getMimePart() === 'audio') {
82
-				$result = new \OC\Search\Result\Audio($fileData);
83
-			}
84
-			// create image result
85
-			elseif ($fileData->getMimePart() === 'image') {
86
-				$result = new \OC\Search\Result\Image($fileData);
87
-			}
88
-			// create folder result
89
-			elseif ($fileData->getMimetype() === FileInfo::MIMETYPE_FOLDER) {
90
-				$result = new \OC\Search\Result\Folder($fileData);
91
-			}
92
-			// or create file result
93
-			else {
94
-				$result = new \OC\Search\Result\File($fileData);
95
-			}
96
-			// add to results
97
-			$results[] = $result;
98
-		}
99
-		// return
100
-		return $results;
101
-	}
48
+    /**
49
+     * Search for files and folders matching the given query
50
+     *
51
+     * @param string $query
52
+     * @param int|null $limit
53
+     * @param int|null $offset
54
+     * @return \OCP\Search\Result[]
55
+     * @deprecated 20.0.0
56
+     */
57
+    public function search($query, int $limit = null, int $offset = null) {
58
+        /** @var IRootFolder $rootFolder */
59
+        $rootFolder = \OC::$server->query(IRootFolder::class);
60
+        /** @var IUserSession $userSession */
61
+        $userSession = \OC::$server->query(IUserSession::class);
62
+        $user = $userSession->getUser();
63
+        if (!$user) {
64
+            return [];
65
+        }
66
+        $userFolder = $rootFolder->getUserFolder($user->getUID());
67
+        $fileQuery = new SearchQuery(
68
+            new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'),
69
+            (int)$limit,
70
+            (int)$offset,
71
+            [
72
+                new SearchOrder(ISearchOrder::DIRECTION_DESCENDING, 'mtime'),
73
+            ],
74
+            $user
75
+        );
76
+        $files = $userFolder->search($fileQuery);
77
+        $results = [];
78
+        // edit results
79
+        foreach ($files as $fileData) {
80
+            // create audio result
81
+            if ($fileData->getMimePart() === 'audio') {
82
+                $result = new \OC\Search\Result\Audio($fileData);
83
+            }
84
+            // create image result
85
+            elseif ($fileData->getMimePart() === 'image') {
86
+                $result = new \OC\Search\Result\Image($fileData);
87
+            }
88
+            // create folder result
89
+            elseif ($fileData->getMimetype() === FileInfo::MIMETYPE_FOLDER) {
90
+                $result = new \OC\Search\Result\Folder($fileData);
91
+            }
92
+            // or create file result
93
+            else {
94
+                $result = new \OC\Search\Result\File($fileData);
95
+            }
96
+            // add to results
97
+            $results[] = $result;
98
+        }
99
+        // return
100
+        return $results;
101
+    }
102 102
 
103
-	public function searchPaged($query, $page, $size) {
104
-		if ($size === 0) {
105
-			return $this->search($query);
106
-		} else {
107
-			return $this->search($query, $size, ($page - 1) * $size);
108
-		}
109
-	}
103
+    public function searchPaged($query, $page, $size) {
104
+        if ($size === 0) {
105
+            return $this->search($query);
106
+        } else {
107
+            return $this->search($query, $size, ($page - 1) * $size);
108
+        }
109
+    }
110 110
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -65,9 +65,9 @@
 block discarded – undo
65 65
 		}
66 66
 		$userFolder = $rootFolder->getUserFolder($user->getUID());
67 67
 		$fileQuery = new SearchQuery(
68
-			new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%' . $query . '%'),
69
-			(int)$limit,
70
-			(int)$offset,
68
+			new SearchComparison(ISearchComparison::COMPARE_LIKE, 'name', '%'.$query.'%'),
69
+			(int) $limit,
70
+			(int) $offset,
71 71
 			[
72 72
 				new SearchOrder(ISearchOrder::DIRECTION_DESCENDING, 'mtime'),
73 73
 			],
Please login to merge, or discard this patch.
lib/public/Files/Search/ISearchOrder.php 1 patch
Indentation   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -30,32 +30,32 @@
 block discarded – undo
30 30
  * @since 12.0.0
31 31
  */
32 32
 interface ISearchOrder {
33
-	public const DIRECTION_ASCENDING = 'asc';
34
-	public const DIRECTION_DESCENDING = 'desc';
33
+    public const DIRECTION_ASCENDING = 'asc';
34
+    public const DIRECTION_DESCENDING = 'desc';
35 35
 
36
-	/**
37
-	 * The direction to sort in, either ISearchOrder::DIRECTION_ASCENDING or ISearchOrder::DIRECTION_DESCENDING
38
-	 *
39
-	 * @return string
40
-	 * @since 12.0.0
41
-	 */
42
-	public function getDirection();
36
+    /**
37
+     * The direction to sort in, either ISearchOrder::DIRECTION_ASCENDING or ISearchOrder::DIRECTION_DESCENDING
38
+     *
39
+     * @return string
40
+     * @since 12.0.0
41
+     */
42
+    public function getDirection();
43 43
 
44
-	/**
45
-	 * The field to sort on
46
-	 *
47
-	 * @return string
48
-	 * @since 12.0.0
49
-	 */
50
-	public function getField();
44
+    /**
45
+     * The field to sort on
46
+     *
47
+     * @return string
48
+     * @since 12.0.0
49
+     */
50
+    public function getField();
51 51
 
52
-	/**
53
-	 * Apply the sorting on 2 FileInfo objects
54
-	 *
55
-	 * @param FileInfo $a
56
-	 * @param FileInfo $b
57
-	 * @return int -1 if $a < $b, 0 if $a = $b, 1 if $a > $b (for ascending, reverse for descending)
58
-	 * @since 22.0.0
59
-	 */
60
-	public function sortFileInfo(FileInfo $a, FileInfo $b): int;
52
+    /**
53
+     * Apply the sorting on 2 FileInfo objects
54
+     *
55
+     * @param FileInfo $a
56
+     * @param FileInfo $b
57
+     * @return int -1 if $a < $b, 0 if $a = $b, 1 if $a > $b (for ascending, reverse for descending)
58
+     * @since 22.0.0
59
+     */
60
+    public function sortFileInfo(FileInfo $a, FileInfo $b): int;
61 61
 }
Please login to merge, or discard this patch.
lib/public/Files/Search/ISearchQuery.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -29,49 +29,49 @@
 block discarded – undo
29 29
  * @since 12.0.0
30 30
  */
31 31
 interface ISearchQuery {
32
-	/**
33
-	 * @return ISearchOperator
34
-	 * @since 12.0.0
35
-	 */
36
-	public function getSearchOperation();
32
+    /**
33
+     * @return ISearchOperator
34
+     * @since 12.0.0
35
+     */
36
+    public function getSearchOperation();
37 37
 
38
-	/**
39
-	 * Get the maximum number of results to return
40
-	 *
41
-	 * @return integer
42
-	 * @since 12.0.0
43
-	 */
44
-	public function getLimit();
38
+    /**
39
+     * Get the maximum number of results to return
40
+     *
41
+     * @return integer
42
+     * @since 12.0.0
43
+     */
44
+    public function getLimit();
45 45
 
46
-	/**
47
-	 * Get the offset for returned results
48
-	 *
49
-	 * @return integer
50
-	 * @since 12.0.0
51
-	 */
52
-	public function getOffset();
46
+    /**
47
+     * Get the offset for returned results
48
+     *
49
+     * @return integer
50
+     * @since 12.0.0
51
+     */
52
+    public function getOffset();
53 53
 
54
-	/**
55
-	 * The fields and directions to order by
56
-	 *
57
-	 * @return ISearchOrder[]
58
-	 * @since 12.0.0
59
-	 */
60
-	public function getOrder();
54
+    /**
55
+     * The fields and directions to order by
56
+     *
57
+     * @return ISearchOrder[]
58
+     * @since 12.0.0
59
+     */
60
+    public function getOrder();
61 61
 
62
-	/**
63
-	 * The user that issued the search
64
-	 *
65
-	 * @return ?IUser
66
-	 * @since 12.0.0
67
-	 */
68
-	public function getUser();
62
+    /**
63
+     * The user that issued the search
64
+     *
65
+     * @return ?IUser
66
+     * @since 12.0.0
67
+     */
68
+    public function getUser();
69 69
 
70
-	/**
71
-	 * Whether or not the search should be limited to the users home storage
72
-	 *
73
-	 * @return bool
74
-	 * @since 18.0.0
75
-	 */
76
-	public function limitToHome(): bool;
70
+    /**
71
+     * Whether or not the search should be limited to the users home storage
72
+     *
73
+     * @return bool
74
+     * @since 18.0.0
75
+     */
76
+    public function limitToHome(): bool;
77 77
 }
Please login to merge, or discard this patch.
core/Controller/SearchController.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -36,39 +36,39 @@
 block discarded – undo
36 36
 
37 37
 class SearchController extends Controller {
38 38
 
39
-	/** @var ISearch */
40
-	private $searcher;
41
-	/** @var ILogger */
42
-	private $logger;
39
+    /** @var ISearch */
40
+    private $searcher;
41
+    /** @var ILogger */
42
+    private $logger;
43 43
 
44
-	public function __construct(
45
-		string $appName,
46
-		IRequest $request,
47
-		ISearch $search,
48
-		ILogger $logger
49
-	) {
50
-		parent::__construct($appName, $request);
44
+    public function __construct(
45
+        string $appName,
46
+        IRequest $request,
47
+        ISearch $search,
48
+        ILogger $logger
49
+    ) {
50
+        parent::__construct($appName, $request);
51 51
 
52
-		$this->searcher = $search;
53
-		$this->logger = $logger;
54
-	}
52
+        $this->searcher = $search;
53
+        $this->logger = $logger;
54
+    }
55 55
 
56
-	/**
57
-	 * @NoAdminRequired
58
-	 * @NoCSRFRequired
59
-	 */
60
-	public function search(string $query, array $inApps = [], int $page = 1, int $size = 30): JSONResponse {
61
-		$results = $this->searcher->searchPaged($query, $inApps, $page, $size);
56
+    /**
57
+     * @NoAdminRequired
58
+     * @NoCSRFRequired
59
+     */
60
+    public function search(string $query, array $inApps = [], int $page = 1, int $size = 30): JSONResponse {
61
+        $results = $this->searcher->searchPaged($query, $inApps, $page, $size);
62 62
 
63
-		$results = array_filter($results, function (Result $result) {
64
-			if (json_encode($result, JSON_HEX_TAG) === false) {
65
-				$this->logger->warning("Skipping search result due to invalid encoding: {type: " . $result->type . ", id: " . $result->id . "}");
66
-				return false;
67
-			} else {
68
-				return true;
69
-			}
70
-		});
63
+        $results = array_filter($results, function (Result $result) {
64
+            if (json_encode($result, JSON_HEX_TAG) === false) {
65
+                $this->logger->warning("Skipping search result due to invalid encoding: {type: " . $result->type . ", id: " . $result->id . "}");
66
+                return false;
67
+            } else {
68
+                return true;
69
+            }
70
+        });
71 71
 
72
-		return new JSONResponse($results);
73
-	}
72
+        return new JSONResponse($results);
73
+    }
74 74
 }
Please login to merge, or discard this patch.