Completed
Push — master ( 0c2934...e2a331 )
by
unknown
31:06 queued 15s
created
lib/public/Files.php 1 patch
Indentation   +110 added lines, -110 removed lines patch added patch discarded remove patch
@@ -18,123 +18,123 @@
 block discarded – undo
18 18
  * @deprecated 14.0.0
19 19
  */
20 20
 class Files {
21
-	/**
22
-	 * Recursive deletion of folders
23
-	 *
24
-	 * @param string $dir path to the folder
25
-	 * @param bool $deleteSelf if set to false only the content of the folder will be deleted
26
-	 * @return bool
27
-	 * @since 5.0.0
28
-	 * @since 32.0.0 added the $deleteSelf parameter
29
-	 * @deprecated 14.0.0
30
-	 */
31
-	public static function rmdirr($dir, bool $deleteSelf = true) {
32
-		if (is_dir($dir)) {
33
-			$files = new \RecursiveIteratorIterator(
34
-				new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
35
-				\RecursiveIteratorIterator::CHILD_FIRST
36
-			);
21
+    /**
22
+     * Recursive deletion of folders
23
+     *
24
+     * @param string $dir path to the folder
25
+     * @param bool $deleteSelf if set to false only the content of the folder will be deleted
26
+     * @return bool
27
+     * @since 5.0.0
28
+     * @since 32.0.0 added the $deleteSelf parameter
29
+     * @deprecated 14.0.0
30
+     */
31
+    public static function rmdirr($dir, bool $deleteSelf = true) {
32
+        if (is_dir($dir)) {
33
+            $files = new \RecursiveIteratorIterator(
34
+                new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
35
+                \RecursiveIteratorIterator::CHILD_FIRST
36
+            );
37 37
 
38
-			foreach ($files as $fileInfo) {
39
-				/** @var \SplFileInfo $fileInfo */
40
-				if ($fileInfo->isLink()) {
41
-					unlink($fileInfo->getPathname());
42
-				} elseif ($fileInfo->isDir()) {
43
-					rmdir($fileInfo->getRealPath());
44
-				} else {
45
-					unlink($fileInfo->getRealPath());
46
-				}
47
-			}
48
-			if ($deleteSelf) {
49
-				rmdir($dir);
50
-			}
51
-		} elseif (file_exists($dir)) {
52
-			if ($deleteSelf) {
53
-				unlink($dir);
54
-			}
55
-		}
56
-		if (!$deleteSelf) {
57
-			return true;
58
-		}
38
+            foreach ($files as $fileInfo) {
39
+                /** @var \SplFileInfo $fileInfo */
40
+                if ($fileInfo->isLink()) {
41
+                    unlink($fileInfo->getPathname());
42
+                } elseif ($fileInfo->isDir()) {
43
+                    rmdir($fileInfo->getRealPath());
44
+                } else {
45
+                    unlink($fileInfo->getRealPath());
46
+                }
47
+            }
48
+            if ($deleteSelf) {
49
+                rmdir($dir);
50
+            }
51
+        } elseif (file_exists($dir)) {
52
+            if ($deleteSelf) {
53
+                unlink($dir);
54
+            }
55
+        }
56
+        if (!$deleteSelf) {
57
+            return true;
58
+        }
59 59
 
60
-		return !file_exists($dir);
61
-	}
60
+        return !file_exists($dir);
61
+    }
62 62
 
63
-	/**
64
-	 * Get the mimetype form a local file
65
-	 * @param string $path
66
-	 * @return string
67
-	 *                does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead
68
-	 * @since 5.0.0
69
-	 * @deprecated 14.0.0
70
-	 */
71
-	public static function getMimeType($path) {
72
-		return Server::get(IMimeTypeDetector::class)->detect($path);
73
-	}
63
+    /**
64
+     * Get the mimetype form a local file
65
+     * @param string $path
66
+     * @return string
67
+     *                does NOT work for ownClouds filesystem, use OC_FileSystem::getMimeType instead
68
+     * @since 5.0.0
69
+     * @deprecated 14.0.0
70
+     */
71
+    public static function getMimeType($path) {
72
+        return Server::get(IMimeTypeDetector::class)->detect($path);
73
+    }
74 74
 
75
-	/**
76
-	 * Search for files by mimetype
77
-	 * @param string $mimetype
78
-	 * @return array
79
-	 * @since 6.0.0
80
-	 * @deprecated 14.0.0
81
-	 */
82
-	public static function searchByMime($mimetype) {
83
-		return \OC\Files\Filesystem::searchByMime($mimetype);
84
-	}
75
+    /**
76
+     * Search for files by mimetype
77
+     * @param string $mimetype
78
+     * @return array
79
+     * @since 6.0.0
80
+     * @deprecated 14.0.0
81
+     */
82
+    public static function searchByMime($mimetype) {
83
+        return \OC\Files\Filesystem::searchByMime($mimetype);
84
+    }
85 85
 
86
-	/**
87
-	 * Copy the contents of one stream to another
88
-	 *
89
-	 * @template T of null|true
90
-	 * @param resource $source
91
-	 * @param resource $target
92
-	 * @param T $includeResult
93
-	 * @return int|array
94
-	 * @psalm-return (T is true ? array{0: int, 1: bool} : int)
95
-	 * @since 5.0.0
96
-	 * @since 32.0.0 added $includeResult parameter
97
-	 * @deprecated 14.0.0
98
-	 */
99
-	public static function streamCopy($source, $target, ?bool $includeResult = null) {
100
-		if (!$source or !$target) {
101
-			return $includeResult ? [0, false] : 0;
102
-		}
86
+    /**
87
+     * Copy the contents of one stream to another
88
+     *
89
+     * @template T of null|true
90
+     * @param resource $source
91
+     * @param resource $target
92
+     * @param T $includeResult
93
+     * @return int|array
94
+     * @psalm-return (T is true ? array{0: int, 1: bool} : int)
95
+     * @since 5.0.0
96
+     * @since 32.0.0 added $includeResult parameter
97
+     * @deprecated 14.0.0
98
+     */
99
+    public static function streamCopy($source, $target, ?bool $includeResult = null) {
100
+        if (!$source or !$target) {
101
+            return $includeResult ? [0, false] : 0;
102
+        }
103 103
 
104
-		$bufSize = 8192;
105
-		$count = 0;
106
-		$result = true;
107
-		while (!feof($source)) {
108
-			$buf = fread($source, $bufSize);
109
-			if ($buf === false) {
110
-				$result = false;
111
-				break;
112
-			}
104
+        $bufSize = 8192;
105
+        $count = 0;
106
+        $result = true;
107
+        while (!feof($source)) {
108
+            $buf = fread($source, $bufSize);
109
+            if ($buf === false) {
110
+                $result = false;
111
+                break;
112
+            }
113 113
 
114
-			$bytesWritten = fwrite($target, $buf);
115
-			if ($bytesWritten !== false) {
116
-				$count += $bytesWritten;
117
-			}
114
+            $bytesWritten = fwrite($target, $buf);
115
+            if ($bytesWritten !== false) {
116
+                $count += $bytesWritten;
117
+            }
118 118
 
119
-			if ($bytesWritten === false
120
-				|| ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
121
-			) {
122
-				$result = false;
123
-				break;
124
-			}
125
-		}
126
-		return $includeResult ? [$count, $result] : $count;
127
-	}
119
+            if ($bytesWritten === false
120
+                || ($bytesWritten < $bufSize && $bytesWritten < strlen($buf))
121
+            ) {
122
+                $result = false;
123
+                break;
124
+            }
125
+        }
126
+        return $includeResult ? [$count, $result] : $count;
127
+    }
128 128
 
129
-	/**
130
-	 * Adds a suffix to the name in case the file exists
131
-	 * @param string $path
132
-	 * @param string $filename
133
-	 * @return string
134
-	 * @since 5.0.0
135
-	 * @deprecated 14.0.0 use getNonExistingName of the OCP\Files\Folder object
136
-	 */
137
-	public static function buildNotExistingFileName($path, $filename) {
138
-		return \OC_Helper::buildNotExistingFileName($path, $filename);
139
-	}
129
+    /**
130
+     * Adds a suffix to the name in case the file exists
131
+     * @param string $path
132
+     * @param string $filename
133
+     * @return string
134
+     * @since 5.0.0
135
+     * @deprecated 14.0.0 use getNonExistingName of the OCP\Files\Folder object
136
+     */
137
+    public static function buildNotExistingFileName($path, $filename) {
138
+        return \OC_Helper::buildNotExistingFileName($path, $filename);
139
+    }
140 140
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Wrapper.php 1 patch
Indentation   +325 added lines, -325 removed lines patch added patch discarded remove patch
@@ -23,329 +23,329 @@
 block discarded – undo
23 23
 use Psr\Log\LoggerInterface;
24 24
 
25 25
 class Wrapper implements \OC\Files\Storage\Storage, ILockingStorage, IWriteStreamStorage {
26
-	/**
27
-	 * @var \OC\Files\Storage\Storage $storage
28
-	 */
29
-	protected $storage;
30
-
31
-	public $cache;
32
-	public $scanner;
33
-	public $watcher;
34
-	public $propagator;
35
-	public $updater;
36
-
37
-	/**
38
-	 * @param array $parameters
39
-	 */
40
-	public function __construct(array $parameters) {
41
-		$this->storage = $parameters['storage'];
42
-	}
43
-
44
-	public function getWrapperStorage(): Storage {
45
-		if (!$this->storage) {
46
-			$message = 'storage wrapper ' . get_class($this) . " doesn't have a wrapped storage set";
47
-			$logger = Server::get(LoggerInterface::class);
48
-			$logger->error($message);
49
-			$this->storage = new FailedStorage(['exception' => new \Exception($message)]);
50
-		}
51
-		return $this->storage;
52
-	}
53
-
54
-	public function getId(): string {
55
-		return $this->getWrapperStorage()->getId();
56
-	}
57
-
58
-	public function mkdir(string $path): bool {
59
-		return $this->getWrapperStorage()->mkdir($path);
60
-	}
61
-
62
-	public function rmdir(string $path): bool {
63
-		return $this->getWrapperStorage()->rmdir($path);
64
-	}
65
-
66
-	public function opendir(string $path) {
67
-		return $this->getWrapperStorage()->opendir($path);
68
-	}
69
-
70
-	public function is_dir(string $path): bool {
71
-		return $this->getWrapperStorage()->is_dir($path);
72
-	}
73
-
74
-	public function is_file(string $path): bool {
75
-		return $this->getWrapperStorage()->is_file($path);
76
-	}
77
-
78
-	public function stat(string $path): array|false {
79
-		return $this->getWrapperStorage()->stat($path);
80
-	}
81
-
82
-	public function filetype(string $path): string|false {
83
-		return $this->getWrapperStorage()->filetype($path);
84
-	}
85
-
86
-	public function filesize(string $path): int|float|false {
87
-		return $this->getWrapperStorage()->filesize($path);
88
-	}
89
-
90
-	public function isCreatable(string $path): bool {
91
-		return $this->getWrapperStorage()->isCreatable($path);
92
-	}
93
-
94
-	public function isReadable(string $path): bool {
95
-		return $this->getWrapperStorage()->isReadable($path);
96
-	}
97
-
98
-	public function isUpdatable(string $path): bool {
99
-		return $this->getWrapperStorage()->isUpdatable($path);
100
-	}
101
-
102
-	public function isDeletable(string $path): bool {
103
-		return $this->getWrapperStorage()->isDeletable($path);
104
-	}
105
-
106
-	public function isSharable(string $path): bool {
107
-		return $this->getWrapperStorage()->isSharable($path);
108
-	}
109
-
110
-	public function getPermissions(string $path): int {
111
-		return $this->getWrapperStorage()->getPermissions($path);
112
-	}
113
-
114
-	public function file_exists(string $path): bool {
115
-		return $this->getWrapperStorage()->file_exists($path);
116
-	}
117
-
118
-	public function filemtime(string $path): int|false {
119
-		return $this->getWrapperStorage()->filemtime($path);
120
-	}
121
-
122
-	public function file_get_contents(string $path): string|false {
123
-		return $this->getWrapperStorage()->file_get_contents($path);
124
-	}
125
-
126
-	public function file_put_contents(string $path, mixed $data): int|float|false {
127
-		return $this->getWrapperStorage()->file_put_contents($path, $data);
128
-	}
129
-
130
-	public function unlink(string $path): bool {
131
-		return $this->getWrapperStorage()->unlink($path);
132
-	}
133
-
134
-	public function rename(string $source, string $target): bool {
135
-		return $this->getWrapperStorage()->rename($source, $target);
136
-	}
137
-
138
-	public function copy(string $source, string $target): bool {
139
-		return $this->getWrapperStorage()->copy($source, $target);
140
-	}
141
-
142
-	public function fopen(string $path, string $mode) {
143
-		return $this->getWrapperStorage()->fopen($path, $mode);
144
-	}
145
-
146
-	public function getMimeType(string $path): string|false {
147
-		return $this->getWrapperStorage()->getMimeType($path);
148
-	}
149
-
150
-	public function hash(string $type, string $path, bool $raw = false): string|false {
151
-		return $this->getWrapperStorage()->hash($type, $path, $raw);
152
-	}
153
-
154
-	public function free_space(string $path): int|float|false {
155
-		return $this->getWrapperStorage()->free_space($path);
156
-	}
157
-
158
-	public function touch(string $path, ?int $mtime = null): bool {
159
-		return $this->getWrapperStorage()->touch($path, $mtime);
160
-	}
161
-
162
-	public function getLocalFile(string $path): string|false {
163
-		return $this->getWrapperStorage()->getLocalFile($path);
164
-	}
165
-
166
-	public function hasUpdated(string $path, int $time): bool {
167
-		return $this->getWrapperStorage()->hasUpdated($path, $time);
168
-	}
169
-
170
-	public function getCache(string $path = '', ?IStorage $storage = null): ICache {
171
-		if (!$storage) {
172
-			$storage = $this;
173
-		}
174
-		return $this->getWrapperStorage()->getCache($path, $storage);
175
-	}
176
-
177
-	public function getScanner(string $path = '', ?IStorage $storage = null): IScanner {
178
-		if (!$storage) {
179
-			$storage = $this;
180
-		}
181
-		return $this->getWrapperStorage()->getScanner($path, $storage);
182
-	}
183
-
184
-	public function getOwner(string $path): string|false {
185
-		return $this->getWrapperStorage()->getOwner($path);
186
-	}
187
-
188
-	public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
189
-		if (!$storage) {
190
-			$storage = $this;
191
-		}
192
-		return $this->getWrapperStorage()->getWatcher($path, $storage);
193
-	}
194
-
195
-	public function getPropagator(?IStorage $storage = null): IPropagator {
196
-		if (!$storage) {
197
-			$storage = $this;
198
-		}
199
-		return $this->getWrapperStorage()->getPropagator($storage);
200
-	}
201
-
202
-	public function getUpdater(?IStorage $storage = null): IUpdater {
203
-		if (!$storage) {
204
-			$storage = $this;
205
-		}
206
-		return $this->getWrapperStorage()->getUpdater($storage);
207
-	}
208
-
209
-	public function getStorageCache(): \OC\Files\Cache\Storage {
210
-		return $this->getWrapperStorage()->getStorageCache();
211
-	}
212
-
213
-	public function getETag(string $path): string|false {
214
-		return $this->getWrapperStorage()->getETag($path);
215
-	}
216
-
217
-	public function test(): bool {
218
-		return $this->getWrapperStorage()->test();
219
-	}
220
-
221
-	public function isLocal(): bool {
222
-		return $this->getWrapperStorage()->isLocal();
223
-	}
224
-
225
-	public function instanceOfStorage(string $class): bool {
226
-		if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
227
-			// FIXME Temporary fix to keep existing checks working
228
-			$class = '\OCA\Files_Sharing\SharedStorage';
229
-		}
230
-		return is_a($this, $class) or $this->getWrapperStorage()->instanceOfStorage($class);
231
-	}
232
-
233
-	/**
234
-	 * @psalm-template T of IStorage
235
-	 * @psalm-param class-string<T> $class
236
-	 * @psalm-return T|null
237
-	 */
238
-	public function getInstanceOfStorage(string $class): ?IStorage {
239
-		$storage = $this;
240
-		while ($storage instanceof Wrapper) {
241
-			if ($storage instanceof $class) {
242
-				break;
243
-			}
244
-			$storage = $storage->getWrapperStorage();
245
-		}
246
-		if (!($storage instanceof $class)) {
247
-			return null;
248
-		}
249
-		return $storage;
250
-	}
251
-
252
-	/**
253
-	 * Pass any methods custom to specific storage implementations to the wrapped storage
254
-	 *
255
-	 * @return mixed
256
-	 */
257
-	public function __call(string $method, array $args) {
258
-		return call_user_func_array([$this->getWrapperStorage(), $method], $args);
259
-	}
260
-
261
-	public function getDirectDownload(string $path): array|false {
262
-		return $this->getWrapperStorage()->getDirectDownload($path);
263
-	}
264
-
265
-	public function getAvailability(): array {
266
-		return $this->getWrapperStorage()->getAvailability();
267
-	}
268
-
269
-	public function setAvailability(bool $isAvailable): void {
270
-		$this->getWrapperStorage()->setAvailability($isAvailable);
271
-	}
272
-
273
-	public function verifyPath(string $path, string $fileName): void {
274
-		$this->getWrapperStorage()->verifyPath($path, $fileName);
275
-	}
276
-
277
-	public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
278
-		if ($sourceStorage === $this) {
279
-			return $this->copy($sourceInternalPath, $targetInternalPath);
280
-		}
281
-
282
-		return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
283
-	}
284
-
285
-	public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
286
-		if ($sourceStorage === $this) {
287
-			return $this->rename($sourceInternalPath, $targetInternalPath);
288
-		}
289
-
290
-		return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
291
-	}
292
-
293
-	public function getMetaData(string $path): ?array {
294
-		return $this->getWrapperStorage()->getMetaData($path);
295
-	}
296
-
297
-	public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
298
-		if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
299
-			$this->getWrapperStorage()->acquireLock($path, $type, $provider);
300
-		}
301
-	}
302
-
303
-	public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
304
-		if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
305
-			$this->getWrapperStorage()->releaseLock($path, $type, $provider);
306
-		}
307
-	}
308
-
309
-	public function changeLock(string $path, int $type, ILockingProvider $provider): void {
310
-		if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
311
-			$this->getWrapperStorage()->changeLock($path, $type, $provider);
312
-		}
313
-	}
314
-
315
-	public function needsPartFile(): bool {
316
-		return $this->getWrapperStorage()->needsPartFile();
317
-	}
318
-
319
-	public function writeStream(string $path, $stream, ?int $size = null): int {
320
-		$storage = $this->getWrapperStorage();
321
-		if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
322
-			/** @var IWriteStreamStorage $storage */
323
-			return $storage->writeStream($path, $stream, $size);
324
-		} else {
325
-			$target = $this->fopen($path, 'w');
326
-			$count = Files::streamCopy($stream, $target);
327
-			fclose($stream);
328
-			fclose($target);
329
-			return $count;
330
-		}
331
-	}
332
-
333
-	public function getDirectoryContent(string $directory): \Traversable {
334
-		return $this->getWrapperStorage()->getDirectoryContent($directory);
335
-	}
336
-
337
-	public function isWrapperOf(IStorage $storage): bool {
338
-		$wrapped = $this->getWrapperStorage();
339
-		if ($wrapped === $storage) {
340
-			return true;
341
-		}
342
-		if ($wrapped instanceof Wrapper) {
343
-			return $wrapped->isWrapperOf($storage);
344
-		}
345
-		return false;
346
-	}
347
-
348
-	public function setOwner(?string $user): void {
349
-		$this->getWrapperStorage()->setOwner($user);
350
-	}
26
+    /**
27
+     * @var \OC\Files\Storage\Storage $storage
28
+     */
29
+    protected $storage;
30
+
31
+    public $cache;
32
+    public $scanner;
33
+    public $watcher;
34
+    public $propagator;
35
+    public $updater;
36
+
37
+    /**
38
+     * @param array $parameters
39
+     */
40
+    public function __construct(array $parameters) {
41
+        $this->storage = $parameters['storage'];
42
+    }
43
+
44
+    public function getWrapperStorage(): Storage {
45
+        if (!$this->storage) {
46
+            $message = 'storage wrapper ' . get_class($this) . " doesn't have a wrapped storage set";
47
+            $logger = Server::get(LoggerInterface::class);
48
+            $logger->error($message);
49
+            $this->storage = new FailedStorage(['exception' => new \Exception($message)]);
50
+        }
51
+        return $this->storage;
52
+    }
53
+
54
+    public function getId(): string {
55
+        return $this->getWrapperStorage()->getId();
56
+    }
57
+
58
+    public function mkdir(string $path): bool {
59
+        return $this->getWrapperStorage()->mkdir($path);
60
+    }
61
+
62
+    public function rmdir(string $path): bool {
63
+        return $this->getWrapperStorage()->rmdir($path);
64
+    }
65
+
66
+    public function opendir(string $path) {
67
+        return $this->getWrapperStorage()->opendir($path);
68
+    }
69
+
70
+    public function is_dir(string $path): bool {
71
+        return $this->getWrapperStorage()->is_dir($path);
72
+    }
73
+
74
+    public function is_file(string $path): bool {
75
+        return $this->getWrapperStorage()->is_file($path);
76
+    }
77
+
78
+    public function stat(string $path): array|false {
79
+        return $this->getWrapperStorage()->stat($path);
80
+    }
81
+
82
+    public function filetype(string $path): string|false {
83
+        return $this->getWrapperStorage()->filetype($path);
84
+    }
85
+
86
+    public function filesize(string $path): int|float|false {
87
+        return $this->getWrapperStorage()->filesize($path);
88
+    }
89
+
90
+    public function isCreatable(string $path): bool {
91
+        return $this->getWrapperStorage()->isCreatable($path);
92
+    }
93
+
94
+    public function isReadable(string $path): bool {
95
+        return $this->getWrapperStorage()->isReadable($path);
96
+    }
97
+
98
+    public function isUpdatable(string $path): bool {
99
+        return $this->getWrapperStorage()->isUpdatable($path);
100
+    }
101
+
102
+    public function isDeletable(string $path): bool {
103
+        return $this->getWrapperStorage()->isDeletable($path);
104
+    }
105
+
106
+    public function isSharable(string $path): bool {
107
+        return $this->getWrapperStorage()->isSharable($path);
108
+    }
109
+
110
+    public function getPermissions(string $path): int {
111
+        return $this->getWrapperStorage()->getPermissions($path);
112
+    }
113
+
114
+    public function file_exists(string $path): bool {
115
+        return $this->getWrapperStorage()->file_exists($path);
116
+    }
117
+
118
+    public function filemtime(string $path): int|false {
119
+        return $this->getWrapperStorage()->filemtime($path);
120
+    }
121
+
122
+    public function file_get_contents(string $path): string|false {
123
+        return $this->getWrapperStorage()->file_get_contents($path);
124
+    }
125
+
126
+    public function file_put_contents(string $path, mixed $data): int|float|false {
127
+        return $this->getWrapperStorage()->file_put_contents($path, $data);
128
+    }
129
+
130
+    public function unlink(string $path): bool {
131
+        return $this->getWrapperStorage()->unlink($path);
132
+    }
133
+
134
+    public function rename(string $source, string $target): bool {
135
+        return $this->getWrapperStorage()->rename($source, $target);
136
+    }
137
+
138
+    public function copy(string $source, string $target): bool {
139
+        return $this->getWrapperStorage()->copy($source, $target);
140
+    }
141
+
142
+    public function fopen(string $path, string $mode) {
143
+        return $this->getWrapperStorage()->fopen($path, $mode);
144
+    }
145
+
146
+    public function getMimeType(string $path): string|false {
147
+        return $this->getWrapperStorage()->getMimeType($path);
148
+    }
149
+
150
+    public function hash(string $type, string $path, bool $raw = false): string|false {
151
+        return $this->getWrapperStorage()->hash($type, $path, $raw);
152
+    }
153
+
154
+    public function free_space(string $path): int|float|false {
155
+        return $this->getWrapperStorage()->free_space($path);
156
+    }
157
+
158
+    public function touch(string $path, ?int $mtime = null): bool {
159
+        return $this->getWrapperStorage()->touch($path, $mtime);
160
+    }
161
+
162
+    public function getLocalFile(string $path): string|false {
163
+        return $this->getWrapperStorage()->getLocalFile($path);
164
+    }
165
+
166
+    public function hasUpdated(string $path, int $time): bool {
167
+        return $this->getWrapperStorage()->hasUpdated($path, $time);
168
+    }
169
+
170
+    public function getCache(string $path = '', ?IStorage $storage = null): ICache {
171
+        if (!$storage) {
172
+            $storage = $this;
173
+        }
174
+        return $this->getWrapperStorage()->getCache($path, $storage);
175
+    }
176
+
177
+    public function getScanner(string $path = '', ?IStorage $storage = null): IScanner {
178
+        if (!$storage) {
179
+            $storage = $this;
180
+        }
181
+        return $this->getWrapperStorage()->getScanner($path, $storage);
182
+    }
183
+
184
+    public function getOwner(string $path): string|false {
185
+        return $this->getWrapperStorage()->getOwner($path);
186
+    }
187
+
188
+    public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
189
+        if (!$storage) {
190
+            $storage = $this;
191
+        }
192
+        return $this->getWrapperStorage()->getWatcher($path, $storage);
193
+    }
194
+
195
+    public function getPropagator(?IStorage $storage = null): IPropagator {
196
+        if (!$storage) {
197
+            $storage = $this;
198
+        }
199
+        return $this->getWrapperStorage()->getPropagator($storage);
200
+    }
201
+
202
+    public function getUpdater(?IStorage $storage = null): IUpdater {
203
+        if (!$storage) {
204
+            $storage = $this;
205
+        }
206
+        return $this->getWrapperStorage()->getUpdater($storage);
207
+    }
208
+
209
+    public function getStorageCache(): \OC\Files\Cache\Storage {
210
+        return $this->getWrapperStorage()->getStorageCache();
211
+    }
212
+
213
+    public function getETag(string $path): string|false {
214
+        return $this->getWrapperStorage()->getETag($path);
215
+    }
216
+
217
+    public function test(): bool {
218
+        return $this->getWrapperStorage()->test();
219
+    }
220
+
221
+    public function isLocal(): bool {
222
+        return $this->getWrapperStorage()->isLocal();
223
+    }
224
+
225
+    public function instanceOfStorage(string $class): bool {
226
+        if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
227
+            // FIXME Temporary fix to keep existing checks working
228
+            $class = '\OCA\Files_Sharing\SharedStorage';
229
+        }
230
+        return is_a($this, $class) or $this->getWrapperStorage()->instanceOfStorage($class);
231
+    }
232
+
233
+    /**
234
+     * @psalm-template T of IStorage
235
+     * @psalm-param class-string<T> $class
236
+     * @psalm-return T|null
237
+     */
238
+    public function getInstanceOfStorage(string $class): ?IStorage {
239
+        $storage = $this;
240
+        while ($storage instanceof Wrapper) {
241
+            if ($storage instanceof $class) {
242
+                break;
243
+            }
244
+            $storage = $storage->getWrapperStorage();
245
+        }
246
+        if (!($storage instanceof $class)) {
247
+            return null;
248
+        }
249
+        return $storage;
250
+    }
251
+
252
+    /**
253
+     * Pass any methods custom to specific storage implementations to the wrapped storage
254
+     *
255
+     * @return mixed
256
+     */
257
+    public function __call(string $method, array $args) {
258
+        return call_user_func_array([$this->getWrapperStorage(), $method], $args);
259
+    }
260
+
261
+    public function getDirectDownload(string $path): array|false {
262
+        return $this->getWrapperStorage()->getDirectDownload($path);
263
+    }
264
+
265
+    public function getAvailability(): array {
266
+        return $this->getWrapperStorage()->getAvailability();
267
+    }
268
+
269
+    public function setAvailability(bool $isAvailable): void {
270
+        $this->getWrapperStorage()->setAvailability($isAvailable);
271
+    }
272
+
273
+    public function verifyPath(string $path, string $fileName): void {
274
+        $this->getWrapperStorage()->verifyPath($path, $fileName);
275
+    }
276
+
277
+    public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
278
+        if ($sourceStorage === $this) {
279
+            return $this->copy($sourceInternalPath, $targetInternalPath);
280
+        }
281
+
282
+        return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
283
+    }
284
+
285
+    public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
286
+        if ($sourceStorage === $this) {
287
+            return $this->rename($sourceInternalPath, $targetInternalPath);
288
+        }
289
+
290
+        return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
291
+    }
292
+
293
+    public function getMetaData(string $path): ?array {
294
+        return $this->getWrapperStorage()->getMetaData($path);
295
+    }
296
+
297
+    public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
298
+        if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
299
+            $this->getWrapperStorage()->acquireLock($path, $type, $provider);
300
+        }
301
+    }
302
+
303
+    public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
304
+        if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
305
+            $this->getWrapperStorage()->releaseLock($path, $type, $provider);
306
+        }
307
+    }
308
+
309
+    public function changeLock(string $path, int $type, ILockingProvider $provider): void {
310
+        if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
311
+            $this->getWrapperStorage()->changeLock($path, $type, $provider);
312
+        }
313
+    }
314
+
315
+    public function needsPartFile(): bool {
316
+        return $this->getWrapperStorage()->needsPartFile();
317
+    }
318
+
319
+    public function writeStream(string $path, $stream, ?int $size = null): int {
320
+        $storage = $this->getWrapperStorage();
321
+        if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
322
+            /** @var IWriteStreamStorage $storage */
323
+            return $storage->writeStream($path, $stream, $size);
324
+        } else {
325
+            $target = $this->fopen($path, 'w');
326
+            $count = Files::streamCopy($stream, $target);
327
+            fclose($stream);
328
+            fclose($target);
329
+            return $count;
330
+        }
331
+    }
332
+
333
+    public function getDirectoryContent(string $directory): \Traversable {
334
+        return $this->getWrapperStorage()->getDirectoryContent($directory);
335
+    }
336
+
337
+    public function isWrapperOf(IStorage $storage): bool {
338
+        $wrapped = $this->getWrapperStorage();
339
+        if ($wrapped === $storage) {
340
+            return true;
341
+        }
342
+        if ($wrapped instanceof Wrapper) {
343
+            return $wrapped->isWrapperOf($storage);
344
+        }
345
+        return false;
346
+    }
347
+
348
+    public function setOwner(?string $user): void {
349
+        $this->getWrapperStorage()->setOwner($user);
350
+    }
351 351
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Jail.php 1 patch
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -25,243 +25,243 @@
 block discarded – undo
25 25
  * This restricts access to a subfolder of the wrapped storage with the subfolder becoming the root folder new storage
26 26
  */
27 27
 class Jail extends Wrapper {
28
-	/**
29
-	 * @var string
30
-	 */
31
-	protected $rootPath;
32
-
33
-	/**
34
-	 * @param array $parameters ['storage' => $storage, 'root' => $root]
35
-	 *
36
-	 * $storage: The storage that will be wrapper
37
-	 * $root: The folder in the wrapped storage that will become the root folder of the wrapped storage
38
-	 */
39
-	public function __construct(array $parameters) {
40
-		parent::__construct($parameters);
41
-		$this->rootPath = $parameters['root'];
42
-	}
43
-
44
-	public function getUnjailedPath(string $path): string {
45
-		return trim(Filesystem::normalizePath($this->rootPath . '/' . $path), '/');
46
-	}
47
-
48
-	/**
49
-	 * This is separate from Wrapper::getWrapperStorage so we can get the jailed storage consistently even if the jail is inside another wrapper
50
-	 */
51
-	public function getUnjailedStorage(): IStorage {
52
-		return $this->storage;
53
-	}
54
-
55
-
56
-	public function getJailedPath(string $path): ?string {
57
-		$root = rtrim($this->rootPath, '/') . '/';
58
-
59
-		if ($path !== $this->rootPath && !str_starts_with($path, $root)) {
60
-			return null;
61
-		} else {
62
-			$path = substr($path, strlen($this->rootPath));
63
-			return trim($path, '/');
64
-		}
65
-	}
66
-
67
-	public function getId(): string {
68
-		return parent::getId();
69
-	}
70
-
71
-	public function mkdir(string $path): bool {
72
-		return $this->getWrapperStorage()->mkdir($this->getUnjailedPath($path));
73
-	}
74
-
75
-	public function rmdir(string $path): bool {
76
-		return $this->getWrapperStorage()->rmdir($this->getUnjailedPath($path));
77
-	}
78
-
79
-	public function opendir(string $path) {
80
-		return $this->getWrapperStorage()->opendir($this->getUnjailedPath($path));
81
-	}
82
-
83
-	public function is_dir(string $path): bool {
84
-		return $this->getWrapperStorage()->is_dir($this->getUnjailedPath($path));
85
-	}
86
-
87
-	public function is_file(string $path): bool {
88
-		return $this->getWrapperStorage()->is_file($this->getUnjailedPath($path));
89
-	}
90
-
91
-	public function stat(string $path): array|false {
92
-		return $this->getWrapperStorage()->stat($this->getUnjailedPath($path));
93
-	}
94
-
95
-	public function filetype(string $path): string|false {
96
-		return $this->getWrapperStorage()->filetype($this->getUnjailedPath($path));
97
-	}
98
-
99
-	public function filesize(string $path): int|float|false {
100
-		return $this->getWrapperStorage()->filesize($this->getUnjailedPath($path));
101
-	}
102
-
103
-	public function isCreatable(string $path): bool {
104
-		return $this->getWrapperStorage()->isCreatable($this->getUnjailedPath($path));
105
-	}
106
-
107
-	public function isReadable(string $path): bool {
108
-		return $this->getWrapperStorage()->isReadable($this->getUnjailedPath($path));
109
-	}
110
-
111
-	public function isUpdatable(string $path): bool {
112
-		return $this->getWrapperStorage()->isUpdatable($this->getUnjailedPath($path));
113
-	}
114
-
115
-	public function isDeletable(string $path): bool {
116
-		return $this->getWrapperStorage()->isDeletable($this->getUnjailedPath($path));
117
-	}
118
-
119
-	public function isSharable(string $path): bool {
120
-		return $this->getWrapperStorage()->isSharable($this->getUnjailedPath($path));
121
-	}
122
-
123
-	public function getPermissions(string $path): int {
124
-		return $this->getWrapperStorage()->getPermissions($this->getUnjailedPath($path));
125
-	}
126
-
127
-	public function file_exists(string $path): bool {
128
-		return $this->getWrapperStorage()->file_exists($this->getUnjailedPath($path));
129
-	}
130
-
131
-	public function filemtime(string $path): int|false {
132
-		return $this->getWrapperStorage()->filemtime($this->getUnjailedPath($path));
133
-	}
134
-
135
-	public function file_get_contents(string $path): string|false {
136
-		return $this->getWrapperStorage()->file_get_contents($this->getUnjailedPath($path));
137
-	}
138
-
139
-	public function file_put_contents(string $path, mixed $data): int|float|false {
140
-		return $this->getWrapperStorage()->file_put_contents($this->getUnjailedPath($path), $data);
141
-	}
142
-
143
-	public function unlink(string $path): bool {
144
-		return $this->getWrapperStorage()->unlink($this->getUnjailedPath($path));
145
-	}
146
-
147
-	public function rename(string $source, string $target): bool {
148
-		return $this->getWrapperStorage()->rename($this->getUnjailedPath($source), $this->getUnjailedPath($target));
149
-	}
150
-
151
-	public function copy(string $source, string $target): bool {
152
-		return $this->getWrapperStorage()->copy($this->getUnjailedPath($source), $this->getUnjailedPath($target));
153
-	}
154
-
155
-	public function fopen(string $path, string $mode) {
156
-		return $this->getWrapperStorage()->fopen($this->getUnjailedPath($path), $mode);
157
-	}
158
-
159
-	public function getMimeType(string $path): string|false {
160
-		return $this->getWrapperStorage()->getMimeType($this->getUnjailedPath($path));
161
-	}
162
-
163
-	public function hash(string $type, string $path, bool $raw = false): string|false {
164
-		return $this->getWrapperStorage()->hash($type, $this->getUnjailedPath($path), $raw);
165
-	}
166
-
167
-	public function free_space(string $path): int|float|false {
168
-		return $this->getWrapperStorage()->free_space($this->getUnjailedPath($path));
169
-	}
170
-
171
-	public function touch(string $path, ?int $mtime = null): bool {
172
-		return $this->getWrapperStorage()->touch($this->getUnjailedPath($path), $mtime);
173
-	}
174
-
175
-	public function getLocalFile(string $path): string|false {
176
-		return $this->getWrapperStorage()->getLocalFile($this->getUnjailedPath($path));
177
-	}
178
-
179
-	public function hasUpdated(string $path, int $time): bool {
180
-		return $this->getWrapperStorage()->hasUpdated($this->getUnjailedPath($path), $time);
181
-	}
182
-
183
-	public function getCache(string $path = '', ?IStorage $storage = null): ICache {
184
-		$sourceCache = $this->getWrapperStorage()->getCache($this->getUnjailedPath($path));
185
-		return new CacheJail($sourceCache, $this->rootPath);
186
-	}
187
-
188
-	public function getOwner(string $path): string|false {
189
-		return $this->getWrapperStorage()->getOwner($this->getUnjailedPath($path));
190
-	}
191
-
192
-	public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
193
-		$sourceWatcher = $this->getWrapperStorage()->getWatcher($this->getUnjailedPath($path), $this->getWrapperStorage());
194
-		return new JailWatcher($sourceWatcher, $this->rootPath);
195
-	}
196
-
197
-	public function getETag(string $path): string|false {
198
-		return $this->getWrapperStorage()->getETag($this->getUnjailedPath($path));
199
-	}
200
-
201
-	public function getMetaData(string $path): ?array {
202
-		return $this->getWrapperStorage()->getMetaData($this->getUnjailedPath($path));
203
-	}
204
-
205
-	public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
206
-		$this->getWrapperStorage()->acquireLock($this->getUnjailedPath($path), $type, $provider);
207
-	}
208
-
209
-	public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
210
-		$this->getWrapperStorage()->releaseLock($this->getUnjailedPath($path), $type, $provider);
211
-	}
212
-
213
-	public function changeLock(string $path, int $type, ILockingProvider $provider): void {
214
-		$this->getWrapperStorage()->changeLock($this->getUnjailedPath($path), $type, $provider);
215
-	}
216
-
217
-	/**
218
-	 * Resolve the path for the source of the share
219
-	 */
220
-	public function resolvePath(string $path): array {
221
-		return [$this->getWrapperStorage(), $this->getUnjailedPath($path)];
222
-	}
223
-
224
-	public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
225
-		if ($sourceStorage === $this) {
226
-			return $this->copy($sourceInternalPath, $targetInternalPath);
227
-		}
228
-		return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
229
-	}
230
-
231
-	public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
232
-		if ($sourceStorage === $this) {
233
-			return $this->rename($sourceInternalPath, $targetInternalPath);
234
-		}
235
-		return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
236
-	}
237
-
238
-	public function getPropagator(?IStorage $storage = null): IPropagator {
239
-		if (isset($this->propagator)) {
240
-			return $this->propagator;
241
-		}
242
-
243
-		if (!$storage) {
244
-			$storage = $this;
245
-		}
246
-		$this->propagator = new JailPropagator($storage, \OC::$server->getDatabaseConnection());
247
-		return $this->propagator;
248
-	}
249
-
250
-	public function writeStream(string $path, $stream, ?int $size = null): int {
251
-		$storage = $this->getWrapperStorage();
252
-		if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
253
-			/** @var IWriteStreamStorage $storage */
254
-			return $storage->writeStream($this->getUnjailedPath($path), $stream, $size);
255
-		} else {
256
-			$target = $this->fopen($path, 'w');
257
-			$count = Files::streamCopy($stream, $target);
258
-			fclose($stream);
259
-			fclose($target);
260
-			return $count;
261
-		}
262
-	}
263
-
264
-	public function getDirectoryContent(string $directory): \Traversable {
265
-		return $this->getWrapperStorage()->getDirectoryContent($this->getUnjailedPath($directory));
266
-	}
28
+    /**
29
+     * @var string
30
+     */
31
+    protected $rootPath;
32
+
33
+    /**
34
+     * @param array $parameters ['storage' => $storage, 'root' => $root]
35
+     *
36
+     * $storage: The storage that will be wrapper
37
+     * $root: The folder in the wrapped storage that will become the root folder of the wrapped storage
38
+     */
39
+    public function __construct(array $parameters) {
40
+        parent::__construct($parameters);
41
+        $this->rootPath = $parameters['root'];
42
+    }
43
+
44
+    public function getUnjailedPath(string $path): string {
45
+        return trim(Filesystem::normalizePath($this->rootPath . '/' . $path), '/');
46
+    }
47
+
48
+    /**
49
+     * This is separate from Wrapper::getWrapperStorage so we can get the jailed storage consistently even if the jail is inside another wrapper
50
+     */
51
+    public function getUnjailedStorage(): IStorage {
52
+        return $this->storage;
53
+    }
54
+
55
+
56
+    public function getJailedPath(string $path): ?string {
57
+        $root = rtrim($this->rootPath, '/') . '/';
58
+
59
+        if ($path !== $this->rootPath && !str_starts_with($path, $root)) {
60
+            return null;
61
+        } else {
62
+            $path = substr($path, strlen($this->rootPath));
63
+            return trim($path, '/');
64
+        }
65
+    }
66
+
67
+    public function getId(): string {
68
+        return parent::getId();
69
+    }
70
+
71
+    public function mkdir(string $path): bool {
72
+        return $this->getWrapperStorage()->mkdir($this->getUnjailedPath($path));
73
+    }
74
+
75
+    public function rmdir(string $path): bool {
76
+        return $this->getWrapperStorage()->rmdir($this->getUnjailedPath($path));
77
+    }
78
+
79
+    public function opendir(string $path) {
80
+        return $this->getWrapperStorage()->opendir($this->getUnjailedPath($path));
81
+    }
82
+
83
+    public function is_dir(string $path): bool {
84
+        return $this->getWrapperStorage()->is_dir($this->getUnjailedPath($path));
85
+    }
86
+
87
+    public function is_file(string $path): bool {
88
+        return $this->getWrapperStorage()->is_file($this->getUnjailedPath($path));
89
+    }
90
+
91
+    public function stat(string $path): array|false {
92
+        return $this->getWrapperStorage()->stat($this->getUnjailedPath($path));
93
+    }
94
+
95
+    public function filetype(string $path): string|false {
96
+        return $this->getWrapperStorage()->filetype($this->getUnjailedPath($path));
97
+    }
98
+
99
+    public function filesize(string $path): int|float|false {
100
+        return $this->getWrapperStorage()->filesize($this->getUnjailedPath($path));
101
+    }
102
+
103
+    public function isCreatable(string $path): bool {
104
+        return $this->getWrapperStorage()->isCreatable($this->getUnjailedPath($path));
105
+    }
106
+
107
+    public function isReadable(string $path): bool {
108
+        return $this->getWrapperStorage()->isReadable($this->getUnjailedPath($path));
109
+    }
110
+
111
+    public function isUpdatable(string $path): bool {
112
+        return $this->getWrapperStorage()->isUpdatable($this->getUnjailedPath($path));
113
+    }
114
+
115
+    public function isDeletable(string $path): bool {
116
+        return $this->getWrapperStorage()->isDeletable($this->getUnjailedPath($path));
117
+    }
118
+
119
+    public function isSharable(string $path): bool {
120
+        return $this->getWrapperStorage()->isSharable($this->getUnjailedPath($path));
121
+    }
122
+
123
+    public function getPermissions(string $path): int {
124
+        return $this->getWrapperStorage()->getPermissions($this->getUnjailedPath($path));
125
+    }
126
+
127
+    public function file_exists(string $path): bool {
128
+        return $this->getWrapperStorage()->file_exists($this->getUnjailedPath($path));
129
+    }
130
+
131
+    public function filemtime(string $path): int|false {
132
+        return $this->getWrapperStorage()->filemtime($this->getUnjailedPath($path));
133
+    }
134
+
135
+    public function file_get_contents(string $path): string|false {
136
+        return $this->getWrapperStorage()->file_get_contents($this->getUnjailedPath($path));
137
+    }
138
+
139
+    public function file_put_contents(string $path, mixed $data): int|float|false {
140
+        return $this->getWrapperStorage()->file_put_contents($this->getUnjailedPath($path), $data);
141
+    }
142
+
143
+    public function unlink(string $path): bool {
144
+        return $this->getWrapperStorage()->unlink($this->getUnjailedPath($path));
145
+    }
146
+
147
+    public function rename(string $source, string $target): bool {
148
+        return $this->getWrapperStorage()->rename($this->getUnjailedPath($source), $this->getUnjailedPath($target));
149
+    }
150
+
151
+    public function copy(string $source, string $target): bool {
152
+        return $this->getWrapperStorage()->copy($this->getUnjailedPath($source), $this->getUnjailedPath($target));
153
+    }
154
+
155
+    public function fopen(string $path, string $mode) {
156
+        return $this->getWrapperStorage()->fopen($this->getUnjailedPath($path), $mode);
157
+    }
158
+
159
+    public function getMimeType(string $path): string|false {
160
+        return $this->getWrapperStorage()->getMimeType($this->getUnjailedPath($path));
161
+    }
162
+
163
+    public function hash(string $type, string $path, bool $raw = false): string|false {
164
+        return $this->getWrapperStorage()->hash($type, $this->getUnjailedPath($path), $raw);
165
+    }
166
+
167
+    public function free_space(string $path): int|float|false {
168
+        return $this->getWrapperStorage()->free_space($this->getUnjailedPath($path));
169
+    }
170
+
171
+    public function touch(string $path, ?int $mtime = null): bool {
172
+        return $this->getWrapperStorage()->touch($this->getUnjailedPath($path), $mtime);
173
+    }
174
+
175
+    public function getLocalFile(string $path): string|false {
176
+        return $this->getWrapperStorage()->getLocalFile($this->getUnjailedPath($path));
177
+    }
178
+
179
+    public function hasUpdated(string $path, int $time): bool {
180
+        return $this->getWrapperStorage()->hasUpdated($this->getUnjailedPath($path), $time);
181
+    }
182
+
183
+    public function getCache(string $path = '', ?IStorage $storage = null): ICache {
184
+        $sourceCache = $this->getWrapperStorage()->getCache($this->getUnjailedPath($path));
185
+        return new CacheJail($sourceCache, $this->rootPath);
186
+    }
187
+
188
+    public function getOwner(string $path): string|false {
189
+        return $this->getWrapperStorage()->getOwner($this->getUnjailedPath($path));
190
+    }
191
+
192
+    public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
193
+        $sourceWatcher = $this->getWrapperStorage()->getWatcher($this->getUnjailedPath($path), $this->getWrapperStorage());
194
+        return new JailWatcher($sourceWatcher, $this->rootPath);
195
+    }
196
+
197
+    public function getETag(string $path): string|false {
198
+        return $this->getWrapperStorage()->getETag($this->getUnjailedPath($path));
199
+    }
200
+
201
+    public function getMetaData(string $path): ?array {
202
+        return $this->getWrapperStorage()->getMetaData($this->getUnjailedPath($path));
203
+    }
204
+
205
+    public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
206
+        $this->getWrapperStorage()->acquireLock($this->getUnjailedPath($path), $type, $provider);
207
+    }
208
+
209
+    public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
210
+        $this->getWrapperStorage()->releaseLock($this->getUnjailedPath($path), $type, $provider);
211
+    }
212
+
213
+    public function changeLock(string $path, int $type, ILockingProvider $provider): void {
214
+        $this->getWrapperStorage()->changeLock($this->getUnjailedPath($path), $type, $provider);
215
+    }
216
+
217
+    /**
218
+     * Resolve the path for the source of the share
219
+     */
220
+    public function resolvePath(string $path): array {
221
+        return [$this->getWrapperStorage(), $this->getUnjailedPath($path)];
222
+    }
223
+
224
+    public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
225
+        if ($sourceStorage === $this) {
226
+            return $this->copy($sourceInternalPath, $targetInternalPath);
227
+        }
228
+        return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
229
+    }
230
+
231
+    public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
232
+        if ($sourceStorage === $this) {
233
+            return $this->rename($sourceInternalPath, $targetInternalPath);
234
+        }
235
+        return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
236
+    }
237
+
238
+    public function getPropagator(?IStorage $storage = null): IPropagator {
239
+        if (isset($this->propagator)) {
240
+            return $this->propagator;
241
+        }
242
+
243
+        if (!$storage) {
244
+            $storage = $this;
245
+        }
246
+        $this->propagator = new JailPropagator($storage, \OC::$server->getDatabaseConnection());
247
+        return $this->propagator;
248
+    }
249
+
250
+    public function writeStream(string $path, $stream, ?int $size = null): int {
251
+        $storage = $this->getWrapperStorage();
252
+        if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
253
+            /** @var IWriteStreamStorage $storage */
254
+            return $storage->writeStream($this->getUnjailedPath($path), $stream, $size);
255
+        } else {
256
+            $target = $this->fopen($path, 'w');
257
+            $count = Files::streamCopy($stream, $target);
258
+            fclose($stream);
259
+            fclose($target);
260
+            return $count;
261
+        }
262
+    }
263
+
264
+    public function getDirectoryContent(string $directory): \Traversable {
265
+        return $this->getWrapperStorage()->getDirectoryContent($this->getUnjailedPath($directory));
266
+    }
267 267
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 1 patch
Indentation   +901 added lines, -901 removed lines patch added patch discarded remove patch
@@ -28,905 +28,905 @@
 block discarded – undo
28 28
 use Psr\Log\LoggerInterface;
29 29
 
30 30
 class Encryption extends Wrapper {
31
-	use LocalTempFileTrait;
32
-
33
-	private string $mountPoint;
34
-	protected array $unencryptedSize = [];
35
-	private IMountPoint $mount;
36
-	/** for which path we execute the repair step to avoid recursions */
37
-	private array $fixUnencryptedSizeOf = [];
38
-	/** @var CappedMemoryCache<bool> */
39
-	private CappedMemoryCache $encryptedPaths;
40
-	private bool $enabled = true;
41
-
42
-	/**
43
-	 * @param array $parameters
44
-	 */
45
-	public function __construct(
46
-		array $parameters,
47
-		private IManager $encryptionManager,
48
-		private Util $util,
49
-		private LoggerInterface $logger,
50
-		private IFile $fileHelper,
51
-		private ?string $uid,
52
-		private IStorage $keyStorage,
53
-		private Manager $mountManager,
54
-		private ArrayCache $arrayCache,
55
-	) {
56
-		$this->mountPoint = $parameters['mountPoint'];
57
-		$this->mount = $parameters['mount'];
58
-		$this->encryptedPaths = new CappedMemoryCache();
59
-		parent::__construct($parameters);
60
-	}
61
-
62
-	public function filesize(string $path): int|float|false {
63
-		$fullPath = $this->getFullPath($path);
64
-
65
-		$info = $this->getCache()->get($path);
66
-		if ($info === false) {
67
-			/* Pass call to wrapped storage, it may be a special file like a part file */
68
-			return $this->storage->filesize($path);
69
-		}
70
-		if (isset($this->unencryptedSize[$fullPath])) {
71
-			$size = $this->unencryptedSize[$fullPath];
72
-
73
-			// Update file cache (only if file is already cached).
74
-			// Certain files are not cached (e.g. *.part).
75
-			if (isset($info['fileid'])) {
76
-				if ($info instanceof ICacheEntry) {
77
-					$info['encrypted'] = $info['encryptedVersion'];
78
-				} else {
79
-					/**
80
-					 * @psalm-suppress RedundantCondition
81
-					 */
82
-					if (!is_array($info)) {
83
-						$info = [];
84
-					}
85
-					$info['encrypted'] = true;
86
-					$info = new CacheEntry($info);
87
-				}
88
-
89
-				if ($size !== $info->getUnencryptedSize()) {
90
-					$this->getCache()->update($info->getId(), [
91
-						'unencrypted_size' => $size
92
-					]);
93
-				}
94
-			}
95
-
96
-			return $size;
97
-		}
98
-
99
-		if (isset($info['fileid']) && $info['encrypted']) {
100
-			return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
101
-		}
102
-
103
-		return $this->storage->filesize($path);
104
-	}
105
-
106
-	private function modifyMetaData(string $path, array $data): array {
107
-		$fullPath = $this->getFullPath($path);
108
-		$info = $this->getCache()->get($path);
109
-
110
-		if (isset($this->unencryptedSize[$fullPath])) {
111
-			$data['encrypted'] = true;
112
-			$data['size'] = $this->unencryptedSize[$fullPath];
113
-			$data['unencrypted_size'] = $data['size'];
114
-		} else {
115
-			if (isset($info['fileid']) && $info['encrypted']) {
116
-				$data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
117
-				$data['encrypted'] = true;
118
-				$data['unencrypted_size'] = $data['size'];
119
-			}
120
-		}
121
-
122
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
123
-			$data['encryptedVersion'] = $info['encryptedVersion'];
124
-		}
125
-
126
-		return $data;
127
-	}
128
-
129
-	public function getMetaData(string $path): ?array {
130
-		$data = $this->storage->getMetaData($path);
131
-		if (is_null($data)) {
132
-			return null;
133
-		}
134
-		return $this->modifyMetaData($path, $data);
135
-	}
136
-
137
-	public function getDirectoryContent(string $directory): \Traversable {
138
-		$parent = rtrim($directory, '/');
139
-		foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
140
-			yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
141
-		}
142
-	}
143
-
144
-	public function file_get_contents(string $path): string|false {
145
-		$encryptionModule = $this->getEncryptionModule($path);
146
-
147
-		if ($encryptionModule) {
148
-			$handle = $this->fopen($path, 'r');
149
-			if (!$handle) {
150
-				return false;
151
-			}
152
-			$data = stream_get_contents($handle);
153
-			fclose($handle);
154
-			return $data;
155
-		}
156
-		return $this->storage->file_get_contents($path);
157
-	}
158
-
159
-	public function file_put_contents(string $path, mixed $data): int|float|false {
160
-		// file put content will always be translated to a stream write
161
-		$handle = $this->fopen($path, 'w');
162
-		if (is_resource($handle)) {
163
-			$written = fwrite($handle, $data);
164
-			fclose($handle);
165
-			return $written;
166
-		}
167
-
168
-		return false;
169
-	}
170
-
171
-	public function unlink(string $path): bool {
172
-		$fullPath = $this->getFullPath($path);
173
-		if ($this->util->isExcluded($fullPath)) {
174
-			return $this->storage->unlink($path);
175
-		}
176
-
177
-		$encryptionModule = $this->getEncryptionModule($path);
178
-		if ($encryptionModule) {
179
-			$this->keyStorage->deleteAllFileKeys($fullPath);
180
-		}
181
-
182
-		return $this->storage->unlink($path);
183
-	}
184
-
185
-	public function rename(string $source, string $target): bool {
186
-		$result = $this->storage->rename($source, $target);
187
-
188
-		if ($result &&
189
-			// versions always use the keys from the original file, so we can skip
190
-			// this step for versions
191
-			$this->isVersion($target) === false &&
192
-			$this->encryptionManager->isEnabled()) {
193
-			$sourcePath = $this->getFullPath($source);
194
-			if (!$this->util->isExcluded($sourcePath)) {
195
-				$targetPath = $this->getFullPath($target);
196
-				if (isset($this->unencryptedSize[$sourcePath])) {
197
-					$this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
198
-				}
199
-				$this->keyStorage->renameKeys($sourcePath, $targetPath);
200
-				$module = $this->getEncryptionModule($target);
201
-				if ($module) {
202
-					$module->update($targetPath, $this->uid, []);
203
-				}
204
-			}
205
-		}
206
-
207
-		return $result;
208
-	}
209
-
210
-	public function rmdir(string $path): bool {
211
-		$result = $this->storage->rmdir($path);
212
-		$fullPath = $this->getFullPath($path);
213
-		if ($result &&
214
-			$this->util->isExcluded($fullPath) === false &&
215
-			$this->encryptionManager->isEnabled()
216
-		) {
217
-			$this->keyStorage->deleteAllFileKeys($fullPath);
218
-		}
219
-
220
-		return $result;
221
-	}
222
-
223
-	public function isReadable(string $path): bool {
224
-		$isReadable = true;
225
-
226
-		$metaData = $this->getMetaData($path);
227
-		if (
228
-			!$this->is_dir($path) &&
229
-			isset($metaData['encrypted']) &&
230
-			$metaData['encrypted'] === true
231
-		) {
232
-			$fullPath = $this->getFullPath($path);
233
-			$module = $this->getEncryptionModule($path);
234
-			$isReadable = $module->isReadable($fullPath, $this->uid);
235
-		}
236
-
237
-		return $this->storage->isReadable($path) && $isReadable;
238
-	}
239
-
240
-	public function copy(string $source, string $target): bool {
241
-		$sourcePath = $this->getFullPath($source);
242
-
243
-		if ($this->util->isExcluded($sourcePath)) {
244
-			return $this->storage->copy($source, $target);
245
-		}
246
-
247
-		// need to stream copy file by file in case we copy between a encrypted
248
-		// and a unencrypted storage
249
-		$this->unlink($target);
250
-		return $this->copyFromStorage($this, $source, $target);
251
-	}
252
-
253
-	public function fopen(string $path, string $mode) {
254
-		// check if the file is stored in the array cache, this means that we
255
-		// copy a file over to the versions folder, in this case we don't want to
256
-		// decrypt it
257
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
258
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
259
-			return $this->storage->fopen($path, $mode);
260
-		}
261
-
262
-		if (!$this->enabled) {
263
-			return $this->storage->fopen($path, $mode);
264
-		}
265
-
266
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
267
-		$shouldEncrypt = false;
268
-		$encryptionModule = null;
269
-		$header = $this->getHeader($path);
270
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
271
-		$fullPath = $this->getFullPath($path);
272
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
273
-
274
-		if ($this->util->isExcluded($fullPath) === false) {
275
-			$size = $unencryptedSize = 0;
276
-			$realFile = $this->util->stripPartialFileExtension($path);
277
-			$targetExists = $this->is_file($realFile) || $this->file_exists($path);
278
-			$targetIsEncrypted = false;
279
-			if ($targetExists) {
280
-				// in case the file exists we require the explicit module as
281
-				// specified in the file header - otherwise we need to fail hard to
282
-				// prevent data loss on client side
283
-				if (!empty($encryptionModuleId)) {
284
-					$targetIsEncrypted = true;
285
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
286
-				}
287
-
288
-				if ($this->file_exists($path)) {
289
-					$size = $this->storage->filesize($path);
290
-					$unencryptedSize = $this->filesize($path);
291
-				} else {
292
-					$size = $unencryptedSize = 0;
293
-				}
294
-			}
295
-
296
-			try {
297
-				if (
298
-					$mode === 'w'
299
-					|| $mode === 'w+'
300
-					|| $mode === 'wb'
301
-					|| $mode === 'wb+'
302
-				) {
303
-					// if we update a encrypted file with a un-encrypted one we change the db flag
304
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
305
-						$cache = $this->storage->getCache();
306
-						$entry = $cache->get($path);
307
-						$cache->update($entry->getId(), ['encrypted' => 0]);
308
-					}
309
-					if ($encryptionEnabled) {
310
-						// if $encryptionModuleId is empty, the default module will be used
311
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
312
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
313
-						$signed = true;
314
-					}
315
-				} else {
316
-					$info = $this->getCache()->get($path);
317
-					// only get encryption module if we found one in the header
318
-					// or if file should be encrypted according to the file cache
319
-					if (!empty($encryptionModuleId)) {
320
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
321
-						$shouldEncrypt = true;
322
-					} elseif ($info !== false && $info['encrypted'] === true) {
323
-						// we come from a old installation. No header and/or no module defined
324
-						// but the file is encrypted. In this case we need to use the
325
-						// OC_DEFAULT_MODULE to read the file
326
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
327
-						$shouldEncrypt = true;
328
-						$targetIsEncrypted = true;
329
-					}
330
-				}
331
-			} catch (ModuleDoesNotExistsException $e) {
332
-				$this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
333
-					'exception' => $e,
334
-					'app' => 'core',
335
-				]);
336
-			}
337
-
338
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
339
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
340
-				if (!$targetExists || !$targetIsEncrypted) {
341
-					$shouldEncrypt = false;
342
-				}
343
-			}
344
-
345
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
346
-				$this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
347
-				$headerSize = $this->getHeaderSize($path);
348
-				if ($mode === 'r' && $headerSize === 0) {
349
-					$firstBlock = $this->readFirstBlock($path);
350
-					if (!$firstBlock) {
351
-						throw new InvalidHeaderException("Unable to get header block for $path");
352
-					} elseif (!str_starts_with($firstBlock, Util::HEADER_START)) {
353
-						throw new InvalidHeaderException("Unable to get header size for $path, file doesn't start with encryption header");
354
-					} else {
355
-						throw new InvalidHeaderException("Unable to get header size for $path, even though file does start with encryption header");
356
-					}
357
-				}
358
-				$source = $this->storage->fopen($path, $mode);
359
-				if (!is_resource($source)) {
360
-					return false;
361
-				}
362
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
363
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
364
-					$size, $unencryptedSize, $headerSize, $signed);
365
-
366
-				return $handle;
367
-			}
368
-		}
369
-
370
-		return $this->storage->fopen($path, $mode);
371
-	}
372
-
373
-
374
-	/**
375
-	 * perform some plausibility checks if the unencrypted size is correct.
376
-	 * If not, we calculate the correct unencrypted size and return it
377
-	 *
378
-	 * @param string $path internal path relative to the storage root
379
-	 * @param int $unencryptedSize size of the unencrypted file
380
-	 *
381
-	 * @return int unencrypted size
382
-	 */
383
-	protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
384
-		$size = $this->storage->filesize($path);
385
-		$result = $unencryptedSize;
386
-
387
-		if ($unencryptedSize < 0 ||
388
-			($size > 0 && $unencryptedSize === $size) ||
389
-			$unencryptedSize > $size
390
-		) {
391
-			// check if we already calculate the unencrypted size for the
392
-			// given path to avoid recursions
393
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
394
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
395
-				try {
396
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
397
-				} catch (\Exception $e) {
398
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
399
-				}
400
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
401
-			}
402
-		}
403
-
404
-		return $result;
405
-	}
406
-
407
-	/**
408
-	 * calculate the unencrypted size
409
-	 *
410
-	 * @param string $path internal path relative to the storage root
411
-	 * @param int $size size of the physical file
412
-	 * @param int $unencryptedSize size of the unencrypted file
413
-	 */
414
-	protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int|float {
415
-		$headerSize = $this->getHeaderSize($path);
416
-		$header = $this->getHeader($path);
417
-		$encryptionModule = $this->getEncryptionModule($path);
418
-
419
-		$stream = $this->storage->fopen($path, 'r');
420
-
421
-		// if we couldn't open the file we return the old unencrypted size
422
-		if (!is_resource($stream)) {
423
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
424
-			return $unencryptedSize;
425
-		}
426
-
427
-		$newUnencryptedSize = 0;
428
-		$size -= $headerSize;
429
-		$blockSize = $this->util->getBlockSize();
430
-
431
-		// if a header exists we skip it
432
-		if ($headerSize > 0) {
433
-			$this->fread_block($stream, $headerSize);
434
-		}
435
-
436
-		// fast path, else the calculation for $lastChunkNr is bogus
437
-		if ($size === 0) {
438
-			return 0;
439
-		}
440
-
441
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
442
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
443
-
444
-		// calculate last chunk nr
445
-		// next highest is end of chunks, one subtracted is last one
446
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
447
-
448
-		$lastChunkNr = ceil($size / $blockSize) - 1;
449
-		// calculate last chunk position
450
-		$lastChunkPos = ($lastChunkNr * $blockSize);
451
-		// try to fseek to the last chunk, if it fails we have to read the whole file
452
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
453
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
454
-		}
455
-
456
-		$lastChunkContentEncrypted = '';
457
-		$count = $blockSize;
458
-
459
-		while ($count > 0) {
460
-			$data = $this->fread_block($stream, $blockSize);
461
-			$count = strlen($data);
462
-			$lastChunkContentEncrypted .= $data;
463
-			if (strlen($lastChunkContentEncrypted) > $blockSize) {
464
-				$newUnencryptedSize += $unencryptedBlockSize;
465
-				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
466
-			}
467
-		}
468
-
469
-		fclose($stream);
470
-
471
-		// we have to decrypt the last chunk to get it actual size
472
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
473
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
474
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
475
-
476
-		// calc the real file size with the size of the last chunk
477
-		$newUnencryptedSize += strlen($decryptedLastChunk);
478
-
479
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
480
-
481
-		// write to cache if applicable
482
-		$cache = $this->storage->getCache();
483
-		$entry = $cache->get($path);
484
-		$cache->update($entry['fileid'], [
485
-			'unencrypted_size' => $newUnencryptedSize
486
-		]);
487
-
488
-		return $newUnencryptedSize;
489
-	}
490
-
491
-	/**
492
-	 * fread_block
493
-	 *
494
-	 * This function is a wrapper around the fread function.  It is based on the
495
-	 * stream_read_block function from lib/private/Files/Streams/Encryption.php
496
-	 * It calls stream read until the requested $blockSize was received or no remaining data is present.
497
-	 * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
498
-	 * remote storage over the internet and it does not care about the given $blockSize.
499
-	 *
500
-	 * @param resource $handle the stream to read from
501
-	 * @param int $blockSize Length of requested data block in bytes
502
-	 * @return string Data fetched from stream.
503
-	 */
504
-	private function fread_block($handle, int $blockSize): string {
505
-		$remaining = $blockSize;
506
-		$data = '';
507
-
508
-		do {
509
-			$chunk = fread($handle, $remaining);
510
-			$chunk_len = strlen($chunk);
511
-			$data .= $chunk;
512
-			$remaining -= $chunk_len;
513
-		} while (($remaining > 0) && ($chunk_len > 0));
514
-
515
-		return $data;
516
-	}
517
-
518
-	public function moveFromStorage(
519
-		Storage\IStorage $sourceStorage,
520
-		string $sourceInternalPath,
521
-		string $targetInternalPath,
522
-		$preserveMtime = true,
523
-	): bool {
524
-		if ($sourceStorage === $this) {
525
-			return $this->rename($sourceInternalPath, $targetInternalPath);
526
-		}
527
-
528
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
529
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
530
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
531
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
532
-		// - remove $this->copyBetweenStorage
533
-
534
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
535
-			return false;
536
-		}
537
-
538
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
539
-		if ($result) {
540
-			$setPreserveCacheOnDelete = $sourceStorage->instanceOfStorage(ObjectStoreStorage::class) && !$this->instanceOfStorage(ObjectStoreStorage::class);
541
-			if ($setPreserveCacheOnDelete) {
542
-				/** @var ObjectStoreStorage $sourceStorage */
543
-				$sourceStorage->setPreserveCacheOnDelete(true);
544
-			}
545
-			try {
546
-				if ($sourceStorage->is_dir($sourceInternalPath)) {
547
-					$result = $sourceStorage->rmdir($sourceInternalPath);
548
-				} else {
549
-					$result = $sourceStorage->unlink($sourceInternalPath);
550
-				}
551
-			} finally {
552
-				if ($setPreserveCacheOnDelete) {
553
-					/** @var ObjectStoreStorage $sourceStorage */
554
-					$sourceStorage->setPreserveCacheOnDelete(false);
555
-				}
556
-			}
557
-		}
558
-		return $result;
559
-	}
560
-
561
-	public function copyFromStorage(
562
-		Storage\IStorage $sourceStorage,
563
-		string $sourceInternalPath,
564
-		string $targetInternalPath,
565
-		$preserveMtime = false,
566
-		$isRename = false,
567
-	): bool {
568
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
569
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
570
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
571
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
572
-		// - remove $this->copyBetweenStorage
573
-
574
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
575
-	}
576
-
577
-	/**
578
-	 * Update the encrypted cache version in the database
579
-	 */
580
-	private function updateEncryptedVersion(
581
-		Storage\IStorage $sourceStorage,
582
-		string $sourceInternalPath,
583
-		string $targetInternalPath,
584
-		bool $isRename,
585
-		bool $keepEncryptionVersion,
586
-	): void {
587
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
588
-		$cacheInformation = [
589
-			'encrypted' => $isEncrypted,
590
-		];
591
-		if ($isEncrypted) {
592
-			$sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
593
-			$targetCacheEntry = $this->getCache()->get($targetInternalPath);
594
-
595
-			// Rename of the cache already happened, so we do the cleanup on the target
596
-			if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
597
-				$encryptedVersion = $targetCacheEntry['encryptedVersion'];
598
-				$isRename = false;
599
-			} else {
600
-				$encryptedVersion = $sourceCacheEntry['encryptedVersion'];
601
-			}
602
-
603
-			// In case of a move operation from an unencrypted to an encrypted
604
-			// storage the old encrypted version would stay with "0" while the
605
-			// correct value would be "1". Thus we manually set the value to "1"
606
-			// for those cases.
607
-			// See also https://github.com/owncloud/core/issues/23078
608
-			if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
609
-				$encryptedVersion = 1;
610
-			}
611
-
612
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
613
-		}
614
-
615
-		// in case of a rename we need to manipulate the source cache because
616
-		// this information will be kept for the new target
617
-		if ($isRename) {
618
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
619
-		} else {
620
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
621
-		}
622
-	}
623
-
624
-	/**
625
-	 * copy file between two storages
626
-	 * @throws \Exception
627
-	 */
628
-	private function copyBetweenStorage(
629
-		Storage\IStorage $sourceStorage,
630
-		string $sourceInternalPath,
631
-		string $targetInternalPath,
632
-		bool $preserveMtime,
633
-		bool $isRename,
634
-	): bool {
635
-		// for versions we have nothing to do, because versions should always use the
636
-		// key from the original file. Just create a 1:1 copy and done
637
-		if ($this->isVersion($targetInternalPath) ||
638
-			$this->isVersion($sourceInternalPath)) {
639
-			// remember that we try to create a version so that we can detect it during
640
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
641
-			// create a 1:1 copy of the file
642
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
643
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
644
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
645
-			if ($result) {
646
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
647
-				// make sure that we update the unencrypted size for the version
648
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
649
-					$this->updateUnencryptedSize(
650
-						$this->getFullPath($targetInternalPath),
651
-						$info->getUnencryptedSize()
652
-					);
653
-				}
654
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
655
-			}
656
-			return $result;
657
-		}
658
-
659
-		// first copy the keys that we reuse the existing file key on the target location
660
-		// and don't create a new one which would break versions for example.
661
-		if ($sourceStorage->instanceOfStorage(Common::class) && $sourceStorage->getMountOption('mount_point')) {
662
-			$mountPoint = $sourceStorage->getMountOption('mount_point');
663
-			$source = $mountPoint . '/' . $sourceInternalPath;
664
-			$target = $this->getFullPath($targetInternalPath);
665
-			$this->copyKeys($source, $target);
666
-		} else {
667
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
668
-		}
669
-
670
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
671
-			$dh = $sourceStorage->opendir($sourceInternalPath);
672
-			if (!$this->is_dir($targetInternalPath)) {
673
-				$result = $this->mkdir($targetInternalPath);
674
-			} else {
675
-				$result = true;
676
-			}
677
-			if (is_resource($dh)) {
678
-				while ($result && ($file = readdir($dh)) !== false) {
679
-					if (!Filesystem::isIgnoredDir($file)) {
680
-						$result = $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, $preserveMtime, $isRename);
681
-					}
682
-				}
683
-			}
684
-		} else {
685
-			try {
686
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
687
-				$target = $this->fopen($targetInternalPath, 'w');
688
-				[, $result] = Files::streamCopy($source, $target, true);
689
-			} finally {
690
-				if (is_resource($source)) {
691
-					fclose($source);
692
-				}
693
-				if (is_resource($target)) {
694
-					fclose($target);
695
-				}
696
-			}
697
-			if ($result) {
698
-				if ($preserveMtime) {
699
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
700
-				}
701
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
702
-			} else {
703
-				// delete partially written target file
704
-				$this->unlink($targetInternalPath);
705
-				// delete cache entry that was created by fopen
706
-				$this->getCache()->remove($targetInternalPath);
707
-			}
708
-		}
709
-		return (bool)$result;
710
-	}
711
-
712
-	public function getLocalFile(string $path): string|false {
713
-		if ($this->encryptionManager->isEnabled()) {
714
-			$cachedFile = $this->getCachedFile($path);
715
-			if (is_string($cachedFile)) {
716
-				return $cachedFile;
717
-			}
718
-		}
719
-		return $this->storage->getLocalFile($path);
720
-	}
721
-
722
-	public function isLocal(): bool {
723
-		if ($this->encryptionManager->isEnabled()) {
724
-			return false;
725
-		}
726
-		return $this->storage->isLocal();
727
-	}
728
-
729
-	public function stat(string $path): array|false {
730
-		$stat = $this->storage->stat($path);
731
-		if (!$stat) {
732
-			return false;
733
-		}
734
-		$fileSize = $this->filesize($path);
735
-		$stat['size'] = $fileSize;
736
-		$stat[7] = $fileSize;
737
-		$stat['hasHeader'] = $this->getHeaderSize($path) > 0;
738
-		return $stat;
739
-	}
740
-
741
-	public function hash(string $type, string $path, bool $raw = false): string|false {
742
-		$fh = $this->fopen($path, 'rb');
743
-		$ctx = hash_init($type);
744
-		hash_update_stream($ctx, $fh);
745
-		fclose($fh);
746
-		return hash_final($ctx, $raw);
747
-	}
748
-
749
-	/**
750
-	 * return full path, including mount point
751
-	 *
752
-	 * @param string $path relative to mount point
753
-	 * @return string full path including mount point
754
-	 */
755
-	protected function getFullPath(string $path): string {
756
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
757
-	}
758
-
759
-	/**
760
-	 * read first block of encrypted file, typically this will contain the
761
-	 * encryption header
762
-	 */
763
-	protected function readFirstBlock(string $path): string {
764
-		$firstBlock = '';
765
-		if ($this->storage->is_file($path)) {
766
-			$handle = $this->storage->fopen($path, 'r');
767
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
768
-			fclose($handle);
769
-		}
770
-		return $firstBlock;
771
-	}
772
-
773
-	/**
774
-	 * return header size of given file
775
-	 */
776
-	protected function getHeaderSize(string $path): int {
777
-		$headerSize = 0;
778
-		$realFile = $this->util->stripPartialFileExtension($path);
779
-		if ($this->storage->is_file($realFile)) {
780
-			$path = $realFile;
781
-		}
782
-		$firstBlock = $this->readFirstBlock($path);
783
-
784
-		if (str_starts_with($firstBlock, Util::HEADER_START)) {
785
-			$headerSize = $this->util->getHeaderSize();
786
-		}
787
-
788
-		return $headerSize;
789
-	}
790
-
791
-	/**
792
-	 * read header from file
793
-	 */
794
-	protected function getHeader(string $path): array {
795
-		$realFile = $this->util->stripPartialFileExtension($path);
796
-		$exists = $this->storage->is_file($realFile);
797
-		if ($exists) {
798
-			$path = $realFile;
799
-		}
800
-
801
-		$result = [];
802
-
803
-		$isEncrypted = $this->encryptedPaths->get($realFile);
804
-		if (is_null($isEncrypted)) {
805
-			$info = $this->getCache()->get($path);
806
-			$isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
807
-		}
808
-
809
-		if ($isEncrypted) {
810
-			$firstBlock = $this->readFirstBlock($path);
811
-			$result = $this->util->parseRawHeader($firstBlock);
812
-
813
-			// if the header doesn't contain a encryption module we check if it is a
814
-			// legacy file. If true, we add the default encryption module
815
-			if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
816
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
817
-			}
818
-		}
819
-
820
-		return $result;
821
-	}
822
-
823
-	/**
824
-	 * read encryption module needed to read/write the file located at $path
825
-	 *
826
-	 * @throws ModuleDoesNotExistsException
827
-	 * @throws \Exception
828
-	 */
829
-	protected function getEncryptionModule(string $path): ?\OCP\Encryption\IEncryptionModule {
830
-		$encryptionModule = null;
831
-		$header = $this->getHeader($path);
832
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
833
-		if (!empty($encryptionModuleId)) {
834
-			try {
835
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
836
-			} catch (ModuleDoesNotExistsException $e) {
837
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
838
-				throw $e;
839
-			}
840
-		}
841
-
842
-		return $encryptionModule;
843
-	}
844
-
845
-	public function updateUnencryptedSize(string $path, int|float $unencryptedSize): void {
846
-		$this->unencryptedSize[$path] = $unencryptedSize;
847
-	}
848
-
849
-	/**
850
-	 * copy keys to new location
851
-	 *
852
-	 * @param string $source path relative to data/
853
-	 * @param string $target path relative to data/
854
-	 */
855
-	protected function copyKeys(string $source, string $target): bool {
856
-		if (!$this->util->isExcluded($source)) {
857
-			return $this->keyStorage->copyKeys($source, $target);
858
-		}
859
-
860
-		return false;
861
-	}
862
-
863
-	/**
864
-	 * check if path points to a files version
865
-	 */
866
-	protected function isVersion(string $path): bool {
867
-		$normalized = Filesystem::normalizePath($path);
868
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
869
-	}
870
-
871
-	/**
872
-	 * check if the given storage should be encrypted or not
873
-	 */
874
-	protected function shouldEncrypt(string $path): bool {
875
-		$fullPath = $this->getFullPath($path);
876
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
877
-		if ($mountPointConfig === false) {
878
-			return false;
879
-		}
880
-
881
-		try {
882
-			$encryptionModule = $this->getEncryptionModule($fullPath);
883
-		} catch (ModuleDoesNotExistsException $e) {
884
-			return false;
885
-		}
886
-
887
-		if ($encryptionModule === null) {
888
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
889
-		}
890
-
891
-		return $encryptionModule->shouldEncrypt($fullPath);
892
-	}
893
-
894
-	public function writeStream(string $path, $stream, ?int $size = null): int {
895
-		// always fall back to fopen
896
-		$target = $this->fopen($path, 'w');
897
-		[$count, $result] = Files::streamCopy($stream, $target, true);
898
-		fclose($stream);
899
-		fclose($target);
900
-
901
-		// object store, stores the size after write and doesn't update this during scan
902
-		// manually store the unencrypted size
903
-		if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class) && $this->shouldEncrypt($path)) {
904
-			$this->getCache()->put($path, ['unencrypted_size' => $count]);
905
-		}
906
-
907
-		return $count;
908
-	}
909
-
910
-	public function clearIsEncryptedCache(): void {
911
-		$this->encryptedPaths->clear();
912
-	}
913
-
914
-	/**
915
-	 * Allow temporarily disabling the wrapper
916
-	 */
917
-	public function setEnabled(bool $enabled): void {
918
-		$this->enabled = $enabled;
919
-	}
920
-
921
-	/**
922
-	 * Check if the on-disk data for a file has a valid encrypted header
923
-	 *
924
-	 * @param string $path
925
-	 * @return bool
926
-	 */
927
-	public function hasValidHeader(string $path): bool {
928
-		$firstBlock = $this->readFirstBlock($path);
929
-		$header = $this->util->parseRawHeader($firstBlock);
930
-		return (count($header) > 0);
931
-	}
31
+    use LocalTempFileTrait;
32
+
33
+    private string $mountPoint;
34
+    protected array $unencryptedSize = [];
35
+    private IMountPoint $mount;
36
+    /** for which path we execute the repair step to avoid recursions */
37
+    private array $fixUnencryptedSizeOf = [];
38
+    /** @var CappedMemoryCache<bool> */
39
+    private CappedMemoryCache $encryptedPaths;
40
+    private bool $enabled = true;
41
+
42
+    /**
43
+     * @param array $parameters
44
+     */
45
+    public function __construct(
46
+        array $parameters,
47
+        private IManager $encryptionManager,
48
+        private Util $util,
49
+        private LoggerInterface $logger,
50
+        private IFile $fileHelper,
51
+        private ?string $uid,
52
+        private IStorage $keyStorage,
53
+        private Manager $mountManager,
54
+        private ArrayCache $arrayCache,
55
+    ) {
56
+        $this->mountPoint = $parameters['mountPoint'];
57
+        $this->mount = $parameters['mount'];
58
+        $this->encryptedPaths = new CappedMemoryCache();
59
+        parent::__construct($parameters);
60
+    }
61
+
62
+    public function filesize(string $path): int|float|false {
63
+        $fullPath = $this->getFullPath($path);
64
+
65
+        $info = $this->getCache()->get($path);
66
+        if ($info === false) {
67
+            /* Pass call to wrapped storage, it may be a special file like a part file */
68
+            return $this->storage->filesize($path);
69
+        }
70
+        if (isset($this->unencryptedSize[$fullPath])) {
71
+            $size = $this->unencryptedSize[$fullPath];
72
+
73
+            // Update file cache (only if file is already cached).
74
+            // Certain files are not cached (e.g. *.part).
75
+            if (isset($info['fileid'])) {
76
+                if ($info instanceof ICacheEntry) {
77
+                    $info['encrypted'] = $info['encryptedVersion'];
78
+                } else {
79
+                    /**
80
+                     * @psalm-suppress RedundantCondition
81
+                     */
82
+                    if (!is_array($info)) {
83
+                        $info = [];
84
+                    }
85
+                    $info['encrypted'] = true;
86
+                    $info = new CacheEntry($info);
87
+                }
88
+
89
+                if ($size !== $info->getUnencryptedSize()) {
90
+                    $this->getCache()->update($info->getId(), [
91
+                        'unencrypted_size' => $size
92
+                    ]);
93
+                }
94
+            }
95
+
96
+            return $size;
97
+        }
98
+
99
+        if (isset($info['fileid']) && $info['encrypted']) {
100
+            return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
101
+        }
102
+
103
+        return $this->storage->filesize($path);
104
+    }
105
+
106
+    private function modifyMetaData(string $path, array $data): array {
107
+        $fullPath = $this->getFullPath($path);
108
+        $info = $this->getCache()->get($path);
109
+
110
+        if (isset($this->unencryptedSize[$fullPath])) {
111
+            $data['encrypted'] = true;
112
+            $data['size'] = $this->unencryptedSize[$fullPath];
113
+            $data['unencrypted_size'] = $data['size'];
114
+        } else {
115
+            if (isset($info['fileid']) && $info['encrypted']) {
116
+                $data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
117
+                $data['encrypted'] = true;
118
+                $data['unencrypted_size'] = $data['size'];
119
+            }
120
+        }
121
+
122
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
123
+            $data['encryptedVersion'] = $info['encryptedVersion'];
124
+        }
125
+
126
+        return $data;
127
+    }
128
+
129
+    public function getMetaData(string $path): ?array {
130
+        $data = $this->storage->getMetaData($path);
131
+        if (is_null($data)) {
132
+            return null;
133
+        }
134
+        return $this->modifyMetaData($path, $data);
135
+    }
136
+
137
+    public function getDirectoryContent(string $directory): \Traversable {
138
+        $parent = rtrim($directory, '/');
139
+        foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
140
+            yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
141
+        }
142
+    }
143
+
144
+    public function file_get_contents(string $path): string|false {
145
+        $encryptionModule = $this->getEncryptionModule($path);
146
+
147
+        if ($encryptionModule) {
148
+            $handle = $this->fopen($path, 'r');
149
+            if (!$handle) {
150
+                return false;
151
+            }
152
+            $data = stream_get_contents($handle);
153
+            fclose($handle);
154
+            return $data;
155
+        }
156
+        return $this->storage->file_get_contents($path);
157
+    }
158
+
159
+    public function file_put_contents(string $path, mixed $data): int|float|false {
160
+        // file put content will always be translated to a stream write
161
+        $handle = $this->fopen($path, 'w');
162
+        if (is_resource($handle)) {
163
+            $written = fwrite($handle, $data);
164
+            fclose($handle);
165
+            return $written;
166
+        }
167
+
168
+        return false;
169
+    }
170
+
171
+    public function unlink(string $path): bool {
172
+        $fullPath = $this->getFullPath($path);
173
+        if ($this->util->isExcluded($fullPath)) {
174
+            return $this->storage->unlink($path);
175
+        }
176
+
177
+        $encryptionModule = $this->getEncryptionModule($path);
178
+        if ($encryptionModule) {
179
+            $this->keyStorage->deleteAllFileKeys($fullPath);
180
+        }
181
+
182
+        return $this->storage->unlink($path);
183
+    }
184
+
185
+    public function rename(string $source, string $target): bool {
186
+        $result = $this->storage->rename($source, $target);
187
+
188
+        if ($result &&
189
+            // versions always use the keys from the original file, so we can skip
190
+            // this step for versions
191
+            $this->isVersion($target) === false &&
192
+            $this->encryptionManager->isEnabled()) {
193
+            $sourcePath = $this->getFullPath($source);
194
+            if (!$this->util->isExcluded($sourcePath)) {
195
+                $targetPath = $this->getFullPath($target);
196
+                if (isset($this->unencryptedSize[$sourcePath])) {
197
+                    $this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
198
+                }
199
+                $this->keyStorage->renameKeys($sourcePath, $targetPath);
200
+                $module = $this->getEncryptionModule($target);
201
+                if ($module) {
202
+                    $module->update($targetPath, $this->uid, []);
203
+                }
204
+            }
205
+        }
206
+
207
+        return $result;
208
+    }
209
+
210
+    public function rmdir(string $path): bool {
211
+        $result = $this->storage->rmdir($path);
212
+        $fullPath = $this->getFullPath($path);
213
+        if ($result &&
214
+            $this->util->isExcluded($fullPath) === false &&
215
+            $this->encryptionManager->isEnabled()
216
+        ) {
217
+            $this->keyStorage->deleteAllFileKeys($fullPath);
218
+        }
219
+
220
+        return $result;
221
+    }
222
+
223
+    public function isReadable(string $path): bool {
224
+        $isReadable = true;
225
+
226
+        $metaData = $this->getMetaData($path);
227
+        if (
228
+            !$this->is_dir($path) &&
229
+            isset($metaData['encrypted']) &&
230
+            $metaData['encrypted'] === true
231
+        ) {
232
+            $fullPath = $this->getFullPath($path);
233
+            $module = $this->getEncryptionModule($path);
234
+            $isReadable = $module->isReadable($fullPath, $this->uid);
235
+        }
236
+
237
+        return $this->storage->isReadable($path) && $isReadable;
238
+    }
239
+
240
+    public function copy(string $source, string $target): bool {
241
+        $sourcePath = $this->getFullPath($source);
242
+
243
+        if ($this->util->isExcluded($sourcePath)) {
244
+            return $this->storage->copy($source, $target);
245
+        }
246
+
247
+        // need to stream copy file by file in case we copy between a encrypted
248
+        // and a unencrypted storage
249
+        $this->unlink($target);
250
+        return $this->copyFromStorage($this, $source, $target);
251
+    }
252
+
253
+    public function fopen(string $path, string $mode) {
254
+        // check if the file is stored in the array cache, this means that we
255
+        // copy a file over to the versions folder, in this case we don't want to
256
+        // decrypt it
257
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
258
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
259
+            return $this->storage->fopen($path, $mode);
260
+        }
261
+
262
+        if (!$this->enabled) {
263
+            return $this->storage->fopen($path, $mode);
264
+        }
265
+
266
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
267
+        $shouldEncrypt = false;
268
+        $encryptionModule = null;
269
+        $header = $this->getHeader($path);
270
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
271
+        $fullPath = $this->getFullPath($path);
272
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
273
+
274
+        if ($this->util->isExcluded($fullPath) === false) {
275
+            $size = $unencryptedSize = 0;
276
+            $realFile = $this->util->stripPartialFileExtension($path);
277
+            $targetExists = $this->is_file($realFile) || $this->file_exists($path);
278
+            $targetIsEncrypted = false;
279
+            if ($targetExists) {
280
+                // in case the file exists we require the explicit module as
281
+                // specified in the file header - otherwise we need to fail hard to
282
+                // prevent data loss on client side
283
+                if (!empty($encryptionModuleId)) {
284
+                    $targetIsEncrypted = true;
285
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
286
+                }
287
+
288
+                if ($this->file_exists($path)) {
289
+                    $size = $this->storage->filesize($path);
290
+                    $unencryptedSize = $this->filesize($path);
291
+                } else {
292
+                    $size = $unencryptedSize = 0;
293
+                }
294
+            }
295
+
296
+            try {
297
+                if (
298
+                    $mode === 'w'
299
+                    || $mode === 'w+'
300
+                    || $mode === 'wb'
301
+                    || $mode === 'wb+'
302
+                ) {
303
+                    // if we update a encrypted file with a un-encrypted one we change the db flag
304
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
305
+                        $cache = $this->storage->getCache();
306
+                        $entry = $cache->get($path);
307
+                        $cache->update($entry->getId(), ['encrypted' => 0]);
308
+                    }
309
+                    if ($encryptionEnabled) {
310
+                        // if $encryptionModuleId is empty, the default module will be used
311
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
312
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
313
+                        $signed = true;
314
+                    }
315
+                } else {
316
+                    $info = $this->getCache()->get($path);
317
+                    // only get encryption module if we found one in the header
318
+                    // or if file should be encrypted according to the file cache
319
+                    if (!empty($encryptionModuleId)) {
320
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
321
+                        $shouldEncrypt = true;
322
+                    } elseif ($info !== false && $info['encrypted'] === true) {
323
+                        // we come from a old installation. No header and/or no module defined
324
+                        // but the file is encrypted. In this case we need to use the
325
+                        // OC_DEFAULT_MODULE to read the file
326
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
327
+                        $shouldEncrypt = true;
328
+                        $targetIsEncrypted = true;
329
+                    }
330
+                }
331
+            } catch (ModuleDoesNotExistsException $e) {
332
+                $this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
333
+                    'exception' => $e,
334
+                    'app' => 'core',
335
+                ]);
336
+            }
337
+
338
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
339
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
340
+                if (!$targetExists || !$targetIsEncrypted) {
341
+                    $shouldEncrypt = false;
342
+                }
343
+            }
344
+
345
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
346
+                $this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
347
+                $headerSize = $this->getHeaderSize($path);
348
+                if ($mode === 'r' && $headerSize === 0) {
349
+                    $firstBlock = $this->readFirstBlock($path);
350
+                    if (!$firstBlock) {
351
+                        throw new InvalidHeaderException("Unable to get header block for $path");
352
+                    } elseif (!str_starts_with($firstBlock, Util::HEADER_START)) {
353
+                        throw new InvalidHeaderException("Unable to get header size for $path, file doesn't start with encryption header");
354
+                    } else {
355
+                        throw new InvalidHeaderException("Unable to get header size for $path, even though file does start with encryption header");
356
+                    }
357
+                }
358
+                $source = $this->storage->fopen($path, $mode);
359
+                if (!is_resource($source)) {
360
+                    return false;
361
+                }
362
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
363
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
364
+                    $size, $unencryptedSize, $headerSize, $signed);
365
+
366
+                return $handle;
367
+            }
368
+        }
369
+
370
+        return $this->storage->fopen($path, $mode);
371
+    }
372
+
373
+
374
+    /**
375
+     * perform some plausibility checks if the unencrypted size is correct.
376
+     * If not, we calculate the correct unencrypted size and return it
377
+     *
378
+     * @param string $path internal path relative to the storage root
379
+     * @param int $unencryptedSize size of the unencrypted file
380
+     *
381
+     * @return int unencrypted size
382
+     */
383
+    protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
384
+        $size = $this->storage->filesize($path);
385
+        $result = $unencryptedSize;
386
+
387
+        if ($unencryptedSize < 0 ||
388
+            ($size > 0 && $unencryptedSize === $size) ||
389
+            $unencryptedSize > $size
390
+        ) {
391
+            // check if we already calculate the unencrypted size for the
392
+            // given path to avoid recursions
393
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
394
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
395
+                try {
396
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
397
+                } catch (\Exception $e) {
398
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
399
+                }
400
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
401
+            }
402
+        }
403
+
404
+        return $result;
405
+    }
406
+
407
+    /**
408
+     * calculate the unencrypted size
409
+     *
410
+     * @param string $path internal path relative to the storage root
411
+     * @param int $size size of the physical file
412
+     * @param int $unencryptedSize size of the unencrypted file
413
+     */
414
+    protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int|float {
415
+        $headerSize = $this->getHeaderSize($path);
416
+        $header = $this->getHeader($path);
417
+        $encryptionModule = $this->getEncryptionModule($path);
418
+
419
+        $stream = $this->storage->fopen($path, 'r');
420
+
421
+        // if we couldn't open the file we return the old unencrypted size
422
+        if (!is_resource($stream)) {
423
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
424
+            return $unencryptedSize;
425
+        }
426
+
427
+        $newUnencryptedSize = 0;
428
+        $size -= $headerSize;
429
+        $blockSize = $this->util->getBlockSize();
430
+
431
+        // if a header exists we skip it
432
+        if ($headerSize > 0) {
433
+            $this->fread_block($stream, $headerSize);
434
+        }
435
+
436
+        // fast path, else the calculation for $lastChunkNr is bogus
437
+        if ($size === 0) {
438
+            return 0;
439
+        }
440
+
441
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
442
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
443
+
444
+        // calculate last chunk nr
445
+        // next highest is end of chunks, one subtracted is last one
446
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
447
+
448
+        $lastChunkNr = ceil($size / $blockSize) - 1;
449
+        // calculate last chunk position
450
+        $lastChunkPos = ($lastChunkNr * $blockSize);
451
+        // try to fseek to the last chunk, if it fails we have to read the whole file
452
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
453
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
454
+        }
455
+
456
+        $lastChunkContentEncrypted = '';
457
+        $count = $blockSize;
458
+
459
+        while ($count > 0) {
460
+            $data = $this->fread_block($stream, $blockSize);
461
+            $count = strlen($data);
462
+            $lastChunkContentEncrypted .= $data;
463
+            if (strlen($lastChunkContentEncrypted) > $blockSize) {
464
+                $newUnencryptedSize += $unencryptedBlockSize;
465
+                $lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
466
+            }
467
+        }
468
+
469
+        fclose($stream);
470
+
471
+        // we have to decrypt the last chunk to get it actual size
472
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
473
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
474
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
475
+
476
+        // calc the real file size with the size of the last chunk
477
+        $newUnencryptedSize += strlen($decryptedLastChunk);
478
+
479
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
480
+
481
+        // write to cache if applicable
482
+        $cache = $this->storage->getCache();
483
+        $entry = $cache->get($path);
484
+        $cache->update($entry['fileid'], [
485
+            'unencrypted_size' => $newUnencryptedSize
486
+        ]);
487
+
488
+        return $newUnencryptedSize;
489
+    }
490
+
491
+    /**
492
+     * fread_block
493
+     *
494
+     * This function is a wrapper around the fread function.  It is based on the
495
+     * stream_read_block function from lib/private/Files/Streams/Encryption.php
496
+     * It calls stream read until the requested $blockSize was received or no remaining data is present.
497
+     * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
498
+     * remote storage over the internet and it does not care about the given $blockSize.
499
+     *
500
+     * @param resource $handle the stream to read from
501
+     * @param int $blockSize Length of requested data block in bytes
502
+     * @return string Data fetched from stream.
503
+     */
504
+    private function fread_block($handle, int $blockSize): string {
505
+        $remaining = $blockSize;
506
+        $data = '';
507
+
508
+        do {
509
+            $chunk = fread($handle, $remaining);
510
+            $chunk_len = strlen($chunk);
511
+            $data .= $chunk;
512
+            $remaining -= $chunk_len;
513
+        } while (($remaining > 0) && ($chunk_len > 0));
514
+
515
+        return $data;
516
+    }
517
+
518
+    public function moveFromStorage(
519
+        Storage\IStorage $sourceStorage,
520
+        string $sourceInternalPath,
521
+        string $targetInternalPath,
522
+        $preserveMtime = true,
523
+    ): bool {
524
+        if ($sourceStorage === $this) {
525
+            return $this->rename($sourceInternalPath, $targetInternalPath);
526
+        }
527
+
528
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
529
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
530
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
531
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
532
+        // - remove $this->copyBetweenStorage
533
+
534
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
535
+            return false;
536
+        }
537
+
538
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
539
+        if ($result) {
540
+            $setPreserveCacheOnDelete = $sourceStorage->instanceOfStorage(ObjectStoreStorage::class) && !$this->instanceOfStorage(ObjectStoreStorage::class);
541
+            if ($setPreserveCacheOnDelete) {
542
+                /** @var ObjectStoreStorage $sourceStorage */
543
+                $sourceStorage->setPreserveCacheOnDelete(true);
544
+            }
545
+            try {
546
+                if ($sourceStorage->is_dir($sourceInternalPath)) {
547
+                    $result = $sourceStorage->rmdir($sourceInternalPath);
548
+                } else {
549
+                    $result = $sourceStorage->unlink($sourceInternalPath);
550
+                }
551
+            } finally {
552
+                if ($setPreserveCacheOnDelete) {
553
+                    /** @var ObjectStoreStorage $sourceStorage */
554
+                    $sourceStorage->setPreserveCacheOnDelete(false);
555
+                }
556
+            }
557
+        }
558
+        return $result;
559
+    }
560
+
561
+    public function copyFromStorage(
562
+        Storage\IStorage $sourceStorage,
563
+        string $sourceInternalPath,
564
+        string $targetInternalPath,
565
+        $preserveMtime = false,
566
+        $isRename = false,
567
+    ): bool {
568
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
569
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
570
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
571
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
572
+        // - remove $this->copyBetweenStorage
573
+
574
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
575
+    }
576
+
577
+    /**
578
+     * Update the encrypted cache version in the database
579
+     */
580
+    private function updateEncryptedVersion(
581
+        Storage\IStorage $sourceStorage,
582
+        string $sourceInternalPath,
583
+        string $targetInternalPath,
584
+        bool $isRename,
585
+        bool $keepEncryptionVersion,
586
+    ): void {
587
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
588
+        $cacheInformation = [
589
+            'encrypted' => $isEncrypted,
590
+        ];
591
+        if ($isEncrypted) {
592
+            $sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
593
+            $targetCacheEntry = $this->getCache()->get($targetInternalPath);
594
+
595
+            // Rename of the cache already happened, so we do the cleanup on the target
596
+            if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
597
+                $encryptedVersion = $targetCacheEntry['encryptedVersion'];
598
+                $isRename = false;
599
+            } else {
600
+                $encryptedVersion = $sourceCacheEntry['encryptedVersion'];
601
+            }
602
+
603
+            // In case of a move operation from an unencrypted to an encrypted
604
+            // storage the old encrypted version would stay with "0" while the
605
+            // correct value would be "1". Thus we manually set the value to "1"
606
+            // for those cases.
607
+            // See also https://github.com/owncloud/core/issues/23078
608
+            if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
609
+                $encryptedVersion = 1;
610
+            }
611
+
612
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
613
+        }
614
+
615
+        // in case of a rename we need to manipulate the source cache because
616
+        // this information will be kept for the new target
617
+        if ($isRename) {
618
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
619
+        } else {
620
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
621
+        }
622
+    }
623
+
624
+    /**
625
+     * copy file between two storages
626
+     * @throws \Exception
627
+     */
628
+    private function copyBetweenStorage(
629
+        Storage\IStorage $sourceStorage,
630
+        string $sourceInternalPath,
631
+        string $targetInternalPath,
632
+        bool $preserveMtime,
633
+        bool $isRename,
634
+    ): bool {
635
+        // for versions we have nothing to do, because versions should always use the
636
+        // key from the original file. Just create a 1:1 copy and done
637
+        if ($this->isVersion($targetInternalPath) ||
638
+            $this->isVersion($sourceInternalPath)) {
639
+            // remember that we try to create a version so that we can detect it during
640
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
641
+            // create a 1:1 copy of the file
642
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
643
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
644
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
645
+            if ($result) {
646
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
647
+                // make sure that we update the unencrypted size for the version
648
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
649
+                    $this->updateUnencryptedSize(
650
+                        $this->getFullPath($targetInternalPath),
651
+                        $info->getUnencryptedSize()
652
+                    );
653
+                }
654
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
655
+            }
656
+            return $result;
657
+        }
658
+
659
+        // first copy the keys that we reuse the existing file key on the target location
660
+        // and don't create a new one which would break versions for example.
661
+        if ($sourceStorage->instanceOfStorage(Common::class) && $sourceStorage->getMountOption('mount_point')) {
662
+            $mountPoint = $sourceStorage->getMountOption('mount_point');
663
+            $source = $mountPoint . '/' . $sourceInternalPath;
664
+            $target = $this->getFullPath($targetInternalPath);
665
+            $this->copyKeys($source, $target);
666
+        } else {
667
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
668
+        }
669
+
670
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
671
+            $dh = $sourceStorage->opendir($sourceInternalPath);
672
+            if (!$this->is_dir($targetInternalPath)) {
673
+                $result = $this->mkdir($targetInternalPath);
674
+            } else {
675
+                $result = true;
676
+            }
677
+            if (is_resource($dh)) {
678
+                while ($result && ($file = readdir($dh)) !== false) {
679
+                    if (!Filesystem::isIgnoredDir($file)) {
680
+                        $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, $preserveMtime, $isRename);
681
+                    }
682
+                }
683
+            }
684
+        } else {
685
+            try {
686
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
687
+                $target = $this->fopen($targetInternalPath, 'w');
688
+                [, $result] = Files::streamCopy($source, $target, true);
689
+            } finally {
690
+                if (is_resource($source)) {
691
+                    fclose($source);
692
+                }
693
+                if (is_resource($target)) {
694
+                    fclose($target);
695
+                }
696
+            }
697
+            if ($result) {
698
+                if ($preserveMtime) {
699
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
700
+                }
701
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
702
+            } else {
703
+                // delete partially written target file
704
+                $this->unlink($targetInternalPath);
705
+                // delete cache entry that was created by fopen
706
+                $this->getCache()->remove($targetInternalPath);
707
+            }
708
+        }
709
+        return (bool)$result;
710
+    }
711
+
712
+    public function getLocalFile(string $path): string|false {
713
+        if ($this->encryptionManager->isEnabled()) {
714
+            $cachedFile = $this->getCachedFile($path);
715
+            if (is_string($cachedFile)) {
716
+                return $cachedFile;
717
+            }
718
+        }
719
+        return $this->storage->getLocalFile($path);
720
+    }
721
+
722
+    public function isLocal(): bool {
723
+        if ($this->encryptionManager->isEnabled()) {
724
+            return false;
725
+        }
726
+        return $this->storage->isLocal();
727
+    }
728
+
729
+    public function stat(string $path): array|false {
730
+        $stat = $this->storage->stat($path);
731
+        if (!$stat) {
732
+            return false;
733
+        }
734
+        $fileSize = $this->filesize($path);
735
+        $stat['size'] = $fileSize;
736
+        $stat[7] = $fileSize;
737
+        $stat['hasHeader'] = $this->getHeaderSize($path) > 0;
738
+        return $stat;
739
+    }
740
+
741
+    public function hash(string $type, string $path, bool $raw = false): string|false {
742
+        $fh = $this->fopen($path, 'rb');
743
+        $ctx = hash_init($type);
744
+        hash_update_stream($ctx, $fh);
745
+        fclose($fh);
746
+        return hash_final($ctx, $raw);
747
+    }
748
+
749
+    /**
750
+     * return full path, including mount point
751
+     *
752
+     * @param string $path relative to mount point
753
+     * @return string full path including mount point
754
+     */
755
+    protected function getFullPath(string $path): string {
756
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
757
+    }
758
+
759
+    /**
760
+     * read first block of encrypted file, typically this will contain the
761
+     * encryption header
762
+     */
763
+    protected function readFirstBlock(string $path): string {
764
+        $firstBlock = '';
765
+        if ($this->storage->is_file($path)) {
766
+            $handle = $this->storage->fopen($path, 'r');
767
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
768
+            fclose($handle);
769
+        }
770
+        return $firstBlock;
771
+    }
772
+
773
+    /**
774
+     * return header size of given file
775
+     */
776
+    protected function getHeaderSize(string $path): int {
777
+        $headerSize = 0;
778
+        $realFile = $this->util->stripPartialFileExtension($path);
779
+        if ($this->storage->is_file($realFile)) {
780
+            $path = $realFile;
781
+        }
782
+        $firstBlock = $this->readFirstBlock($path);
783
+
784
+        if (str_starts_with($firstBlock, Util::HEADER_START)) {
785
+            $headerSize = $this->util->getHeaderSize();
786
+        }
787
+
788
+        return $headerSize;
789
+    }
790
+
791
+    /**
792
+     * read header from file
793
+     */
794
+    protected function getHeader(string $path): array {
795
+        $realFile = $this->util->stripPartialFileExtension($path);
796
+        $exists = $this->storage->is_file($realFile);
797
+        if ($exists) {
798
+            $path = $realFile;
799
+        }
800
+
801
+        $result = [];
802
+
803
+        $isEncrypted = $this->encryptedPaths->get($realFile);
804
+        if (is_null($isEncrypted)) {
805
+            $info = $this->getCache()->get($path);
806
+            $isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
807
+        }
808
+
809
+        if ($isEncrypted) {
810
+            $firstBlock = $this->readFirstBlock($path);
811
+            $result = $this->util->parseRawHeader($firstBlock);
812
+
813
+            // if the header doesn't contain a encryption module we check if it is a
814
+            // legacy file. If true, we add the default encryption module
815
+            if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
816
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
817
+            }
818
+        }
819
+
820
+        return $result;
821
+    }
822
+
823
+    /**
824
+     * read encryption module needed to read/write the file located at $path
825
+     *
826
+     * @throws ModuleDoesNotExistsException
827
+     * @throws \Exception
828
+     */
829
+    protected function getEncryptionModule(string $path): ?\OCP\Encryption\IEncryptionModule {
830
+        $encryptionModule = null;
831
+        $header = $this->getHeader($path);
832
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
833
+        if (!empty($encryptionModuleId)) {
834
+            try {
835
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
836
+            } catch (ModuleDoesNotExistsException $e) {
837
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
838
+                throw $e;
839
+            }
840
+        }
841
+
842
+        return $encryptionModule;
843
+    }
844
+
845
+    public function updateUnencryptedSize(string $path, int|float $unencryptedSize): void {
846
+        $this->unencryptedSize[$path] = $unencryptedSize;
847
+    }
848
+
849
+    /**
850
+     * copy keys to new location
851
+     *
852
+     * @param string $source path relative to data/
853
+     * @param string $target path relative to data/
854
+     */
855
+    protected function copyKeys(string $source, string $target): bool {
856
+        if (!$this->util->isExcluded($source)) {
857
+            return $this->keyStorage->copyKeys($source, $target);
858
+        }
859
+
860
+        return false;
861
+    }
862
+
863
+    /**
864
+     * check if path points to a files version
865
+     */
866
+    protected function isVersion(string $path): bool {
867
+        $normalized = Filesystem::normalizePath($path);
868
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
869
+    }
870
+
871
+    /**
872
+     * check if the given storage should be encrypted or not
873
+     */
874
+    protected function shouldEncrypt(string $path): bool {
875
+        $fullPath = $this->getFullPath($path);
876
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
877
+        if ($mountPointConfig === false) {
878
+            return false;
879
+        }
880
+
881
+        try {
882
+            $encryptionModule = $this->getEncryptionModule($fullPath);
883
+        } catch (ModuleDoesNotExistsException $e) {
884
+            return false;
885
+        }
886
+
887
+        if ($encryptionModule === null) {
888
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
889
+        }
890
+
891
+        return $encryptionModule->shouldEncrypt($fullPath);
892
+    }
893
+
894
+    public function writeStream(string $path, $stream, ?int $size = null): int {
895
+        // always fall back to fopen
896
+        $target = $this->fopen($path, 'w');
897
+        [$count, $result] = Files::streamCopy($stream, $target, true);
898
+        fclose($stream);
899
+        fclose($target);
900
+
901
+        // object store, stores the size after write and doesn't update this during scan
902
+        // manually store the unencrypted size
903
+        if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class) && $this->shouldEncrypt($path)) {
904
+            $this->getCache()->put($path, ['unencrypted_size' => $count]);
905
+        }
906
+
907
+        return $count;
908
+    }
909
+
910
+    public function clearIsEncryptedCache(): void {
911
+        $this->encryptedPaths->clear();
912
+    }
913
+
914
+    /**
915
+     * Allow temporarily disabling the wrapper
916
+     */
917
+    public function setEnabled(bool $enabled): void {
918
+        $this->enabled = $enabled;
919
+    }
920
+
921
+    /**
922
+     * Check if the on-disk data for a file has a valid encrypted header
923
+     *
924
+     * @param string $path
925
+     * @return bool
926
+     */
927
+    public function hasValidHeader(string $path): bool {
928
+        $firstBlock = $this->readFirstBlock($path);
929
+        $header = $this->util->parseRawHeader($firstBlock);
930
+        return (count($header) > 0);
931
+    }
932 932
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/LocalTempFileTrait.php 1 patch
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -21,34 +21,34 @@
 block discarded – undo
21 21
  * in classes which extend it, e.g. $this->stat() .
22 22
  */
23 23
 trait LocalTempFileTrait {
24
-	/** @var array<string,string|false> */
25
-	protected array $cachedFiles = [];
24
+    /** @var array<string,string|false> */
25
+    protected array $cachedFiles = [];
26 26
 
27
-	protected function getCachedFile(string $path): string|false {
28
-		if (!isset($this->cachedFiles[$path])) {
29
-			$this->cachedFiles[$path] = $this->toTmpFile($path);
30
-		}
31
-		return $this->cachedFiles[$path];
32
-	}
27
+    protected function getCachedFile(string $path): string|false {
28
+        if (!isset($this->cachedFiles[$path])) {
29
+            $this->cachedFiles[$path] = $this->toTmpFile($path);
30
+        }
31
+        return $this->cachedFiles[$path];
32
+    }
33 33
 
34
-	protected function removeCachedFile(string $path): void {
35
-		unset($this->cachedFiles[$path]);
36
-	}
34
+    protected function removeCachedFile(string $path): void {
35
+        unset($this->cachedFiles[$path]);
36
+    }
37 37
 
38
-	protected function toTmpFile(string $path): string|false { //no longer in the storage api, still useful here
39
-		$source = $this->fopen($path, 'r');
40
-		if (!$source) {
41
-			return false;
42
-		}
43
-		if ($pos = strrpos($path, '.')) {
44
-			$extension = substr($path, $pos);
45
-		} else {
46
-			$extension = '';
47
-		}
48
-		$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
49
-		$target = fopen($tmpFile, 'w');
50
-		Files::streamCopy($source, $target);
51
-		fclose($target);
52
-		return $tmpFile;
53
-	}
38
+    protected function toTmpFile(string $path): string|false { //no longer in the storage api, still useful here
39
+        $source = $this->fopen($path, 'r');
40
+        if (!$source) {
41
+            return false;
42
+        }
43
+        if ($pos = strrpos($path, '.')) {
44
+            $extension = substr($path, $pos);
45
+        } else {
46
+            $extension = '';
47
+        }
48
+        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
49
+        $target = fopen($tmpFile, 'w');
50
+        Files::streamCopy($source, $target);
51
+        fclose($target);
52
+        return $tmpFile;
53
+    }
54 54
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Common.php 1 patch
Indentation   +714 added lines, -714 removed lines patch added patch discarded remove patch
@@ -52,718 +52,718 @@
 block discarded – undo
52 52
  * in classes which extend it, e.g. $this->stat() .
53 53
  */
54 54
 abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage, IConstructableStorage {
55
-	use LocalTempFileTrait;
56
-
57
-	protected ?Cache $cache = null;
58
-	protected ?Scanner $scanner = null;
59
-	protected ?Watcher $watcher = null;
60
-	protected ?Propagator $propagator = null;
61
-	protected $storageCache;
62
-	protected ?Updater $updater = null;
63
-
64
-	protected array $mountOptions = [];
65
-	protected $owner = null;
66
-
67
-	private ?bool $shouldLogLocks = null;
68
-	private ?LoggerInterface $logger = null;
69
-	private ?IFilenameValidator $filenameValidator = null;
70
-
71
-	public function __construct(array $parameters) {
72
-	}
73
-
74
-	protected function remove(string $path): bool {
75
-		if ($this->file_exists($path)) {
76
-			if ($this->is_dir($path)) {
77
-				return $this->rmdir($path);
78
-			} elseif ($this->is_file($path)) {
79
-				return $this->unlink($path);
80
-			}
81
-		}
82
-		return false;
83
-	}
84
-
85
-	public function is_dir(string $path): bool {
86
-		return $this->filetype($path) === 'dir';
87
-	}
88
-
89
-	public function is_file(string $path): bool {
90
-		return $this->filetype($path) === 'file';
91
-	}
92
-
93
-	public function filesize(string $path): int|float|false {
94
-		if ($this->is_dir($path)) {
95
-			return 0; //by definition
96
-		} else {
97
-			$stat = $this->stat($path);
98
-			return isset($stat['size']) ? $stat['size'] : 0;
99
-		}
100
-	}
101
-
102
-	public function isReadable(string $path): bool {
103
-		// at least check whether it exists
104
-		// subclasses might want to implement this more thoroughly
105
-		return $this->file_exists($path);
106
-	}
107
-
108
-	public function isUpdatable(string $path): bool {
109
-		// at least check whether it exists
110
-		// subclasses might want to implement this more thoroughly
111
-		// a non-existing file/folder isn't updatable
112
-		return $this->file_exists($path);
113
-	}
114
-
115
-	public function isCreatable(string $path): bool {
116
-		if ($this->is_dir($path) && $this->isUpdatable($path)) {
117
-			return true;
118
-		}
119
-		return false;
120
-	}
121
-
122
-	public function isDeletable(string $path): bool {
123
-		if ($path === '' || $path === '/') {
124
-			return $this->isUpdatable($path);
125
-		}
126
-		$parent = dirname($path);
127
-		return $this->isUpdatable($parent) && $this->isUpdatable($path);
128
-	}
129
-
130
-	public function isSharable(string $path): bool {
131
-		return $this->isReadable($path);
132
-	}
133
-
134
-	public function getPermissions(string $path): int {
135
-		$permissions = 0;
136
-		if ($this->isCreatable($path)) {
137
-			$permissions |= \OCP\Constants::PERMISSION_CREATE;
138
-		}
139
-		if ($this->isReadable($path)) {
140
-			$permissions |= \OCP\Constants::PERMISSION_READ;
141
-		}
142
-		if ($this->isUpdatable($path)) {
143
-			$permissions |= \OCP\Constants::PERMISSION_UPDATE;
144
-		}
145
-		if ($this->isDeletable($path)) {
146
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
147
-		}
148
-		if ($this->isSharable($path)) {
149
-			$permissions |= \OCP\Constants::PERMISSION_SHARE;
150
-		}
151
-		return $permissions;
152
-	}
153
-
154
-	public function filemtime(string $path): int|false {
155
-		$stat = $this->stat($path);
156
-		if (isset($stat['mtime']) && $stat['mtime'] > 0) {
157
-			return $stat['mtime'];
158
-		} else {
159
-			return 0;
160
-		}
161
-	}
162
-
163
-	public function file_get_contents(string $path): string|false {
164
-		$handle = $this->fopen($path, 'r');
165
-		if (!$handle) {
166
-			return false;
167
-		}
168
-		$data = stream_get_contents($handle);
169
-		fclose($handle);
170
-		return $data;
171
-	}
172
-
173
-	public function file_put_contents(string $path, mixed $data): int|float|false {
174
-		$handle = $this->fopen($path, 'w');
175
-		if (!$handle) {
176
-			return false;
177
-		}
178
-		$this->removeCachedFile($path);
179
-		$count = fwrite($handle, $data);
180
-		fclose($handle);
181
-		return $count;
182
-	}
183
-
184
-	public function rename(string $source, string $target): bool {
185
-		$this->remove($target);
186
-
187
-		$this->removeCachedFile($source);
188
-		return $this->copy($source, $target) and $this->remove($source);
189
-	}
190
-
191
-	public function copy(string $source, string $target): bool {
192
-		if ($this->is_dir($source)) {
193
-			$this->remove($target);
194
-			$dir = $this->opendir($source);
195
-			$this->mkdir($target);
196
-			while (($file = readdir($dir)) !== false) {
197
-				if (!Filesystem::isIgnoredDir($file)) {
198
-					if (!$this->copy($source . '/' . $file, $target . '/' . $file)) {
199
-						closedir($dir);
200
-						return false;
201
-					}
202
-				}
203
-			}
204
-			closedir($dir);
205
-			return true;
206
-		} else {
207
-			$sourceStream = $this->fopen($source, 'r');
208
-			$targetStream = $this->fopen($target, 'w');
209
-			[, $result] = Files::streamCopy($sourceStream, $targetStream, true);
210
-			if (!$result) {
211
-				Server::get(LoggerInterface::class)->warning("Failed to write data while copying $source to $target");
212
-			}
213
-			$this->removeCachedFile($target);
214
-			return $result;
215
-		}
216
-	}
217
-
218
-	public function getMimeType(string $path): string|false {
219
-		if ($this->is_dir($path)) {
220
-			return 'httpd/unix-directory';
221
-		} elseif ($this->file_exists($path)) {
222
-			return \OC::$server->getMimeTypeDetector()->detectPath($path);
223
-		} else {
224
-			return false;
225
-		}
226
-	}
227
-
228
-	public function hash(string $type, string $path, bool $raw = false): string|false {
229
-		$fh = $this->fopen($path, 'rb');
230
-		if (!$fh) {
231
-			return false;
232
-		}
233
-		$ctx = hash_init($type);
234
-		hash_update_stream($ctx, $fh);
235
-		fclose($fh);
236
-		return hash_final($ctx, $raw);
237
-	}
238
-
239
-	public function getLocalFile(string $path): string|false {
240
-		return $this->getCachedFile($path);
241
-	}
242
-
243
-	private function addLocalFolder(string $path, string $target): void {
244
-		$dh = $this->opendir($path);
245
-		if (is_resource($dh)) {
246
-			while (($file = readdir($dh)) !== false) {
247
-				if (!Filesystem::isIgnoredDir($file)) {
248
-					if ($this->is_dir($path . '/' . $file)) {
249
-						mkdir($target . '/' . $file);
250
-						$this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
251
-					} else {
252
-						$tmp = $this->toTmpFile($path . '/' . $file);
253
-						rename($tmp, $target . '/' . $file);
254
-					}
255
-				}
256
-			}
257
-		}
258
-	}
259
-
260
-	protected function searchInDir(string $query, string $dir = ''): array {
261
-		$files = [];
262
-		$dh = $this->opendir($dir);
263
-		if (is_resource($dh)) {
264
-			while (($item = readdir($dh)) !== false) {
265
-				if (Filesystem::isIgnoredDir($item)) {
266
-					continue;
267
-				}
268
-				if (strstr(strtolower($item), strtolower($query)) !== false) {
269
-					$files[] = $dir . '/' . $item;
270
-				}
271
-				if ($this->is_dir($dir . '/' . $item)) {
272
-					$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
273
-				}
274
-			}
275
-		}
276
-		closedir($dh);
277
-		return $files;
278
-	}
279
-
280
-	/**
281
-	 * @inheritDoc
282
-	 * Check if a file or folder has been updated since $time
283
-	 *
284
-	 * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
285
-	 * the mtime should always return false here. As a result storage implementations that always return false expect
286
-	 * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
287
-	 * Nextcloud filesystem.
288
-	 */
289
-	public function hasUpdated(string $path, int $time): bool {
290
-		return $this->filemtime($path) > $time;
291
-	}
292
-
293
-	protected function getCacheDependencies(): CacheDependencies {
294
-		static $dependencies = null;
295
-		if (!$dependencies) {
296
-			$dependencies = Server::get(CacheDependencies::class);
297
-		}
298
-		return $dependencies;
299
-	}
300
-
301
-	public function getCache(string $path = '', ?IStorage $storage = null): ICache {
302
-		if (!$storage) {
303
-			$storage = $this;
304
-		}
305
-		/** @var self $storage */
306
-		if (!isset($storage->cache)) {
307
-			$storage->cache = new Cache($storage, $this->getCacheDependencies());
308
-		}
309
-		return $storage->cache;
310
-	}
311
-
312
-	public function getScanner(string $path = '', ?IStorage $storage = null): IScanner {
313
-		if (!$storage) {
314
-			$storage = $this;
315
-		}
316
-		if (!$storage->instanceOfStorage(self::class)) {
317
-			throw new \InvalidArgumentException('Storage is not of the correct class');
318
-		}
319
-		if (!isset($storage->scanner)) {
320
-			$storage->scanner = new Scanner($storage);
321
-		}
322
-		return $storage->scanner;
323
-	}
324
-
325
-	public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
326
-		if (!$storage) {
327
-			$storage = $this;
328
-		}
329
-		if (!isset($this->watcher)) {
330
-			$this->watcher = new Watcher($storage);
331
-			$globalPolicy = Server::get(IConfig::class)->getSystemValueInt('filesystem_check_changes', Watcher::CHECK_NEVER);
332
-			$this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
333
-		}
334
-		return $this->watcher;
335
-	}
336
-
337
-	public function getPropagator(?IStorage $storage = null): IPropagator {
338
-		if (!$storage) {
339
-			$storage = $this;
340
-		}
341
-		if (!$storage->instanceOfStorage(self::class)) {
342
-			throw new \InvalidArgumentException('Storage is not of the correct class');
343
-		}
344
-		/** @var self $storage */
345
-		if (!isset($storage->propagator)) {
346
-			$config = Server::get(IConfig::class);
347
-			$storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getSystemValueString('instanceid')]);
348
-		}
349
-		return $storage->propagator;
350
-	}
351
-
352
-	public function getUpdater(?IStorage $storage = null): IUpdater {
353
-		if (!$storage) {
354
-			$storage = $this;
355
-		}
356
-		if (!$storage->instanceOfStorage(self::class)) {
357
-			throw new \InvalidArgumentException('Storage is not of the correct class');
358
-		}
359
-		/** @var self $storage */
360
-		if (!isset($storage->updater)) {
361
-			$storage->updater = new Updater($storage);
362
-		}
363
-		return $storage->updater;
364
-	}
365
-
366
-	public function getStorageCache(?IStorage $storage = null): \OC\Files\Cache\Storage {
367
-		/** @var Cache $cache */
368
-		$cache = $this->getCache(storage: $storage);
369
-		return $cache->getStorageCache();
370
-	}
371
-
372
-	public function getOwner(string $path): string|false {
373
-		if ($this->owner === null) {
374
-			$this->owner = \OC_User::getUser();
375
-		}
376
-
377
-		return $this->owner;
378
-	}
379
-
380
-	public function getETag(string $path): string|false {
381
-		return uniqid();
382
-	}
383
-
384
-	/**
385
-	 * clean a path, i.e. remove all redundant '.' and '..'
386
-	 * making sure that it can't point to higher than '/'
387
-	 *
388
-	 * @param string $path The path to clean
389
-	 * @return string cleaned path
390
-	 */
391
-	public function cleanPath(string $path): string {
392
-		if (strlen($path) == 0 || $path[0] != '/') {
393
-			$path = '/' . $path;
394
-		}
395
-
396
-		$output = [];
397
-		foreach (explode('/', $path) as $chunk) {
398
-			if ($chunk == '..') {
399
-				array_pop($output);
400
-			} elseif ($chunk == '.') {
401
-			} else {
402
-				$output[] = $chunk;
403
-			}
404
-		}
405
-		return implode('/', $output);
406
-	}
407
-
408
-	/**
409
-	 * Test a storage for availability
410
-	 */
411
-	public function test(): bool {
412
-		try {
413
-			if ($this->stat('')) {
414
-				return true;
415
-			}
416
-			Server::get(LoggerInterface::class)->info('External storage not available: stat() failed');
417
-			return false;
418
-		} catch (\Exception $e) {
419
-			Server::get(LoggerInterface::class)->warning(
420
-				'External storage not available: ' . $e->getMessage(),
421
-				['exception' => $e]
422
-			);
423
-			return false;
424
-		}
425
-	}
426
-
427
-	public function free_space(string $path): int|float|false {
428
-		return \OCP\Files\FileInfo::SPACE_UNKNOWN;
429
-	}
430
-
431
-	public function isLocal(): bool {
432
-		// the common implementation returns a temporary file by
433
-		// default, which is not local
434
-		return false;
435
-	}
436
-
437
-	/**
438
-	 * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
439
-	 */
440
-	public function instanceOfStorage(string $class): bool {
441
-		if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
442
-			// FIXME Temporary fix to keep existing checks working
443
-			$class = '\OCA\Files_Sharing\SharedStorage';
444
-		}
445
-		return is_a($this, $class);
446
-	}
447
-
448
-	/**
449
-	 * A custom storage implementation can return an url for direct download of a give file.
450
-	 *
451
-	 * For now the returned array can hold the parameter url - in future more attributes might follow.
452
-	 */
453
-	public function getDirectDownload(string $path): array|false {
454
-		return [];
455
-	}
456
-
457
-	public function verifyPath(string $path, string $fileName): void {
458
-		$this->getFilenameValidator()
459
-			->validateFilename($fileName);
460
-
461
-		// verify also the path is valid
462
-		if ($path && $path !== '/' && $path !== '.') {
463
-			try {
464
-				$this->verifyPath(dirname($path), basename($path));
465
-			} catch (InvalidPathException $e) {
466
-				// Ignore invalid file type exceptions on directories
467
-				if ($e->getCode() !== FilenameValidator::INVALID_FILE_TYPE) {
468
-					$l = \OCP\Util::getL10N('lib');
469
-					throw new InvalidPathException($l->t('Invalid parent path'), previous: $e);
470
-				}
471
-			}
472
-		}
473
-	}
474
-
475
-	/**
476
-	 * Get the filename validator
477
-	 * (cached for performance)
478
-	 */
479
-	protected function getFilenameValidator(): IFilenameValidator {
480
-		if ($this->filenameValidator === null) {
481
-			$this->filenameValidator = Server::get(IFilenameValidator::class);
482
-		}
483
-		return $this->filenameValidator;
484
-	}
485
-
486
-	public function setMountOptions(array $options): void {
487
-		$this->mountOptions = $options;
488
-	}
489
-
490
-	public function getMountOption(string $name, mixed $default = null): mixed {
491
-		return $this->mountOptions[$name] ?? $default;
492
-	}
493
-
494
-	public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath, bool $preserveMtime = false): bool {
495
-		if ($sourceStorage === $this) {
496
-			return $this->copy($sourceInternalPath, $targetInternalPath);
497
-		}
498
-
499
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
500
-			$dh = $sourceStorage->opendir($sourceInternalPath);
501
-			$result = $this->mkdir($targetInternalPath);
502
-			if (is_resource($dh)) {
503
-				$result = true;
504
-				while ($result && ($file = readdir($dh)) !== false) {
505
-					if (!Filesystem::isIgnoredDir($file)) {
506
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
507
-					}
508
-				}
509
-			}
510
-		} else {
511
-			$source = $sourceStorage->fopen($sourceInternalPath, 'r');
512
-			$result = false;
513
-			if ($source) {
514
-				try {
515
-					$this->writeStream($targetInternalPath, $source);
516
-					$result = true;
517
-				} catch (\Exception $e) {
518
-					Server::get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
519
-				}
520
-			}
521
-
522
-			if ($result && $preserveMtime) {
523
-				$mtime = $sourceStorage->filemtime($sourceInternalPath);
524
-				$this->touch($targetInternalPath, is_int($mtime) ? $mtime : null);
525
-			}
526
-
527
-			if (!$result) {
528
-				// delete partially written target file
529
-				$this->unlink($targetInternalPath);
530
-				// delete cache entry that was created by fopen
531
-				$this->getCache()->remove($targetInternalPath);
532
-			}
533
-		}
534
-		return (bool)$result;
535
-	}
536
-
537
-	/**
538
-	 * Check if a storage is the same as the current one, including wrapped storages
539
-	 */
540
-	private function isSameStorage(IStorage $storage): bool {
541
-		while ($storage->instanceOfStorage(Wrapper::class)) {
542
-			/**
543
-			 * @var Wrapper $storage
544
-			 */
545
-			$storage = $storage->getWrapperStorage();
546
-		}
547
-
548
-		return $storage === $this;
549
-	}
550
-
551
-	public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
552
-		if (
553
-			!$sourceStorage->instanceOfStorage(Encryption::class) &&
554
-			$this->isSameStorage($sourceStorage)
555
-		) {
556
-			// resolve any jailed paths
557
-			while ($sourceStorage->instanceOfStorage(Jail::class)) {
558
-				/**
559
-				 * @var Jail $sourceStorage
560
-				 */
561
-				$sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
562
-				$sourceStorage = $sourceStorage->getUnjailedStorage();
563
-			}
564
-
565
-			return $this->rename($sourceInternalPath, $targetInternalPath);
566
-		}
567
-
568
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
569
-			return false;
570
-		}
571
-
572
-		$result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
573
-		if ($result) {
574
-			if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
575
-				/** @var ObjectStoreStorage $sourceStorage */
576
-				$sourceStorage->setPreserveCacheOnDelete(true);
577
-			}
578
-			try {
579
-				if ($sourceStorage->is_dir($sourceInternalPath)) {
580
-					$result = $sourceStorage->rmdir($sourceInternalPath);
581
-				} else {
582
-					$result = $sourceStorage->unlink($sourceInternalPath);
583
-				}
584
-			} finally {
585
-				if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
586
-					/** @var ObjectStoreStorage $sourceStorage */
587
-					$sourceStorage->setPreserveCacheOnDelete(false);
588
-				}
589
-			}
590
-		}
591
-		return $result;
592
-	}
593
-
594
-	public function getMetaData(string $path): ?array {
595
-		if (Filesystem::isFileBlacklisted($path)) {
596
-			throw new ForbiddenException('Invalid path: ' . $path, false);
597
-		}
598
-
599
-		$permissions = $this->getPermissions($path);
600
-		if (!$permissions & \OCP\Constants::PERMISSION_READ) {
601
-			//can't read, nothing we can do
602
-			return null;
603
-		}
604
-
605
-		$data = [];
606
-		$data['mimetype'] = $this->getMimeType($path);
607
-		$data['mtime'] = $this->filemtime($path);
608
-		if ($data['mtime'] === false) {
609
-			$data['mtime'] = time();
610
-		}
611
-		if ($data['mimetype'] == 'httpd/unix-directory') {
612
-			$data['size'] = -1; //unknown
613
-		} else {
614
-			$data['size'] = $this->filesize($path);
615
-		}
616
-		$data['etag'] = $this->getETag($path);
617
-		$data['storage_mtime'] = $data['mtime'];
618
-		$data['permissions'] = $permissions;
619
-		$data['name'] = basename($path);
620
-
621
-		return $data;
622
-	}
623
-
624
-	public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
625
-		$logger = $this->getLockLogger();
626
-		if ($logger) {
627
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
628
-			$logger->info(
629
-				sprintf(
630
-					'acquire %s lock on "%s" on storage "%s"',
631
-					$typeString,
632
-					$path,
633
-					$this->getId()
634
-				),
635
-				[
636
-					'app' => 'locking',
637
-				]
638
-			);
639
-		}
640
-		try {
641
-			$provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type, $this->getId() . '::' . $path);
642
-		} catch (LockedException $e) {
643
-			$e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
644
-			if ($logger) {
645
-				$logger->info($e->getMessage(), ['exception' => $e]);
646
-			}
647
-			throw $e;
648
-		}
649
-	}
650
-
651
-	public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
652
-		$logger = $this->getLockLogger();
653
-		if ($logger) {
654
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
655
-			$logger->info(
656
-				sprintf(
657
-					'release %s lock on "%s" on storage "%s"',
658
-					$typeString,
659
-					$path,
660
-					$this->getId()
661
-				),
662
-				[
663
-					'app' => 'locking',
664
-				]
665
-			);
666
-		}
667
-		try {
668
-			$provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
669
-		} catch (LockedException $e) {
670
-			$e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
671
-			if ($logger) {
672
-				$logger->info($e->getMessage(), ['exception' => $e]);
673
-			}
674
-			throw $e;
675
-		}
676
-	}
677
-
678
-	public function changeLock(string $path, int $type, ILockingProvider $provider): void {
679
-		$logger = $this->getLockLogger();
680
-		if ($logger) {
681
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
682
-			$logger->info(
683
-				sprintf(
684
-					'change lock on "%s" to %s on storage "%s"',
685
-					$path,
686
-					$typeString,
687
-					$this->getId()
688
-				),
689
-				[
690
-					'app' => 'locking',
691
-				]
692
-			);
693
-		}
694
-		try {
695
-			$provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
696
-		} catch (LockedException $e) {
697
-			$e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
698
-			if ($logger) {
699
-				$logger->info($e->getMessage(), ['exception' => $e]);
700
-			}
701
-			throw $e;
702
-		}
703
-	}
704
-
705
-	private function getLockLogger(): ?LoggerInterface {
706
-		if (is_null($this->shouldLogLocks)) {
707
-			$this->shouldLogLocks = Server::get(IConfig::class)->getSystemValueBool('filelocking.debug', false);
708
-			$this->logger = $this->shouldLogLocks ? Server::get(LoggerInterface::class) : null;
709
-		}
710
-		return $this->logger;
711
-	}
712
-
713
-	/**
714
-	 * @return array [ available, last_checked ]
715
-	 */
716
-	public function getAvailability(): array {
717
-		return $this->getStorageCache()->getAvailability();
718
-	}
719
-
720
-	public function setAvailability(bool $isAvailable): void {
721
-		$this->getStorageCache()->setAvailability($isAvailable);
722
-	}
723
-
724
-	public function setOwner(?string $user): void {
725
-		$this->owner = $user;
726
-	}
727
-
728
-	public function needsPartFile(): bool {
729
-		return true;
730
-	}
731
-
732
-	public function writeStream(string $path, $stream, ?int $size = null): int {
733
-		$target = $this->fopen($path, 'w');
734
-		if (!$target) {
735
-			throw new GenericFileException("Failed to open $path for writing");
736
-		}
737
-		try {
738
-			[$count, $result] = Files::streamCopy($stream, $target, true);
739
-			if (!$result) {
740
-				throw new GenericFileException('Failed to copy stream');
741
-			}
742
-		} finally {
743
-			fclose($target);
744
-			fclose($stream);
745
-		}
746
-		return $count;
747
-	}
748
-
749
-	public function getDirectoryContent(string $directory): \Traversable {
750
-		$dh = $this->opendir($directory);
751
-
752
-		if ($dh === false) {
753
-			throw new StorageNotAvailableException('Directory listing failed');
754
-		}
755
-
756
-		if (is_resource($dh)) {
757
-			$basePath = rtrim($directory, '/');
758
-			while (($file = readdir($dh)) !== false) {
759
-				if (!Filesystem::isIgnoredDir($file)) {
760
-					$childPath = $basePath . '/' . trim($file, '/');
761
-					$metadata = $this->getMetaData($childPath);
762
-					if ($metadata !== null) {
763
-						yield $metadata;
764
-					}
765
-				}
766
-			}
767
-		}
768
-	}
55
+    use LocalTempFileTrait;
56
+
57
+    protected ?Cache $cache = null;
58
+    protected ?Scanner $scanner = null;
59
+    protected ?Watcher $watcher = null;
60
+    protected ?Propagator $propagator = null;
61
+    protected $storageCache;
62
+    protected ?Updater $updater = null;
63
+
64
+    protected array $mountOptions = [];
65
+    protected $owner = null;
66
+
67
+    private ?bool $shouldLogLocks = null;
68
+    private ?LoggerInterface $logger = null;
69
+    private ?IFilenameValidator $filenameValidator = null;
70
+
71
+    public function __construct(array $parameters) {
72
+    }
73
+
74
+    protected function remove(string $path): bool {
75
+        if ($this->file_exists($path)) {
76
+            if ($this->is_dir($path)) {
77
+                return $this->rmdir($path);
78
+            } elseif ($this->is_file($path)) {
79
+                return $this->unlink($path);
80
+            }
81
+        }
82
+        return false;
83
+    }
84
+
85
+    public function is_dir(string $path): bool {
86
+        return $this->filetype($path) === 'dir';
87
+    }
88
+
89
+    public function is_file(string $path): bool {
90
+        return $this->filetype($path) === 'file';
91
+    }
92
+
93
+    public function filesize(string $path): int|float|false {
94
+        if ($this->is_dir($path)) {
95
+            return 0; //by definition
96
+        } else {
97
+            $stat = $this->stat($path);
98
+            return isset($stat['size']) ? $stat['size'] : 0;
99
+        }
100
+    }
101
+
102
+    public function isReadable(string $path): bool {
103
+        // at least check whether it exists
104
+        // subclasses might want to implement this more thoroughly
105
+        return $this->file_exists($path);
106
+    }
107
+
108
+    public function isUpdatable(string $path): bool {
109
+        // at least check whether it exists
110
+        // subclasses might want to implement this more thoroughly
111
+        // a non-existing file/folder isn't updatable
112
+        return $this->file_exists($path);
113
+    }
114
+
115
+    public function isCreatable(string $path): bool {
116
+        if ($this->is_dir($path) && $this->isUpdatable($path)) {
117
+            return true;
118
+        }
119
+        return false;
120
+    }
121
+
122
+    public function isDeletable(string $path): bool {
123
+        if ($path === '' || $path === '/') {
124
+            return $this->isUpdatable($path);
125
+        }
126
+        $parent = dirname($path);
127
+        return $this->isUpdatable($parent) && $this->isUpdatable($path);
128
+    }
129
+
130
+    public function isSharable(string $path): bool {
131
+        return $this->isReadable($path);
132
+    }
133
+
134
+    public function getPermissions(string $path): int {
135
+        $permissions = 0;
136
+        if ($this->isCreatable($path)) {
137
+            $permissions |= \OCP\Constants::PERMISSION_CREATE;
138
+        }
139
+        if ($this->isReadable($path)) {
140
+            $permissions |= \OCP\Constants::PERMISSION_READ;
141
+        }
142
+        if ($this->isUpdatable($path)) {
143
+            $permissions |= \OCP\Constants::PERMISSION_UPDATE;
144
+        }
145
+        if ($this->isDeletable($path)) {
146
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
147
+        }
148
+        if ($this->isSharable($path)) {
149
+            $permissions |= \OCP\Constants::PERMISSION_SHARE;
150
+        }
151
+        return $permissions;
152
+    }
153
+
154
+    public function filemtime(string $path): int|false {
155
+        $stat = $this->stat($path);
156
+        if (isset($stat['mtime']) && $stat['mtime'] > 0) {
157
+            return $stat['mtime'];
158
+        } else {
159
+            return 0;
160
+        }
161
+    }
162
+
163
+    public function file_get_contents(string $path): string|false {
164
+        $handle = $this->fopen($path, 'r');
165
+        if (!$handle) {
166
+            return false;
167
+        }
168
+        $data = stream_get_contents($handle);
169
+        fclose($handle);
170
+        return $data;
171
+    }
172
+
173
+    public function file_put_contents(string $path, mixed $data): int|float|false {
174
+        $handle = $this->fopen($path, 'w');
175
+        if (!$handle) {
176
+            return false;
177
+        }
178
+        $this->removeCachedFile($path);
179
+        $count = fwrite($handle, $data);
180
+        fclose($handle);
181
+        return $count;
182
+    }
183
+
184
+    public function rename(string $source, string $target): bool {
185
+        $this->remove($target);
186
+
187
+        $this->removeCachedFile($source);
188
+        return $this->copy($source, $target) and $this->remove($source);
189
+    }
190
+
191
+    public function copy(string $source, string $target): bool {
192
+        if ($this->is_dir($source)) {
193
+            $this->remove($target);
194
+            $dir = $this->opendir($source);
195
+            $this->mkdir($target);
196
+            while (($file = readdir($dir)) !== false) {
197
+                if (!Filesystem::isIgnoredDir($file)) {
198
+                    if (!$this->copy($source . '/' . $file, $target . '/' . $file)) {
199
+                        closedir($dir);
200
+                        return false;
201
+                    }
202
+                }
203
+            }
204
+            closedir($dir);
205
+            return true;
206
+        } else {
207
+            $sourceStream = $this->fopen($source, 'r');
208
+            $targetStream = $this->fopen($target, 'w');
209
+            [, $result] = Files::streamCopy($sourceStream, $targetStream, true);
210
+            if (!$result) {
211
+                Server::get(LoggerInterface::class)->warning("Failed to write data while copying $source to $target");
212
+            }
213
+            $this->removeCachedFile($target);
214
+            return $result;
215
+        }
216
+    }
217
+
218
+    public function getMimeType(string $path): string|false {
219
+        if ($this->is_dir($path)) {
220
+            return 'httpd/unix-directory';
221
+        } elseif ($this->file_exists($path)) {
222
+            return \OC::$server->getMimeTypeDetector()->detectPath($path);
223
+        } else {
224
+            return false;
225
+        }
226
+    }
227
+
228
+    public function hash(string $type, string $path, bool $raw = false): string|false {
229
+        $fh = $this->fopen($path, 'rb');
230
+        if (!$fh) {
231
+            return false;
232
+        }
233
+        $ctx = hash_init($type);
234
+        hash_update_stream($ctx, $fh);
235
+        fclose($fh);
236
+        return hash_final($ctx, $raw);
237
+    }
238
+
239
+    public function getLocalFile(string $path): string|false {
240
+        return $this->getCachedFile($path);
241
+    }
242
+
243
+    private function addLocalFolder(string $path, string $target): void {
244
+        $dh = $this->opendir($path);
245
+        if (is_resource($dh)) {
246
+            while (($file = readdir($dh)) !== false) {
247
+                if (!Filesystem::isIgnoredDir($file)) {
248
+                    if ($this->is_dir($path . '/' . $file)) {
249
+                        mkdir($target . '/' . $file);
250
+                        $this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
251
+                    } else {
252
+                        $tmp = $this->toTmpFile($path . '/' . $file);
253
+                        rename($tmp, $target . '/' . $file);
254
+                    }
255
+                }
256
+            }
257
+        }
258
+    }
259
+
260
+    protected function searchInDir(string $query, string $dir = ''): array {
261
+        $files = [];
262
+        $dh = $this->opendir($dir);
263
+        if (is_resource($dh)) {
264
+            while (($item = readdir($dh)) !== false) {
265
+                if (Filesystem::isIgnoredDir($item)) {
266
+                    continue;
267
+                }
268
+                if (strstr(strtolower($item), strtolower($query)) !== false) {
269
+                    $files[] = $dir . '/' . $item;
270
+                }
271
+                if ($this->is_dir($dir . '/' . $item)) {
272
+                    $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
273
+                }
274
+            }
275
+        }
276
+        closedir($dh);
277
+        return $files;
278
+    }
279
+
280
+    /**
281
+     * @inheritDoc
282
+     * Check if a file or folder has been updated since $time
283
+     *
284
+     * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
285
+     * the mtime should always return false here. As a result storage implementations that always return false expect
286
+     * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
287
+     * Nextcloud filesystem.
288
+     */
289
+    public function hasUpdated(string $path, int $time): bool {
290
+        return $this->filemtime($path) > $time;
291
+    }
292
+
293
+    protected function getCacheDependencies(): CacheDependencies {
294
+        static $dependencies = null;
295
+        if (!$dependencies) {
296
+            $dependencies = Server::get(CacheDependencies::class);
297
+        }
298
+        return $dependencies;
299
+    }
300
+
301
+    public function getCache(string $path = '', ?IStorage $storage = null): ICache {
302
+        if (!$storage) {
303
+            $storage = $this;
304
+        }
305
+        /** @var self $storage */
306
+        if (!isset($storage->cache)) {
307
+            $storage->cache = new Cache($storage, $this->getCacheDependencies());
308
+        }
309
+        return $storage->cache;
310
+    }
311
+
312
+    public function getScanner(string $path = '', ?IStorage $storage = null): IScanner {
313
+        if (!$storage) {
314
+            $storage = $this;
315
+        }
316
+        if (!$storage->instanceOfStorage(self::class)) {
317
+            throw new \InvalidArgumentException('Storage is not of the correct class');
318
+        }
319
+        if (!isset($storage->scanner)) {
320
+            $storage->scanner = new Scanner($storage);
321
+        }
322
+        return $storage->scanner;
323
+    }
324
+
325
+    public function getWatcher(string $path = '', ?IStorage $storage = null): IWatcher {
326
+        if (!$storage) {
327
+            $storage = $this;
328
+        }
329
+        if (!isset($this->watcher)) {
330
+            $this->watcher = new Watcher($storage);
331
+            $globalPolicy = Server::get(IConfig::class)->getSystemValueInt('filesystem_check_changes', Watcher::CHECK_NEVER);
332
+            $this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
333
+        }
334
+        return $this->watcher;
335
+    }
336
+
337
+    public function getPropagator(?IStorage $storage = null): IPropagator {
338
+        if (!$storage) {
339
+            $storage = $this;
340
+        }
341
+        if (!$storage->instanceOfStorage(self::class)) {
342
+            throw new \InvalidArgumentException('Storage is not of the correct class');
343
+        }
344
+        /** @var self $storage */
345
+        if (!isset($storage->propagator)) {
346
+            $config = Server::get(IConfig::class);
347
+            $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getSystemValueString('instanceid')]);
348
+        }
349
+        return $storage->propagator;
350
+    }
351
+
352
+    public function getUpdater(?IStorage $storage = null): IUpdater {
353
+        if (!$storage) {
354
+            $storage = $this;
355
+        }
356
+        if (!$storage->instanceOfStorage(self::class)) {
357
+            throw new \InvalidArgumentException('Storage is not of the correct class');
358
+        }
359
+        /** @var self $storage */
360
+        if (!isset($storage->updater)) {
361
+            $storage->updater = new Updater($storage);
362
+        }
363
+        return $storage->updater;
364
+    }
365
+
366
+    public function getStorageCache(?IStorage $storage = null): \OC\Files\Cache\Storage {
367
+        /** @var Cache $cache */
368
+        $cache = $this->getCache(storage: $storage);
369
+        return $cache->getStorageCache();
370
+    }
371
+
372
+    public function getOwner(string $path): string|false {
373
+        if ($this->owner === null) {
374
+            $this->owner = \OC_User::getUser();
375
+        }
376
+
377
+        return $this->owner;
378
+    }
379
+
380
+    public function getETag(string $path): string|false {
381
+        return uniqid();
382
+    }
383
+
384
+    /**
385
+     * clean a path, i.e. remove all redundant '.' and '..'
386
+     * making sure that it can't point to higher than '/'
387
+     *
388
+     * @param string $path The path to clean
389
+     * @return string cleaned path
390
+     */
391
+    public function cleanPath(string $path): string {
392
+        if (strlen($path) == 0 || $path[0] != '/') {
393
+            $path = '/' . $path;
394
+        }
395
+
396
+        $output = [];
397
+        foreach (explode('/', $path) as $chunk) {
398
+            if ($chunk == '..') {
399
+                array_pop($output);
400
+            } elseif ($chunk == '.') {
401
+            } else {
402
+                $output[] = $chunk;
403
+            }
404
+        }
405
+        return implode('/', $output);
406
+    }
407
+
408
+    /**
409
+     * Test a storage for availability
410
+     */
411
+    public function test(): bool {
412
+        try {
413
+            if ($this->stat('')) {
414
+                return true;
415
+            }
416
+            Server::get(LoggerInterface::class)->info('External storage not available: stat() failed');
417
+            return false;
418
+        } catch (\Exception $e) {
419
+            Server::get(LoggerInterface::class)->warning(
420
+                'External storage not available: ' . $e->getMessage(),
421
+                ['exception' => $e]
422
+            );
423
+            return false;
424
+        }
425
+    }
426
+
427
+    public function free_space(string $path): int|float|false {
428
+        return \OCP\Files\FileInfo::SPACE_UNKNOWN;
429
+    }
430
+
431
+    public function isLocal(): bool {
432
+        // the common implementation returns a temporary file by
433
+        // default, which is not local
434
+        return false;
435
+    }
436
+
437
+    /**
438
+     * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
439
+     */
440
+    public function instanceOfStorage(string $class): bool {
441
+        if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
442
+            // FIXME Temporary fix to keep existing checks working
443
+            $class = '\OCA\Files_Sharing\SharedStorage';
444
+        }
445
+        return is_a($this, $class);
446
+    }
447
+
448
+    /**
449
+     * A custom storage implementation can return an url for direct download of a give file.
450
+     *
451
+     * For now the returned array can hold the parameter url - in future more attributes might follow.
452
+     */
453
+    public function getDirectDownload(string $path): array|false {
454
+        return [];
455
+    }
456
+
457
+    public function verifyPath(string $path, string $fileName): void {
458
+        $this->getFilenameValidator()
459
+            ->validateFilename($fileName);
460
+
461
+        // verify also the path is valid
462
+        if ($path && $path !== '/' && $path !== '.') {
463
+            try {
464
+                $this->verifyPath(dirname($path), basename($path));
465
+            } catch (InvalidPathException $e) {
466
+                // Ignore invalid file type exceptions on directories
467
+                if ($e->getCode() !== FilenameValidator::INVALID_FILE_TYPE) {
468
+                    $l = \OCP\Util::getL10N('lib');
469
+                    throw new InvalidPathException($l->t('Invalid parent path'), previous: $e);
470
+                }
471
+            }
472
+        }
473
+    }
474
+
475
+    /**
476
+     * Get the filename validator
477
+     * (cached for performance)
478
+     */
479
+    protected function getFilenameValidator(): IFilenameValidator {
480
+        if ($this->filenameValidator === null) {
481
+            $this->filenameValidator = Server::get(IFilenameValidator::class);
482
+        }
483
+        return $this->filenameValidator;
484
+    }
485
+
486
+    public function setMountOptions(array $options): void {
487
+        $this->mountOptions = $options;
488
+    }
489
+
490
+    public function getMountOption(string $name, mixed $default = null): mixed {
491
+        return $this->mountOptions[$name] ?? $default;
492
+    }
493
+
494
+    public function copyFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath, bool $preserveMtime = false): bool {
495
+        if ($sourceStorage === $this) {
496
+            return $this->copy($sourceInternalPath, $targetInternalPath);
497
+        }
498
+
499
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
500
+            $dh = $sourceStorage->opendir($sourceInternalPath);
501
+            $result = $this->mkdir($targetInternalPath);
502
+            if (is_resource($dh)) {
503
+                $result = true;
504
+                while ($result && ($file = readdir($dh)) !== false) {
505
+                    if (!Filesystem::isIgnoredDir($file)) {
506
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
507
+                    }
508
+                }
509
+            }
510
+        } else {
511
+            $source = $sourceStorage->fopen($sourceInternalPath, 'r');
512
+            $result = false;
513
+            if ($source) {
514
+                try {
515
+                    $this->writeStream($targetInternalPath, $source);
516
+                    $result = true;
517
+                } catch (\Exception $e) {
518
+                    Server::get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
519
+                }
520
+            }
521
+
522
+            if ($result && $preserveMtime) {
523
+                $mtime = $sourceStorage->filemtime($sourceInternalPath);
524
+                $this->touch($targetInternalPath, is_int($mtime) ? $mtime : null);
525
+            }
526
+
527
+            if (!$result) {
528
+                // delete partially written target file
529
+                $this->unlink($targetInternalPath);
530
+                // delete cache entry that was created by fopen
531
+                $this->getCache()->remove($targetInternalPath);
532
+            }
533
+        }
534
+        return (bool)$result;
535
+    }
536
+
537
+    /**
538
+     * Check if a storage is the same as the current one, including wrapped storages
539
+     */
540
+    private function isSameStorage(IStorage $storage): bool {
541
+        while ($storage->instanceOfStorage(Wrapper::class)) {
542
+            /**
543
+             * @var Wrapper $storage
544
+             */
545
+            $storage = $storage->getWrapperStorage();
546
+        }
547
+
548
+        return $storage === $this;
549
+    }
550
+
551
+    public function moveFromStorage(IStorage $sourceStorage, string $sourceInternalPath, string $targetInternalPath): bool {
552
+        if (
553
+            !$sourceStorage->instanceOfStorage(Encryption::class) &&
554
+            $this->isSameStorage($sourceStorage)
555
+        ) {
556
+            // resolve any jailed paths
557
+            while ($sourceStorage->instanceOfStorage(Jail::class)) {
558
+                /**
559
+                 * @var Jail $sourceStorage
560
+                 */
561
+                $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
562
+                $sourceStorage = $sourceStorage->getUnjailedStorage();
563
+            }
564
+
565
+            return $this->rename($sourceInternalPath, $targetInternalPath);
566
+        }
567
+
568
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
569
+            return false;
570
+        }
571
+
572
+        $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
573
+        if ($result) {
574
+            if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
575
+                /** @var ObjectStoreStorage $sourceStorage */
576
+                $sourceStorage->setPreserveCacheOnDelete(true);
577
+            }
578
+            try {
579
+                if ($sourceStorage->is_dir($sourceInternalPath)) {
580
+                    $result = $sourceStorage->rmdir($sourceInternalPath);
581
+                } else {
582
+                    $result = $sourceStorage->unlink($sourceInternalPath);
583
+                }
584
+            } finally {
585
+                if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
586
+                    /** @var ObjectStoreStorage $sourceStorage */
587
+                    $sourceStorage->setPreserveCacheOnDelete(false);
588
+                }
589
+            }
590
+        }
591
+        return $result;
592
+    }
593
+
594
+    public function getMetaData(string $path): ?array {
595
+        if (Filesystem::isFileBlacklisted($path)) {
596
+            throw new ForbiddenException('Invalid path: ' . $path, false);
597
+        }
598
+
599
+        $permissions = $this->getPermissions($path);
600
+        if (!$permissions & \OCP\Constants::PERMISSION_READ) {
601
+            //can't read, nothing we can do
602
+            return null;
603
+        }
604
+
605
+        $data = [];
606
+        $data['mimetype'] = $this->getMimeType($path);
607
+        $data['mtime'] = $this->filemtime($path);
608
+        if ($data['mtime'] === false) {
609
+            $data['mtime'] = time();
610
+        }
611
+        if ($data['mimetype'] == 'httpd/unix-directory') {
612
+            $data['size'] = -1; //unknown
613
+        } else {
614
+            $data['size'] = $this->filesize($path);
615
+        }
616
+        $data['etag'] = $this->getETag($path);
617
+        $data['storage_mtime'] = $data['mtime'];
618
+        $data['permissions'] = $permissions;
619
+        $data['name'] = basename($path);
620
+
621
+        return $data;
622
+    }
623
+
624
+    public function acquireLock(string $path, int $type, ILockingProvider $provider): void {
625
+        $logger = $this->getLockLogger();
626
+        if ($logger) {
627
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
628
+            $logger->info(
629
+                sprintf(
630
+                    'acquire %s lock on "%s" on storage "%s"',
631
+                    $typeString,
632
+                    $path,
633
+                    $this->getId()
634
+                ),
635
+                [
636
+                    'app' => 'locking',
637
+                ]
638
+            );
639
+        }
640
+        try {
641
+            $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type, $this->getId() . '::' . $path);
642
+        } catch (LockedException $e) {
643
+            $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
644
+            if ($logger) {
645
+                $logger->info($e->getMessage(), ['exception' => $e]);
646
+            }
647
+            throw $e;
648
+        }
649
+    }
650
+
651
+    public function releaseLock(string $path, int $type, ILockingProvider $provider): void {
652
+        $logger = $this->getLockLogger();
653
+        if ($logger) {
654
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
655
+            $logger->info(
656
+                sprintf(
657
+                    'release %s lock on "%s" on storage "%s"',
658
+                    $typeString,
659
+                    $path,
660
+                    $this->getId()
661
+                ),
662
+                [
663
+                    'app' => 'locking',
664
+                ]
665
+            );
666
+        }
667
+        try {
668
+            $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
669
+        } catch (LockedException $e) {
670
+            $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
671
+            if ($logger) {
672
+                $logger->info($e->getMessage(), ['exception' => $e]);
673
+            }
674
+            throw $e;
675
+        }
676
+    }
677
+
678
+    public function changeLock(string $path, int $type, ILockingProvider $provider): void {
679
+        $logger = $this->getLockLogger();
680
+        if ($logger) {
681
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
682
+            $logger->info(
683
+                sprintf(
684
+                    'change lock on "%s" to %s on storage "%s"',
685
+                    $path,
686
+                    $typeString,
687
+                    $this->getId()
688
+                ),
689
+                [
690
+                    'app' => 'locking',
691
+                ]
692
+            );
693
+        }
694
+        try {
695
+            $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
696
+        } catch (LockedException $e) {
697
+            $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
698
+            if ($logger) {
699
+                $logger->info($e->getMessage(), ['exception' => $e]);
700
+            }
701
+            throw $e;
702
+        }
703
+    }
704
+
705
+    private function getLockLogger(): ?LoggerInterface {
706
+        if (is_null($this->shouldLogLocks)) {
707
+            $this->shouldLogLocks = Server::get(IConfig::class)->getSystemValueBool('filelocking.debug', false);
708
+            $this->logger = $this->shouldLogLocks ? Server::get(LoggerInterface::class) : null;
709
+        }
710
+        return $this->logger;
711
+    }
712
+
713
+    /**
714
+     * @return array [ available, last_checked ]
715
+     */
716
+    public function getAvailability(): array {
717
+        return $this->getStorageCache()->getAvailability();
718
+    }
719
+
720
+    public function setAvailability(bool $isAvailable): void {
721
+        $this->getStorageCache()->setAvailability($isAvailable);
722
+    }
723
+
724
+    public function setOwner(?string $user): void {
725
+        $this->owner = $user;
726
+    }
727
+
728
+    public function needsPartFile(): bool {
729
+        return true;
730
+    }
731
+
732
+    public function writeStream(string $path, $stream, ?int $size = null): int {
733
+        $target = $this->fopen($path, 'w');
734
+        if (!$target) {
735
+            throw new GenericFileException("Failed to open $path for writing");
736
+        }
737
+        try {
738
+            [$count, $result] = Files::streamCopy($stream, $target, true);
739
+            if (!$result) {
740
+                throw new GenericFileException('Failed to copy stream');
741
+            }
742
+        } finally {
743
+            fclose($target);
744
+            fclose($stream);
745
+        }
746
+        return $count;
747
+    }
748
+
749
+    public function getDirectoryContent(string $directory): \Traversable {
750
+        $dh = $this->opendir($directory);
751
+
752
+        if ($dh === false) {
753
+            throw new StorageNotAvailableException('Directory listing failed');
754
+        }
755
+
756
+        if (is_resource($dh)) {
757
+            $basePath = rtrim($directory, '/');
758
+            while (($file = readdir($dh)) !== false) {
759
+                if (!Filesystem::isIgnoredDir($file)) {
760
+                    $childPath = $basePath . '/' . trim($file, '/');
761
+                    $metadata = $this->getMetaData($childPath);
762
+                    if ($metadata !== null) {
763
+                        yield $metadata;
764
+                    }
765
+                }
766
+            }
767
+        }
768
+    }
769 769
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2244 added lines, -2244 removed lines patch added patch discarded remove patch
@@ -57,2248 +57,2248 @@
 block discarded – undo
57 57
  * \OC\Files\Storage\Storage object
58 58
  */
59 59
 class View {
60
-	private string $fakeRoot = '';
61
-	private ILockingProvider $lockingProvider;
62
-	private bool $lockingEnabled;
63
-	private bool $updaterEnabled = true;
64
-	private UserManager $userManager;
65
-	private LoggerInterface $logger;
66
-
67
-	/**
68
-	 * @throws \Exception If $root contains an invalid path
69
-	 */
70
-	public function __construct(string $root = '') {
71
-		if (!Filesystem::isValidPath($root)) {
72
-			throw new \Exception();
73
-		}
74
-
75
-		$this->fakeRoot = $root;
76
-		$this->lockingProvider = \OC::$server->get(ILockingProvider::class);
77
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
78
-		$this->userManager = \OC::$server->getUserManager();
79
-		$this->logger = \OC::$server->get(LoggerInterface::class);
80
-	}
81
-
82
-	/**
83
-	 * @param ?string $path
84
-	 * @psalm-template S as string|null
85
-	 * @psalm-param S $path
86
-	 * @psalm-return (S is string ? string : null)
87
-	 */
88
-	public function getAbsolutePath($path = '/'): ?string {
89
-		if ($path === null) {
90
-			return null;
91
-		}
92
-		$this->assertPathLength($path);
93
-		if ($path === '') {
94
-			$path = '/';
95
-		}
96
-		if ($path[0] !== '/') {
97
-			$path = '/' . $path;
98
-		}
99
-		return $this->fakeRoot . $path;
100
-	}
101
-
102
-	/**
103
-	 * Change the root to a fake root
104
-	 *
105
-	 * @param string $fakeRoot
106
-	 */
107
-	public function chroot($fakeRoot): void {
108
-		if (!$fakeRoot == '') {
109
-			if ($fakeRoot[0] !== '/') {
110
-				$fakeRoot = '/' . $fakeRoot;
111
-			}
112
-		}
113
-		$this->fakeRoot = $fakeRoot;
114
-	}
115
-
116
-	/**
117
-	 * Get the fake root
118
-	 */
119
-	public function getRoot(): string {
120
-		return $this->fakeRoot;
121
-	}
122
-
123
-	/**
124
-	 * get path relative to the root of the view
125
-	 *
126
-	 * @param string $path
127
-	 */
128
-	public function getRelativePath($path): ?string {
129
-		$this->assertPathLength($path);
130
-		if ($this->fakeRoot == '') {
131
-			return $path;
132
-		}
133
-
134
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
135
-			return '/';
136
-		}
137
-
138
-		// missing slashes can cause wrong matches!
139
-		$root = rtrim($this->fakeRoot, '/') . '/';
140
-
141
-		if (!str_starts_with($path, $root)) {
142
-			return null;
143
-		} else {
144
-			$path = substr($path, strlen($this->fakeRoot));
145
-			if (strlen($path) === 0) {
146
-				return '/';
147
-			} else {
148
-				return $path;
149
-			}
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * Get the mountpoint of the storage object for a path
155
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
156
-	 * returned mountpoint is relative to the absolute root of the filesystem
157
-	 * and does not take the chroot into account )
158
-	 *
159
-	 * @param string $path
160
-	 */
161
-	public function getMountPoint($path): string {
162
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
163
-	}
164
-
165
-	/**
166
-	 * Get the mountpoint of the storage object for a path
167
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
168
-	 * returned mountpoint is relative to the absolute root of the filesystem
169
-	 * and does not take the chroot into account )
170
-	 *
171
-	 * @param string $path
172
-	 */
173
-	public function getMount($path): IMountPoint {
174
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
175
-	}
176
-
177
-	/**
178
-	 * Resolve a path to a storage and internal path
179
-	 *
180
-	 * @param string $path
181
-	 * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
182
-	 */
183
-	public function resolvePath($path): array {
184
-		$a = $this->getAbsolutePath($path);
185
-		$p = Filesystem::normalizePath($a);
186
-		return Filesystem::resolvePath($p);
187
-	}
188
-
189
-	/**
190
-	 * Return the path to a local version of the file
191
-	 * we need this because we can't know if a file is stored local or not from
192
-	 * outside the filestorage and for some purposes a local file is needed
193
-	 *
194
-	 * @param string $path
195
-	 */
196
-	public function getLocalFile($path): string|false {
197
-		$parent = substr($path, 0, strrpos($path, '/') ?: 0);
198
-		$path = $this->getAbsolutePath($path);
199
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
200
-		if (Filesystem::isValidPath($parent) && $storage) {
201
-			return $storage->getLocalFile($internalPath);
202
-		} else {
203
-			return false;
204
-		}
205
-	}
206
-
207
-	/**
208
-	 * the following functions operate with arguments and return values identical
209
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
210
-	 * for \OC\Files\Storage\Storage via basicOperation().
211
-	 */
212
-	public function mkdir($path) {
213
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
214
-	}
215
-
216
-	/**
217
-	 * remove mount point
218
-	 *
219
-	 * @param IMountPoint $mount
220
-	 * @param string $path relative to data/
221
-	 */
222
-	protected function removeMount($mount, $path): bool {
223
-		if ($mount instanceof MoveableMount) {
224
-			// cut of /user/files to get the relative path to data/user/files
225
-			$pathParts = explode('/', $path, 4);
226
-			$relPath = '/' . $pathParts[3];
227
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
228
-			\OC_Hook::emit(
229
-				Filesystem::CLASSNAME, 'umount',
230
-				[Filesystem::signal_param_path => $relPath]
231
-			);
232
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
233
-			$result = $mount->removeMount();
234
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
235
-			if ($result) {
236
-				\OC_Hook::emit(
237
-					Filesystem::CLASSNAME, 'post_umount',
238
-					[Filesystem::signal_param_path => $relPath]
239
-				);
240
-			}
241
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
242
-			return $result;
243
-		} else {
244
-			// do not allow deleting the storage's root / the mount point
245
-			// because for some storages it might delete the whole contents
246
-			// but isn't supposed to work that way
247
-			return false;
248
-		}
249
-	}
250
-
251
-	public function disableCacheUpdate(): void {
252
-		$this->updaterEnabled = false;
253
-	}
254
-
255
-	public function enableCacheUpdate(): void {
256
-		$this->updaterEnabled = true;
257
-	}
258
-
259
-	protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
260
-		if ($this->updaterEnabled) {
261
-			if (is_null($time)) {
262
-				$time = time();
263
-			}
264
-			$storage->getUpdater()->update($internalPath, $time, $sizeDifference);
265
-		}
266
-	}
267
-
268
-	protected function removeUpdate(Storage $storage, string $internalPath): void {
269
-		if ($this->updaterEnabled) {
270
-			$storage->getUpdater()->remove($internalPath);
271
-		}
272
-	}
273
-
274
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
275
-		if ($this->updaterEnabled) {
276
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
277
-		}
278
-	}
279
-
280
-	protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
281
-		if ($this->updaterEnabled) {
282
-			$targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * @param string $path
288
-	 * @return bool|mixed
289
-	 */
290
-	public function rmdir($path) {
291
-		$absolutePath = $this->getAbsolutePath($path);
292
-		$mount = Filesystem::getMountManager()->find($absolutePath);
293
-		if ($mount->getInternalPath($absolutePath) === '') {
294
-			return $this->removeMount($mount, $absolutePath);
295
-		}
296
-		if ($this->is_dir($path)) {
297
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
298
-		} else {
299
-			$result = false;
300
-		}
301
-
302
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
303
-			$storage = $mount->getStorage();
304
-			$internalPath = $mount->getInternalPath($absolutePath);
305
-			$storage->getUpdater()->remove($internalPath);
306
-		}
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * @param string $path
312
-	 * @return resource|false
313
-	 */
314
-	public function opendir($path) {
315
-		return $this->basicOperation('opendir', $path, ['read']);
316
-	}
317
-
318
-	/**
319
-	 * @param string $path
320
-	 * @return bool|mixed
321
-	 */
322
-	public function is_dir($path) {
323
-		if ($path == '/') {
324
-			return true;
325
-		}
326
-		return $this->basicOperation('is_dir', $path);
327
-	}
328
-
329
-	/**
330
-	 * @param string $path
331
-	 * @return bool|mixed
332
-	 */
333
-	public function is_file($path) {
334
-		if ($path == '/') {
335
-			return false;
336
-		}
337
-		return $this->basicOperation('is_file', $path);
338
-	}
339
-
340
-	/**
341
-	 * @param string $path
342
-	 * @return mixed
343
-	 */
344
-	public function stat($path) {
345
-		return $this->basicOperation('stat', $path);
346
-	}
347
-
348
-	/**
349
-	 * @param string $path
350
-	 * @return mixed
351
-	 */
352
-	public function filetype($path) {
353
-		return $this->basicOperation('filetype', $path);
354
-	}
355
-
356
-	/**
357
-	 * @param string $path
358
-	 * @return mixed
359
-	 */
360
-	public function filesize(string $path) {
361
-		return $this->basicOperation('filesize', $path);
362
-	}
363
-
364
-	/**
365
-	 * @param string $path
366
-	 * @return bool|mixed
367
-	 * @throws InvalidPathException
368
-	 */
369
-	public function readfile($path) {
370
-		$this->assertPathLength($path);
371
-		if (ob_get_level()) {
372
-			ob_end_clean();
373
-		}
374
-		$handle = $this->fopen($path, 'rb');
375
-		if ($handle) {
376
-			$chunkSize = 524288; // 512 kiB chunks
377
-			while (!feof($handle)) {
378
-				echo fread($handle, $chunkSize);
379
-				flush();
380
-				$this->checkConnectionStatus();
381
-			}
382
-			fclose($handle);
383
-			return $this->filesize($path);
384
-		}
385
-		return false;
386
-	}
387
-
388
-	/**
389
-	 * @param string $path
390
-	 * @param int $from
391
-	 * @param int $to
392
-	 * @return bool|mixed
393
-	 * @throws InvalidPathException
394
-	 * @throws \OCP\Files\UnseekableException
395
-	 */
396
-	public function readfilePart($path, $from, $to) {
397
-		$this->assertPathLength($path);
398
-		if (ob_get_level()) {
399
-			ob_end_clean();
400
-		}
401
-		$handle = $this->fopen($path, 'rb');
402
-		if ($handle) {
403
-			$chunkSize = 524288; // 512 kiB chunks
404
-			$startReading = true;
405
-
406
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
407
-				// forward file handle via chunked fread because fseek seem to have failed
408
-
409
-				$end = $from + 1;
410
-				while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
411
-					$len = $from - ftell($handle);
412
-					if ($len > $chunkSize) {
413
-						$len = $chunkSize;
414
-					}
415
-					$result = fread($handle, $len);
416
-
417
-					if ($result === false) {
418
-						$startReading = false;
419
-						break;
420
-					}
421
-				}
422
-			}
423
-
424
-			if ($startReading) {
425
-				$end = $to + 1;
426
-				while (!feof($handle) && ftell($handle) < $end) {
427
-					$len = $end - ftell($handle);
428
-					if ($len > $chunkSize) {
429
-						$len = $chunkSize;
430
-					}
431
-					echo fread($handle, $len);
432
-					flush();
433
-					$this->checkConnectionStatus();
434
-				}
435
-				return ftell($handle) - $from;
436
-			}
437
-
438
-			throw new \OCP\Files\UnseekableException('fseek error');
439
-		}
440
-		return false;
441
-	}
442
-
443
-	private function checkConnectionStatus(): void {
444
-		$connectionStatus = \connection_status();
445
-		if ($connectionStatus !== CONNECTION_NORMAL) {
446
-			throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * @param string $path
452
-	 * @return mixed
453
-	 */
454
-	public function isCreatable($path) {
455
-		return $this->basicOperation('isCreatable', $path);
456
-	}
457
-
458
-	/**
459
-	 * @param string $path
460
-	 * @return mixed
461
-	 */
462
-	public function isReadable($path) {
463
-		return $this->basicOperation('isReadable', $path);
464
-	}
465
-
466
-	/**
467
-	 * @param string $path
468
-	 * @return mixed
469
-	 */
470
-	public function isUpdatable($path) {
471
-		return $this->basicOperation('isUpdatable', $path);
472
-	}
473
-
474
-	/**
475
-	 * @param string $path
476
-	 * @return bool|mixed
477
-	 */
478
-	public function isDeletable($path) {
479
-		$absolutePath = $this->getAbsolutePath($path);
480
-		$mount = Filesystem::getMountManager()->find($absolutePath);
481
-		if ($mount->getInternalPath($absolutePath) === '') {
482
-			return $mount instanceof MoveableMount;
483
-		}
484
-		return $this->basicOperation('isDeletable', $path);
485
-	}
486
-
487
-	/**
488
-	 * @param string $path
489
-	 * @return mixed
490
-	 */
491
-	public function isSharable($path) {
492
-		return $this->basicOperation('isSharable', $path);
493
-	}
494
-
495
-	/**
496
-	 * @param string $path
497
-	 * @return bool|mixed
498
-	 */
499
-	public function file_exists($path) {
500
-		if ($path == '/') {
501
-			return true;
502
-		}
503
-		return $this->basicOperation('file_exists', $path);
504
-	}
505
-
506
-	/**
507
-	 * @param string $path
508
-	 * @return mixed
509
-	 */
510
-	public function filemtime($path) {
511
-		return $this->basicOperation('filemtime', $path);
512
-	}
513
-
514
-	/**
515
-	 * @param string $path
516
-	 * @param int|string $mtime
517
-	 */
518
-	public function touch($path, $mtime = null): bool {
519
-		if (!is_null($mtime) && !is_numeric($mtime)) {
520
-			$mtime = strtotime($mtime);
521
-		}
522
-
523
-		$hooks = ['touch'];
524
-
525
-		if (!$this->file_exists($path)) {
526
-			$hooks[] = 'create';
527
-			$hooks[] = 'write';
528
-		}
529
-		try {
530
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
531
-		} catch (\Exception $e) {
532
-			$this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
533
-			$result = false;
534
-		}
535
-		if (!$result) {
536
-			// If create file fails because of permissions on external storage like SMB folders,
537
-			// check file exists and return false if not.
538
-			if (!$this->file_exists($path)) {
539
-				return false;
540
-			}
541
-			if (is_null($mtime)) {
542
-				$mtime = time();
543
-			}
544
-			//if native touch fails, we emulate it by changing the mtime in the cache
545
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
546
-		}
547
-		return true;
548
-	}
549
-
550
-	/**
551
-	 * @param string $path
552
-	 * @return string|false
553
-	 * @throws LockedException
554
-	 */
555
-	public function file_get_contents($path) {
556
-		return $this->basicOperation('file_get_contents', $path, ['read']);
557
-	}
558
-
559
-	protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
560
-		if (!$exists) {
561
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
562
-				Filesystem::signal_param_path => $this->getHookPath($path),
563
-				Filesystem::signal_param_run => &$run,
564
-			]);
565
-		} else {
566
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
567
-				Filesystem::signal_param_path => $this->getHookPath($path),
568
-				Filesystem::signal_param_run => &$run,
569
-			]);
570
-		}
571
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
572
-			Filesystem::signal_param_path => $this->getHookPath($path),
573
-			Filesystem::signal_param_run => &$run,
574
-		]);
575
-	}
576
-
577
-	protected function emit_file_hooks_post(bool $exists, string $path): void {
578
-		if (!$exists) {
579
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
580
-				Filesystem::signal_param_path => $this->getHookPath($path),
581
-			]);
582
-		} else {
583
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
584
-				Filesystem::signal_param_path => $this->getHookPath($path),
585
-			]);
586
-		}
587
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
588
-			Filesystem::signal_param_path => $this->getHookPath($path),
589
-		]);
590
-	}
591
-
592
-	/**
593
-	 * @param string $path
594
-	 * @param string|resource $data
595
-	 * @return bool|mixed
596
-	 * @throws LockedException
597
-	 */
598
-	public function file_put_contents($path, $data) {
599
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
600
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
601
-			if (Filesystem::isValidPath($path)
602
-				&& !Filesystem::isFileBlacklisted($path)
603
-			) {
604
-				$path = $this->getRelativePath($absolutePath);
605
-				if ($path === null) {
606
-					throw new InvalidPathException("Path $absolutePath is not in the expected root");
607
-				}
608
-
609
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
610
-
611
-				$exists = $this->file_exists($path);
612
-				if ($this->shouldEmitHooks($path)) {
613
-					$run = true;
614
-					$this->emit_file_hooks_pre($exists, $path, $run);
615
-					if (!$run) {
616
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
617
-						return false;
618
-					}
619
-				}
620
-
621
-				try {
622
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
623
-				} catch (\Exception $e) {
624
-					// Release the shared lock before throwing.
625
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
626
-					throw $e;
627
-				}
628
-
629
-				/** @var Storage $storage */
630
-				[$storage, $internalPath] = $this->resolvePath($path);
631
-				$target = $storage->fopen($internalPath, 'w');
632
-				if ($target) {
633
-					[, $result] = Files::streamCopy($data, $target, true);
634
-					fclose($target);
635
-					fclose($data);
636
-
637
-					$this->writeUpdate($storage, $internalPath);
638
-
639
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
640
-
641
-					if ($this->shouldEmitHooks($path) && $result !== false) {
642
-						$this->emit_file_hooks_post($exists, $path);
643
-					}
644
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
645
-					return $result;
646
-				} else {
647
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
648
-					return false;
649
-				}
650
-			} else {
651
-				return false;
652
-			}
653
-		} else {
654
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
655
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
656
-		}
657
-	}
658
-
659
-	/**
660
-	 * @param string $path
661
-	 * @return bool|mixed
662
-	 */
663
-	public function unlink($path) {
664
-		if ($path === '' || $path === '/') {
665
-			// do not allow deleting the root
666
-			return false;
667
-		}
668
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
669
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
670
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
671
-		if ($mount->getInternalPath($absolutePath) === '') {
672
-			return $this->removeMount($mount, $absolutePath);
673
-		}
674
-		if ($this->is_dir($path)) {
675
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
676
-		} else {
677
-			$result = $this->basicOperation('unlink', $path, ['delete']);
678
-		}
679
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
680
-			$storage = $mount->getStorage();
681
-			$internalPath = $mount->getInternalPath($absolutePath);
682
-			$storage->getUpdater()->remove($internalPath);
683
-			return true;
684
-		} else {
685
-			return $result;
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * @param string $directory
691
-	 * @return bool|mixed
692
-	 */
693
-	public function deleteAll($directory) {
694
-		return $this->rmdir($directory);
695
-	}
696
-
697
-	/**
698
-	 * Rename/move a file or folder from the source path to target path.
699
-	 *
700
-	 * @param string $source source path
701
-	 * @param string $target target path
702
-	 * @param array $options
703
-	 *
704
-	 * @return bool|mixed
705
-	 * @throws LockedException
706
-	 */
707
-	public function rename($source, $target, array $options = []) {
708
-		$checkSubMounts = $options['checkSubMounts'] ?? true;
709
-
710
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
711
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
712
-
713
-		if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
714
-			throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
715
-		}
716
-
717
-		/** @var IMountManager $mountManager */
718
-		$mountManager = \OC::$server->get(IMountManager::class);
719
-
720
-		$targetParts = explode('/', $absolutePath2);
721
-		$targetUser = $targetParts[1] ?? null;
722
-		$result = false;
723
-		if (
724
-			Filesystem::isValidPath($target)
725
-			&& Filesystem::isValidPath($source)
726
-			&& !Filesystem::isFileBlacklisted($target)
727
-		) {
728
-			$source = $this->getRelativePath($absolutePath1);
729
-			$target = $this->getRelativePath($absolutePath2);
730
-			$exists = $this->file_exists($target);
731
-
732
-			if ($source == null || $target == null) {
733
-				return false;
734
-			}
735
-
736
-			try {
737
-				$this->verifyPath(dirname($target), basename($target));
738
-			} catch (InvalidPathException) {
739
-				return false;
740
-			}
741
-
742
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
743
-			try {
744
-				$this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
745
-
746
-				$run = true;
747
-				if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
748
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
749
-					$this->emit_file_hooks_pre($exists, $target, $run);
750
-				} elseif ($this->shouldEmitHooks($source)) {
751
-					$sourcePath = $this->getHookPath($source);
752
-					$targetPath = $this->getHookPath($target);
753
-					if ($sourcePath !== null && $targetPath !== null) {
754
-						\OC_Hook::emit(
755
-							Filesystem::CLASSNAME, Filesystem::signal_rename,
756
-							[
757
-								Filesystem::signal_param_oldpath => $sourcePath,
758
-								Filesystem::signal_param_newpath => $targetPath,
759
-								Filesystem::signal_param_run => &$run
760
-							]
761
-						);
762
-					}
763
-				}
764
-				if ($run) {
765
-					$manager = Filesystem::getMountManager();
766
-					$mount1 = $this->getMount($source);
767
-					$mount2 = $this->getMount($target);
768
-					$storage1 = $mount1->getStorage();
769
-					$storage2 = $mount2->getStorage();
770
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
771
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
772
-
773
-					$this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
774
-					try {
775
-						$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
776
-
777
-						if ($checkSubMounts) {
778
-							$movedMounts = $mountManager->findIn($this->getAbsolutePath($source));
779
-						} else {
780
-							$movedMounts = [];
781
-						}
782
-
783
-						if ($internalPath1 === '') {
784
-							$sourceParentMount = $this->getMount(dirname($source));
785
-							$movedMounts[] = $mount1;
786
-							$this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
787
-							/**
788
-							 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
789
-							 */
790
-							$sourceMountPoint = $mount1->getMountPoint();
791
-							$result = $mount1->moveMount($absolutePath2);
792
-							$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
793
-
794
-							// moving a file/folder within the same mount point
795
-						} elseif ($storage1 === $storage2) {
796
-							if (count($movedMounts) > 0) {
797
-								$this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
798
-							}
799
-							if ($storage1) {
800
-								$result = $storage1->rename($internalPath1, $internalPath2);
801
-							} else {
802
-								$result = false;
803
-							}
804
-							// moving a file/folder between storages (from $storage1 to $storage2)
805
-						} else {
806
-							if (count($movedMounts) > 0) {
807
-								$this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
808
-							}
809
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
810
-						}
811
-
812
-						if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
813
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
814
-							$this->writeUpdate($storage2, $internalPath2);
815
-						} elseif ($result) {
816
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
817
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
818
-							}
819
-						}
820
-					} catch (\Exception $e) {
821
-						throw $e;
822
-					} finally {
823
-						$this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
824
-						$this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
825
-					}
826
-
827
-					if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
828
-						if ($this->shouldEmitHooks()) {
829
-							$this->emit_file_hooks_post($exists, $target);
830
-						}
831
-					} elseif ($result) {
832
-						if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
833
-							$sourcePath = $this->getHookPath($source);
834
-							$targetPath = $this->getHookPath($target);
835
-							if ($sourcePath !== null && $targetPath !== null) {
836
-								\OC_Hook::emit(
837
-									Filesystem::CLASSNAME,
838
-									Filesystem::signal_post_rename,
839
-									[
840
-										Filesystem::signal_param_oldpath => $sourcePath,
841
-										Filesystem::signal_param_newpath => $targetPath,
842
-									]
843
-								);
844
-							}
845
-						}
846
-					}
847
-				}
848
-			} catch (\Exception $e) {
849
-				throw $e;
850
-			} finally {
851
-				$this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
852
-				$this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
853
-			}
854
-		}
855
-		return $result;
856
-	}
857
-
858
-	/**
859
-	 * @throws ForbiddenException
860
-	 */
861
-	private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMountPoint $targetMount, bool $targetIsShared): void {
862
-		$targetPath = $this->getRelativePath($targetMount->getMountPoint());
863
-		if ($targetPath) {
864
-			$targetPath = trim($targetPath, '/');
865
-		} else {
866
-			$targetPath = $targetMount->getMountPoint();
867
-		}
868
-
869
-		$l = \OC::$server->get(IFactory::class)->get('files');
870
-		foreach ($mounts as $mount) {
871
-			$sourcePath = $this->getRelativePath($mount->getMountPoint());
872
-			if ($sourcePath) {
873
-				$sourcePath = trim($sourcePath, '/');
874
-			} else {
875
-				$sourcePath = $mount->getMountPoint();
876
-			}
877
-
878
-			if (!$mount instanceof MoveableMount) {
879
-				throw new ForbiddenException($l->t('Storage %s cannot be moved', [$sourcePath]), false);
880
-			}
881
-
882
-			if ($targetIsShared) {
883
-				if ($sourceMount instanceof SharedMount) {
884
-					throw new ForbiddenException($l->t('Moving a share (%s) into a shared folder is not allowed', [$sourcePath]), false);
885
-				} else {
886
-					throw new ForbiddenException($l->t('Moving a storage (%s) into a shared folder is not allowed', [$sourcePath]), false);
887
-				}
888
-			}
889
-
890
-			if ($sourceMount !== $targetMount) {
891
-				if ($sourceMount instanceof SharedMount) {
892
-					if ($targetMount instanceof SharedMount) {
893
-						throw new ForbiddenException($l->t('Moving a share (%s) into another share (%s) is not allowed', [$sourcePath, $targetPath]), false);
894
-					} else {
895
-						throw new ForbiddenException($l->t('Moving a share (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
896
-					}
897
-				} else {
898
-					if ($targetMount instanceof SharedMount) {
899
-						throw new ForbiddenException($l->t('Moving a storage (%s) into a share (%s) is not allowed', [$sourcePath, $targetPath]), false);
900
-					} else {
901
-						throw new ForbiddenException($l->t('Moving a storage (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
902
-					}
903
-				}
904
-			}
905
-		}
906
-	}
907
-
908
-	/**
909
-	 * Copy a file/folder from the source path to target path
910
-	 *
911
-	 * @param string $source source path
912
-	 * @param string $target target path
913
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
914
-	 *
915
-	 * @return bool|mixed
916
-	 */
917
-	public function copy($source, $target, $preserveMtime = false) {
918
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
919
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
920
-		$result = false;
921
-		if (
922
-			Filesystem::isValidPath($target)
923
-			&& Filesystem::isValidPath($source)
924
-			&& !Filesystem::isFileBlacklisted($target)
925
-		) {
926
-			$source = $this->getRelativePath($absolutePath1);
927
-			$target = $this->getRelativePath($absolutePath2);
928
-
929
-			if ($source == null || $target == null) {
930
-				return false;
931
-			}
932
-			$run = true;
933
-
934
-			$this->lockFile($target, ILockingProvider::LOCK_SHARED);
935
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED);
936
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
937
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
938
-
939
-			try {
940
-				$exists = $this->file_exists($target);
941
-				if ($this->shouldEmitHooks()) {
942
-					\OC_Hook::emit(
943
-						Filesystem::CLASSNAME,
944
-						Filesystem::signal_copy,
945
-						[
946
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
947
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
948
-							Filesystem::signal_param_run => &$run
949
-						]
950
-					);
951
-					$this->emit_file_hooks_pre($exists, $target, $run);
952
-				}
953
-				if ($run) {
954
-					$mount1 = $this->getMount($source);
955
-					$mount2 = $this->getMount($target);
956
-					$storage1 = $mount1->getStorage();
957
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
958
-					$storage2 = $mount2->getStorage();
959
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
960
-
961
-					$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
962
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
963
-
964
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
965
-						if ($storage1) {
966
-							$result = $storage1->copy($internalPath1, $internalPath2);
967
-						} else {
968
-							$result = false;
969
-						}
970
-					} else {
971
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
972
-					}
973
-
974
-					if ($result) {
975
-						$this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
976
-					}
977
-
978
-					$this->changeLock($target, ILockingProvider::LOCK_SHARED);
979
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
980
-
981
-					if ($this->shouldEmitHooks() && $result !== false) {
982
-						\OC_Hook::emit(
983
-							Filesystem::CLASSNAME,
984
-							Filesystem::signal_post_copy,
985
-							[
986
-								Filesystem::signal_param_oldpath => $this->getHookPath($source),
987
-								Filesystem::signal_param_newpath => $this->getHookPath($target)
988
-							]
989
-						);
990
-						$this->emit_file_hooks_post($exists, $target);
991
-					}
992
-				}
993
-			} catch (\Exception $e) {
994
-				$this->unlockFile($target, $lockTypePath2);
995
-				$this->unlockFile($source, $lockTypePath1);
996
-				throw $e;
997
-			}
998
-
999
-			$this->unlockFile($target, $lockTypePath2);
1000
-			$this->unlockFile($source, $lockTypePath1);
1001
-		}
1002
-		return $result;
1003
-	}
1004
-
1005
-	/**
1006
-	 * @param string $path
1007
-	 * @param string $mode 'r' or 'w'
1008
-	 * @return resource|false
1009
-	 * @throws LockedException
1010
-	 */
1011
-	public function fopen($path, $mode) {
1012
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
1013
-		$hooks = [];
1014
-		switch ($mode) {
1015
-			case 'r':
1016
-				$hooks[] = 'read';
1017
-				break;
1018
-			case 'r+':
1019
-			case 'w+':
1020
-			case 'x+':
1021
-			case 'a+':
1022
-				$hooks[] = 'read';
1023
-				$hooks[] = 'write';
1024
-				break;
1025
-			case 'w':
1026
-			case 'x':
1027
-			case 'a':
1028
-				$hooks[] = 'write';
1029
-				break;
1030
-			default:
1031
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1032
-		}
1033
-
1034
-		if ($mode !== 'r' && $mode !== 'w') {
1035
-			$this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1036
-		}
1037
-
1038
-		$handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1039
-		if (!is_resource($handle) && $mode === 'r') {
1040
-			// trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1041
-			$mount = $this->getMount($path);
1042
-			$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1043
-			$storage = $mount->getStorage();
1044
-			if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1045
-				$this->writeUpdate($storage, $internalPath);
1046
-			}
1047
-		}
1048
-		return $handle;
1049
-	}
1050
-
1051
-	/**
1052
-	 * @param string $path
1053
-	 * @throws InvalidPathException
1054
-	 */
1055
-	public function toTmpFile($path): string|false {
1056
-		$this->assertPathLength($path);
1057
-		if (Filesystem::isValidPath($path)) {
1058
-			$source = $this->fopen($path, 'r');
1059
-			if ($source) {
1060
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1061
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1062
-				file_put_contents($tmpFile, $source);
1063
-				return $tmpFile;
1064
-			} else {
1065
-				return false;
1066
-			}
1067
-		} else {
1068
-			return false;
1069
-		}
1070
-	}
1071
-
1072
-	/**
1073
-	 * @param string $tmpFile
1074
-	 * @param string $path
1075
-	 * @return bool|mixed
1076
-	 * @throws InvalidPathException
1077
-	 */
1078
-	public function fromTmpFile($tmpFile, $path) {
1079
-		$this->assertPathLength($path);
1080
-		if (Filesystem::isValidPath($path)) {
1081
-			// Get directory that the file is going into
1082
-			$filePath = dirname($path);
1083
-
1084
-			// Create the directories if any
1085
-			if (!$this->file_exists($filePath)) {
1086
-				$result = $this->createParentDirectories($filePath);
1087
-				if ($result === false) {
1088
-					return false;
1089
-				}
1090
-			}
1091
-
1092
-			$source = fopen($tmpFile, 'r');
1093
-			if ($source) {
1094
-				$result = $this->file_put_contents($path, $source);
1095
-				/**
1096
-				 * $this->file_put_contents() might have already closed
1097
-				 * the resource, so we check it, before trying to close it
1098
-				 * to avoid messages in the error log.
1099
-				 * @psalm-suppress RedundantCondition false-positive
1100
-				 */
1101
-				if (is_resource($source)) {
1102
-					fclose($source);
1103
-				}
1104
-				unlink($tmpFile);
1105
-				return $result;
1106
-			} else {
1107
-				return false;
1108
-			}
1109
-		} else {
1110
-			return false;
1111
-		}
1112
-	}
1113
-
1114
-
1115
-	/**
1116
-	 * @param string $path
1117
-	 * @return mixed
1118
-	 * @throws InvalidPathException
1119
-	 */
1120
-	public function getMimeType($path) {
1121
-		$this->assertPathLength($path);
1122
-		return $this->basicOperation('getMimeType', $path);
1123
-	}
1124
-
1125
-	/**
1126
-	 * @param string $type
1127
-	 * @param string $path
1128
-	 * @param bool $raw
1129
-	 */
1130
-	public function hash($type, $path, $raw = false): string|bool {
1131
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1132
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
-		if (Filesystem::isValidPath($path)) {
1134
-			$path = $this->getRelativePath($absolutePath);
1135
-			if ($path == null) {
1136
-				return false;
1137
-			}
1138
-			if ($this->shouldEmitHooks($path)) {
1139
-				\OC_Hook::emit(
1140
-					Filesystem::CLASSNAME,
1141
-					Filesystem::signal_read,
1142
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1143
-				);
1144
-			}
1145
-			/** @var Storage|null $storage */
1146
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1147
-			if ($storage) {
1148
-				return $storage->hash($type, $internalPath, $raw);
1149
-			}
1150
-		}
1151
-		return false;
1152
-	}
1153
-
1154
-	/**
1155
-	 * @param string $path
1156
-	 * @return mixed
1157
-	 * @throws InvalidPathException
1158
-	 */
1159
-	public function free_space($path = '/') {
1160
-		$this->assertPathLength($path);
1161
-		$result = $this->basicOperation('free_space', $path);
1162
-		if ($result === null) {
1163
-			throw new InvalidPathException();
1164
-		}
1165
-		return $result;
1166
-	}
1167
-
1168
-	/**
1169
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1170
-	 *
1171
-	 * @param mixed $extraParam (optional)
1172
-	 * @return mixed
1173
-	 * @throws LockedException
1174
-	 *
1175
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1176
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1177
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1178
-	 */
1179
-	private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1180
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1181
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1182
-		if (Filesystem::isValidPath($path)
1183
-			&& !Filesystem::isFileBlacklisted($path)
1184
-		) {
1185
-			$path = $this->getRelativePath($absolutePath);
1186
-			if ($path == null) {
1187
-				return false;
1188
-			}
1189
-
1190
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1191
-				// always a shared lock during pre-hooks so the hook can read the file
1192
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1193
-			}
1194
-
1195
-			$run = $this->runHooks($hooks, $path);
1196
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1197
-			if ($run && $storage) {
1198
-				/** @var Storage $storage */
1199
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1200
-					try {
1201
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1202
-					} catch (LockedException $e) {
1203
-						// release the shared lock we acquired before quitting
1204
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1205
-						throw $e;
1206
-					}
1207
-				}
1208
-				try {
1209
-					if (!is_null($extraParam)) {
1210
-						$result = $storage->$operation($internalPath, $extraParam);
1211
-					} else {
1212
-						$result = $storage->$operation($internalPath);
1213
-					}
1214
-				} catch (\Exception $e) {
1215
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1216
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1217
-					} elseif (in_array('read', $hooks)) {
1218
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1219
-					}
1220
-					throw $e;
1221
-				}
1222
-
1223
-				if ($result !== false && in_array('delete', $hooks)) {
1224
-					$this->removeUpdate($storage, $internalPath);
1225
-				}
1226
-				if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1227
-					$isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
1228
-					$sizeDifference = $operation === 'mkdir' ? 0 : $result;
1229
-					$this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
1230
-				}
1231
-				if ($result !== false && in_array('touch', $hooks)) {
1232
-					$this->writeUpdate($storage, $internalPath, $extraParam, 0);
1233
-				}
1234
-
1235
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1236
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1237
-				}
1238
-
1239
-				$unlockLater = false;
1240
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1241
-					$unlockLater = true;
1242
-					// make sure our unlocking callback will still be called if connection is aborted
1243
-					ignore_user_abort(true);
1244
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1245
-						if (in_array('write', $hooks)) {
1246
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1247
-						} elseif (in_array('read', $hooks)) {
1248
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1249
-						}
1250
-					});
1251
-				}
1252
-
1253
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1254
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1255
-						$this->runHooks($hooks, $path, true);
1256
-					}
1257
-				}
1258
-
1259
-				if (!$unlockLater
1260
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1261
-				) {
1262
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1263
-				}
1264
-				return $result;
1265
-			} else {
1266
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1267
-			}
1268
-		}
1269
-		return null;
1270
-	}
1271
-
1272
-	/**
1273
-	 * get the path relative to the default root for hook usage
1274
-	 *
1275
-	 * @param string $path
1276
-	 * @return ?string
1277
-	 */
1278
-	private function getHookPath($path): ?string {
1279
-		$view = Filesystem::getView();
1280
-		if (!$view) {
1281
-			return $path;
1282
-		}
1283
-		return $view->getRelativePath($this->getAbsolutePath($path));
1284
-	}
1285
-
1286
-	private function shouldEmitHooks(string $path = ''): bool {
1287
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1288
-			return false;
1289
-		}
1290
-		if (!Filesystem::$loaded) {
1291
-			return false;
1292
-		}
1293
-		$defaultRoot = Filesystem::getRoot();
1294
-		if ($defaultRoot === null) {
1295
-			return false;
1296
-		}
1297
-		if ($this->fakeRoot === $defaultRoot) {
1298
-			return true;
1299
-		}
1300
-		$fullPath = $this->getAbsolutePath($path);
1301
-
1302
-		if ($fullPath === $defaultRoot) {
1303
-			return true;
1304
-		}
1305
-
1306
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1307
-	}
1308
-
1309
-	/**
1310
-	 * @param string[] $hooks
1311
-	 * @param string $path
1312
-	 * @param bool $post
1313
-	 * @return bool
1314
-	 */
1315
-	private function runHooks($hooks, $path, $post = false) {
1316
-		$relativePath = $path;
1317
-		$path = $this->getHookPath($path);
1318
-		$prefix = $post ? 'post_' : '';
1319
-		$run = true;
1320
-		if ($this->shouldEmitHooks($relativePath)) {
1321
-			foreach ($hooks as $hook) {
1322
-				if ($hook != 'read') {
1323
-					\OC_Hook::emit(
1324
-						Filesystem::CLASSNAME,
1325
-						$prefix . $hook,
1326
-						[
1327
-							Filesystem::signal_param_run => &$run,
1328
-							Filesystem::signal_param_path => $path
1329
-						]
1330
-					);
1331
-				} elseif (!$post) {
1332
-					\OC_Hook::emit(
1333
-						Filesystem::CLASSNAME,
1334
-						$prefix . $hook,
1335
-						[
1336
-							Filesystem::signal_param_path => $path
1337
-						]
1338
-					);
1339
-				}
1340
-			}
1341
-		}
1342
-		return $run;
1343
-	}
1344
-
1345
-	/**
1346
-	 * check if a file or folder has been updated since $time
1347
-	 *
1348
-	 * @param string $path
1349
-	 * @param int $time
1350
-	 * @return bool
1351
-	 */
1352
-	public function hasUpdated($path, $time) {
1353
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1354
-	}
1355
-
1356
-	/**
1357
-	 * @param string $ownerId
1358
-	 * @return IUser
1359
-	 */
1360
-	private function getUserObjectForOwner(string $ownerId) {
1361
-		return new LazyUser($ownerId, $this->userManager);
1362
-	}
1363
-
1364
-	/**
1365
-	 * Get file info from cache
1366
-	 *
1367
-	 * If the file is not in cached it will be scanned
1368
-	 * If the file has changed on storage the cache will be updated
1369
-	 *
1370
-	 * @param Storage $storage
1371
-	 * @param string $internalPath
1372
-	 * @param string $relativePath
1373
-	 * @return ICacheEntry|bool
1374
-	 */
1375
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1376
-		$cache = $storage->getCache($internalPath);
1377
-		$data = $cache->get($internalPath);
1378
-		$watcher = $storage->getWatcher($internalPath);
1379
-
1380
-		try {
1381
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1382
-			if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1383
-				if (!$storage->file_exists($internalPath)) {
1384
-					return false;
1385
-				}
1386
-				// don't need to get a lock here since the scanner does it's own locking
1387
-				$scanner = $storage->getScanner($internalPath);
1388
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1389
-				$data = $cache->get($internalPath);
1390
-			} elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1391
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1392
-				$watcher->update($internalPath, $data);
1393
-				$storage->getPropagator()->propagateChange($internalPath, time());
1394
-				$data = $cache->get($internalPath);
1395
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1396
-			}
1397
-		} catch (LockedException $e) {
1398
-			// if the file is locked we just use the old cache info
1399
-		}
1400
-
1401
-		return $data;
1402
-	}
1403
-
1404
-	/**
1405
-	 * get the filesystem info
1406
-	 *
1407
-	 * @param string $path
1408
-	 * @param bool|string $includeMountPoints true to add mountpoint sizes,
1409
-	 *                                        'ext' to add only ext storage mount point sizes. Defaults to true.
1410
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1411
-	 */
1412
-	public function getFileInfo($path, $includeMountPoints = true) {
1413
-		$this->assertPathLength($path);
1414
-		if (!Filesystem::isValidPath($path)) {
1415
-			return false;
1416
-		}
1417
-		$relativePath = $path;
1418
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1419
-
1420
-		$mount = Filesystem::getMountManager()->find($path);
1421
-		$storage = $mount->getStorage();
1422
-		$internalPath = $mount->getInternalPath($path);
1423
-		if ($storage) {
1424
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1425
-
1426
-			if (!$data instanceof ICacheEntry) {
1427
-				if (Cache\Scanner::isPartialFile($relativePath)) {
1428
-					return $this->getPartFileInfo($relativePath);
1429
-				}
1430
-
1431
-				return false;
1432
-			}
1433
-
1434
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1435
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1436
-			}
1437
-			if ($internalPath === '' && $data['name']) {
1438
-				$data['name'] = basename($path);
1439
-			}
1440
-
1441
-			$ownerId = $storage->getOwner($internalPath);
1442
-			$owner = null;
1443
-			if ($ownerId !== false) {
1444
-				// ownerId might be null if files are accessed with an access token without file system access
1445
-				$owner = $this->getUserObjectForOwner($ownerId);
1446
-			}
1447
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1448
-
1449
-			if (isset($data['fileid'])) {
1450
-				if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1451
-					//add the sizes of other mount points to the folder
1452
-					$extOnly = ($includeMountPoints === 'ext');
1453
-					$this->addSubMounts($info, $extOnly);
1454
-				}
1455
-			}
1456
-
1457
-			return $info;
1458
-		} else {
1459
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1460
-		}
1461
-
1462
-		return false;
1463
-	}
1464
-
1465
-	/**
1466
-	 * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1467
-	 */
1468
-	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1469
-		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1470
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1471
-			return !($extOnly && $mount instanceof SharedMount);
1472
-		}));
1473
-	}
1474
-
1475
-	/**
1476
-	 * get the content of a directory
1477
-	 *
1478
-	 * @param string $directory path under datadirectory
1479
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1480
-	 * @return FileInfo[]
1481
-	 */
1482
-	public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
1483
-		$this->assertPathLength($directory);
1484
-		if (!Filesystem::isValidPath($directory)) {
1485
-			return [];
1486
-		}
1487
-
1488
-		$path = $this->getAbsolutePath($directory);
1489
-		$path = Filesystem::normalizePath($path);
1490
-		$mount = $this->getMount($directory);
1491
-		$storage = $mount->getStorage();
1492
-		$internalPath = $mount->getInternalPath($path);
1493
-		if (!$storage) {
1494
-			return [];
1495
-		}
1496
-
1497
-		$cache = $storage->getCache($internalPath);
1498
-		$user = \OC_User::getUser();
1499
-
1500
-		if (!$directoryInfo) {
1501
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1502
-			if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1503
-				return [];
1504
-			}
1505
-		} else {
1506
-			$data = $directoryInfo;
1507
-		}
1508
-
1509
-		if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1510
-			return [];
1511
-		}
1512
-
1513
-		$folderId = $data->getId();
1514
-		$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1515
-
1516
-		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1517
-
1518
-		$fileNames = array_map(function (ICacheEntry $content) {
1519
-			return $content->getName();
1520
-		}, $contents);
1521
-		/**
1522
-		 * @var \OC\Files\FileInfo[] $fileInfos
1523
-		 */
1524
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1525
-			if ($sharingDisabled) {
1526
-				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1527
-			}
1528
-			$ownerId = $storage->getOwner($content['path']);
1529
-			if ($ownerId !== false) {
1530
-				$owner = $this->getUserObjectForOwner($ownerId);
1531
-			} else {
1532
-				$owner = null;
1533
-			}
1534
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1535
-		}, $contents);
1536
-		$files = array_combine($fileNames, $fileInfos);
1537
-
1538
-		//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1539
-		$mounts = Filesystem::getMountManager()->findIn($path);
1540
-
1541
-		// make sure nested mounts are sorted after their parent mounts
1542
-		// otherwise doesn't propagate the etag across storage boundaries correctly
1543
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1544
-			return $a->getMountPoint() <=> $b->getMountPoint();
1545
-		});
1546
-
1547
-		$dirLength = strlen($path);
1548
-		foreach ($mounts as $mount) {
1549
-			$mountPoint = $mount->getMountPoint();
1550
-			$subStorage = $mount->getStorage();
1551
-			if ($subStorage) {
1552
-				$subCache = $subStorage->getCache('');
1553
-
1554
-				$rootEntry = $subCache->get('');
1555
-				if (!$rootEntry) {
1556
-					$subScanner = $subStorage->getScanner();
1557
-					try {
1558
-						$subScanner->scanFile('');
1559
-					} catch (\OCP\Files\StorageNotAvailableException $e) {
1560
-						continue;
1561
-					} catch (\OCP\Files\StorageInvalidException $e) {
1562
-						continue;
1563
-					} catch (\Exception $e) {
1564
-						// sometimes when the storage is not available it can be any exception
1565
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1566
-							'exception' => $e,
1567
-							'app' => 'core',
1568
-						]);
1569
-						continue;
1570
-					}
1571
-					$rootEntry = $subCache->get('');
1572
-				}
1573
-
1574
-				if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1575
-					$relativePath = trim(substr($mountPoint, $dirLength), '/');
1576
-					if ($pos = strpos($relativePath, '/')) {
1577
-						//mountpoint inside subfolder add size to the correct folder
1578
-						$entryName = substr($relativePath, 0, $pos);
1579
-
1580
-						// Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1581
-						if (!isset($files[$entryName])) {
1582
-							try {
1583
-								[$storage, ] = $this->resolvePath($path . '/' . $entryName);
1584
-								// make sure we can create the mountpoint folder, even if the user has a quota of 0
1585
-								if ($storage->instanceOfStorage(Quota::class)) {
1586
-									$storage->enableQuota(false);
1587
-								}
1588
-
1589
-								if ($this->mkdir($path . '/' . $entryName) !== false) {
1590
-									$info = $this->getFileInfo($path . '/' . $entryName);
1591
-									if ($info !== false) {
1592
-										$files[$entryName] = $info;
1593
-									}
1594
-								}
1595
-
1596
-								if ($storage->instanceOfStorage(Quota::class)) {
1597
-									$storage->enableQuota(true);
1598
-								}
1599
-							} catch (\Exception $e) {
1600
-								// Creating the parent folder might not be possible, for example due to a lack of permissions.
1601
-								$this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1602
-							}
1603
-						}
1604
-
1605
-						if (isset($files[$entryName])) {
1606
-							$files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1607
-						}
1608
-					} else { //mountpoint in this folder, add an entry for it
1609
-						$rootEntry['name'] = $relativePath;
1610
-						$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1611
-						$permissions = $rootEntry['permissions'];
1612
-						// do not allow renaming/deleting the mount point if they are not shared files/folders
1613
-						// for shared files/folders we use the permissions given by the owner
1614
-						if ($mount instanceof MoveableMount) {
1615
-							$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1616
-						} else {
1617
-							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1618
-						}
1619
-
1620
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1621
-
1622
-						// if sharing was disabled for the user we remove the share permissions
1623
-						if ($sharingDisabled) {
1624
-							$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1625
-						}
1626
-
1627
-						$ownerId = $subStorage->getOwner('');
1628
-						if ($ownerId !== false) {
1629
-							$owner = $this->getUserObjectForOwner($ownerId);
1630
-						} else {
1631
-							$owner = null;
1632
-						}
1633
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1634
-					}
1635
-				}
1636
-			}
1637
-		}
1638
-
1639
-		if ($mimetype_filter) {
1640
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1641
-				if (strpos($mimetype_filter, '/')) {
1642
-					return $file->getMimetype() === $mimetype_filter;
1643
-				} else {
1644
-					return $file->getMimePart() === $mimetype_filter;
1645
-				}
1646
-			});
1647
-		}
1648
-
1649
-		return array_values($files);
1650
-	}
1651
-
1652
-	/**
1653
-	 * change file metadata
1654
-	 *
1655
-	 * @param string $path
1656
-	 * @param array|\OCP\Files\FileInfo $data
1657
-	 * @return int
1658
-	 *
1659
-	 * returns the fileid of the updated file
1660
-	 */
1661
-	public function putFileInfo($path, $data) {
1662
-		$this->assertPathLength($path);
1663
-		if ($data instanceof FileInfo) {
1664
-			$data = $data->getData();
1665
-		}
1666
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1667
-		/**
1668
-		 * @var Storage $storage
1669
-		 * @var string $internalPath
1670
-		 */
1671
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
1672
-		if ($storage) {
1673
-			$cache = $storage->getCache($path);
1674
-
1675
-			if (!$cache->inCache($internalPath)) {
1676
-				$scanner = $storage->getScanner($internalPath);
1677
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1678
-			}
1679
-
1680
-			return $cache->put($internalPath, $data);
1681
-		} else {
1682
-			return -1;
1683
-		}
1684
-	}
1685
-
1686
-	/**
1687
-	 * search for files with the name matching $query
1688
-	 *
1689
-	 * @param string $query
1690
-	 * @return FileInfo[]
1691
-	 */
1692
-	public function search($query) {
1693
-		return $this->searchCommon('search', ['%' . $query . '%']);
1694
-	}
1695
-
1696
-	/**
1697
-	 * search for files with the name matching $query
1698
-	 *
1699
-	 * @param string $query
1700
-	 * @return FileInfo[]
1701
-	 */
1702
-	public function searchRaw($query) {
1703
-		return $this->searchCommon('search', [$query]);
1704
-	}
1705
-
1706
-	/**
1707
-	 * search for files by mimetype
1708
-	 *
1709
-	 * @param string $mimetype
1710
-	 * @return FileInfo[]
1711
-	 */
1712
-	public function searchByMime($mimetype) {
1713
-		return $this->searchCommon('searchByMime', [$mimetype]);
1714
-	}
1715
-
1716
-	/**
1717
-	 * search for files by tag
1718
-	 *
1719
-	 * @param string|int $tag name or tag id
1720
-	 * @param string $userId owner of the tags
1721
-	 * @return FileInfo[]
1722
-	 */
1723
-	public function searchByTag($tag, $userId) {
1724
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1725
-	}
1726
-
1727
-	/**
1728
-	 * @param string $method cache method
1729
-	 * @param array $args
1730
-	 * @return FileInfo[]
1731
-	 */
1732
-	private function searchCommon($method, $args) {
1733
-		$files = [];
1734
-		$rootLength = strlen($this->fakeRoot);
1735
-
1736
-		$mount = $this->getMount('');
1737
-		$mountPoint = $mount->getMountPoint();
1738
-		$storage = $mount->getStorage();
1739
-		$userManager = \OC::$server->getUserManager();
1740
-		if ($storage) {
1741
-			$cache = $storage->getCache('');
1742
-
1743
-			$results = call_user_func_array([$cache, $method], $args);
1744
-			foreach ($results as $result) {
1745
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1746
-					$internalPath = $result['path'];
1747
-					$path = $mountPoint . $result['path'];
1748
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1749
-					$ownerId = $storage->getOwner($internalPath);
1750
-					if ($ownerId !== false) {
1751
-						$owner = $userManager->get($ownerId);
1752
-					} else {
1753
-						$owner = null;
1754
-					}
1755
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1756
-				}
1757
-			}
1758
-
1759
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1760
-			foreach ($mounts as $mount) {
1761
-				$mountPoint = $mount->getMountPoint();
1762
-				$storage = $mount->getStorage();
1763
-				if ($storage) {
1764
-					$cache = $storage->getCache('');
1765
-
1766
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1767
-					$results = call_user_func_array([$cache, $method], $args);
1768
-					if ($results) {
1769
-						foreach ($results as $result) {
1770
-							$internalPath = $result['path'];
1771
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1772
-							$path = rtrim($mountPoint . $internalPath, '/');
1773
-							$ownerId = $storage->getOwner($internalPath);
1774
-							if ($ownerId !== false) {
1775
-								$owner = $userManager->get($ownerId);
1776
-							} else {
1777
-								$owner = null;
1778
-							}
1779
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1780
-						}
1781
-					}
1782
-				}
1783
-			}
1784
-		}
1785
-		return $files;
1786
-	}
1787
-
1788
-	/**
1789
-	 * Get the owner for a file or folder
1790
-	 *
1791
-	 * @throws NotFoundException
1792
-	 */
1793
-	public function getOwner(string $path): string {
1794
-		$info = $this->getFileInfo($path);
1795
-		if (!$info) {
1796
-			throw new NotFoundException($path . ' not found while trying to get owner');
1797
-		}
1798
-
1799
-		if ($info->getOwner() === null) {
1800
-			throw new NotFoundException($path . ' has no owner');
1801
-		}
1802
-
1803
-		return $info->getOwner()->getUID();
1804
-	}
1805
-
1806
-	/**
1807
-	 * get the ETag for a file or folder
1808
-	 *
1809
-	 * @param string $path
1810
-	 * @return string|false
1811
-	 */
1812
-	public function getETag($path) {
1813
-		[$storage, $internalPath] = $this->resolvePath($path);
1814
-		if ($storage) {
1815
-			return $storage->getETag($internalPath);
1816
-		} else {
1817
-			return false;
1818
-		}
1819
-	}
1820
-
1821
-	/**
1822
-	 * Get the path of a file by id, relative to the view
1823
-	 *
1824
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1825
-	 *
1826
-	 * @param int $id
1827
-	 * @param int|null $storageId
1828
-	 * @return string
1829
-	 * @throws NotFoundException
1830
-	 */
1831
-	public function getPath($id, ?int $storageId = null) {
1832
-		$id = (int)$id;
1833
-		$manager = Filesystem::getMountManager();
1834
-		$mounts = $manager->findIn($this->fakeRoot);
1835
-		$mounts[] = $manager->find($this->fakeRoot);
1836
-		$mounts = array_filter($mounts);
1837
-		// reverse the array, so we start with the storage this view is in
1838
-		// which is the most likely to contain the file we're looking for
1839
-		$mounts = array_reverse($mounts);
1840
-
1841
-		// put non-shared mounts in front of the shared mount
1842
-		// this prevents unneeded recursion into shares
1843
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1844
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1845
-		});
1846
-
1847
-		if (!is_null($storageId)) {
1848
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1849
-				return $mount->getNumericStorageId() === $storageId;
1850
-			});
1851
-		}
1852
-
1853
-		foreach ($mounts as $mount) {
1854
-			/**
1855
-			 * @var \OC\Files\Mount\MountPoint $mount
1856
-			 */
1857
-			if ($mount->getStorage()) {
1858
-				$cache = $mount->getStorage()->getCache();
1859
-				$internalPath = $cache->getPathById($id);
1860
-				if (is_string($internalPath)) {
1861
-					$fullPath = $mount->getMountPoint() . $internalPath;
1862
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1863
-						return $path;
1864
-					}
1865
-				}
1866
-			}
1867
-		}
1868
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1869
-	}
1870
-
1871
-	/**
1872
-	 * @param string $path
1873
-	 * @throws InvalidPathException
1874
-	 */
1875
-	private function assertPathLength($path): void {
1876
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1877
-		// Check for the string length - performed using isset() instead of strlen()
1878
-		// because isset() is about 5x-40x faster.
1879
-		if (isset($path[$maxLen])) {
1880
-			$pathLen = strlen($path);
1881
-			throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1882
-		}
1883
-	}
1884
-
1885
-	/**
1886
-	 * check if it is allowed to move a mount point to a given target.
1887
-	 * It is not allowed to move a mount point into a different mount point or
1888
-	 * into an already shared folder
1889
-	 */
1890
-	private function targetIsNotShared(string $user, string $targetPath): bool {
1891
-		$providers = [
1892
-			IShare::TYPE_USER,
1893
-			IShare::TYPE_GROUP,
1894
-			IShare::TYPE_EMAIL,
1895
-			IShare::TYPE_CIRCLE,
1896
-			IShare::TYPE_ROOM,
1897
-			IShare::TYPE_DECK,
1898
-			IShare::TYPE_SCIENCEMESH
1899
-		];
1900
-		$shareManager = Server::get(IManager::class);
1901
-		/** @var IShare[] $shares */
1902
-		$shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1903
-			return $shareManager->getSharesBy($user, $type);
1904
-		}, $providers));
1905
-
1906
-		foreach ($shares as $share) {
1907
-			$sharedPath = $share->getNode()->getPath();
1908
-			if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1909
-				$this->logger->debug(
1910
-					'It is not allowed to move one mount point into a shared folder',
1911
-					['app' => 'files']);
1912
-				return false;
1913
-			}
1914
-		}
1915
-
1916
-		return true;
1917
-	}
1918
-
1919
-	/**
1920
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1921
-	 */
1922
-	private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1923
-		$mount = $this->getMount($path);
1924
-		$storage = $mount->getStorage();
1925
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1926
-		$ownerId = $storage->getOwner($internalPath);
1927
-		if ($ownerId !== false) {
1928
-			$owner = Server::get(IUserManager::class)->get($ownerId);
1929
-		} else {
1930
-			$owner = null;
1931
-		}
1932
-		return new FileInfo(
1933
-			$this->getAbsolutePath($path),
1934
-			$storage,
1935
-			$internalPath,
1936
-			[
1937
-				'fileid' => null,
1938
-				'mimetype' => $storage->getMimeType($internalPath),
1939
-				'name' => basename($path),
1940
-				'etag' => null,
1941
-				'size' => $storage->filesize($internalPath),
1942
-				'mtime' => $storage->filemtime($internalPath),
1943
-				'encrypted' => false,
1944
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1945
-			],
1946
-			$mount,
1947
-			$owner
1948
-		);
1949
-	}
1950
-
1951
-	/**
1952
-	 * @param string $path
1953
-	 * @param string $fileName
1954
-	 * @param bool $readonly Check only if the path is allowed for read-only access
1955
-	 * @throws InvalidPathException
1956
-	 */
1957
-	public function verifyPath($path, $fileName, $readonly = false): void {
1958
-		// All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
1959
-		if (!Filesystem::isValidPath($path ?: '/')) {
1960
-			$l = \OCP\Util::getL10N('lib');
1961
-			throw new InvalidPathException($l->t('Path contains invalid segments'));
1962
-		}
1963
-
1964
-		// Short cut for read-only validation
1965
-		if ($readonly) {
1966
-			$validator = Server::get(FilenameValidator::class);
1967
-			if ($validator->isForbidden($fileName)) {
1968
-				$l = \OCP\Util::getL10N('lib');
1969
-				throw new InvalidPathException($l->t('Filename is a reserved word'));
1970
-			}
1971
-			return;
1972
-		}
1973
-
1974
-		try {
1975
-			/** @type \OCP\Files\Storage $storage */
1976
-			[$storage, $internalPath] = $this->resolvePath($path);
1977
-			$storage->verifyPath($internalPath, $fileName);
1978
-		} catch (ReservedWordException $ex) {
1979
-			$l = \OCP\Util::getL10N('lib');
1980
-			throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
1981
-		} catch (InvalidCharacterInPathException $ex) {
1982
-			$l = \OCP\Util::getL10N('lib');
1983
-			throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
1984
-		} catch (FileNameTooLongException $ex) {
1985
-			$l = \OCP\Util::getL10N('lib');
1986
-			throw new InvalidPathException($l->t('Filename is too long'));
1987
-		} catch (InvalidDirectoryException $ex) {
1988
-			$l = \OCP\Util::getL10N('lib');
1989
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1990
-		} catch (EmptyFileNameException $ex) {
1991
-			$l = \OCP\Util::getL10N('lib');
1992
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1993
-		}
1994
-	}
1995
-
1996
-	/**
1997
-	 * get all parent folders of $path
1998
-	 *
1999
-	 * @param string $path
2000
-	 * @return string[]
2001
-	 */
2002
-	private function getParents($path) {
2003
-		$path = trim($path, '/');
2004
-		if (!$path) {
2005
-			return [];
2006
-		}
2007
-
2008
-		$parts = explode('/', $path);
2009
-
2010
-		// remove the single file
2011
-		array_pop($parts);
2012
-		$result = ['/'];
2013
-		$resultPath = '';
2014
-		foreach ($parts as $part) {
2015
-			if ($part) {
2016
-				$resultPath .= '/' . $part;
2017
-				$result[] = $resultPath;
2018
-			}
2019
-		}
2020
-		return $result;
2021
-	}
2022
-
2023
-	/**
2024
-	 * Returns the mount point for which to lock
2025
-	 *
2026
-	 * @param string $absolutePath absolute path
2027
-	 * @param bool $useParentMount true to return parent mount instead of whatever
2028
-	 *                             is mounted directly on the given path, false otherwise
2029
-	 * @return IMountPoint mount point for which to apply locks
2030
-	 */
2031
-	private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
2032
-		$mount = Filesystem::getMountManager()->find($absolutePath);
2033
-
2034
-		if ($useParentMount) {
2035
-			// find out if something is mounted directly on the path
2036
-			$internalPath = $mount->getInternalPath($absolutePath);
2037
-			if ($internalPath === '') {
2038
-				// resolve the parent mount instead
2039
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
2040
-			}
2041
-		}
2042
-
2043
-		return $mount;
2044
-	}
2045
-
2046
-	/**
2047
-	 * Lock the given path
2048
-	 *
2049
-	 * @param string $path the path of the file to lock, relative to the view
2050
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
-	 *
2053
-	 * @return bool False if the path is excluded from locking, true otherwise
2054
-	 * @throws LockedException if the path is already locked
2055
-	 */
2056
-	private function lockPath($path, $type, $lockMountPoint = false) {
2057
-		$absolutePath = $this->getAbsolutePath($path);
2058
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2059
-		if (!$this->shouldLockFile($absolutePath)) {
2060
-			return false;
2061
-		}
2062
-
2063
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2064
-		try {
2065
-			$storage = $mount->getStorage();
2066
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2067
-				$storage->acquireLock(
2068
-					$mount->getInternalPath($absolutePath),
2069
-					$type,
2070
-					$this->lockingProvider
2071
-				);
2072
-			}
2073
-		} catch (LockedException $e) {
2074
-			// rethrow with the human-readable path
2075
-			throw new LockedException(
2076
-				$path,
2077
-				$e,
2078
-				$e->getExistingLock()
2079
-			);
2080
-		}
2081
-
2082
-		return true;
2083
-	}
2084
-
2085
-	/**
2086
-	 * Change the lock type
2087
-	 *
2088
-	 * @param string $path the path of the file to lock, relative to the view
2089
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2090
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2091
-	 *
2092
-	 * @return bool False if the path is excluded from locking, true otherwise
2093
-	 * @throws LockedException if the path is already locked
2094
-	 */
2095
-	public function changeLock($path, $type, $lockMountPoint = false) {
2096
-		$path = Filesystem::normalizePath($path);
2097
-		$absolutePath = $this->getAbsolutePath($path);
2098
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2099
-		if (!$this->shouldLockFile($absolutePath)) {
2100
-			return false;
2101
-		}
2102
-
2103
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2104
-		try {
2105
-			$storage = $mount->getStorage();
2106
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2107
-				$storage->changeLock(
2108
-					$mount->getInternalPath($absolutePath),
2109
-					$type,
2110
-					$this->lockingProvider
2111
-				);
2112
-			}
2113
-		} catch (LockedException $e) {
2114
-			// rethrow with the a human-readable path
2115
-			throw new LockedException(
2116
-				$path,
2117
-				$e,
2118
-				$e->getExistingLock()
2119
-			);
2120
-		}
2121
-
2122
-		return true;
2123
-	}
2124
-
2125
-	/**
2126
-	 * Unlock the given path
2127
-	 *
2128
-	 * @param string $path the path of the file to unlock, relative to the view
2129
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2130
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2131
-	 *
2132
-	 * @return bool False if the path is excluded from locking, true otherwise
2133
-	 * @throws LockedException
2134
-	 */
2135
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2136
-		$absolutePath = $this->getAbsolutePath($path);
2137
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2138
-		if (!$this->shouldLockFile($absolutePath)) {
2139
-			return false;
2140
-		}
2141
-
2142
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2143
-		$storage = $mount->getStorage();
2144
-		if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2145
-			$storage->releaseLock(
2146
-				$mount->getInternalPath($absolutePath),
2147
-				$type,
2148
-				$this->lockingProvider
2149
-			);
2150
-		}
2151
-
2152
-		return true;
2153
-	}
2154
-
2155
-	/**
2156
-	 * Lock a path and all its parents up to the root of the view
2157
-	 *
2158
-	 * @param string $path the path of the file to lock relative to the view
2159
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2160
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2161
-	 *
2162
-	 * @return bool False if the path is excluded from locking, true otherwise
2163
-	 * @throws LockedException
2164
-	 */
2165
-	public function lockFile($path, $type, $lockMountPoint = false) {
2166
-		$absolutePath = $this->getAbsolutePath($path);
2167
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2168
-		if (!$this->shouldLockFile($absolutePath)) {
2169
-			return false;
2170
-		}
2171
-
2172
-		$this->lockPath($path, $type, $lockMountPoint);
2173
-
2174
-		$parents = $this->getParents($path);
2175
-		foreach ($parents as $parent) {
2176
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2177
-		}
2178
-
2179
-		return true;
2180
-	}
2181
-
2182
-	/**
2183
-	 * Unlock a path and all its parents up to the root of the view
2184
-	 *
2185
-	 * @param string $path the path of the file to lock relative to the view
2186
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2187
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2188
-	 *
2189
-	 * @return bool False if the path is excluded from locking, true otherwise
2190
-	 * @throws LockedException
2191
-	 */
2192
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2193
-		$absolutePath = $this->getAbsolutePath($path);
2194
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2195
-		if (!$this->shouldLockFile($absolutePath)) {
2196
-			return false;
2197
-		}
2198
-
2199
-		$this->unlockPath($path, $type, $lockMountPoint);
2200
-
2201
-		$parents = $this->getParents($path);
2202
-		foreach ($parents as $parent) {
2203
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2204
-		}
2205
-
2206
-		return true;
2207
-	}
2208
-
2209
-	/**
2210
-	 * Only lock files in data/user/files/
2211
-	 *
2212
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2213
-	 * @return bool
2214
-	 */
2215
-	protected function shouldLockFile($path) {
2216
-		$path = Filesystem::normalizePath($path);
2217
-
2218
-		$pathSegments = explode('/', $path);
2219
-		if (isset($pathSegments[2])) {
2220
-			// E.g.: /username/files/path-to-file
2221
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2222
-		}
2223
-
2224
-		return !str_starts_with($path, '/appdata_');
2225
-	}
2226
-
2227
-	/**
2228
-	 * Shortens the given absolute path to be relative to
2229
-	 * "$user/files".
2230
-	 *
2231
-	 * @param string $absolutePath absolute path which is under "files"
2232
-	 *
2233
-	 * @return string path relative to "files" with trimmed slashes or null
2234
-	 *                if the path was NOT relative to files
2235
-	 *
2236
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2237
-	 * @since 8.1.0
2238
-	 */
2239
-	public function getPathRelativeToFiles($absolutePath) {
2240
-		$path = Filesystem::normalizePath($absolutePath);
2241
-		$parts = explode('/', trim($path, '/'), 3);
2242
-		// "$user", "files", "path/to/dir"
2243
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2244
-			$this->logger->error(
2245
-				'$absolutePath must be relative to "files", value is "{absolutePath}"',
2246
-				[
2247
-					'absolutePath' => $absolutePath,
2248
-				]
2249
-			);
2250
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2251
-		}
2252
-		if (isset($parts[2])) {
2253
-			return $parts[2];
2254
-		}
2255
-		return '';
2256
-	}
2257
-
2258
-	/**
2259
-	 * @param string $filename
2260
-	 * @return array
2261
-	 * @throws \OC\User\NoUserException
2262
-	 * @throws NotFoundException
2263
-	 */
2264
-	public function getUidAndFilename($filename) {
2265
-		$info = $this->getFileInfo($filename);
2266
-		if (!$info instanceof \OCP\Files\FileInfo) {
2267
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2268
-		}
2269
-		$uid = $info->getOwner()->getUID();
2270
-		if ($uid != \OC_User::getUser()) {
2271
-			Filesystem::initMountPoints($uid);
2272
-			$ownerView = new View('/' . $uid . '/files');
2273
-			try {
2274
-				$filename = $ownerView->getPath($info['fileid']);
2275
-			} catch (NotFoundException $e) {
2276
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2277
-			}
2278
-		}
2279
-		return [$uid, $filename];
2280
-	}
2281
-
2282
-	/**
2283
-	 * Creates parent non-existing folders
2284
-	 *
2285
-	 * @param string $filePath
2286
-	 * @return bool
2287
-	 */
2288
-	private function createParentDirectories($filePath) {
2289
-		$directoryParts = explode('/', $filePath);
2290
-		$directoryParts = array_filter($directoryParts);
2291
-		foreach ($directoryParts as $key => $part) {
2292
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2293
-			$currentPath = '/' . implode('/', $currentPathElements);
2294
-			if ($this->is_file($currentPath)) {
2295
-				return false;
2296
-			}
2297
-			if (!$this->file_exists($currentPath)) {
2298
-				$this->mkdir($currentPath);
2299
-			}
2300
-		}
2301
-
2302
-		return true;
2303
-	}
60
+    private string $fakeRoot = '';
61
+    private ILockingProvider $lockingProvider;
62
+    private bool $lockingEnabled;
63
+    private bool $updaterEnabled = true;
64
+    private UserManager $userManager;
65
+    private LoggerInterface $logger;
66
+
67
+    /**
68
+     * @throws \Exception If $root contains an invalid path
69
+     */
70
+    public function __construct(string $root = '') {
71
+        if (!Filesystem::isValidPath($root)) {
72
+            throw new \Exception();
73
+        }
74
+
75
+        $this->fakeRoot = $root;
76
+        $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
77
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
78
+        $this->userManager = \OC::$server->getUserManager();
79
+        $this->logger = \OC::$server->get(LoggerInterface::class);
80
+    }
81
+
82
+    /**
83
+     * @param ?string $path
84
+     * @psalm-template S as string|null
85
+     * @psalm-param S $path
86
+     * @psalm-return (S is string ? string : null)
87
+     */
88
+    public function getAbsolutePath($path = '/'): ?string {
89
+        if ($path === null) {
90
+            return null;
91
+        }
92
+        $this->assertPathLength($path);
93
+        if ($path === '') {
94
+            $path = '/';
95
+        }
96
+        if ($path[0] !== '/') {
97
+            $path = '/' . $path;
98
+        }
99
+        return $this->fakeRoot . $path;
100
+    }
101
+
102
+    /**
103
+     * Change the root to a fake root
104
+     *
105
+     * @param string $fakeRoot
106
+     */
107
+    public function chroot($fakeRoot): void {
108
+        if (!$fakeRoot == '') {
109
+            if ($fakeRoot[0] !== '/') {
110
+                $fakeRoot = '/' . $fakeRoot;
111
+            }
112
+        }
113
+        $this->fakeRoot = $fakeRoot;
114
+    }
115
+
116
+    /**
117
+     * Get the fake root
118
+     */
119
+    public function getRoot(): string {
120
+        return $this->fakeRoot;
121
+    }
122
+
123
+    /**
124
+     * get path relative to the root of the view
125
+     *
126
+     * @param string $path
127
+     */
128
+    public function getRelativePath($path): ?string {
129
+        $this->assertPathLength($path);
130
+        if ($this->fakeRoot == '') {
131
+            return $path;
132
+        }
133
+
134
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
135
+            return '/';
136
+        }
137
+
138
+        // missing slashes can cause wrong matches!
139
+        $root = rtrim($this->fakeRoot, '/') . '/';
140
+
141
+        if (!str_starts_with($path, $root)) {
142
+            return null;
143
+        } else {
144
+            $path = substr($path, strlen($this->fakeRoot));
145
+            if (strlen($path) === 0) {
146
+                return '/';
147
+            } else {
148
+                return $path;
149
+            }
150
+        }
151
+    }
152
+
153
+    /**
154
+     * Get the mountpoint of the storage object for a path
155
+     * ( note: because a storage is not always mounted inside the fakeroot, the
156
+     * returned mountpoint is relative to the absolute root of the filesystem
157
+     * and does not take the chroot into account )
158
+     *
159
+     * @param string $path
160
+     */
161
+    public function getMountPoint($path): string {
162
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
163
+    }
164
+
165
+    /**
166
+     * Get the mountpoint of the storage object for a path
167
+     * ( note: because a storage is not always mounted inside the fakeroot, the
168
+     * returned mountpoint is relative to the absolute root of the filesystem
169
+     * and does not take the chroot into account )
170
+     *
171
+     * @param string $path
172
+     */
173
+    public function getMount($path): IMountPoint {
174
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
175
+    }
176
+
177
+    /**
178
+     * Resolve a path to a storage and internal path
179
+     *
180
+     * @param string $path
181
+     * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
182
+     */
183
+    public function resolvePath($path): array {
184
+        $a = $this->getAbsolutePath($path);
185
+        $p = Filesystem::normalizePath($a);
186
+        return Filesystem::resolvePath($p);
187
+    }
188
+
189
+    /**
190
+     * Return the path to a local version of the file
191
+     * we need this because we can't know if a file is stored local or not from
192
+     * outside the filestorage and for some purposes a local file is needed
193
+     *
194
+     * @param string $path
195
+     */
196
+    public function getLocalFile($path): string|false {
197
+        $parent = substr($path, 0, strrpos($path, '/') ?: 0);
198
+        $path = $this->getAbsolutePath($path);
199
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
200
+        if (Filesystem::isValidPath($parent) && $storage) {
201
+            return $storage->getLocalFile($internalPath);
202
+        } else {
203
+            return false;
204
+        }
205
+    }
206
+
207
+    /**
208
+     * the following functions operate with arguments and return values identical
209
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
210
+     * for \OC\Files\Storage\Storage via basicOperation().
211
+     */
212
+    public function mkdir($path) {
213
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
214
+    }
215
+
216
+    /**
217
+     * remove mount point
218
+     *
219
+     * @param IMountPoint $mount
220
+     * @param string $path relative to data/
221
+     */
222
+    protected function removeMount($mount, $path): bool {
223
+        if ($mount instanceof MoveableMount) {
224
+            // cut of /user/files to get the relative path to data/user/files
225
+            $pathParts = explode('/', $path, 4);
226
+            $relPath = '/' . $pathParts[3];
227
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
228
+            \OC_Hook::emit(
229
+                Filesystem::CLASSNAME, 'umount',
230
+                [Filesystem::signal_param_path => $relPath]
231
+            );
232
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
233
+            $result = $mount->removeMount();
234
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
235
+            if ($result) {
236
+                \OC_Hook::emit(
237
+                    Filesystem::CLASSNAME, 'post_umount',
238
+                    [Filesystem::signal_param_path => $relPath]
239
+                );
240
+            }
241
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
242
+            return $result;
243
+        } else {
244
+            // do not allow deleting the storage's root / the mount point
245
+            // because for some storages it might delete the whole contents
246
+            // but isn't supposed to work that way
247
+            return false;
248
+        }
249
+    }
250
+
251
+    public function disableCacheUpdate(): void {
252
+        $this->updaterEnabled = false;
253
+    }
254
+
255
+    public function enableCacheUpdate(): void {
256
+        $this->updaterEnabled = true;
257
+    }
258
+
259
+    protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
260
+        if ($this->updaterEnabled) {
261
+            if (is_null($time)) {
262
+                $time = time();
263
+            }
264
+            $storage->getUpdater()->update($internalPath, $time, $sizeDifference);
265
+        }
266
+    }
267
+
268
+    protected function removeUpdate(Storage $storage, string $internalPath): void {
269
+        if ($this->updaterEnabled) {
270
+            $storage->getUpdater()->remove($internalPath);
271
+        }
272
+    }
273
+
274
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
275
+        if ($this->updaterEnabled) {
276
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
277
+        }
278
+    }
279
+
280
+    protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
281
+        if ($this->updaterEnabled) {
282
+            $targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
283
+        }
284
+    }
285
+
286
+    /**
287
+     * @param string $path
288
+     * @return bool|mixed
289
+     */
290
+    public function rmdir($path) {
291
+        $absolutePath = $this->getAbsolutePath($path);
292
+        $mount = Filesystem::getMountManager()->find($absolutePath);
293
+        if ($mount->getInternalPath($absolutePath) === '') {
294
+            return $this->removeMount($mount, $absolutePath);
295
+        }
296
+        if ($this->is_dir($path)) {
297
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
298
+        } else {
299
+            $result = false;
300
+        }
301
+
302
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
303
+            $storage = $mount->getStorage();
304
+            $internalPath = $mount->getInternalPath($absolutePath);
305
+            $storage->getUpdater()->remove($internalPath);
306
+        }
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * @param string $path
312
+     * @return resource|false
313
+     */
314
+    public function opendir($path) {
315
+        return $this->basicOperation('opendir', $path, ['read']);
316
+    }
317
+
318
+    /**
319
+     * @param string $path
320
+     * @return bool|mixed
321
+     */
322
+    public function is_dir($path) {
323
+        if ($path == '/') {
324
+            return true;
325
+        }
326
+        return $this->basicOperation('is_dir', $path);
327
+    }
328
+
329
+    /**
330
+     * @param string $path
331
+     * @return bool|mixed
332
+     */
333
+    public function is_file($path) {
334
+        if ($path == '/') {
335
+            return false;
336
+        }
337
+        return $this->basicOperation('is_file', $path);
338
+    }
339
+
340
+    /**
341
+     * @param string $path
342
+     * @return mixed
343
+     */
344
+    public function stat($path) {
345
+        return $this->basicOperation('stat', $path);
346
+    }
347
+
348
+    /**
349
+     * @param string $path
350
+     * @return mixed
351
+     */
352
+    public function filetype($path) {
353
+        return $this->basicOperation('filetype', $path);
354
+    }
355
+
356
+    /**
357
+     * @param string $path
358
+     * @return mixed
359
+     */
360
+    public function filesize(string $path) {
361
+        return $this->basicOperation('filesize', $path);
362
+    }
363
+
364
+    /**
365
+     * @param string $path
366
+     * @return bool|mixed
367
+     * @throws InvalidPathException
368
+     */
369
+    public function readfile($path) {
370
+        $this->assertPathLength($path);
371
+        if (ob_get_level()) {
372
+            ob_end_clean();
373
+        }
374
+        $handle = $this->fopen($path, 'rb');
375
+        if ($handle) {
376
+            $chunkSize = 524288; // 512 kiB chunks
377
+            while (!feof($handle)) {
378
+                echo fread($handle, $chunkSize);
379
+                flush();
380
+                $this->checkConnectionStatus();
381
+            }
382
+            fclose($handle);
383
+            return $this->filesize($path);
384
+        }
385
+        return false;
386
+    }
387
+
388
+    /**
389
+     * @param string $path
390
+     * @param int $from
391
+     * @param int $to
392
+     * @return bool|mixed
393
+     * @throws InvalidPathException
394
+     * @throws \OCP\Files\UnseekableException
395
+     */
396
+    public function readfilePart($path, $from, $to) {
397
+        $this->assertPathLength($path);
398
+        if (ob_get_level()) {
399
+            ob_end_clean();
400
+        }
401
+        $handle = $this->fopen($path, 'rb');
402
+        if ($handle) {
403
+            $chunkSize = 524288; // 512 kiB chunks
404
+            $startReading = true;
405
+
406
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
407
+                // forward file handle via chunked fread because fseek seem to have failed
408
+
409
+                $end = $from + 1;
410
+                while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
411
+                    $len = $from - ftell($handle);
412
+                    if ($len > $chunkSize) {
413
+                        $len = $chunkSize;
414
+                    }
415
+                    $result = fread($handle, $len);
416
+
417
+                    if ($result === false) {
418
+                        $startReading = false;
419
+                        break;
420
+                    }
421
+                }
422
+            }
423
+
424
+            if ($startReading) {
425
+                $end = $to + 1;
426
+                while (!feof($handle) && ftell($handle) < $end) {
427
+                    $len = $end - ftell($handle);
428
+                    if ($len > $chunkSize) {
429
+                        $len = $chunkSize;
430
+                    }
431
+                    echo fread($handle, $len);
432
+                    flush();
433
+                    $this->checkConnectionStatus();
434
+                }
435
+                return ftell($handle) - $from;
436
+            }
437
+
438
+            throw new \OCP\Files\UnseekableException('fseek error');
439
+        }
440
+        return false;
441
+    }
442
+
443
+    private function checkConnectionStatus(): void {
444
+        $connectionStatus = \connection_status();
445
+        if ($connectionStatus !== CONNECTION_NORMAL) {
446
+            throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
447
+        }
448
+    }
449
+
450
+    /**
451
+     * @param string $path
452
+     * @return mixed
453
+     */
454
+    public function isCreatable($path) {
455
+        return $this->basicOperation('isCreatable', $path);
456
+    }
457
+
458
+    /**
459
+     * @param string $path
460
+     * @return mixed
461
+     */
462
+    public function isReadable($path) {
463
+        return $this->basicOperation('isReadable', $path);
464
+    }
465
+
466
+    /**
467
+     * @param string $path
468
+     * @return mixed
469
+     */
470
+    public function isUpdatable($path) {
471
+        return $this->basicOperation('isUpdatable', $path);
472
+    }
473
+
474
+    /**
475
+     * @param string $path
476
+     * @return bool|mixed
477
+     */
478
+    public function isDeletable($path) {
479
+        $absolutePath = $this->getAbsolutePath($path);
480
+        $mount = Filesystem::getMountManager()->find($absolutePath);
481
+        if ($mount->getInternalPath($absolutePath) === '') {
482
+            return $mount instanceof MoveableMount;
483
+        }
484
+        return $this->basicOperation('isDeletable', $path);
485
+    }
486
+
487
+    /**
488
+     * @param string $path
489
+     * @return mixed
490
+     */
491
+    public function isSharable($path) {
492
+        return $this->basicOperation('isSharable', $path);
493
+    }
494
+
495
+    /**
496
+     * @param string $path
497
+     * @return bool|mixed
498
+     */
499
+    public function file_exists($path) {
500
+        if ($path == '/') {
501
+            return true;
502
+        }
503
+        return $this->basicOperation('file_exists', $path);
504
+    }
505
+
506
+    /**
507
+     * @param string $path
508
+     * @return mixed
509
+     */
510
+    public function filemtime($path) {
511
+        return $this->basicOperation('filemtime', $path);
512
+    }
513
+
514
+    /**
515
+     * @param string $path
516
+     * @param int|string $mtime
517
+     */
518
+    public function touch($path, $mtime = null): bool {
519
+        if (!is_null($mtime) && !is_numeric($mtime)) {
520
+            $mtime = strtotime($mtime);
521
+        }
522
+
523
+        $hooks = ['touch'];
524
+
525
+        if (!$this->file_exists($path)) {
526
+            $hooks[] = 'create';
527
+            $hooks[] = 'write';
528
+        }
529
+        try {
530
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
531
+        } catch (\Exception $e) {
532
+            $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
533
+            $result = false;
534
+        }
535
+        if (!$result) {
536
+            // If create file fails because of permissions on external storage like SMB folders,
537
+            // check file exists and return false if not.
538
+            if (!$this->file_exists($path)) {
539
+                return false;
540
+            }
541
+            if (is_null($mtime)) {
542
+                $mtime = time();
543
+            }
544
+            //if native touch fails, we emulate it by changing the mtime in the cache
545
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
546
+        }
547
+        return true;
548
+    }
549
+
550
+    /**
551
+     * @param string $path
552
+     * @return string|false
553
+     * @throws LockedException
554
+     */
555
+    public function file_get_contents($path) {
556
+        return $this->basicOperation('file_get_contents', $path, ['read']);
557
+    }
558
+
559
+    protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
560
+        if (!$exists) {
561
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
562
+                Filesystem::signal_param_path => $this->getHookPath($path),
563
+                Filesystem::signal_param_run => &$run,
564
+            ]);
565
+        } else {
566
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
567
+                Filesystem::signal_param_path => $this->getHookPath($path),
568
+                Filesystem::signal_param_run => &$run,
569
+            ]);
570
+        }
571
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
572
+            Filesystem::signal_param_path => $this->getHookPath($path),
573
+            Filesystem::signal_param_run => &$run,
574
+        ]);
575
+    }
576
+
577
+    protected function emit_file_hooks_post(bool $exists, string $path): void {
578
+        if (!$exists) {
579
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
580
+                Filesystem::signal_param_path => $this->getHookPath($path),
581
+            ]);
582
+        } else {
583
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
584
+                Filesystem::signal_param_path => $this->getHookPath($path),
585
+            ]);
586
+        }
587
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
588
+            Filesystem::signal_param_path => $this->getHookPath($path),
589
+        ]);
590
+    }
591
+
592
+    /**
593
+     * @param string $path
594
+     * @param string|resource $data
595
+     * @return bool|mixed
596
+     * @throws LockedException
597
+     */
598
+    public function file_put_contents($path, $data) {
599
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
600
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
601
+            if (Filesystem::isValidPath($path)
602
+                && !Filesystem::isFileBlacklisted($path)
603
+            ) {
604
+                $path = $this->getRelativePath($absolutePath);
605
+                if ($path === null) {
606
+                    throw new InvalidPathException("Path $absolutePath is not in the expected root");
607
+                }
608
+
609
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
610
+
611
+                $exists = $this->file_exists($path);
612
+                if ($this->shouldEmitHooks($path)) {
613
+                    $run = true;
614
+                    $this->emit_file_hooks_pre($exists, $path, $run);
615
+                    if (!$run) {
616
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
617
+                        return false;
618
+                    }
619
+                }
620
+
621
+                try {
622
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
623
+                } catch (\Exception $e) {
624
+                    // Release the shared lock before throwing.
625
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
626
+                    throw $e;
627
+                }
628
+
629
+                /** @var Storage $storage */
630
+                [$storage, $internalPath] = $this->resolvePath($path);
631
+                $target = $storage->fopen($internalPath, 'w');
632
+                if ($target) {
633
+                    [, $result] = Files::streamCopy($data, $target, true);
634
+                    fclose($target);
635
+                    fclose($data);
636
+
637
+                    $this->writeUpdate($storage, $internalPath);
638
+
639
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
640
+
641
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
642
+                        $this->emit_file_hooks_post($exists, $path);
643
+                    }
644
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
645
+                    return $result;
646
+                } else {
647
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
648
+                    return false;
649
+                }
650
+            } else {
651
+                return false;
652
+            }
653
+        } else {
654
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
655
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
656
+        }
657
+    }
658
+
659
+    /**
660
+     * @param string $path
661
+     * @return bool|mixed
662
+     */
663
+    public function unlink($path) {
664
+        if ($path === '' || $path === '/') {
665
+            // do not allow deleting the root
666
+            return false;
667
+        }
668
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
669
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
670
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
671
+        if ($mount->getInternalPath($absolutePath) === '') {
672
+            return $this->removeMount($mount, $absolutePath);
673
+        }
674
+        if ($this->is_dir($path)) {
675
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
676
+        } else {
677
+            $result = $this->basicOperation('unlink', $path, ['delete']);
678
+        }
679
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
680
+            $storage = $mount->getStorage();
681
+            $internalPath = $mount->getInternalPath($absolutePath);
682
+            $storage->getUpdater()->remove($internalPath);
683
+            return true;
684
+        } else {
685
+            return $result;
686
+        }
687
+    }
688
+
689
+    /**
690
+     * @param string $directory
691
+     * @return bool|mixed
692
+     */
693
+    public function deleteAll($directory) {
694
+        return $this->rmdir($directory);
695
+    }
696
+
697
+    /**
698
+     * Rename/move a file or folder from the source path to target path.
699
+     *
700
+     * @param string $source source path
701
+     * @param string $target target path
702
+     * @param array $options
703
+     *
704
+     * @return bool|mixed
705
+     * @throws LockedException
706
+     */
707
+    public function rename($source, $target, array $options = []) {
708
+        $checkSubMounts = $options['checkSubMounts'] ?? true;
709
+
710
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
711
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
712
+
713
+        if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
714
+            throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
715
+        }
716
+
717
+        /** @var IMountManager $mountManager */
718
+        $mountManager = \OC::$server->get(IMountManager::class);
719
+
720
+        $targetParts = explode('/', $absolutePath2);
721
+        $targetUser = $targetParts[1] ?? null;
722
+        $result = false;
723
+        if (
724
+            Filesystem::isValidPath($target)
725
+            && Filesystem::isValidPath($source)
726
+            && !Filesystem::isFileBlacklisted($target)
727
+        ) {
728
+            $source = $this->getRelativePath($absolutePath1);
729
+            $target = $this->getRelativePath($absolutePath2);
730
+            $exists = $this->file_exists($target);
731
+
732
+            if ($source == null || $target == null) {
733
+                return false;
734
+            }
735
+
736
+            try {
737
+                $this->verifyPath(dirname($target), basename($target));
738
+            } catch (InvalidPathException) {
739
+                return false;
740
+            }
741
+
742
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
743
+            try {
744
+                $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
745
+
746
+                $run = true;
747
+                if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
748
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
749
+                    $this->emit_file_hooks_pre($exists, $target, $run);
750
+                } elseif ($this->shouldEmitHooks($source)) {
751
+                    $sourcePath = $this->getHookPath($source);
752
+                    $targetPath = $this->getHookPath($target);
753
+                    if ($sourcePath !== null && $targetPath !== null) {
754
+                        \OC_Hook::emit(
755
+                            Filesystem::CLASSNAME, Filesystem::signal_rename,
756
+                            [
757
+                                Filesystem::signal_param_oldpath => $sourcePath,
758
+                                Filesystem::signal_param_newpath => $targetPath,
759
+                                Filesystem::signal_param_run => &$run
760
+                            ]
761
+                        );
762
+                    }
763
+                }
764
+                if ($run) {
765
+                    $manager = Filesystem::getMountManager();
766
+                    $mount1 = $this->getMount($source);
767
+                    $mount2 = $this->getMount($target);
768
+                    $storage1 = $mount1->getStorage();
769
+                    $storage2 = $mount2->getStorage();
770
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
771
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
772
+
773
+                    $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
774
+                    try {
775
+                        $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
776
+
777
+                        if ($checkSubMounts) {
778
+                            $movedMounts = $mountManager->findIn($this->getAbsolutePath($source));
779
+                        } else {
780
+                            $movedMounts = [];
781
+                        }
782
+
783
+                        if ($internalPath1 === '') {
784
+                            $sourceParentMount = $this->getMount(dirname($source));
785
+                            $movedMounts[] = $mount1;
786
+                            $this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
787
+                            /**
788
+                             * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
789
+                             */
790
+                            $sourceMountPoint = $mount1->getMountPoint();
791
+                            $result = $mount1->moveMount($absolutePath2);
792
+                            $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
793
+
794
+                            // moving a file/folder within the same mount point
795
+                        } elseif ($storage1 === $storage2) {
796
+                            if (count($movedMounts) > 0) {
797
+                                $this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
798
+                            }
799
+                            if ($storage1) {
800
+                                $result = $storage1->rename($internalPath1, $internalPath2);
801
+                            } else {
802
+                                $result = false;
803
+                            }
804
+                            // moving a file/folder between storages (from $storage1 to $storage2)
805
+                        } else {
806
+                            if (count($movedMounts) > 0) {
807
+                                $this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
808
+                            }
809
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
810
+                        }
811
+
812
+                        if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
813
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
814
+                            $this->writeUpdate($storage2, $internalPath2);
815
+                        } elseif ($result) {
816
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
817
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
818
+                            }
819
+                        }
820
+                    } catch (\Exception $e) {
821
+                        throw $e;
822
+                    } finally {
823
+                        $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
824
+                        $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
825
+                    }
826
+
827
+                    if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
828
+                        if ($this->shouldEmitHooks()) {
829
+                            $this->emit_file_hooks_post($exists, $target);
830
+                        }
831
+                    } elseif ($result) {
832
+                        if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
833
+                            $sourcePath = $this->getHookPath($source);
834
+                            $targetPath = $this->getHookPath($target);
835
+                            if ($sourcePath !== null && $targetPath !== null) {
836
+                                \OC_Hook::emit(
837
+                                    Filesystem::CLASSNAME,
838
+                                    Filesystem::signal_post_rename,
839
+                                    [
840
+                                        Filesystem::signal_param_oldpath => $sourcePath,
841
+                                        Filesystem::signal_param_newpath => $targetPath,
842
+                                    ]
843
+                                );
844
+                            }
845
+                        }
846
+                    }
847
+                }
848
+            } catch (\Exception $e) {
849
+                throw $e;
850
+            } finally {
851
+                $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
852
+                $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
853
+            }
854
+        }
855
+        return $result;
856
+    }
857
+
858
+    /**
859
+     * @throws ForbiddenException
860
+     */
861
+    private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMountPoint $targetMount, bool $targetIsShared): void {
862
+        $targetPath = $this->getRelativePath($targetMount->getMountPoint());
863
+        if ($targetPath) {
864
+            $targetPath = trim($targetPath, '/');
865
+        } else {
866
+            $targetPath = $targetMount->getMountPoint();
867
+        }
868
+
869
+        $l = \OC::$server->get(IFactory::class)->get('files');
870
+        foreach ($mounts as $mount) {
871
+            $sourcePath = $this->getRelativePath($mount->getMountPoint());
872
+            if ($sourcePath) {
873
+                $sourcePath = trim($sourcePath, '/');
874
+            } else {
875
+                $sourcePath = $mount->getMountPoint();
876
+            }
877
+
878
+            if (!$mount instanceof MoveableMount) {
879
+                throw new ForbiddenException($l->t('Storage %s cannot be moved', [$sourcePath]), false);
880
+            }
881
+
882
+            if ($targetIsShared) {
883
+                if ($sourceMount instanceof SharedMount) {
884
+                    throw new ForbiddenException($l->t('Moving a share (%s) into a shared folder is not allowed', [$sourcePath]), false);
885
+                } else {
886
+                    throw new ForbiddenException($l->t('Moving a storage (%s) into a shared folder is not allowed', [$sourcePath]), false);
887
+                }
888
+            }
889
+
890
+            if ($sourceMount !== $targetMount) {
891
+                if ($sourceMount instanceof SharedMount) {
892
+                    if ($targetMount instanceof SharedMount) {
893
+                        throw new ForbiddenException($l->t('Moving a share (%s) into another share (%s) is not allowed', [$sourcePath, $targetPath]), false);
894
+                    } else {
895
+                        throw new ForbiddenException($l->t('Moving a share (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
896
+                    }
897
+                } else {
898
+                    if ($targetMount instanceof SharedMount) {
899
+                        throw new ForbiddenException($l->t('Moving a storage (%s) into a share (%s) is not allowed', [$sourcePath, $targetPath]), false);
900
+                    } else {
901
+                        throw new ForbiddenException($l->t('Moving a storage (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
902
+                    }
903
+                }
904
+            }
905
+        }
906
+    }
907
+
908
+    /**
909
+     * Copy a file/folder from the source path to target path
910
+     *
911
+     * @param string $source source path
912
+     * @param string $target target path
913
+     * @param bool $preserveMtime whether to preserve mtime on the copy
914
+     *
915
+     * @return bool|mixed
916
+     */
917
+    public function copy($source, $target, $preserveMtime = false) {
918
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
919
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
920
+        $result = false;
921
+        if (
922
+            Filesystem::isValidPath($target)
923
+            && Filesystem::isValidPath($source)
924
+            && !Filesystem::isFileBlacklisted($target)
925
+        ) {
926
+            $source = $this->getRelativePath($absolutePath1);
927
+            $target = $this->getRelativePath($absolutePath2);
928
+
929
+            if ($source == null || $target == null) {
930
+                return false;
931
+            }
932
+            $run = true;
933
+
934
+            $this->lockFile($target, ILockingProvider::LOCK_SHARED);
935
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED);
936
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
937
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
938
+
939
+            try {
940
+                $exists = $this->file_exists($target);
941
+                if ($this->shouldEmitHooks()) {
942
+                    \OC_Hook::emit(
943
+                        Filesystem::CLASSNAME,
944
+                        Filesystem::signal_copy,
945
+                        [
946
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
947
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
948
+                            Filesystem::signal_param_run => &$run
949
+                        ]
950
+                    );
951
+                    $this->emit_file_hooks_pre($exists, $target, $run);
952
+                }
953
+                if ($run) {
954
+                    $mount1 = $this->getMount($source);
955
+                    $mount2 = $this->getMount($target);
956
+                    $storage1 = $mount1->getStorage();
957
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
958
+                    $storage2 = $mount2->getStorage();
959
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
960
+
961
+                    $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
962
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
963
+
964
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
965
+                        if ($storage1) {
966
+                            $result = $storage1->copy($internalPath1, $internalPath2);
967
+                        } else {
968
+                            $result = false;
969
+                        }
970
+                    } else {
971
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
972
+                    }
973
+
974
+                    if ($result) {
975
+                        $this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
976
+                    }
977
+
978
+                    $this->changeLock($target, ILockingProvider::LOCK_SHARED);
979
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
980
+
981
+                    if ($this->shouldEmitHooks() && $result !== false) {
982
+                        \OC_Hook::emit(
983
+                            Filesystem::CLASSNAME,
984
+                            Filesystem::signal_post_copy,
985
+                            [
986
+                                Filesystem::signal_param_oldpath => $this->getHookPath($source),
987
+                                Filesystem::signal_param_newpath => $this->getHookPath($target)
988
+                            ]
989
+                        );
990
+                        $this->emit_file_hooks_post($exists, $target);
991
+                    }
992
+                }
993
+            } catch (\Exception $e) {
994
+                $this->unlockFile($target, $lockTypePath2);
995
+                $this->unlockFile($source, $lockTypePath1);
996
+                throw $e;
997
+            }
998
+
999
+            $this->unlockFile($target, $lockTypePath2);
1000
+            $this->unlockFile($source, $lockTypePath1);
1001
+        }
1002
+        return $result;
1003
+    }
1004
+
1005
+    /**
1006
+     * @param string $path
1007
+     * @param string $mode 'r' or 'w'
1008
+     * @return resource|false
1009
+     * @throws LockedException
1010
+     */
1011
+    public function fopen($path, $mode) {
1012
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
1013
+        $hooks = [];
1014
+        switch ($mode) {
1015
+            case 'r':
1016
+                $hooks[] = 'read';
1017
+                break;
1018
+            case 'r+':
1019
+            case 'w+':
1020
+            case 'x+':
1021
+            case 'a+':
1022
+                $hooks[] = 'read';
1023
+                $hooks[] = 'write';
1024
+                break;
1025
+            case 'w':
1026
+            case 'x':
1027
+            case 'a':
1028
+                $hooks[] = 'write';
1029
+                break;
1030
+            default:
1031
+                $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1032
+        }
1033
+
1034
+        if ($mode !== 'r' && $mode !== 'w') {
1035
+            $this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1036
+        }
1037
+
1038
+        $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1039
+        if (!is_resource($handle) && $mode === 'r') {
1040
+            // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1041
+            $mount = $this->getMount($path);
1042
+            $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1043
+            $storage = $mount->getStorage();
1044
+            if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1045
+                $this->writeUpdate($storage, $internalPath);
1046
+            }
1047
+        }
1048
+        return $handle;
1049
+    }
1050
+
1051
+    /**
1052
+     * @param string $path
1053
+     * @throws InvalidPathException
1054
+     */
1055
+    public function toTmpFile($path): string|false {
1056
+        $this->assertPathLength($path);
1057
+        if (Filesystem::isValidPath($path)) {
1058
+            $source = $this->fopen($path, 'r');
1059
+            if ($source) {
1060
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1061
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1062
+                file_put_contents($tmpFile, $source);
1063
+                return $tmpFile;
1064
+            } else {
1065
+                return false;
1066
+            }
1067
+        } else {
1068
+            return false;
1069
+        }
1070
+    }
1071
+
1072
+    /**
1073
+     * @param string $tmpFile
1074
+     * @param string $path
1075
+     * @return bool|mixed
1076
+     * @throws InvalidPathException
1077
+     */
1078
+    public function fromTmpFile($tmpFile, $path) {
1079
+        $this->assertPathLength($path);
1080
+        if (Filesystem::isValidPath($path)) {
1081
+            // Get directory that the file is going into
1082
+            $filePath = dirname($path);
1083
+
1084
+            // Create the directories if any
1085
+            if (!$this->file_exists($filePath)) {
1086
+                $result = $this->createParentDirectories($filePath);
1087
+                if ($result === false) {
1088
+                    return false;
1089
+                }
1090
+            }
1091
+
1092
+            $source = fopen($tmpFile, 'r');
1093
+            if ($source) {
1094
+                $result = $this->file_put_contents($path, $source);
1095
+                /**
1096
+                 * $this->file_put_contents() might have already closed
1097
+                 * the resource, so we check it, before trying to close it
1098
+                 * to avoid messages in the error log.
1099
+                 * @psalm-suppress RedundantCondition false-positive
1100
+                 */
1101
+                if (is_resource($source)) {
1102
+                    fclose($source);
1103
+                }
1104
+                unlink($tmpFile);
1105
+                return $result;
1106
+            } else {
1107
+                return false;
1108
+            }
1109
+        } else {
1110
+            return false;
1111
+        }
1112
+    }
1113
+
1114
+
1115
+    /**
1116
+     * @param string $path
1117
+     * @return mixed
1118
+     * @throws InvalidPathException
1119
+     */
1120
+    public function getMimeType($path) {
1121
+        $this->assertPathLength($path);
1122
+        return $this->basicOperation('getMimeType', $path);
1123
+    }
1124
+
1125
+    /**
1126
+     * @param string $type
1127
+     * @param string $path
1128
+     * @param bool $raw
1129
+     */
1130
+    public function hash($type, $path, $raw = false): string|bool {
1131
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1132
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
+        if (Filesystem::isValidPath($path)) {
1134
+            $path = $this->getRelativePath($absolutePath);
1135
+            if ($path == null) {
1136
+                return false;
1137
+            }
1138
+            if ($this->shouldEmitHooks($path)) {
1139
+                \OC_Hook::emit(
1140
+                    Filesystem::CLASSNAME,
1141
+                    Filesystem::signal_read,
1142
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1143
+                );
1144
+            }
1145
+            /** @var Storage|null $storage */
1146
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1147
+            if ($storage) {
1148
+                return $storage->hash($type, $internalPath, $raw);
1149
+            }
1150
+        }
1151
+        return false;
1152
+    }
1153
+
1154
+    /**
1155
+     * @param string $path
1156
+     * @return mixed
1157
+     * @throws InvalidPathException
1158
+     */
1159
+    public function free_space($path = '/') {
1160
+        $this->assertPathLength($path);
1161
+        $result = $this->basicOperation('free_space', $path);
1162
+        if ($result === null) {
1163
+            throw new InvalidPathException();
1164
+        }
1165
+        return $result;
1166
+    }
1167
+
1168
+    /**
1169
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1170
+     *
1171
+     * @param mixed $extraParam (optional)
1172
+     * @return mixed
1173
+     * @throws LockedException
1174
+     *
1175
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1176
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1177
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1178
+     */
1179
+    private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1180
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1181
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1182
+        if (Filesystem::isValidPath($path)
1183
+            && !Filesystem::isFileBlacklisted($path)
1184
+        ) {
1185
+            $path = $this->getRelativePath($absolutePath);
1186
+            if ($path == null) {
1187
+                return false;
1188
+            }
1189
+
1190
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1191
+                // always a shared lock during pre-hooks so the hook can read the file
1192
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1193
+            }
1194
+
1195
+            $run = $this->runHooks($hooks, $path);
1196
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1197
+            if ($run && $storage) {
1198
+                /** @var Storage $storage */
1199
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1200
+                    try {
1201
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1202
+                    } catch (LockedException $e) {
1203
+                        // release the shared lock we acquired before quitting
1204
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1205
+                        throw $e;
1206
+                    }
1207
+                }
1208
+                try {
1209
+                    if (!is_null($extraParam)) {
1210
+                        $result = $storage->$operation($internalPath, $extraParam);
1211
+                    } else {
1212
+                        $result = $storage->$operation($internalPath);
1213
+                    }
1214
+                } catch (\Exception $e) {
1215
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1216
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1217
+                    } elseif (in_array('read', $hooks)) {
1218
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1219
+                    }
1220
+                    throw $e;
1221
+                }
1222
+
1223
+                if ($result !== false && in_array('delete', $hooks)) {
1224
+                    $this->removeUpdate($storage, $internalPath);
1225
+                }
1226
+                if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1227
+                    $isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
1228
+                    $sizeDifference = $operation === 'mkdir' ? 0 : $result;
1229
+                    $this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
1230
+                }
1231
+                if ($result !== false && in_array('touch', $hooks)) {
1232
+                    $this->writeUpdate($storage, $internalPath, $extraParam, 0);
1233
+                }
1234
+
1235
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1236
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1237
+                }
1238
+
1239
+                $unlockLater = false;
1240
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1241
+                    $unlockLater = true;
1242
+                    // make sure our unlocking callback will still be called if connection is aborted
1243
+                    ignore_user_abort(true);
1244
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1245
+                        if (in_array('write', $hooks)) {
1246
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1247
+                        } elseif (in_array('read', $hooks)) {
1248
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1249
+                        }
1250
+                    });
1251
+                }
1252
+
1253
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1254
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1255
+                        $this->runHooks($hooks, $path, true);
1256
+                    }
1257
+                }
1258
+
1259
+                if (!$unlockLater
1260
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1261
+                ) {
1262
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1263
+                }
1264
+                return $result;
1265
+            } else {
1266
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1267
+            }
1268
+        }
1269
+        return null;
1270
+    }
1271
+
1272
+    /**
1273
+     * get the path relative to the default root for hook usage
1274
+     *
1275
+     * @param string $path
1276
+     * @return ?string
1277
+     */
1278
+    private function getHookPath($path): ?string {
1279
+        $view = Filesystem::getView();
1280
+        if (!$view) {
1281
+            return $path;
1282
+        }
1283
+        return $view->getRelativePath($this->getAbsolutePath($path));
1284
+    }
1285
+
1286
+    private function shouldEmitHooks(string $path = ''): bool {
1287
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1288
+            return false;
1289
+        }
1290
+        if (!Filesystem::$loaded) {
1291
+            return false;
1292
+        }
1293
+        $defaultRoot = Filesystem::getRoot();
1294
+        if ($defaultRoot === null) {
1295
+            return false;
1296
+        }
1297
+        if ($this->fakeRoot === $defaultRoot) {
1298
+            return true;
1299
+        }
1300
+        $fullPath = $this->getAbsolutePath($path);
1301
+
1302
+        if ($fullPath === $defaultRoot) {
1303
+            return true;
1304
+        }
1305
+
1306
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1307
+    }
1308
+
1309
+    /**
1310
+     * @param string[] $hooks
1311
+     * @param string $path
1312
+     * @param bool $post
1313
+     * @return bool
1314
+     */
1315
+    private function runHooks($hooks, $path, $post = false) {
1316
+        $relativePath = $path;
1317
+        $path = $this->getHookPath($path);
1318
+        $prefix = $post ? 'post_' : '';
1319
+        $run = true;
1320
+        if ($this->shouldEmitHooks($relativePath)) {
1321
+            foreach ($hooks as $hook) {
1322
+                if ($hook != 'read') {
1323
+                    \OC_Hook::emit(
1324
+                        Filesystem::CLASSNAME,
1325
+                        $prefix . $hook,
1326
+                        [
1327
+                            Filesystem::signal_param_run => &$run,
1328
+                            Filesystem::signal_param_path => $path
1329
+                        ]
1330
+                    );
1331
+                } elseif (!$post) {
1332
+                    \OC_Hook::emit(
1333
+                        Filesystem::CLASSNAME,
1334
+                        $prefix . $hook,
1335
+                        [
1336
+                            Filesystem::signal_param_path => $path
1337
+                        ]
1338
+                    );
1339
+                }
1340
+            }
1341
+        }
1342
+        return $run;
1343
+    }
1344
+
1345
+    /**
1346
+     * check if a file or folder has been updated since $time
1347
+     *
1348
+     * @param string $path
1349
+     * @param int $time
1350
+     * @return bool
1351
+     */
1352
+    public function hasUpdated($path, $time) {
1353
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1354
+    }
1355
+
1356
+    /**
1357
+     * @param string $ownerId
1358
+     * @return IUser
1359
+     */
1360
+    private function getUserObjectForOwner(string $ownerId) {
1361
+        return new LazyUser($ownerId, $this->userManager);
1362
+    }
1363
+
1364
+    /**
1365
+     * Get file info from cache
1366
+     *
1367
+     * If the file is not in cached it will be scanned
1368
+     * If the file has changed on storage the cache will be updated
1369
+     *
1370
+     * @param Storage $storage
1371
+     * @param string $internalPath
1372
+     * @param string $relativePath
1373
+     * @return ICacheEntry|bool
1374
+     */
1375
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1376
+        $cache = $storage->getCache($internalPath);
1377
+        $data = $cache->get($internalPath);
1378
+        $watcher = $storage->getWatcher($internalPath);
1379
+
1380
+        try {
1381
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1382
+            if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1383
+                if (!$storage->file_exists($internalPath)) {
1384
+                    return false;
1385
+                }
1386
+                // don't need to get a lock here since the scanner does it's own locking
1387
+                $scanner = $storage->getScanner($internalPath);
1388
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1389
+                $data = $cache->get($internalPath);
1390
+            } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1391
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1392
+                $watcher->update($internalPath, $data);
1393
+                $storage->getPropagator()->propagateChange($internalPath, time());
1394
+                $data = $cache->get($internalPath);
1395
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1396
+            }
1397
+        } catch (LockedException $e) {
1398
+            // if the file is locked we just use the old cache info
1399
+        }
1400
+
1401
+        return $data;
1402
+    }
1403
+
1404
+    /**
1405
+     * get the filesystem info
1406
+     *
1407
+     * @param string $path
1408
+     * @param bool|string $includeMountPoints true to add mountpoint sizes,
1409
+     *                                        'ext' to add only ext storage mount point sizes. Defaults to true.
1410
+     * @return \OC\Files\FileInfo|false False if file does not exist
1411
+     */
1412
+    public function getFileInfo($path, $includeMountPoints = true) {
1413
+        $this->assertPathLength($path);
1414
+        if (!Filesystem::isValidPath($path)) {
1415
+            return false;
1416
+        }
1417
+        $relativePath = $path;
1418
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1419
+
1420
+        $mount = Filesystem::getMountManager()->find($path);
1421
+        $storage = $mount->getStorage();
1422
+        $internalPath = $mount->getInternalPath($path);
1423
+        if ($storage) {
1424
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1425
+
1426
+            if (!$data instanceof ICacheEntry) {
1427
+                if (Cache\Scanner::isPartialFile($relativePath)) {
1428
+                    return $this->getPartFileInfo($relativePath);
1429
+                }
1430
+
1431
+                return false;
1432
+            }
1433
+
1434
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1435
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1436
+            }
1437
+            if ($internalPath === '' && $data['name']) {
1438
+                $data['name'] = basename($path);
1439
+            }
1440
+
1441
+            $ownerId = $storage->getOwner($internalPath);
1442
+            $owner = null;
1443
+            if ($ownerId !== false) {
1444
+                // ownerId might be null if files are accessed with an access token without file system access
1445
+                $owner = $this->getUserObjectForOwner($ownerId);
1446
+            }
1447
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1448
+
1449
+            if (isset($data['fileid'])) {
1450
+                if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1451
+                    //add the sizes of other mount points to the folder
1452
+                    $extOnly = ($includeMountPoints === 'ext');
1453
+                    $this->addSubMounts($info, $extOnly);
1454
+                }
1455
+            }
1456
+
1457
+            return $info;
1458
+        } else {
1459
+            $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1460
+        }
1461
+
1462
+        return false;
1463
+    }
1464
+
1465
+    /**
1466
+     * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1467
+     */
1468
+    public function addSubMounts(FileInfo $info, $extOnly = false): void {
1469
+        $mounts = Filesystem::getMountManager()->findIn($info->getPath());
1470
+        $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1471
+            return !($extOnly && $mount instanceof SharedMount);
1472
+        }));
1473
+    }
1474
+
1475
+    /**
1476
+     * get the content of a directory
1477
+     *
1478
+     * @param string $directory path under datadirectory
1479
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1480
+     * @return FileInfo[]
1481
+     */
1482
+    public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
1483
+        $this->assertPathLength($directory);
1484
+        if (!Filesystem::isValidPath($directory)) {
1485
+            return [];
1486
+        }
1487
+
1488
+        $path = $this->getAbsolutePath($directory);
1489
+        $path = Filesystem::normalizePath($path);
1490
+        $mount = $this->getMount($directory);
1491
+        $storage = $mount->getStorage();
1492
+        $internalPath = $mount->getInternalPath($path);
1493
+        if (!$storage) {
1494
+            return [];
1495
+        }
1496
+
1497
+        $cache = $storage->getCache($internalPath);
1498
+        $user = \OC_User::getUser();
1499
+
1500
+        if (!$directoryInfo) {
1501
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1502
+            if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1503
+                return [];
1504
+            }
1505
+        } else {
1506
+            $data = $directoryInfo;
1507
+        }
1508
+
1509
+        if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1510
+            return [];
1511
+        }
1512
+
1513
+        $folderId = $data->getId();
1514
+        $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1515
+
1516
+        $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1517
+
1518
+        $fileNames = array_map(function (ICacheEntry $content) {
1519
+            return $content->getName();
1520
+        }, $contents);
1521
+        /**
1522
+         * @var \OC\Files\FileInfo[] $fileInfos
1523
+         */
1524
+        $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1525
+            if ($sharingDisabled) {
1526
+                $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1527
+            }
1528
+            $ownerId = $storage->getOwner($content['path']);
1529
+            if ($ownerId !== false) {
1530
+                $owner = $this->getUserObjectForOwner($ownerId);
1531
+            } else {
1532
+                $owner = null;
1533
+            }
1534
+            return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1535
+        }, $contents);
1536
+        $files = array_combine($fileNames, $fileInfos);
1537
+
1538
+        //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1539
+        $mounts = Filesystem::getMountManager()->findIn($path);
1540
+
1541
+        // make sure nested mounts are sorted after their parent mounts
1542
+        // otherwise doesn't propagate the etag across storage boundaries correctly
1543
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1544
+            return $a->getMountPoint() <=> $b->getMountPoint();
1545
+        });
1546
+
1547
+        $dirLength = strlen($path);
1548
+        foreach ($mounts as $mount) {
1549
+            $mountPoint = $mount->getMountPoint();
1550
+            $subStorage = $mount->getStorage();
1551
+            if ($subStorage) {
1552
+                $subCache = $subStorage->getCache('');
1553
+
1554
+                $rootEntry = $subCache->get('');
1555
+                if (!$rootEntry) {
1556
+                    $subScanner = $subStorage->getScanner();
1557
+                    try {
1558
+                        $subScanner->scanFile('');
1559
+                    } catch (\OCP\Files\StorageNotAvailableException $e) {
1560
+                        continue;
1561
+                    } catch (\OCP\Files\StorageInvalidException $e) {
1562
+                        continue;
1563
+                    } catch (\Exception $e) {
1564
+                        // sometimes when the storage is not available it can be any exception
1565
+                        $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1566
+                            'exception' => $e,
1567
+                            'app' => 'core',
1568
+                        ]);
1569
+                        continue;
1570
+                    }
1571
+                    $rootEntry = $subCache->get('');
1572
+                }
1573
+
1574
+                if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1575
+                    $relativePath = trim(substr($mountPoint, $dirLength), '/');
1576
+                    if ($pos = strpos($relativePath, '/')) {
1577
+                        //mountpoint inside subfolder add size to the correct folder
1578
+                        $entryName = substr($relativePath, 0, $pos);
1579
+
1580
+                        // Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1581
+                        if (!isset($files[$entryName])) {
1582
+                            try {
1583
+                                [$storage, ] = $this->resolvePath($path . '/' . $entryName);
1584
+                                // make sure we can create the mountpoint folder, even if the user has a quota of 0
1585
+                                if ($storage->instanceOfStorage(Quota::class)) {
1586
+                                    $storage->enableQuota(false);
1587
+                                }
1588
+
1589
+                                if ($this->mkdir($path . '/' . $entryName) !== false) {
1590
+                                    $info = $this->getFileInfo($path . '/' . $entryName);
1591
+                                    if ($info !== false) {
1592
+                                        $files[$entryName] = $info;
1593
+                                    }
1594
+                                }
1595
+
1596
+                                if ($storage->instanceOfStorage(Quota::class)) {
1597
+                                    $storage->enableQuota(true);
1598
+                                }
1599
+                            } catch (\Exception $e) {
1600
+                                // Creating the parent folder might not be possible, for example due to a lack of permissions.
1601
+                                $this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1602
+                            }
1603
+                        }
1604
+
1605
+                        if (isset($files[$entryName])) {
1606
+                            $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1607
+                        }
1608
+                    } else { //mountpoint in this folder, add an entry for it
1609
+                        $rootEntry['name'] = $relativePath;
1610
+                        $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1611
+                        $permissions = $rootEntry['permissions'];
1612
+                        // do not allow renaming/deleting the mount point if they are not shared files/folders
1613
+                        // for shared files/folders we use the permissions given by the owner
1614
+                        if ($mount instanceof MoveableMount) {
1615
+                            $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1616
+                        } else {
1617
+                            $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1618
+                        }
1619
+
1620
+                        $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1621
+
1622
+                        // if sharing was disabled for the user we remove the share permissions
1623
+                        if ($sharingDisabled) {
1624
+                            $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1625
+                        }
1626
+
1627
+                        $ownerId = $subStorage->getOwner('');
1628
+                        if ($ownerId !== false) {
1629
+                            $owner = $this->getUserObjectForOwner($ownerId);
1630
+                        } else {
1631
+                            $owner = null;
1632
+                        }
1633
+                        $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1634
+                    }
1635
+                }
1636
+            }
1637
+        }
1638
+
1639
+        if ($mimetype_filter) {
1640
+            $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1641
+                if (strpos($mimetype_filter, '/')) {
1642
+                    return $file->getMimetype() === $mimetype_filter;
1643
+                } else {
1644
+                    return $file->getMimePart() === $mimetype_filter;
1645
+                }
1646
+            });
1647
+        }
1648
+
1649
+        return array_values($files);
1650
+    }
1651
+
1652
+    /**
1653
+     * change file metadata
1654
+     *
1655
+     * @param string $path
1656
+     * @param array|\OCP\Files\FileInfo $data
1657
+     * @return int
1658
+     *
1659
+     * returns the fileid of the updated file
1660
+     */
1661
+    public function putFileInfo($path, $data) {
1662
+        $this->assertPathLength($path);
1663
+        if ($data instanceof FileInfo) {
1664
+            $data = $data->getData();
1665
+        }
1666
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1667
+        /**
1668
+         * @var Storage $storage
1669
+         * @var string $internalPath
1670
+         */
1671
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
1672
+        if ($storage) {
1673
+            $cache = $storage->getCache($path);
1674
+
1675
+            if (!$cache->inCache($internalPath)) {
1676
+                $scanner = $storage->getScanner($internalPath);
1677
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1678
+            }
1679
+
1680
+            return $cache->put($internalPath, $data);
1681
+        } else {
1682
+            return -1;
1683
+        }
1684
+    }
1685
+
1686
+    /**
1687
+     * search for files with the name matching $query
1688
+     *
1689
+     * @param string $query
1690
+     * @return FileInfo[]
1691
+     */
1692
+    public function search($query) {
1693
+        return $this->searchCommon('search', ['%' . $query . '%']);
1694
+    }
1695
+
1696
+    /**
1697
+     * search for files with the name matching $query
1698
+     *
1699
+     * @param string $query
1700
+     * @return FileInfo[]
1701
+     */
1702
+    public function searchRaw($query) {
1703
+        return $this->searchCommon('search', [$query]);
1704
+    }
1705
+
1706
+    /**
1707
+     * search for files by mimetype
1708
+     *
1709
+     * @param string $mimetype
1710
+     * @return FileInfo[]
1711
+     */
1712
+    public function searchByMime($mimetype) {
1713
+        return $this->searchCommon('searchByMime', [$mimetype]);
1714
+    }
1715
+
1716
+    /**
1717
+     * search for files by tag
1718
+     *
1719
+     * @param string|int $tag name or tag id
1720
+     * @param string $userId owner of the tags
1721
+     * @return FileInfo[]
1722
+     */
1723
+    public function searchByTag($tag, $userId) {
1724
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1725
+    }
1726
+
1727
+    /**
1728
+     * @param string $method cache method
1729
+     * @param array $args
1730
+     * @return FileInfo[]
1731
+     */
1732
+    private function searchCommon($method, $args) {
1733
+        $files = [];
1734
+        $rootLength = strlen($this->fakeRoot);
1735
+
1736
+        $mount = $this->getMount('');
1737
+        $mountPoint = $mount->getMountPoint();
1738
+        $storage = $mount->getStorage();
1739
+        $userManager = \OC::$server->getUserManager();
1740
+        if ($storage) {
1741
+            $cache = $storage->getCache('');
1742
+
1743
+            $results = call_user_func_array([$cache, $method], $args);
1744
+            foreach ($results as $result) {
1745
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1746
+                    $internalPath = $result['path'];
1747
+                    $path = $mountPoint . $result['path'];
1748
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1749
+                    $ownerId = $storage->getOwner($internalPath);
1750
+                    if ($ownerId !== false) {
1751
+                        $owner = $userManager->get($ownerId);
1752
+                    } else {
1753
+                        $owner = null;
1754
+                    }
1755
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1756
+                }
1757
+            }
1758
+
1759
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1760
+            foreach ($mounts as $mount) {
1761
+                $mountPoint = $mount->getMountPoint();
1762
+                $storage = $mount->getStorage();
1763
+                if ($storage) {
1764
+                    $cache = $storage->getCache('');
1765
+
1766
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1767
+                    $results = call_user_func_array([$cache, $method], $args);
1768
+                    if ($results) {
1769
+                        foreach ($results as $result) {
1770
+                            $internalPath = $result['path'];
1771
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1772
+                            $path = rtrim($mountPoint . $internalPath, '/');
1773
+                            $ownerId = $storage->getOwner($internalPath);
1774
+                            if ($ownerId !== false) {
1775
+                                $owner = $userManager->get($ownerId);
1776
+                            } else {
1777
+                                $owner = null;
1778
+                            }
1779
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1780
+                        }
1781
+                    }
1782
+                }
1783
+            }
1784
+        }
1785
+        return $files;
1786
+    }
1787
+
1788
+    /**
1789
+     * Get the owner for a file or folder
1790
+     *
1791
+     * @throws NotFoundException
1792
+     */
1793
+    public function getOwner(string $path): string {
1794
+        $info = $this->getFileInfo($path);
1795
+        if (!$info) {
1796
+            throw new NotFoundException($path . ' not found while trying to get owner');
1797
+        }
1798
+
1799
+        if ($info->getOwner() === null) {
1800
+            throw new NotFoundException($path . ' has no owner');
1801
+        }
1802
+
1803
+        return $info->getOwner()->getUID();
1804
+    }
1805
+
1806
+    /**
1807
+     * get the ETag for a file or folder
1808
+     *
1809
+     * @param string $path
1810
+     * @return string|false
1811
+     */
1812
+    public function getETag($path) {
1813
+        [$storage, $internalPath] = $this->resolvePath($path);
1814
+        if ($storage) {
1815
+            return $storage->getETag($internalPath);
1816
+        } else {
1817
+            return false;
1818
+        }
1819
+    }
1820
+
1821
+    /**
1822
+     * Get the path of a file by id, relative to the view
1823
+     *
1824
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1825
+     *
1826
+     * @param int $id
1827
+     * @param int|null $storageId
1828
+     * @return string
1829
+     * @throws NotFoundException
1830
+     */
1831
+    public function getPath($id, ?int $storageId = null) {
1832
+        $id = (int)$id;
1833
+        $manager = Filesystem::getMountManager();
1834
+        $mounts = $manager->findIn($this->fakeRoot);
1835
+        $mounts[] = $manager->find($this->fakeRoot);
1836
+        $mounts = array_filter($mounts);
1837
+        // reverse the array, so we start with the storage this view is in
1838
+        // which is the most likely to contain the file we're looking for
1839
+        $mounts = array_reverse($mounts);
1840
+
1841
+        // put non-shared mounts in front of the shared mount
1842
+        // this prevents unneeded recursion into shares
1843
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1844
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1845
+        });
1846
+
1847
+        if (!is_null($storageId)) {
1848
+            $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1849
+                return $mount->getNumericStorageId() === $storageId;
1850
+            });
1851
+        }
1852
+
1853
+        foreach ($mounts as $mount) {
1854
+            /**
1855
+             * @var \OC\Files\Mount\MountPoint $mount
1856
+             */
1857
+            if ($mount->getStorage()) {
1858
+                $cache = $mount->getStorage()->getCache();
1859
+                $internalPath = $cache->getPathById($id);
1860
+                if (is_string($internalPath)) {
1861
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1862
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1863
+                        return $path;
1864
+                    }
1865
+                }
1866
+            }
1867
+        }
1868
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1869
+    }
1870
+
1871
+    /**
1872
+     * @param string $path
1873
+     * @throws InvalidPathException
1874
+     */
1875
+    private function assertPathLength($path): void {
1876
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1877
+        // Check for the string length - performed using isset() instead of strlen()
1878
+        // because isset() is about 5x-40x faster.
1879
+        if (isset($path[$maxLen])) {
1880
+            $pathLen = strlen($path);
1881
+            throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1882
+        }
1883
+    }
1884
+
1885
+    /**
1886
+     * check if it is allowed to move a mount point to a given target.
1887
+     * It is not allowed to move a mount point into a different mount point or
1888
+     * into an already shared folder
1889
+     */
1890
+    private function targetIsNotShared(string $user, string $targetPath): bool {
1891
+        $providers = [
1892
+            IShare::TYPE_USER,
1893
+            IShare::TYPE_GROUP,
1894
+            IShare::TYPE_EMAIL,
1895
+            IShare::TYPE_CIRCLE,
1896
+            IShare::TYPE_ROOM,
1897
+            IShare::TYPE_DECK,
1898
+            IShare::TYPE_SCIENCEMESH
1899
+        ];
1900
+        $shareManager = Server::get(IManager::class);
1901
+        /** @var IShare[] $shares */
1902
+        $shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1903
+            return $shareManager->getSharesBy($user, $type);
1904
+        }, $providers));
1905
+
1906
+        foreach ($shares as $share) {
1907
+            $sharedPath = $share->getNode()->getPath();
1908
+            if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1909
+                $this->logger->debug(
1910
+                    'It is not allowed to move one mount point into a shared folder',
1911
+                    ['app' => 'files']);
1912
+                return false;
1913
+            }
1914
+        }
1915
+
1916
+        return true;
1917
+    }
1918
+
1919
+    /**
1920
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1921
+     */
1922
+    private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1923
+        $mount = $this->getMount($path);
1924
+        $storage = $mount->getStorage();
1925
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1926
+        $ownerId = $storage->getOwner($internalPath);
1927
+        if ($ownerId !== false) {
1928
+            $owner = Server::get(IUserManager::class)->get($ownerId);
1929
+        } else {
1930
+            $owner = null;
1931
+        }
1932
+        return new FileInfo(
1933
+            $this->getAbsolutePath($path),
1934
+            $storage,
1935
+            $internalPath,
1936
+            [
1937
+                'fileid' => null,
1938
+                'mimetype' => $storage->getMimeType($internalPath),
1939
+                'name' => basename($path),
1940
+                'etag' => null,
1941
+                'size' => $storage->filesize($internalPath),
1942
+                'mtime' => $storage->filemtime($internalPath),
1943
+                'encrypted' => false,
1944
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1945
+            ],
1946
+            $mount,
1947
+            $owner
1948
+        );
1949
+    }
1950
+
1951
+    /**
1952
+     * @param string $path
1953
+     * @param string $fileName
1954
+     * @param bool $readonly Check only if the path is allowed for read-only access
1955
+     * @throws InvalidPathException
1956
+     */
1957
+    public function verifyPath($path, $fileName, $readonly = false): void {
1958
+        // All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
1959
+        if (!Filesystem::isValidPath($path ?: '/')) {
1960
+            $l = \OCP\Util::getL10N('lib');
1961
+            throw new InvalidPathException($l->t('Path contains invalid segments'));
1962
+        }
1963
+
1964
+        // Short cut for read-only validation
1965
+        if ($readonly) {
1966
+            $validator = Server::get(FilenameValidator::class);
1967
+            if ($validator->isForbidden($fileName)) {
1968
+                $l = \OCP\Util::getL10N('lib');
1969
+                throw new InvalidPathException($l->t('Filename is a reserved word'));
1970
+            }
1971
+            return;
1972
+        }
1973
+
1974
+        try {
1975
+            /** @type \OCP\Files\Storage $storage */
1976
+            [$storage, $internalPath] = $this->resolvePath($path);
1977
+            $storage->verifyPath($internalPath, $fileName);
1978
+        } catch (ReservedWordException $ex) {
1979
+            $l = \OCP\Util::getL10N('lib');
1980
+            throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
1981
+        } catch (InvalidCharacterInPathException $ex) {
1982
+            $l = \OCP\Util::getL10N('lib');
1983
+            throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
1984
+        } catch (FileNameTooLongException $ex) {
1985
+            $l = \OCP\Util::getL10N('lib');
1986
+            throw new InvalidPathException($l->t('Filename is too long'));
1987
+        } catch (InvalidDirectoryException $ex) {
1988
+            $l = \OCP\Util::getL10N('lib');
1989
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1990
+        } catch (EmptyFileNameException $ex) {
1991
+            $l = \OCP\Util::getL10N('lib');
1992
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1993
+        }
1994
+    }
1995
+
1996
+    /**
1997
+     * get all parent folders of $path
1998
+     *
1999
+     * @param string $path
2000
+     * @return string[]
2001
+     */
2002
+    private function getParents($path) {
2003
+        $path = trim($path, '/');
2004
+        if (!$path) {
2005
+            return [];
2006
+        }
2007
+
2008
+        $parts = explode('/', $path);
2009
+
2010
+        // remove the single file
2011
+        array_pop($parts);
2012
+        $result = ['/'];
2013
+        $resultPath = '';
2014
+        foreach ($parts as $part) {
2015
+            if ($part) {
2016
+                $resultPath .= '/' . $part;
2017
+                $result[] = $resultPath;
2018
+            }
2019
+        }
2020
+        return $result;
2021
+    }
2022
+
2023
+    /**
2024
+     * Returns the mount point for which to lock
2025
+     *
2026
+     * @param string $absolutePath absolute path
2027
+     * @param bool $useParentMount true to return parent mount instead of whatever
2028
+     *                             is mounted directly on the given path, false otherwise
2029
+     * @return IMountPoint mount point for which to apply locks
2030
+     */
2031
+    private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
2032
+        $mount = Filesystem::getMountManager()->find($absolutePath);
2033
+
2034
+        if ($useParentMount) {
2035
+            // find out if something is mounted directly on the path
2036
+            $internalPath = $mount->getInternalPath($absolutePath);
2037
+            if ($internalPath === '') {
2038
+                // resolve the parent mount instead
2039
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
2040
+            }
2041
+        }
2042
+
2043
+        return $mount;
2044
+    }
2045
+
2046
+    /**
2047
+     * Lock the given path
2048
+     *
2049
+     * @param string $path the path of the file to lock, relative to the view
2050
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
+     *
2053
+     * @return bool False if the path is excluded from locking, true otherwise
2054
+     * @throws LockedException if the path is already locked
2055
+     */
2056
+    private function lockPath($path, $type, $lockMountPoint = false) {
2057
+        $absolutePath = $this->getAbsolutePath($path);
2058
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2059
+        if (!$this->shouldLockFile($absolutePath)) {
2060
+            return false;
2061
+        }
2062
+
2063
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2064
+        try {
2065
+            $storage = $mount->getStorage();
2066
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2067
+                $storage->acquireLock(
2068
+                    $mount->getInternalPath($absolutePath),
2069
+                    $type,
2070
+                    $this->lockingProvider
2071
+                );
2072
+            }
2073
+        } catch (LockedException $e) {
2074
+            // rethrow with the human-readable path
2075
+            throw new LockedException(
2076
+                $path,
2077
+                $e,
2078
+                $e->getExistingLock()
2079
+            );
2080
+        }
2081
+
2082
+        return true;
2083
+    }
2084
+
2085
+    /**
2086
+     * Change the lock type
2087
+     *
2088
+     * @param string $path the path of the file to lock, relative to the view
2089
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2090
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2091
+     *
2092
+     * @return bool False if the path is excluded from locking, true otherwise
2093
+     * @throws LockedException if the path is already locked
2094
+     */
2095
+    public function changeLock($path, $type, $lockMountPoint = false) {
2096
+        $path = Filesystem::normalizePath($path);
2097
+        $absolutePath = $this->getAbsolutePath($path);
2098
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2099
+        if (!$this->shouldLockFile($absolutePath)) {
2100
+            return false;
2101
+        }
2102
+
2103
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2104
+        try {
2105
+            $storage = $mount->getStorage();
2106
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2107
+                $storage->changeLock(
2108
+                    $mount->getInternalPath($absolutePath),
2109
+                    $type,
2110
+                    $this->lockingProvider
2111
+                );
2112
+            }
2113
+        } catch (LockedException $e) {
2114
+            // rethrow with the a human-readable path
2115
+            throw new LockedException(
2116
+                $path,
2117
+                $e,
2118
+                $e->getExistingLock()
2119
+            );
2120
+        }
2121
+
2122
+        return true;
2123
+    }
2124
+
2125
+    /**
2126
+     * Unlock the given path
2127
+     *
2128
+     * @param string $path the path of the file to unlock, relative to the view
2129
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2130
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2131
+     *
2132
+     * @return bool False if the path is excluded from locking, true otherwise
2133
+     * @throws LockedException
2134
+     */
2135
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2136
+        $absolutePath = $this->getAbsolutePath($path);
2137
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2138
+        if (!$this->shouldLockFile($absolutePath)) {
2139
+            return false;
2140
+        }
2141
+
2142
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2143
+        $storage = $mount->getStorage();
2144
+        if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2145
+            $storage->releaseLock(
2146
+                $mount->getInternalPath($absolutePath),
2147
+                $type,
2148
+                $this->lockingProvider
2149
+            );
2150
+        }
2151
+
2152
+        return true;
2153
+    }
2154
+
2155
+    /**
2156
+     * Lock a path and all its parents up to the root of the view
2157
+     *
2158
+     * @param string $path the path of the file to lock relative to the view
2159
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2160
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2161
+     *
2162
+     * @return bool False if the path is excluded from locking, true otherwise
2163
+     * @throws LockedException
2164
+     */
2165
+    public function lockFile($path, $type, $lockMountPoint = false) {
2166
+        $absolutePath = $this->getAbsolutePath($path);
2167
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2168
+        if (!$this->shouldLockFile($absolutePath)) {
2169
+            return false;
2170
+        }
2171
+
2172
+        $this->lockPath($path, $type, $lockMountPoint);
2173
+
2174
+        $parents = $this->getParents($path);
2175
+        foreach ($parents as $parent) {
2176
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2177
+        }
2178
+
2179
+        return true;
2180
+    }
2181
+
2182
+    /**
2183
+     * Unlock a path and all its parents up to the root of the view
2184
+     *
2185
+     * @param string $path the path of the file to lock relative to the view
2186
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2187
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2188
+     *
2189
+     * @return bool False if the path is excluded from locking, true otherwise
2190
+     * @throws LockedException
2191
+     */
2192
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2193
+        $absolutePath = $this->getAbsolutePath($path);
2194
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2195
+        if (!$this->shouldLockFile($absolutePath)) {
2196
+            return false;
2197
+        }
2198
+
2199
+        $this->unlockPath($path, $type, $lockMountPoint);
2200
+
2201
+        $parents = $this->getParents($path);
2202
+        foreach ($parents as $parent) {
2203
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2204
+        }
2205
+
2206
+        return true;
2207
+    }
2208
+
2209
+    /**
2210
+     * Only lock files in data/user/files/
2211
+     *
2212
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2213
+     * @return bool
2214
+     */
2215
+    protected function shouldLockFile($path) {
2216
+        $path = Filesystem::normalizePath($path);
2217
+
2218
+        $pathSegments = explode('/', $path);
2219
+        if (isset($pathSegments[2])) {
2220
+            // E.g.: /username/files/path-to-file
2221
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2222
+        }
2223
+
2224
+        return !str_starts_with($path, '/appdata_');
2225
+    }
2226
+
2227
+    /**
2228
+     * Shortens the given absolute path to be relative to
2229
+     * "$user/files".
2230
+     *
2231
+     * @param string $absolutePath absolute path which is under "files"
2232
+     *
2233
+     * @return string path relative to "files" with trimmed slashes or null
2234
+     *                if the path was NOT relative to files
2235
+     *
2236
+     * @throws \InvalidArgumentException if the given path was not under "files"
2237
+     * @since 8.1.0
2238
+     */
2239
+    public function getPathRelativeToFiles($absolutePath) {
2240
+        $path = Filesystem::normalizePath($absolutePath);
2241
+        $parts = explode('/', trim($path, '/'), 3);
2242
+        // "$user", "files", "path/to/dir"
2243
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2244
+            $this->logger->error(
2245
+                '$absolutePath must be relative to "files", value is "{absolutePath}"',
2246
+                [
2247
+                    'absolutePath' => $absolutePath,
2248
+                ]
2249
+            );
2250
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2251
+        }
2252
+        if (isset($parts[2])) {
2253
+            return $parts[2];
2254
+        }
2255
+        return '';
2256
+    }
2257
+
2258
+    /**
2259
+     * @param string $filename
2260
+     * @return array
2261
+     * @throws \OC\User\NoUserException
2262
+     * @throws NotFoundException
2263
+     */
2264
+    public function getUidAndFilename($filename) {
2265
+        $info = $this->getFileInfo($filename);
2266
+        if (!$info instanceof \OCP\Files\FileInfo) {
2267
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2268
+        }
2269
+        $uid = $info->getOwner()->getUID();
2270
+        if ($uid != \OC_User::getUser()) {
2271
+            Filesystem::initMountPoints($uid);
2272
+            $ownerView = new View('/' . $uid . '/files');
2273
+            try {
2274
+                $filename = $ownerView->getPath($info['fileid']);
2275
+            } catch (NotFoundException $e) {
2276
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2277
+            }
2278
+        }
2279
+        return [$uid, $filename];
2280
+    }
2281
+
2282
+    /**
2283
+     * Creates parent non-existing folders
2284
+     *
2285
+     * @param string $filePath
2286
+     * @return bool
2287
+     */
2288
+    private function createParentDirectories($filePath) {
2289
+        $directoryParts = explode('/', $filePath);
2290
+        $directoryParts = array_filter($directoryParts);
2291
+        foreach ($directoryParts as $key => $part) {
2292
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2293
+            $currentPath = '/' . implode('/', $currentPathElements);
2294
+            if ($this->is_file($currentPath)) {
2295
+                return false;
2296
+            }
2297
+            if (!$this->file_exists($currentPath)) {
2298
+                $this->mkdir($currentPath);
2299
+            }
2300
+        }
2301
+
2302
+        return true;
2303
+    }
2304 2304
 }
Please login to merge, or discard this patch.
lib/private/legacy/OC_Helper.php 2 patches
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -32,391 +32,391 @@
 block discarded – undo
32 32
  * }
33 33
  */
34 34
 class OC_Helper {
35
-	private static $templateManager;
36
-	private static ?ICacheFactory $cacheFactory = null;
37
-	private static ?bool $quotaIncludeExternalStorage = null;
38
-
39
-	/**
40
-	 * Recursive copying of folders
41
-	 * @param string $src source folder
42
-	 * @param string $dest target folder
43
-	 * @return void
44
-	 * @deprecated 32.0.0 - use \OCP\Files\Folder::copy
45
-	 */
46
-	public static function copyr($src, $dest) {
47
-		if (!file_exists($src)) {
48
-			return;
49
-		}
50
-
51
-		if (is_dir($src)) {
52
-			if (!is_dir($dest)) {
53
-				mkdir($dest);
54
-			}
55
-			$files = scandir($src);
56
-			foreach ($files as $file) {
57
-				if ($file != '.' && $file != '..') {
58
-					self::copyr("$src/$file", "$dest/$file");
59
-				}
60
-			}
61
-		} else {
62
-			$validator = \OCP\Server::get(FilenameValidator::class);
63
-			if (!$validator->isForbidden($src)) {
64
-				copy($src, $dest);
65
-			}
66
-		}
67
-	}
68
-
69
-	/**
70
-	 * @deprecated 18.0.0
71
-	 * @return \OC\Files\Type\TemplateManager
72
-	 */
73
-	public static function getFileTemplateManager() {
74
-		if (!self::$templateManager) {
75
-			self::$templateManager = new \OC\Files\Type\TemplateManager();
76
-		}
77
-		return self::$templateManager;
78
-	}
79
-
80
-	/**
81
-	 * detect if a given program is found in the search PATH
82
-	 *
83
-	 * @param string $name
84
-	 * @param bool $path
85
-	 * @internal param string $program name
86
-	 * @internal param string $optional search path, defaults to $PATH
87
-	 * @return bool true if executable program found in path
88
-	 * @deprecated 32.0.0 use the \OCP\IBinaryFinder
89
-	 */
90
-	public static function canExecute($name, $path = false) {
91
-		// path defaults to PATH from environment if not set
92
-		if ($path === false) {
93
-			$path = getenv('PATH');
94
-		}
95
-		// we look for an executable file of that name
96
-		$exts = [''];
97
-		$check_fn = 'is_executable';
98
-		// Default check will be done with $path directories :
99
-		$dirs = explode(PATH_SEPARATOR, (string)$path);
100
-		// WARNING : We have to check if open_basedir is enabled :
101
-		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
102
-		if ($obd != 'none') {
103
-			$obd_values = explode(PATH_SEPARATOR, $obd);
104
-			if (count($obd_values) > 0 and $obd_values[0]) {
105
-				// open_basedir is in effect !
106
-				// We need to check if the program is in one of these dirs :
107
-				$dirs = $obd_values;
108
-			}
109
-		}
110
-		foreach ($dirs as $dir) {
111
-			foreach ($exts as $ext) {
112
-				if ($check_fn("$dir/$name" . $ext)) {
113
-					return true;
114
-				}
115
-			}
116
-		}
117
-		return false;
118
-	}
119
-
120
-	/**
121
-	 * copy the contents of one stream to another
122
-	 *
123
-	 * @param resource $source
124
-	 * @param resource $target
125
-	 * @return array the number of bytes copied and result
126
-	 * @deprecated 5.0.0 - Use \OCP\Files::streamCopy
127
-	 */
128
-	public static function streamCopy($source, $target) {
129
-		return \OCP\Files::streamCopy($source, $target, true);
130
-	}
131
-
132
-	/**
133
-	 * Adds a suffix to the name in case the file exists
134
-	 *
135
-	 * @param string $path
136
-	 * @param string $filename
137
-	 * @return string
138
-	 */
139
-	public static function buildNotExistingFileName($path, $filename) {
140
-		$view = \OC\Files\Filesystem::getView();
141
-		return self::buildNotExistingFileNameForView($path, $filename, $view);
142
-	}
143
-
144
-	/**
145
-	 * Adds a suffix to the name in case the file exists
146
-	 *
147
-	 * @param string $path
148
-	 * @param string $filename
149
-	 * @return string
150
-	 */
151
-	public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
152
-		if ($path === '/') {
153
-			$path = '';
154
-		}
155
-		if ($pos = strrpos($filename, '.')) {
156
-			$name = substr($filename, 0, $pos);
157
-			$ext = substr($filename, $pos);
158
-		} else {
159
-			$name = $filename;
160
-			$ext = '';
161
-		}
162
-
163
-		$newpath = $path . '/' . $filename;
164
-		if ($view->file_exists($newpath)) {
165
-			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
166
-				//Replace the last "(number)" with "(number+1)"
167
-				$last_match = count($matches[0]) - 1;
168
-				$counter = $matches[1][$last_match][0] + 1;
169
-				$offset = $matches[0][$last_match][1];
170
-				$match_length = strlen($matches[0][$last_match][0]);
171
-			} else {
172
-				$counter = 2;
173
-				$match_length = 0;
174
-				$offset = false;
175
-			}
176
-			do {
177
-				if ($offset) {
178
-					//Replace the last "(number)" with "(number+1)"
179
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
180
-				} else {
181
-					$newname = $name . ' (' . $counter . ')';
182
-				}
183
-				$newpath = $path . '/' . $newname . $ext;
184
-				$counter++;
185
-			} while ($view->file_exists($newpath));
186
-		}
187
-
188
-		return $newpath;
189
-	}
190
-
191
-	/**
192
-	 * Checks if a function is available
193
-	 *
194
-	 * @deprecated 25.0.0 use \OCP\Util::isFunctionEnabled instead
195
-	 */
196
-	public static function is_function_enabled(string $function_name): bool {
197
-		return Util::isFunctionEnabled($function_name);
198
-	}
199
-
200
-	/**
201
-	 * Try to find a program
202
-	 * @deprecated 25.0.0 Use \OC\BinaryFinder directly
203
-	 */
204
-	public static function findBinaryPath(string $program): ?string {
205
-		$result = Server::get(IBinaryFinder::class)->findBinaryPath($program);
206
-		return $result !== false ? $result : null;
207
-	}
208
-
209
-	/**
210
-	 * Calculate the disc space for the given path
211
-	 *
212
-	 * BEWARE: this requires that Util::setupFS() was called
213
-	 * already !
214
-	 *
215
-	 * @param string $path
216
-	 * @param \OCP\Files\FileInfo $rootInfo (optional)
217
-	 * @param bool $includeMountPoints whether to include mount points in the size calculation
218
-	 * @param bool $useCache whether to use the cached quota values
219
-	 * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
220
-	 * @return StorageInfo
221
-	 * @throws \OCP\Files\NotFoundException
222
-	 */
223
-	public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
224
-		if (!self::$cacheFactory) {
225
-			self::$cacheFactory = Server::get(ICacheFactory::class);
226
-		}
227
-		$memcache = self::$cacheFactory->createLocal('storage_info');
228
-
229
-		// return storage info without adding mount points
230
-		if (self::$quotaIncludeExternalStorage === null) {
231
-			self::$quotaIncludeExternalStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
232
-		}
233
-
234
-		$view = Filesystem::getView();
235
-		if (!$view) {
236
-			throw new \OCP\Files\NotFoundException();
237
-		}
238
-		$fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
239
-
240
-		$cacheKey = $fullPath . '::' . ($includeMountPoints ? 'include' : 'exclude');
241
-		if ($useCache) {
242
-			$cached = $memcache->get($cacheKey);
243
-			if ($cached) {
244
-				return $cached;
245
-			}
246
-		}
247
-
248
-		if (!$rootInfo) {
249
-			$rootInfo = \OC\Files\Filesystem::getFileInfo($path, self::$quotaIncludeExternalStorage ? 'ext' : false);
250
-		}
251
-		if (!$rootInfo instanceof \OCP\Files\FileInfo) {
252
-			throw new \OCP\Files\NotFoundException('The root directory of the user\'s files is missing');
253
-		}
254
-		$used = $rootInfo->getSize($includeMountPoints);
255
-		if ($used < 0) {
256
-			$used = 0.0;
257
-		}
258
-		/** @var int|float $quota */
259
-		$quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
260
-		$mount = $rootInfo->getMountPoint();
261
-		$storage = $mount->getStorage();
262
-		$sourceStorage = $storage;
263
-		if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
264
-			self::$quotaIncludeExternalStorage = false;
265
-		}
266
-		if (self::$quotaIncludeExternalStorage) {
267
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
268
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
269
-			) {
270
-				/** @var \OC\Files\Storage\Home $storage */
271
-				$user = $storage->getUser();
272
-			} else {
273
-				$user = \OC::$server->getUserSession()->getUser();
274
-			}
275
-			$quota = OC_Util::getUserQuota($user);
276
-			if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
277
-				// always get free space / total space from root + mount points
278
-				return self::getGlobalStorageInfo($quota, $user, $mount);
279
-			}
280
-		}
281
-
282
-		// TODO: need a better way to get total space from storage
283
-		if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
284
-			/** @var \OC\Files\Storage\Wrapper\Quota $storage */
285
-			$quota = $sourceStorage->getQuota();
286
-		}
287
-		try {
288
-			$free = $sourceStorage->free_space($rootInfo->getInternalPath());
289
-			if (is_bool($free)) {
290
-				$free = 0.0;
291
-			}
292
-		} catch (\Exception $e) {
293
-			if ($path === '') {
294
-				throw $e;
295
-			}
296
-			/** @var LoggerInterface $logger */
297
-			$logger = \OC::$server->get(LoggerInterface::class);
298
-			$logger->warning('Error while getting quota info, using root quota', ['exception' => $e]);
299
-			$rootInfo = self::getStorageInfo('');
300
-			$memcache->set($cacheKey, $rootInfo, 5 * 60);
301
-			return $rootInfo;
302
-		}
303
-		if ($free >= 0) {
304
-			$total = $free + $used;
305
-		} else {
306
-			$total = $free; //either unknown or unlimited
307
-		}
308
-		if ($total > 0) {
309
-			if ($quota > 0 && $total > $quota) {
310
-				$total = $quota;
311
-			}
312
-			// prevent division by zero or error codes (negative values)
313
-			$relative = round(($used / $total) * 10000) / 100;
314
-		} else {
315
-			$relative = 0;
316
-		}
317
-
318
-		/*
35
+    private static $templateManager;
36
+    private static ?ICacheFactory $cacheFactory = null;
37
+    private static ?bool $quotaIncludeExternalStorage = null;
38
+
39
+    /**
40
+     * Recursive copying of folders
41
+     * @param string $src source folder
42
+     * @param string $dest target folder
43
+     * @return void
44
+     * @deprecated 32.0.0 - use \OCP\Files\Folder::copy
45
+     */
46
+    public static function copyr($src, $dest) {
47
+        if (!file_exists($src)) {
48
+            return;
49
+        }
50
+
51
+        if (is_dir($src)) {
52
+            if (!is_dir($dest)) {
53
+                mkdir($dest);
54
+            }
55
+            $files = scandir($src);
56
+            foreach ($files as $file) {
57
+                if ($file != '.' && $file != '..') {
58
+                    self::copyr("$src/$file", "$dest/$file");
59
+                }
60
+            }
61
+        } else {
62
+            $validator = \OCP\Server::get(FilenameValidator::class);
63
+            if (!$validator->isForbidden($src)) {
64
+                copy($src, $dest);
65
+            }
66
+        }
67
+    }
68
+
69
+    /**
70
+     * @deprecated 18.0.0
71
+     * @return \OC\Files\Type\TemplateManager
72
+     */
73
+    public static function getFileTemplateManager() {
74
+        if (!self::$templateManager) {
75
+            self::$templateManager = new \OC\Files\Type\TemplateManager();
76
+        }
77
+        return self::$templateManager;
78
+    }
79
+
80
+    /**
81
+     * detect if a given program is found in the search PATH
82
+     *
83
+     * @param string $name
84
+     * @param bool $path
85
+     * @internal param string $program name
86
+     * @internal param string $optional search path, defaults to $PATH
87
+     * @return bool true if executable program found in path
88
+     * @deprecated 32.0.0 use the \OCP\IBinaryFinder
89
+     */
90
+    public static function canExecute($name, $path = false) {
91
+        // path defaults to PATH from environment if not set
92
+        if ($path === false) {
93
+            $path = getenv('PATH');
94
+        }
95
+        // we look for an executable file of that name
96
+        $exts = [''];
97
+        $check_fn = 'is_executable';
98
+        // Default check will be done with $path directories :
99
+        $dirs = explode(PATH_SEPARATOR, (string)$path);
100
+        // WARNING : We have to check if open_basedir is enabled :
101
+        $obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
102
+        if ($obd != 'none') {
103
+            $obd_values = explode(PATH_SEPARATOR, $obd);
104
+            if (count($obd_values) > 0 and $obd_values[0]) {
105
+                // open_basedir is in effect !
106
+                // We need to check if the program is in one of these dirs :
107
+                $dirs = $obd_values;
108
+            }
109
+        }
110
+        foreach ($dirs as $dir) {
111
+            foreach ($exts as $ext) {
112
+                if ($check_fn("$dir/$name" . $ext)) {
113
+                    return true;
114
+                }
115
+            }
116
+        }
117
+        return false;
118
+    }
119
+
120
+    /**
121
+     * copy the contents of one stream to another
122
+     *
123
+     * @param resource $source
124
+     * @param resource $target
125
+     * @return array the number of bytes copied and result
126
+     * @deprecated 5.0.0 - Use \OCP\Files::streamCopy
127
+     */
128
+    public static function streamCopy($source, $target) {
129
+        return \OCP\Files::streamCopy($source, $target, true);
130
+    }
131
+
132
+    /**
133
+     * Adds a suffix to the name in case the file exists
134
+     *
135
+     * @param string $path
136
+     * @param string $filename
137
+     * @return string
138
+     */
139
+    public static function buildNotExistingFileName($path, $filename) {
140
+        $view = \OC\Files\Filesystem::getView();
141
+        return self::buildNotExistingFileNameForView($path, $filename, $view);
142
+    }
143
+
144
+    /**
145
+     * Adds a suffix to the name in case the file exists
146
+     *
147
+     * @param string $path
148
+     * @param string $filename
149
+     * @return string
150
+     */
151
+    public static function buildNotExistingFileNameForView($path, $filename, \OC\Files\View $view) {
152
+        if ($path === '/') {
153
+            $path = '';
154
+        }
155
+        if ($pos = strrpos($filename, '.')) {
156
+            $name = substr($filename, 0, $pos);
157
+            $ext = substr($filename, $pos);
158
+        } else {
159
+            $name = $filename;
160
+            $ext = '';
161
+        }
162
+
163
+        $newpath = $path . '/' . $filename;
164
+        if ($view->file_exists($newpath)) {
165
+            if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
166
+                //Replace the last "(number)" with "(number+1)"
167
+                $last_match = count($matches[0]) - 1;
168
+                $counter = $matches[1][$last_match][0] + 1;
169
+                $offset = $matches[0][$last_match][1];
170
+                $match_length = strlen($matches[0][$last_match][0]);
171
+            } else {
172
+                $counter = 2;
173
+                $match_length = 0;
174
+                $offset = false;
175
+            }
176
+            do {
177
+                if ($offset) {
178
+                    //Replace the last "(number)" with "(number+1)"
179
+                    $newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
180
+                } else {
181
+                    $newname = $name . ' (' . $counter . ')';
182
+                }
183
+                $newpath = $path . '/' . $newname . $ext;
184
+                $counter++;
185
+            } while ($view->file_exists($newpath));
186
+        }
187
+
188
+        return $newpath;
189
+    }
190
+
191
+    /**
192
+     * Checks if a function is available
193
+     *
194
+     * @deprecated 25.0.0 use \OCP\Util::isFunctionEnabled instead
195
+     */
196
+    public static function is_function_enabled(string $function_name): bool {
197
+        return Util::isFunctionEnabled($function_name);
198
+    }
199
+
200
+    /**
201
+     * Try to find a program
202
+     * @deprecated 25.0.0 Use \OC\BinaryFinder directly
203
+     */
204
+    public static function findBinaryPath(string $program): ?string {
205
+        $result = Server::get(IBinaryFinder::class)->findBinaryPath($program);
206
+        return $result !== false ? $result : null;
207
+    }
208
+
209
+    /**
210
+     * Calculate the disc space for the given path
211
+     *
212
+     * BEWARE: this requires that Util::setupFS() was called
213
+     * already !
214
+     *
215
+     * @param string $path
216
+     * @param \OCP\Files\FileInfo $rootInfo (optional)
217
+     * @param bool $includeMountPoints whether to include mount points in the size calculation
218
+     * @param bool $useCache whether to use the cached quota values
219
+     * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
220
+     * @return StorageInfo
221
+     * @throws \OCP\Files\NotFoundException
222
+     */
223
+    public static function getStorageInfo($path, $rootInfo = null, $includeMountPoints = true, $useCache = true) {
224
+        if (!self::$cacheFactory) {
225
+            self::$cacheFactory = Server::get(ICacheFactory::class);
226
+        }
227
+        $memcache = self::$cacheFactory->createLocal('storage_info');
228
+
229
+        // return storage info without adding mount points
230
+        if (self::$quotaIncludeExternalStorage === null) {
231
+            self::$quotaIncludeExternalStorage = \OC::$server->getSystemConfig()->getValue('quota_include_external_storage', false);
232
+        }
233
+
234
+        $view = Filesystem::getView();
235
+        if (!$view) {
236
+            throw new \OCP\Files\NotFoundException();
237
+        }
238
+        $fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
239
+
240
+        $cacheKey = $fullPath . '::' . ($includeMountPoints ? 'include' : 'exclude');
241
+        if ($useCache) {
242
+            $cached = $memcache->get($cacheKey);
243
+            if ($cached) {
244
+                return $cached;
245
+            }
246
+        }
247
+
248
+        if (!$rootInfo) {
249
+            $rootInfo = \OC\Files\Filesystem::getFileInfo($path, self::$quotaIncludeExternalStorage ? 'ext' : false);
250
+        }
251
+        if (!$rootInfo instanceof \OCP\Files\FileInfo) {
252
+            throw new \OCP\Files\NotFoundException('The root directory of the user\'s files is missing');
253
+        }
254
+        $used = $rootInfo->getSize($includeMountPoints);
255
+        if ($used < 0) {
256
+            $used = 0.0;
257
+        }
258
+        /** @var int|float $quota */
259
+        $quota = \OCP\Files\FileInfo::SPACE_UNLIMITED;
260
+        $mount = $rootInfo->getMountPoint();
261
+        $storage = $mount->getStorage();
262
+        $sourceStorage = $storage;
263
+        if ($storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) {
264
+            self::$quotaIncludeExternalStorage = false;
265
+        }
266
+        if (self::$quotaIncludeExternalStorage) {
267
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
268
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
269
+            ) {
270
+                /** @var \OC\Files\Storage\Home $storage */
271
+                $user = $storage->getUser();
272
+            } else {
273
+                $user = \OC::$server->getUserSession()->getUser();
274
+            }
275
+            $quota = OC_Util::getUserQuota($user);
276
+            if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
277
+                // always get free space / total space from root + mount points
278
+                return self::getGlobalStorageInfo($quota, $user, $mount);
279
+            }
280
+        }
281
+
282
+        // TODO: need a better way to get total space from storage
283
+        if ($sourceStorage->instanceOfStorage('\OC\Files\Storage\Wrapper\Quota')) {
284
+            /** @var \OC\Files\Storage\Wrapper\Quota $storage */
285
+            $quota = $sourceStorage->getQuota();
286
+        }
287
+        try {
288
+            $free = $sourceStorage->free_space($rootInfo->getInternalPath());
289
+            if (is_bool($free)) {
290
+                $free = 0.0;
291
+            }
292
+        } catch (\Exception $e) {
293
+            if ($path === '') {
294
+                throw $e;
295
+            }
296
+            /** @var LoggerInterface $logger */
297
+            $logger = \OC::$server->get(LoggerInterface::class);
298
+            $logger->warning('Error while getting quota info, using root quota', ['exception' => $e]);
299
+            $rootInfo = self::getStorageInfo('');
300
+            $memcache->set($cacheKey, $rootInfo, 5 * 60);
301
+            return $rootInfo;
302
+        }
303
+        if ($free >= 0) {
304
+            $total = $free + $used;
305
+        } else {
306
+            $total = $free; //either unknown or unlimited
307
+        }
308
+        if ($total > 0) {
309
+            if ($quota > 0 && $total > $quota) {
310
+                $total = $quota;
311
+            }
312
+            // prevent division by zero or error codes (negative values)
313
+            $relative = round(($used / $total) * 10000) / 100;
314
+        } else {
315
+            $relative = 0;
316
+        }
317
+
318
+        /*
319 319
 		 * \OCA\Files_Sharing\External\Storage returns the cloud ID as the owner for the storage.
320 320
 		 * It is unnecessary to query the user manager for the display name, as it won't have this information.
321 321
 		 */
322
-		$isRemoteShare = $storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class);
323
-
324
-		$ownerId = $storage->getOwner($path);
325
-		$ownerDisplayName = '';
326
-
327
-		if ($isRemoteShare === false && $ownerId !== false) {
328
-			$ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
329
-		}
330
-
331
-		if (substr_count($mount->getMountPoint(), '/') < 3) {
332
-			$mountPoint = '';
333
-		} else {
334
-			[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
335
-		}
336
-
337
-		$info = [
338
-			'free' => $free,
339
-			'used' => $used,
340
-			'quota' => $quota,
341
-			'total' => $total,
342
-			'relative' => $relative,
343
-			'owner' => $ownerId,
344
-			'ownerDisplayName' => $ownerDisplayName,
345
-			'mountType' => $mount->getMountType(),
346
-			'mountPoint' => trim($mountPoint, '/'),
347
-		];
348
-
349
-		if ($isRemoteShare === false && $ownerId !== false && $path === '/') {
350
-			// If path is root, store this as last known quota usage for this user
351
-			\OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative);
352
-		}
353
-
354
-		$memcache->set($cacheKey, $info, 5 * 60);
355
-
356
-		return $info;
357
-	}
358
-
359
-	/**
360
-	 * Get storage info including all mount points and quota
361
-	 *
362
-	 * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
363
-	 * @return StorageInfo
364
-	 */
365
-	private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
366
-		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
367
-		/** @var int|float $used */
368
-		$used = $rootInfo['size'];
369
-		if ($used < 0) {
370
-			$used = 0.0;
371
-		}
372
-
373
-		$total = $quota;
374
-		/** @var int|float $free */
375
-		$free = $quota - $used;
376
-
377
-		if ($total > 0) {
378
-			if ($quota > 0 && $total > $quota) {
379
-				$total = $quota;
380
-			}
381
-			// prevent division by zero or error codes (negative values)
382
-			$relative = round(($used / $total) * 10000) / 100;
383
-		} else {
384
-			$relative = 0.0;
385
-		}
386
-
387
-		if (substr_count($mount->getMountPoint(), '/') < 3) {
388
-			$mountPoint = '';
389
-		} else {
390
-			[,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
391
-		}
392
-
393
-		return [
394
-			'free' => $free,
395
-			'used' => $used,
396
-			'total' => $total,
397
-			'relative' => $relative,
398
-			'quota' => $quota,
399
-			'owner' => $user->getUID(),
400
-			'ownerDisplayName' => $user->getDisplayName(),
401
-			'mountType' => $mount->getMountType(),
402
-			'mountPoint' => trim($mountPoint, '/'),
403
-		];
404
-	}
405
-
406
-	public static function clearStorageInfo(string $absolutePath): void {
407
-		/** @var ICacheFactory $cacheFactory */
408
-		$cacheFactory = \OC::$server->get(ICacheFactory::class);
409
-		$memcache = $cacheFactory->createLocal('storage_info');
410
-		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
411
-		$memcache->remove($cacheKeyPrefix . 'include');
412
-		$memcache->remove($cacheKeyPrefix . 'exclude');
413
-	}
414
-
415
-	/**
416
-	 * Returns whether the config file is set manually to read-only
417
-	 * @return bool
418
-	 */
419
-	public static function isReadOnlyConfigEnabled() {
420
-		return \OC::$server->getConfig()->getSystemValueBool('config_is_read_only', false);
421
-	}
322
+        $isRemoteShare = $storage->instanceOfStorage(\OCA\Files_Sharing\External\Storage::class);
323
+
324
+        $ownerId = $storage->getOwner($path);
325
+        $ownerDisplayName = '';
326
+
327
+        if ($isRemoteShare === false && $ownerId !== false) {
328
+            $ownerDisplayName = \OC::$server->getUserManager()->getDisplayName($ownerId) ?? '';
329
+        }
330
+
331
+        if (substr_count($mount->getMountPoint(), '/') < 3) {
332
+            $mountPoint = '';
333
+        } else {
334
+            [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
335
+        }
336
+
337
+        $info = [
338
+            'free' => $free,
339
+            'used' => $used,
340
+            'quota' => $quota,
341
+            'total' => $total,
342
+            'relative' => $relative,
343
+            'owner' => $ownerId,
344
+            'ownerDisplayName' => $ownerDisplayName,
345
+            'mountType' => $mount->getMountType(),
346
+            'mountPoint' => trim($mountPoint, '/'),
347
+        ];
348
+
349
+        if ($isRemoteShare === false && $ownerId !== false && $path === '/') {
350
+            // If path is root, store this as last known quota usage for this user
351
+            \OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative);
352
+        }
353
+
354
+        $memcache->set($cacheKey, $info, 5 * 60);
355
+
356
+        return $info;
357
+    }
358
+
359
+    /**
360
+     * Get storage info including all mount points and quota
361
+     *
362
+     * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
363
+     * @return StorageInfo
364
+     */
365
+    private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
366
+        $rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
367
+        /** @var int|float $used */
368
+        $used = $rootInfo['size'];
369
+        if ($used < 0) {
370
+            $used = 0.0;
371
+        }
372
+
373
+        $total = $quota;
374
+        /** @var int|float $free */
375
+        $free = $quota - $used;
376
+
377
+        if ($total > 0) {
378
+            if ($quota > 0 && $total > $quota) {
379
+                $total = $quota;
380
+            }
381
+            // prevent division by zero or error codes (negative values)
382
+            $relative = round(($used / $total) * 10000) / 100;
383
+        } else {
384
+            $relative = 0.0;
385
+        }
386
+
387
+        if (substr_count($mount->getMountPoint(), '/') < 3) {
388
+            $mountPoint = '';
389
+        } else {
390
+            [,,,$mountPoint] = explode('/', $mount->getMountPoint(), 4);
391
+        }
392
+
393
+        return [
394
+            'free' => $free,
395
+            'used' => $used,
396
+            'total' => $total,
397
+            'relative' => $relative,
398
+            'quota' => $quota,
399
+            'owner' => $user->getUID(),
400
+            'ownerDisplayName' => $user->getDisplayName(),
401
+            'mountType' => $mount->getMountType(),
402
+            'mountPoint' => trim($mountPoint, '/'),
403
+        ];
404
+    }
405
+
406
+    public static function clearStorageInfo(string $absolutePath): void {
407
+        /** @var ICacheFactory $cacheFactory */
408
+        $cacheFactory = \OC::$server->get(ICacheFactory::class);
409
+        $memcache = $cacheFactory->createLocal('storage_info');
410
+        $cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
411
+        $memcache->remove($cacheKeyPrefix . 'include');
412
+        $memcache->remove($cacheKeyPrefix . 'exclude');
413
+    }
414
+
415
+    /**
416
+     * Returns whether the config file is set manually to read-only
417
+     * @return bool
418
+     */
419
+    public static function isReadOnlyConfigEnabled() {
420
+        return \OC::$server->getConfig()->getSystemValueBool('config_is_read_only', false);
421
+    }
422 422
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 		$exts = [''];
97 97
 		$check_fn = 'is_executable';
98 98
 		// Default check will be done with $path directories :
99
-		$dirs = explode(PATH_SEPARATOR, (string)$path);
99
+		$dirs = explode(PATH_SEPARATOR, (string) $path);
100 100
 		// WARNING : We have to check if open_basedir is enabled :
101 101
 		$obd = OC::$server->get(IniGetWrapper::class)->getString('open_basedir');
102 102
 		if ($obd != 'none') {
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		}
110 110
 		foreach ($dirs as $dir) {
111 111
 			foreach ($exts as $ext) {
112
-				if ($check_fn("$dir/$name" . $ext)) {
112
+				if ($check_fn("$dir/$name".$ext)) {
113 113
 					return true;
114 114
 				}
115 115
 			}
@@ -160,7 +160,7 @@  discard block
 block discarded – undo
160 160
 			$ext = '';
161 161
 		}
162 162
 
163
-		$newpath = $path . '/' . $filename;
163
+		$newpath = $path.'/'.$filename;
164 164
 		if ($view->file_exists($newpath)) {
165 165
 			if (preg_match_all('/\((\d+)\)/', $name, $matches, PREG_OFFSET_CAPTURE)) {
166 166
 				//Replace the last "(number)" with "(number+1)"
@@ -176,11 +176,11 @@  discard block
 block discarded – undo
176 176
 			do {
177 177
 				if ($offset) {
178 178
 					//Replace the last "(number)" with "(number+1)"
179
-					$newname = substr_replace($name, '(' . $counter . ')', $offset, $match_length);
179
+					$newname = substr_replace($name, '('.$counter.')', $offset, $match_length);
180 180
 				} else {
181
-					$newname = $name . ' (' . $counter . ')';
181
+					$newname = $name.' ('.$counter.')';
182 182
 				}
183
-				$newpath = $path . '/' . $newname . $ext;
183
+				$newpath = $path.'/'.$newname.$ext;
184 184
 				$counter++;
185 185
 			} while ($view->file_exists($newpath));
186 186
 		}
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 		}
238 238
 		$fullPath = Filesystem::normalizePath($view->getAbsolutePath($path));
239 239
 
240
-		$cacheKey = $fullPath . '::' . ($includeMountPoints ? 'include' : 'exclude');
240
+		$cacheKey = $fullPath.'::'.($includeMountPoints ? 'include' : 'exclude');
241 241
 		if ($useCache) {
242 242
 			$cached = $memcache->get($cacheKey);
243 243
 			if ($cached) {
@@ -348,7 +348,7 @@  discard block
 block discarded – undo
348 348
 
349 349
 		if ($isRemoteShare === false && $ownerId !== false && $path === '/') {
350 350
 			// If path is root, store this as last known quota usage for this user
351
-			\OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string)$relative);
351
+			\OCP\Server::get(\OCP\IConfig::class)->setUserValue($ownerId, 'files', 'lastSeenQuotaUsage', (string) $relative);
352 352
 		}
353 353
 
354 354
 		$memcache->set($cacheKey, $info, 5 * 60);
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 	 * @psalm-suppress LessSpecificReturnStatement Legacy code outputs weird types - manually validated that they are correct
363 363
 	 * @return StorageInfo
364 364
 	 */
365
-	private static function getGlobalStorageInfo(int|float $quota, IUser $user, IMountPoint $mount): array {
365
+	private static function getGlobalStorageInfo(int | float $quota, IUser $user, IMountPoint $mount): array {
366 366
 		$rootInfo = \OC\Files\Filesystem::getFileInfo('', 'ext');
367 367
 		/** @var int|float $used */
368 368
 		$used = $rootInfo['size'];
@@ -407,9 +407,9 @@  discard block
 block discarded – undo
407 407
 		/** @var ICacheFactory $cacheFactory */
408 408
 		$cacheFactory = \OC::$server->get(ICacheFactory::class);
409 409
 		$memcache = $cacheFactory->createLocal('storage_info');
410
-		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath) . '::';
411
-		$memcache->remove($cacheKeyPrefix . 'include');
412
-		$memcache->remove($cacheKeyPrefix . 'exclude');
410
+		$cacheKeyPrefix = Filesystem::normalizePath($absolutePath).'::';
411
+		$memcache->remove($cacheKeyPrefix.'include');
412
+		$memcache->remove($cacheKeyPrefix.'exclude');
413 413
 	}
414 414
 
415 415
 	/**
Please login to merge, or discard this patch.
apps/files_versions/lib/Storage.php 1 patch
Indentation   +951 added lines, -951 removed lines patch added patch discarded remove patch
@@ -45,955 +45,955 @@
 block discarded – undo
45 45
 use Psr\Log\LoggerInterface;
46 46
 
47 47
 class Storage {
48
-	public const DEFAULTENABLED = true;
49
-	public const DEFAULTMAXSIZE = 50; // unit: percentage; 50% of available disk space/quota
50
-	public const VERSIONS_ROOT = 'files_versions/';
51
-
52
-	public const DELETE_TRIGGER_MASTER_REMOVED = 0;
53
-	public const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
54
-	public const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
55
-
56
-	// files for which we can remove the versions after the delete operation was successful
57
-	private static $deletedFiles = [];
58
-
59
-	private static $sourcePathAndUser = [];
60
-
61
-	private static $max_versions_per_interval = [
62
-		//first 10sec, one version every 2sec
63
-		1 => ['intervalEndsAfter' => 10,      'step' => 2],
64
-		//next minute, one version every 10sec
65
-		2 => ['intervalEndsAfter' => 60,      'step' => 10],
66
-		//next hour, one version every minute
67
-		3 => ['intervalEndsAfter' => 3600,    'step' => 60],
68
-		//next 24h, one version every hour
69
-		4 => ['intervalEndsAfter' => 86400,   'step' => 3600],
70
-		//next 30days, one version per day
71
-		5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
72
-		//until the end one version per week
73
-		6 => ['intervalEndsAfter' => -1,      'step' => 604800],
74
-	];
75
-
76
-	/** @var Application */
77
-	private static $application;
78
-
79
-	/**
80
-	 * get the UID of the owner of the file and the path to the file relative to
81
-	 * owners files folder
82
-	 *
83
-	 * @param string $filename
84
-	 * @return array
85
-	 * @throws NoUserException
86
-	 */
87
-	public static function getUidAndFilename($filename) {
88
-		$uid = Filesystem::getOwner($filename);
89
-		$userManager = Server::get(IUserManager::class);
90
-		// if the user with the UID doesn't exists, e.g. because the UID points
91
-		// to a remote user with a federated cloud ID we use the current logged-in
92
-		// user. We need a valid local user to create the versions
93
-		if (!$userManager->userExists($uid)) {
94
-			$uid = OC_User::getUser();
95
-		}
96
-		Filesystem::initMountPoints($uid);
97
-		if ($uid !== OC_User::getUser()) {
98
-			$info = Filesystem::getFileInfo($filename);
99
-			$ownerView = new View('/' . $uid . '/files');
100
-			try {
101
-				$filename = $ownerView->getPath($info['fileid']);
102
-				// make sure that the file name doesn't end with a trailing slash
103
-				// can for example happen single files shared across servers
104
-				$filename = rtrim($filename, '/');
105
-			} catch (NotFoundException $e) {
106
-				$filename = null;
107
-			}
108
-		}
109
-		return [$uid, $filename];
110
-	}
111
-
112
-	/**
113
-	 * Remember the owner and the owner path of the source file
114
-	 *
115
-	 * @param string $source source path
116
-	 */
117
-	public static function setSourcePathAndUser($source) {
118
-		[$uid, $path] = self::getUidAndFilename($source);
119
-		self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path];
120
-	}
121
-
122
-	/**
123
-	 * Gets the owner and the owner path from the source path
124
-	 *
125
-	 * @param string $source source path
126
-	 * @return array with user id and path
127
-	 */
128
-	public static function getSourcePathAndUser($source) {
129
-		if (isset(self::$sourcePathAndUser[$source])) {
130
-			$uid = self::$sourcePathAndUser[$source]['uid'];
131
-			$path = self::$sourcePathAndUser[$source]['path'];
132
-			unset(self::$sourcePathAndUser[$source]);
133
-		} else {
134
-			$uid = $path = false;
135
-		}
136
-		return [$uid, $path];
137
-	}
138
-
139
-	/**
140
-	 * get current size of all versions from a given user
141
-	 *
142
-	 * @param string $user user who owns the versions
143
-	 * @return int versions size
144
-	 */
145
-	private static function getVersionsSize($user) {
146
-		$view = new View('/' . $user);
147
-		$fileInfo = $view->getFileInfo('/files_versions');
148
-		return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
149
-	}
150
-
151
-	/**
152
-	 * store a new version of a file.
153
-	 */
154
-	public static function store($filename) {
155
-		// if the file gets streamed we need to remove the .part extension
156
-		// to get the right target
157
-		$ext = pathinfo($filename, PATHINFO_EXTENSION);
158
-		if ($ext === 'part') {
159
-			$filename = substr($filename, 0, -5);
160
-		}
161
-
162
-		// we only handle existing files
163
-		if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
164
-			return false;
165
-		}
166
-
167
-		// since hook paths are always relative to the "default filesystem view"
168
-		// we always use the owner from there to get the full node
169
-		$uid = Filesystem::getView()->getOwner('');
170
-
171
-		/** @var IRootFolder $rootFolder */
172
-		$rootFolder = Server::get(IRootFolder::class);
173
-		$userFolder = $rootFolder->getUserFolder($uid);
174
-
175
-		$eventDispatcher = Server::get(IEventDispatcher::class);
176
-		try {
177
-			$file = $userFolder->get($filename);
178
-		} catch (NotFoundException $e) {
179
-			return false;
180
-		}
181
-
182
-		$mount = $file->getMountPoint();
183
-		if ($mount instanceof SharedMount) {
184
-			$ownerFolder = $rootFolder->getUserFolder($mount->getShare()->getShareOwner());
185
-			$ownerNode = $ownerFolder->getFirstNodeById($file->getId());
186
-			if ($ownerNode) {
187
-				$file = $ownerNode;
188
-				$uid = $mount->getShare()->getShareOwner();
189
-			}
190
-		}
191
-
192
-		/** @var IUserManager $userManager */
193
-		$userManager = Server::get(IUserManager::class);
194
-		$user = $userManager->get($uid);
195
-
196
-		if (!$user) {
197
-			return false;
198
-		}
199
-
200
-		// no use making versions for empty files
201
-		if ($file->getSize() === 0) {
202
-			return false;
203
-		}
204
-
205
-		$event = new CreateVersionEvent($file);
206
-		$eventDispatcher->dispatch('OCA\Files_Versions::createVersion', $event);
207
-		if ($event->shouldCreateVersion() === false) {
208
-			return false;
209
-		}
210
-
211
-		/** @var IVersionManager $versionManager */
212
-		$versionManager = Server::get(IVersionManager::class);
213
-
214
-		$versionManager->createVersion($user, $file);
215
-	}
216
-
217
-
218
-	/**
219
-	 * mark file as deleted so that we can remove the versions if the file is gone
220
-	 * @param string $path
221
-	 */
222
-	public static function markDeletedFile($path) {
223
-		[$uid, $filename] = self::getUidAndFilename($path);
224
-		self::$deletedFiles[$path] = [
225
-			'uid' => $uid,
226
-			'filename' => $filename];
227
-	}
228
-
229
-	/**
230
-	 * delete the version from the storage and cache
231
-	 *
232
-	 * @param View $view
233
-	 * @param string $path
234
-	 */
235
-	protected static function deleteVersion($view, $path) {
236
-		$view->unlink($path);
237
-		/**
238
-		 * @var \OC\Files\Storage\Storage $storage
239
-		 * @var string $internalPath
240
-		 */
241
-		[$storage, $internalPath] = $view->resolvePath($path);
242
-		$cache = $storage->getCache($internalPath);
243
-		$cache->remove($internalPath);
244
-	}
245
-
246
-	/**
247
-	 * Delete versions of a file
248
-	 */
249
-	public static function delete($path) {
250
-		$deletedFile = self::$deletedFiles[$path];
251
-		$uid = $deletedFile['uid'];
252
-		$filename = $deletedFile['filename'];
253
-
254
-		if (!Filesystem::file_exists($path)) {
255
-			$view = new View('/' . $uid . '/files_versions');
256
-
257
-			$versions = self::getVersions($uid, $filename);
258
-			if (!empty($versions)) {
259
-				foreach ($versions as $v) {
260
-					\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
261
-					self::deleteVersion($view, $filename . '.v' . $v['version']);
262
-					\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
263
-				}
264
-			}
265
-		}
266
-		unset(self::$deletedFiles[$path]);
267
-	}
268
-
269
-	/**
270
-	 * Delete a version of a file
271
-	 */
272
-	public static function deleteRevision(string $path, int $revision): void {
273
-		[$uid, $filename] = self::getUidAndFilename($path);
274
-		$view = new View('/' . $uid . '/files_versions');
275
-		\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $revision, 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
276
-		self::deleteVersion($view, $filename . '.v' . $revision);
277
-		\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $revision, 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
278
-	}
279
-
280
-	/**
281
-	 * Rename or copy versions of a file of the given paths
282
-	 *
283
-	 * @param string $sourcePath source path of the file to move, relative to
284
-	 *                           the currently logged in user's "files" folder
285
-	 * @param string $targetPath target path of the file to move, relative to
286
-	 *                           the currently logged in user's "files" folder
287
-	 * @param string $operation can be 'copy' or 'rename'
288
-	 */
289
-	public static function renameOrCopy($sourcePath, $targetPath, $operation) {
290
-		[$sourceOwner, $sourcePath] = self::getSourcePathAndUser($sourcePath);
291
-
292
-		// it was a upload of a existing file if no old path exists
293
-		// in this case the pre-hook already called the store method and we can
294
-		// stop here
295
-		if ($sourcePath === false) {
296
-			return true;
297
-		}
298
-
299
-		[$targetOwner, $targetPath] = self::getUidAndFilename($targetPath);
300
-
301
-		$sourcePath = ltrim($sourcePath, '/');
302
-		$targetPath = ltrim($targetPath, '/');
303
-
304
-		$rootView = new View('');
305
-
306
-		// did we move a directory ?
307
-		if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
308
-			// does the directory exists for versions too ?
309
-			if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
310
-				// create missing dirs if necessary
311
-				self::createMissingDirectories($targetPath, new View('/' . $targetOwner));
312
-
313
-				// move the directory containing the versions
314
-				$rootView->$operation(
315
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath,
316
-					'/' . $targetOwner . '/files_versions/' . $targetPath
317
-				);
318
-			}
319
-		} elseif ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
320
-			// create missing dirs if necessary
321
-			self::createMissingDirectories($targetPath, new View('/' . $targetOwner));
322
-
323
-			foreach ($versions as $v) {
324
-				// move each version one by one to the target directory
325
-				$rootView->$operation(
326
-					'/' . $sourceOwner . '/files_versions/' . $sourcePath . '.v' . $v['version'],
327
-					'/' . $targetOwner . '/files_versions/' . $targetPath . '.v' . $v['version']
328
-				);
329
-			}
330
-		}
331
-
332
-		// if we moved versions directly for a file, schedule expiration check for that file
333
-		if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
334
-			self::scheduleExpire($targetOwner, $targetPath);
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * Rollback to an old version of a file.
340
-	 *
341
-	 * @param string $file file name
342
-	 * @param int $revision revision timestamp
343
-	 * @return bool
344
-	 */
345
-	public static function rollback(string $file, int $revision, IUser $user) {
346
-		// add expected leading slash
347
-		$filename = '/' . ltrim($file, '/');
348
-
349
-		// Fetch the userfolder to trigger view hooks
350
-		$root = Server::get(IRootFolder::class);
351
-		$userFolder = $root->getUserFolder($user->getUID());
352
-
353
-		$users_view = new View('/' . $user->getUID());
354
-		$files_view = new View('/' . $user->getUID() . '/files');
355
-
356
-		$versionCreated = false;
357
-
358
-		$fileInfo = $files_view->getFileInfo($file);
359
-
360
-		// check if user has the permissions to revert a version
361
-		if (!$fileInfo->isUpdateable()) {
362
-			return false;
363
-		}
364
-
365
-		//first create a new version
366
-		$version = 'files_versions' . $filename . '.v' . $users_view->filemtime('files' . $filename);
367
-		if (!$users_view->file_exists($version)) {
368
-			$users_view->copy('files' . $filename, 'files_versions' . $filename . '.v' . $users_view->filemtime('files' . $filename));
369
-			$versionCreated = true;
370
-		}
371
-
372
-		$fileToRestore = 'files_versions' . $filename . '.v' . $revision;
373
-
374
-		// Restore encrypted version of the old file for the newly restored file
375
-		// This has to happen manually here since the file is manually copied below
376
-		$oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
377
-		$oldFileInfo = $users_view->getFileInfo($fileToRestore);
378
-		$cache = $fileInfo->getStorage()->getCache();
379
-		$cache->update(
380
-			$fileInfo->getId(), [
381
-				'encrypted' => $oldVersion,
382
-				'encryptedVersion' => $oldVersion,
383
-				'size' => $oldFileInfo->getData()['size'],
384
-				'unencrypted_size' => $oldFileInfo->getData()['unencrypted_size'],
385
-			]
386
-		);
387
-
388
-		// rollback
389
-		if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
390
-			$files_view->touch($file, $revision);
391
-			Storage::scheduleExpire($user->getUID(), $file);
392
-
393
-			return true;
394
-		} elseif ($versionCreated) {
395
-			self::deleteVersion($users_view, $version);
396
-		}
397
-
398
-		return false;
399
-	}
400
-
401
-	/**
402
-	 * Stream copy file contents from $path1 to $path2
403
-	 *
404
-	 * @param View $view view to use for copying
405
-	 * @param string $path1 source file to copy
406
-	 * @param string $path2 target file
407
-	 *
408
-	 * @return bool true for success, false otherwise
409
-	 */
410
-	private static function copyFileContents($view, $path1, $path2) {
411
-		/** @var \OC\Files\Storage\Storage $storage1 */
412
-		[$storage1, $internalPath1] = $view->resolvePath($path1);
413
-		/** @var \OC\Files\Storage\Storage $storage2 */
414
-		[$storage2, $internalPath2] = $view->resolvePath($path2);
415
-
416
-		$view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
417
-		$view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
418
-
419
-		try {
420
-			// TODO add a proper way of overwriting a file while maintaining file ids
421
-			if ($storage1->instanceOfStorage(\OC\Files\ObjectStore\ObjectStoreStorage::class)
422
-				|| $storage2->instanceOfStorage(\OC\Files\ObjectStore\ObjectStoreStorage::class)
423
-			) {
424
-				$source = $storage1->fopen($internalPath1, 'r');
425
-				$result = $source !== false;
426
-				if ($result) {
427
-					if ($storage2->instanceOfStorage(IWriteStreamStorage::class)) {
428
-						/** @var IWriteStreamStorage $storage2 */
429
-						$storage2->writeStream($internalPath2, $source);
430
-					} else {
431
-						$target = $storage2->fopen($internalPath2, 'w');
432
-						$result = $target !== false;
433
-						if ($target !== false) {
434
-							[, $result] = Files::streamCopy($source, $target, true);
435
-							fclose($target);
436
-						}
437
-					}
438
-					fclose($source);
439
-				}
440
-
441
-				if ($result !== false) {
442
-					$storage1->unlink($internalPath1);
443
-				}
444
-			} else {
445
-				$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
446
-			}
447
-		} finally {
448
-			$view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
449
-			$view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
450
-		}
451
-
452
-		return ($result !== false);
453
-	}
454
-
455
-	/**
456
-	 * get a list of all available versions of a file in descending chronological order
457
-	 * @param string $uid user id from the owner of the file
458
-	 * @param string $filename file to find versions of, relative to the user files dir
459
-	 * @param string $userFullPath
460
-	 * @return array versions newest version first
461
-	 */
462
-	public static function getVersions($uid, $filename, $userFullPath = '') {
463
-		$versions = [];
464
-		if (empty($filename)) {
465
-			return $versions;
466
-		}
467
-		// fetch for old versions
468
-		$view = new View('/' . $uid . '/');
469
-
470
-		$pathinfo = pathinfo($filename);
471
-		$versionedFile = $pathinfo['basename'];
472
-
473
-		$dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
474
-
475
-		$dirContent = false;
476
-		if ($view->is_dir($dir)) {
477
-			$dirContent = $view->opendir($dir);
478
-		}
479
-
480
-		if ($dirContent === false) {
481
-			return $versions;
482
-		}
483
-
484
-		if (is_resource($dirContent)) {
485
-			while (($entryName = readdir($dirContent)) !== false) {
486
-				if (!Filesystem::isIgnoredDir($entryName)) {
487
-					$pathparts = pathinfo($entryName);
488
-					$filename = $pathparts['filename'];
489
-					if ($filename === $versionedFile) {
490
-						$pathparts = pathinfo($entryName);
491
-						$timestamp = substr($pathparts['extension'] ?? '', 1);
492
-						if (!is_numeric($timestamp)) {
493
-							Server::get(LoggerInterface::class)->error(
494
-								'Version file {path} has incorrect name format',
495
-								[
496
-									'path' => $entryName,
497
-									'app' => 'files_versions',
498
-								]
499
-							);
500
-							continue;
501
-						}
502
-						$filename = $pathparts['filename'];
503
-						$key = $timestamp . '#' . $filename;
504
-						$versions[$key]['version'] = $timestamp;
505
-						$versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp((int)$timestamp);
506
-						if (empty($userFullPath)) {
507
-							$versions[$key]['preview'] = '';
508
-						} else {
509
-							/** @var IURLGenerator $urlGenerator */
510
-							$urlGenerator = Server::get(IURLGenerator::class);
511
-							$versions[$key]['preview'] = $urlGenerator->linkToRoute('files_version.Preview.getPreview',
512
-								['file' => $userFullPath, 'version' => $timestamp]);
513
-						}
514
-						$versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
515
-						$versions[$key]['name'] = $versionedFile;
516
-						$versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
517
-						$versions[$key]['mimetype'] = Server::get(IMimeTypeDetector::class)->detectPath($versionedFile);
518
-					}
519
-				}
520
-			}
521
-			closedir($dirContent);
522
-		}
523
-
524
-		// sort with newest version first
525
-		krsort($versions);
526
-
527
-		return $versions;
528
-	}
529
-
530
-	/**
531
-	 * Expire versions that older than max version retention time
532
-	 *
533
-	 * @param string $uid
534
-	 */
535
-	public static function expireOlderThanMaxForUser($uid) {
536
-		/** @var IRootFolder $root */
537
-		$root = Server::get(IRootFolder::class);
538
-		try {
539
-			/** @var Folder $versionsRoot */
540
-			$versionsRoot = $root->get('/' . $uid . '/files_versions');
541
-		} catch (NotFoundException $e) {
542
-			return;
543
-		}
544
-
545
-		$expiration = self::getExpiration();
546
-		$threshold = $expiration->getMaxAgeAsTimestamp();
547
-		if (!$threshold) {
548
-			return;
549
-		}
550
-
551
-		$allVersions = $versionsRoot->search(new SearchQuery(
552
-			new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
553
-				new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', FileInfo::MIMETYPE_FOLDER),
554
-			]),
555
-			0,
556
-			0,
557
-			[]
558
-		));
559
-
560
-		/** @var VersionsMapper $versionsMapper */
561
-		$versionsMapper = Server::get(VersionsMapper::class);
562
-		$userFolder = $root->getUserFolder($uid);
563
-		$versionEntities = [];
564
-
565
-		/** @var Node[] $versions */
566
-		$versions = array_filter($allVersions, function (Node $info) use ($threshold, $userFolder, $versionsMapper, $versionsRoot, &$versionEntities) {
567
-			// Check that the file match '*.v*'
568
-			$versionsBegin = strrpos($info->getName(), '.v');
569
-			if ($versionsBegin === false) {
570
-				return false;
571
-			}
572
-
573
-			$version = (int)substr($info->getName(), $versionsBegin + 2);
574
-
575
-			// Check that the version does not have a label.
576
-			$path = $versionsRoot->getRelativePath($info->getPath());
577
-			if ($path === null) {
578
-				throw new DoesNotExistException('Could not find relative path of (' . $info->getPath() . ')');
579
-			}
580
-
581
-			try {
582
-				$node = $userFolder->get(substr($path, 0, -strlen('.v' . $version)));
583
-				$versionEntity = $versionsMapper->findVersionForFileId($node->getId(), $version);
584
-				$versionEntities[$info->getId()] = $versionEntity;
585
-
586
-				if ($versionEntity->getMetadataValue('label') !== null && $versionEntity->getMetadataValue('label') !== '') {
587
-					return false;
588
-				}
589
-			} catch (NotFoundException $e) {
590
-				// Original node not found, delete the version
591
-				return true;
592
-			} catch (StorageNotAvailableException|StorageInvalidException $e) {
593
-				// Storage can't be used, but it might only be temporary so we can't always delete the version
594
-				// since we can't determine if the version is named we take the safe route and don't expire
595
-				return false;
596
-			} catch (DoesNotExistException $ex) {
597
-				// Version on FS can have no equivalent in the DB if they were created before the version naming feature.
598
-				// So we ignore DoesNotExistException.
599
-			}
600
-
601
-			// Check that the version's timestamp is lower than $threshold
602
-			return $version < $threshold;
603
-		});
604
-
605
-		foreach ($versions as $version) {
606
-			$internalPath = $version->getInternalPath();
607
-			\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
608
-
609
-			$versionEntity = isset($versionEntities[$version->getId()]) ? $versionEntities[$version->getId()] : null;
610
-			if (!is_null($versionEntity)) {
611
-				$versionsMapper->delete($versionEntity);
612
-			}
613
-
614
-			try {
615
-				$version->delete();
616
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
617
-			} catch (NotPermittedException $e) {
618
-				Server::get(LoggerInterface::class)->error("Missing permissions to delete version: {$internalPath}", ['app' => 'files_versions', 'exception' => $e]);
619
-			}
620
-		}
621
-	}
622
-
623
-	/**
624
-	 * translate a timestamp into a string like "5 days ago"
625
-	 *
626
-	 * @param int $timestamp
627
-	 * @return string for example "5 days ago"
628
-	 */
629
-	private static function getHumanReadableTimestamp(int $timestamp): string {
630
-		$diff = time() - $timestamp;
631
-
632
-		if ($diff < 60) { // first minute
633
-			return  $diff . ' seconds ago';
634
-		} elseif ($diff < 3600) { //first hour
635
-			return round($diff / 60) . ' minutes ago';
636
-		} elseif ($diff < 86400) { // first day
637
-			return round($diff / 3600) . ' hours ago';
638
-		} elseif ($diff < 604800) { //first week
639
-			return round($diff / 86400) . ' days ago';
640
-		} elseif ($diff < 2419200) { //first month
641
-			return round($diff / 604800) . ' weeks ago';
642
-		} elseif ($diff < 29030400) { // first year
643
-			return round($diff / 2419200) . ' months ago';
644
-		} else {
645
-			return round($diff / 29030400) . ' years ago';
646
-		}
647
-	}
648
-
649
-	/**
650
-	 * returns all stored file versions from a given user
651
-	 * @param string $uid id of the user
652
-	 * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
653
-	 */
654
-	private static function getAllVersions($uid) {
655
-		$view = new View('/' . $uid . '/');
656
-		$dirs = [self::VERSIONS_ROOT];
657
-		$versions = [];
658
-
659
-		while (!empty($dirs)) {
660
-			$dir = array_pop($dirs);
661
-			$files = $view->getDirectoryContent($dir);
662
-
663
-			foreach ($files as $file) {
664
-				$fileData = $file->getData();
665
-				$filePath = $dir . '/' . $fileData['name'];
666
-				if ($file['type'] === 'dir') {
667
-					$dirs[] = $filePath;
668
-				} else {
669
-					$versionsBegin = strrpos($filePath, '.v');
670
-					$relPathStart = strlen(self::VERSIONS_ROOT);
671
-					$version = substr($filePath, $versionsBegin + 2);
672
-					$relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
673
-					$key = $version . '#' . $relpath;
674
-					$versions[$key] = ['path' => $relpath, 'timestamp' => $version];
675
-				}
676
-			}
677
-		}
678
-
679
-		// newest version first
680
-		krsort($versions);
681
-
682
-		$result = [
683
-			'all' => [],
684
-			'by_file' => [],
685
-		];
686
-
687
-		foreach ($versions as $key => $value) {
688
-			$size = $view->filesize(self::VERSIONS_ROOT . '/' . $value['path'] . '.v' . $value['timestamp']);
689
-			$filename = $value['path'];
690
-
691
-			$result['all'][$key]['version'] = $value['timestamp'];
692
-			$result['all'][$key]['path'] = $filename;
693
-			$result['all'][$key]['size'] = $size;
694
-
695
-			$result['by_file'][$filename][$key]['version'] = $value['timestamp'];
696
-			$result['by_file'][$filename][$key]['path'] = $filename;
697
-			$result['by_file'][$filename][$key]['size'] = $size;
698
-		}
699
-
700
-		return $result;
701
-	}
702
-
703
-	/**
704
-	 * get list of files we want to expire
705
-	 * @param array $versions list of versions
706
-	 * @param integer $time
707
-	 * @param bool $quotaExceeded is versions storage limit reached
708
-	 * @return array containing the list of to deleted versions and the size of them
709
-	 */
710
-	protected static function getExpireList($time, $versions, $quotaExceeded = false) {
711
-		$expiration = self::getExpiration();
712
-
713
-		if ($expiration->shouldAutoExpire()) {
714
-			// Exclude versions that are newer than the minimum age from the auto expiration logic.
715
-			$minAge = $expiration->getMinAgeAsTimestamp();
716
-			if ($minAge !== false) {
717
-				$versionsToAutoExpire = array_filter($versions, fn ($version) => $version['version'] < $minAge);
718
-			} else {
719
-				$versionsToAutoExpire = $versions;
720
-			}
721
-
722
-			[$toDelete, $size] = self::getAutoExpireList($time, $versionsToAutoExpire);
723
-		} else {
724
-			$size = 0;
725
-			$toDelete = [];  // versions we want to delete
726
-		}
727
-
728
-		foreach ($versions as $key => $version) {
729
-			if (!is_numeric($version['version'])) {
730
-				Server::get(LoggerInterface::class)->error(
731
-					'Found a non-numeric timestamp version: ' . json_encode($version),
732
-					['app' => 'files_versions']);
733
-				continue;
734
-			}
735
-			if ($expiration->isExpired((int)($version['version']), $quotaExceeded) && !isset($toDelete[$key])) {
736
-				$size += $version['size'];
737
-				$toDelete[$key] = $version['path'] . '.v' . $version['version'];
738
-			}
739
-		}
740
-
741
-		return [$toDelete, $size];
742
-	}
743
-
744
-	/**
745
-	 * get list of files we want to expire
746
-	 * @param array $versions list of versions
747
-	 * @param integer $time
748
-	 * @return array containing the list of to deleted versions and the size of them
749
-	 */
750
-	protected static function getAutoExpireList($time, $versions) {
751
-		$size = 0;
752
-		$toDelete = [];  // versions we want to delete
753
-
754
-		$interval = 1;
755
-		$step = Storage::$max_versions_per_interval[$interval]['step'];
756
-		if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
757
-			$nextInterval = -1;
758
-		} else {
759
-			$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
760
-		}
761
-
762
-		$firstVersion = reset($versions);
763
-
764
-		if ($firstVersion === false) {
765
-			return [$toDelete, $size];
766
-		}
767
-
768
-		$firstKey = key($versions);
769
-		$prevTimestamp = $firstVersion['version'];
770
-		$nextVersion = $firstVersion['version'] - $step;
771
-		unset($versions[$firstKey]);
772
-
773
-		foreach ($versions as $key => $version) {
774
-			$newInterval = true;
775
-			while ($newInterval) {
776
-				if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
777
-					if ($version['version'] > $nextVersion) {
778
-						//distance between two version too small, mark to delete
779
-						$toDelete[$key] = $version['path'] . '.v' . $version['version'];
780
-						$size += $version['size'];
781
-						Server::get(LoggerInterface::class)->info('Mark to expire ' . $version['path'] . ' next version should be ' . $nextVersion . ' or smaller. (prevTimestamp: ' . $prevTimestamp . '; step: ' . $step, ['app' => 'files_versions']);
782
-					} else {
783
-						$nextVersion = $version['version'] - $step;
784
-						$prevTimestamp = $version['version'];
785
-					}
786
-					$newInterval = false; // version checked so we can move to the next one
787
-				} else { // time to move on to the next interval
788
-					$interval++;
789
-					$step = Storage::$max_versions_per_interval[$interval]['step'];
790
-					$nextVersion = $prevTimestamp - $step;
791
-					if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
792
-						$nextInterval = -1;
793
-					} else {
794
-						$nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
795
-					}
796
-					$newInterval = true; // we changed the interval -> check same version with new interval
797
-				}
798
-			}
799
-		}
800
-
801
-		return [$toDelete, $size];
802
-	}
803
-
804
-	/**
805
-	 * Schedule versions expiration for the given file
806
-	 *
807
-	 * @param string $uid owner of the file
808
-	 * @param string $fileName file/folder for which to schedule expiration
809
-	 */
810
-	public static function scheduleExpire($uid, $fileName) {
811
-		// let the admin disable auto expire
812
-		$expiration = self::getExpiration();
813
-		if ($expiration->isEnabled()) {
814
-			$command = new Expire($uid, $fileName);
815
-			/** @var IBus $bus */
816
-			$bus = Server::get(IBus::class);
817
-			$bus->push($command);
818
-		}
819
-	}
820
-
821
-	/**
822
-	 * Expire versions which exceed the quota.
823
-	 *
824
-	 * This will setup the filesystem for the given user but will not
825
-	 * tear it down afterwards.
826
-	 *
827
-	 * @param string $filename path to file to expire
828
-	 * @param string $uid user for which to expire the version
829
-	 * @return bool|int|null
830
-	 */
831
-	public static function expire($filename, $uid) {
832
-		$expiration = self::getExpiration();
833
-
834
-		/** @var LoggerInterface $logger */
835
-		$logger = Server::get(LoggerInterface::class);
836
-
837
-		if ($expiration->isEnabled()) {
838
-			// get available disk space for user
839
-			$user = Server::get(IUserManager::class)->get($uid);
840
-			if (is_null($user)) {
841
-				$logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
842
-				throw new NoUserException('Backends provided no user object for ' . $uid);
843
-			}
844
-
845
-			\OC_Util::setupFS($uid);
846
-
847
-			try {
848
-				if (!Filesystem::file_exists($filename)) {
849
-					return false;
850
-				}
851
-			} catch (StorageNotAvailableException $e) {
852
-				// if we can't check that the file hasn't been deleted we can only assume that it hasn't
853
-				// note that this `StorageNotAvailableException` is about the file the versions originate from,
854
-				// not the storage that the versions are stored on
855
-			}
856
-
857
-			if (empty($filename)) {
858
-				// file maybe renamed or deleted
859
-				return false;
860
-			}
861
-			$versionsFileview = new View('/' . $uid . '/files_versions');
862
-
863
-			$softQuota = true;
864
-			$quota = $user->getQuota();
865
-			if ($quota === null || $quota === 'none') {
866
-				$quota = Filesystem::free_space('/');
867
-				$softQuota = false;
868
-			} else {
869
-				$quota = Util::computerFileSize($quota);
870
-			}
871
-
872
-			// make sure that we have the current size of the version history
873
-			$versionsSize = self::getVersionsSize($uid);
874
-
875
-			// calculate available space for version history
876
-			// subtract size of files and current versions size from quota
877
-			if ($quota >= 0) {
878
-				if ($softQuota) {
879
-					$root = Server::get(IRootFolder::class);
880
-					$userFolder = $root->getUserFolder($uid);
881
-					if (is_null($userFolder)) {
882
-						$availableSpace = 0;
883
-					} else {
884
-						$free = $quota - $userFolder->getSize(false); // remaining free space for user
885
-						if ($free > 0) {
886
-							$availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
887
-						} else {
888
-							$availableSpace = $free - $versionsSize;
889
-						}
890
-					}
891
-				} else {
892
-					$availableSpace = $quota;
893
-				}
894
-			} else {
895
-				$availableSpace = PHP_INT_MAX;
896
-			}
897
-
898
-			$allVersions = Storage::getVersions($uid, $filename);
899
-
900
-			$time = time();
901
-			[$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
902
-
903
-			$availableSpace = $availableSpace + $sizeOfDeletedVersions;
904
-			$versionsSize = $versionsSize - $sizeOfDeletedVersions;
905
-
906
-			// if still not enough free space we rearrange the versions from all files
907
-			if ($availableSpace <= 0) {
908
-				$result = self::getAllVersions($uid);
909
-				$allVersions = $result['all'];
910
-
911
-				foreach ($result['by_file'] as $versions) {
912
-					[$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
913
-					$toDelete = array_merge($toDelete, $toDeleteNew);
914
-					$sizeOfDeletedVersions += $size;
915
-				}
916
-				$availableSpace = $availableSpace + $sizeOfDeletedVersions;
917
-				$versionsSize = $versionsSize - $sizeOfDeletedVersions;
918
-			}
919
-
920
-			foreach ($toDelete as $key => $path) {
921
-				// Make sure to cleanup version table relations as expire does not pass deleteVersion
922
-				try {
923
-					/** @var VersionsMapper $versionsMapper */
924
-					$versionsMapper = Server::get(VersionsMapper::class);
925
-					$file = Server::get(IRootFolder::class)->getUserFolder($uid)->get($filename);
926
-					$pathparts = pathinfo($path);
927
-					$timestamp = (int)substr($pathparts['extension'] ?? '', 1);
928
-					$versionEntity = $versionsMapper->findVersionForFileId($file->getId(), $timestamp);
929
-					if ($versionEntity->getMetadataValue('label') !== null && $versionEntity->getMetadataValue('label') !== '') {
930
-						continue;
931
-					}
932
-					$versionsMapper->delete($versionEntity);
933
-				} catch (DoesNotExistException $e) {
934
-				}
935
-
936
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
937
-				self::deleteVersion($versionsFileview, $path);
938
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
939
-				unset($allVersions[$key]); // update array with the versions we keep
940
-				$logger->info('Expire: ' . $path, ['app' => 'files_versions']);
941
-			}
942
-
943
-			// Check if enough space is available after versions are rearranged.
944
-			// If not we delete the oldest versions until we meet the size limit for versions,
945
-			// but always keep the two latest versions
946
-			$numOfVersions = count($allVersions) - 2 ;
947
-			$i = 0;
948
-			// sort oldest first and make sure that we start at the first element
949
-			ksort($allVersions);
950
-			reset($allVersions);
951
-			while ($availableSpace < 0 && $i < $numOfVersions) {
952
-				$version = current($allVersions);
953
-				\OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'] . '.v' . $version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
954
-				self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
955
-				\OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'] . '.v' . $version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
956
-				$logger->info('running out of space! Delete oldest version: ' . $version['path'] . '.v' . $version['version'], ['app' => 'files_versions']);
957
-				$versionsSize -= $version['size'];
958
-				$availableSpace += $version['size'];
959
-				next($allVersions);
960
-				$i++;
961
-			}
962
-
963
-			return $versionsSize; // finally return the new size of the version history
964
-		}
965
-
966
-		return false;
967
-	}
968
-
969
-	/**
970
-	 * Create recursively missing directories inside of files_versions
971
-	 * that match the given path to a file.
972
-	 *
973
-	 * @param string $filename $path to a file, relative to the user's
974
-	 *                         "files" folder
975
-	 * @param View $view view on data/user/
976
-	 */
977
-	public static function createMissingDirectories($filename, $view) {
978
-		$dirname = Filesystem::normalizePath(dirname($filename));
979
-		$dirParts = explode('/', $dirname);
980
-		$dir = '/files_versions';
981
-		foreach ($dirParts as $part) {
982
-			$dir = $dir . '/' . $part;
983
-			if (!$view->file_exists($dir)) {
984
-				$view->mkdir($dir);
985
-			}
986
-		}
987
-	}
988
-
989
-	/**
990
-	 * Static workaround
991
-	 * @return Expiration
992
-	 */
993
-	protected static function getExpiration() {
994
-		if (self::$application === null) {
995
-			self::$application = Server::get(Application::class);
996
-		}
997
-		return self::$application->getContainer()->get(Expiration::class);
998
-	}
48
+    public const DEFAULTENABLED = true;
49
+    public const DEFAULTMAXSIZE = 50; // unit: percentage; 50% of available disk space/quota
50
+    public const VERSIONS_ROOT = 'files_versions/';
51
+
52
+    public const DELETE_TRIGGER_MASTER_REMOVED = 0;
53
+    public const DELETE_TRIGGER_RETENTION_CONSTRAINT = 1;
54
+    public const DELETE_TRIGGER_QUOTA_EXCEEDED = 2;
55
+
56
+    // files for which we can remove the versions after the delete operation was successful
57
+    private static $deletedFiles = [];
58
+
59
+    private static $sourcePathAndUser = [];
60
+
61
+    private static $max_versions_per_interval = [
62
+        //first 10sec, one version every 2sec
63
+        1 => ['intervalEndsAfter' => 10,      'step' => 2],
64
+        //next minute, one version every 10sec
65
+        2 => ['intervalEndsAfter' => 60,      'step' => 10],
66
+        //next hour, one version every minute
67
+        3 => ['intervalEndsAfter' => 3600,    'step' => 60],
68
+        //next 24h, one version every hour
69
+        4 => ['intervalEndsAfter' => 86400,   'step' => 3600],
70
+        //next 30days, one version per day
71
+        5 => ['intervalEndsAfter' => 2592000, 'step' => 86400],
72
+        //until the end one version per week
73
+        6 => ['intervalEndsAfter' => -1,      'step' => 604800],
74
+    ];
75
+
76
+    /** @var Application */
77
+    private static $application;
78
+
79
+    /**
80
+     * get the UID of the owner of the file and the path to the file relative to
81
+     * owners files folder
82
+     *
83
+     * @param string $filename
84
+     * @return array
85
+     * @throws NoUserException
86
+     */
87
+    public static function getUidAndFilename($filename) {
88
+        $uid = Filesystem::getOwner($filename);
89
+        $userManager = Server::get(IUserManager::class);
90
+        // if the user with the UID doesn't exists, e.g. because the UID points
91
+        // to a remote user with a federated cloud ID we use the current logged-in
92
+        // user. We need a valid local user to create the versions
93
+        if (!$userManager->userExists($uid)) {
94
+            $uid = OC_User::getUser();
95
+        }
96
+        Filesystem::initMountPoints($uid);
97
+        if ($uid !== OC_User::getUser()) {
98
+            $info = Filesystem::getFileInfo($filename);
99
+            $ownerView = new View('/' . $uid . '/files');
100
+            try {
101
+                $filename = $ownerView->getPath($info['fileid']);
102
+                // make sure that the file name doesn't end with a trailing slash
103
+                // can for example happen single files shared across servers
104
+                $filename = rtrim($filename, '/');
105
+            } catch (NotFoundException $e) {
106
+                $filename = null;
107
+            }
108
+        }
109
+        return [$uid, $filename];
110
+    }
111
+
112
+    /**
113
+     * Remember the owner and the owner path of the source file
114
+     *
115
+     * @param string $source source path
116
+     */
117
+    public static function setSourcePathAndUser($source) {
118
+        [$uid, $path] = self::getUidAndFilename($source);
119
+        self::$sourcePathAndUser[$source] = ['uid' => $uid, 'path' => $path];
120
+    }
121
+
122
+    /**
123
+     * Gets the owner and the owner path from the source path
124
+     *
125
+     * @param string $source source path
126
+     * @return array with user id and path
127
+     */
128
+    public static function getSourcePathAndUser($source) {
129
+        if (isset(self::$sourcePathAndUser[$source])) {
130
+            $uid = self::$sourcePathAndUser[$source]['uid'];
131
+            $path = self::$sourcePathAndUser[$source]['path'];
132
+            unset(self::$sourcePathAndUser[$source]);
133
+        } else {
134
+            $uid = $path = false;
135
+        }
136
+        return [$uid, $path];
137
+    }
138
+
139
+    /**
140
+     * get current size of all versions from a given user
141
+     *
142
+     * @param string $user user who owns the versions
143
+     * @return int versions size
144
+     */
145
+    private static function getVersionsSize($user) {
146
+        $view = new View('/' . $user);
147
+        $fileInfo = $view->getFileInfo('/files_versions');
148
+        return isset($fileInfo['size']) ? $fileInfo['size'] : 0;
149
+    }
150
+
151
+    /**
152
+     * store a new version of a file.
153
+     */
154
+    public static function store($filename) {
155
+        // if the file gets streamed we need to remove the .part extension
156
+        // to get the right target
157
+        $ext = pathinfo($filename, PATHINFO_EXTENSION);
158
+        if ($ext === 'part') {
159
+            $filename = substr($filename, 0, -5);
160
+        }
161
+
162
+        // we only handle existing files
163
+        if (! Filesystem::file_exists($filename) || Filesystem::is_dir($filename)) {
164
+            return false;
165
+        }
166
+
167
+        // since hook paths are always relative to the "default filesystem view"
168
+        // we always use the owner from there to get the full node
169
+        $uid = Filesystem::getView()->getOwner('');
170
+
171
+        /** @var IRootFolder $rootFolder */
172
+        $rootFolder = Server::get(IRootFolder::class);
173
+        $userFolder = $rootFolder->getUserFolder($uid);
174
+
175
+        $eventDispatcher = Server::get(IEventDispatcher::class);
176
+        try {
177
+            $file = $userFolder->get($filename);
178
+        } catch (NotFoundException $e) {
179
+            return false;
180
+        }
181
+
182
+        $mount = $file->getMountPoint();
183
+        if ($mount instanceof SharedMount) {
184
+            $ownerFolder = $rootFolder->getUserFolder($mount->getShare()->getShareOwner());
185
+            $ownerNode = $ownerFolder->getFirstNodeById($file->getId());
186
+            if ($ownerNode) {
187
+                $file = $ownerNode;
188
+                $uid = $mount->getShare()->getShareOwner();
189
+            }
190
+        }
191
+
192
+        /** @var IUserManager $userManager */
193
+        $userManager = Server::get(IUserManager::class);
194
+        $user = $userManager->get($uid);
195
+
196
+        if (!$user) {
197
+            return false;
198
+        }
199
+
200
+        // no use making versions for empty files
201
+        if ($file->getSize() === 0) {
202
+            return false;
203
+        }
204
+
205
+        $event = new CreateVersionEvent($file);
206
+        $eventDispatcher->dispatch('OCA\Files_Versions::createVersion', $event);
207
+        if ($event->shouldCreateVersion() === false) {
208
+            return false;
209
+        }
210
+
211
+        /** @var IVersionManager $versionManager */
212
+        $versionManager = Server::get(IVersionManager::class);
213
+
214
+        $versionManager->createVersion($user, $file);
215
+    }
216
+
217
+
218
+    /**
219
+     * mark file as deleted so that we can remove the versions if the file is gone
220
+     * @param string $path
221
+     */
222
+    public static function markDeletedFile($path) {
223
+        [$uid, $filename] = self::getUidAndFilename($path);
224
+        self::$deletedFiles[$path] = [
225
+            'uid' => $uid,
226
+            'filename' => $filename];
227
+    }
228
+
229
+    /**
230
+     * delete the version from the storage and cache
231
+     *
232
+     * @param View $view
233
+     * @param string $path
234
+     */
235
+    protected static function deleteVersion($view, $path) {
236
+        $view->unlink($path);
237
+        /**
238
+         * @var \OC\Files\Storage\Storage $storage
239
+         * @var string $internalPath
240
+         */
241
+        [$storage, $internalPath] = $view->resolvePath($path);
242
+        $cache = $storage->getCache($internalPath);
243
+        $cache->remove($internalPath);
244
+    }
245
+
246
+    /**
247
+     * Delete versions of a file
248
+     */
249
+    public static function delete($path) {
250
+        $deletedFile = self::$deletedFiles[$path];
251
+        $uid = $deletedFile['uid'];
252
+        $filename = $deletedFile['filename'];
253
+
254
+        if (!Filesystem::file_exists($path)) {
255
+            $view = new View('/' . $uid . '/files_versions');
256
+
257
+            $versions = self::getVersions($uid, $filename);
258
+            if (!empty($versions)) {
259
+                foreach ($versions as $v) {
260
+                    \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
261
+                    self::deleteVersion($view, $filename . '.v' . $v['version']);
262
+                    \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $v['version'], 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
263
+                }
264
+            }
265
+        }
266
+        unset(self::$deletedFiles[$path]);
267
+    }
268
+
269
+    /**
270
+     * Delete a version of a file
271
+     */
272
+    public static function deleteRevision(string $path, int $revision): void {
273
+        [$uid, $filename] = self::getUidAndFilename($path);
274
+        $view = new View('/' . $uid . '/files_versions');
275
+        \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path . $revision, 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
276
+        self::deleteVersion($view, $filename . '.v' . $revision);
277
+        \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path . $revision, 'trigger' => self::DELETE_TRIGGER_MASTER_REMOVED]);
278
+    }
279
+
280
+    /**
281
+     * Rename or copy versions of a file of the given paths
282
+     *
283
+     * @param string $sourcePath source path of the file to move, relative to
284
+     *                           the currently logged in user's "files" folder
285
+     * @param string $targetPath target path of the file to move, relative to
286
+     *                           the currently logged in user's "files" folder
287
+     * @param string $operation can be 'copy' or 'rename'
288
+     */
289
+    public static function renameOrCopy($sourcePath, $targetPath, $operation) {
290
+        [$sourceOwner, $sourcePath] = self::getSourcePathAndUser($sourcePath);
291
+
292
+        // it was a upload of a existing file if no old path exists
293
+        // in this case the pre-hook already called the store method and we can
294
+        // stop here
295
+        if ($sourcePath === false) {
296
+            return true;
297
+        }
298
+
299
+        [$targetOwner, $targetPath] = self::getUidAndFilename($targetPath);
300
+
301
+        $sourcePath = ltrim($sourcePath, '/');
302
+        $targetPath = ltrim($targetPath, '/');
303
+
304
+        $rootView = new View('');
305
+
306
+        // did we move a directory ?
307
+        if ($rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
308
+            // does the directory exists for versions too ?
309
+            if ($rootView->is_dir('/' . $sourceOwner . '/files_versions/' . $sourcePath)) {
310
+                // create missing dirs if necessary
311
+                self::createMissingDirectories($targetPath, new View('/' . $targetOwner));
312
+
313
+                // move the directory containing the versions
314
+                $rootView->$operation(
315
+                    '/' . $sourceOwner . '/files_versions/' . $sourcePath,
316
+                    '/' . $targetOwner . '/files_versions/' . $targetPath
317
+                );
318
+            }
319
+        } elseif ($versions = Storage::getVersions($sourceOwner, '/' . $sourcePath)) {
320
+            // create missing dirs if necessary
321
+            self::createMissingDirectories($targetPath, new View('/' . $targetOwner));
322
+
323
+            foreach ($versions as $v) {
324
+                // move each version one by one to the target directory
325
+                $rootView->$operation(
326
+                    '/' . $sourceOwner . '/files_versions/' . $sourcePath . '.v' . $v['version'],
327
+                    '/' . $targetOwner . '/files_versions/' . $targetPath . '.v' . $v['version']
328
+                );
329
+            }
330
+        }
331
+
332
+        // if we moved versions directly for a file, schedule expiration check for that file
333
+        if (!$rootView->is_dir('/' . $targetOwner . '/files/' . $targetPath)) {
334
+            self::scheduleExpire($targetOwner, $targetPath);
335
+        }
336
+    }
337
+
338
+    /**
339
+     * Rollback to an old version of a file.
340
+     *
341
+     * @param string $file file name
342
+     * @param int $revision revision timestamp
343
+     * @return bool
344
+     */
345
+    public static function rollback(string $file, int $revision, IUser $user) {
346
+        // add expected leading slash
347
+        $filename = '/' . ltrim($file, '/');
348
+
349
+        // Fetch the userfolder to trigger view hooks
350
+        $root = Server::get(IRootFolder::class);
351
+        $userFolder = $root->getUserFolder($user->getUID());
352
+
353
+        $users_view = new View('/' . $user->getUID());
354
+        $files_view = new View('/' . $user->getUID() . '/files');
355
+
356
+        $versionCreated = false;
357
+
358
+        $fileInfo = $files_view->getFileInfo($file);
359
+
360
+        // check if user has the permissions to revert a version
361
+        if (!$fileInfo->isUpdateable()) {
362
+            return false;
363
+        }
364
+
365
+        //first create a new version
366
+        $version = 'files_versions' . $filename . '.v' . $users_view->filemtime('files' . $filename);
367
+        if (!$users_view->file_exists($version)) {
368
+            $users_view->copy('files' . $filename, 'files_versions' . $filename . '.v' . $users_view->filemtime('files' . $filename));
369
+            $versionCreated = true;
370
+        }
371
+
372
+        $fileToRestore = 'files_versions' . $filename . '.v' . $revision;
373
+
374
+        // Restore encrypted version of the old file for the newly restored file
375
+        // This has to happen manually here since the file is manually copied below
376
+        $oldVersion = $users_view->getFileInfo($fileToRestore)->getEncryptedVersion();
377
+        $oldFileInfo = $users_view->getFileInfo($fileToRestore);
378
+        $cache = $fileInfo->getStorage()->getCache();
379
+        $cache->update(
380
+            $fileInfo->getId(), [
381
+                'encrypted' => $oldVersion,
382
+                'encryptedVersion' => $oldVersion,
383
+                'size' => $oldFileInfo->getData()['size'],
384
+                'unencrypted_size' => $oldFileInfo->getData()['unencrypted_size'],
385
+            ]
386
+        );
387
+
388
+        // rollback
389
+        if (self::copyFileContents($users_view, $fileToRestore, 'files' . $filename)) {
390
+            $files_view->touch($file, $revision);
391
+            Storage::scheduleExpire($user->getUID(), $file);
392
+
393
+            return true;
394
+        } elseif ($versionCreated) {
395
+            self::deleteVersion($users_view, $version);
396
+        }
397
+
398
+        return false;
399
+    }
400
+
401
+    /**
402
+     * Stream copy file contents from $path1 to $path2
403
+     *
404
+     * @param View $view view to use for copying
405
+     * @param string $path1 source file to copy
406
+     * @param string $path2 target file
407
+     *
408
+     * @return bool true for success, false otherwise
409
+     */
410
+    private static function copyFileContents($view, $path1, $path2) {
411
+        /** @var \OC\Files\Storage\Storage $storage1 */
412
+        [$storage1, $internalPath1] = $view->resolvePath($path1);
413
+        /** @var \OC\Files\Storage\Storage $storage2 */
414
+        [$storage2, $internalPath2] = $view->resolvePath($path2);
415
+
416
+        $view->lockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
417
+        $view->lockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
418
+
419
+        try {
420
+            // TODO add a proper way of overwriting a file while maintaining file ids
421
+            if ($storage1->instanceOfStorage(\OC\Files\ObjectStore\ObjectStoreStorage::class)
422
+                || $storage2->instanceOfStorage(\OC\Files\ObjectStore\ObjectStoreStorage::class)
423
+            ) {
424
+                $source = $storage1->fopen($internalPath1, 'r');
425
+                $result = $source !== false;
426
+                if ($result) {
427
+                    if ($storage2->instanceOfStorage(IWriteStreamStorage::class)) {
428
+                        /** @var IWriteStreamStorage $storage2 */
429
+                        $storage2->writeStream($internalPath2, $source);
430
+                    } else {
431
+                        $target = $storage2->fopen($internalPath2, 'w');
432
+                        $result = $target !== false;
433
+                        if ($target !== false) {
434
+                            [, $result] = Files::streamCopy($source, $target, true);
435
+                            fclose($target);
436
+                        }
437
+                    }
438
+                    fclose($source);
439
+                }
440
+
441
+                if ($result !== false) {
442
+                    $storage1->unlink($internalPath1);
443
+                }
444
+            } else {
445
+                $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
446
+            }
447
+        } finally {
448
+            $view->unlockFile($path1, ILockingProvider::LOCK_EXCLUSIVE);
449
+            $view->unlockFile($path2, ILockingProvider::LOCK_EXCLUSIVE);
450
+        }
451
+
452
+        return ($result !== false);
453
+    }
454
+
455
+    /**
456
+     * get a list of all available versions of a file in descending chronological order
457
+     * @param string $uid user id from the owner of the file
458
+     * @param string $filename file to find versions of, relative to the user files dir
459
+     * @param string $userFullPath
460
+     * @return array versions newest version first
461
+     */
462
+    public static function getVersions($uid, $filename, $userFullPath = '') {
463
+        $versions = [];
464
+        if (empty($filename)) {
465
+            return $versions;
466
+        }
467
+        // fetch for old versions
468
+        $view = new View('/' . $uid . '/');
469
+
470
+        $pathinfo = pathinfo($filename);
471
+        $versionedFile = $pathinfo['basename'];
472
+
473
+        $dir = Filesystem::normalizePath(self::VERSIONS_ROOT . '/' . $pathinfo['dirname']);
474
+
475
+        $dirContent = false;
476
+        if ($view->is_dir($dir)) {
477
+            $dirContent = $view->opendir($dir);
478
+        }
479
+
480
+        if ($dirContent === false) {
481
+            return $versions;
482
+        }
483
+
484
+        if (is_resource($dirContent)) {
485
+            while (($entryName = readdir($dirContent)) !== false) {
486
+                if (!Filesystem::isIgnoredDir($entryName)) {
487
+                    $pathparts = pathinfo($entryName);
488
+                    $filename = $pathparts['filename'];
489
+                    if ($filename === $versionedFile) {
490
+                        $pathparts = pathinfo($entryName);
491
+                        $timestamp = substr($pathparts['extension'] ?? '', 1);
492
+                        if (!is_numeric($timestamp)) {
493
+                            Server::get(LoggerInterface::class)->error(
494
+                                'Version file {path} has incorrect name format',
495
+                                [
496
+                                    'path' => $entryName,
497
+                                    'app' => 'files_versions',
498
+                                ]
499
+                            );
500
+                            continue;
501
+                        }
502
+                        $filename = $pathparts['filename'];
503
+                        $key = $timestamp . '#' . $filename;
504
+                        $versions[$key]['version'] = $timestamp;
505
+                        $versions[$key]['humanReadableTimestamp'] = self::getHumanReadableTimestamp((int)$timestamp);
506
+                        if (empty($userFullPath)) {
507
+                            $versions[$key]['preview'] = '';
508
+                        } else {
509
+                            /** @var IURLGenerator $urlGenerator */
510
+                            $urlGenerator = Server::get(IURLGenerator::class);
511
+                            $versions[$key]['preview'] = $urlGenerator->linkToRoute('files_version.Preview.getPreview',
512
+                                ['file' => $userFullPath, 'version' => $timestamp]);
513
+                        }
514
+                        $versions[$key]['path'] = Filesystem::normalizePath($pathinfo['dirname'] . '/' . $filename);
515
+                        $versions[$key]['name'] = $versionedFile;
516
+                        $versions[$key]['size'] = $view->filesize($dir . '/' . $entryName);
517
+                        $versions[$key]['mimetype'] = Server::get(IMimeTypeDetector::class)->detectPath($versionedFile);
518
+                    }
519
+                }
520
+            }
521
+            closedir($dirContent);
522
+        }
523
+
524
+        // sort with newest version first
525
+        krsort($versions);
526
+
527
+        return $versions;
528
+    }
529
+
530
+    /**
531
+     * Expire versions that older than max version retention time
532
+     *
533
+     * @param string $uid
534
+     */
535
+    public static function expireOlderThanMaxForUser($uid) {
536
+        /** @var IRootFolder $root */
537
+        $root = Server::get(IRootFolder::class);
538
+        try {
539
+            /** @var Folder $versionsRoot */
540
+            $versionsRoot = $root->get('/' . $uid . '/files_versions');
541
+        } catch (NotFoundException $e) {
542
+            return;
543
+        }
544
+
545
+        $expiration = self::getExpiration();
546
+        $threshold = $expiration->getMaxAgeAsTimestamp();
547
+        if (!$threshold) {
548
+            return;
549
+        }
550
+
551
+        $allVersions = $versionsRoot->search(new SearchQuery(
552
+            new SearchBinaryOperator(ISearchBinaryOperator::OPERATOR_NOT, [
553
+                new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', FileInfo::MIMETYPE_FOLDER),
554
+            ]),
555
+            0,
556
+            0,
557
+            []
558
+        ));
559
+
560
+        /** @var VersionsMapper $versionsMapper */
561
+        $versionsMapper = Server::get(VersionsMapper::class);
562
+        $userFolder = $root->getUserFolder($uid);
563
+        $versionEntities = [];
564
+
565
+        /** @var Node[] $versions */
566
+        $versions = array_filter($allVersions, function (Node $info) use ($threshold, $userFolder, $versionsMapper, $versionsRoot, &$versionEntities) {
567
+            // Check that the file match '*.v*'
568
+            $versionsBegin = strrpos($info->getName(), '.v');
569
+            if ($versionsBegin === false) {
570
+                return false;
571
+            }
572
+
573
+            $version = (int)substr($info->getName(), $versionsBegin + 2);
574
+
575
+            // Check that the version does not have a label.
576
+            $path = $versionsRoot->getRelativePath($info->getPath());
577
+            if ($path === null) {
578
+                throw new DoesNotExistException('Could not find relative path of (' . $info->getPath() . ')');
579
+            }
580
+
581
+            try {
582
+                $node = $userFolder->get(substr($path, 0, -strlen('.v' . $version)));
583
+                $versionEntity = $versionsMapper->findVersionForFileId($node->getId(), $version);
584
+                $versionEntities[$info->getId()] = $versionEntity;
585
+
586
+                if ($versionEntity->getMetadataValue('label') !== null && $versionEntity->getMetadataValue('label') !== '') {
587
+                    return false;
588
+                }
589
+            } catch (NotFoundException $e) {
590
+                // Original node not found, delete the version
591
+                return true;
592
+            } catch (StorageNotAvailableException|StorageInvalidException $e) {
593
+                // Storage can't be used, but it might only be temporary so we can't always delete the version
594
+                // since we can't determine if the version is named we take the safe route and don't expire
595
+                return false;
596
+            } catch (DoesNotExistException $ex) {
597
+                // Version on FS can have no equivalent in the DB if they were created before the version naming feature.
598
+                // So we ignore DoesNotExistException.
599
+            }
600
+
601
+            // Check that the version's timestamp is lower than $threshold
602
+            return $version < $threshold;
603
+        });
604
+
605
+        foreach ($versions as $version) {
606
+            $internalPath = $version->getInternalPath();
607
+            \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
608
+
609
+            $versionEntity = isset($versionEntities[$version->getId()]) ? $versionEntities[$version->getId()] : null;
610
+            if (!is_null($versionEntity)) {
611
+                $versionsMapper->delete($versionEntity);
612
+            }
613
+
614
+            try {
615
+                $version->delete();
616
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $internalPath, 'trigger' => self::DELETE_TRIGGER_RETENTION_CONSTRAINT]);
617
+            } catch (NotPermittedException $e) {
618
+                Server::get(LoggerInterface::class)->error("Missing permissions to delete version: {$internalPath}", ['app' => 'files_versions', 'exception' => $e]);
619
+            }
620
+        }
621
+    }
622
+
623
+    /**
624
+     * translate a timestamp into a string like "5 days ago"
625
+     *
626
+     * @param int $timestamp
627
+     * @return string for example "5 days ago"
628
+     */
629
+    private static function getHumanReadableTimestamp(int $timestamp): string {
630
+        $diff = time() - $timestamp;
631
+
632
+        if ($diff < 60) { // first minute
633
+            return  $diff . ' seconds ago';
634
+        } elseif ($diff < 3600) { //first hour
635
+            return round($diff / 60) . ' minutes ago';
636
+        } elseif ($diff < 86400) { // first day
637
+            return round($diff / 3600) . ' hours ago';
638
+        } elseif ($diff < 604800) { //first week
639
+            return round($diff / 86400) . ' days ago';
640
+        } elseif ($diff < 2419200) { //first month
641
+            return round($diff / 604800) . ' weeks ago';
642
+        } elseif ($diff < 29030400) { // first year
643
+            return round($diff / 2419200) . ' months ago';
644
+        } else {
645
+            return round($diff / 29030400) . ' years ago';
646
+        }
647
+    }
648
+
649
+    /**
650
+     * returns all stored file versions from a given user
651
+     * @param string $uid id of the user
652
+     * @return array with contains two arrays 'all' which contains all versions sorted by age and 'by_file' which contains all versions sorted by filename
653
+     */
654
+    private static function getAllVersions($uid) {
655
+        $view = new View('/' . $uid . '/');
656
+        $dirs = [self::VERSIONS_ROOT];
657
+        $versions = [];
658
+
659
+        while (!empty($dirs)) {
660
+            $dir = array_pop($dirs);
661
+            $files = $view->getDirectoryContent($dir);
662
+
663
+            foreach ($files as $file) {
664
+                $fileData = $file->getData();
665
+                $filePath = $dir . '/' . $fileData['name'];
666
+                if ($file['type'] === 'dir') {
667
+                    $dirs[] = $filePath;
668
+                } else {
669
+                    $versionsBegin = strrpos($filePath, '.v');
670
+                    $relPathStart = strlen(self::VERSIONS_ROOT);
671
+                    $version = substr($filePath, $versionsBegin + 2);
672
+                    $relpath = substr($filePath, $relPathStart, $versionsBegin - $relPathStart);
673
+                    $key = $version . '#' . $relpath;
674
+                    $versions[$key] = ['path' => $relpath, 'timestamp' => $version];
675
+                }
676
+            }
677
+        }
678
+
679
+        // newest version first
680
+        krsort($versions);
681
+
682
+        $result = [
683
+            'all' => [],
684
+            'by_file' => [],
685
+        ];
686
+
687
+        foreach ($versions as $key => $value) {
688
+            $size = $view->filesize(self::VERSIONS_ROOT . '/' . $value['path'] . '.v' . $value['timestamp']);
689
+            $filename = $value['path'];
690
+
691
+            $result['all'][$key]['version'] = $value['timestamp'];
692
+            $result['all'][$key]['path'] = $filename;
693
+            $result['all'][$key]['size'] = $size;
694
+
695
+            $result['by_file'][$filename][$key]['version'] = $value['timestamp'];
696
+            $result['by_file'][$filename][$key]['path'] = $filename;
697
+            $result['by_file'][$filename][$key]['size'] = $size;
698
+        }
699
+
700
+        return $result;
701
+    }
702
+
703
+    /**
704
+     * get list of files we want to expire
705
+     * @param array $versions list of versions
706
+     * @param integer $time
707
+     * @param bool $quotaExceeded is versions storage limit reached
708
+     * @return array containing the list of to deleted versions and the size of them
709
+     */
710
+    protected static function getExpireList($time, $versions, $quotaExceeded = false) {
711
+        $expiration = self::getExpiration();
712
+
713
+        if ($expiration->shouldAutoExpire()) {
714
+            // Exclude versions that are newer than the minimum age from the auto expiration logic.
715
+            $minAge = $expiration->getMinAgeAsTimestamp();
716
+            if ($minAge !== false) {
717
+                $versionsToAutoExpire = array_filter($versions, fn ($version) => $version['version'] < $minAge);
718
+            } else {
719
+                $versionsToAutoExpire = $versions;
720
+            }
721
+
722
+            [$toDelete, $size] = self::getAutoExpireList($time, $versionsToAutoExpire);
723
+        } else {
724
+            $size = 0;
725
+            $toDelete = [];  // versions we want to delete
726
+        }
727
+
728
+        foreach ($versions as $key => $version) {
729
+            if (!is_numeric($version['version'])) {
730
+                Server::get(LoggerInterface::class)->error(
731
+                    'Found a non-numeric timestamp version: ' . json_encode($version),
732
+                    ['app' => 'files_versions']);
733
+                continue;
734
+            }
735
+            if ($expiration->isExpired((int)($version['version']), $quotaExceeded) && !isset($toDelete[$key])) {
736
+                $size += $version['size'];
737
+                $toDelete[$key] = $version['path'] . '.v' . $version['version'];
738
+            }
739
+        }
740
+
741
+        return [$toDelete, $size];
742
+    }
743
+
744
+    /**
745
+     * get list of files we want to expire
746
+     * @param array $versions list of versions
747
+     * @param integer $time
748
+     * @return array containing the list of to deleted versions and the size of them
749
+     */
750
+    protected static function getAutoExpireList($time, $versions) {
751
+        $size = 0;
752
+        $toDelete = [];  // versions we want to delete
753
+
754
+        $interval = 1;
755
+        $step = Storage::$max_versions_per_interval[$interval]['step'];
756
+        if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
757
+            $nextInterval = -1;
758
+        } else {
759
+            $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
760
+        }
761
+
762
+        $firstVersion = reset($versions);
763
+
764
+        if ($firstVersion === false) {
765
+            return [$toDelete, $size];
766
+        }
767
+
768
+        $firstKey = key($versions);
769
+        $prevTimestamp = $firstVersion['version'];
770
+        $nextVersion = $firstVersion['version'] - $step;
771
+        unset($versions[$firstKey]);
772
+
773
+        foreach ($versions as $key => $version) {
774
+            $newInterval = true;
775
+            while ($newInterval) {
776
+                if ($nextInterval === -1 || $prevTimestamp > $nextInterval) {
777
+                    if ($version['version'] > $nextVersion) {
778
+                        //distance between two version too small, mark to delete
779
+                        $toDelete[$key] = $version['path'] . '.v' . $version['version'];
780
+                        $size += $version['size'];
781
+                        Server::get(LoggerInterface::class)->info('Mark to expire ' . $version['path'] . ' next version should be ' . $nextVersion . ' or smaller. (prevTimestamp: ' . $prevTimestamp . '; step: ' . $step, ['app' => 'files_versions']);
782
+                    } else {
783
+                        $nextVersion = $version['version'] - $step;
784
+                        $prevTimestamp = $version['version'];
785
+                    }
786
+                    $newInterval = false; // version checked so we can move to the next one
787
+                } else { // time to move on to the next interval
788
+                    $interval++;
789
+                    $step = Storage::$max_versions_per_interval[$interval]['step'];
790
+                    $nextVersion = $prevTimestamp - $step;
791
+                    if (Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'] === -1) {
792
+                        $nextInterval = -1;
793
+                    } else {
794
+                        $nextInterval = $time - Storage::$max_versions_per_interval[$interval]['intervalEndsAfter'];
795
+                    }
796
+                    $newInterval = true; // we changed the interval -> check same version with new interval
797
+                }
798
+            }
799
+        }
800
+
801
+        return [$toDelete, $size];
802
+    }
803
+
804
+    /**
805
+     * Schedule versions expiration for the given file
806
+     *
807
+     * @param string $uid owner of the file
808
+     * @param string $fileName file/folder for which to schedule expiration
809
+     */
810
+    public static function scheduleExpire($uid, $fileName) {
811
+        // let the admin disable auto expire
812
+        $expiration = self::getExpiration();
813
+        if ($expiration->isEnabled()) {
814
+            $command = new Expire($uid, $fileName);
815
+            /** @var IBus $bus */
816
+            $bus = Server::get(IBus::class);
817
+            $bus->push($command);
818
+        }
819
+    }
820
+
821
+    /**
822
+     * Expire versions which exceed the quota.
823
+     *
824
+     * This will setup the filesystem for the given user but will not
825
+     * tear it down afterwards.
826
+     *
827
+     * @param string $filename path to file to expire
828
+     * @param string $uid user for which to expire the version
829
+     * @return bool|int|null
830
+     */
831
+    public static function expire($filename, $uid) {
832
+        $expiration = self::getExpiration();
833
+
834
+        /** @var LoggerInterface $logger */
835
+        $logger = Server::get(LoggerInterface::class);
836
+
837
+        if ($expiration->isEnabled()) {
838
+            // get available disk space for user
839
+            $user = Server::get(IUserManager::class)->get($uid);
840
+            if (is_null($user)) {
841
+                $logger->error('Backends provided no user object for ' . $uid, ['app' => 'files_versions']);
842
+                throw new NoUserException('Backends provided no user object for ' . $uid);
843
+            }
844
+
845
+            \OC_Util::setupFS($uid);
846
+
847
+            try {
848
+                if (!Filesystem::file_exists($filename)) {
849
+                    return false;
850
+                }
851
+            } catch (StorageNotAvailableException $e) {
852
+                // if we can't check that the file hasn't been deleted we can only assume that it hasn't
853
+                // note that this `StorageNotAvailableException` is about the file the versions originate from,
854
+                // not the storage that the versions are stored on
855
+            }
856
+
857
+            if (empty($filename)) {
858
+                // file maybe renamed or deleted
859
+                return false;
860
+            }
861
+            $versionsFileview = new View('/' . $uid . '/files_versions');
862
+
863
+            $softQuota = true;
864
+            $quota = $user->getQuota();
865
+            if ($quota === null || $quota === 'none') {
866
+                $quota = Filesystem::free_space('/');
867
+                $softQuota = false;
868
+            } else {
869
+                $quota = Util::computerFileSize($quota);
870
+            }
871
+
872
+            // make sure that we have the current size of the version history
873
+            $versionsSize = self::getVersionsSize($uid);
874
+
875
+            // calculate available space for version history
876
+            // subtract size of files and current versions size from quota
877
+            if ($quota >= 0) {
878
+                if ($softQuota) {
879
+                    $root = Server::get(IRootFolder::class);
880
+                    $userFolder = $root->getUserFolder($uid);
881
+                    if (is_null($userFolder)) {
882
+                        $availableSpace = 0;
883
+                    } else {
884
+                        $free = $quota - $userFolder->getSize(false); // remaining free space for user
885
+                        if ($free > 0) {
886
+                            $availableSpace = ($free * self::DEFAULTMAXSIZE / 100) - $versionsSize; // how much space can be used for versions
887
+                        } else {
888
+                            $availableSpace = $free - $versionsSize;
889
+                        }
890
+                    }
891
+                } else {
892
+                    $availableSpace = $quota;
893
+                }
894
+            } else {
895
+                $availableSpace = PHP_INT_MAX;
896
+            }
897
+
898
+            $allVersions = Storage::getVersions($uid, $filename);
899
+
900
+            $time = time();
901
+            [$toDelete, $sizeOfDeletedVersions] = self::getExpireList($time, $allVersions, $availableSpace <= 0);
902
+
903
+            $availableSpace = $availableSpace + $sizeOfDeletedVersions;
904
+            $versionsSize = $versionsSize - $sizeOfDeletedVersions;
905
+
906
+            // if still not enough free space we rearrange the versions from all files
907
+            if ($availableSpace <= 0) {
908
+                $result = self::getAllVersions($uid);
909
+                $allVersions = $result['all'];
910
+
911
+                foreach ($result['by_file'] as $versions) {
912
+                    [$toDeleteNew, $size] = self::getExpireList($time, $versions, $availableSpace <= 0);
913
+                    $toDelete = array_merge($toDelete, $toDeleteNew);
914
+                    $sizeOfDeletedVersions += $size;
915
+                }
916
+                $availableSpace = $availableSpace + $sizeOfDeletedVersions;
917
+                $versionsSize = $versionsSize - $sizeOfDeletedVersions;
918
+            }
919
+
920
+            foreach ($toDelete as $key => $path) {
921
+                // Make sure to cleanup version table relations as expire does not pass deleteVersion
922
+                try {
923
+                    /** @var VersionsMapper $versionsMapper */
924
+                    $versionsMapper = Server::get(VersionsMapper::class);
925
+                    $file = Server::get(IRootFolder::class)->getUserFolder($uid)->get($filename);
926
+                    $pathparts = pathinfo($path);
927
+                    $timestamp = (int)substr($pathparts['extension'] ?? '', 1);
928
+                    $versionEntity = $versionsMapper->findVersionForFileId($file->getId(), $timestamp);
929
+                    if ($versionEntity->getMetadataValue('label') !== null && $versionEntity->getMetadataValue('label') !== '') {
930
+                        continue;
931
+                    }
932
+                    $versionsMapper->delete($versionEntity);
933
+                } catch (DoesNotExistException $e) {
934
+                }
935
+
936
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
937
+                self::deleteVersion($versionsFileview, $path);
938
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $path, 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
939
+                unset($allVersions[$key]); // update array with the versions we keep
940
+                $logger->info('Expire: ' . $path, ['app' => 'files_versions']);
941
+            }
942
+
943
+            // Check if enough space is available after versions are rearranged.
944
+            // If not we delete the oldest versions until we meet the size limit for versions,
945
+            // but always keep the two latest versions
946
+            $numOfVersions = count($allVersions) - 2 ;
947
+            $i = 0;
948
+            // sort oldest first and make sure that we start at the first element
949
+            ksort($allVersions);
950
+            reset($allVersions);
951
+            while ($availableSpace < 0 && $i < $numOfVersions) {
952
+                $version = current($allVersions);
953
+                \OC_Hook::emit('\OCP\Versions', 'preDelete', ['path' => $version['path'] . '.v' . $version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
954
+                self::deleteVersion($versionsFileview, $version['path'] . '.v' . $version['version']);
955
+                \OC_Hook::emit('\OCP\Versions', 'delete', ['path' => $version['path'] . '.v' . $version['version'], 'trigger' => self::DELETE_TRIGGER_QUOTA_EXCEEDED]);
956
+                $logger->info('running out of space! Delete oldest version: ' . $version['path'] . '.v' . $version['version'], ['app' => 'files_versions']);
957
+                $versionsSize -= $version['size'];
958
+                $availableSpace += $version['size'];
959
+                next($allVersions);
960
+                $i++;
961
+            }
962
+
963
+            return $versionsSize; // finally return the new size of the version history
964
+        }
965
+
966
+        return false;
967
+    }
968
+
969
+    /**
970
+     * Create recursively missing directories inside of files_versions
971
+     * that match the given path to a file.
972
+     *
973
+     * @param string $filename $path to a file, relative to the user's
974
+     *                         "files" folder
975
+     * @param View $view view on data/user/
976
+     */
977
+    public static function createMissingDirectories($filename, $view) {
978
+        $dirname = Filesystem::normalizePath(dirname($filename));
979
+        $dirParts = explode('/', $dirname);
980
+        $dir = '/files_versions';
981
+        foreach ($dirParts as $part) {
982
+            $dir = $dir . '/' . $part;
983
+            if (!$view->file_exists($dir)) {
984
+                $view->mkdir($dir);
985
+            }
986
+        }
987
+    }
988
+
989
+    /**
990
+     * Static workaround
991
+     * @return Expiration
992
+     */
993
+    protected static function getExpiration() {
994
+        if (self::$application === null) {
995
+            self::$application = Server::get(Application::class);
996
+        }
997
+        return self::$application->getContainer()->get(Expiration::class);
998
+    }
999 999
 }
Please login to merge, or discard this patch.