Passed
Push — master ( 7fcf42...997efe )
by Blizzz
41:39 queued 24:50
created
lib/public/Files/File.php 1 patch
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -35,73 +35,73 @@
 block discarded – undo
35 35
  * @since 6.0.0
36 36
  */
37 37
 interface File extends Node {
38
-	/**
39
-	 * Get the content of the file as string
40
-	 *
41
-	 * @return string
42
-	 * @throws NotPermittedException
43
-	 * @throws GenericFileException
44
-	 * @throws LockedException
45
-	 * @since 6.0.0
46
-	 */
47
-	public function getContent();
38
+    /**
39
+     * Get the content of the file as string
40
+     *
41
+     * @return string
42
+     * @throws NotPermittedException
43
+     * @throws GenericFileException
44
+     * @throws LockedException
45
+     * @since 6.0.0
46
+     */
47
+    public function getContent();
48 48
 
49
-	/**
50
-	 * Write to the file from string data
51
-	 *
52
-	 * @param string|resource $data
53
-	 * @throws NotPermittedException
54
-	 * @throws GenericFileException
55
-	 * @throws LockedException
56
-	 * @since 6.0.0
57
-	 */
58
-	public function putContent($data);
49
+    /**
50
+     * Write to the file from string data
51
+     *
52
+     * @param string|resource $data
53
+     * @throws NotPermittedException
54
+     * @throws GenericFileException
55
+     * @throws LockedException
56
+     * @since 6.0.0
57
+     */
58
+    public function putContent($data);
59 59
 
60
-	/**
61
-	 * Get the mimetype of the file
62
-	 *
63
-	 * @return string
64
-	 * @since 6.0.0
65
-	 */
66
-	public function getMimeType();
60
+    /**
61
+     * Get the mimetype of the file
62
+     *
63
+     * @return string
64
+     * @since 6.0.0
65
+     */
66
+    public function getMimeType();
67 67
 
68
-	/**
69
-	 * Open the file as stream, resulting resource can be operated as stream like the result from php's own fopen
70
-	 *
71
-	 * @param string $mode
72
-	 * @return resource|false
73
-	 * @throws NotPermittedException
74
-	 * @throws LockedException
75
-	 * @since 6.0.0
76
-	 */
77
-	public function fopen($mode);
68
+    /**
69
+     * Open the file as stream, resulting resource can be operated as stream like the result from php's own fopen
70
+     *
71
+     * @param string $mode
72
+     * @return resource|false
73
+     * @throws NotPermittedException
74
+     * @throws LockedException
75
+     * @since 6.0.0
76
+     */
77
+    public function fopen($mode);
78 78
 
79
-	/**
80
-	 * Compute the hash of the file
81
-	 * Type of hash is set with $type and can be anything supported by php's hash_file
82
-	 *
83
-	 * @param string $type
84
-	 * @param bool $raw
85
-	 * @return string
86
-	 * @since 6.0.0
87
-	 */
88
-	public function hash($type, $raw = false);
79
+    /**
80
+     * Compute the hash of the file
81
+     * Type of hash is set with $type and can be anything supported by php's hash_file
82
+     *
83
+     * @param string $type
84
+     * @param bool $raw
85
+     * @return string
86
+     * @since 6.0.0
87
+     */
88
+    public function hash($type, $raw = false);
89 89
 
90
-	/**
91
-	 * Get the stored checksum for this file
92
-	 *
93
-	 * @return string
94
-	 * @since 9.0.0
95
-	 * @throws InvalidPathException
96
-	 * @throws NotFoundException
97
-	 */
98
-	public function getChecksum();
90
+    /**
91
+     * Get the stored checksum for this file
92
+     *
93
+     * @return string
94
+     * @since 9.0.0
95
+     * @throws InvalidPathException
96
+     * @throws NotFoundException
97
+     */
98
+    public function getChecksum();
99 99
 
100
-	/**
101
-	 * Get the extension of this file
102
-	 *
103
-	 * @return string
104
-	 * @since 15.0.0
105
-	 */
106
-	public function getExtension(): string;
100
+    /**
101
+     * Get the extension of this file
102
+     *
103
+     * @return string
104
+     * @since 15.0.0
105
+     */
106
+    public function getExtension(): string;
107 107
 }
Please login to merge, or discard this patch.
lib/public/Files/Storage/IStorage.php 1 patch
Indentation   +416 added lines, -416 removed lines patch added patch discarded remove patch
@@ -44,420 +44,420 @@
 block discarded – undo
44 44
  * @since 9.0.0
45 45
  */
46 46
 interface IStorage {
47
-	/**
48
-	 * $parameters is a free form array with the configuration options needed to construct the storage
49
-	 *
50
-	 * @param array $parameters
51
-	 * @since 9.0.0
52
-	 */
53
-	public function __construct($parameters);
54
-
55
-	/**
56
-	 * Get the identifier for the storage,
57
-	 * the returned id should be the same for every storage object that is created with the same parameters
58
-	 * and two storage objects with the same id should refer to two storages that display the same files.
59
-	 *
60
-	 * @return string
61
-	 * @since 9.0.0
62
-	 */
63
-	public function getId();
64
-
65
-	/**
66
-	 * see https://www.php.net/manual/en/function.mkdir.php
67
-	 * implementations need to implement a recursive mkdir
68
-	 *
69
-	 * @param string $path
70
-	 * @return bool
71
-	 * @since 9.0.0
72
-	 */
73
-	public function mkdir($path);
74
-
75
-	/**
76
-	 * see https://www.php.net/manual/en/function.rmdir.php
77
-	 *
78
-	 * @param string $path
79
-	 * @return bool
80
-	 * @since 9.0.0
81
-	 */
82
-	public function rmdir($path);
83
-
84
-	/**
85
-	 * see https://www.php.net/manual/en/function.opendir.php
86
-	 *
87
-	 * @param string $path
88
-	 * @return resource|false
89
-	 * @since 9.0.0
90
-	 */
91
-	public function opendir($path);
92
-
93
-	/**
94
-	 * see https://www.php.net/manual/en/function.is-dir.php
95
-	 *
96
-	 * @param string $path
97
-	 * @return bool
98
-	 * @since 9.0.0
99
-	 */
100
-	public function is_dir($path);
101
-
102
-	/**
103
-	 * see https://www.php.net/manual/en/function.is-file.php
104
-	 *
105
-	 * @param string $path
106
-	 * @return bool
107
-	 * @since 9.0.0
108
-	 */
109
-	public function is_file($path);
110
-
111
-	/**
112
-	 * see https://www.php.net/manual/en/function.stat.php
113
-	 * only the following keys are required in the result: size and mtime
114
-	 *
115
-	 * @param string $path
116
-	 * @return array|bool
117
-	 * @since 9.0.0
118
-	 */
119
-	public function stat($path);
120
-
121
-	/**
122
-	 * see https://www.php.net/manual/en/function.filetype.php
123
-	 *
124
-	 * @param string $path
125
-	 * @return string|bool
126
-	 * @since 9.0.0
127
-	 */
128
-	public function filetype($path);
129
-
130
-	/**
131
-	 * see https://www.php.net/manual/en/function.filesize.php
132
-	 * The result for filesize when called on a folder is required to be 0
133
-	 *
134
-	 * @param string $path
135
-	 * @return false|int|float
136
-	 * @since 9.0.0
137
-	 */
138
-	public function filesize($path);
139
-
140
-	/**
141
-	 * check if a file can be created in $path
142
-	 *
143
-	 * @param string $path
144
-	 * @return bool
145
-	 * @since 9.0.0
146
-	 */
147
-	public function isCreatable($path);
148
-
149
-	/**
150
-	 * check if a file can be read
151
-	 *
152
-	 * @param string $path
153
-	 * @return bool
154
-	 * @since 9.0.0
155
-	 */
156
-	public function isReadable($path);
157
-
158
-	/**
159
-	 * check if a file can be written to
160
-	 *
161
-	 * @param string $path
162
-	 * @return bool
163
-	 * @since 9.0.0
164
-	 */
165
-	public function isUpdatable($path);
166
-
167
-	/**
168
-	 * check if a file can be deleted
169
-	 *
170
-	 * @param string $path
171
-	 * @return bool
172
-	 * @since 9.0.0
173
-	 */
174
-	public function isDeletable($path);
175
-
176
-	/**
177
-	 * check if a file can be shared
178
-	 *
179
-	 * @param string $path
180
-	 * @return bool
181
-	 * @since 9.0.0
182
-	 */
183
-	public function isSharable($path);
184
-
185
-	/**
186
-	 * get the full permissions of a path.
187
-	 * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
188
-	 *
189
-	 * @param string $path
190
-	 * @return int
191
-	 * @since 9.0.0
192
-	 */
193
-	public function getPermissions($path);
194
-
195
-	/**
196
-	 * see https://www.php.net/manual/en/function.file_exists.php
197
-	 *
198
-	 * @param string $path
199
-	 * @return bool
200
-	 * @since 9.0.0
201
-	 */
202
-	public function file_exists($path);
203
-
204
-	/**
205
-	 * see https://www.php.net/manual/en/function.filemtime.php
206
-	 *
207
-	 * @param string $path
208
-	 * @return int|bool
209
-	 * @since 9.0.0
210
-	 */
211
-	public function filemtime($path);
212
-
213
-	/**
214
-	 * see https://www.php.net/manual/en/function.file_get_contents.php
215
-	 *
216
-	 * @param string $path
217
-	 * @return string|false
218
-	 * @since 9.0.0
219
-	 */
220
-	public function file_get_contents($path);
221
-
222
-	/**
223
-	 * see https://www.php.net/manual/en/function.file_put_contents.php
224
-	 *
225
-	 * @param string $path
226
-	 * @param mixed $data
227
-	 * @return int|float|false
228
-	 * @since 9.0.0
229
-	 */
230
-	public function file_put_contents($path, $data);
231
-
232
-	/**
233
-	 * see https://www.php.net/manual/en/function.unlink.php
234
-	 *
235
-	 * @param string $path
236
-	 * @return bool
237
-	 * @since 9.0.0
238
-	 */
239
-	public function unlink($path);
240
-
241
-	/**
242
-	 * see https://www.php.net/manual/en/function.rename.php
243
-	 *
244
-	 * @param string $source
245
-	 * @param string $target
246
-	 * @return bool
247
-	 * @since 9.0.0
248
-	 */
249
-	public function rename($source, $target);
250
-
251
-	/**
252
-	 * see https://www.php.net/manual/en/function.copy.php
253
-	 *
254
-	 * @param string $source
255
-	 * @param string $target
256
-	 * @return bool
257
-	 * @since 9.0.0
258
-	 */
259
-	public function copy($source, $target);
260
-
261
-	/**
262
-	 * see https://www.php.net/manual/en/function.fopen.php
263
-	 *
264
-	 * @param string $path
265
-	 * @param string $mode
266
-	 * @return resource|bool
267
-	 * @since 9.0.0
268
-	 */
269
-	public function fopen($path, $mode);
270
-
271
-	/**
272
-	 * get the mimetype for a file or folder
273
-	 * The mimetype for a folder is required to be "httpd/unix-directory"
274
-	 *
275
-	 * @param string $path
276
-	 * @return string|bool
277
-	 * @since 9.0.0
278
-	 */
279
-	public function getMimeType($path);
280
-
281
-	/**
282
-	 * see https://www.php.net/manual/en/function.hash-file.php
283
-	 *
284
-	 * @param string $type
285
-	 * @param string $path
286
-	 * @param bool $raw
287
-	 * @return string|bool
288
-	 * @since 9.0.0
289
-	 */
290
-	public function hash($type, $path, $raw = false);
291
-
292
-	/**
293
-	 * see https://www.php.net/manual/en/function.free_space.php
294
-	 *
295
-	 * @param string $path
296
-	 * @return int|float|bool
297
-	 * @since 9.0.0
298
-	 */
299
-	public function free_space($path);
300
-
301
-	/**
302
-	 * see https://www.php.net/manual/en/function.touch.php
303
-	 * If the backend does not support the operation, false should be returned
304
-	 *
305
-	 * @param string $path
306
-	 * @param int $mtime
307
-	 * @return bool
308
-	 * @since 9.0.0
309
-	 */
310
-	public function touch($path, $mtime = null);
311
-
312
-	/**
313
-	 * get the path to a local version of the file.
314
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
315
-	 *
316
-	 * @param string $path
317
-	 * @return string|false
318
-	 * @since 9.0.0
319
-	 */
320
-	public function getLocalFile($path);
321
-
322
-	/**
323
-	 * check if a file or folder has been updated since $time
324
-	 *
325
-	 * @param string $path
326
-	 * @param int $time
327
-	 * @return bool
328
-	 * @since 9.0.0
329
-	 *
330
-	 * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
331
-	 * returning true for other changes in the folder is optional
332
-	 */
333
-	public function hasUpdated($path, $time);
334
-
335
-	/**
336
-	 * get the ETag for a file or folder
337
-	 *
338
-	 * @param string $path
339
-	 * @return string|false
340
-	 * @since 9.0.0
341
-	 */
342
-	public function getETag($path);
343
-
344
-	/**
345
-	 * Returns whether the storage is local, which means that files
346
-	 * are stored on the local filesystem instead of remotely.
347
-	 * Calling getLocalFile() for local storages should always
348
-	 * return the local files, whereas for non-local storages
349
-	 * it might return a temporary file.
350
-	 *
351
-	 * @return bool true if the files are stored locally, false otherwise
352
-	 * @since 9.0.0
353
-	 */
354
-	public function isLocal();
355
-
356
-	/**
357
-	 * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
358
-	 *
359
-	 * @template T of IStorage
360
-	 * @param string $class
361
-	 * @psalm-param class-string<T> $class
362
-	 * @return bool
363
-	 * @since 9.0.0
364
-	 * @psalm-assert-if-true T $this
365
-	 */
366
-	public function instanceOfStorage($class);
367
-
368
-	/**
369
-	 * A custom storage implementation can return an url for direct download of a give file.
370
-	 *
371
-	 * For now the returned array can hold the parameter url - in future more attributes might follow.
372
-	 *
373
-	 * @param string $path
374
-	 * @return array|bool
375
-	 * @since 9.0.0
376
-	 */
377
-	public function getDirectDownload($path);
378
-
379
-	/**
380
-	 * @param string $path the path of the target folder
381
-	 * @param string $fileName the name of the file itself
382
-	 * @return void
383
-	 * @throws InvalidPathException
384
-	 * @since 9.0.0
385
-	 */
386
-	public function verifyPath($path, $fileName);
387
-
388
-	/**
389
-	 * @param IStorage $sourceStorage
390
-	 * @param string $sourceInternalPath
391
-	 * @param string $targetInternalPath
392
-	 * @return bool
393
-	 * @since 9.0.0
394
-	 */
395
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
396
-
397
-	/**
398
-	 * @param IStorage $sourceStorage
399
-	 * @param string $sourceInternalPath
400
-	 * @param string $targetInternalPath
401
-	 * @return bool
402
-	 * @since 9.0.0
403
-	 */
404
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
405
-
406
-	/**
407
-	 * Test a storage for availability
408
-	 *
409
-	 * @since 9.0.0
410
-	 * @return bool
411
-	 */
412
-	public function test();
413
-
414
-	/**
415
-	 * @since 9.0.0
416
-	 * @return array [ available, last_checked ]
417
-	 */
418
-	public function getAvailability();
419
-
420
-	/**
421
-	 * @since 9.0.0
422
-	 * @param bool $isAvailable
423
-	 */
424
-	public function setAvailability($isAvailable);
425
-
426
-	/**
427
-	 * @param string $path path for which to retrieve the owner
428
-	 * @since 9.0.0
429
-	 */
430
-	public function getOwner($path);
431
-
432
-	/**
433
-	 * @param string $path
434
-	 * @param IStorage|null $storage
435
-	 * @return ICache
436
-	 * @since 9.0.0
437
-	 */
438
-	public function getCache($path = '', $storage = null);
439
-
440
-	/**
441
-	 * @return IPropagator
442
-	 * @since 9.0.0
443
-	 */
444
-	public function getPropagator();
445
-
446
-	/**
447
-	 * @return IScanner
448
-	 * @since 9.0.0
449
-	 */
450
-	public function getScanner();
451
-
452
-	/**
453
-	 * @return IUpdater
454
-	 * @since 9.0.0
455
-	 */
456
-	public function getUpdater();
457
-
458
-	/**
459
-	 * @return IWatcher
460
-	 * @since 9.0.0
461
-	 */
462
-	public function getWatcher();
47
+    /**
48
+     * $parameters is a free form array with the configuration options needed to construct the storage
49
+     *
50
+     * @param array $parameters
51
+     * @since 9.0.0
52
+     */
53
+    public function __construct($parameters);
54
+
55
+    /**
56
+     * Get the identifier for the storage,
57
+     * the returned id should be the same for every storage object that is created with the same parameters
58
+     * and two storage objects with the same id should refer to two storages that display the same files.
59
+     *
60
+     * @return string
61
+     * @since 9.0.0
62
+     */
63
+    public function getId();
64
+
65
+    /**
66
+     * see https://www.php.net/manual/en/function.mkdir.php
67
+     * implementations need to implement a recursive mkdir
68
+     *
69
+     * @param string $path
70
+     * @return bool
71
+     * @since 9.0.0
72
+     */
73
+    public function mkdir($path);
74
+
75
+    /**
76
+     * see https://www.php.net/manual/en/function.rmdir.php
77
+     *
78
+     * @param string $path
79
+     * @return bool
80
+     * @since 9.0.0
81
+     */
82
+    public function rmdir($path);
83
+
84
+    /**
85
+     * see https://www.php.net/manual/en/function.opendir.php
86
+     *
87
+     * @param string $path
88
+     * @return resource|false
89
+     * @since 9.0.0
90
+     */
91
+    public function opendir($path);
92
+
93
+    /**
94
+     * see https://www.php.net/manual/en/function.is-dir.php
95
+     *
96
+     * @param string $path
97
+     * @return bool
98
+     * @since 9.0.0
99
+     */
100
+    public function is_dir($path);
101
+
102
+    /**
103
+     * see https://www.php.net/manual/en/function.is-file.php
104
+     *
105
+     * @param string $path
106
+     * @return bool
107
+     * @since 9.0.0
108
+     */
109
+    public function is_file($path);
110
+
111
+    /**
112
+     * see https://www.php.net/manual/en/function.stat.php
113
+     * only the following keys are required in the result: size and mtime
114
+     *
115
+     * @param string $path
116
+     * @return array|bool
117
+     * @since 9.0.0
118
+     */
119
+    public function stat($path);
120
+
121
+    /**
122
+     * see https://www.php.net/manual/en/function.filetype.php
123
+     *
124
+     * @param string $path
125
+     * @return string|bool
126
+     * @since 9.0.0
127
+     */
128
+    public function filetype($path);
129
+
130
+    /**
131
+     * see https://www.php.net/manual/en/function.filesize.php
132
+     * The result for filesize when called on a folder is required to be 0
133
+     *
134
+     * @param string $path
135
+     * @return false|int|float
136
+     * @since 9.0.0
137
+     */
138
+    public function filesize($path);
139
+
140
+    /**
141
+     * check if a file can be created in $path
142
+     *
143
+     * @param string $path
144
+     * @return bool
145
+     * @since 9.0.0
146
+     */
147
+    public function isCreatable($path);
148
+
149
+    /**
150
+     * check if a file can be read
151
+     *
152
+     * @param string $path
153
+     * @return bool
154
+     * @since 9.0.0
155
+     */
156
+    public function isReadable($path);
157
+
158
+    /**
159
+     * check if a file can be written to
160
+     *
161
+     * @param string $path
162
+     * @return bool
163
+     * @since 9.0.0
164
+     */
165
+    public function isUpdatable($path);
166
+
167
+    /**
168
+     * check if a file can be deleted
169
+     *
170
+     * @param string $path
171
+     * @return bool
172
+     * @since 9.0.0
173
+     */
174
+    public function isDeletable($path);
175
+
176
+    /**
177
+     * check if a file can be shared
178
+     *
179
+     * @param string $path
180
+     * @return bool
181
+     * @since 9.0.0
182
+     */
183
+    public function isSharable($path);
184
+
185
+    /**
186
+     * get the full permissions of a path.
187
+     * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
188
+     *
189
+     * @param string $path
190
+     * @return int
191
+     * @since 9.0.0
192
+     */
193
+    public function getPermissions($path);
194
+
195
+    /**
196
+     * see https://www.php.net/manual/en/function.file_exists.php
197
+     *
198
+     * @param string $path
199
+     * @return bool
200
+     * @since 9.0.0
201
+     */
202
+    public function file_exists($path);
203
+
204
+    /**
205
+     * see https://www.php.net/manual/en/function.filemtime.php
206
+     *
207
+     * @param string $path
208
+     * @return int|bool
209
+     * @since 9.0.0
210
+     */
211
+    public function filemtime($path);
212
+
213
+    /**
214
+     * see https://www.php.net/manual/en/function.file_get_contents.php
215
+     *
216
+     * @param string $path
217
+     * @return string|false
218
+     * @since 9.0.0
219
+     */
220
+    public function file_get_contents($path);
221
+
222
+    /**
223
+     * see https://www.php.net/manual/en/function.file_put_contents.php
224
+     *
225
+     * @param string $path
226
+     * @param mixed $data
227
+     * @return int|float|false
228
+     * @since 9.0.0
229
+     */
230
+    public function file_put_contents($path, $data);
231
+
232
+    /**
233
+     * see https://www.php.net/manual/en/function.unlink.php
234
+     *
235
+     * @param string $path
236
+     * @return bool
237
+     * @since 9.0.0
238
+     */
239
+    public function unlink($path);
240
+
241
+    /**
242
+     * see https://www.php.net/manual/en/function.rename.php
243
+     *
244
+     * @param string $source
245
+     * @param string $target
246
+     * @return bool
247
+     * @since 9.0.0
248
+     */
249
+    public function rename($source, $target);
250
+
251
+    /**
252
+     * see https://www.php.net/manual/en/function.copy.php
253
+     *
254
+     * @param string $source
255
+     * @param string $target
256
+     * @return bool
257
+     * @since 9.0.0
258
+     */
259
+    public function copy($source, $target);
260
+
261
+    /**
262
+     * see https://www.php.net/manual/en/function.fopen.php
263
+     *
264
+     * @param string $path
265
+     * @param string $mode
266
+     * @return resource|bool
267
+     * @since 9.0.0
268
+     */
269
+    public function fopen($path, $mode);
270
+
271
+    /**
272
+     * get the mimetype for a file or folder
273
+     * The mimetype for a folder is required to be "httpd/unix-directory"
274
+     *
275
+     * @param string $path
276
+     * @return string|bool
277
+     * @since 9.0.0
278
+     */
279
+    public function getMimeType($path);
280
+
281
+    /**
282
+     * see https://www.php.net/manual/en/function.hash-file.php
283
+     *
284
+     * @param string $type
285
+     * @param string $path
286
+     * @param bool $raw
287
+     * @return string|bool
288
+     * @since 9.0.0
289
+     */
290
+    public function hash($type, $path, $raw = false);
291
+
292
+    /**
293
+     * see https://www.php.net/manual/en/function.free_space.php
294
+     *
295
+     * @param string $path
296
+     * @return int|float|bool
297
+     * @since 9.0.0
298
+     */
299
+    public function free_space($path);
300
+
301
+    /**
302
+     * see https://www.php.net/manual/en/function.touch.php
303
+     * If the backend does not support the operation, false should be returned
304
+     *
305
+     * @param string $path
306
+     * @param int $mtime
307
+     * @return bool
308
+     * @since 9.0.0
309
+     */
310
+    public function touch($path, $mtime = null);
311
+
312
+    /**
313
+     * get the path to a local version of the file.
314
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
315
+     *
316
+     * @param string $path
317
+     * @return string|false
318
+     * @since 9.0.0
319
+     */
320
+    public function getLocalFile($path);
321
+
322
+    /**
323
+     * check if a file or folder has been updated since $time
324
+     *
325
+     * @param string $path
326
+     * @param int $time
327
+     * @return bool
328
+     * @since 9.0.0
329
+     *
330
+     * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
331
+     * returning true for other changes in the folder is optional
332
+     */
333
+    public function hasUpdated($path, $time);
334
+
335
+    /**
336
+     * get the ETag for a file or folder
337
+     *
338
+     * @param string $path
339
+     * @return string|false
340
+     * @since 9.0.0
341
+     */
342
+    public function getETag($path);
343
+
344
+    /**
345
+     * Returns whether the storage is local, which means that files
346
+     * are stored on the local filesystem instead of remotely.
347
+     * Calling getLocalFile() for local storages should always
348
+     * return the local files, whereas for non-local storages
349
+     * it might return a temporary file.
350
+     *
351
+     * @return bool true if the files are stored locally, false otherwise
352
+     * @since 9.0.0
353
+     */
354
+    public function isLocal();
355
+
356
+    /**
357
+     * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
358
+     *
359
+     * @template T of IStorage
360
+     * @param string $class
361
+     * @psalm-param class-string<T> $class
362
+     * @return bool
363
+     * @since 9.0.0
364
+     * @psalm-assert-if-true T $this
365
+     */
366
+    public function instanceOfStorage($class);
367
+
368
+    /**
369
+     * A custom storage implementation can return an url for direct download of a give file.
370
+     *
371
+     * For now the returned array can hold the parameter url - in future more attributes might follow.
372
+     *
373
+     * @param string $path
374
+     * @return array|bool
375
+     * @since 9.0.0
376
+     */
377
+    public function getDirectDownload($path);
378
+
379
+    /**
380
+     * @param string $path the path of the target folder
381
+     * @param string $fileName the name of the file itself
382
+     * @return void
383
+     * @throws InvalidPathException
384
+     * @since 9.0.0
385
+     */
386
+    public function verifyPath($path, $fileName);
387
+
388
+    /**
389
+     * @param IStorage $sourceStorage
390
+     * @param string $sourceInternalPath
391
+     * @param string $targetInternalPath
392
+     * @return bool
393
+     * @since 9.0.0
394
+     */
395
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
396
+
397
+    /**
398
+     * @param IStorage $sourceStorage
399
+     * @param string $sourceInternalPath
400
+     * @param string $targetInternalPath
401
+     * @return bool
402
+     * @since 9.0.0
403
+     */
404
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
405
+
406
+    /**
407
+     * Test a storage for availability
408
+     *
409
+     * @since 9.0.0
410
+     * @return bool
411
+     */
412
+    public function test();
413
+
414
+    /**
415
+     * @since 9.0.0
416
+     * @return array [ available, last_checked ]
417
+     */
418
+    public function getAvailability();
419
+
420
+    /**
421
+     * @since 9.0.0
422
+     * @param bool $isAvailable
423
+     */
424
+    public function setAvailability($isAvailable);
425
+
426
+    /**
427
+     * @param string $path path for which to retrieve the owner
428
+     * @since 9.0.0
429
+     */
430
+    public function getOwner($path);
431
+
432
+    /**
433
+     * @param string $path
434
+     * @param IStorage|null $storage
435
+     * @return ICache
436
+     * @since 9.0.0
437
+     */
438
+    public function getCache($path = '', $storage = null);
439
+
440
+    /**
441
+     * @return IPropagator
442
+     * @since 9.0.0
443
+     */
444
+    public function getPropagator();
445
+
446
+    /**
447
+     * @return IScanner
448
+     * @since 9.0.0
449
+     */
450
+    public function getScanner();
451
+
452
+    /**
453
+     * @return IUpdater
454
+     * @since 9.0.0
455
+     */
456
+    public function getUpdater();
457
+
458
+    /**
459
+     * @return IWatcher
460
+     * @since 9.0.0
461
+     */
462
+    public function getWatcher();
463 463
 }
Please login to merge, or discard this patch.
lib/public/Files/Storage.php 1 patch
Indentation   +420 added lines, -420 removed lines patch added patch discarded remove patch
@@ -47,424 +47,424 @@
 block discarded – undo
47 47
  * @deprecated 9.0.0 use \OCP\Files\Storage\IStorage instead
48 48
  */
49 49
 interface Storage extends IStorage {
50
-	/**
51
-	 * $parameters is a free form array with the configuration options needed to construct the storage
52
-	 *
53
-	 * @param array $parameters
54
-	 * @since 6.0.0
55
-	 */
56
-	public function __construct($parameters);
57
-
58
-	/**
59
-	 * Get the identifier for the storage,
60
-	 * the returned id should be the same for every storage object that is created with the same parameters
61
-	 * and two storage objects with the same id should refer to two storages that display the same files.
62
-	 *
63
-	 * @return string
64
-	 * @since 6.0.0
65
-	 */
66
-	public function getId();
67
-
68
-	/**
69
-	 * see https://www.php.net/manual/en/function.mkdir.php
70
-	 * implementations need to implement a recursive mkdir
71
-	 *
72
-	 * @param string $path
73
-	 * @return bool
74
-	 * @since 6.0.0
75
-	 */
76
-	public function mkdir($path);
77
-
78
-	/**
79
-	 * see https://www.php.net/manual/en/function.rmdir.php
80
-	 *
81
-	 * @param string $path
82
-	 * @return bool
83
-	 * @since 6.0.0
84
-	 */
85
-	public function rmdir($path);
86
-
87
-	/**
88
-	 * see https://www.php.net/manual/en/function.opendir.php
89
-	 *
90
-	 * @param string $path
91
-	 * @return resource|false
92
-	 * @since 6.0.0
93
-	 */
94
-	public function opendir($path);
95
-
96
-	/**
97
-	 * see https://www.php.net/manual/en/function.is-dir.php
98
-	 *
99
-	 * @param string $path
100
-	 * @return bool
101
-	 * @since 6.0.0
102
-	 */
103
-	public function is_dir($path);
104
-
105
-	/**
106
-	 * see https://www.php.net/manual/en/function.is-file.php
107
-	 *
108
-	 * @param string $path
109
-	 * @return bool
110
-	 * @since 6.0.0
111
-	 */
112
-	public function is_file($path);
113
-
114
-	/**
115
-	 * see https://www.php.net/manual/en/function.stat.php
116
-	 * only the following keys are required in the result: size and mtime
117
-	 *
118
-	 * @param string $path
119
-	 * @return array|bool
120
-	 * @since 6.0.0
121
-	 */
122
-	public function stat($path);
123
-
124
-	/**
125
-	 * see https://www.php.net/manual/en/function.filetype.php
126
-	 *
127
-	 * @param string $path
128
-	 * @return string|bool
129
-	 * @since 6.0.0
130
-	 */
131
-	public function filetype($path);
132
-
133
-	/**
134
-	 * see https://www.php.net/manual/en/function.filesize.php
135
-	 * The result for filesize when called on a folder is required to be 0
136
-	 *
137
-	 * @param string $path
138
-	 * @return false|int|float
139
-	 * @since 6.0.0
140
-	 */
141
-	public function filesize($path);
142
-
143
-	/**
144
-	 * check if a file can be created in $path
145
-	 *
146
-	 * @param string $path
147
-	 * @return bool
148
-	 * @since 6.0.0
149
-	 */
150
-	public function isCreatable($path);
151
-
152
-	/**
153
-	 * check if a file can be read
154
-	 *
155
-	 * @param string $path
156
-	 * @return bool
157
-	 * @since 6.0.0
158
-	 */
159
-	public function isReadable($path);
160
-
161
-	/**
162
-	 * check if a file can be written to
163
-	 *
164
-	 * @param string $path
165
-	 * @return bool
166
-	 * @since 6.0.0
167
-	 */
168
-	public function isUpdatable($path);
169
-
170
-	/**
171
-	 * check if a file can be deleted
172
-	 *
173
-	 * @param string $path
174
-	 * @return bool
175
-	 * @since 6.0.0
176
-	 */
177
-	public function isDeletable($path);
178
-
179
-	/**
180
-	 * check if a file can be shared
181
-	 *
182
-	 * @param string $path
183
-	 * @return bool
184
-	 * @since 6.0.0
185
-	 */
186
-	public function isSharable($path);
187
-
188
-	/**
189
-	 * get the full permissions of a path.
190
-	 * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
191
-	 *
192
-	 * @param string $path
193
-	 * @return int
194
-	 * @since 6.0.0
195
-	 */
196
-	public function getPermissions($path);
197
-
198
-	/**
199
-	 * see https://www.php.net/manual/en/function.file_exists.php
200
-	 *
201
-	 * @param string $path
202
-	 * @return bool
203
-	 * @since 6.0.0
204
-	 */
205
-	public function file_exists($path);
206
-
207
-	/**
208
-	 * see https://www.php.net/manual/en/function.filemtime.php
209
-	 *
210
-	 * @param string $path
211
-	 * @return int|bool
212
-	 * @since 6.0.0
213
-	 */
214
-	public function filemtime($path);
215
-
216
-	/**
217
-	 * see https://www.php.net/manual/en/function.file_get_contents.php
218
-	 *
219
-	 * @param string $path
220
-	 * @return string|false
221
-	 * @since 6.0.0
222
-	 */
223
-	public function file_get_contents($path);
224
-
225
-	/**
226
-	 * see https://www.php.net/manual/en/function.file_put_contents.php
227
-	 *
228
-	 * @param string $path
229
-	 * @param mixed $data
230
-	 * @return int|float|false
231
-	 * @since 6.0.0
232
-	 */
233
-	public function file_put_contents($path, $data);
234
-
235
-	/**
236
-	 * see https://www.php.net/manual/en/function.unlink.php
237
-	 *
238
-	 * @param string $path
239
-	 * @return bool
240
-	 * @since 6.0.0
241
-	 */
242
-	public function unlink($path);
243
-
244
-	/**
245
-	 * see https://www.php.net/manual/en/function.rename.php
246
-	 *
247
-	 * @param string $source
248
-	 * @param string $target
249
-	 * @return bool
250
-	 * @since 6.0.0
251
-	 */
252
-	public function rename($source, $target);
253
-
254
-	/**
255
-	 * see https://www.php.net/manual/en/function.copy.php
256
-	 *
257
-	 * @param string $source
258
-	 * @param string $target
259
-	 * @return bool
260
-	 * @since 6.0.0
261
-	 */
262
-	public function copy($source, $target);
263
-
264
-	/**
265
-	 * see https://www.php.net/manual/en/function.fopen.php
266
-	 *
267
-	 * @param string $path
268
-	 * @param string $mode
269
-	 * @return resource|bool
270
-	 * @since 6.0.0
271
-	 */
272
-	public function fopen($path, $mode);
273
-
274
-	/**
275
-	 * get the mimetype for a file or folder
276
-	 * The mimetype for a folder is required to be "httpd/unix-directory"
277
-	 *
278
-	 * @param string $path
279
-	 * @return string|bool
280
-	 * @since 6.0.0
281
-	 */
282
-	public function getMimeType($path);
283
-
284
-	/**
285
-	 * see https://www.php.net/manual/en/function.hash-file.php
286
-	 *
287
-	 * @param string $type
288
-	 * @param string $path
289
-	 * @param bool $raw
290
-	 * @return string|bool
291
-	 * @since 6.0.0
292
-	 */
293
-	public function hash($type, $path, $raw = false);
294
-
295
-	/**
296
-	 * see https://www.php.net/manual/en/function.disk-free-space.php
297
-	 *
298
-	 * @param string $path
299
-	 * @return int|float|bool
300
-	 * @since 6.0.0
301
-	 */
302
-	public function free_space($path);
303
-
304
-	/**
305
-	 * search for occurrences of $query in file names
306
-	 *
307
-	 * @param string $query
308
-	 * @return array|bool
309
-	 * @since 6.0.0
310
-	 */
311
-	public function search($query);
312
-
313
-	/**
314
-	 * see https://www.php.net/manual/en/function.touch.php
315
-	 * If the backend does not support the operation, false should be returned
316
-	 *
317
-	 * @param string $path
318
-	 * @param int $mtime
319
-	 * @return bool
320
-	 * @since 6.0.0
321
-	 */
322
-	public function touch($path, $mtime = null);
323
-
324
-	/**
325
-	 * get the path to a local version of the file.
326
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
327
-	 *
328
-	 * @param string $path
329
-	 * @return string|false
330
-	 * @since 6.0.0
331
-	 */
332
-	public function getLocalFile($path);
333
-
334
-	/**
335
-	 * check if a file or folder has been updated since $time
336
-	 *
337
-	 * @param string $path
338
-	 * @param int $time
339
-	 * @return bool
340
-	 * @since 6.0.0
341
-	 *
342
-	 * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
343
-	 * returning true for other changes in the folder is optional
344
-	 */
345
-	public function hasUpdated($path, $time);
346
-
347
-	/**
348
-	 * get the ETag for a file or folder
349
-	 *
350
-	 * @param string $path
351
-	 * @return string|false
352
-	 * @since 6.0.0
353
-	 */
354
-	public function getETag($path);
355
-
356
-	/**
357
-	 * Returns whether the storage is local, which means that files
358
-	 * are stored on the local filesystem instead of remotely.
359
-	 * Calling getLocalFile() for local storages should always
360
-	 * return the local files, whereas for non-local storages
361
-	 * it might return a temporary file.
362
-	 *
363
-	 * @return bool true if the files are stored locally, false otherwise
364
-	 * @since 7.0.0
365
-	 */
366
-	public function isLocal();
367
-
368
-	/**
369
-	 * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
370
-	 *
371
-	 * @template T of IStorage
372
-	 * @param string $class
373
-	 * @psalm-param class-string<T> $class
374
-	 * @return bool
375
-	 * @since 7.0.0
376
-	 * @psalm-assert-if-true T $this
377
-	 */
378
-	public function instanceOfStorage($class);
379
-
380
-	/**
381
-	 * A custom storage implementation can return an url for direct download of a give file.
382
-	 *
383
-	 * For now the returned array can hold the parameter url - in future more attributes might follow.
384
-	 *
385
-	 * @param string $path
386
-	 * @return array|bool
387
-	 * @since 8.0.0
388
-	 */
389
-	public function getDirectDownload($path);
390
-
391
-	/**
392
-	 * @param string $path the path of the target folder
393
-	 * @param string $fileName the name of the file itself
394
-	 * @return void
395
-	 * @throws InvalidPathException
396
-	 * @since 8.1.0
397
-	 */
398
-	public function verifyPath($path, $fileName);
399
-
400
-	/**
401
-	 * @param IStorage $sourceStorage
402
-	 * @param string $sourceInternalPath
403
-	 * @param string $targetInternalPath
404
-	 * @return bool
405
-	 * @since 8.1.0
406
-	 */
407
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
408
-
409
-	/**
410
-	 * @param IStorage $sourceStorage
411
-	 * @param string $sourceInternalPath
412
-	 * @param string $targetInternalPath
413
-	 * @return bool
414
-	 * @since 8.1.0
415
-	 */
416
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
417
-
418
-	/**
419
-	 * @param string $path The path of the file to acquire the lock for
420
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
421
-	 * @param \OCP\Lock\ILockingProvider $provider
422
-	 * @throws \OCP\Lock\LockedException
423
-	 * @since 8.1.0
424
-	 */
425
-	public function acquireLock($path, $type, ILockingProvider $provider);
426
-
427
-	/**
428
-	 * @param string $path The path of the file to acquire the lock for
429
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
430
-	 * @param \OCP\Lock\ILockingProvider $provider
431
-	 * @throws \OCP\Lock\LockedException
432
-	 * @since 8.1.0
433
-	 */
434
-	public function releaseLock($path, $type, ILockingProvider $provider);
435
-
436
-	/**
437
-	 * @param string $path The path of the file to change the lock for
438
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
439
-	 * @param \OCP\Lock\ILockingProvider $provider
440
-	 * @throws \OCP\Lock\LockedException
441
-	 * @since 8.1.0
442
-	 */
443
-	public function changeLock($path, $type, ILockingProvider $provider);
444
-
445
-	/**
446
-	 * Test a storage for availability
447
-	 *
448
-	 * @since 8.2.0
449
-	 * @return bool
450
-	 */
451
-	public function test();
452
-
453
-	/**
454
-	 * @since 8.2.0
455
-	 * @return array [ available, last_checked ]
456
-	 */
457
-	public function getAvailability();
458
-
459
-	/**
460
-	 * @since 8.2.0
461
-	 * @param bool $isAvailable
462
-	 */
463
-	public function setAvailability($isAvailable);
464
-
465
-	/**
466
-	 * @since 12.0.0
467
-	 * @return mixed
468
-	 */
469
-	public function needsPartFile();
50
+    /**
51
+     * $parameters is a free form array with the configuration options needed to construct the storage
52
+     *
53
+     * @param array $parameters
54
+     * @since 6.0.0
55
+     */
56
+    public function __construct($parameters);
57
+
58
+    /**
59
+     * Get the identifier for the storage,
60
+     * the returned id should be the same for every storage object that is created with the same parameters
61
+     * and two storage objects with the same id should refer to two storages that display the same files.
62
+     *
63
+     * @return string
64
+     * @since 6.0.0
65
+     */
66
+    public function getId();
67
+
68
+    /**
69
+     * see https://www.php.net/manual/en/function.mkdir.php
70
+     * implementations need to implement a recursive mkdir
71
+     *
72
+     * @param string $path
73
+     * @return bool
74
+     * @since 6.0.0
75
+     */
76
+    public function mkdir($path);
77
+
78
+    /**
79
+     * see https://www.php.net/manual/en/function.rmdir.php
80
+     *
81
+     * @param string $path
82
+     * @return bool
83
+     * @since 6.0.0
84
+     */
85
+    public function rmdir($path);
86
+
87
+    /**
88
+     * see https://www.php.net/manual/en/function.opendir.php
89
+     *
90
+     * @param string $path
91
+     * @return resource|false
92
+     * @since 6.0.0
93
+     */
94
+    public function opendir($path);
95
+
96
+    /**
97
+     * see https://www.php.net/manual/en/function.is-dir.php
98
+     *
99
+     * @param string $path
100
+     * @return bool
101
+     * @since 6.0.0
102
+     */
103
+    public function is_dir($path);
104
+
105
+    /**
106
+     * see https://www.php.net/manual/en/function.is-file.php
107
+     *
108
+     * @param string $path
109
+     * @return bool
110
+     * @since 6.0.0
111
+     */
112
+    public function is_file($path);
113
+
114
+    /**
115
+     * see https://www.php.net/manual/en/function.stat.php
116
+     * only the following keys are required in the result: size and mtime
117
+     *
118
+     * @param string $path
119
+     * @return array|bool
120
+     * @since 6.0.0
121
+     */
122
+    public function stat($path);
123
+
124
+    /**
125
+     * see https://www.php.net/manual/en/function.filetype.php
126
+     *
127
+     * @param string $path
128
+     * @return string|bool
129
+     * @since 6.0.0
130
+     */
131
+    public function filetype($path);
132
+
133
+    /**
134
+     * see https://www.php.net/manual/en/function.filesize.php
135
+     * The result for filesize when called on a folder is required to be 0
136
+     *
137
+     * @param string $path
138
+     * @return false|int|float
139
+     * @since 6.0.0
140
+     */
141
+    public function filesize($path);
142
+
143
+    /**
144
+     * check if a file can be created in $path
145
+     *
146
+     * @param string $path
147
+     * @return bool
148
+     * @since 6.0.0
149
+     */
150
+    public function isCreatable($path);
151
+
152
+    /**
153
+     * check if a file can be read
154
+     *
155
+     * @param string $path
156
+     * @return bool
157
+     * @since 6.0.0
158
+     */
159
+    public function isReadable($path);
160
+
161
+    /**
162
+     * check if a file can be written to
163
+     *
164
+     * @param string $path
165
+     * @return bool
166
+     * @since 6.0.0
167
+     */
168
+    public function isUpdatable($path);
169
+
170
+    /**
171
+     * check if a file can be deleted
172
+     *
173
+     * @param string $path
174
+     * @return bool
175
+     * @since 6.0.0
176
+     */
177
+    public function isDeletable($path);
178
+
179
+    /**
180
+     * check if a file can be shared
181
+     *
182
+     * @param string $path
183
+     * @return bool
184
+     * @since 6.0.0
185
+     */
186
+    public function isSharable($path);
187
+
188
+    /**
189
+     * get the full permissions of a path.
190
+     * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
191
+     *
192
+     * @param string $path
193
+     * @return int
194
+     * @since 6.0.0
195
+     */
196
+    public function getPermissions($path);
197
+
198
+    /**
199
+     * see https://www.php.net/manual/en/function.file_exists.php
200
+     *
201
+     * @param string $path
202
+     * @return bool
203
+     * @since 6.0.0
204
+     */
205
+    public function file_exists($path);
206
+
207
+    /**
208
+     * see https://www.php.net/manual/en/function.filemtime.php
209
+     *
210
+     * @param string $path
211
+     * @return int|bool
212
+     * @since 6.0.0
213
+     */
214
+    public function filemtime($path);
215
+
216
+    /**
217
+     * see https://www.php.net/manual/en/function.file_get_contents.php
218
+     *
219
+     * @param string $path
220
+     * @return string|false
221
+     * @since 6.0.0
222
+     */
223
+    public function file_get_contents($path);
224
+
225
+    /**
226
+     * see https://www.php.net/manual/en/function.file_put_contents.php
227
+     *
228
+     * @param string $path
229
+     * @param mixed $data
230
+     * @return int|float|false
231
+     * @since 6.0.0
232
+     */
233
+    public function file_put_contents($path, $data);
234
+
235
+    /**
236
+     * see https://www.php.net/manual/en/function.unlink.php
237
+     *
238
+     * @param string $path
239
+     * @return bool
240
+     * @since 6.0.0
241
+     */
242
+    public function unlink($path);
243
+
244
+    /**
245
+     * see https://www.php.net/manual/en/function.rename.php
246
+     *
247
+     * @param string $source
248
+     * @param string $target
249
+     * @return bool
250
+     * @since 6.0.0
251
+     */
252
+    public function rename($source, $target);
253
+
254
+    /**
255
+     * see https://www.php.net/manual/en/function.copy.php
256
+     *
257
+     * @param string $source
258
+     * @param string $target
259
+     * @return bool
260
+     * @since 6.0.0
261
+     */
262
+    public function copy($source, $target);
263
+
264
+    /**
265
+     * see https://www.php.net/manual/en/function.fopen.php
266
+     *
267
+     * @param string $path
268
+     * @param string $mode
269
+     * @return resource|bool
270
+     * @since 6.0.0
271
+     */
272
+    public function fopen($path, $mode);
273
+
274
+    /**
275
+     * get the mimetype for a file or folder
276
+     * The mimetype for a folder is required to be "httpd/unix-directory"
277
+     *
278
+     * @param string $path
279
+     * @return string|bool
280
+     * @since 6.0.0
281
+     */
282
+    public function getMimeType($path);
283
+
284
+    /**
285
+     * see https://www.php.net/manual/en/function.hash-file.php
286
+     *
287
+     * @param string $type
288
+     * @param string $path
289
+     * @param bool $raw
290
+     * @return string|bool
291
+     * @since 6.0.0
292
+     */
293
+    public function hash($type, $path, $raw = false);
294
+
295
+    /**
296
+     * see https://www.php.net/manual/en/function.disk-free-space.php
297
+     *
298
+     * @param string $path
299
+     * @return int|float|bool
300
+     * @since 6.0.0
301
+     */
302
+    public function free_space($path);
303
+
304
+    /**
305
+     * search for occurrences of $query in file names
306
+     *
307
+     * @param string $query
308
+     * @return array|bool
309
+     * @since 6.0.0
310
+     */
311
+    public function search($query);
312
+
313
+    /**
314
+     * see https://www.php.net/manual/en/function.touch.php
315
+     * If the backend does not support the operation, false should be returned
316
+     *
317
+     * @param string $path
318
+     * @param int $mtime
319
+     * @return bool
320
+     * @since 6.0.0
321
+     */
322
+    public function touch($path, $mtime = null);
323
+
324
+    /**
325
+     * get the path to a local version of the file.
326
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
327
+     *
328
+     * @param string $path
329
+     * @return string|false
330
+     * @since 6.0.0
331
+     */
332
+    public function getLocalFile($path);
333
+
334
+    /**
335
+     * check if a file or folder has been updated since $time
336
+     *
337
+     * @param string $path
338
+     * @param int $time
339
+     * @return bool
340
+     * @since 6.0.0
341
+     *
342
+     * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
343
+     * returning true for other changes in the folder is optional
344
+     */
345
+    public function hasUpdated($path, $time);
346
+
347
+    /**
348
+     * get the ETag for a file or folder
349
+     *
350
+     * @param string $path
351
+     * @return string|false
352
+     * @since 6.0.0
353
+     */
354
+    public function getETag($path);
355
+
356
+    /**
357
+     * Returns whether the storage is local, which means that files
358
+     * are stored on the local filesystem instead of remotely.
359
+     * Calling getLocalFile() for local storages should always
360
+     * return the local files, whereas for non-local storages
361
+     * it might return a temporary file.
362
+     *
363
+     * @return bool true if the files are stored locally, false otherwise
364
+     * @since 7.0.0
365
+     */
366
+    public function isLocal();
367
+
368
+    /**
369
+     * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
370
+     *
371
+     * @template T of IStorage
372
+     * @param string $class
373
+     * @psalm-param class-string<T> $class
374
+     * @return bool
375
+     * @since 7.0.0
376
+     * @psalm-assert-if-true T $this
377
+     */
378
+    public function instanceOfStorage($class);
379
+
380
+    /**
381
+     * A custom storage implementation can return an url for direct download of a give file.
382
+     *
383
+     * For now the returned array can hold the parameter url - in future more attributes might follow.
384
+     *
385
+     * @param string $path
386
+     * @return array|bool
387
+     * @since 8.0.0
388
+     */
389
+    public function getDirectDownload($path);
390
+
391
+    /**
392
+     * @param string $path the path of the target folder
393
+     * @param string $fileName the name of the file itself
394
+     * @return void
395
+     * @throws InvalidPathException
396
+     * @since 8.1.0
397
+     */
398
+    public function verifyPath($path, $fileName);
399
+
400
+    /**
401
+     * @param IStorage $sourceStorage
402
+     * @param string $sourceInternalPath
403
+     * @param string $targetInternalPath
404
+     * @return bool
405
+     * @since 8.1.0
406
+     */
407
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
408
+
409
+    /**
410
+     * @param IStorage $sourceStorage
411
+     * @param string $sourceInternalPath
412
+     * @param string $targetInternalPath
413
+     * @return bool
414
+     * @since 8.1.0
415
+     */
416
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath);
417
+
418
+    /**
419
+     * @param string $path The path of the file to acquire the lock for
420
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
421
+     * @param \OCP\Lock\ILockingProvider $provider
422
+     * @throws \OCP\Lock\LockedException
423
+     * @since 8.1.0
424
+     */
425
+    public function acquireLock($path, $type, ILockingProvider $provider);
426
+
427
+    /**
428
+     * @param string $path The path of the file to acquire the lock for
429
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
430
+     * @param \OCP\Lock\ILockingProvider $provider
431
+     * @throws \OCP\Lock\LockedException
432
+     * @since 8.1.0
433
+     */
434
+    public function releaseLock($path, $type, ILockingProvider $provider);
435
+
436
+    /**
437
+     * @param string $path The path of the file to change the lock for
438
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
439
+     * @param \OCP\Lock\ILockingProvider $provider
440
+     * @throws \OCP\Lock\LockedException
441
+     * @since 8.1.0
442
+     */
443
+    public function changeLock($path, $type, ILockingProvider $provider);
444
+
445
+    /**
446
+     * Test a storage for availability
447
+     *
448
+     * @since 8.2.0
449
+     * @return bool
450
+     */
451
+    public function test();
452
+
453
+    /**
454
+     * @since 8.2.0
455
+     * @return array [ available, last_checked ]
456
+     */
457
+    public function getAvailability();
458
+
459
+    /**
460
+     * @since 8.2.0
461
+     * @param bool $isAvailable
462
+     */
463
+    public function setAvailability($isAvailable);
464
+
465
+    /**
466
+     * @since 12.0.0
467
+     * @return mixed
468
+     */
469
+    public function needsPartFile();
470 470
 }
Please login to merge, or discard this patch.
lib/private/Files/Node/File.php 1 patch
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -33,129 +33,129 @@
 block discarded – undo
33 33
 use OCP\Lock\LockedException;
34 34
 
35 35
 class File extends Node implements \OCP\Files\File {
36
-	/**
37
-	 * Creates a Folder that represents a non-existing path
38
-	 *
39
-	 * @param string $path path
40
-	 * @return NonExistingFile non-existing node
41
-	 */
42
-	protected function createNonExistingNode($path) {
43
-		return new NonExistingFile($this->root, $this->view, $path);
44
-	}
36
+    /**
37
+     * Creates a Folder that represents a non-existing path
38
+     *
39
+     * @param string $path path
40
+     * @return NonExistingFile non-existing node
41
+     */
42
+    protected function createNonExistingNode($path) {
43
+        return new NonExistingFile($this->root, $this->view, $path);
44
+    }
45 45
 
46
-	/**
47
-	 * @return string
48
-	 * @throws NotPermittedException
49
-	 * @throws GenericFileException
50
-	 * @throws LockedException
51
-	 */
52
-	public function getContent() {
53
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
54
-			$content = $this->view->file_get_contents($this->path);
55
-			if ($content === false) {
56
-				throw new GenericFileException();
57
-			}
58
-			return $content;
59
-		} else {
60
-			throw new NotPermittedException();
61
-		}
62
-	}
46
+    /**
47
+     * @return string
48
+     * @throws NotPermittedException
49
+     * @throws GenericFileException
50
+     * @throws LockedException
51
+     */
52
+    public function getContent() {
53
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
54
+            $content = $this->view->file_get_contents($this->path);
55
+            if ($content === false) {
56
+                throw new GenericFileException();
57
+            }
58
+            return $content;
59
+        } else {
60
+            throw new NotPermittedException();
61
+        }
62
+    }
63 63
 
64
-	/**
65
-	 * @param string|resource $data
66
-	 * @throws NotPermittedException
67
-	 * @throws GenericFileException
68
-	 * @throws LockedException
69
-	 */
70
-	public function putContent($data) {
71
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
72
-			$this->sendHooks(['preWrite']);
73
-			if ($this->view->file_put_contents($this->path, $data) === false) {
74
-				throw new GenericFileException('file_put_contents failed');
75
-			}
76
-			$this->fileInfo = null;
77
-			$this->sendHooks(['postWrite']);
78
-		} else {
79
-			throw new NotPermittedException();
80
-		}
81
-	}
64
+    /**
65
+     * @param string|resource $data
66
+     * @throws NotPermittedException
67
+     * @throws GenericFileException
68
+     * @throws LockedException
69
+     */
70
+    public function putContent($data) {
71
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
72
+            $this->sendHooks(['preWrite']);
73
+            if ($this->view->file_put_contents($this->path, $data) === false) {
74
+                throw new GenericFileException('file_put_contents failed');
75
+            }
76
+            $this->fileInfo = null;
77
+            $this->sendHooks(['postWrite']);
78
+        } else {
79
+            throw new NotPermittedException();
80
+        }
81
+    }
82 82
 
83
-	/**
84
-	 * @param string $mode
85
-	 * @return resource|false
86
-	 * @throws NotPermittedException
87
-	 * @throws LockedException
88
-	 */
89
-	public function fopen($mode) {
90
-		$preHooks = [];
91
-		$postHooks = [];
92
-		$requiredPermissions = \OCP\Constants::PERMISSION_READ;
93
-		switch ($mode) {
94
-			case 'r+':
95
-			case 'rb+':
96
-			case 'w+':
97
-			case 'wb+':
98
-			case 'x+':
99
-			case 'xb+':
100
-			case 'a+':
101
-			case 'ab+':
102
-			case 'w':
103
-			case 'wb':
104
-			case 'x':
105
-			case 'xb':
106
-			case 'a':
107
-			case 'ab':
108
-				$preHooks[] = 'preWrite';
109
-				$postHooks[] = 'postWrite';
110
-				$requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
111
-				break;
112
-		}
83
+    /**
84
+     * @param string $mode
85
+     * @return resource|false
86
+     * @throws NotPermittedException
87
+     * @throws LockedException
88
+     */
89
+    public function fopen($mode) {
90
+        $preHooks = [];
91
+        $postHooks = [];
92
+        $requiredPermissions = \OCP\Constants::PERMISSION_READ;
93
+        switch ($mode) {
94
+            case 'r+':
95
+            case 'rb+':
96
+            case 'w+':
97
+            case 'wb+':
98
+            case 'x+':
99
+            case 'xb+':
100
+            case 'a+':
101
+            case 'ab+':
102
+            case 'w':
103
+            case 'wb':
104
+            case 'x':
105
+            case 'xb':
106
+            case 'a':
107
+            case 'ab':
108
+                $preHooks[] = 'preWrite';
109
+                $postHooks[] = 'postWrite';
110
+                $requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
111
+                break;
112
+        }
113 113
 
114
-		if ($this->checkPermissions($requiredPermissions)) {
115
-			$this->sendHooks($preHooks);
116
-			$result = $this->view->fopen($this->path, $mode);
117
-			$this->sendHooks($postHooks);
118
-			return $result;
119
-		} else {
120
-			throw new NotPermittedException();
121
-		}
122
-	}
114
+        if ($this->checkPermissions($requiredPermissions)) {
115
+            $this->sendHooks($preHooks);
116
+            $result = $this->view->fopen($this->path, $mode);
117
+            $this->sendHooks($postHooks);
118
+            return $result;
119
+        } else {
120
+            throw new NotPermittedException();
121
+        }
122
+    }
123 123
 
124
-	/**
125
-	 * @throws NotPermittedException
126
-	 * @throws \OCP\Files\InvalidPathException
127
-	 * @throws \OCP\Files\NotFoundException
128
-	 */
129
-	public function delete() {
130
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
131
-			$this->sendHooks(['preDelete']);
132
-			$fileInfo = $this->getFileInfo();
133
-			$this->view->unlink($this->path);
134
-			$nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
135
-			$this->sendHooks(['postDelete'], [$nonExisting]);
136
-			$this->fileInfo = null;
137
-		} else {
138
-			throw new NotPermittedException();
139
-		}
140
-	}
124
+    /**
125
+     * @throws NotPermittedException
126
+     * @throws \OCP\Files\InvalidPathException
127
+     * @throws \OCP\Files\NotFoundException
128
+     */
129
+    public function delete() {
130
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
131
+            $this->sendHooks(['preDelete']);
132
+            $fileInfo = $this->getFileInfo();
133
+            $this->view->unlink($this->path);
134
+            $nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
135
+            $this->sendHooks(['postDelete'], [$nonExisting]);
136
+            $this->fileInfo = null;
137
+        } else {
138
+            throw new NotPermittedException();
139
+        }
140
+    }
141 141
 
142
-	/**
143
-	 * @param string $type
144
-	 * @param bool $raw
145
-	 * @return string
146
-	 */
147
-	public function hash($type, $raw = false) {
148
-		return $this->view->hash($type, $this->path, $raw);
149
-	}
142
+    /**
143
+     * @param string $type
144
+     * @param bool $raw
145
+     * @return string
146
+     */
147
+    public function hash($type, $raw = false) {
148
+        return $this->view->hash($type, $this->path, $raw);
149
+    }
150 150
 
151
-	/**
152
-	 * @inheritdoc
153
-	 */
154
-	public function getChecksum() {
155
-		return $this->getFileInfo()->getChecksum();
156
-	}
151
+    /**
152
+     * @inheritdoc
153
+     */
154
+    public function getChecksum() {
155
+        return $this->getFileInfo()->getChecksum();
156
+    }
157 157
 
158
-	public function getExtension(): string {
159
-		return $this->getFileInfo()->getExtension();
160
-	}
158
+    public function getExtension(): string {
159
+        return $this->getFileInfo()->getExtension();
160
+    }
161 161
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encoding.php 1 patch
Indentation   +502 added lines, -502 removed lines patch added patch discarded remove patch
@@ -40,506 +40,506 @@
 block discarded – undo
40 40
  * the actual given name and then try its NFD form.
41 41
  */
42 42
 class Encoding extends Wrapper {
43
-	/**
44
-	 * @var ICache
45
-	 */
46
-	private $namesCache;
47
-
48
-	/**
49
-	 * @param array $parameters
50
-	 */
51
-	public function __construct($parameters) {
52
-		$this->storage = $parameters['storage'];
53
-		$this->namesCache = new CappedMemoryCache();
54
-	}
55
-
56
-	/**
57
-	 * Returns whether the given string is only made of ASCII characters
58
-	 *
59
-	 * @param string $str string
60
-	 *
61
-	 * @return bool true if the string is all ASCII, false otherwise
62
-	 */
63
-	private function isAscii($str) {
64
-		return !preg_match('/[\\x80-\\xff]+/', $str);
65
-	}
66
-
67
-	/**
68
-	 * Checks whether the given path exists in NFC or NFD form after checking
69
-	 * each form for each path section and returns the correct form.
70
-	 * If no existing path found, returns the path as it was given.
71
-	 *
72
-	 * @param string $fullPath path to check
73
-	 *
74
-	 * @return string original or converted path
75
-	 */
76
-	private function findPathToUse($fullPath) {
77
-		$cachedPath = $this->namesCache[$fullPath];
78
-		if ($cachedPath !== null) {
79
-			return $cachedPath;
80
-		}
81
-
82
-		$sections = explode('/', $fullPath);
83
-		$path = '';
84
-		foreach ($sections as $section) {
85
-			$convertedPath = $this->findPathToUseLastSection($path, $section);
86
-			if ($convertedPath === null) {
87
-				// no point in continuing if the section was not found, use original path
88
-				return $fullPath;
89
-			}
90
-			$path = $convertedPath . '/';
91
-		}
92
-		$path = rtrim($path, '/');
93
-		return $path;
94
-	}
95
-
96
-	/**
97
-	 * Checks whether the last path section of the given path exists in NFC or NFD form
98
-	 * and returns the correct form. If no existing path found, returns null.
99
-	 *
100
-	 * @param string $basePath base path to check
101
-	 * @param string $lastSection last section of the path to check for NFD/NFC variations
102
-	 *
103
-	 * @return string|null original or converted path, or null if none of the forms was found
104
-	 */
105
-	private function findPathToUseLastSection($basePath, $lastSection) {
106
-		$fullPath = $basePath . $lastSection;
107
-		if ($lastSection === '' || $this->isAscii($lastSection) || $this->storage->file_exists($fullPath)) {
108
-			$this->namesCache[$fullPath] = $fullPath;
109
-			return $fullPath;
110
-		}
111
-
112
-		// swap encoding
113
-		if (\Normalizer::isNormalized($lastSection, \Normalizer::FORM_C)) {
114
-			$otherFormPath = \Normalizer::normalize($lastSection, \Normalizer::FORM_D);
115
-		} else {
116
-			$otherFormPath = \Normalizer::normalize($lastSection, \Normalizer::FORM_C);
117
-		}
118
-		$otherFullPath = $basePath . $otherFormPath;
119
-		if ($this->storage->file_exists($otherFullPath)) {
120
-			$this->namesCache[$fullPath] = $otherFullPath;
121
-			return $otherFullPath;
122
-		}
123
-
124
-		// return original path, file did not exist at all
125
-		$this->namesCache[$fullPath] = $fullPath;
126
-		return null;
127
-	}
128
-
129
-	/**
130
-	 * see https://www.php.net/manual/en/function.mkdir.php
131
-	 *
132
-	 * @param string $path
133
-	 * @return bool
134
-	 */
135
-	public function mkdir($path) {
136
-		// note: no conversion here, method should not be called with non-NFC names!
137
-		$result = $this->storage->mkdir($path);
138
-		if ($result) {
139
-			$this->namesCache[$path] = $path;
140
-		}
141
-		return $result;
142
-	}
143
-
144
-	/**
145
-	 * see https://www.php.net/manual/en/function.rmdir.php
146
-	 *
147
-	 * @param string $path
148
-	 * @return bool
149
-	 */
150
-	public function rmdir($path) {
151
-		$result = $this->storage->rmdir($this->findPathToUse($path));
152
-		if ($result) {
153
-			unset($this->namesCache[$path]);
154
-		}
155
-		return $result;
156
-	}
157
-
158
-	/**
159
-	 * see https://www.php.net/manual/en/function.opendir.php
160
-	 *
161
-	 * @param string $path
162
-	 * @return resource|false
163
-	 */
164
-	public function opendir($path) {
165
-		$handle = $this->storage->opendir($this->findPathToUse($path));
166
-		return EncodingDirectoryWrapper::wrap($handle);
167
-	}
168
-
169
-	/**
170
-	 * see https://www.php.net/manual/en/function.is_dir.php
171
-	 *
172
-	 * @param string $path
173
-	 * @return bool
174
-	 */
175
-	public function is_dir($path) {
176
-		return $this->storage->is_dir($this->findPathToUse($path));
177
-	}
178
-
179
-	/**
180
-	 * see https://www.php.net/manual/en/function.is_file.php
181
-	 *
182
-	 * @param string $path
183
-	 * @return bool
184
-	 */
185
-	public function is_file($path) {
186
-		return $this->storage->is_file($this->findPathToUse($path));
187
-	}
188
-
189
-	/**
190
-	 * see https://www.php.net/manual/en/function.stat.php
191
-	 * only the following keys are required in the result: size and mtime
192
-	 *
193
-	 * @param string $path
194
-	 * @return array|bool
195
-	 */
196
-	public function stat($path) {
197
-		return $this->storage->stat($this->findPathToUse($path));
198
-	}
199
-
200
-	/**
201
-	 * see https://www.php.net/manual/en/function.filetype.php
202
-	 *
203
-	 * @param string $path
204
-	 * @return string|bool
205
-	 */
206
-	public function filetype($path) {
207
-		return $this->storage->filetype($this->findPathToUse($path));
208
-	}
209
-
210
-	/**
211
-	 * see https://www.php.net/manual/en/function.filesize.php
212
-	 * The result for filesize when called on a folder is required to be 0
213
-	 */
214
-	public function filesize($path): false|int|float {
215
-		return $this->storage->filesize($this->findPathToUse($path));
216
-	}
217
-
218
-	/**
219
-	 * check if a file can be created in $path
220
-	 *
221
-	 * @param string $path
222
-	 * @return bool
223
-	 */
224
-	public function isCreatable($path) {
225
-		return $this->storage->isCreatable($this->findPathToUse($path));
226
-	}
227
-
228
-	/**
229
-	 * check if a file can be read
230
-	 *
231
-	 * @param string $path
232
-	 * @return bool
233
-	 */
234
-	public function isReadable($path) {
235
-		return $this->storage->isReadable($this->findPathToUse($path));
236
-	}
237
-
238
-	/**
239
-	 * check if a file can be written to
240
-	 *
241
-	 * @param string $path
242
-	 * @return bool
243
-	 */
244
-	public function isUpdatable($path) {
245
-		return $this->storage->isUpdatable($this->findPathToUse($path));
246
-	}
247
-
248
-	/**
249
-	 * check if a file can be deleted
250
-	 *
251
-	 * @param string $path
252
-	 * @return bool
253
-	 */
254
-	public function isDeletable($path) {
255
-		return $this->storage->isDeletable($this->findPathToUse($path));
256
-	}
257
-
258
-	/**
259
-	 * check if a file can be shared
260
-	 *
261
-	 * @param string $path
262
-	 * @return bool
263
-	 */
264
-	public function isSharable($path) {
265
-		return $this->storage->isSharable($this->findPathToUse($path));
266
-	}
267
-
268
-	/**
269
-	 * get the full permissions of a path.
270
-	 * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
271
-	 *
272
-	 * @param string $path
273
-	 * @return int
274
-	 */
275
-	public function getPermissions($path) {
276
-		return $this->storage->getPermissions($this->findPathToUse($path));
277
-	}
278
-
279
-	/**
280
-	 * see https://www.php.net/manual/en/function.file_exists.php
281
-	 *
282
-	 * @param string $path
283
-	 * @return bool
284
-	 */
285
-	public function file_exists($path) {
286
-		return $this->storage->file_exists($this->findPathToUse($path));
287
-	}
288
-
289
-	/**
290
-	 * see https://www.php.net/manual/en/function.filemtime.php
291
-	 *
292
-	 * @param string $path
293
-	 * @return int|bool
294
-	 */
295
-	public function filemtime($path) {
296
-		return $this->storage->filemtime($this->findPathToUse($path));
297
-	}
298
-
299
-	/**
300
-	 * see https://www.php.net/manual/en/function.file_get_contents.php
301
-	 *
302
-	 * @param string $path
303
-	 * @return string|false
304
-	 */
305
-	public function file_get_contents($path) {
306
-		return $this->storage->file_get_contents($this->findPathToUse($path));
307
-	}
308
-
309
-	/**
310
-	 * see https://www.php.net/manual/en/function.file_put_contents.php
311
-	 *
312
-	 * @param string $path
313
-	 * @param mixed $data
314
-	 * @return int|float|false
315
-	 */
316
-	public function file_put_contents($path, $data) {
317
-		return $this->storage->file_put_contents($this->findPathToUse($path), $data);
318
-	}
319
-
320
-	/**
321
-	 * see https://www.php.net/manual/en/function.unlink.php
322
-	 *
323
-	 * @param string $path
324
-	 * @return bool
325
-	 */
326
-	public function unlink($path) {
327
-		$result = $this->storage->unlink($this->findPathToUse($path));
328
-		if ($result) {
329
-			unset($this->namesCache[$path]);
330
-		}
331
-		return $result;
332
-	}
333
-
334
-	/**
335
-	 * see https://www.php.net/manual/en/function.rename.php
336
-	 *
337
-	 * @param string $source
338
-	 * @param string $target
339
-	 * @return bool
340
-	 */
341
-	public function rename($source, $target) {
342
-		// second name always NFC
343
-		return $this->storage->rename($this->findPathToUse($source), $this->findPathToUse($target));
344
-	}
345
-
346
-	/**
347
-	 * see https://www.php.net/manual/en/function.copy.php
348
-	 *
349
-	 * @param string $source
350
-	 * @param string $target
351
-	 * @return bool
352
-	 */
353
-	public function copy($source, $target) {
354
-		return $this->storage->copy($this->findPathToUse($source), $this->findPathToUse($target));
355
-	}
356
-
357
-	/**
358
-	 * see https://www.php.net/manual/en/function.fopen.php
359
-	 *
360
-	 * @param string $path
361
-	 * @param string $mode
362
-	 * @return resource|bool
363
-	 */
364
-	public function fopen($path, $mode) {
365
-		$result = $this->storage->fopen($this->findPathToUse($path), $mode);
366
-		if ($result && $mode !== 'r' && $mode !== 'rb') {
367
-			unset($this->namesCache[$path]);
368
-		}
369
-		return $result;
370
-	}
371
-
372
-	/**
373
-	 * get the mimetype for a file or folder
374
-	 * The mimetype for a folder is required to be "httpd/unix-directory"
375
-	 *
376
-	 * @param string $path
377
-	 * @return string|bool
378
-	 */
379
-	public function getMimeType($path) {
380
-		return $this->storage->getMimeType($this->findPathToUse($path));
381
-	}
382
-
383
-	/**
384
-	 * see https://www.php.net/manual/en/function.hash.php
385
-	 *
386
-	 * @param string $type
387
-	 * @param string $path
388
-	 * @param bool $raw
389
-	 * @return string|bool
390
-	 */
391
-	public function hash($type, $path, $raw = false) {
392
-		return $this->storage->hash($type, $this->findPathToUse($path), $raw);
393
-	}
394
-
395
-	/**
396
-	 * see https://www.php.net/manual/en/function.free_space.php
397
-	 *
398
-	 * @param string $path
399
-	 * @return int|float|bool
400
-	 */
401
-	public function free_space($path) {
402
-		return $this->storage->free_space($this->findPathToUse($path));
403
-	}
404
-
405
-	/**
406
-	 * search for occurrences of $query in file names
407
-	 *
408
-	 * @param string $query
409
-	 * @return array|bool
410
-	 */
411
-	public function search($query) {
412
-		return $this->storage->search($query);
413
-	}
414
-
415
-	/**
416
-	 * see https://www.php.net/manual/en/function.touch.php
417
-	 * If the backend does not support the operation, false should be returned
418
-	 *
419
-	 * @param string $path
420
-	 * @param int $mtime
421
-	 * @return bool
422
-	 */
423
-	public function touch($path, $mtime = null) {
424
-		return $this->storage->touch($this->findPathToUse($path), $mtime);
425
-	}
426
-
427
-	/**
428
-	 * get the path to a local version of the file.
429
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
430
-	 *
431
-	 * @param string $path
432
-	 * @return string|false
433
-	 */
434
-	public function getLocalFile($path) {
435
-		return $this->storage->getLocalFile($this->findPathToUse($path));
436
-	}
437
-
438
-	/**
439
-	 * check if a file or folder has been updated since $time
440
-	 *
441
-	 * @param string $path
442
-	 * @param int $time
443
-	 * @return bool
444
-	 *
445
-	 * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
446
-	 * returning true for other changes in the folder is optional
447
-	 */
448
-	public function hasUpdated($path, $time) {
449
-		return $this->storage->hasUpdated($this->findPathToUse($path), $time);
450
-	}
451
-
452
-	/**
453
-	 * get a cache instance for the storage
454
-	 *
455
-	 * @param string $path
456
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
457
-	 * @return \OC\Files\Cache\Cache
458
-	 */
459
-	public function getCache($path = '', $storage = null) {
460
-		if (!$storage) {
461
-			$storage = $this;
462
-		}
463
-		return $this->storage->getCache($this->findPathToUse($path), $storage);
464
-	}
465
-
466
-	/**
467
-	 * get a scanner instance for the storage
468
-	 *
469
-	 * @param string $path
470
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
471
-	 * @return \OC\Files\Cache\Scanner
472
-	 */
473
-	public function getScanner($path = '', $storage = null) {
474
-		if (!$storage) {
475
-			$storage = $this;
476
-		}
477
-		return $this->storage->getScanner($this->findPathToUse($path), $storage);
478
-	}
479
-
480
-	/**
481
-	 * get the ETag for a file or folder
482
-	 *
483
-	 * @param string $path
484
-	 * @return string|false
485
-	 */
486
-	public function getETag($path) {
487
-		return $this->storage->getETag($this->findPathToUse($path));
488
-	}
489
-
490
-	/**
491
-	 * @param IStorage $sourceStorage
492
-	 * @param string $sourceInternalPath
493
-	 * @param string $targetInternalPath
494
-	 * @return bool
495
-	 */
496
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
497
-		if ($sourceStorage === $this) {
498
-			return $this->copy($sourceInternalPath, $this->findPathToUse($targetInternalPath));
499
-		}
500
-
501
-		$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $this->findPathToUse($targetInternalPath));
502
-		if ($result) {
503
-			unset($this->namesCache[$targetInternalPath]);
504
-		}
505
-		return $result;
506
-	}
507
-
508
-	/**
509
-	 * @param IStorage $sourceStorage
510
-	 * @param string $sourceInternalPath
511
-	 * @param string $targetInternalPath
512
-	 * @return bool
513
-	 */
514
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
515
-		if ($sourceStorage === $this) {
516
-			$result = $this->rename($sourceInternalPath, $this->findPathToUse($targetInternalPath));
517
-			if ($result) {
518
-				unset($this->namesCache[$sourceInternalPath]);
519
-				unset($this->namesCache[$targetInternalPath]);
520
-			}
521
-			return $result;
522
-		}
523
-
524
-		$result = $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $this->findPathToUse($targetInternalPath));
525
-		if ($result) {
526
-			unset($this->namesCache[$sourceInternalPath]);
527
-			unset($this->namesCache[$targetInternalPath]);
528
-		}
529
-		return $result;
530
-	}
531
-
532
-	public function getMetaData($path) {
533
-		$entry = $this->storage->getMetaData($this->findPathToUse($path));
534
-		$entry['name'] = trim(Filesystem::normalizePath($entry['name']), '/');
535
-		return $entry;
536
-	}
537
-
538
-	public function getDirectoryContent($directory): \Traversable {
539
-		$entries = $this->storage->getDirectoryContent($this->findPathToUse($directory));
540
-		foreach ($entries as $entry) {
541
-			$entry['name'] = trim(Filesystem::normalizePath($entry['name']), '/');
542
-			yield $entry;
543
-		}
544
-	}
43
+    /**
44
+     * @var ICache
45
+     */
46
+    private $namesCache;
47
+
48
+    /**
49
+     * @param array $parameters
50
+     */
51
+    public function __construct($parameters) {
52
+        $this->storage = $parameters['storage'];
53
+        $this->namesCache = new CappedMemoryCache();
54
+    }
55
+
56
+    /**
57
+     * Returns whether the given string is only made of ASCII characters
58
+     *
59
+     * @param string $str string
60
+     *
61
+     * @return bool true if the string is all ASCII, false otherwise
62
+     */
63
+    private function isAscii($str) {
64
+        return !preg_match('/[\\x80-\\xff]+/', $str);
65
+    }
66
+
67
+    /**
68
+     * Checks whether the given path exists in NFC or NFD form after checking
69
+     * each form for each path section and returns the correct form.
70
+     * If no existing path found, returns the path as it was given.
71
+     *
72
+     * @param string $fullPath path to check
73
+     *
74
+     * @return string original or converted path
75
+     */
76
+    private function findPathToUse($fullPath) {
77
+        $cachedPath = $this->namesCache[$fullPath];
78
+        if ($cachedPath !== null) {
79
+            return $cachedPath;
80
+        }
81
+
82
+        $sections = explode('/', $fullPath);
83
+        $path = '';
84
+        foreach ($sections as $section) {
85
+            $convertedPath = $this->findPathToUseLastSection($path, $section);
86
+            if ($convertedPath === null) {
87
+                // no point in continuing if the section was not found, use original path
88
+                return $fullPath;
89
+            }
90
+            $path = $convertedPath . '/';
91
+        }
92
+        $path = rtrim($path, '/');
93
+        return $path;
94
+    }
95
+
96
+    /**
97
+     * Checks whether the last path section of the given path exists in NFC or NFD form
98
+     * and returns the correct form. If no existing path found, returns null.
99
+     *
100
+     * @param string $basePath base path to check
101
+     * @param string $lastSection last section of the path to check for NFD/NFC variations
102
+     *
103
+     * @return string|null original or converted path, or null if none of the forms was found
104
+     */
105
+    private function findPathToUseLastSection($basePath, $lastSection) {
106
+        $fullPath = $basePath . $lastSection;
107
+        if ($lastSection === '' || $this->isAscii($lastSection) || $this->storage->file_exists($fullPath)) {
108
+            $this->namesCache[$fullPath] = $fullPath;
109
+            return $fullPath;
110
+        }
111
+
112
+        // swap encoding
113
+        if (\Normalizer::isNormalized($lastSection, \Normalizer::FORM_C)) {
114
+            $otherFormPath = \Normalizer::normalize($lastSection, \Normalizer::FORM_D);
115
+        } else {
116
+            $otherFormPath = \Normalizer::normalize($lastSection, \Normalizer::FORM_C);
117
+        }
118
+        $otherFullPath = $basePath . $otherFormPath;
119
+        if ($this->storage->file_exists($otherFullPath)) {
120
+            $this->namesCache[$fullPath] = $otherFullPath;
121
+            return $otherFullPath;
122
+        }
123
+
124
+        // return original path, file did not exist at all
125
+        $this->namesCache[$fullPath] = $fullPath;
126
+        return null;
127
+    }
128
+
129
+    /**
130
+     * see https://www.php.net/manual/en/function.mkdir.php
131
+     *
132
+     * @param string $path
133
+     * @return bool
134
+     */
135
+    public function mkdir($path) {
136
+        // note: no conversion here, method should not be called with non-NFC names!
137
+        $result = $this->storage->mkdir($path);
138
+        if ($result) {
139
+            $this->namesCache[$path] = $path;
140
+        }
141
+        return $result;
142
+    }
143
+
144
+    /**
145
+     * see https://www.php.net/manual/en/function.rmdir.php
146
+     *
147
+     * @param string $path
148
+     * @return bool
149
+     */
150
+    public function rmdir($path) {
151
+        $result = $this->storage->rmdir($this->findPathToUse($path));
152
+        if ($result) {
153
+            unset($this->namesCache[$path]);
154
+        }
155
+        return $result;
156
+    }
157
+
158
+    /**
159
+     * see https://www.php.net/manual/en/function.opendir.php
160
+     *
161
+     * @param string $path
162
+     * @return resource|false
163
+     */
164
+    public function opendir($path) {
165
+        $handle = $this->storage->opendir($this->findPathToUse($path));
166
+        return EncodingDirectoryWrapper::wrap($handle);
167
+    }
168
+
169
+    /**
170
+     * see https://www.php.net/manual/en/function.is_dir.php
171
+     *
172
+     * @param string $path
173
+     * @return bool
174
+     */
175
+    public function is_dir($path) {
176
+        return $this->storage->is_dir($this->findPathToUse($path));
177
+    }
178
+
179
+    /**
180
+     * see https://www.php.net/manual/en/function.is_file.php
181
+     *
182
+     * @param string $path
183
+     * @return bool
184
+     */
185
+    public function is_file($path) {
186
+        return $this->storage->is_file($this->findPathToUse($path));
187
+    }
188
+
189
+    /**
190
+     * see https://www.php.net/manual/en/function.stat.php
191
+     * only the following keys are required in the result: size and mtime
192
+     *
193
+     * @param string $path
194
+     * @return array|bool
195
+     */
196
+    public function stat($path) {
197
+        return $this->storage->stat($this->findPathToUse($path));
198
+    }
199
+
200
+    /**
201
+     * see https://www.php.net/manual/en/function.filetype.php
202
+     *
203
+     * @param string $path
204
+     * @return string|bool
205
+     */
206
+    public function filetype($path) {
207
+        return $this->storage->filetype($this->findPathToUse($path));
208
+    }
209
+
210
+    /**
211
+     * see https://www.php.net/manual/en/function.filesize.php
212
+     * The result for filesize when called on a folder is required to be 0
213
+     */
214
+    public function filesize($path): false|int|float {
215
+        return $this->storage->filesize($this->findPathToUse($path));
216
+    }
217
+
218
+    /**
219
+     * check if a file can be created in $path
220
+     *
221
+     * @param string $path
222
+     * @return bool
223
+     */
224
+    public function isCreatable($path) {
225
+        return $this->storage->isCreatable($this->findPathToUse($path));
226
+    }
227
+
228
+    /**
229
+     * check if a file can be read
230
+     *
231
+     * @param string $path
232
+     * @return bool
233
+     */
234
+    public function isReadable($path) {
235
+        return $this->storage->isReadable($this->findPathToUse($path));
236
+    }
237
+
238
+    /**
239
+     * check if a file can be written to
240
+     *
241
+     * @param string $path
242
+     * @return bool
243
+     */
244
+    public function isUpdatable($path) {
245
+        return $this->storage->isUpdatable($this->findPathToUse($path));
246
+    }
247
+
248
+    /**
249
+     * check if a file can be deleted
250
+     *
251
+     * @param string $path
252
+     * @return bool
253
+     */
254
+    public function isDeletable($path) {
255
+        return $this->storage->isDeletable($this->findPathToUse($path));
256
+    }
257
+
258
+    /**
259
+     * check if a file can be shared
260
+     *
261
+     * @param string $path
262
+     * @return bool
263
+     */
264
+    public function isSharable($path) {
265
+        return $this->storage->isSharable($this->findPathToUse($path));
266
+    }
267
+
268
+    /**
269
+     * get the full permissions of a path.
270
+     * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
271
+     *
272
+     * @param string $path
273
+     * @return int
274
+     */
275
+    public function getPermissions($path) {
276
+        return $this->storage->getPermissions($this->findPathToUse($path));
277
+    }
278
+
279
+    /**
280
+     * see https://www.php.net/manual/en/function.file_exists.php
281
+     *
282
+     * @param string $path
283
+     * @return bool
284
+     */
285
+    public function file_exists($path) {
286
+        return $this->storage->file_exists($this->findPathToUse($path));
287
+    }
288
+
289
+    /**
290
+     * see https://www.php.net/manual/en/function.filemtime.php
291
+     *
292
+     * @param string $path
293
+     * @return int|bool
294
+     */
295
+    public function filemtime($path) {
296
+        return $this->storage->filemtime($this->findPathToUse($path));
297
+    }
298
+
299
+    /**
300
+     * see https://www.php.net/manual/en/function.file_get_contents.php
301
+     *
302
+     * @param string $path
303
+     * @return string|false
304
+     */
305
+    public function file_get_contents($path) {
306
+        return $this->storage->file_get_contents($this->findPathToUse($path));
307
+    }
308
+
309
+    /**
310
+     * see https://www.php.net/manual/en/function.file_put_contents.php
311
+     *
312
+     * @param string $path
313
+     * @param mixed $data
314
+     * @return int|float|false
315
+     */
316
+    public function file_put_contents($path, $data) {
317
+        return $this->storage->file_put_contents($this->findPathToUse($path), $data);
318
+    }
319
+
320
+    /**
321
+     * see https://www.php.net/manual/en/function.unlink.php
322
+     *
323
+     * @param string $path
324
+     * @return bool
325
+     */
326
+    public function unlink($path) {
327
+        $result = $this->storage->unlink($this->findPathToUse($path));
328
+        if ($result) {
329
+            unset($this->namesCache[$path]);
330
+        }
331
+        return $result;
332
+    }
333
+
334
+    /**
335
+     * see https://www.php.net/manual/en/function.rename.php
336
+     *
337
+     * @param string $source
338
+     * @param string $target
339
+     * @return bool
340
+     */
341
+    public function rename($source, $target) {
342
+        // second name always NFC
343
+        return $this->storage->rename($this->findPathToUse($source), $this->findPathToUse($target));
344
+    }
345
+
346
+    /**
347
+     * see https://www.php.net/manual/en/function.copy.php
348
+     *
349
+     * @param string $source
350
+     * @param string $target
351
+     * @return bool
352
+     */
353
+    public function copy($source, $target) {
354
+        return $this->storage->copy($this->findPathToUse($source), $this->findPathToUse($target));
355
+    }
356
+
357
+    /**
358
+     * see https://www.php.net/manual/en/function.fopen.php
359
+     *
360
+     * @param string $path
361
+     * @param string $mode
362
+     * @return resource|bool
363
+     */
364
+    public function fopen($path, $mode) {
365
+        $result = $this->storage->fopen($this->findPathToUse($path), $mode);
366
+        if ($result && $mode !== 'r' && $mode !== 'rb') {
367
+            unset($this->namesCache[$path]);
368
+        }
369
+        return $result;
370
+    }
371
+
372
+    /**
373
+     * get the mimetype for a file or folder
374
+     * The mimetype for a folder is required to be "httpd/unix-directory"
375
+     *
376
+     * @param string $path
377
+     * @return string|bool
378
+     */
379
+    public function getMimeType($path) {
380
+        return $this->storage->getMimeType($this->findPathToUse($path));
381
+    }
382
+
383
+    /**
384
+     * see https://www.php.net/manual/en/function.hash.php
385
+     *
386
+     * @param string $type
387
+     * @param string $path
388
+     * @param bool $raw
389
+     * @return string|bool
390
+     */
391
+    public function hash($type, $path, $raw = false) {
392
+        return $this->storage->hash($type, $this->findPathToUse($path), $raw);
393
+    }
394
+
395
+    /**
396
+     * see https://www.php.net/manual/en/function.free_space.php
397
+     *
398
+     * @param string $path
399
+     * @return int|float|bool
400
+     */
401
+    public function free_space($path) {
402
+        return $this->storage->free_space($this->findPathToUse($path));
403
+    }
404
+
405
+    /**
406
+     * search for occurrences of $query in file names
407
+     *
408
+     * @param string $query
409
+     * @return array|bool
410
+     */
411
+    public function search($query) {
412
+        return $this->storage->search($query);
413
+    }
414
+
415
+    /**
416
+     * see https://www.php.net/manual/en/function.touch.php
417
+     * If the backend does not support the operation, false should be returned
418
+     *
419
+     * @param string $path
420
+     * @param int $mtime
421
+     * @return bool
422
+     */
423
+    public function touch($path, $mtime = null) {
424
+        return $this->storage->touch($this->findPathToUse($path), $mtime);
425
+    }
426
+
427
+    /**
428
+     * get the path to a local version of the file.
429
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
430
+     *
431
+     * @param string $path
432
+     * @return string|false
433
+     */
434
+    public function getLocalFile($path) {
435
+        return $this->storage->getLocalFile($this->findPathToUse($path));
436
+    }
437
+
438
+    /**
439
+     * check if a file or folder has been updated since $time
440
+     *
441
+     * @param string $path
442
+     * @param int $time
443
+     * @return bool
444
+     *
445
+     * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
446
+     * returning true for other changes in the folder is optional
447
+     */
448
+    public function hasUpdated($path, $time) {
449
+        return $this->storage->hasUpdated($this->findPathToUse($path), $time);
450
+    }
451
+
452
+    /**
453
+     * get a cache instance for the storage
454
+     *
455
+     * @param string $path
456
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the cache
457
+     * @return \OC\Files\Cache\Cache
458
+     */
459
+    public function getCache($path = '', $storage = null) {
460
+        if (!$storage) {
461
+            $storage = $this;
462
+        }
463
+        return $this->storage->getCache($this->findPathToUse($path), $storage);
464
+    }
465
+
466
+    /**
467
+     * get a scanner instance for the storage
468
+     *
469
+     * @param string $path
470
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
471
+     * @return \OC\Files\Cache\Scanner
472
+     */
473
+    public function getScanner($path = '', $storage = null) {
474
+        if (!$storage) {
475
+            $storage = $this;
476
+        }
477
+        return $this->storage->getScanner($this->findPathToUse($path), $storage);
478
+    }
479
+
480
+    /**
481
+     * get the ETag for a file or folder
482
+     *
483
+     * @param string $path
484
+     * @return string|false
485
+     */
486
+    public function getETag($path) {
487
+        return $this->storage->getETag($this->findPathToUse($path));
488
+    }
489
+
490
+    /**
491
+     * @param IStorage $sourceStorage
492
+     * @param string $sourceInternalPath
493
+     * @param string $targetInternalPath
494
+     * @return bool
495
+     */
496
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
497
+        if ($sourceStorage === $this) {
498
+            return $this->copy($sourceInternalPath, $this->findPathToUse($targetInternalPath));
499
+        }
500
+
501
+        $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $this->findPathToUse($targetInternalPath));
502
+        if ($result) {
503
+            unset($this->namesCache[$targetInternalPath]);
504
+        }
505
+        return $result;
506
+    }
507
+
508
+    /**
509
+     * @param IStorage $sourceStorage
510
+     * @param string $sourceInternalPath
511
+     * @param string $targetInternalPath
512
+     * @return bool
513
+     */
514
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
515
+        if ($sourceStorage === $this) {
516
+            $result = $this->rename($sourceInternalPath, $this->findPathToUse($targetInternalPath));
517
+            if ($result) {
518
+                unset($this->namesCache[$sourceInternalPath]);
519
+                unset($this->namesCache[$targetInternalPath]);
520
+            }
521
+            return $result;
522
+        }
523
+
524
+        $result = $this->storage->moveFromStorage($sourceStorage, $sourceInternalPath, $this->findPathToUse($targetInternalPath));
525
+        if ($result) {
526
+            unset($this->namesCache[$sourceInternalPath]);
527
+            unset($this->namesCache[$targetInternalPath]);
528
+        }
529
+        return $result;
530
+    }
531
+
532
+    public function getMetaData($path) {
533
+        $entry = $this->storage->getMetaData($this->findPathToUse($path));
534
+        $entry['name'] = trim(Filesystem::normalizePath($entry['name']), '/');
535
+        return $entry;
536
+    }
537
+
538
+    public function getDirectoryContent($directory): \Traversable {
539
+        $entries = $this->storage->getDirectoryContent($this->findPathToUse($directory));
540
+        foreach ($entries as $entry) {
541
+            $entry['name'] = trim(Filesystem::normalizePath($entry['name']), '/');
542
+            yield $entry;
543
+        }
544
+    }
545 545
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Jail.php 1 patch
Indentation   +493 added lines, -493 removed lines patch added patch discarded remove patch
@@ -41,497 +41,497 @@
 block discarded – undo
41 41
  * This restricts access to a subfolder of the wrapped storage with the subfolder becoming the root folder new storage
42 42
  */
43 43
 class Jail extends Wrapper {
44
-	/**
45
-	 * @var string
46
-	 */
47
-	protected $rootPath;
48
-
49
-	/**
50
-	 * @param array $arguments ['storage' => $storage, 'root' => $root]
51
-	 *
52
-	 * $storage: The storage that will be wrapper
53
-	 * $root: The folder in the wrapped storage that will become the root folder of the wrapped storage
54
-	 */
55
-	public function __construct($arguments) {
56
-		parent::__construct($arguments);
57
-		$this->rootPath = $arguments['root'];
58
-	}
59
-
60
-	public function getUnjailedPath($path) {
61
-		return trim(Filesystem::normalizePath($this->rootPath . '/' . $path), '/');
62
-	}
63
-
64
-	/**
65
-	 * This is separate from Wrapper::getWrapperStorage so we can get the jailed storage consistently even if the jail is inside another wrapper
66
-	 */
67
-	public function getUnjailedStorage() {
68
-		return $this->storage;
69
-	}
70
-
71
-
72
-	public function getJailedPath($path) {
73
-		$root = rtrim($this->rootPath, '/') . '/';
74
-
75
-		if ($path !== $this->rootPath && strpos($path, $root) !== 0) {
76
-			return null;
77
-		} else {
78
-			$path = substr($path, strlen($this->rootPath));
79
-			return trim($path, '/');
80
-		}
81
-	}
82
-
83
-	public function getId() {
84
-		return parent::getId();
85
-	}
86
-
87
-	/**
88
-	 * see https://www.php.net/manual/en/function.mkdir.php
89
-	 *
90
-	 * @param string $path
91
-	 * @return bool
92
-	 */
93
-	public function mkdir($path) {
94
-		return $this->getWrapperStorage()->mkdir($this->getUnjailedPath($path));
95
-	}
96
-
97
-	/**
98
-	 * see https://www.php.net/manual/en/function.rmdir.php
99
-	 *
100
-	 * @param string $path
101
-	 * @return bool
102
-	 */
103
-	public function rmdir($path) {
104
-		return $this->getWrapperStorage()->rmdir($this->getUnjailedPath($path));
105
-	}
106
-
107
-	/**
108
-	 * see https://www.php.net/manual/en/function.opendir.php
109
-	 *
110
-	 * @param string $path
111
-	 * @return resource|false
112
-	 */
113
-	public function opendir($path) {
114
-		return $this->getWrapperStorage()->opendir($this->getUnjailedPath($path));
115
-	}
116
-
117
-	/**
118
-	 * see https://www.php.net/manual/en/function.is_dir.php
119
-	 *
120
-	 * @param string $path
121
-	 * @return bool
122
-	 */
123
-	public function is_dir($path) {
124
-		return $this->getWrapperStorage()->is_dir($this->getUnjailedPath($path));
125
-	}
126
-
127
-	/**
128
-	 * see https://www.php.net/manual/en/function.is_file.php
129
-	 *
130
-	 * @param string $path
131
-	 * @return bool
132
-	 */
133
-	public function is_file($path) {
134
-		return $this->getWrapperStorage()->is_file($this->getUnjailedPath($path));
135
-	}
136
-
137
-	/**
138
-	 * see https://www.php.net/manual/en/function.stat.php
139
-	 * only the following keys are required in the result: size and mtime
140
-	 *
141
-	 * @param string $path
142
-	 * @return array|bool
143
-	 */
144
-	public function stat($path) {
145
-		return $this->getWrapperStorage()->stat($this->getUnjailedPath($path));
146
-	}
147
-
148
-	/**
149
-	 * see https://www.php.net/manual/en/function.filetype.php
150
-	 *
151
-	 * @param string $path
152
-	 * @return bool
153
-	 */
154
-	public function filetype($path) {
155
-		return $this->getWrapperStorage()->filetype($this->getUnjailedPath($path));
156
-	}
157
-
158
-	/**
159
-	 * see https://www.php.net/manual/en/function.filesize.php
160
-	 * The result for filesize when called on a folder is required to be 0
161
-	 */
162
-	public function filesize($path): false|int|float {
163
-		return $this->getWrapperStorage()->filesize($this->getUnjailedPath($path));
164
-	}
165
-
166
-	/**
167
-	 * check if a file can be created in $path
168
-	 *
169
-	 * @param string $path
170
-	 * @return bool
171
-	 */
172
-	public function isCreatable($path) {
173
-		return $this->getWrapperStorage()->isCreatable($this->getUnjailedPath($path));
174
-	}
175
-
176
-	/**
177
-	 * check if a file can be read
178
-	 *
179
-	 * @param string $path
180
-	 * @return bool
181
-	 */
182
-	public function isReadable($path) {
183
-		return $this->getWrapperStorage()->isReadable($this->getUnjailedPath($path));
184
-	}
185
-
186
-	/**
187
-	 * check if a file can be written to
188
-	 *
189
-	 * @param string $path
190
-	 * @return bool
191
-	 */
192
-	public function isUpdatable($path) {
193
-		return $this->getWrapperStorage()->isUpdatable($this->getUnjailedPath($path));
194
-	}
195
-
196
-	/**
197
-	 * check if a file can be deleted
198
-	 *
199
-	 * @param string $path
200
-	 * @return bool
201
-	 */
202
-	public function isDeletable($path) {
203
-		return $this->getWrapperStorage()->isDeletable($this->getUnjailedPath($path));
204
-	}
205
-
206
-	/**
207
-	 * check if a file can be shared
208
-	 *
209
-	 * @param string $path
210
-	 * @return bool
211
-	 */
212
-	public function isSharable($path) {
213
-		return $this->getWrapperStorage()->isSharable($this->getUnjailedPath($path));
214
-	}
215
-
216
-	/**
217
-	 * get the full permissions of a path.
218
-	 * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
219
-	 *
220
-	 * @param string $path
221
-	 * @return int
222
-	 */
223
-	public function getPermissions($path) {
224
-		return $this->getWrapperStorage()->getPermissions($this->getUnjailedPath($path));
225
-	}
226
-
227
-	/**
228
-	 * see https://www.php.net/manual/en/function.file_exists.php
229
-	 *
230
-	 * @param string $path
231
-	 * @return bool
232
-	 */
233
-	public function file_exists($path) {
234
-		return $this->getWrapperStorage()->file_exists($this->getUnjailedPath($path));
235
-	}
236
-
237
-	/**
238
-	 * see https://www.php.net/manual/en/function.filemtime.php
239
-	 *
240
-	 * @param string $path
241
-	 * @return int|bool
242
-	 */
243
-	public function filemtime($path) {
244
-		return $this->getWrapperStorage()->filemtime($this->getUnjailedPath($path));
245
-	}
246
-
247
-	/**
248
-	 * see https://www.php.net/manual/en/function.file_get_contents.php
249
-	 *
250
-	 * @param string $path
251
-	 * @return string|false
252
-	 */
253
-	public function file_get_contents($path) {
254
-		return $this->getWrapperStorage()->file_get_contents($this->getUnjailedPath($path));
255
-	}
256
-
257
-	/**
258
-	 * see https://www.php.net/manual/en/function.file_put_contents.php
259
-	 *
260
-	 * @param string $path
261
-	 * @param mixed $data
262
-	 * @return int|float|false
263
-	 */
264
-	public function file_put_contents($path, $data) {
265
-		return $this->getWrapperStorage()->file_put_contents($this->getUnjailedPath($path), $data);
266
-	}
267
-
268
-	/**
269
-	 * see https://www.php.net/manual/en/function.unlink.php
270
-	 *
271
-	 * @param string $path
272
-	 * @return bool
273
-	 */
274
-	public function unlink($path) {
275
-		return $this->getWrapperStorage()->unlink($this->getUnjailedPath($path));
276
-	}
277
-
278
-	/**
279
-	 * see https://www.php.net/manual/en/function.rename.php
280
-	 *
281
-	 * @param string $source
282
-	 * @param string $target
283
-	 * @return bool
284
-	 */
285
-	public function rename($source, $target) {
286
-		return $this->getWrapperStorage()->rename($this->getUnjailedPath($source), $this->getUnjailedPath($target));
287
-	}
288
-
289
-	/**
290
-	 * see https://www.php.net/manual/en/function.copy.php
291
-	 *
292
-	 * @param string $source
293
-	 * @param string $target
294
-	 * @return bool
295
-	 */
296
-	public function copy($source, $target) {
297
-		return $this->getWrapperStorage()->copy($this->getUnjailedPath($source), $this->getUnjailedPath($target));
298
-	}
299
-
300
-	/**
301
-	 * see https://www.php.net/manual/en/function.fopen.php
302
-	 *
303
-	 * @param string $path
304
-	 * @param string $mode
305
-	 * @return resource|bool
306
-	 */
307
-	public function fopen($path, $mode) {
308
-		return $this->getWrapperStorage()->fopen($this->getUnjailedPath($path), $mode);
309
-	}
310
-
311
-	/**
312
-	 * get the mimetype for a file or folder
313
-	 * The mimetype for a folder is required to be "httpd/unix-directory"
314
-	 *
315
-	 * @param string $path
316
-	 * @return string|bool
317
-	 */
318
-	public function getMimeType($path) {
319
-		return $this->getWrapperStorage()->getMimeType($this->getUnjailedPath($path));
320
-	}
321
-
322
-	/**
323
-	 * see https://www.php.net/manual/en/function.hash.php
324
-	 *
325
-	 * @param string $type
326
-	 * @param string $path
327
-	 * @param bool $raw
328
-	 * @return string|bool
329
-	 */
330
-	public function hash($type, $path, $raw = false) {
331
-		return $this->getWrapperStorage()->hash($type, $this->getUnjailedPath($path), $raw);
332
-	}
333
-
334
-	/**
335
-	 * see https://www.php.net/manual/en/function.free_space.php
336
-	 *
337
-	 * @param string $path
338
-	 * @return int|float|bool
339
-	 */
340
-	public function free_space($path) {
341
-		return $this->getWrapperStorage()->free_space($this->getUnjailedPath($path));
342
-	}
343
-
344
-	/**
345
-	 * search for occurrences of $query in file names
346
-	 *
347
-	 * @param string $query
348
-	 * @return array|bool
349
-	 */
350
-	public function search($query) {
351
-		return $this->getWrapperStorage()->search($query);
352
-	}
353
-
354
-	/**
355
-	 * see https://www.php.net/manual/en/function.touch.php
356
-	 * If the backend does not support the operation, false should be returned
357
-	 *
358
-	 * @param string $path
359
-	 * @param int $mtime
360
-	 * @return bool
361
-	 */
362
-	public function touch($path, $mtime = null) {
363
-		return $this->getWrapperStorage()->touch($this->getUnjailedPath($path), $mtime);
364
-	}
365
-
366
-	/**
367
-	 * get the path to a local version of the file.
368
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
369
-	 *
370
-	 * @param string $path
371
-	 * @return string|false
372
-	 */
373
-	public function getLocalFile($path) {
374
-		return $this->getWrapperStorage()->getLocalFile($this->getUnjailedPath($path));
375
-	}
376
-
377
-	/**
378
-	 * check if a file or folder has been updated since $time
379
-	 *
380
-	 * @param string $path
381
-	 * @param int $time
382
-	 * @return bool
383
-	 *
384
-	 * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
385
-	 * returning true for other changes in the folder is optional
386
-	 */
387
-	public function hasUpdated($path, $time) {
388
-		return $this->getWrapperStorage()->hasUpdated($this->getUnjailedPath($path), $time);
389
-	}
390
-
391
-	/**
392
-	 * get a cache instance for the storage
393
-	 *
394
-	 * @param string $path
395
-	 * @param \OC\Files\Storage\Storage|null (optional) the storage to pass to the cache
396
-	 * @return \OC\Files\Cache\Cache
397
-	 */
398
-	public function getCache($path = '', $storage = null) {
399
-		if (!$storage) {
400
-			$storage = $this->getWrapperStorage();
401
-		}
402
-		$sourceCache = $this->getWrapperStorage()->getCache($this->getUnjailedPath($path), $storage);
403
-		return new CacheJail($sourceCache, $this->rootPath);
404
-	}
405
-
406
-	/**
407
-	 * get the user id of the owner of a file or folder
408
-	 *
409
-	 * @param string $path
410
-	 * @return string
411
-	 */
412
-	public function getOwner($path) {
413
-		return $this->getWrapperStorage()->getOwner($this->getUnjailedPath($path));
414
-	}
415
-
416
-	/**
417
-	 * get a watcher instance for the cache
418
-	 *
419
-	 * @param string $path
420
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
421
-	 * @return \OC\Files\Cache\Watcher
422
-	 */
423
-	public function getWatcher($path = '', $storage = null) {
424
-		if (!$storage) {
425
-			$storage = $this;
426
-		}
427
-		return $this->getWrapperStorage()->getWatcher($this->getUnjailedPath($path), $storage);
428
-	}
429
-
430
-	/**
431
-	 * get the ETag for a file or folder
432
-	 *
433
-	 * @param string $path
434
-	 * @return string|false
435
-	 */
436
-	public function getETag($path) {
437
-		return $this->getWrapperStorage()->getETag($this->getUnjailedPath($path));
438
-	}
439
-
440
-	public function getMetaData($path) {
441
-		return $this->getWrapperStorage()->getMetaData($this->getUnjailedPath($path));
442
-	}
443
-
444
-	/**
445
-	 * @param string $path
446
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
447
-	 * @param \OCP\Lock\ILockingProvider $provider
448
-	 * @throws \OCP\Lock\LockedException
449
-	 */
450
-	public function acquireLock($path, $type, ILockingProvider $provider) {
451
-		$this->getWrapperStorage()->acquireLock($this->getUnjailedPath($path), $type, $provider);
452
-	}
453
-
454
-	/**
455
-	 * @param string $path
456
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
457
-	 * @param \OCP\Lock\ILockingProvider $provider
458
-	 */
459
-	public function releaseLock($path, $type, ILockingProvider $provider) {
460
-		$this->getWrapperStorage()->releaseLock($this->getUnjailedPath($path), $type, $provider);
461
-	}
462
-
463
-	/**
464
-	 * @param string $path
465
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
466
-	 * @param \OCP\Lock\ILockingProvider $provider
467
-	 */
468
-	public function changeLock($path, $type, ILockingProvider $provider) {
469
-		$this->getWrapperStorage()->changeLock($this->getUnjailedPath($path), $type, $provider);
470
-	}
471
-
472
-	/**
473
-	 * Resolve the path for the source of the share
474
-	 *
475
-	 * @param string $path
476
-	 * @return array
477
-	 */
478
-	public function resolvePath($path) {
479
-		return [$this->getWrapperStorage(), $this->getUnjailedPath($path)];
480
-	}
481
-
482
-	/**
483
-	 * @param IStorage $sourceStorage
484
-	 * @param string $sourceInternalPath
485
-	 * @param string $targetInternalPath
486
-	 * @return bool
487
-	 */
488
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
489
-		if ($sourceStorage === $this) {
490
-			return $this->copy($sourceInternalPath, $targetInternalPath);
491
-		}
492
-		return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
493
-	}
494
-
495
-	/**
496
-	 * @param IStorage $sourceStorage
497
-	 * @param string $sourceInternalPath
498
-	 * @param string $targetInternalPath
499
-	 * @return bool
500
-	 */
501
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
502
-		if ($sourceStorage === $this) {
503
-			return $this->rename($sourceInternalPath, $targetInternalPath);
504
-		}
505
-		return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
506
-	}
507
-
508
-	public function getPropagator($storage = null) {
509
-		if (isset($this->propagator)) {
510
-			return $this->propagator;
511
-		}
512
-
513
-		if (!$storage) {
514
-			$storage = $this;
515
-		}
516
-		$this->propagator = new JailPropagator($storage, \OC::$server->getDatabaseConnection());
517
-		return $this->propagator;
518
-	}
519
-
520
-	public function writeStream(string $path, $stream, int $size = null): int {
521
-		$storage = $this->getWrapperStorage();
522
-		if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
523
-			/** @var IWriteStreamStorage $storage */
524
-			return $storage->writeStream($this->getUnjailedPath($path), $stream, $size);
525
-		} else {
526
-			$target = $this->fopen($path, 'w');
527
-			[$count, $result] = \OC_Helper::streamCopy($stream, $target);
528
-			fclose($stream);
529
-			fclose($target);
530
-			return $count;
531
-		}
532
-	}
533
-
534
-	public function getDirectoryContent($directory): \Traversable {
535
-		return $this->getWrapperStorage()->getDirectoryContent($this->getUnjailedPath($directory));
536
-	}
44
+    /**
45
+     * @var string
46
+     */
47
+    protected $rootPath;
48
+
49
+    /**
50
+     * @param array $arguments ['storage' => $storage, 'root' => $root]
51
+     *
52
+     * $storage: The storage that will be wrapper
53
+     * $root: The folder in the wrapped storage that will become the root folder of the wrapped storage
54
+     */
55
+    public function __construct($arguments) {
56
+        parent::__construct($arguments);
57
+        $this->rootPath = $arguments['root'];
58
+    }
59
+
60
+    public function getUnjailedPath($path) {
61
+        return trim(Filesystem::normalizePath($this->rootPath . '/' . $path), '/');
62
+    }
63
+
64
+    /**
65
+     * This is separate from Wrapper::getWrapperStorage so we can get the jailed storage consistently even if the jail is inside another wrapper
66
+     */
67
+    public function getUnjailedStorage() {
68
+        return $this->storage;
69
+    }
70
+
71
+
72
+    public function getJailedPath($path) {
73
+        $root = rtrim($this->rootPath, '/') . '/';
74
+
75
+        if ($path !== $this->rootPath && strpos($path, $root) !== 0) {
76
+            return null;
77
+        } else {
78
+            $path = substr($path, strlen($this->rootPath));
79
+            return trim($path, '/');
80
+        }
81
+    }
82
+
83
+    public function getId() {
84
+        return parent::getId();
85
+    }
86
+
87
+    /**
88
+     * see https://www.php.net/manual/en/function.mkdir.php
89
+     *
90
+     * @param string $path
91
+     * @return bool
92
+     */
93
+    public function mkdir($path) {
94
+        return $this->getWrapperStorage()->mkdir($this->getUnjailedPath($path));
95
+    }
96
+
97
+    /**
98
+     * see https://www.php.net/manual/en/function.rmdir.php
99
+     *
100
+     * @param string $path
101
+     * @return bool
102
+     */
103
+    public function rmdir($path) {
104
+        return $this->getWrapperStorage()->rmdir($this->getUnjailedPath($path));
105
+    }
106
+
107
+    /**
108
+     * see https://www.php.net/manual/en/function.opendir.php
109
+     *
110
+     * @param string $path
111
+     * @return resource|false
112
+     */
113
+    public function opendir($path) {
114
+        return $this->getWrapperStorage()->opendir($this->getUnjailedPath($path));
115
+    }
116
+
117
+    /**
118
+     * see https://www.php.net/manual/en/function.is_dir.php
119
+     *
120
+     * @param string $path
121
+     * @return bool
122
+     */
123
+    public function is_dir($path) {
124
+        return $this->getWrapperStorage()->is_dir($this->getUnjailedPath($path));
125
+    }
126
+
127
+    /**
128
+     * see https://www.php.net/manual/en/function.is_file.php
129
+     *
130
+     * @param string $path
131
+     * @return bool
132
+     */
133
+    public function is_file($path) {
134
+        return $this->getWrapperStorage()->is_file($this->getUnjailedPath($path));
135
+    }
136
+
137
+    /**
138
+     * see https://www.php.net/manual/en/function.stat.php
139
+     * only the following keys are required in the result: size and mtime
140
+     *
141
+     * @param string $path
142
+     * @return array|bool
143
+     */
144
+    public function stat($path) {
145
+        return $this->getWrapperStorage()->stat($this->getUnjailedPath($path));
146
+    }
147
+
148
+    /**
149
+     * see https://www.php.net/manual/en/function.filetype.php
150
+     *
151
+     * @param string $path
152
+     * @return bool
153
+     */
154
+    public function filetype($path) {
155
+        return $this->getWrapperStorage()->filetype($this->getUnjailedPath($path));
156
+    }
157
+
158
+    /**
159
+     * see https://www.php.net/manual/en/function.filesize.php
160
+     * The result for filesize when called on a folder is required to be 0
161
+     */
162
+    public function filesize($path): false|int|float {
163
+        return $this->getWrapperStorage()->filesize($this->getUnjailedPath($path));
164
+    }
165
+
166
+    /**
167
+     * check if a file can be created in $path
168
+     *
169
+     * @param string $path
170
+     * @return bool
171
+     */
172
+    public function isCreatable($path) {
173
+        return $this->getWrapperStorage()->isCreatable($this->getUnjailedPath($path));
174
+    }
175
+
176
+    /**
177
+     * check if a file can be read
178
+     *
179
+     * @param string $path
180
+     * @return bool
181
+     */
182
+    public function isReadable($path) {
183
+        return $this->getWrapperStorage()->isReadable($this->getUnjailedPath($path));
184
+    }
185
+
186
+    /**
187
+     * check if a file can be written to
188
+     *
189
+     * @param string $path
190
+     * @return bool
191
+     */
192
+    public function isUpdatable($path) {
193
+        return $this->getWrapperStorage()->isUpdatable($this->getUnjailedPath($path));
194
+    }
195
+
196
+    /**
197
+     * check if a file can be deleted
198
+     *
199
+     * @param string $path
200
+     * @return bool
201
+     */
202
+    public function isDeletable($path) {
203
+        return $this->getWrapperStorage()->isDeletable($this->getUnjailedPath($path));
204
+    }
205
+
206
+    /**
207
+     * check if a file can be shared
208
+     *
209
+     * @param string $path
210
+     * @return bool
211
+     */
212
+    public function isSharable($path) {
213
+        return $this->getWrapperStorage()->isSharable($this->getUnjailedPath($path));
214
+    }
215
+
216
+    /**
217
+     * get the full permissions of a path.
218
+     * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
219
+     *
220
+     * @param string $path
221
+     * @return int
222
+     */
223
+    public function getPermissions($path) {
224
+        return $this->getWrapperStorage()->getPermissions($this->getUnjailedPath($path));
225
+    }
226
+
227
+    /**
228
+     * see https://www.php.net/manual/en/function.file_exists.php
229
+     *
230
+     * @param string $path
231
+     * @return bool
232
+     */
233
+    public function file_exists($path) {
234
+        return $this->getWrapperStorage()->file_exists($this->getUnjailedPath($path));
235
+    }
236
+
237
+    /**
238
+     * see https://www.php.net/manual/en/function.filemtime.php
239
+     *
240
+     * @param string $path
241
+     * @return int|bool
242
+     */
243
+    public function filemtime($path) {
244
+        return $this->getWrapperStorage()->filemtime($this->getUnjailedPath($path));
245
+    }
246
+
247
+    /**
248
+     * see https://www.php.net/manual/en/function.file_get_contents.php
249
+     *
250
+     * @param string $path
251
+     * @return string|false
252
+     */
253
+    public function file_get_contents($path) {
254
+        return $this->getWrapperStorage()->file_get_contents($this->getUnjailedPath($path));
255
+    }
256
+
257
+    /**
258
+     * see https://www.php.net/manual/en/function.file_put_contents.php
259
+     *
260
+     * @param string $path
261
+     * @param mixed $data
262
+     * @return int|float|false
263
+     */
264
+    public function file_put_contents($path, $data) {
265
+        return $this->getWrapperStorage()->file_put_contents($this->getUnjailedPath($path), $data);
266
+    }
267
+
268
+    /**
269
+     * see https://www.php.net/manual/en/function.unlink.php
270
+     *
271
+     * @param string $path
272
+     * @return bool
273
+     */
274
+    public function unlink($path) {
275
+        return $this->getWrapperStorage()->unlink($this->getUnjailedPath($path));
276
+    }
277
+
278
+    /**
279
+     * see https://www.php.net/manual/en/function.rename.php
280
+     *
281
+     * @param string $source
282
+     * @param string $target
283
+     * @return bool
284
+     */
285
+    public function rename($source, $target) {
286
+        return $this->getWrapperStorage()->rename($this->getUnjailedPath($source), $this->getUnjailedPath($target));
287
+    }
288
+
289
+    /**
290
+     * see https://www.php.net/manual/en/function.copy.php
291
+     *
292
+     * @param string $source
293
+     * @param string $target
294
+     * @return bool
295
+     */
296
+    public function copy($source, $target) {
297
+        return $this->getWrapperStorage()->copy($this->getUnjailedPath($source), $this->getUnjailedPath($target));
298
+    }
299
+
300
+    /**
301
+     * see https://www.php.net/manual/en/function.fopen.php
302
+     *
303
+     * @param string $path
304
+     * @param string $mode
305
+     * @return resource|bool
306
+     */
307
+    public function fopen($path, $mode) {
308
+        return $this->getWrapperStorage()->fopen($this->getUnjailedPath($path), $mode);
309
+    }
310
+
311
+    /**
312
+     * get the mimetype for a file or folder
313
+     * The mimetype for a folder is required to be "httpd/unix-directory"
314
+     *
315
+     * @param string $path
316
+     * @return string|bool
317
+     */
318
+    public function getMimeType($path) {
319
+        return $this->getWrapperStorage()->getMimeType($this->getUnjailedPath($path));
320
+    }
321
+
322
+    /**
323
+     * see https://www.php.net/manual/en/function.hash.php
324
+     *
325
+     * @param string $type
326
+     * @param string $path
327
+     * @param bool $raw
328
+     * @return string|bool
329
+     */
330
+    public function hash($type, $path, $raw = false) {
331
+        return $this->getWrapperStorage()->hash($type, $this->getUnjailedPath($path), $raw);
332
+    }
333
+
334
+    /**
335
+     * see https://www.php.net/manual/en/function.free_space.php
336
+     *
337
+     * @param string $path
338
+     * @return int|float|bool
339
+     */
340
+    public function free_space($path) {
341
+        return $this->getWrapperStorage()->free_space($this->getUnjailedPath($path));
342
+    }
343
+
344
+    /**
345
+     * search for occurrences of $query in file names
346
+     *
347
+     * @param string $query
348
+     * @return array|bool
349
+     */
350
+    public function search($query) {
351
+        return $this->getWrapperStorage()->search($query);
352
+    }
353
+
354
+    /**
355
+     * see https://www.php.net/manual/en/function.touch.php
356
+     * If the backend does not support the operation, false should be returned
357
+     *
358
+     * @param string $path
359
+     * @param int $mtime
360
+     * @return bool
361
+     */
362
+    public function touch($path, $mtime = null) {
363
+        return $this->getWrapperStorage()->touch($this->getUnjailedPath($path), $mtime);
364
+    }
365
+
366
+    /**
367
+     * get the path to a local version of the file.
368
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
369
+     *
370
+     * @param string $path
371
+     * @return string|false
372
+     */
373
+    public function getLocalFile($path) {
374
+        return $this->getWrapperStorage()->getLocalFile($this->getUnjailedPath($path));
375
+    }
376
+
377
+    /**
378
+     * check if a file or folder has been updated since $time
379
+     *
380
+     * @param string $path
381
+     * @param int $time
382
+     * @return bool
383
+     *
384
+     * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
385
+     * returning true for other changes in the folder is optional
386
+     */
387
+    public function hasUpdated($path, $time) {
388
+        return $this->getWrapperStorage()->hasUpdated($this->getUnjailedPath($path), $time);
389
+    }
390
+
391
+    /**
392
+     * get a cache instance for the storage
393
+     *
394
+     * @param string $path
395
+     * @param \OC\Files\Storage\Storage|null (optional) the storage to pass to the cache
396
+     * @return \OC\Files\Cache\Cache
397
+     */
398
+    public function getCache($path = '', $storage = null) {
399
+        if (!$storage) {
400
+            $storage = $this->getWrapperStorage();
401
+        }
402
+        $sourceCache = $this->getWrapperStorage()->getCache($this->getUnjailedPath($path), $storage);
403
+        return new CacheJail($sourceCache, $this->rootPath);
404
+    }
405
+
406
+    /**
407
+     * get the user id of the owner of a file or folder
408
+     *
409
+     * @param string $path
410
+     * @return string
411
+     */
412
+    public function getOwner($path) {
413
+        return $this->getWrapperStorage()->getOwner($this->getUnjailedPath($path));
414
+    }
415
+
416
+    /**
417
+     * get a watcher instance for the cache
418
+     *
419
+     * @param string $path
420
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
421
+     * @return \OC\Files\Cache\Watcher
422
+     */
423
+    public function getWatcher($path = '', $storage = null) {
424
+        if (!$storage) {
425
+            $storage = $this;
426
+        }
427
+        return $this->getWrapperStorage()->getWatcher($this->getUnjailedPath($path), $storage);
428
+    }
429
+
430
+    /**
431
+     * get the ETag for a file or folder
432
+     *
433
+     * @param string $path
434
+     * @return string|false
435
+     */
436
+    public function getETag($path) {
437
+        return $this->getWrapperStorage()->getETag($this->getUnjailedPath($path));
438
+    }
439
+
440
+    public function getMetaData($path) {
441
+        return $this->getWrapperStorage()->getMetaData($this->getUnjailedPath($path));
442
+    }
443
+
444
+    /**
445
+     * @param string $path
446
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
447
+     * @param \OCP\Lock\ILockingProvider $provider
448
+     * @throws \OCP\Lock\LockedException
449
+     */
450
+    public function acquireLock($path, $type, ILockingProvider $provider) {
451
+        $this->getWrapperStorage()->acquireLock($this->getUnjailedPath($path), $type, $provider);
452
+    }
453
+
454
+    /**
455
+     * @param string $path
456
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
457
+     * @param \OCP\Lock\ILockingProvider $provider
458
+     */
459
+    public function releaseLock($path, $type, ILockingProvider $provider) {
460
+        $this->getWrapperStorage()->releaseLock($this->getUnjailedPath($path), $type, $provider);
461
+    }
462
+
463
+    /**
464
+     * @param string $path
465
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
466
+     * @param \OCP\Lock\ILockingProvider $provider
467
+     */
468
+    public function changeLock($path, $type, ILockingProvider $provider) {
469
+        $this->getWrapperStorage()->changeLock($this->getUnjailedPath($path), $type, $provider);
470
+    }
471
+
472
+    /**
473
+     * Resolve the path for the source of the share
474
+     *
475
+     * @param string $path
476
+     * @return array
477
+     */
478
+    public function resolvePath($path) {
479
+        return [$this->getWrapperStorage(), $this->getUnjailedPath($path)];
480
+    }
481
+
482
+    /**
483
+     * @param IStorage $sourceStorage
484
+     * @param string $sourceInternalPath
485
+     * @param string $targetInternalPath
486
+     * @return bool
487
+     */
488
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
489
+        if ($sourceStorage === $this) {
490
+            return $this->copy($sourceInternalPath, $targetInternalPath);
491
+        }
492
+        return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
493
+    }
494
+
495
+    /**
496
+     * @param IStorage $sourceStorage
497
+     * @param string $sourceInternalPath
498
+     * @param string $targetInternalPath
499
+     * @return bool
500
+     */
501
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
502
+        if ($sourceStorage === $this) {
503
+            return $this->rename($sourceInternalPath, $targetInternalPath);
504
+        }
505
+        return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $this->getUnjailedPath($targetInternalPath));
506
+    }
507
+
508
+    public function getPropagator($storage = null) {
509
+        if (isset($this->propagator)) {
510
+            return $this->propagator;
511
+        }
512
+
513
+        if (!$storage) {
514
+            $storage = $this;
515
+        }
516
+        $this->propagator = new JailPropagator($storage, \OC::$server->getDatabaseConnection());
517
+        return $this->propagator;
518
+    }
519
+
520
+    public function writeStream(string $path, $stream, int $size = null): int {
521
+        $storage = $this->getWrapperStorage();
522
+        if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
523
+            /** @var IWriteStreamStorage $storage */
524
+            return $storage->writeStream($this->getUnjailedPath($path), $stream, $size);
525
+        } else {
526
+            $target = $this->fopen($path, 'w');
527
+            [$count, $result] = \OC_Helper::streamCopy($stream, $target);
528
+            fclose($stream);
529
+            fclose($target);
530
+            return $count;
531
+        }
532
+    }
533
+
534
+    public function getDirectoryContent($directory): \Traversable {
535
+        return $this->getWrapperStorage()->getDirectoryContent($this->getUnjailedPath($directory));
536
+    }
537 537
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Encryption.php 1 patch
Indentation   +1039 added lines, -1039 removed lines patch added patch discarded remove patch
@@ -56,1043 +56,1043 @@
 block discarded – undo
56 56
 use Psr\Log\LoggerInterface;
57 57
 
58 58
 class Encryption extends Wrapper {
59
-	use LocalTempFileTrait;
60
-
61
-	/** @var string */
62
-	private $mountPoint;
63
-
64
-	/** @var \OC\Encryption\Util */
65
-	private $util;
66
-
67
-	/** @var \OCP\Encryption\IManager */
68
-	private $encryptionManager;
69
-
70
-	private LoggerInterface $logger;
71
-
72
-	/** @var string */
73
-	private $uid;
74
-
75
-	/** @var array */
76
-	protected $unencryptedSize;
77
-
78
-	/** @var \OCP\Encryption\IFile */
79
-	private $fileHelper;
80
-
81
-	/** @var IMountPoint */
82
-	private $mount;
83
-
84
-	/** @var IStorage */
85
-	private $keyStorage;
86
-
87
-	/** @var Update */
88
-	private $update;
89
-
90
-	/** @var Manager */
91
-	private $mountManager;
92
-
93
-	/** @var array remember for which path we execute the repair step to avoid recursions */
94
-	private $fixUnencryptedSizeOf = [];
95
-
96
-	/** @var  ArrayCache */
97
-	private $arrayCache;
98
-
99
-	/** @var CappedMemoryCache<bool> */
100
-	private CappedMemoryCache $encryptedPaths;
101
-
102
-	/**
103
-	 * @param array $parameters
104
-	 */
105
-	public function __construct(
106
-		$parameters,
107
-		IManager $encryptionManager = null,
108
-		Util $util = null,
109
-		LoggerInterface $logger = null,
110
-		IFile $fileHelper = null,
111
-		$uid = null,
112
-		IStorage $keyStorage = null,
113
-		Update $update = null,
114
-		Manager $mountManager = null,
115
-		ArrayCache $arrayCache = null
116
-	) {
117
-		$this->mountPoint = $parameters['mountPoint'];
118
-		$this->mount = $parameters['mount'];
119
-		$this->encryptionManager = $encryptionManager;
120
-		$this->util = $util;
121
-		$this->logger = $logger;
122
-		$this->uid = $uid;
123
-		$this->fileHelper = $fileHelper;
124
-		$this->keyStorage = $keyStorage;
125
-		$this->unencryptedSize = [];
126
-		$this->update = $update;
127
-		$this->mountManager = $mountManager;
128
-		$this->arrayCache = $arrayCache;
129
-		$this->encryptedPaths = new CappedMemoryCache();
130
-		parent::__construct($parameters);
131
-	}
132
-
133
-	/**
134
-	 * see https://www.php.net/manual/en/function.filesize.php
135
-	 * The result for filesize when called on a folder is required to be 0
136
-	 */
137
-	public function filesize($path): false|int|float {
138
-		$fullPath = $this->getFullPath($path);
139
-
140
-		$info = $this->getCache()->get($path);
141
-		if ($info === false) {
142
-			return false;
143
-		}
144
-		if (isset($this->unencryptedSize[$fullPath])) {
145
-			$size = $this->unencryptedSize[$fullPath];
146
-			// update file cache
147
-			if ($info instanceof ICacheEntry) {
148
-				$info['encrypted'] = $info['encryptedVersion'];
149
-			} else {
150
-				if (!is_array($info)) {
151
-					$info = [];
152
-				}
153
-				$info['encrypted'] = true;
154
-				$info = new CacheEntry($info);
155
-			}
156
-
157
-			if ($size !== $info->getUnencryptedSize()) {
158
-				$this->getCache()->update($info->getId(), [
159
-					'unencrypted_size' => $size
160
-				]);
161
-			}
162
-
163
-			return $size;
164
-		}
165
-
166
-		if (isset($info['fileid']) && $info['encrypted']) {
167
-			return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
168
-		}
169
-
170
-		return $this->storage->filesize($path);
171
-	}
172
-
173
-	/**
174
-	 * @param string $path
175
-	 * @param array $data
176
-	 * @return array
177
-	 */
178
-	private function modifyMetaData(string $path, array $data): array {
179
-		$fullPath = $this->getFullPath($path);
180
-		$info = $this->getCache()->get($path);
181
-
182
-		if (isset($this->unencryptedSize[$fullPath])) {
183
-			$data['encrypted'] = true;
184
-			$data['size'] = $this->unencryptedSize[$fullPath];
185
-			$data['unencrypted_size'] = $data['size'];
186
-		} else {
187
-			if (isset($info['fileid']) && $info['encrypted']) {
188
-				$data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
189
-				$data['encrypted'] = true;
190
-				$data['unencrypted_size'] = $data['size'];
191
-			}
192
-		}
193
-
194
-		if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
195
-			$data['encryptedVersion'] = $info['encryptedVersion'];
196
-		}
197
-
198
-		return $data;
199
-	}
200
-
201
-	public function getMetaData($path) {
202
-		$data = $this->storage->getMetaData($path);
203
-		if (is_null($data)) {
204
-			return null;
205
-		}
206
-		return $this->modifyMetaData($path, $data);
207
-	}
208
-
209
-	public function getDirectoryContent($directory): \Traversable {
210
-		$parent = rtrim($directory, '/');
211
-		foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
212
-			yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
213
-		}
214
-	}
215
-
216
-	/**
217
-	 * see https://www.php.net/manual/en/function.file_get_contents.php
218
-	 *
219
-	 * @param string $path
220
-	 * @return string|false
221
-	 */
222
-	public function file_get_contents($path) {
223
-		$encryptionModule = $this->getEncryptionModule($path);
224
-
225
-		if ($encryptionModule) {
226
-			$handle = $this->fopen($path, "r");
227
-			if (!$handle) {
228
-				return false;
229
-			}
230
-			$data = stream_get_contents($handle);
231
-			fclose($handle);
232
-			return $data;
233
-		}
234
-		return $this->storage->file_get_contents($path);
235
-	}
236
-
237
-	/**
238
-	 * see https://www.php.net/manual/en/function.file_put_contents.php
239
-	 *
240
-	 * @param string $path
241
-	 * @param mixed $data
242
-	 * @return int|false
243
-	 */
244
-	public function file_put_contents($path, $data) {
245
-		// file put content will always be translated to a stream write
246
-		$handle = $this->fopen($path, 'w');
247
-		if (is_resource($handle)) {
248
-			$written = fwrite($handle, $data);
249
-			fclose($handle);
250
-			return $written;
251
-		}
252
-
253
-		return false;
254
-	}
255
-
256
-	/**
257
-	 * see https://www.php.net/manual/en/function.unlink.php
258
-	 *
259
-	 * @param string $path
260
-	 * @return bool
261
-	 */
262
-	public function unlink($path) {
263
-		$fullPath = $this->getFullPath($path);
264
-		if ($this->util->isExcluded($fullPath)) {
265
-			return $this->storage->unlink($path);
266
-		}
267
-
268
-		$encryptionModule = $this->getEncryptionModule($path);
269
-		if ($encryptionModule) {
270
-			$this->keyStorage->deleteAllFileKeys($fullPath);
271
-		}
272
-
273
-		return $this->storage->unlink($path);
274
-	}
275
-
276
-	/**
277
-	 * see https://www.php.net/manual/en/function.rename.php
278
-	 *
279
-	 * @param string $source
280
-	 * @param string $target
281
-	 * @return bool
282
-	 */
283
-	public function rename($source, $target) {
284
-		$result = $this->storage->rename($source, $target);
285
-
286
-		if ($result &&
287
-			// versions always use the keys from the original file, so we can skip
288
-			// this step for versions
289
-			$this->isVersion($target) === false &&
290
-			$this->encryptionManager->isEnabled()) {
291
-			$sourcePath = $this->getFullPath($source);
292
-			if (!$this->util->isExcluded($sourcePath)) {
293
-				$targetPath = $this->getFullPath($target);
294
-				if (isset($this->unencryptedSize[$sourcePath])) {
295
-					$this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
296
-				}
297
-				$this->keyStorage->renameKeys($sourcePath, $targetPath);
298
-				$module = $this->getEncryptionModule($target);
299
-				if ($module) {
300
-					$module->update($targetPath, $this->uid, []);
301
-				}
302
-			}
303
-		}
304
-
305
-		return $result;
306
-	}
307
-
308
-	/**
309
-	 * see https://www.php.net/manual/en/function.rmdir.php
310
-	 *
311
-	 * @param string $path
312
-	 * @return bool
313
-	 */
314
-	public function rmdir($path) {
315
-		$result = $this->storage->rmdir($path);
316
-		$fullPath = $this->getFullPath($path);
317
-		if ($result &&
318
-			$this->util->isExcluded($fullPath) === false &&
319
-			$this->encryptionManager->isEnabled()
320
-		) {
321
-			$this->keyStorage->deleteAllFileKeys($fullPath);
322
-		}
323
-
324
-		return $result;
325
-	}
326
-
327
-	/**
328
-	 * check if a file can be read
329
-	 *
330
-	 * @param string $path
331
-	 * @return bool
332
-	 */
333
-	public function isReadable($path) {
334
-		$isReadable = true;
335
-
336
-		$metaData = $this->getMetaData($path);
337
-		if (
338
-			!$this->is_dir($path) &&
339
-			isset($metaData['encrypted']) &&
340
-			$metaData['encrypted'] === true
341
-		) {
342
-			$fullPath = $this->getFullPath($path);
343
-			$module = $this->getEncryptionModule($path);
344
-			$isReadable = $module->isReadable($fullPath, $this->uid);
345
-		}
346
-
347
-		return $this->storage->isReadable($path) && $isReadable;
348
-	}
349
-
350
-	/**
351
-	 * see https://www.php.net/manual/en/function.copy.php
352
-	 *
353
-	 * @param string $source
354
-	 * @param string $target
355
-	 */
356
-	public function copy($source, $target): bool {
357
-		$sourcePath = $this->getFullPath($source);
358
-
359
-		if ($this->util->isExcluded($sourcePath)) {
360
-			return $this->storage->copy($source, $target);
361
-		}
362
-
363
-		// need to stream copy file by file in case we copy between a encrypted
364
-		// and a unencrypted storage
365
-		$this->unlink($target);
366
-		return $this->copyFromStorage($this, $source, $target);
367
-	}
368
-
369
-	/**
370
-	 * see https://www.php.net/manual/en/function.fopen.php
371
-	 *
372
-	 * @param string $path
373
-	 * @param string $mode
374
-	 * @return resource|bool
375
-	 * @throws GenericEncryptionException
376
-	 * @throws ModuleDoesNotExistsException
377
-	 */
378
-	public function fopen($path, $mode) {
379
-		// check if the file is stored in the array cache, this means that we
380
-		// copy a file over to the versions folder, in this case we don't want to
381
-		// decrypt it
382
-		if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
383
-			$this->arrayCache->remove('encryption_copy_version_' . $path);
384
-			return $this->storage->fopen($path, $mode);
385
-		}
386
-
387
-		$encryptionEnabled = $this->encryptionManager->isEnabled();
388
-		$shouldEncrypt = false;
389
-		$encryptionModule = null;
390
-		$header = $this->getHeader($path);
391
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
392
-		$fullPath = $this->getFullPath($path);
393
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
394
-
395
-		if ($this->util->isExcluded($fullPath) === false) {
396
-			$size = $unencryptedSize = 0;
397
-			$realFile = $this->util->stripPartialFileExtension($path);
398
-			$targetExists = $this->is_file($realFile) || $this->file_exists($path);
399
-			$targetIsEncrypted = false;
400
-			if ($targetExists) {
401
-				// in case the file exists we require the explicit module as
402
-				// specified in the file header - otherwise we need to fail hard to
403
-				// prevent data loss on client side
404
-				if (!empty($encryptionModuleId)) {
405
-					$targetIsEncrypted = true;
406
-					$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
407
-				}
408
-
409
-				if ($this->file_exists($path)) {
410
-					$size = $this->storage->filesize($path);
411
-					$unencryptedSize = $this->filesize($path);
412
-				} else {
413
-					$size = $unencryptedSize = 0;
414
-				}
415
-			}
416
-
417
-			try {
418
-				if (
419
-					$mode === 'w'
420
-					|| $mode === 'w+'
421
-					|| $mode === 'wb'
422
-					|| $mode === 'wb+'
423
-				) {
424
-					// if we update a encrypted file with a un-encrypted one we change the db flag
425
-					if ($targetIsEncrypted && $encryptionEnabled === false) {
426
-						$cache = $this->storage->getCache();
427
-						if ($cache) {
428
-							$entry = $cache->get($path);
429
-							$cache->update($entry->getId(), ['encrypted' => 0]);
430
-						}
431
-					}
432
-					if ($encryptionEnabled) {
433
-						// if $encryptionModuleId is empty, the default module will be used
434
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
435
-						$shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
436
-						$signed = true;
437
-					}
438
-				} else {
439
-					$info = $this->getCache()->get($path);
440
-					// only get encryption module if we found one in the header
441
-					// or if file should be encrypted according to the file cache
442
-					if (!empty($encryptionModuleId)) {
443
-						$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
444
-						$shouldEncrypt = true;
445
-					} elseif (empty($encryptionModuleId) && $info['encrypted'] === true) {
446
-						// we come from a old installation. No header and/or no module defined
447
-						// but the file is encrypted. In this case we need to use the
448
-						// OC_DEFAULT_MODULE to read the file
449
-						$encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
450
-						$shouldEncrypt = true;
451
-						$targetIsEncrypted = true;
452
-					}
453
-				}
454
-			} catch (ModuleDoesNotExistsException $e) {
455
-				$this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
456
-					'exception' => $e,
457
-					'app' => 'core',
458
-				]);
459
-			}
460
-
461
-			// encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
462
-			if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
463
-				if (!$targetExists || !$targetIsEncrypted) {
464
-					$shouldEncrypt = false;
465
-				}
466
-			}
467
-
468
-			if ($shouldEncrypt === true && $encryptionModule !== null) {
469
-				$this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
470
-				$headerSize = $this->getHeaderSize($path);
471
-				$source = $this->storage->fopen($path, $mode);
472
-				if (!is_resource($source)) {
473
-					return false;
474
-				}
475
-				$handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
476
-					$this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
477
-					$size, $unencryptedSize, $headerSize, $signed);
478
-
479
-				return $handle;
480
-			}
481
-		}
482
-
483
-		return $this->storage->fopen($path, $mode);
484
-	}
485
-
486
-
487
-	/**
488
-	 * perform some plausibility checks if the the unencrypted size is correct.
489
-	 * If not, we calculate the correct unencrypted size and return it
490
-	 *
491
-	 * @param string $path internal path relative to the storage root
492
-	 * @param int $unencryptedSize size of the unencrypted file
493
-	 *
494
-	 * @return int unencrypted size
495
-	 */
496
-	protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
497
-		$size = $this->storage->filesize($path);
498
-		$result = $unencryptedSize;
499
-
500
-		if ($unencryptedSize < 0 ||
501
-			($size > 0 && $unencryptedSize === $size) ||
502
-			$unencryptedSize > $size
503
-		) {
504
-			// check if we already calculate the unencrypted size for the
505
-			// given path to avoid recursions
506
-			if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
507
-				$this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
508
-				try {
509
-					$result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
510
-				} catch (\Exception $e) {
511
-					$this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
512
-				}
513
-				unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
514
-			}
515
-		}
516
-
517
-		return $result;
518
-	}
519
-
520
-	/**
521
-	 * calculate the unencrypted size
522
-	 *
523
-	 * @param string $path internal path relative to the storage root
524
-	 * @param int $size size of the physical file
525
-	 * @param int $unencryptedSize size of the unencrypted file
526
-	 *
527
-	 * @return int calculated unencrypted size
528
-	 */
529
-	protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int {
530
-		$headerSize = $this->getHeaderSize($path);
531
-		$header = $this->getHeader($path);
532
-		$encryptionModule = $this->getEncryptionModule($path);
533
-
534
-		$stream = $this->storage->fopen($path, 'r');
535
-
536
-		// if we couldn't open the file we return the old unencrypted size
537
-		if (!is_resource($stream)) {
538
-			$this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
539
-			return $unencryptedSize;
540
-		}
541
-
542
-		$newUnencryptedSize = 0;
543
-		$size -= $headerSize;
544
-		$blockSize = $this->util->getBlockSize();
545
-
546
-		// if a header exists we skip it
547
-		if ($headerSize > 0) {
548
-			$this->fread_block($stream, $headerSize);
549
-		}
550
-
551
-		// fast path, else the calculation for $lastChunkNr is bogus
552
-		if ($size === 0) {
553
-			return 0;
554
-		}
555
-
556
-		$signed = isset($header['signed']) && $header['signed'] === 'true';
557
-		$unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
558
-
559
-		// calculate last chunk nr
560
-		// next highest is end of chunks, one subtracted is last one
561
-		// we have to read the last chunk, we can't just calculate it (because of padding etc)
562
-
563
-		$lastChunkNr = ceil($size / $blockSize) - 1;
564
-		// calculate last chunk position
565
-		$lastChunkPos = ($lastChunkNr * $blockSize);
566
-		// try to fseek to the last chunk, if it fails we have to read the whole file
567
-		if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
568
-			$newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
569
-		}
570
-
571
-		$lastChunkContentEncrypted = '';
572
-		$count = $blockSize;
573
-
574
-		while ($count > 0) {
575
-			$data = $this->fread_block($stream, $blockSize);
576
-			$count = strlen($data);
577
-			$lastChunkContentEncrypted .= $data;
578
-			if (strlen($lastChunkContentEncrypted) > $blockSize) {
579
-				$newUnencryptedSize += $unencryptedBlockSize;
580
-				$lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
581
-			}
582
-		}
583
-
584
-		fclose($stream);
585
-
586
-		// we have to decrypt the last chunk to get it actual size
587
-		$encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
588
-		$decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
589
-		$decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
590
-
591
-		// calc the real file size with the size of the last chunk
592
-		$newUnencryptedSize += strlen($decryptedLastChunk);
593
-
594
-		$this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
595
-
596
-		// write to cache if applicable
597
-		$cache = $this->storage->getCache();
598
-		if ($cache) {
599
-			$entry = $cache->get($path);
600
-			$cache->update($entry['fileid'], [
601
-				'unencrypted_size' => $newUnencryptedSize
602
-			]);
603
-		}
604
-
605
-		return $newUnencryptedSize;
606
-	}
607
-
608
-	/**
609
-	 * fread_block
610
-	 *
611
-	 * This function is a wrapper around the fread function.  It is based on the
612
-	 * stream_read_block function from lib/private/Files/Streams/Encryption.php
613
-	 * It calls stream read until the requested $blockSize was received or no remaining data is present.
614
-	 * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
615
-	 * remote storage over the internet and it does not care about the given $blockSize.
616
-	 *
617
-	 * @param handle the stream to read from
618
-	 * @param int $blockSize Length of requested data block in bytes
619
-	 * @return string Data fetched from stream.
620
-	 */
621
-	private function fread_block($handle, int $blockSize): string {
622
-		$remaining = $blockSize;
623
-		$data = '';
624
-
625
-		do {
626
-			$chunk = fread($handle, $remaining);
627
-			$chunk_len = strlen($chunk);
628
-			$data .= $chunk;
629
-			$remaining -= $chunk_len;
630
-		} while (($remaining > 0) && ($chunk_len > 0));
631
-
632
-		return $data;
633
-	}
634
-
635
-	/**
636
-	 * @param Storage\IStorage $sourceStorage
637
-	 * @param string $sourceInternalPath
638
-	 * @param string $targetInternalPath
639
-	 * @param bool $preserveMtime
640
-	 * @return bool
641
-	 */
642
-	public function moveFromStorage(
643
-		Storage\IStorage $sourceStorage,
644
-		$sourceInternalPath,
645
-		$targetInternalPath,
646
-		$preserveMtime = true
647
-	) {
648
-		if ($sourceStorage === $this) {
649
-			return $this->rename($sourceInternalPath, $targetInternalPath);
650
-		}
651
-
652
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
653
-		// - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
654
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
655
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
656
-		// - remove $this->copyBetweenStorage
657
-
658
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
659
-			return false;
660
-		}
661
-
662
-		$result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
663
-		if ($result) {
664
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
665
-				$result &= $sourceStorage->rmdir($sourceInternalPath);
666
-			} else {
667
-				$result &= $sourceStorage->unlink($sourceInternalPath);
668
-			}
669
-		}
670
-		return $result;
671
-	}
672
-
673
-
674
-	/**
675
-	 * @param Storage\IStorage $sourceStorage
676
-	 * @param string $sourceInternalPath
677
-	 * @param string $targetInternalPath
678
-	 * @param bool $preserveMtime
679
-	 * @param bool $isRename
680
-	 * @return bool
681
-	 */
682
-	public function copyFromStorage(
683
-		Storage\IStorage $sourceStorage,
684
-		$sourceInternalPath,
685
-		$targetInternalPath,
686
-		$preserveMtime = false,
687
-		$isRename = false
688
-	) {
689
-		// TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
690
-		// - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
691
-		// - copy the file cache update from  $this->copyBetweenStorage to this method
692
-		// - copy the copyKeys() call from  $this->copyBetweenStorage to this method
693
-		// - remove $this->copyBetweenStorage
694
-
695
-		return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
696
-	}
697
-
698
-	/**
699
-	 * Update the encrypted cache version in the database
700
-	 *
701
-	 * @param Storage\IStorage $sourceStorage
702
-	 * @param string $sourceInternalPath
703
-	 * @param string $targetInternalPath
704
-	 * @param bool $isRename
705
-	 * @param bool $keepEncryptionVersion
706
-	 */
707
-	private function updateEncryptedVersion(
708
-		Storage\IStorage $sourceStorage,
709
-		$sourceInternalPath,
710
-		$targetInternalPath,
711
-		$isRename,
712
-		$keepEncryptionVersion
713
-	) {
714
-		$isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
715
-		$cacheInformation = [
716
-			'encrypted' => $isEncrypted,
717
-		];
718
-		if ($isEncrypted) {
719
-			$sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
720
-			$targetCacheEntry = $this->getCache()->get($targetInternalPath);
721
-
722
-			// Rename of the cache already happened, so we do the cleanup on the target
723
-			if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
724
-				$encryptedVersion = $targetCacheEntry['encryptedVersion'];
725
-				$isRename = false;
726
-			} else {
727
-				$encryptedVersion = $sourceCacheEntry['encryptedVersion'];
728
-			}
729
-
730
-			// In case of a move operation from an unencrypted to an encrypted
731
-			// storage the old encrypted version would stay with "0" while the
732
-			// correct value would be "1". Thus we manually set the value to "1"
733
-			// for those cases.
734
-			// See also https://github.com/owncloud/core/issues/23078
735
-			if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
736
-				$encryptedVersion = 1;
737
-			}
738
-
739
-			$cacheInformation['encryptedVersion'] = $encryptedVersion;
740
-		}
741
-
742
-		// in case of a rename we need to manipulate the source cache because
743
-		// this information will be kept for the new target
744
-		if ($isRename) {
745
-			$sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
746
-		} else {
747
-			$this->getCache()->put($targetInternalPath, $cacheInformation);
748
-		}
749
-	}
750
-
751
-	/**
752
-	 * copy file between two storages
753
-	 *
754
-	 * @param Storage\IStorage $sourceStorage
755
-	 * @param string $sourceInternalPath
756
-	 * @param string $targetInternalPath
757
-	 * @param bool $preserveMtime
758
-	 * @param bool $isRename
759
-	 * @return bool
760
-	 * @throws \Exception
761
-	 */
762
-	private function copyBetweenStorage(
763
-		Storage\IStorage $sourceStorage,
764
-		$sourceInternalPath,
765
-		$targetInternalPath,
766
-		$preserveMtime,
767
-		$isRename
768
-	) {
769
-		// for versions we have nothing to do, because versions should always use the
770
-		// key from the original file. Just create a 1:1 copy and done
771
-		if ($this->isVersion($targetInternalPath) ||
772
-			$this->isVersion($sourceInternalPath)) {
773
-			// remember that we try to create a version so that we can detect it during
774
-			// fopen($sourceInternalPath) and by-pass the encryption in order to
775
-			// create a 1:1 copy of the file
776
-			$this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
777
-			$result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
778
-			$this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
779
-			if ($result) {
780
-				$info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
781
-				// make sure that we update the unencrypted size for the version
782
-				if (isset($info['encrypted']) && $info['encrypted'] === true) {
783
-					$this->updateUnencryptedSize(
784
-						$this->getFullPath($targetInternalPath),
785
-						$info->getUnencryptedSize()
786
-					);
787
-				}
788
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
789
-			}
790
-			return $result;
791
-		}
792
-
793
-		// first copy the keys that we reuse the existing file key on the target location
794
-		// and don't create a new one which would break versions for example.
795
-		$mount = $this->mountManager->findByStorageId($sourceStorage->getId());
796
-		if (count($mount) === 1) {
797
-			$mountPoint = $mount[0]->getMountPoint();
798
-			$source = $mountPoint . '/' . $sourceInternalPath;
799
-			$target = $this->getFullPath($targetInternalPath);
800
-			$this->copyKeys($source, $target);
801
-		} else {
802
-			$this->logger->error('Could not find mount point, can\'t keep encryption keys');
803
-		}
804
-
805
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
806
-			$dh = $sourceStorage->opendir($sourceInternalPath);
807
-			if (!$this->is_dir($targetInternalPath)) {
808
-				$result = $this->mkdir($targetInternalPath);
809
-			} else {
810
-				$result = true;
811
-			}
812
-			if (is_resource($dh)) {
813
-				while ($result and ($file = readdir($dh)) !== false) {
814
-					if (!Filesystem::isIgnoredDir($file)) {
815
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
816
-					}
817
-				}
818
-			}
819
-		} else {
820
-			try {
821
-				$source = $sourceStorage->fopen($sourceInternalPath, 'r');
822
-				$target = $this->fopen($targetInternalPath, 'w');
823
-				[, $result] = \OC_Helper::streamCopy($source, $target);
824
-			} finally {
825
-				if (is_resource($source)) {
826
-					fclose($source);
827
-				}
828
-				if (is_resource($target)) {
829
-					fclose($target);
830
-				}
831
-			}
832
-			if ($result) {
833
-				if ($preserveMtime) {
834
-					$this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
835
-				}
836
-				$this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
837
-			} else {
838
-				// delete partially written target file
839
-				$this->unlink($targetInternalPath);
840
-				// delete cache entry that was created by fopen
841
-				$this->getCache()->remove($targetInternalPath);
842
-			}
843
-		}
844
-		return (bool)$result;
845
-	}
846
-
847
-	public function getLocalFile($path) {
848
-		if ($this->encryptionManager->isEnabled()) {
849
-			$cachedFile = $this->getCachedFile($path);
850
-			if (is_string($cachedFile)) {
851
-				return $cachedFile;
852
-			}
853
-		}
854
-		return $this->storage->getLocalFile($path);
855
-	}
856
-
857
-	public function isLocal() {
858
-		if ($this->encryptionManager->isEnabled()) {
859
-			return false;
860
-		}
861
-		return $this->storage->isLocal();
862
-	}
863
-
864
-	public function stat($path) {
865
-		$stat = $this->storage->stat($path);
866
-		if (!$stat) {
867
-			return false;
868
-		}
869
-		$fileSize = $this->filesize($path);
870
-		$stat['size'] = $fileSize;
871
-		$stat[7] = $fileSize;
872
-		$stat['hasHeader'] = $this->getHeaderSize($path) > 0;
873
-		return $stat;
874
-	}
875
-
876
-	public function hash($type, $path, $raw = false) {
877
-		$fh = $this->fopen($path, 'rb');
878
-		$ctx = hash_init($type);
879
-		hash_update_stream($ctx, $fh);
880
-		fclose($fh);
881
-		return hash_final($ctx, $raw);
882
-	}
883
-
884
-	/**
885
-	 * return full path, including mount point
886
-	 *
887
-	 * @param string $path relative to mount point
888
-	 * @return string full path including mount point
889
-	 */
890
-	protected function getFullPath($path) {
891
-		return Filesystem::normalizePath($this->mountPoint . '/' . $path);
892
-	}
893
-
894
-	/**
895
-	 * read first block of encrypted file, typically this will contain the
896
-	 * encryption header
897
-	 *
898
-	 * @param string $path
899
-	 * @return string
900
-	 */
901
-	protected function readFirstBlock($path) {
902
-		$firstBlock = '';
903
-		if ($this->storage->is_file($path)) {
904
-			$handle = $this->storage->fopen($path, 'r');
905
-			$firstBlock = fread($handle, $this->util->getHeaderSize());
906
-			fclose($handle);
907
-		}
908
-		return $firstBlock;
909
-	}
910
-
911
-	/**
912
-	 * return header size of given file
913
-	 *
914
-	 * @param string $path
915
-	 * @return int
916
-	 */
917
-	protected function getHeaderSize($path) {
918
-		$headerSize = 0;
919
-		$realFile = $this->util->stripPartialFileExtension($path);
920
-		if ($this->storage->is_file($realFile)) {
921
-			$path = $realFile;
922
-		}
923
-		$firstBlock = $this->readFirstBlock($path);
924
-
925
-		if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
926
-			$headerSize = $this->util->getHeaderSize();
927
-		}
928
-
929
-		return $headerSize;
930
-	}
931
-
932
-	/**
933
-	 * parse raw header to array
934
-	 *
935
-	 * @param string $rawHeader
936
-	 * @return array
937
-	 */
938
-	protected function parseRawHeader($rawHeader) {
939
-		$result = [];
940
-		if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
941
-			$header = $rawHeader;
942
-			$endAt = strpos($header, Util::HEADER_END);
943
-			if ($endAt !== false) {
944
-				$header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
945
-
946
-				// +1 to not start with an ':' which would result in empty element at the beginning
947
-				$exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
948
-
949
-				$element = array_shift($exploded);
950
-				while ($element !== Util::HEADER_END) {
951
-					$result[$element] = array_shift($exploded);
952
-					$element = array_shift($exploded);
953
-				}
954
-			}
955
-		}
956
-
957
-		return $result;
958
-	}
959
-
960
-	/**
961
-	 * read header from file
962
-	 *
963
-	 * @param string $path
964
-	 * @return array
965
-	 */
966
-	protected function getHeader($path) {
967
-		$realFile = $this->util->stripPartialFileExtension($path);
968
-		$exists = $this->storage->is_file($realFile);
969
-		if ($exists) {
970
-			$path = $realFile;
971
-		}
972
-
973
-		$result = [];
974
-
975
-		$isEncrypted = $this->encryptedPaths->get($realFile);
976
-		if (is_null($isEncrypted)) {
977
-			$info = $this->getCache()->get($path);
978
-			$isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
979
-		}
980
-
981
-		if ($isEncrypted) {
982
-			$firstBlock = $this->readFirstBlock($path);
983
-			$result = $this->parseRawHeader($firstBlock);
984
-
985
-			// if the header doesn't contain a encryption module we check if it is a
986
-			// legacy file. If true, we add the default encryption module
987
-			if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
988
-				$result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
989
-			}
990
-		}
991
-
992
-		return $result;
993
-	}
994
-
995
-	/**
996
-	 * read encryption module needed to read/write the file located at $path
997
-	 *
998
-	 * @param string $path
999
-	 * @return null|\OCP\Encryption\IEncryptionModule
1000
-	 * @throws ModuleDoesNotExistsException
1001
-	 * @throws \Exception
1002
-	 */
1003
-	protected function getEncryptionModule($path) {
1004
-		$encryptionModule = null;
1005
-		$header = $this->getHeader($path);
1006
-		$encryptionModuleId = $this->util->getEncryptionModuleId($header);
1007
-		if (!empty($encryptionModuleId)) {
1008
-			try {
1009
-				$encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
1010
-			} catch (ModuleDoesNotExistsException $e) {
1011
-				$this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
1012
-				throw $e;
1013
-			}
1014
-		}
1015
-
1016
-		return $encryptionModule;
1017
-	}
1018
-
1019
-	/**
1020
-	 * @param string $path
1021
-	 * @param int $unencryptedSize
1022
-	 */
1023
-	public function updateUnencryptedSize($path, $unencryptedSize) {
1024
-		$this->unencryptedSize[$path] = $unencryptedSize;
1025
-	}
1026
-
1027
-	/**
1028
-	 * copy keys to new location
1029
-	 *
1030
-	 * @param string $source path relative to data/
1031
-	 * @param string $target path relative to data/
1032
-	 * @return bool
1033
-	 */
1034
-	protected function copyKeys($source, $target) {
1035
-		if (!$this->util->isExcluded($source)) {
1036
-			return $this->keyStorage->copyKeys($source, $target);
1037
-		}
1038
-
1039
-		return false;
1040
-	}
1041
-
1042
-	/**
1043
-	 * check if path points to a files version
1044
-	 *
1045
-	 * @param $path
1046
-	 * @return bool
1047
-	 */
1048
-	protected function isVersion($path) {
1049
-		$normalized = Filesystem::normalizePath($path);
1050
-		return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1051
-	}
1052
-
1053
-	/**
1054
-	 * check if the given storage should be encrypted or not
1055
-	 *
1056
-	 * @param $path
1057
-	 * @return bool
1058
-	 */
1059
-	protected function shouldEncrypt($path) {
1060
-		$fullPath = $this->getFullPath($path);
1061
-		$mountPointConfig = $this->mount->getOption('encrypt', true);
1062
-		if ($mountPointConfig === false) {
1063
-			return false;
1064
-		}
1065
-
1066
-		try {
1067
-			$encryptionModule = $this->getEncryptionModule($fullPath);
1068
-		} catch (ModuleDoesNotExistsException $e) {
1069
-			return false;
1070
-		}
1071
-
1072
-		if ($encryptionModule === null) {
1073
-			$encryptionModule = $this->encryptionManager->getEncryptionModule();
1074
-		}
1075
-
1076
-		return $encryptionModule->shouldEncrypt($fullPath);
1077
-	}
1078
-
1079
-	public function writeStream(string $path, $stream, int $size = null): int {
1080
-		// always fall back to fopen
1081
-		$target = $this->fopen($path, 'w');
1082
-		[$count, $result] = \OC_Helper::streamCopy($stream, $target);
1083
-		fclose($stream);
1084
-		fclose($target);
1085
-
1086
-		// object store, stores the size after write and doesn't update this during scan
1087
-		// manually store the unencrypted size
1088
-		if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class)) {
1089
-			$this->getCache()->put($path, ['unencrypted_size' => $count]);
1090
-		}
1091
-
1092
-		return $count;
1093
-	}
1094
-
1095
-	public function clearIsEncryptedCache(): void {
1096
-		$this->encryptedPaths->clear();
1097
-	}
59
+    use LocalTempFileTrait;
60
+
61
+    /** @var string */
62
+    private $mountPoint;
63
+
64
+    /** @var \OC\Encryption\Util */
65
+    private $util;
66
+
67
+    /** @var \OCP\Encryption\IManager */
68
+    private $encryptionManager;
69
+
70
+    private LoggerInterface $logger;
71
+
72
+    /** @var string */
73
+    private $uid;
74
+
75
+    /** @var array */
76
+    protected $unencryptedSize;
77
+
78
+    /** @var \OCP\Encryption\IFile */
79
+    private $fileHelper;
80
+
81
+    /** @var IMountPoint */
82
+    private $mount;
83
+
84
+    /** @var IStorage */
85
+    private $keyStorage;
86
+
87
+    /** @var Update */
88
+    private $update;
89
+
90
+    /** @var Manager */
91
+    private $mountManager;
92
+
93
+    /** @var array remember for which path we execute the repair step to avoid recursions */
94
+    private $fixUnencryptedSizeOf = [];
95
+
96
+    /** @var  ArrayCache */
97
+    private $arrayCache;
98
+
99
+    /** @var CappedMemoryCache<bool> */
100
+    private CappedMemoryCache $encryptedPaths;
101
+
102
+    /**
103
+     * @param array $parameters
104
+     */
105
+    public function __construct(
106
+        $parameters,
107
+        IManager $encryptionManager = null,
108
+        Util $util = null,
109
+        LoggerInterface $logger = null,
110
+        IFile $fileHelper = null,
111
+        $uid = null,
112
+        IStorage $keyStorage = null,
113
+        Update $update = null,
114
+        Manager $mountManager = null,
115
+        ArrayCache $arrayCache = null
116
+    ) {
117
+        $this->mountPoint = $parameters['mountPoint'];
118
+        $this->mount = $parameters['mount'];
119
+        $this->encryptionManager = $encryptionManager;
120
+        $this->util = $util;
121
+        $this->logger = $logger;
122
+        $this->uid = $uid;
123
+        $this->fileHelper = $fileHelper;
124
+        $this->keyStorage = $keyStorage;
125
+        $this->unencryptedSize = [];
126
+        $this->update = $update;
127
+        $this->mountManager = $mountManager;
128
+        $this->arrayCache = $arrayCache;
129
+        $this->encryptedPaths = new CappedMemoryCache();
130
+        parent::__construct($parameters);
131
+    }
132
+
133
+    /**
134
+     * see https://www.php.net/manual/en/function.filesize.php
135
+     * The result for filesize when called on a folder is required to be 0
136
+     */
137
+    public function filesize($path): false|int|float {
138
+        $fullPath = $this->getFullPath($path);
139
+
140
+        $info = $this->getCache()->get($path);
141
+        if ($info === false) {
142
+            return false;
143
+        }
144
+        if (isset($this->unencryptedSize[$fullPath])) {
145
+            $size = $this->unencryptedSize[$fullPath];
146
+            // update file cache
147
+            if ($info instanceof ICacheEntry) {
148
+                $info['encrypted'] = $info['encryptedVersion'];
149
+            } else {
150
+                if (!is_array($info)) {
151
+                    $info = [];
152
+                }
153
+                $info['encrypted'] = true;
154
+                $info = new CacheEntry($info);
155
+            }
156
+
157
+            if ($size !== $info->getUnencryptedSize()) {
158
+                $this->getCache()->update($info->getId(), [
159
+                    'unencrypted_size' => $size
160
+                ]);
161
+            }
162
+
163
+            return $size;
164
+        }
165
+
166
+        if (isset($info['fileid']) && $info['encrypted']) {
167
+            return $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
168
+        }
169
+
170
+        return $this->storage->filesize($path);
171
+    }
172
+
173
+    /**
174
+     * @param string $path
175
+     * @param array $data
176
+     * @return array
177
+     */
178
+    private function modifyMetaData(string $path, array $data): array {
179
+        $fullPath = $this->getFullPath($path);
180
+        $info = $this->getCache()->get($path);
181
+
182
+        if (isset($this->unencryptedSize[$fullPath])) {
183
+            $data['encrypted'] = true;
184
+            $data['size'] = $this->unencryptedSize[$fullPath];
185
+            $data['unencrypted_size'] = $data['size'];
186
+        } else {
187
+            if (isset($info['fileid']) && $info['encrypted']) {
188
+                $data['size'] = $this->verifyUnencryptedSize($path, $info->getUnencryptedSize());
189
+                $data['encrypted'] = true;
190
+                $data['unencrypted_size'] = $data['size'];
191
+            }
192
+        }
193
+
194
+        if (isset($info['encryptedVersion']) && $info['encryptedVersion'] > 1) {
195
+            $data['encryptedVersion'] = $info['encryptedVersion'];
196
+        }
197
+
198
+        return $data;
199
+    }
200
+
201
+    public function getMetaData($path) {
202
+        $data = $this->storage->getMetaData($path);
203
+        if (is_null($data)) {
204
+            return null;
205
+        }
206
+        return $this->modifyMetaData($path, $data);
207
+    }
208
+
209
+    public function getDirectoryContent($directory): \Traversable {
210
+        $parent = rtrim($directory, '/');
211
+        foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) {
212
+            yield $this->modifyMetaData($parent . '/' . $data['name'], $data);
213
+        }
214
+    }
215
+
216
+    /**
217
+     * see https://www.php.net/manual/en/function.file_get_contents.php
218
+     *
219
+     * @param string $path
220
+     * @return string|false
221
+     */
222
+    public function file_get_contents($path) {
223
+        $encryptionModule = $this->getEncryptionModule($path);
224
+
225
+        if ($encryptionModule) {
226
+            $handle = $this->fopen($path, "r");
227
+            if (!$handle) {
228
+                return false;
229
+            }
230
+            $data = stream_get_contents($handle);
231
+            fclose($handle);
232
+            return $data;
233
+        }
234
+        return $this->storage->file_get_contents($path);
235
+    }
236
+
237
+    /**
238
+     * see https://www.php.net/manual/en/function.file_put_contents.php
239
+     *
240
+     * @param string $path
241
+     * @param mixed $data
242
+     * @return int|false
243
+     */
244
+    public function file_put_contents($path, $data) {
245
+        // file put content will always be translated to a stream write
246
+        $handle = $this->fopen($path, 'w');
247
+        if (is_resource($handle)) {
248
+            $written = fwrite($handle, $data);
249
+            fclose($handle);
250
+            return $written;
251
+        }
252
+
253
+        return false;
254
+    }
255
+
256
+    /**
257
+     * see https://www.php.net/manual/en/function.unlink.php
258
+     *
259
+     * @param string $path
260
+     * @return bool
261
+     */
262
+    public function unlink($path) {
263
+        $fullPath = $this->getFullPath($path);
264
+        if ($this->util->isExcluded($fullPath)) {
265
+            return $this->storage->unlink($path);
266
+        }
267
+
268
+        $encryptionModule = $this->getEncryptionModule($path);
269
+        if ($encryptionModule) {
270
+            $this->keyStorage->deleteAllFileKeys($fullPath);
271
+        }
272
+
273
+        return $this->storage->unlink($path);
274
+    }
275
+
276
+    /**
277
+     * see https://www.php.net/manual/en/function.rename.php
278
+     *
279
+     * @param string $source
280
+     * @param string $target
281
+     * @return bool
282
+     */
283
+    public function rename($source, $target) {
284
+        $result = $this->storage->rename($source, $target);
285
+
286
+        if ($result &&
287
+            // versions always use the keys from the original file, so we can skip
288
+            // this step for versions
289
+            $this->isVersion($target) === false &&
290
+            $this->encryptionManager->isEnabled()) {
291
+            $sourcePath = $this->getFullPath($source);
292
+            if (!$this->util->isExcluded($sourcePath)) {
293
+                $targetPath = $this->getFullPath($target);
294
+                if (isset($this->unencryptedSize[$sourcePath])) {
295
+                    $this->unencryptedSize[$targetPath] = $this->unencryptedSize[$sourcePath];
296
+                }
297
+                $this->keyStorage->renameKeys($sourcePath, $targetPath);
298
+                $module = $this->getEncryptionModule($target);
299
+                if ($module) {
300
+                    $module->update($targetPath, $this->uid, []);
301
+                }
302
+            }
303
+        }
304
+
305
+        return $result;
306
+    }
307
+
308
+    /**
309
+     * see https://www.php.net/manual/en/function.rmdir.php
310
+     *
311
+     * @param string $path
312
+     * @return bool
313
+     */
314
+    public function rmdir($path) {
315
+        $result = $this->storage->rmdir($path);
316
+        $fullPath = $this->getFullPath($path);
317
+        if ($result &&
318
+            $this->util->isExcluded($fullPath) === false &&
319
+            $this->encryptionManager->isEnabled()
320
+        ) {
321
+            $this->keyStorage->deleteAllFileKeys($fullPath);
322
+        }
323
+
324
+        return $result;
325
+    }
326
+
327
+    /**
328
+     * check if a file can be read
329
+     *
330
+     * @param string $path
331
+     * @return bool
332
+     */
333
+    public function isReadable($path) {
334
+        $isReadable = true;
335
+
336
+        $metaData = $this->getMetaData($path);
337
+        if (
338
+            !$this->is_dir($path) &&
339
+            isset($metaData['encrypted']) &&
340
+            $metaData['encrypted'] === true
341
+        ) {
342
+            $fullPath = $this->getFullPath($path);
343
+            $module = $this->getEncryptionModule($path);
344
+            $isReadable = $module->isReadable($fullPath, $this->uid);
345
+        }
346
+
347
+        return $this->storage->isReadable($path) && $isReadable;
348
+    }
349
+
350
+    /**
351
+     * see https://www.php.net/manual/en/function.copy.php
352
+     *
353
+     * @param string $source
354
+     * @param string $target
355
+     */
356
+    public function copy($source, $target): bool {
357
+        $sourcePath = $this->getFullPath($source);
358
+
359
+        if ($this->util->isExcluded($sourcePath)) {
360
+            return $this->storage->copy($source, $target);
361
+        }
362
+
363
+        // need to stream copy file by file in case we copy between a encrypted
364
+        // and a unencrypted storage
365
+        $this->unlink($target);
366
+        return $this->copyFromStorage($this, $source, $target);
367
+    }
368
+
369
+    /**
370
+     * see https://www.php.net/manual/en/function.fopen.php
371
+     *
372
+     * @param string $path
373
+     * @param string $mode
374
+     * @return resource|bool
375
+     * @throws GenericEncryptionException
376
+     * @throws ModuleDoesNotExistsException
377
+     */
378
+    public function fopen($path, $mode) {
379
+        // check if the file is stored in the array cache, this means that we
380
+        // copy a file over to the versions folder, in this case we don't want to
381
+        // decrypt it
382
+        if ($this->arrayCache->hasKey('encryption_copy_version_' . $path)) {
383
+            $this->arrayCache->remove('encryption_copy_version_' . $path);
384
+            return $this->storage->fopen($path, $mode);
385
+        }
386
+
387
+        $encryptionEnabled = $this->encryptionManager->isEnabled();
388
+        $shouldEncrypt = false;
389
+        $encryptionModule = null;
390
+        $header = $this->getHeader($path);
391
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
392
+        $fullPath = $this->getFullPath($path);
393
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
394
+
395
+        if ($this->util->isExcluded($fullPath) === false) {
396
+            $size = $unencryptedSize = 0;
397
+            $realFile = $this->util->stripPartialFileExtension($path);
398
+            $targetExists = $this->is_file($realFile) || $this->file_exists($path);
399
+            $targetIsEncrypted = false;
400
+            if ($targetExists) {
401
+                // in case the file exists we require the explicit module as
402
+                // specified in the file header - otherwise we need to fail hard to
403
+                // prevent data loss on client side
404
+                if (!empty($encryptionModuleId)) {
405
+                    $targetIsEncrypted = true;
406
+                    $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
407
+                }
408
+
409
+                if ($this->file_exists($path)) {
410
+                    $size = $this->storage->filesize($path);
411
+                    $unencryptedSize = $this->filesize($path);
412
+                } else {
413
+                    $size = $unencryptedSize = 0;
414
+                }
415
+            }
416
+
417
+            try {
418
+                if (
419
+                    $mode === 'w'
420
+                    || $mode === 'w+'
421
+                    || $mode === 'wb'
422
+                    || $mode === 'wb+'
423
+                ) {
424
+                    // if we update a encrypted file with a un-encrypted one we change the db flag
425
+                    if ($targetIsEncrypted && $encryptionEnabled === false) {
426
+                        $cache = $this->storage->getCache();
427
+                        if ($cache) {
428
+                            $entry = $cache->get($path);
429
+                            $cache->update($entry->getId(), ['encrypted' => 0]);
430
+                        }
431
+                    }
432
+                    if ($encryptionEnabled) {
433
+                        // if $encryptionModuleId is empty, the default module will be used
434
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
435
+                        $shouldEncrypt = $encryptionModule->shouldEncrypt($fullPath);
436
+                        $signed = true;
437
+                    }
438
+                } else {
439
+                    $info = $this->getCache()->get($path);
440
+                    // only get encryption module if we found one in the header
441
+                    // or if file should be encrypted according to the file cache
442
+                    if (!empty($encryptionModuleId)) {
443
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
444
+                        $shouldEncrypt = true;
445
+                    } elseif (empty($encryptionModuleId) && $info['encrypted'] === true) {
446
+                        // we come from a old installation. No header and/or no module defined
447
+                        // but the file is encrypted. In this case we need to use the
448
+                        // OC_DEFAULT_MODULE to read the file
449
+                        $encryptionModule = $this->encryptionManager->getEncryptionModule('OC_DEFAULT_MODULE');
450
+                        $shouldEncrypt = true;
451
+                        $targetIsEncrypted = true;
452
+                    }
453
+                }
454
+            } catch (ModuleDoesNotExistsException $e) {
455
+                $this->logger->warning('Encryption module "' . $encryptionModuleId . '" not found, file will be stored unencrypted', [
456
+                    'exception' => $e,
457
+                    'app' => 'core',
458
+                ]);
459
+            }
460
+
461
+            // encryption disabled on write of new file and write to existing unencrypted file -> don't encrypt
462
+            if (!$encryptionEnabled || !$this->shouldEncrypt($path)) {
463
+                if (!$targetExists || !$targetIsEncrypted) {
464
+                    $shouldEncrypt = false;
465
+                }
466
+            }
467
+
468
+            if ($shouldEncrypt === true && $encryptionModule !== null) {
469
+                $this->encryptedPaths->set($this->util->stripPartialFileExtension($path), true);
470
+                $headerSize = $this->getHeaderSize($path);
471
+                $source = $this->storage->fopen($path, $mode);
472
+                if (!is_resource($source)) {
473
+                    return false;
474
+                }
475
+                $handle = \OC\Files\Stream\Encryption::wrap($source, $path, $fullPath, $header,
476
+                    $this->uid, $encryptionModule, $this->storage, $this, $this->util, $this->fileHelper, $mode,
477
+                    $size, $unencryptedSize, $headerSize, $signed);
478
+
479
+                return $handle;
480
+            }
481
+        }
482
+
483
+        return $this->storage->fopen($path, $mode);
484
+    }
485
+
486
+
487
+    /**
488
+     * perform some plausibility checks if the the unencrypted size is correct.
489
+     * If not, we calculate the correct unencrypted size and return it
490
+     *
491
+     * @param string $path internal path relative to the storage root
492
+     * @param int $unencryptedSize size of the unencrypted file
493
+     *
494
+     * @return int unencrypted size
495
+     */
496
+    protected function verifyUnencryptedSize(string $path, int $unencryptedSize): int {
497
+        $size = $this->storage->filesize($path);
498
+        $result = $unencryptedSize;
499
+
500
+        if ($unencryptedSize < 0 ||
501
+            ($size > 0 && $unencryptedSize === $size) ||
502
+            $unencryptedSize > $size
503
+        ) {
504
+            // check if we already calculate the unencrypted size for the
505
+            // given path to avoid recursions
506
+            if (isset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]) === false) {
507
+                $this->fixUnencryptedSizeOf[$this->getFullPath($path)] = true;
508
+                try {
509
+                    $result = $this->fixUnencryptedSize($path, $size, $unencryptedSize);
510
+                } catch (\Exception $e) {
511
+                    $this->logger->error('Couldn\'t re-calculate unencrypted size for ' . $path, ['exception' => $e]);
512
+                }
513
+                unset($this->fixUnencryptedSizeOf[$this->getFullPath($path)]);
514
+            }
515
+        }
516
+
517
+        return $result;
518
+    }
519
+
520
+    /**
521
+     * calculate the unencrypted size
522
+     *
523
+     * @param string $path internal path relative to the storage root
524
+     * @param int $size size of the physical file
525
+     * @param int $unencryptedSize size of the unencrypted file
526
+     *
527
+     * @return int calculated unencrypted size
528
+     */
529
+    protected function fixUnencryptedSize(string $path, int $size, int $unencryptedSize): int {
530
+        $headerSize = $this->getHeaderSize($path);
531
+        $header = $this->getHeader($path);
532
+        $encryptionModule = $this->getEncryptionModule($path);
533
+
534
+        $stream = $this->storage->fopen($path, 'r');
535
+
536
+        // if we couldn't open the file we return the old unencrypted size
537
+        if (!is_resource($stream)) {
538
+            $this->logger->error('Could not open ' . $path . '. Recalculation of unencrypted size aborted.');
539
+            return $unencryptedSize;
540
+        }
541
+
542
+        $newUnencryptedSize = 0;
543
+        $size -= $headerSize;
544
+        $blockSize = $this->util->getBlockSize();
545
+
546
+        // if a header exists we skip it
547
+        if ($headerSize > 0) {
548
+            $this->fread_block($stream, $headerSize);
549
+        }
550
+
551
+        // fast path, else the calculation for $lastChunkNr is bogus
552
+        if ($size === 0) {
553
+            return 0;
554
+        }
555
+
556
+        $signed = isset($header['signed']) && $header['signed'] === 'true';
557
+        $unencryptedBlockSize = $encryptionModule->getUnencryptedBlockSize($signed);
558
+
559
+        // calculate last chunk nr
560
+        // next highest is end of chunks, one subtracted is last one
561
+        // we have to read the last chunk, we can't just calculate it (because of padding etc)
562
+
563
+        $lastChunkNr = ceil($size / $blockSize) - 1;
564
+        // calculate last chunk position
565
+        $lastChunkPos = ($lastChunkNr * $blockSize);
566
+        // try to fseek to the last chunk, if it fails we have to read the whole file
567
+        if (@fseek($stream, $lastChunkPos, SEEK_CUR) === 0) {
568
+            $newUnencryptedSize += $lastChunkNr * $unencryptedBlockSize;
569
+        }
570
+
571
+        $lastChunkContentEncrypted = '';
572
+        $count = $blockSize;
573
+
574
+        while ($count > 0) {
575
+            $data = $this->fread_block($stream, $blockSize);
576
+            $count = strlen($data);
577
+            $lastChunkContentEncrypted .= $data;
578
+            if (strlen($lastChunkContentEncrypted) > $blockSize) {
579
+                $newUnencryptedSize += $unencryptedBlockSize;
580
+                $lastChunkContentEncrypted = substr($lastChunkContentEncrypted, $blockSize);
581
+            }
582
+        }
583
+
584
+        fclose($stream);
585
+
586
+        // we have to decrypt the last chunk to get it actual size
587
+        $encryptionModule->begin($this->getFullPath($path), $this->uid, 'r', $header, []);
588
+        $decryptedLastChunk = $encryptionModule->decrypt($lastChunkContentEncrypted, $lastChunkNr . 'end');
589
+        $decryptedLastChunk .= $encryptionModule->end($this->getFullPath($path), $lastChunkNr . 'end');
590
+
591
+        // calc the real file size with the size of the last chunk
592
+        $newUnencryptedSize += strlen($decryptedLastChunk);
593
+
594
+        $this->updateUnencryptedSize($this->getFullPath($path), $newUnencryptedSize);
595
+
596
+        // write to cache if applicable
597
+        $cache = $this->storage->getCache();
598
+        if ($cache) {
599
+            $entry = $cache->get($path);
600
+            $cache->update($entry['fileid'], [
601
+                'unencrypted_size' => $newUnencryptedSize
602
+            ]);
603
+        }
604
+
605
+        return $newUnencryptedSize;
606
+    }
607
+
608
+    /**
609
+     * fread_block
610
+     *
611
+     * This function is a wrapper around the fread function.  It is based on the
612
+     * stream_read_block function from lib/private/Files/Streams/Encryption.php
613
+     * It calls stream read until the requested $blockSize was received or no remaining data is present.
614
+     * This is required as stream_read only returns smaller chunks of data when the stream fetches from a
615
+     * remote storage over the internet and it does not care about the given $blockSize.
616
+     *
617
+     * @param handle the stream to read from
618
+     * @param int $blockSize Length of requested data block in bytes
619
+     * @return string Data fetched from stream.
620
+     */
621
+    private function fread_block($handle, int $blockSize): string {
622
+        $remaining = $blockSize;
623
+        $data = '';
624
+
625
+        do {
626
+            $chunk = fread($handle, $remaining);
627
+            $chunk_len = strlen($chunk);
628
+            $data .= $chunk;
629
+            $remaining -= $chunk_len;
630
+        } while (($remaining > 0) && ($chunk_len > 0));
631
+
632
+        return $data;
633
+    }
634
+
635
+    /**
636
+     * @param Storage\IStorage $sourceStorage
637
+     * @param string $sourceInternalPath
638
+     * @param string $targetInternalPath
639
+     * @param bool $preserveMtime
640
+     * @return bool
641
+     */
642
+    public function moveFromStorage(
643
+        Storage\IStorage $sourceStorage,
644
+        $sourceInternalPath,
645
+        $targetInternalPath,
646
+        $preserveMtime = true
647
+    ) {
648
+        if ($sourceStorage === $this) {
649
+            return $this->rename($sourceInternalPath, $targetInternalPath);
650
+        }
651
+
652
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
653
+        // - call $this->storage->moveFromStorage() instead of $this->copyBetweenStorage
654
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
655
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
656
+        // - remove $this->copyBetweenStorage
657
+
658
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
659
+            return false;
660
+        }
661
+
662
+        $result = $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, true);
663
+        if ($result) {
664
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
665
+                $result &= $sourceStorage->rmdir($sourceInternalPath);
666
+            } else {
667
+                $result &= $sourceStorage->unlink($sourceInternalPath);
668
+            }
669
+        }
670
+        return $result;
671
+    }
672
+
673
+
674
+    /**
675
+     * @param Storage\IStorage $sourceStorage
676
+     * @param string $sourceInternalPath
677
+     * @param string $targetInternalPath
678
+     * @param bool $preserveMtime
679
+     * @param bool $isRename
680
+     * @return bool
681
+     */
682
+    public function copyFromStorage(
683
+        Storage\IStorage $sourceStorage,
684
+        $sourceInternalPath,
685
+        $targetInternalPath,
686
+        $preserveMtime = false,
687
+        $isRename = false
688
+    ) {
689
+        // TODO clean this up once the underlying moveFromStorage in OC\Files\Storage\Wrapper\Common is fixed:
690
+        // - call $this->storage->copyFromStorage() instead of $this->copyBetweenStorage
691
+        // - copy the file cache update from  $this->copyBetweenStorage to this method
692
+        // - copy the copyKeys() call from  $this->copyBetweenStorage to this method
693
+        // - remove $this->copyBetweenStorage
694
+
695
+        return $this->copyBetweenStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime, $isRename);
696
+    }
697
+
698
+    /**
699
+     * Update the encrypted cache version in the database
700
+     *
701
+     * @param Storage\IStorage $sourceStorage
702
+     * @param string $sourceInternalPath
703
+     * @param string $targetInternalPath
704
+     * @param bool $isRename
705
+     * @param bool $keepEncryptionVersion
706
+     */
707
+    private function updateEncryptedVersion(
708
+        Storage\IStorage $sourceStorage,
709
+        $sourceInternalPath,
710
+        $targetInternalPath,
711
+        $isRename,
712
+        $keepEncryptionVersion
713
+    ) {
714
+        $isEncrypted = $this->encryptionManager->isEnabled() && $this->shouldEncrypt($targetInternalPath);
715
+        $cacheInformation = [
716
+            'encrypted' => $isEncrypted,
717
+        ];
718
+        if ($isEncrypted) {
719
+            $sourceCacheEntry = $sourceStorage->getCache()->get($sourceInternalPath);
720
+            $targetCacheEntry = $this->getCache()->get($targetInternalPath);
721
+
722
+            // Rename of the cache already happened, so we do the cleanup on the target
723
+            if ($sourceCacheEntry === false && $targetCacheEntry !== false) {
724
+                $encryptedVersion = $targetCacheEntry['encryptedVersion'];
725
+                $isRename = false;
726
+            } else {
727
+                $encryptedVersion = $sourceCacheEntry['encryptedVersion'];
728
+            }
729
+
730
+            // In case of a move operation from an unencrypted to an encrypted
731
+            // storage the old encrypted version would stay with "0" while the
732
+            // correct value would be "1". Thus we manually set the value to "1"
733
+            // for those cases.
734
+            // See also https://github.com/owncloud/core/issues/23078
735
+            if ($encryptedVersion === 0 || !$keepEncryptionVersion) {
736
+                $encryptedVersion = 1;
737
+            }
738
+
739
+            $cacheInformation['encryptedVersion'] = $encryptedVersion;
740
+        }
741
+
742
+        // in case of a rename we need to manipulate the source cache because
743
+        // this information will be kept for the new target
744
+        if ($isRename) {
745
+            $sourceStorage->getCache()->put($sourceInternalPath, $cacheInformation);
746
+        } else {
747
+            $this->getCache()->put($targetInternalPath, $cacheInformation);
748
+        }
749
+    }
750
+
751
+    /**
752
+     * copy file between two storages
753
+     *
754
+     * @param Storage\IStorage $sourceStorage
755
+     * @param string $sourceInternalPath
756
+     * @param string $targetInternalPath
757
+     * @param bool $preserveMtime
758
+     * @param bool $isRename
759
+     * @return bool
760
+     * @throws \Exception
761
+     */
762
+    private function copyBetweenStorage(
763
+        Storage\IStorage $sourceStorage,
764
+        $sourceInternalPath,
765
+        $targetInternalPath,
766
+        $preserveMtime,
767
+        $isRename
768
+    ) {
769
+        // for versions we have nothing to do, because versions should always use the
770
+        // key from the original file. Just create a 1:1 copy and done
771
+        if ($this->isVersion($targetInternalPath) ||
772
+            $this->isVersion($sourceInternalPath)) {
773
+            // remember that we try to create a version so that we can detect it during
774
+            // fopen($sourceInternalPath) and by-pass the encryption in order to
775
+            // create a 1:1 copy of the file
776
+            $this->arrayCache->set('encryption_copy_version_' . $sourceInternalPath, true);
777
+            $result = $this->storage->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
778
+            $this->arrayCache->remove('encryption_copy_version_' . $sourceInternalPath);
779
+            if ($result) {
780
+                $info = $this->getCache('', $sourceStorage)->get($sourceInternalPath);
781
+                // make sure that we update the unencrypted size for the version
782
+                if (isset($info['encrypted']) && $info['encrypted'] === true) {
783
+                    $this->updateUnencryptedSize(
784
+                        $this->getFullPath($targetInternalPath),
785
+                        $info->getUnencryptedSize()
786
+                    );
787
+                }
788
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, true);
789
+            }
790
+            return $result;
791
+        }
792
+
793
+        // first copy the keys that we reuse the existing file key on the target location
794
+        // and don't create a new one which would break versions for example.
795
+        $mount = $this->mountManager->findByStorageId($sourceStorage->getId());
796
+        if (count($mount) === 1) {
797
+            $mountPoint = $mount[0]->getMountPoint();
798
+            $source = $mountPoint . '/' . $sourceInternalPath;
799
+            $target = $this->getFullPath($targetInternalPath);
800
+            $this->copyKeys($source, $target);
801
+        } else {
802
+            $this->logger->error('Could not find mount point, can\'t keep encryption keys');
803
+        }
804
+
805
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
806
+            $dh = $sourceStorage->opendir($sourceInternalPath);
807
+            if (!$this->is_dir($targetInternalPath)) {
808
+                $result = $this->mkdir($targetInternalPath);
809
+            } else {
810
+                $result = true;
811
+            }
812
+            if (is_resource($dh)) {
813
+                while ($result and ($file = readdir($dh)) !== false) {
814
+                    if (!Filesystem::isIgnoredDir($file)) {
815
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file, false, $isRename);
816
+                    }
817
+                }
818
+            }
819
+        } else {
820
+            try {
821
+                $source = $sourceStorage->fopen($sourceInternalPath, 'r');
822
+                $target = $this->fopen($targetInternalPath, 'w');
823
+                [, $result] = \OC_Helper::streamCopy($source, $target);
824
+            } finally {
825
+                if (is_resource($source)) {
826
+                    fclose($source);
827
+                }
828
+                if (is_resource($target)) {
829
+                    fclose($target);
830
+                }
831
+            }
832
+            if ($result) {
833
+                if ($preserveMtime) {
834
+                    $this->touch($targetInternalPath, $sourceStorage->filemtime($sourceInternalPath));
835
+                }
836
+                $this->updateEncryptedVersion($sourceStorage, $sourceInternalPath, $targetInternalPath, $isRename, false);
837
+            } else {
838
+                // delete partially written target file
839
+                $this->unlink($targetInternalPath);
840
+                // delete cache entry that was created by fopen
841
+                $this->getCache()->remove($targetInternalPath);
842
+            }
843
+        }
844
+        return (bool)$result;
845
+    }
846
+
847
+    public function getLocalFile($path) {
848
+        if ($this->encryptionManager->isEnabled()) {
849
+            $cachedFile = $this->getCachedFile($path);
850
+            if (is_string($cachedFile)) {
851
+                return $cachedFile;
852
+            }
853
+        }
854
+        return $this->storage->getLocalFile($path);
855
+    }
856
+
857
+    public function isLocal() {
858
+        if ($this->encryptionManager->isEnabled()) {
859
+            return false;
860
+        }
861
+        return $this->storage->isLocal();
862
+    }
863
+
864
+    public function stat($path) {
865
+        $stat = $this->storage->stat($path);
866
+        if (!$stat) {
867
+            return false;
868
+        }
869
+        $fileSize = $this->filesize($path);
870
+        $stat['size'] = $fileSize;
871
+        $stat[7] = $fileSize;
872
+        $stat['hasHeader'] = $this->getHeaderSize($path) > 0;
873
+        return $stat;
874
+    }
875
+
876
+    public function hash($type, $path, $raw = false) {
877
+        $fh = $this->fopen($path, 'rb');
878
+        $ctx = hash_init($type);
879
+        hash_update_stream($ctx, $fh);
880
+        fclose($fh);
881
+        return hash_final($ctx, $raw);
882
+    }
883
+
884
+    /**
885
+     * return full path, including mount point
886
+     *
887
+     * @param string $path relative to mount point
888
+     * @return string full path including mount point
889
+     */
890
+    protected function getFullPath($path) {
891
+        return Filesystem::normalizePath($this->mountPoint . '/' . $path);
892
+    }
893
+
894
+    /**
895
+     * read first block of encrypted file, typically this will contain the
896
+     * encryption header
897
+     *
898
+     * @param string $path
899
+     * @return string
900
+     */
901
+    protected function readFirstBlock($path) {
902
+        $firstBlock = '';
903
+        if ($this->storage->is_file($path)) {
904
+            $handle = $this->storage->fopen($path, 'r');
905
+            $firstBlock = fread($handle, $this->util->getHeaderSize());
906
+            fclose($handle);
907
+        }
908
+        return $firstBlock;
909
+    }
910
+
911
+    /**
912
+     * return header size of given file
913
+     *
914
+     * @param string $path
915
+     * @return int
916
+     */
917
+    protected function getHeaderSize($path) {
918
+        $headerSize = 0;
919
+        $realFile = $this->util->stripPartialFileExtension($path);
920
+        if ($this->storage->is_file($realFile)) {
921
+            $path = $realFile;
922
+        }
923
+        $firstBlock = $this->readFirstBlock($path);
924
+
925
+        if (substr($firstBlock, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
926
+            $headerSize = $this->util->getHeaderSize();
927
+        }
928
+
929
+        return $headerSize;
930
+    }
931
+
932
+    /**
933
+     * parse raw header to array
934
+     *
935
+     * @param string $rawHeader
936
+     * @return array
937
+     */
938
+    protected function parseRawHeader($rawHeader) {
939
+        $result = [];
940
+        if (substr($rawHeader, 0, strlen(Util::HEADER_START)) === Util::HEADER_START) {
941
+            $header = $rawHeader;
942
+            $endAt = strpos($header, Util::HEADER_END);
943
+            if ($endAt !== false) {
944
+                $header = substr($header, 0, $endAt + strlen(Util::HEADER_END));
945
+
946
+                // +1 to not start with an ':' which would result in empty element at the beginning
947
+                $exploded = explode(':', substr($header, strlen(Util::HEADER_START) + 1));
948
+
949
+                $element = array_shift($exploded);
950
+                while ($element !== Util::HEADER_END) {
951
+                    $result[$element] = array_shift($exploded);
952
+                    $element = array_shift($exploded);
953
+                }
954
+            }
955
+        }
956
+
957
+        return $result;
958
+    }
959
+
960
+    /**
961
+     * read header from file
962
+     *
963
+     * @param string $path
964
+     * @return array
965
+     */
966
+    protected function getHeader($path) {
967
+        $realFile = $this->util->stripPartialFileExtension($path);
968
+        $exists = $this->storage->is_file($realFile);
969
+        if ($exists) {
970
+            $path = $realFile;
971
+        }
972
+
973
+        $result = [];
974
+
975
+        $isEncrypted = $this->encryptedPaths->get($realFile);
976
+        if (is_null($isEncrypted)) {
977
+            $info = $this->getCache()->get($path);
978
+            $isEncrypted = isset($info['encrypted']) && $info['encrypted'] === true;
979
+        }
980
+
981
+        if ($isEncrypted) {
982
+            $firstBlock = $this->readFirstBlock($path);
983
+            $result = $this->parseRawHeader($firstBlock);
984
+
985
+            // if the header doesn't contain a encryption module we check if it is a
986
+            // legacy file. If true, we add the default encryption module
987
+            if (!isset($result[Util::HEADER_ENCRYPTION_MODULE_KEY]) && (!empty($result) || $exists)) {
988
+                $result[Util::HEADER_ENCRYPTION_MODULE_KEY] = 'OC_DEFAULT_MODULE';
989
+            }
990
+        }
991
+
992
+        return $result;
993
+    }
994
+
995
+    /**
996
+     * read encryption module needed to read/write the file located at $path
997
+     *
998
+     * @param string $path
999
+     * @return null|\OCP\Encryption\IEncryptionModule
1000
+     * @throws ModuleDoesNotExistsException
1001
+     * @throws \Exception
1002
+     */
1003
+    protected function getEncryptionModule($path) {
1004
+        $encryptionModule = null;
1005
+        $header = $this->getHeader($path);
1006
+        $encryptionModuleId = $this->util->getEncryptionModuleId($header);
1007
+        if (!empty($encryptionModuleId)) {
1008
+            try {
1009
+                $encryptionModule = $this->encryptionManager->getEncryptionModule($encryptionModuleId);
1010
+            } catch (ModuleDoesNotExistsException $e) {
1011
+                $this->logger->critical('Encryption module defined in "' . $path . '" not loaded!');
1012
+                throw $e;
1013
+            }
1014
+        }
1015
+
1016
+        return $encryptionModule;
1017
+    }
1018
+
1019
+    /**
1020
+     * @param string $path
1021
+     * @param int $unencryptedSize
1022
+     */
1023
+    public function updateUnencryptedSize($path, $unencryptedSize) {
1024
+        $this->unencryptedSize[$path] = $unencryptedSize;
1025
+    }
1026
+
1027
+    /**
1028
+     * copy keys to new location
1029
+     *
1030
+     * @param string $source path relative to data/
1031
+     * @param string $target path relative to data/
1032
+     * @return bool
1033
+     */
1034
+    protected function copyKeys($source, $target) {
1035
+        if (!$this->util->isExcluded($source)) {
1036
+            return $this->keyStorage->copyKeys($source, $target);
1037
+        }
1038
+
1039
+        return false;
1040
+    }
1041
+
1042
+    /**
1043
+     * check if path points to a files version
1044
+     *
1045
+     * @param $path
1046
+     * @return bool
1047
+     */
1048
+    protected function isVersion($path) {
1049
+        $normalized = Filesystem::normalizePath($path);
1050
+        return substr($normalized, 0, strlen('/files_versions/')) === '/files_versions/';
1051
+    }
1052
+
1053
+    /**
1054
+     * check if the given storage should be encrypted or not
1055
+     *
1056
+     * @param $path
1057
+     * @return bool
1058
+     */
1059
+    protected function shouldEncrypt($path) {
1060
+        $fullPath = $this->getFullPath($path);
1061
+        $mountPointConfig = $this->mount->getOption('encrypt', true);
1062
+        if ($mountPointConfig === false) {
1063
+            return false;
1064
+        }
1065
+
1066
+        try {
1067
+            $encryptionModule = $this->getEncryptionModule($fullPath);
1068
+        } catch (ModuleDoesNotExistsException $e) {
1069
+            return false;
1070
+        }
1071
+
1072
+        if ($encryptionModule === null) {
1073
+            $encryptionModule = $this->encryptionManager->getEncryptionModule();
1074
+        }
1075
+
1076
+        return $encryptionModule->shouldEncrypt($fullPath);
1077
+    }
1078
+
1079
+    public function writeStream(string $path, $stream, int $size = null): int {
1080
+        // always fall back to fopen
1081
+        $target = $this->fopen($path, 'w');
1082
+        [$count, $result] = \OC_Helper::streamCopy($stream, $target);
1083
+        fclose($stream);
1084
+        fclose($target);
1085
+
1086
+        // object store, stores the size after write and doesn't update this during scan
1087
+        // manually store the unencrypted size
1088
+        if ($result && $this->getWrapperStorage()->instanceOfStorage(ObjectStoreStorage::class)) {
1089
+            $this->getCache()->put($path, ['unencrypted_size' => $count]);
1090
+        }
1091
+
1092
+        return $count;
1093
+    }
1094
+
1095
+    public function clearIsEncryptedCache(): void {
1096
+        $this->encryptedPaths->clear();
1097
+    }
1098 1098
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/Wrapper/Wrapper.php 1 patch
Indentation   +616 added lines, -616 removed lines patch added patch discarded remove patch
@@ -38,620 +38,620 @@
 block discarded – undo
38 38
 use OCP\Lock\ILockingProvider;
39 39
 
40 40
 class Wrapper implements \OC\Files\Storage\Storage, ILockingStorage, IWriteStreamStorage {
41
-	/**
42
-	 * @var \OC\Files\Storage\Storage $storage
43
-	 */
44
-	protected $storage;
45
-
46
-	public $cache;
47
-	public $scanner;
48
-	public $watcher;
49
-	public $propagator;
50
-	public $updater;
51
-
52
-	/**
53
-	 * @param array $parameters
54
-	 */
55
-	public function __construct($parameters) {
56
-		$this->storage = $parameters['storage'];
57
-	}
58
-
59
-	/**
60
-	 * @return \OC\Files\Storage\Storage
61
-	 */
62
-	public function getWrapperStorage() {
63
-		return $this->storage;
64
-	}
65
-
66
-	/**
67
-	 * Get the identifier for the storage,
68
-	 * the returned id should be the same for every storage object that is created with the same parameters
69
-	 * and two storage objects with the same id should refer to two storages that display the same files.
70
-	 *
71
-	 * @return string
72
-	 */
73
-	public function getId() {
74
-		return $this->getWrapperStorage()->getId();
75
-	}
76
-
77
-	/**
78
-	 * see https://www.php.net/manual/en/function.mkdir.php
79
-	 *
80
-	 * @param string $path
81
-	 * @return bool
82
-	 */
83
-	public function mkdir($path) {
84
-		return $this->getWrapperStorage()->mkdir($path);
85
-	}
86
-
87
-	/**
88
-	 * see https://www.php.net/manual/en/function.rmdir.php
89
-	 *
90
-	 * @param string $path
91
-	 * @return bool
92
-	 */
93
-	public function rmdir($path) {
94
-		return $this->getWrapperStorage()->rmdir($path);
95
-	}
96
-
97
-	/**
98
-	 * see https://www.php.net/manual/en/function.opendir.php
99
-	 *
100
-	 * @param string $path
101
-	 * @return resource|false
102
-	 */
103
-	public function opendir($path) {
104
-		return $this->getWrapperStorage()->opendir($path);
105
-	}
106
-
107
-	/**
108
-	 * see https://www.php.net/manual/en/function.is_dir.php
109
-	 *
110
-	 * @param string $path
111
-	 * @return bool
112
-	 */
113
-	public function is_dir($path) {
114
-		return $this->getWrapperStorage()->is_dir($path);
115
-	}
116
-
117
-	/**
118
-	 * see https://www.php.net/manual/en/function.is_file.php
119
-	 *
120
-	 * @param string $path
121
-	 * @return bool
122
-	 */
123
-	public function is_file($path) {
124
-		return $this->getWrapperStorage()->is_file($path);
125
-	}
126
-
127
-	/**
128
-	 * see https://www.php.net/manual/en/function.stat.php
129
-	 * only the following keys are required in the result: size and mtime
130
-	 *
131
-	 * @param string $path
132
-	 * @return array|bool
133
-	 */
134
-	public function stat($path) {
135
-		return $this->getWrapperStorage()->stat($path);
136
-	}
137
-
138
-	/**
139
-	 * see https://www.php.net/manual/en/function.filetype.php
140
-	 *
141
-	 * @param string $path
142
-	 * @return string|bool
143
-	 */
144
-	public function filetype($path) {
145
-		return $this->getWrapperStorage()->filetype($path);
146
-	}
147
-
148
-	/**
149
-	 * see https://www.php.net/manual/en/function.filesize.php
150
-	 * The result for filesize when called on a folder is required to be 0
151
-	 */
152
-	public function filesize($path): false|int|float {
153
-		return $this->getWrapperStorage()->filesize($path);
154
-	}
155
-
156
-	/**
157
-	 * check if a file can be created in $path
158
-	 *
159
-	 * @param string $path
160
-	 * @return bool
161
-	 */
162
-	public function isCreatable($path) {
163
-		return $this->getWrapperStorage()->isCreatable($path);
164
-	}
165
-
166
-	/**
167
-	 * check if a file can be read
168
-	 *
169
-	 * @param string $path
170
-	 * @return bool
171
-	 */
172
-	public function isReadable($path) {
173
-		return $this->getWrapperStorage()->isReadable($path);
174
-	}
175
-
176
-	/**
177
-	 * check if a file can be written to
178
-	 *
179
-	 * @param string $path
180
-	 * @return bool
181
-	 */
182
-	public function isUpdatable($path) {
183
-		return $this->getWrapperStorage()->isUpdatable($path);
184
-	}
185
-
186
-	/**
187
-	 * check if a file can be deleted
188
-	 *
189
-	 * @param string $path
190
-	 * @return bool
191
-	 */
192
-	public function isDeletable($path) {
193
-		return $this->getWrapperStorage()->isDeletable($path);
194
-	}
195
-
196
-	/**
197
-	 * check if a file can be shared
198
-	 *
199
-	 * @param string $path
200
-	 * @return bool
201
-	 */
202
-	public function isSharable($path) {
203
-		return $this->getWrapperStorage()->isSharable($path);
204
-	}
205
-
206
-	/**
207
-	 * get the full permissions of a path.
208
-	 * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
209
-	 *
210
-	 * @param string $path
211
-	 * @return int
212
-	 */
213
-	public function getPermissions($path) {
214
-		return $this->getWrapperStorage()->getPermissions($path);
215
-	}
216
-
217
-	/**
218
-	 * see https://www.php.net/manual/en/function.file_exists.php
219
-	 *
220
-	 * @param string $path
221
-	 * @return bool
222
-	 */
223
-	public function file_exists($path) {
224
-		return $this->getWrapperStorage()->file_exists($path);
225
-	}
226
-
227
-	/**
228
-	 * see https://www.php.net/manual/en/function.filemtime.php
229
-	 *
230
-	 * @param string $path
231
-	 * @return int|bool
232
-	 */
233
-	public function filemtime($path) {
234
-		return $this->getWrapperStorage()->filemtime($path);
235
-	}
236
-
237
-	/**
238
-	 * see https://www.php.net/manual/en/function.file_get_contents.php
239
-	 *
240
-	 * @param string $path
241
-	 * @return string|false
242
-	 */
243
-	public function file_get_contents($path) {
244
-		return $this->getWrapperStorage()->file_get_contents($path);
245
-	}
246
-
247
-	/**
248
-	 * see https://www.php.net/manual/en/function.file_put_contents.php
249
-	 *
250
-	 * @param string $path
251
-	 * @param mixed $data
252
-	 * @return int|float|false
253
-	 */
254
-	public function file_put_contents($path, $data) {
255
-		return $this->getWrapperStorage()->file_put_contents($path, $data);
256
-	}
257
-
258
-	/**
259
-	 * see https://www.php.net/manual/en/function.unlink.php
260
-	 *
261
-	 * @param string $path
262
-	 * @return bool
263
-	 */
264
-	public function unlink($path) {
265
-		return $this->getWrapperStorage()->unlink($path);
266
-	}
267
-
268
-	/**
269
-	 * see https://www.php.net/manual/en/function.rename.php
270
-	 *
271
-	 * @param string $source
272
-	 * @param string $target
273
-	 * @return bool
274
-	 */
275
-	public function rename($source, $target) {
276
-		return $this->getWrapperStorage()->rename($source, $target);
277
-	}
278
-
279
-	/**
280
-	 * see https://www.php.net/manual/en/function.copy.php
281
-	 *
282
-	 * @param string $source
283
-	 * @param string $target
284
-	 * @return bool
285
-	 */
286
-	public function copy($source, $target) {
287
-		return $this->getWrapperStorage()->copy($source, $target);
288
-	}
289
-
290
-	/**
291
-	 * see https://www.php.net/manual/en/function.fopen.php
292
-	 *
293
-	 * @param string $path
294
-	 * @param string $mode
295
-	 * @return resource|bool
296
-	 */
297
-	public function fopen($path, $mode) {
298
-		return $this->getWrapperStorage()->fopen($path, $mode);
299
-	}
300
-
301
-	/**
302
-	 * get the mimetype for a file or folder
303
-	 * The mimetype for a folder is required to be "httpd/unix-directory"
304
-	 *
305
-	 * @param string $path
306
-	 * @return string|bool
307
-	 */
308
-	public function getMimeType($path) {
309
-		return $this->getWrapperStorage()->getMimeType($path);
310
-	}
311
-
312
-	/**
313
-	 * see https://www.php.net/manual/en/function.hash.php
314
-	 *
315
-	 * @param string $type
316
-	 * @param string $path
317
-	 * @param bool $raw
318
-	 * @return string|bool
319
-	 */
320
-	public function hash($type, $path, $raw = false) {
321
-		return $this->getWrapperStorage()->hash($type, $path, $raw);
322
-	}
323
-
324
-	/**
325
-	 * see https://www.php.net/manual/en/function.free_space.php
326
-	 *
327
-	 * @param string $path
328
-	 * @return int|float|bool
329
-	 */
330
-	public function free_space($path) {
331
-		return $this->getWrapperStorage()->free_space($path);
332
-	}
333
-
334
-	/**
335
-	 * search for occurrences of $query in file names
336
-	 *
337
-	 * @param string $query
338
-	 * @return array|bool
339
-	 */
340
-	public function search($query) {
341
-		return $this->getWrapperStorage()->search($query);
342
-	}
343
-
344
-	/**
345
-	 * see https://www.php.net/manual/en/function.touch.php
346
-	 * If the backend does not support the operation, false should be returned
347
-	 *
348
-	 * @param string $path
349
-	 * @param int $mtime
350
-	 * @return bool
351
-	 */
352
-	public function touch($path, $mtime = null) {
353
-		return $this->getWrapperStorage()->touch($path, $mtime);
354
-	}
355
-
356
-	/**
357
-	 * get the path to a local version of the file.
358
-	 * The local version of the file can be temporary and doesn't have to be persistent across requests
359
-	 *
360
-	 * @param string $path
361
-	 * @return string|false
362
-	 */
363
-	public function getLocalFile($path) {
364
-		return $this->getWrapperStorage()->getLocalFile($path);
365
-	}
366
-
367
-	/**
368
-	 * check if a file or folder has been updated since $time
369
-	 *
370
-	 * @param string $path
371
-	 * @param int $time
372
-	 * @return bool
373
-	 *
374
-	 * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
375
-	 * returning true for other changes in the folder is optional
376
-	 */
377
-	public function hasUpdated($path, $time) {
378
-		return $this->getWrapperStorage()->hasUpdated($path, $time);
379
-	}
380
-
381
-	/**
382
-	 * get a cache instance for the storage
383
-	 *
384
-	 * @param string $path
385
-	 * @param \OC\Files\Storage\Storage|null (optional) the storage to pass to the cache
386
-	 * @return \OC\Files\Cache\Cache
387
-	 */
388
-	public function getCache($path = '', $storage = null) {
389
-		if (!$storage) {
390
-			$storage = $this;
391
-		}
392
-		return $this->getWrapperStorage()->getCache($path, $storage);
393
-	}
394
-
395
-	/**
396
-	 * get a scanner instance for the storage
397
-	 *
398
-	 * @param string $path
399
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
400
-	 * @return \OC\Files\Cache\Scanner
401
-	 */
402
-	public function getScanner($path = '', $storage = null) {
403
-		if (!$storage) {
404
-			$storage = $this;
405
-		}
406
-		return $this->getWrapperStorage()->getScanner($path, $storage);
407
-	}
408
-
409
-
410
-	/**
411
-	 * get the user id of the owner of a file or folder
412
-	 *
413
-	 * @param string $path
414
-	 * @return string
415
-	 */
416
-	public function getOwner($path) {
417
-		return $this->getWrapperStorage()->getOwner($path);
418
-	}
419
-
420
-	/**
421
-	 * get a watcher instance for the cache
422
-	 *
423
-	 * @param string $path
424
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
425
-	 * @return \OC\Files\Cache\Watcher
426
-	 */
427
-	public function getWatcher($path = '', $storage = null) {
428
-		if (!$storage) {
429
-			$storage = $this;
430
-		}
431
-		return $this->getWrapperStorage()->getWatcher($path, $storage);
432
-	}
433
-
434
-	public function getPropagator($storage = null) {
435
-		if (!$storage) {
436
-			$storage = $this;
437
-		}
438
-		return $this->getWrapperStorage()->getPropagator($storage);
439
-	}
440
-
441
-	public function getUpdater($storage = null) {
442
-		if (!$storage) {
443
-			$storage = $this;
444
-		}
445
-		return $this->getWrapperStorage()->getUpdater($storage);
446
-	}
447
-
448
-	/**
449
-	 * @return \OC\Files\Cache\Storage
450
-	 */
451
-	public function getStorageCache() {
452
-		return $this->getWrapperStorage()->getStorageCache();
453
-	}
454
-
455
-	/**
456
-	 * get the ETag for a file or folder
457
-	 *
458
-	 * @param string $path
459
-	 * @return string|false
460
-	 */
461
-	public function getETag($path) {
462
-		return $this->getWrapperStorage()->getETag($path);
463
-	}
464
-
465
-	/**
466
-	 * Returns true
467
-	 *
468
-	 * @return true
469
-	 */
470
-	public function test() {
471
-		return $this->getWrapperStorage()->test();
472
-	}
473
-
474
-	/**
475
-	 * Returns the wrapped storage's value for isLocal()
476
-	 *
477
-	 * @return bool wrapped storage's isLocal() value
478
-	 */
479
-	public function isLocal() {
480
-		return $this->getWrapperStorage()->isLocal();
481
-	}
482
-
483
-	/**
484
-	 * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
485
-	 *
486
-	 * @param class-string<IStorage> $class
487
-	 * @return bool
488
-	 */
489
-	public function instanceOfStorage($class) {
490
-		if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
491
-			// FIXME Temporary fix to keep existing checks working
492
-			$class = '\OCA\Files_Sharing\SharedStorage';
493
-		}
494
-		return is_a($this, $class) or $this->getWrapperStorage()->instanceOfStorage($class);
495
-	}
496
-
497
-	/**
498
-	 * @psalm-template T of IStorage
499
-	 * @psalm-param class-string<T> $class
500
-	 * @psalm-return T|null
501
-	 */
502
-	public function getInstanceOfStorage(string $class) {
503
-		$storage = $this;
504
-		while ($storage instanceof Wrapper) {
505
-			if ($storage instanceof $class) {
506
-				break;
507
-			}
508
-			$storage = $storage->getWrapperStorage();
509
-		}
510
-		if (!($storage instanceof $class)) {
511
-			return null;
512
-		}
513
-		return $storage;
514
-	}
515
-
516
-	/**
517
-	 * Pass any methods custom to specific storage implementations to the wrapped storage
518
-	 *
519
-	 * @param string $method
520
-	 * @param array $args
521
-	 * @return mixed
522
-	 */
523
-	public function __call($method, $args) {
524
-		return call_user_func_array([$this->getWrapperStorage(), $method], $args);
525
-	}
526
-
527
-	/**
528
-	 * A custom storage implementation can return an url for direct download of a give file.
529
-	 *
530
-	 * For now the returned array can hold the parameter url - in future more attributes might follow.
531
-	 *
532
-	 * @param string $path
533
-	 * @return array|bool
534
-	 */
535
-	public function getDirectDownload($path) {
536
-		return $this->getWrapperStorage()->getDirectDownload($path);
537
-	}
538
-
539
-	/**
540
-	 * Get availability of the storage
541
-	 *
542
-	 * @return array [ available, last_checked ]
543
-	 */
544
-	public function getAvailability() {
545
-		return $this->getWrapperStorage()->getAvailability();
546
-	}
547
-
548
-	/**
549
-	 * Set availability of the storage
550
-	 *
551
-	 * @param bool $isAvailable
552
-	 */
553
-	public function setAvailability($isAvailable) {
554
-		$this->getWrapperStorage()->setAvailability($isAvailable);
555
-	}
556
-
557
-	/**
558
-	 * @param string $path the path of the target folder
559
-	 * @param string $fileName the name of the file itself
560
-	 * @return void
561
-	 * @throws InvalidPathException
562
-	 */
563
-	public function verifyPath($path, $fileName) {
564
-		$this->getWrapperStorage()->verifyPath($path, $fileName);
565
-	}
566
-
567
-	/**
568
-	 * @param IStorage $sourceStorage
569
-	 * @param string $sourceInternalPath
570
-	 * @param string $targetInternalPath
571
-	 * @return bool
572
-	 */
573
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
574
-		if ($sourceStorage === $this) {
575
-			return $this->copy($sourceInternalPath, $targetInternalPath);
576
-		}
577
-
578
-		return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
579
-	}
580
-
581
-	/**
582
-	 * @param IStorage $sourceStorage
583
-	 * @param string $sourceInternalPath
584
-	 * @param string $targetInternalPath
585
-	 * @return bool
586
-	 */
587
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
588
-		if ($sourceStorage === $this) {
589
-			return $this->rename($sourceInternalPath, $targetInternalPath);
590
-		}
591
-
592
-		return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
593
-	}
594
-
595
-	public function getMetaData($path) {
596
-		return $this->getWrapperStorage()->getMetaData($path);
597
-	}
598
-
599
-	/**
600
-	 * @param string $path
601
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
602
-	 * @param \OCP\Lock\ILockingProvider $provider
603
-	 * @throws \OCP\Lock\LockedException
604
-	 */
605
-	public function acquireLock($path, $type, ILockingProvider $provider) {
606
-		if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
607
-			$this->getWrapperStorage()->acquireLock($path, $type, $provider);
608
-		}
609
-	}
610
-
611
-	/**
612
-	 * @param string $path
613
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
614
-	 * @param \OCP\Lock\ILockingProvider $provider
615
-	 */
616
-	public function releaseLock($path, $type, ILockingProvider $provider) {
617
-		if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
618
-			$this->getWrapperStorage()->releaseLock($path, $type, $provider);
619
-		}
620
-	}
621
-
622
-	/**
623
-	 * @param string $path
624
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
625
-	 * @param \OCP\Lock\ILockingProvider $provider
626
-	 */
627
-	public function changeLock($path, $type, ILockingProvider $provider) {
628
-		if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
629
-			$this->getWrapperStorage()->changeLock($path, $type, $provider);
630
-		}
631
-	}
632
-
633
-	/**
634
-	 * @return bool
635
-	 */
636
-	public function needsPartFile() {
637
-		return $this->getWrapperStorage()->needsPartFile();
638
-	}
639
-
640
-	public function writeStream(string $path, $stream, int $size = null): int {
641
-		$storage = $this->getWrapperStorage();
642
-		if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
643
-			/** @var IWriteStreamStorage $storage */
644
-			return $storage->writeStream($path, $stream, $size);
645
-		} else {
646
-			$target = $this->fopen($path, 'w');
647
-			[$count, $result] = \OC_Helper::streamCopy($stream, $target);
648
-			fclose($stream);
649
-			fclose($target);
650
-			return $count;
651
-		}
652
-	}
653
-
654
-	public function getDirectoryContent($directory): \Traversable {
655
-		return $this->getWrapperStorage()->getDirectoryContent($directory);
656
-	}
41
+    /**
42
+     * @var \OC\Files\Storage\Storage $storage
43
+     */
44
+    protected $storage;
45
+
46
+    public $cache;
47
+    public $scanner;
48
+    public $watcher;
49
+    public $propagator;
50
+    public $updater;
51
+
52
+    /**
53
+     * @param array $parameters
54
+     */
55
+    public function __construct($parameters) {
56
+        $this->storage = $parameters['storage'];
57
+    }
58
+
59
+    /**
60
+     * @return \OC\Files\Storage\Storage
61
+     */
62
+    public function getWrapperStorage() {
63
+        return $this->storage;
64
+    }
65
+
66
+    /**
67
+     * Get the identifier for the storage,
68
+     * the returned id should be the same for every storage object that is created with the same parameters
69
+     * and two storage objects with the same id should refer to two storages that display the same files.
70
+     *
71
+     * @return string
72
+     */
73
+    public function getId() {
74
+        return $this->getWrapperStorage()->getId();
75
+    }
76
+
77
+    /**
78
+     * see https://www.php.net/manual/en/function.mkdir.php
79
+     *
80
+     * @param string $path
81
+     * @return bool
82
+     */
83
+    public function mkdir($path) {
84
+        return $this->getWrapperStorage()->mkdir($path);
85
+    }
86
+
87
+    /**
88
+     * see https://www.php.net/manual/en/function.rmdir.php
89
+     *
90
+     * @param string $path
91
+     * @return bool
92
+     */
93
+    public function rmdir($path) {
94
+        return $this->getWrapperStorage()->rmdir($path);
95
+    }
96
+
97
+    /**
98
+     * see https://www.php.net/manual/en/function.opendir.php
99
+     *
100
+     * @param string $path
101
+     * @return resource|false
102
+     */
103
+    public function opendir($path) {
104
+        return $this->getWrapperStorage()->opendir($path);
105
+    }
106
+
107
+    /**
108
+     * see https://www.php.net/manual/en/function.is_dir.php
109
+     *
110
+     * @param string $path
111
+     * @return bool
112
+     */
113
+    public function is_dir($path) {
114
+        return $this->getWrapperStorage()->is_dir($path);
115
+    }
116
+
117
+    /**
118
+     * see https://www.php.net/manual/en/function.is_file.php
119
+     *
120
+     * @param string $path
121
+     * @return bool
122
+     */
123
+    public function is_file($path) {
124
+        return $this->getWrapperStorage()->is_file($path);
125
+    }
126
+
127
+    /**
128
+     * see https://www.php.net/manual/en/function.stat.php
129
+     * only the following keys are required in the result: size and mtime
130
+     *
131
+     * @param string $path
132
+     * @return array|bool
133
+     */
134
+    public function stat($path) {
135
+        return $this->getWrapperStorage()->stat($path);
136
+    }
137
+
138
+    /**
139
+     * see https://www.php.net/manual/en/function.filetype.php
140
+     *
141
+     * @param string $path
142
+     * @return string|bool
143
+     */
144
+    public function filetype($path) {
145
+        return $this->getWrapperStorage()->filetype($path);
146
+    }
147
+
148
+    /**
149
+     * see https://www.php.net/manual/en/function.filesize.php
150
+     * The result for filesize when called on a folder is required to be 0
151
+     */
152
+    public function filesize($path): false|int|float {
153
+        return $this->getWrapperStorage()->filesize($path);
154
+    }
155
+
156
+    /**
157
+     * check if a file can be created in $path
158
+     *
159
+     * @param string $path
160
+     * @return bool
161
+     */
162
+    public function isCreatable($path) {
163
+        return $this->getWrapperStorage()->isCreatable($path);
164
+    }
165
+
166
+    /**
167
+     * check if a file can be read
168
+     *
169
+     * @param string $path
170
+     * @return bool
171
+     */
172
+    public function isReadable($path) {
173
+        return $this->getWrapperStorage()->isReadable($path);
174
+    }
175
+
176
+    /**
177
+     * check if a file can be written to
178
+     *
179
+     * @param string $path
180
+     * @return bool
181
+     */
182
+    public function isUpdatable($path) {
183
+        return $this->getWrapperStorage()->isUpdatable($path);
184
+    }
185
+
186
+    /**
187
+     * check if a file can be deleted
188
+     *
189
+     * @param string $path
190
+     * @return bool
191
+     */
192
+    public function isDeletable($path) {
193
+        return $this->getWrapperStorage()->isDeletable($path);
194
+    }
195
+
196
+    /**
197
+     * check if a file can be shared
198
+     *
199
+     * @param string $path
200
+     * @return bool
201
+     */
202
+    public function isSharable($path) {
203
+        return $this->getWrapperStorage()->isSharable($path);
204
+    }
205
+
206
+    /**
207
+     * get the full permissions of a path.
208
+     * Should return a combination of the PERMISSION_ constants defined in lib/public/constants.php
209
+     *
210
+     * @param string $path
211
+     * @return int
212
+     */
213
+    public function getPermissions($path) {
214
+        return $this->getWrapperStorage()->getPermissions($path);
215
+    }
216
+
217
+    /**
218
+     * see https://www.php.net/manual/en/function.file_exists.php
219
+     *
220
+     * @param string $path
221
+     * @return bool
222
+     */
223
+    public function file_exists($path) {
224
+        return $this->getWrapperStorage()->file_exists($path);
225
+    }
226
+
227
+    /**
228
+     * see https://www.php.net/manual/en/function.filemtime.php
229
+     *
230
+     * @param string $path
231
+     * @return int|bool
232
+     */
233
+    public function filemtime($path) {
234
+        return $this->getWrapperStorage()->filemtime($path);
235
+    }
236
+
237
+    /**
238
+     * see https://www.php.net/manual/en/function.file_get_contents.php
239
+     *
240
+     * @param string $path
241
+     * @return string|false
242
+     */
243
+    public function file_get_contents($path) {
244
+        return $this->getWrapperStorage()->file_get_contents($path);
245
+    }
246
+
247
+    /**
248
+     * see https://www.php.net/manual/en/function.file_put_contents.php
249
+     *
250
+     * @param string $path
251
+     * @param mixed $data
252
+     * @return int|float|false
253
+     */
254
+    public function file_put_contents($path, $data) {
255
+        return $this->getWrapperStorage()->file_put_contents($path, $data);
256
+    }
257
+
258
+    /**
259
+     * see https://www.php.net/manual/en/function.unlink.php
260
+     *
261
+     * @param string $path
262
+     * @return bool
263
+     */
264
+    public function unlink($path) {
265
+        return $this->getWrapperStorage()->unlink($path);
266
+    }
267
+
268
+    /**
269
+     * see https://www.php.net/manual/en/function.rename.php
270
+     *
271
+     * @param string $source
272
+     * @param string $target
273
+     * @return bool
274
+     */
275
+    public function rename($source, $target) {
276
+        return $this->getWrapperStorage()->rename($source, $target);
277
+    }
278
+
279
+    /**
280
+     * see https://www.php.net/manual/en/function.copy.php
281
+     *
282
+     * @param string $source
283
+     * @param string $target
284
+     * @return bool
285
+     */
286
+    public function copy($source, $target) {
287
+        return $this->getWrapperStorage()->copy($source, $target);
288
+    }
289
+
290
+    /**
291
+     * see https://www.php.net/manual/en/function.fopen.php
292
+     *
293
+     * @param string $path
294
+     * @param string $mode
295
+     * @return resource|bool
296
+     */
297
+    public function fopen($path, $mode) {
298
+        return $this->getWrapperStorage()->fopen($path, $mode);
299
+    }
300
+
301
+    /**
302
+     * get the mimetype for a file or folder
303
+     * The mimetype for a folder is required to be "httpd/unix-directory"
304
+     *
305
+     * @param string $path
306
+     * @return string|bool
307
+     */
308
+    public function getMimeType($path) {
309
+        return $this->getWrapperStorage()->getMimeType($path);
310
+    }
311
+
312
+    /**
313
+     * see https://www.php.net/manual/en/function.hash.php
314
+     *
315
+     * @param string $type
316
+     * @param string $path
317
+     * @param bool $raw
318
+     * @return string|bool
319
+     */
320
+    public function hash($type, $path, $raw = false) {
321
+        return $this->getWrapperStorage()->hash($type, $path, $raw);
322
+    }
323
+
324
+    /**
325
+     * see https://www.php.net/manual/en/function.free_space.php
326
+     *
327
+     * @param string $path
328
+     * @return int|float|bool
329
+     */
330
+    public function free_space($path) {
331
+        return $this->getWrapperStorage()->free_space($path);
332
+    }
333
+
334
+    /**
335
+     * search for occurrences of $query in file names
336
+     *
337
+     * @param string $query
338
+     * @return array|bool
339
+     */
340
+    public function search($query) {
341
+        return $this->getWrapperStorage()->search($query);
342
+    }
343
+
344
+    /**
345
+     * see https://www.php.net/manual/en/function.touch.php
346
+     * If the backend does not support the operation, false should be returned
347
+     *
348
+     * @param string $path
349
+     * @param int $mtime
350
+     * @return bool
351
+     */
352
+    public function touch($path, $mtime = null) {
353
+        return $this->getWrapperStorage()->touch($path, $mtime);
354
+    }
355
+
356
+    /**
357
+     * get the path to a local version of the file.
358
+     * The local version of the file can be temporary and doesn't have to be persistent across requests
359
+     *
360
+     * @param string $path
361
+     * @return string|false
362
+     */
363
+    public function getLocalFile($path) {
364
+        return $this->getWrapperStorage()->getLocalFile($path);
365
+    }
366
+
367
+    /**
368
+     * check if a file or folder has been updated since $time
369
+     *
370
+     * @param string $path
371
+     * @param int $time
372
+     * @return bool
373
+     *
374
+     * hasUpdated for folders should return at least true if a file inside the folder is add, removed or renamed.
375
+     * returning true for other changes in the folder is optional
376
+     */
377
+    public function hasUpdated($path, $time) {
378
+        return $this->getWrapperStorage()->hasUpdated($path, $time);
379
+    }
380
+
381
+    /**
382
+     * get a cache instance for the storage
383
+     *
384
+     * @param string $path
385
+     * @param \OC\Files\Storage\Storage|null (optional) the storage to pass to the cache
386
+     * @return \OC\Files\Cache\Cache
387
+     */
388
+    public function getCache($path = '', $storage = null) {
389
+        if (!$storage) {
390
+            $storage = $this;
391
+        }
392
+        return $this->getWrapperStorage()->getCache($path, $storage);
393
+    }
394
+
395
+    /**
396
+     * get a scanner instance for the storage
397
+     *
398
+     * @param string $path
399
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
400
+     * @return \OC\Files\Cache\Scanner
401
+     */
402
+    public function getScanner($path = '', $storage = null) {
403
+        if (!$storage) {
404
+            $storage = $this;
405
+        }
406
+        return $this->getWrapperStorage()->getScanner($path, $storage);
407
+    }
408
+
409
+
410
+    /**
411
+     * get the user id of the owner of a file or folder
412
+     *
413
+     * @param string $path
414
+     * @return string
415
+     */
416
+    public function getOwner($path) {
417
+        return $this->getWrapperStorage()->getOwner($path);
418
+    }
419
+
420
+    /**
421
+     * get a watcher instance for the cache
422
+     *
423
+     * @param string $path
424
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
425
+     * @return \OC\Files\Cache\Watcher
426
+     */
427
+    public function getWatcher($path = '', $storage = null) {
428
+        if (!$storage) {
429
+            $storage = $this;
430
+        }
431
+        return $this->getWrapperStorage()->getWatcher($path, $storage);
432
+    }
433
+
434
+    public function getPropagator($storage = null) {
435
+        if (!$storage) {
436
+            $storage = $this;
437
+        }
438
+        return $this->getWrapperStorage()->getPropagator($storage);
439
+    }
440
+
441
+    public function getUpdater($storage = null) {
442
+        if (!$storage) {
443
+            $storage = $this;
444
+        }
445
+        return $this->getWrapperStorage()->getUpdater($storage);
446
+    }
447
+
448
+    /**
449
+     * @return \OC\Files\Cache\Storage
450
+     */
451
+    public function getStorageCache() {
452
+        return $this->getWrapperStorage()->getStorageCache();
453
+    }
454
+
455
+    /**
456
+     * get the ETag for a file or folder
457
+     *
458
+     * @param string $path
459
+     * @return string|false
460
+     */
461
+    public function getETag($path) {
462
+        return $this->getWrapperStorage()->getETag($path);
463
+    }
464
+
465
+    /**
466
+     * Returns true
467
+     *
468
+     * @return true
469
+     */
470
+    public function test() {
471
+        return $this->getWrapperStorage()->test();
472
+    }
473
+
474
+    /**
475
+     * Returns the wrapped storage's value for isLocal()
476
+     *
477
+     * @return bool wrapped storage's isLocal() value
478
+     */
479
+    public function isLocal() {
480
+        return $this->getWrapperStorage()->isLocal();
481
+    }
482
+
483
+    /**
484
+     * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
485
+     *
486
+     * @param class-string<IStorage> $class
487
+     * @return bool
488
+     */
489
+    public function instanceOfStorage($class) {
490
+        if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
491
+            // FIXME Temporary fix to keep existing checks working
492
+            $class = '\OCA\Files_Sharing\SharedStorage';
493
+        }
494
+        return is_a($this, $class) or $this->getWrapperStorage()->instanceOfStorage($class);
495
+    }
496
+
497
+    /**
498
+     * @psalm-template T of IStorage
499
+     * @psalm-param class-string<T> $class
500
+     * @psalm-return T|null
501
+     */
502
+    public function getInstanceOfStorage(string $class) {
503
+        $storage = $this;
504
+        while ($storage instanceof Wrapper) {
505
+            if ($storage instanceof $class) {
506
+                break;
507
+            }
508
+            $storage = $storage->getWrapperStorage();
509
+        }
510
+        if (!($storage instanceof $class)) {
511
+            return null;
512
+        }
513
+        return $storage;
514
+    }
515
+
516
+    /**
517
+     * Pass any methods custom to specific storage implementations to the wrapped storage
518
+     *
519
+     * @param string $method
520
+     * @param array $args
521
+     * @return mixed
522
+     */
523
+    public function __call($method, $args) {
524
+        return call_user_func_array([$this->getWrapperStorage(), $method], $args);
525
+    }
526
+
527
+    /**
528
+     * A custom storage implementation can return an url for direct download of a give file.
529
+     *
530
+     * For now the returned array can hold the parameter url - in future more attributes might follow.
531
+     *
532
+     * @param string $path
533
+     * @return array|bool
534
+     */
535
+    public function getDirectDownload($path) {
536
+        return $this->getWrapperStorage()->getDirectDownload($path);
537
+    }
538
+
539
+    /**
540
+     * Get availability of the storage
541
+     *
542
+     * @return array [ available, last_checked ]
543
+     */
544
+    public function getAvailability() {
545
+        return $this->getWrapperStorage()->getAvailability();
546
+    }
547
+
548
+    /**
549
+     * Set availability of the storage
550
+     *
551
+     * @param bool $isAvailable
552
+     */
553
+    public function setAvailability($isAvailable) {
554
+        $this->getWrapperStorage()->setAvailability($isAvailable);
555
+    }
556
+
557
+    /**
558
+     * @param string $path the path of the target folder
559
+     * @param string $fileName the name of the file itself
560
+     * @return void
561
+     * @throws InvalidPathException
562
+     */
563
+    public function verifyPath($path, $fileName) {
564
+        $this->getWrapperStorage()->verifyPath($path, $fileName);
565
+    }
566
+
567
+    /**
568
+     * @param IStorage $sourceStorage
569
+     * @param string $sourceInternalPath
570
+     * @param string $targetInternalPath
571
+     * @return bool
572
+     */
573
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
574
+        if ($sourceStorage === $this) {
575
+            return $this->copy($sourceInternalPath, $targetInternalPath);
576
+        }
577
+
578
+        return $this->getWrapperStorage()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
579
+    }
580
+
581
+    /**
582
+     * @param IStorage $sourceStorage
583
+     * @param string $sourceInternalPath
584
+     * @param string $targetInternalPath
585
+     * @return bool
586
+     */
587
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
588
+        if ($sourceStorage === $this) {
589
+            return $this->rename($sourceInternalPath, $targetInternalPath);
590
+        }
591
+
592
+        return $this->getWrapperStorage()->moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
593
+    }
594
+
595
+    public function getMetaData($path) {
596
+        return $this->getWrapperStorage()->getMetaData($path);
597
+    }
598
+
599
+    /**
600
+     * @param string $path
601
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
602
+     * @param \OCP\Lock\ILockingProvider $provider
603
+     * @throws \OCP\Lock\LockedException
604
+     */
605
+    public function acquireLock($path, $type, ILockingProvider $provider) {
606
+        if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
607
+            $this->getWrapperStorage()->acquireLock($path, $type, $provider);
608
+        }
609
+    }
610
+
611
+    /**
612
+     * @param string $path
613
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
614
+     * @param \OCP\Lock\ILockingProvider $provider
615
+     */
616
+    public function releaseLock($path, $type, ILockingProvider $provider) {
617
+        if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
618
+            $this->getWrapperStorage()->releaseLock($path, $type, $provider);
619
+        }
620
+    }
621
+
622
+    /**
623
+     * @param string $path
624
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
625
+     * @param \OCP\Lock\ILockingProvider $provider
626
+     */
627
+    public function changeLock($path, $type, ILockingProvider $provider) {
628
+        if ($this->getWrapperStorage()->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
629
+            $this->getWrapperStorage()->changeLock($path, $type, $provider);
630
+        }
631
+    }
632
+
633
+    /**
634
+     * @return bool
635
+     */
636
+    public function needsPartFile() {
637
+        return $this->getWrapperStorage()->needsPartFile();
638
+    }
639
+
640
+    public function writeStream(string $path, $stream, int $size = null): int {
641
+        $storage = $this->getWrapperStorage();
642
+        if ($storage->instanceOfStorage(IWriteStreamStorage::class)) {
643
+            /** @var IWriteStreamStorage $storage */
644
+            return $storage->writeStream($path, $stream, $size);
645
+        } else {
646
+            $target = $this->fopen($path, 'w');
647
+            [$count, $result] = \OC_Helper::streamCopy($stream, $target);
648
+            fclose($stream);
649
+            fclose($target);
650
+            return $count;
651
+        }
652
+    }
653
+
654
+    public function getDirectoryContent($directory): \Traversable {
655
+        return $this->getWrapperStorage()->getDirectoryContent($directory);
656
+    }
657 657
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2072 added lines, -2072 removed lines patch added patch discarded remove patch
@@ -87,2076 +87,2076 @@
 block discarded – undo
87 87
  * \OC\Files\Storage\Storage object
88 88
  */
89 89
 class View {
90
-	private string $fakeRoot = '';
91
-	private ILockingProvider $lockingProvider;
92
-	private bool $lockingEnabled;
93
-	private bool $updaterEnabled = true;
94
-	private UserManager $userManager;
95
-	private LoggerInterface $logger;
96
-
97
-	/**
98
-	 * @throws \Exception If $root contains an invalid path
99
-	 */
100
-	public function __construct(string $root = '') {
101
-		if (!Filesystem::isValidPath($root)) {
102
-			throw new \Exception();
103
-		}
104
-
105
-		$this->fakeRoot = $root;
106
-		$this->lockingProvider = \OC::$server->getLockingProvider();
107
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
108
-		$this->userManager = \OC::$server->getUserManager();
109
-		$this->logger = \OC::$server->get(LoggerInterface::class);
110
-	}
111
-
112
-	/**
113
-	 * @param ?string $path
114
-	 * @psalm-template S as string|null
115
-	 * @psalm-param S $path
116
-	 * @psalm-return (S is string ? string : null)
117
-	 */
118
-	public function getAbsolutePath($path = '/'): ?string {
119
-		if ($path === null) {
120
-			return null;
121
-		}
122
-		$this->assertPathLength($path);
123
-		if ($path === '') {
124
-			$path = '/';
125
-		}
126
-		if ($path[0] !== '/') {
127
-			$path = '/' . $path;
128
-		}
129
-		return $this->fakeRoot . $path;
130
-	}
131
-
132
-	/**
133
-	 * Change the root to a fake root
134
-	 *
135
-	 * @param string $fakeRoot
136
-	 */
137
-	public function chroot($fakeRoot): void {
138
-		if (!$fakeRoot == '') {
139
-			if ($fakeRoot[0] !== '/') {
140
-				$fakeRoot = '/' . $fakeRoot;
141
-			}
142
-		}
143
-		$this->fakeRoot = $fakeRoot;
144
-	}
145
-
146
-	/**
147
-	 * Get the fake root
148
-	 */
149
-	public function getRoot(): string {
150
-		return $this->fakeRoot;
151
-	}
152
-
153
-	/**
154
-	 * get path relative to the root of the view
155
-	 *
156
-	 * @param string $path
157
-	 */
158
-	public function getRelativePath($path): ?string {
159
-		$this->assertPathLength($path);
160
-		if ($this->fakeRoot == '') {
161
-			return $path;
162
-		}
163
-
164
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
165
-			return '/';
166
-		}
167
-
168
-		// missing slashes can cause wrong matches!
169
-		$root = rtrim($this->fakeRoot, '/') . '/';
170
-
171
-		if (strpos($path, $root) !== 0) {
172
-			return null;
173
-		} else {
174
-			$path = substr($path, strlen($this->fakeRoot));
175
-			if (strlen($path) === 0) {
176
-				return '/';
177
-			} else {
178
-				return $path;
179
-			}
180
-		}
181
-	}
182
-
183
-	/**
184
-	 * Get the mountpoint of the storage object for a path
185
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
186
-	 * returned mountpoint is relative to the absolute root of the filesystem
187
-	 * and does not take the chroot into account )
188
-	 *
189
-	 * @param string $path
190
-	 */
191
-	public function getMountPoint($path): string {
192
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
193
-	}
194
-
195
-	/**
196
-	 * Get the mountpoint of the storage object for a path
197
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
198
-	 * returned mountpoint is relative to the absolute root of the filesystem
199
-	 * and does not take the chroot into account )
200
-	 *
201
-	 * @param string $path
202
-	 */
203
-	public function getMount($path): IMountPoint {
204
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
205
-	}
206
-
207
-	/**
208
-	 * Resolve a path to a storage and internal path
209
-	 *
210
-	 * @param string $path
211
-	 * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
212
-	 */
213
-	public function resolvePath($path): array {
214
-		$a = $this->getAbsolutePath($path);
215
-		$p = Filesystem::normalizePath($a);
216
-		return Filesystem::resolvePath($p);
217
-	}
218
-
219
-	/**
220
-	 * Return the path to a local version of the file
221
-	 * we need this because we can't know if a file is stored local or not from
222
-	 * outside the filestorage and for some purposes a local file is needed
223
-	 *
224
-	 * @param string $path
225
-	 */
226
-	public function getLocalFile($path): string|false {
227
-		$parent = substr($path, 0, strrpos($path, '/') ?: 0);
228
-		$path = $this->getAbsolutePath($path);
229
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
230
-		if (Filesystem::isValidPath($parent) && $storage) {
231
-			return $storage->getLocalFile($internalPath);
232
-		} else {
233
-			return false;
234
-		}
235
-	}
236
-
237
-	/**
238
-	 * the following functions operate with arguments and return values identical
239
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
240
-	 * for \OC\Files\Storage\Storage via basicOperation().
241
-	 */
242
-	public function mkdir($path) {
243
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
244
-	}
245
-
246
-	/**
247
-	 * remove mount point
248
-	 *
249
-	 * @param IMountPoint $mount
250
-	 * @param string $path relative to data/
251
-	 */
252
-	protected function removeMount($mount, $path): bool {
253
-		if ($mount instanceof MoveableMount) {
254
-			// cut of /user/files to get the relative path to data/user/files
255
-			$pathParts = explode('/', $path, 4);
256
-			$relPath = '/' . $pathParts[3];
257
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
258
-			\OC_Hook::emit(
259
-				Filesystem::CLASSNAME, "umount",
260
-				[Filesystem::signal_param_path => $relPath]
261
-			);
262
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
263
-			$result = $mount->removeMount();
264
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
265
-			if ($result) {
266
-				\OC_Hook::emit(
267
-					Filesystem::CLASSNAME, "post_umount",
268
-					[Filesystem::signal_param_path => $relPath]
269
-				);
270
-			}
271
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
272
-			return $result;
273
-		} else {
274
-			// do not allow deleting the storage's root / the mount point
275
-			// because for some storages it might delete the whole contents
276
-			// but isn't supposed to work that way
277
-			return false;
278
-		}
279
-	}
280
-
281
-	public function disableCacheUpdate(): void {
282
-		$this->updaterEnabled = false;
283
-	}
284
-
285
-	public function enableCacheUpdate(): void {
286
-		$this->updaterEnabled = true;
287
-	}
288
-
289
-	protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null): void {
290
-		if ($this->updaterEnabled) {
291
-			if (is_null($time)) {
292
-				$time = time();
293
-			}
294
-			$storage->getUpdater()->update($internalPath, $time);
295
-		}
296
-	}
297
-
298
-	protected function removeUpdate(Storage $storage, string $internalPath): void {
299
-		if ($this->updaterEnabled) {
300
-			$storage->getUpdater()->remove($internalPath);
301
-		}
302
-	}
303
-
304
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
305
-		if ($this->updaterEnabled) {
306
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
307
-		}
308
-	}
309
-
310
-	/**
311
-	 * @param string $path
312
-	 * @return bool|mixed
313
-	 */
314
-	public function rmdir($path) {
315
-		$absolutePath = $this->getAbsolutePath($path);
316
-		$mount = Filesystem::getMountManager()->find($absolutePath);
317
-		if ($mount->getInternalPath($absolutePath) === '') {
318
-			return $this->removeMount($mount, $absolutePath);
319
-		}
320
-		if ($this->is_dir($path)) {
321
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
322
-		} else {
323
-			$result = false;
324
-		}
325
-
326
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
327
-			$storage = $mount->getStorage();
328
-			$internalPath = $mount->getInternalPath($absolutePath);
329
-			$storage->getUpdater()->remove($internalPath);
330
-		}
331
-		return $result;
332
-	}
333
-
334
-	/**
335
-	 * @param string $path
336
-	 * @return resource|false
337
-	 */
338
-	public function opendir($path) {
339
-		return $this->basicOperation('opendir', $path, ['read']);
340
-	}
341
-
342
-	/**
343
-	 * @param string $path
344
-	 * @return bool|mixed
345
-	 */
346
-	public function is_dir($path) {
347
-		if ($path == '/') {
348
-			return true;
349
-		}
350
-		return $this->basicOperation('is_dir', $path);
351
-	}
352
-
353
-	/**
354
-	 * @param string $path
355
-	 * @return bool|mixed
356
-	 */
357
-	public function is_file($path) {
358
-		if ($path == '/') {
359
-			return false;
360
-		}
361
-		return $this->basicOperation('is_file', $path);
362
-	}
363
-
364
-	/**
365
-	 * @param string $path
366
-	 * @return mixed
367
-	 */
368
-	public function stat($path) {
369
-		return $this->basicOperation('stat', $path);
370
-	}
371
-
372
-	/**
373
-	 * @param string $path
374
-	 * @return mixed
375
-	 */
376
-	public function filetype($path) {
377
-		return $this->basicOperation('filetype', $path);
378
-	}
379
-
380
-	/**
381
-	 * @param string $path
382
-	 * @return mixed
383
-	 */
384
-	public function filesize(string $path) {
385
-		return $this->basicOperation('filesize', $path);
386
-	}
387
-
388
-	/**
389
-	 * @param string $path
390
-	 * @return bool|mixed
391
-	 * @throws InvalidPathException
392
-	 */
393
-	public function readfile($path) {
394
-		$this->assertPathLength($path);
395
-		if (ob_get_level()) {
396
-			ob_end_clean();
397
-		}
398
-		$handle = $this->fopen($path, 'rb');
399
-		if ($handle) {
400
-			$chunkSize = 524288; // 512 kB chunks
401
-			while (!feof($handle)) {
402
-				echo fread($handle, $chunkSize);
403
-				flush();
404
-			}
405
-			fclose($handle);
406
-			return $this->filesize($path);
407
-		}
408
-		return false;
409
-	}
410
-
411
-	/**
412
-	 * @param string $path
413
-	 * @param int $from
414
-	 * @param int $to
415
-	 * @return bool|mixed
416
-	 * @throws InvalidPathException
417
-	 * @throws \OCP\Files\UnseekableException
418
-	 */
419
-	public function readfilePart($path, $from, $to) {
420
-		$this->assertPathLength($path);
421
-		if (ob_get_level()) {
422
-			ob_end_clean();
423
-		}
424
-		$handle = $this->fopen($path, 'rb');
425
-		if ($handle) {
426
-			$chunkSize = 524288; // 512 kB chunks
427
-			$startReading = true;
428
-
429
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
430
-				// forward file handle via chunked fread because fseek seem to have failed
431
-
432
-				$end = $from + 1;
433
-				while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
434
-					$len = $from - ftell($handle);
435
-					if ($len > $chunkSize) {
436
-						$len = $chunkSize;
437
-					}
438
-					$result = fread($handle, $len);
439
-
440
-					if ($result === false) {
441
-						$startReading = false;
442
-						break;
443
-					}
444
-				}
445
-			}
446
-
447
-			if ($startReading) {
448
-				$end = $to + 1;
449
-				while (!feof($handle) && ftell($handle) < $end) {
450
-					$len = $end - ftell($handle);
451
-					if ($len > $chunkSize) {
452
-						$len = $chunkSize;
453
-					}
454
-					echo fread($handle, $len);
455
-					flush();
456
-				}
457
-				return ftell($handle) - $from;
458
-			}
459
-
460
-			throw new \OCP\Files\UnseekableException('fseek error');
461
-		}
462
-		return false;
463
-	}
464
-
465
-	/**
466
-	 * @param string $path
467
-	 * @return mixed
468
-	 */
469
-	public function isCreatable($path) {
470
-		return $this->basicOperation('isCreatable', $path);
471
-	}
472
-
473
-	/**
474
-	 * @param string $path
475
-	 * @return mixed
476
-	 */
477
-	public function isReadable($path) {
478
-		return $this->basicOperation('isReadable', $path);
479
-	}
480
-
481
-	/**
482
-	 * @param string $path
483
-	 * @return mixed
484
-	 */
485
-	public function isUpdatable($path) {
486
-		return $this->basicOperation('isUpdatable', $path);
487
-	}
488
-
489
-	/**
490
-	 * @param string $path
491
-	 * @return bool|mixed
492
-	 */
493
-	public function isDeletable($path) {
494
-		$absolutePath = $this->getAbsolutePath($path);
495
-		$mount = Filesystem::getMountManager()->find($absolutePath);
496
-		if ($mount->getInternalPath($absolutePath) === '') {
497
-			return $mount instanceof MoveableMount;
498
-		}
499
-		return $this->basicOperation('isDeletable', $path);
500
-	}
501
-
502
-	/**
503
-	 * @param string $path
504
-	 * @return mixed
505
-	 */
506
-	public function isSharable($path) {
507
-		return $this->basicOperation('isSharable', $path);
508
-	}
509
-
510
-	/**
511
-	 * @param string $path
512
-	 * @return bool|mixed
513
-	 */
514
-	public function file_exists($path) {
515
-		if ($path == '/') {
516
-			return true;
517
-		}
518
-		return $this->basicOperation('file_exists', $path);
519
-	}
520
-
521
-	/**
522
-	 * @param string $path
523
-	 * @return mixed
524
-	 */
525
-	public function filemtime($path) {
526
-		return $this->basicOperation('filemtime', $path);
527
-	}
528
-
529
-	/**
530
-	 * @param string $path
531
-	 * @param int|string $mtime
532
-	 */
533
-	public function touch($path, $mtime = null): bool {
534
-		if (!is_null($mtime) && !is_numeric($mtime)) {
535
-			$mtime = strtotime($mtime);
536
-		}
537
-
538
-		$hooks = ['touch'];
539
-
540
-		if (!$this->file_exists($path)) {
541
-			$hooks[] = 'create';
542
-			$hooks[] = 'write';
543
-		}
544
-		try {
545
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
546
-		} catch (\Exception $e) {
547
-			$this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
548
-			$result = false;
549
-		}
550
-		if (!$result) {
551
-			// If create file fails because of permissions on external storage like SMB folders,
552
-			// check file exists and return false if not.
553
-			if (!$this->file_exists($path)) {
554
-				return false;
555
-			}
556
-			if (is_null($mtime)) {
557
-				$mtime = time();
558
-			}
559
-			//if native touch fails, we emulate it by changing the mtime in the cache
560
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
561
-		}
562
-		return true;
563
-	}
564
-
565
-	/**
566
-	 * @param string $path
567
-	 * @return string|false
568
-	 * @throws LockedException
569
-	 */
570
-	public function file_get_contents($path) {
571
-		return $this->basicOperation('file_get_contents', $path, ['read']);
572
-	}
573
-
574
-	protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
575
-		if (!$exists) {
576
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
577
-				Filesystem::signal_param_path => $this->getHookPath($path),
578
-				Filesystem::signal_param_run => &$run,
579
-			]);
580
-		} else {
581
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
582
-				Filesystem::signal_param_path => $this->getHookPath($path),
583
-				Filesystem::signal_param_run => &$run,
584
-			]);
585
-		}
586
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
587
-			Filesystem::signal_param_path => $this->getHookPath($path),
588
-			Filesystem::signal_param_run => &$run,
589
-		]);
590
-	}
591
-
592
-	protected function emit_file_hooks_post(bool $exists, string $path): void {
593
-		if (!$exists) {
594
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
595
-				Filesystem::signal_param_path => $this->getHookPath($path),
596
-			]);
597
-		} else {
598
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
599
-				Filesystem::signal_param_path => $this->getHookPath($path),
600
-			]);
601
-		}
602
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
603
-			Filesystem::signal_param_path => $this->getHookPath($path),
604
-		]);
605
-	}
606
-
607
-	/**
608
-	 * @param string $path
609
-	 * @param string|resource $data
610
-	 * @return bool|mixed
611
-	 * @throws LockedException
612
-	 */
613
-	public function file_put_contents($path, $data) {
614
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
615
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
616
-			if (Filesystem::isValidPath($path)
617
-				&& !Filesystem::isFileBlacklisted($path)
618
-			) {
619
-				$path = $this->getRelativePath($absolutePath);
620
-				if ($path === null) {
621
-					throw new InvalidPathException("Path $absolutePath is not in the expected root");
622
-				}
623
-
624
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
625
-
626
-				$exists = $this->file_exists($path);
627
-				$run = true;
628
-				if ($this->shouldEmitHooks($path)) {
629
-					$this->emit_file_hooks_pre($exists, $path, $run);
630
-				}
631
-				if (!$run) {
632
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
633
-					return false;
634
-				}
635
-
636
-				try {
637
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
638
-				} catch (\Exception $e) {
639
-					// Release the shared lock before throwing.
640
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
641
-					throw $e;
642
-				}
643
-
644
-				/** @var Storage $storage */
645
-				[$storage, $internalPath] = $this->resolvePath($path);
646
-				$target = $storage->fopen($internalPath, 'w');
647
-				if ($target) {
648
-					[, $result] = \OC_Helper::streamCopy($data, $target);
649
-					fclose($target);
650
-					fclose($data);
651
-
652
-					$this->writeUpdate($storage, $internalPath);
653
-
654
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
655
-
656
-					if ($this->shouldEmitHooks($path) && $result !== false) {
657
-						$this->emit_file_hooks_post($exists, $path);
658
-					}
659
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
660
-					return $result;
661
-				} else {
662
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
663
-					return false;
664
-				}
665
-			} else {
666
-				return false;
667
-			}
668
-		} else {
669
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
670
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
671
-		}
672
-	}
673
-
674
-	/**
675
-	 * @param string $path
676
-	 * @return bool|mixed
677
-	 */
678
-	public function unlink($path) {
679
-		if ($path === '' || $path === '/') {
680
-			// do not allow deleting the root
681
-			return false;
682
-		}
683
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
684
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
686
-		if ($mount->getInternalPath($absolutePath) === '') {
687
-			return $this->removeMount($mount, $absolutePath);
688
-		}
689
-		if ($this->is_dir($path)) {
690
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
691
-		} else {
692
-			$result = $this->basicOperation('unlink', $path, ['delete']);
693
-		}
694
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
695
-			$storage = $mount->getStorage();
696
-			$internalPath = $mount->getInternalPath($absolutePath);
697
-			$storage->getUpdater()->remove($internalPath);
698
-			return true;
699
-		} else {
700
-			return $result;
701
-		}
702
-	}
703
-
704
-	/**
705
-	 * @param string $directory
706
-	 * @return bool|mixed
707
-	 */
708
-	public function deleteAll($directory) {
709
-		return $this->rmdir($directory);
710
-	}
711
-
712
-	/**
713
-	 * Rename/move a file or folder from the source path to target path.
714
-	 *
715
-	 * @param string $source source path
716
-	 * @param string $target target path
717
-	 *
718
-	 * @return bool|mixed
719
-	 * @throws LockedException
720
-	 */
721
-	public function rename($source, $target) {
722
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
723
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
724
-		$result = false;
725
-		if (
726
-			Filesystem::isValidPath($target)
727
-			&& Filesystem::isValidPath($source)
728
-			&& !Filesystem::isFileBlacklisted($target)
729
-		) {
730
-			$source = $this->getRelativePath($absolutePath1);
731
-			$target = $this->getRelativePath($absolutePath2);
732
-			$exists = $this->file_exists($target);
733
-
734
-			if ($source == null || $target == null) {
735
-				return false;
736
-			}
737
-
738
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
739
-			try {
740
-				$this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
741
-
742
-				$run = true;
743
-				if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
744
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
745
-					$this->emit_file_hooks_pre($exists, $target, $run);
746
-				} elseif ($this->shouldEmitHooks($source)) {
747
-					\OC_Hook::emit(
748
-						Filesystem::CLASSNAME, Filesystem::signal_rename,
749
-						[
750
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
751
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
752
-							Filesystem::signal_param_run => &$run
753
-						]
754
-					);
755
-				}
756
-				if ($run) {
757
-					$this->verifyPath(dirname($target), basename($target));
758
-
759
-					$manager = Filesystem::getMountManager();
760
-					$mount1 = $this->getMount($source);
761
-					$mount2 = $this->getMount($target);
762
-					$storage1 = $mount1->getStorage();
763
-					$storage2 = $mount2->getStorage();
764
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
765
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
766
-
767
-					$this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
768
-					try {
769
-						$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
770
-
771
-						if ($internalPath1 === '') {
772
-							if ($mount1 instanceof MoveableMount) {
773
-								$sourceParentMount = $this->getMount(dirname($source));
774
-								if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
775
-									/**
776
-									 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
777
-									 */
778
-									$sourceMountPoint = $mount1->getMountPoint();
779
-									$result = $mount1->moveMount($absolutePath2);
780
-									$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
781
-								} else {
782
-									$result = false;
783
-								}
784
-							} else {
785
-								$result = false;
786
-							}
787
-						// moving a file/folder within the same mount point
788
-						} elseif ($storage1 === $storage2) {
789
-							if ($storage1) {
790
-								$result = $storage1->rename($internalPath1, $internalPath2);
791
-							} else {
792
-								$result = false;
793
-							}
794
-						// moving a file/folder between storages (from $storage1 to $storage2)
795
-						} else {
796
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
797
-						}
798
-
799
-						if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
800
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
801
-							$this->writeUpdate($storage2, $internalPath2);
802
-						} elseif ($result) {
803
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
804
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
805
-							}
806
-						}
807
-					} catch (\Exception $e) {
808
-						throw $e;
809
-					} finally {
810
-						$this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
811
-						$this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
812
-					}
813
-
814
-					if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
815
-						if ($this->shouldEmitHooks()) {
816
-							$this->emit_file_hooks_post($exists, $target);
817
-						}
818
-					} elseif ($result) {
819
-						if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
820
-							\OC_Hook::emit(
821
-								Filesystem::CLASSNAME,
822
-								Filesystem::signal_post_rename,
823
-								[
824
-									Filesystem::signal_param_oldpath => $this->getHookPath($source),
825
-									Filesystem::signal_param_newpath => $this->getHookPath($target)
826
-								]
827
-							);
828
-						}
829
-					}
830
-				}
831
-			} catch (\Exception $e) {
832
-				throw $e;
833
-			} finally {
834
-				$this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
835
-				$this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
836
-			}
837
-		}
838
-		return $result;
839
-	}
840
-
841
-	/**
842
-	 * Copy a file/folder from the source path to target path
843
-	 *
844
-	 * @param string $source source path
845
-	 * @param string $target target path
846
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
847
-	 *
848
-	 * @return bool|mixed
849
-	 */
850
-	public function copy($source, $target, $preserveMtime = false) {
851
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
852
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
853
-		$result = false;
854
-		if (
855
-			Filesystem::isValidPath($target)
856
-			&& Filesystem::isValidPath($source)
857
-			&& !Filesystem::isFileBlacklisted($target)
858
-		) {
859
-			$source = $this->getRelativePath($absolutePath1);
860
-			$target = $this->getRelativePath($absolutePath2);
861
-
862
-			if ($source == null || $target == null) {
863
-				return false;
864
-			}
865
-			$run = true;
866
-
867
-			$this->lockFile($target, ILockingProvider::LOCK_SHARED);
868
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED);
869
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
870
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
871
-
872
-			try {
873
-				$exists = $this->file_exists($target);
874
-				if ($this->shouldEmitHooks()) {
875
-					\OC_Hook::emit(
876
-						Filesystem::CLASSNAME,
877
-						Filesystem::signal_copy,
878
-						[
879
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
880
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
881
-							Filesystem::signal_param_run => &$run
882
-						]
883
-					);
884
-					$this->emit_file_hooks_pre($exists, $target, $run);
885
-				}
886
-				if ($run) {
887
-					$mount1 = $this->getMount($source);
888
-					$mount2 = $this->getMount($target);
889
-					$storage1 = $mount1->getStorage();
890
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
891
-					$storage2 = $mount2->getStorage();
892
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
893
-
894
-					$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
895
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
896
-
897
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
898
-						if ($storage1) {
899
-							$result = $storage1->copy($internalPath1, $internalPath2);
900
-						} else {
901
-							$result = false;
902
-						}
903
-					} else {
904
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
905
-					}
906
-
907
-					$this->writeUpdate($storage2, $internalPath2);
908
-
909
-					$this->changeLock($target, ILockingProvider::LOCK_SHARED);
910
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
911
-
912
-					if ($this->shouldEmitHooks() && $result !== false) {
913
-						\OC_Hook::emit(
914
-							Filesystem::CLASSNAME,
915
-							Filesystem::signal_post_copy,
916
-							[
917
-								Filesystem::signal_param_oldpath => $this->getHookPath($source),
918
-								Filesystem::signal_param_newpath => $this->getHookPath($target)
919
-							]
920
-						);
921
-						$this->emit_file_hooks_post($exists, $target);
922
-					}
923
-				}
924
-			} catch (\Exception $e) {
925
-				$this->unlockFile($target, $lockTypePath2);
926
-				$this->unlockFile($source, $lockTypePath1);
927
-				throw $e;
928
-			}
929
-
930
-			$this->unlockFile($target, $lockTypePath2);
931
-			$this->unlockFile($source, $lockTypePath1);
932
-		}
933
-		return $result;
934
-	}
935
-
936
-	/**
937
-	 * @param string $path
938
-	 * @param string $mode 'r' or 'w'
939
-	 * @return resource|false
940
-	 * @throws LockedException
941
-	 */
942
-	public function fopen($path, $mode) {
943
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
944
-		$hooks = [];
945
-		switch ($mode) {
946
-			case 'r':
947
-				$hooks[] = 'read';
948
-				break;
949
-			case 'r+':
950
-			case 'w+':
951
-			case 'x+':
952
-			case 'a+':
953
-				$hooks[] = 'read';
954
-				$hooks[] = 'write';
955
-				break;
956
-			case 'w':
957
-			case 'x':
958
-			case 'a':
959
-				$hooks[] = 'write';
960
-				break;
961
-			default:
962
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
963
-		}
964
-
965
-		if ($mode !== 'r' && $mode !== 'w') {
966
-			$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']);
967
-		}
968
-
969
-		$handle = $this->basicOperation('fopen', $path, $hooks, $mode);
970
-		if (!is_resource($handle) && $mode === 'r') {
971
-			// trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
972
-			$mount = $this->getMount($path);
973
-			$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
974
-			$storage = $mount->getStorage();
975
-			if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
976
-				$this->writeUpdate($storage, $internalPath);
977
-			}
978
-		}
979
-		return $handle;
980
-	}
981
-
982
-	/**
983
-	 * @param string $path
984
-	 * @throws InvalidPathException
985
-	 */
986
-	public function toTmpFile($path): string|false {
987
-		$this->assertPathLength($path);
988
-		if (Filesystem::isValidPath($path)) {
989
-			$source = $this->fopen($path, 'r');
990
-			if ($source) {
991
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
992
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
993
-				file_put_contents($tmpFile, $source);
994
-				return $tmpFile;
995
-			} else {
996
-				return false;
997
-			}
998
-		} else {
999
-			return false;
1000
-		}
1001
-	}
1002
-
1003
-	/**
1004
-	 * @param string $tmpFile
1005
-	 * @param string $path
1006
-	 * @return bool|mixed
1007
-	 * @throws InvalidPathException
1008
-	 */
1009
-	public function fromTmpFile($tmpFile, $path) {
1010
-		$this->assertPathLength($path);
1011
-		if (Filesystem::isValidPath($path)) {
1012
-			// Get directory that the file is going into
1013
-			$filePath = dirname($path);
1014
-
1015
-			// Create the directories if any
1016
-			if (!$this->file_exists($filePath)) {
1017
-				$result = $this->createParentDirectories($filePath);
1018
-				if ($result === false) {
1019
-					return false;
1020
-				}
1021
-			}
1022
-
1023
-			$source = fopen($tmpFile, 'r');
1024
-			if ($source) {
1025
-				$result = $this->file_put_contents($path, $source);
1026
-				/**
1027
-				 * $this->file_put_contents() might have already closed
1028
-				 * the resource, so we check it, before trying to close it
1029
-				 * to avoid messages in the error log.
1030
-				 * @psalm-suppress RedundantCondition false-positive
1031
-				 */
1032
-				if (is_resource($source)) {
1033
-					fclose($source);
1034
-				}
1035
-				unlink($tmpFile);
1036
-				return $result;
1037
-			} else {
1038
-				return false;
1039
-			}
1040
-		} else {
1041
-			return false;
1042
-		}
1043
-	}
1044
-
1045
-
1046
-	/**
1047
-	 * @param string $path
1048
-	 * @return mixed
1049
-	 * @throws InvalidPathException
1050
-	 */
1051
-	public function getMimeType($path) {
1052
-		$this->assertPathLength($path);
1053
-		return $this->basicOperation('getMimeType', $path);
1054
-	}
1055
-
1056
-	/**
1057
-	 * @param string $type
1058
-	 * @param string $path
1059
-	 * @param bool $raw
1060
-	 */
1061
-	public function hash($type, $path, $raw = false): string|bool {
1062
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1063
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1064
-		if (Filesystem::isValidPath($path)) {
1065
-			$path = $this->getRelativePath($absolutePath);
1066
-			if ($path == null) {
1067
-				return false;
1068
-			}
1069
-			if ($this->shouldEmitHooks($path)) {
1070
-				\OC_Hook::emit(
1071
-					Filesystem::CLASSNAME,
1072
-					Filesystem::signal_read,
1073
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1074
-				);
1075
-			}
1076
-			/** @var Storage|null $storage */
1077
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1078
-			if ($storage) {
1079
-				return $storage->hash($type, $internalPath, $raw);
1080
-			}
1081
-		}
1082
-		return false;
1083
-	}
1084
-
1085
-	/**
1086
-	 * @param string $path
1087
-	 * @return mixed
1088
-	 * @throws InvalidPathException
1089
-	 */
1090
-	public function free_space($path = '/') {
1091
-		$this->assertPathLength($path);
1092
-		$result = $this->basicOperation('free_space', $path);
1093
-		if ($result === null) {
1094
-			throw new InvalidPathException();
1095
-		}
1096
-		return $result;
1097
-	}
1098
-
1099
-	/**
1100
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1101
-	 *
1102
-	 * @param mixed $extraParam (optional)
1103
-	 * @return mixed
1104
-	 * @throws LockedException
1105
-	 *
1106
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1107
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1108
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1109
-	 */
1110
-	private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1111
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1112
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1113
-		if (Filesystem::isValidPath($path)
1114
-			&& !Filesystem::isFileBlacklisted($path)
1115
-		) {
1116
-			$path = $this->getRelativePath($absolutePath);
1117
-			if ($path == null) {
1118
-				return false;
1119
-			}
1120
-
1121
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1122
-				// always a shared lock during pre-hooks so the hook can read the file
1123
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1124
-			}
1125
-
1126
-			$run = $this->runHooks($hooks, $path);
1127
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1128
-			if ($run && $storage) {
1129
-				/** @var Storage $storage */
1130
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1131
-					try {
1132
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1133
-					} catch (LockedException $e) {
1134
-						// release the shared lock we acquired before quitting
1135
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1136
-						throw $e;
1137
-					}
1138
-				}
1139
-				try {
1140
-					if (!is_null($extraParam)) {
1141
-						$result = $storage->$operation($internalPath, $extraParam);
1142
-					} else {
1143
-						$result = $storage->$operation($internalPath);
1144
-					}
1145
-				} catch (\Exception $e) {
1146
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1147
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1148
-					} elseif (in_array('read', $hooks)) {
1149
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1150
-					}
1151
-					throw $e;
1152
-				}
1153
-
1154
-				if ($result !== false && in_array('delete', $hooks)) {
1155
-					$this->removeUpdate($storage, $internalPath);
1156
-				}
1157
-				if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1158
-					$this->writeUpdate($storage, $internalPath);
1159
-				}
1160
-				if ($result !== false && in_array('touch', $hooks)) {
1161
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1162
-				}
1163
-
1164
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1165
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1166
-				}
1167
-
1168
-				$unlockLater = false;
1169
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1170
-					$unlockLater = true;
1171
-					// make sure our unlocking callback will still be called if connection is aborted
1172
-					ignore_user_abort(true);
1173
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1174
-						if (in_array('write', $hooks)) {
1175
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1176
-						} elseif (in_array('read', $hooks)) {
1177
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1178
-						}
1179
-					});
1180
-				}
1181
-
1182
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1183
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1184
-						$this->runHooks($hooks, $path, true);
1185
-					}
1186
-				}
1187
-
1188
-				if (!$unlockLater
1189
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1190
-				) {
1191
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1192
-				}
1193
-				return $result;
1194
-			} else {
1195
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1196
-			}
1197
-		}
1198
-		return null;
1199
-	}
1200
-
1201
-	/**
1202
-	 * get the path relative to the default root for hook usage
1203
-	 *
1204
-	 * @param string $path
1205
-	 * @return ?string
1206
-	 */
1207
-	private function getHookPath($path): ?string {
1208
-		$view = Filesystem::getView();
1209
-		if (!$view) {
1210
-			return $path;
1211
-		}
1212
-		return $view->getRelativePath($this->getAbsolutePath($path));
1213
-	}
1214
-
1215
-	private function shouldEmitHooks(string $path = ''): bool {
1216
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1217
-			return false;
1218
-		}
1219
-		if (!Filesystem::$loaded) {
1220
-			return false;
1221
-		}
1222
-		$defaultRoot = Filesystem::getRoot();
1223
-		if ($defaultRoot === null) {
1224
-			return false;
1225
-		}
1226
-		if ($this->fakeRoot === $defaultRoot) {
1227
-			return true;
1228
-		}
1229
-		$fullPath = $this->getAbsolutePath($path);
1230
-
1231
-		if ($fullPath === $defaultRoot) {
1232
-			return true;
1233
-		}
1234
-
1235
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1236
-	}
1237
-
1238
-	/**
1239
-	 * @param string[] $hooks
1240
-	 * @param string $path
1241
-	 * @param bool $post
1242
-	 * @return bool
1243
-	 */
1244
-	private function runHooks($hooks, $path, $post = false) {
1245
-		$relativePath = $path;
1246
-		$path = $this->getHookPath($path);
1247
-		$prefix = $post ? 'post_' : '';
1248
-		$run = true;
1249
-		if ($this->shouldEmitHooks($relativePath)) {
1250
-			foreach ($hooks as $hook) {
1251
-				if ($hook != 'read') {
1252
-					\OC_Hook::emit(
1253
-						Filesystem::CLASSNAME,
1254
-						$prefix . $hook,
1255
-						[
1256
-							Filesystem::signal_param_run => &$run,
1257
-							Filesystem::signal_param_path => $path
1258
-						]
1259
-					);
1260
-				} elseif (!$post) {
1261
-					\OC_Hook::emit(
1262
-						Filesystem::CLASSNAME,
1263
-						$prefix . $hook,
1264
-						[
1265
-							Filesystem::signal_param_path => $path
1266
-						]
1267
-					);
1268
-				}
1269
-			}
1270
-		}
1271
-		return $run;
1272
-	}
1273
-
1274
-	/**
1275
-	 * check if a file or folder has been updated since $time
1276
-	 *
1277
-	 * @param string $path
1278
-	 * @param int $time
1279
-	 * @return bool
1280
-	 */
1281
-	public function hasUpdated($path, $time) {
1282
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1283
-	}
1284
-
1285
-	/**
1286
-	 * @param string $ownerId
1287
-	 * @return IUser
1288
-	 */
1289
-	private function getUserObjectForOwner(string $ownerId) {
1290
-		return new LazyUser($ownerId, $this->userManager);
1291
-	}
1292
-
1293
-	/**
1294
-	 * Get file info from cache
1295
-	 *
1296
-	 * If the file is not in cached it will be scanned
1297
-	 * If the file has changed on storage the cache will be updated
1298
-	 *
1299
-	 * @param Storage $storage
1300
-	 * @param string $internalPath
1301
-	 * @param string $relativePath
1302
-	 * @return ICacheEntry|bool
1303
-	 */
1304
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1305
-		$cache = $storage->getCache($internalPath);
1306
-		$data = $cache->get($internalPath);
1307
-		$watcher = $storage->getWatcher($internalPath);
1308
-
1309
-		try {
1310
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1311
-			if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1312
-				if (!$storage->file_exists($internalPath)) {
1313
-					return false;
1314
-				}
1315
-				// don't need to get a lock here since the scanner does it's own locking
1316
-				$scanner = $storage->getScanner($internalPath);
1317
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1318
-				$data = $cache->get($internalPath);
1319
-			} elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1320
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1321
-				$watcher->update($internalPath, $data);
1322
-				$storage->getPropagator()->propagateChange($internalPath, time());
1323
-				$data = $cache->get($internalPath);
1324
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1325
-			}
1326
-		} catch (LockedException $e) {
1327
-			// if the file is locked we just use the old cache info
1328
-		}
1329
-
1330
-		return $data;
1331
-	}
1332
-
1333
-	/**
1334
-	 * get the filesystem info
1335
-	 *
1336
-	 * @param string $path
1337
-	 * @param bool|string $includeMountPoints true to add mountpoint sizes,
1338
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1339
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1340
-	 */
1341
-	public function getFileInfo($path, $includeMountPoints = true) {
1342
-		$this->assertPathLength($path);
1343
-		if (!Filesystem::isValidPath($path)) {
1344
-			return false;
1345
-		}
1346
-		if (Cache\Scanner::isPartialFile($path)) {
1347
-			return $this->getPartFileInfo($path);
1348
-		}
1349
-		$relativePath = $path;
1350
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1351
-
1352
-		$mount = Filesystem::getMountManager()->find($path);
1353
-		$storage = $mount->getStorage();
1354
-		$internalPath = $mount->getInternalPath($path);
1355
-		if ($storage) {
1356
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1357
-
1358
-			if (!$data instanceof ICacheEntry) {
1359
-				return false;
1360
-			}
1361
-
1362
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1363
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1364
-			}
1365
-			$ownerId = $storage->getOwner($internalPath);
1366
-			$owner = null;
1367
-			if ($ownerId !== null && $ownerId !== false) {
1368
-				// ownerId might be null if files are accessed with an access token without file system access
1369
-				$owner = $this->getUserObjectForOwner($ownerId);
1370
-			}
1371
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1372
-
1373
-			if (isset($data['fileid'])) {
1374
-				if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1375
-					//add the sizes of other mount points to the folder
1376
-					$extOnly = ($includeMountPoints === 'ext');
1377
-					$this->addSubMounts($info, $extOnly);
1378
-				}
1379
-			}
1380
-
1381
-			return $info;
1382
-		} else {
1383
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1384
-		}
1385
-
1386
-		return false;
1387
-	}
1388
-
1389
-	/**
1390
-	 * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1391
-	 */
1392
-	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1393
-		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1394
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1395
-			$subStorage = $mount->getStorage();
1396
-			return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1397
-		}));
1398
-	}
1399
-
1400
-	/**
1401
-	 * get the content of a directory
1402
-	 *
1403
-	 * @param string $directory path under datadirectory
1404
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1405
-	 * @return FileInfo[]
1406
-	 */
1407
-	public function getDirectoryContent($directory, $mimetype_filter = '', \OCP\Files\FileInfo $directoryInfo = null) {
1408
-		$this->assertPathLength($directory);
1409
-		if (!Filesystem::isValidPath($directory)) {
1410
-			return [];
1411
-		}
1412
-
1413
-		$path = $this->getAbsolutePath($directory);
1414
-		$path = Filesystem::normalizePath($path);
1415
-		$mount = $this->getMount($directory);
1416
-		$storage = $mount->getStorage();
1417
-		$internalPath = $mount->getInternalPath($path);
1418
-		if (!$storage) {
1419
-			return [];
1420
-		}
1421
-
1422
-		$cache = $storage->getCache($internalPath);
1423
-		$user = \OC_User::getUser();
1424
-
1425
-		if (!$directoryInfo) {
1426
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1427
-			if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1428
-				return [];
1429
-			}
1430
-		} else {
1431
-			$data = $directoryInfo;
1432
-		}
1433
-
1434
-		if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1435
-			return [];
1436
-		}
1437
-
1438
-		$folderId = $data->getId();
1439
-		$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1440
-
1441
-		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1442
-
1443
-		$fileNames = array_map(function (ICacheEntry $content) {
1444
-			return $content->getName();
1445
-		}, $contents);
1446
-		/**
1447
-		 * @var \OC\Files\FileInfo[] $fileInfos
1448
-		 */
1449
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1450
-			if ($sharingDisabled) {
1451
-				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1452
-			}
1453
-			$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1454
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1455
-		}, $contents);
1456
-		$files = array_combine($fileNames, $fileInfos);
1457
-
1458
-		//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1459
-		$mounts = Filesystem::getMountManager()->findIn($path);
1460
-		$dirLength = strlen($path);
1461
-		foreach ($mounts as $mount) {
1462
-			$mountPoint = $mount->getMountPoint();
1463
-			$subStorage = $mount->getStorage();
1464
-			if ($subStorage) {
1465
-				$subCache = $subStorage->getCache('');
1466
-
1467
-				$rootEntry = $subCache->get('');
1468
-				if (!$rootEntry) {
1469
-					$subScanner = $subStorage->getScanner();
1470
-					try {
1471
-						$subScanner->scanFile('');
1472
-					} catch (\OCP\Files\StorageNotAvailableException $e) {
1473
-						continue;
1474
-					} catch (\OCP\Files\StorageInvalidException $e) {
1475
-						continue;
1476
-					} catch (\Exception $e) {
1477
-						// sometimes when the storage is not available it can be any exception
1478
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1479
-							'exception' => $e,
1480
-							'app' => 'core',
1481
-						]);
1482
-						continue;
1483
-					}
1484
-					$rootEntry = $subCache->get('');
1485
-				}
1486
-
1487
-				if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1488
-					$relativePath = trim(substr($mountPoint, $dirLength), '/');
1489
-					if ($pos = strpos($relativePath, '/')) {
1490
-						//mountpoint inside subfolder add size to the correct folder
1491
-						$entryName = substr($relativePath, 0, $pos);
1492
-						if (isset($files[$entryName])) {
1493
-							$files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1494
-						}
1495
-					} else { //mountpoint in this folder, add an entry for it
1496
-						$rootEntry['name'] = $relativePath;
1497
-						$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1498
-						$permissions = $rootEntry['permissions'];
1499
-						// do not allow renaming/deleting the mount point if they are not shared files/folders
1500
-						// for shared files/folders we use the permissions given by the owner
1501
-						if ($mount instanceof MoveableMount) {
1502
-							$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1503
-						} else {
1504
-							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1505
-						}
1506
-
1507
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1508
-
1509
-						// if sharing was disabled for the user we remove the share permissions
1510
-						if (\OCP\Util::isSharingDisabledForUser()) {
1511
-							$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1512
-						}
1513
-
1514
-						$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1515
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1516
-					}
1517
-				}
1518
-			}
1519
-		}
1520
-
1521
-		if ($mimetype_filter) {
1522
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1523
-				if (strpos($mimetype_filter, '/')) {
1524
-					return $file->getMimetype() === $mimetype_filter;
1525
-				} else {
1526
-					return $file->getMimePart() === $mimetype_filter;
1527
-				}
1528
-			});
1529
-		}
1530
-
1531
-		return array_values($files);
1532
-	}
1533
-
1534
-	/**
1535
-	 * change file metadata
1536
-	 *
1537
-	 * @param string $path
1538
-	 * @param array|\OCP\Files\FileInfo $data
1539
-	 * @return int
1540
-	 *
1541
-	 * returns the fileid of the updated file
1542
-	 */
1543
-	public function putFileInfo($path, $data) {
1544
-		$this->assertPathLength($path);
1545
-		if ($data instanceof FileInfo) {
1546
-			$data = $data->getData();
1547
-		}
1548
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1549
-		/**
1550
-		 * @var Storage $storage
1551
-		 * @var string $internalPath
1552
-		 */
1553
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
1554
-		if ($storage) {
1555
-			$cache = $storage->getCache($path);
1556
-
1557
-			if (!$cache->inCache($internalPath)) {
1558
-				$scanner = $storage->getScanner($internalPath);
1559
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1560
-			}
1561
-
1562
-			return $cache->put($internalPath, $data);
1563
-		} else {
1564
-			return -1;
1565
-		}
1566
-	}
1567
-
1568
-	/**
1569
-	 * search for files with the name matching $query
1570
-	 *
1571
-	 * @param string $query
1572
-	 * @return FileInfo[]
1573
-	 */
1574
-	public function search($query) {
1575
-		return $this->searchCommon('search', ['%' . $query . '%']);
1576
-	}
1577
-
1578
-	/**
1579
-	 * search for files with the name matching $query
1580
-	 *
1581
-	 * @param string $query
1582
-	 * @return FileInfo[]
1583
-	 */
1584
-	public function searchRaw($query) {
1585
-		return $this->searchCommon('search', [$query]);
1586
-	}
1587
-
1588
-	/**
1589
-	 * search for files by mimetype
1590
-	 *
1591
-	 * @param string $mimetype
1592
-	 * @return FileInfo[]
1593
-	 */
1594
-	public function searchByMime($mimetype) {
1595
-		return $this->searchCommon('searchByMime', [$mimetype]);
1596
-	}
1597
-
1598
-	/**
1599
-	 * search for files by tag
1600
-	 *
1601
-	 * @param string|int $tag name or tag id
1602
-	 * @param string $userId owner of the tags
1603
-	 * @return FileInfo[]
1604
-	 */
1605
-	public function searchByTag($tag, $userId) {
1606
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1607
-	}
1608
-
1609
-	/**
1610
-	 * @param string $method cache method
1611
-	 * @param array $args
1612
-	 * @return FileInfo[]
1613
-	 */
1614
-	private function searchCommon($method, $args) {
1615
-		$files = [];
1616
-		$rootLength = strlen($this->fakeRoot);
1617
-
1618
-		$mount = $this->getMount('');
1619
-		$mountPoint = $mount->getMountPoint();
1620
-		$storage = $mount->getStorage();
1621
-		$userManager = \OC::$server->getUserManager();
1622
-		if ($storage) {
1623
-			$cache = $storage->getCache('');
1624
-
1625
-			$results = call_user_func_array([$cache, $method], $args);
1626
-			foreach ($results as $result) {
1627
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1628
-					$internalPath = $result['path'];
1629
-					$path = $mountPoint . $result['path'];
1630
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1631
-					$owner = $userManager->get($storage->getOwner($internalPath));
1632
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1633
-				}
1634
-			}
1635
-
1636
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1637
-			foreach ($mounts as $mount) {
1638
-				$mountPoint = $mount->getMountPoint();
1639
-				$storage = $mount->getStorage();
1640
-				if ($storage) {
1641
-					$cache = $storage->getCache('');
1642
-
1643
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1644
-					$results = call_user_func_array([$cache, $method], $args);
1645
-					if ($results) {
1646
-						foreach ($results as $result) {
1647
-							$internalPath = $result['path'];
1648
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1649
-							$path = rtrim($mountPoint . $internalPath, '/');
1650
-							$owner = $userManager->get($storage->getOwner($internalPath));
1651
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652
-						}
1653
-					}
1654
-				}
1655
-			}
1656
-		}
1657
-		return $files;
1658
-	}
1659
-
1660
-	/**
1661
-	 * Get the owner for a file or folder
1662
-	 *
1663
-	 * @param string $path
1664
-	 * @return string the user id of the owner
1665
-	 * @throws NotFoundException
1666
-	 */
1667
-	public function getOwner($path) {
1668
-		$info = $this->getFileInfo($path);
1669
-		if (!$info) {
1670
-			throw new NotFoundException($path . ' not found while trying to get owner');
1671
-		}
1672
-
1673
-		if ($info->getOwner() === null) {
1674
-			throw new NotFoundException($path . ' has no owner');
1675
-		}
1676
-
1677
-		return $info->getOwner()->getUID();
1678
-	}
1679
-
1680
-	/**
1681
-	 * get the ETag for a file or folder
1682
-	 *
1683
-	 * @param string $path
1684
-	 * @return string|false
1685
-	 */
1686
-	public function getETag($path) {
1687
-		[$storage, $internalPath] = $this->resolvePath($path);
1688
-		if ($storage) {
1689
-			return $storage->getETag($internalPath);
1690
-		} else {
1691
-			return false;
1692
-		}
1693
-	}
1694
-
1695
-	/**
1696
-	 * Get the path of a file by id, relative to the view
1697
-	 *
1698
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1699
-	 *
1700
-	 * @param int $id
1701
-	 * @param int|null $storageId
1702
-	 * @return string
1703
-	 * @throws NotFoundException
1704
-	 */
1705
-	public function getPath($id, int $storageId = null) {
1706
-		$id = (int)$id;
1707
-		$manager = Filesystem::getMountManager();
1708
-		$mounts = $manager->findIn($this->fakeRoot);
1709
-		$mounts[] = $manager->find($this->fakeRoot);
1710
-		$mounts = array_filter($mounts);
1711
-		// reverse the array, so we start with the storage this view is in
1712
-		// which is the most likely to contain the file we're looking for
1713
-		$mounts = array_reverse($mounts);
1714
-
1715
-		// put non-shared mounts in front of the shared mount
1716
-		// this prevents unneeded recursion into shares
1717
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1718
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1719
-		});
1720
-
1721
-		if (!is_null($storageId)) {
1722
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1723
-				return $mount->getNumericStorageId() === $storageId;
1724
-			});
1725
-		}
1726
-
1727
-		foreach ($mounts as $mount) {
1728
-			/**
1729
-			 * @var \OC\Files\Mount\MountPoint $mount
1730
-			 */
1731
-			if ($mount->getStorage()) {
1732
-				$cache = $mount->getStorage()->getCache();
1733
-				$internalPath = $cache->getPathById($id);
1734
-				if (is_string($internalPath)) {
1735
-					$fullPath = $mount->getMountPoint() . $internalPath;
1736
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1737
-						return $path;
1738
-					}
1739
-				}
1740
-			}
1741
-		}
1742
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1743
-	}
1744
-
1745
-	/**
1746
-	 * @param string $path
1747
-	 * @throws InvalidPathException
1748
-	 */
1749
-	private function assertPathLength($path): void {
1750
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1751
-		// Check for the string length - performed using isset() instead of strlen()
1752
-		// because isset() is about 5x-40x faster.
1753
-		if (isset($path[$maxLen])) {
1754
-			$pathLen = strlen($path);
1755
-			throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1756
-		}
1757
-	}
1758
-
1759
-	/**
1760
-	 * check if it is allowed to move a mount point to a given target.
1761
-	 * It is not allowed to move a mount point into a different mount point or
1762
-	 * into an already shared folder
1763
-	 */
1764
-	private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath): bool {
1765
-		// note: cannot use the view because the target is already locked
1766
-		$fileId = $targetStorage->getCache()->getId($targetInternalPath);
1767
-		if ($fileId === -1) {
1768
-			// target might not exist, need to check parent instead
1769
-			$fileId = $targetStorage->getCache()->getId(dirname($targetInternalPath));
1770
-		}
1771
-
1772
-		// check if any of the parents were shared by the current owner (include collections)
1773
-		$shares = Share::getItemShared(
1774
-			'folder',
1775
-			(string)$fileId,
1776
-			\OC\Share\Constants::FORMAT_NONE,
1777
-			null,
1778
-			true
1779
-		);
1780
-
1781
-		if (count($shares) > 0) {
1782
-			$this->logger->debug(
1783
-				'It is not allowed to move one mount point into a shared folder',
1784
-				['app' => 'files']);
1785
-			return false;
1786
-		}
1787
-
1788
-		return true;
1789
-	}
1790
-
1791
-	/**
1792
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1793
-	 */
1794
-	private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1795
-		$mount = $this->getMount($path);
1796
-		$storage = $mount->getStorage();
1797
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1798
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1799
-		return new FileInfo(
1800
-			$this->getAbsolutePath($path),
1801
-			$storage,
1802
-			$internalPath,
1803
-			[
1804
-				'fileid' => null,
1805
-				'mimetype' => $storage->getMimeType($internalPath),
1806
-				'name' => basename($path),
1807
-				'etag' => null,
1808
-				'size' => $storage->filesize($internalPath),
1809
-				'mtime' => $storage->filemtime($internalPath),
1810
-				'encrypted' => false,
1811
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1812
-			],
1813
-			$mount,
1814
-			$owner
1815
-		);
1816
-	}
1817
-
1818
-	/**
1819
-	 * @param string $path
1820
-	 * @param string $fileName
1821
-	 * @throws InvalidPathException
1822
-	 */
1823
-	public function verifyPath($path, $fileName): void {
1824
-		try {
1825
-			/** @type \OCP\Files\Storage $storage */
1826
-			[$storage, $internalPath] = $this->resolvePath($path);
1827
-			$storage->verifyPath($internalPath, $fileName);
1828
-		} catch (ReservedWordException $ex) {
1829
-			$l = \OC::$server->getL10N('lib');
1830
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1831
-		} catch (InvalidCharacterInPathException $ex) {
1832
-			$l = \OC::$server->getL10N('lib');
1833
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1834
-		} catch (FileNameTooLongException $ex) {
1835
-			$l = \OC::$server->getL10N('lib');
1836
-			throw new InvalidPathException($l->t('File name is too long'));
1837
-		} catch (InvalidDirectoryException $ex) {
1838
-			$l = \OC::$server->getL10N('lib');
1839
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1840
-		} catch (EmptyFileNameException $ex) {
1841
-			$l = \OC::$server->getL10N('lib');
1842
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1843
-		}
1844
-	}
1845
-
1846
-	/**
1847
-	 * get all parent folders of $path
1848
-	 *
1849
-	 * @param string $path
1850
-	 * @return string[]
1851
-	 */
1852
-	private function getParents($path) {
1853
-		$path = trim($path, '/');
1854
-		if (!$path) {
1855
-			return [];
1856
-		}
1857
-
1858
-		$parts = explode('/', $path);
1859
-
1860
-		// remove the single file
1861
-		array_pop($parts);
1862
-		$result = ['/'];
1863
-		$resultPath = '';
1864
-		foreach ($parts as $part) {
1865
-			if ($part) {
1866
-				$resultPath .= '/' . $part;
1867
-				$result[] = $resultPath;
1868
-			}
1869
-		}
1870
-		return $result;
1871
-	}
1872
-
1873
-	/**
1874
-	 * Returns the mount point for which to lock
1875
-	 *
1876
-	 * @param string $absolutePath absolute path
1877
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1878
-	 * is mounted directly on the given path, false otherwise
1879
-	 * @return IMountPoint mount point for which to apply locks
1880
-	 */
1881
-	private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
1882
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1883
-
1884
-		if ($useParentMount) {
1885
-			// find out if something is mounted directly on the path
1886
-			$internalPath = $mount->getInternalPath($absolutePath);
1887
-			if ($internalPath === '') {
1888
-				// resolve the parent mount instead
1889
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1890
-			}
1891
-		}
1892
-
1893
-		return $mount;
1894
-	}
1895
-
1896
-	/**
1897
-	 * Lock the given path
1898
-	 *
1899
-	 * @param string $path the path of the file to lock, relative to the view
1900
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1901
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1902
-	 *
1903
-	 * @return bool False if the path is excluded from locking, true otherwise
1904
-	 * @throws LockedException if the path is already locked
1905
-	 */
1906
-	private function lockPath($path, $type, $lockMountPoint = false) {
1907
-		$absolutePath = $this->getAbsolutePath($path);
1908
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1909
-		if (!$this->shouldLockFile($absolutePath)) {
1910
-			return false;
1911
-		}
1912
-
1913
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1914
-		try {
1915
-			$storage = $mount->getStorage();
1916
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1917
-				$storage->acquireLock(
1918
-					$mount->getInternalPath($absolutePath),
1919
-					$type,
1920
-					$this->lockingProvider
1921
-				);
1922
-			}
1923
-		} catch (LockedException $e) {
1924
-			// rethrow with the a human-readable path
1925
-			throw new LockedException(
1926
-				$this->getPathRelativeToFiles($absolutePath),
1927
-				$e,
1928
-				$e->getExistingLock()
1929
-			);
1930
-		}
1931
-
1932
-		return true;
1933
-	}
1934
-
1935
-	/**
1936
-	 * Change the lock type
1937
-	 *
1938
-	 * @param string $path the path of the file to lock, relative to the view
1939
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1940
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1941
-	 *
1942
-	 * @return bool False if the path is excluded from locking, true otherwise
1943
-	 * @throws LockedException if the path is already locked
1944
-	 */
1945
-	public function changeLock($path, $type, $lockMountPoint = false) {
1946
-		$path = Filesystem::normalizePath($path);
1947
-		$absolutePath = $this->getAbsolutePath($path);
1948
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1949
-		if (!$this->shouldLockFile($absolutePath)) {
1950
-			return false;
1951
-		}
1952
-
1953
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1954
-		try {
1955
-			$storage = $mount->getStorage();
1956
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1957
-				$storage->changeLock(
1958
-					$mount->getInternalPath($absolutePath),
1959
-					$type,
1960
-					$this->lockingProvider
1961
-				);
1962
-			}
1963
-		} catch (LockedException $e) {
1964
-			try {
1965
-				// rethrow with the a human-readable path
1966
-				throw new LockedException(
1967
-					$this->getPathRelativeToFiles($absolutePath),
1968
-					$e,
1969
-					$e->getExistingLock()
1970
-				);
1971
-			} catch (\InvalidArgumentException $ex) {
1972
-				throw new LockedException(
1973
-					$absolutePath,
1974
-					$ex,
1975
-					$e->getExistingLock()
1976
-				);
1977
-			}
1978
-		}
1979
-
1980
-		return true;
1981
-	}
1982
-
1983
-	/**
1984
-	 * Unlock the given path
1985
-	 *
1986
-	 * @param string $path the path of the file to unlock, relative to the view
1987
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1988
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1989
-	 *
1990
-	 * @return bool False if the path is excluded from locking, true otherwise
1991
-	 * @throws LockedException
1992
-	 */
1993
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1994
-		$absolutePath = $this->getAbsolutePath($path);
1995
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1996
-		if (!$this->shouldLockFile($absolutePath)) {
1997
-			return false;
1998
-		}
1999
-
2000
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2001
-		$storage = $mount->getStorage();
2002
-		if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2003
-			$storage->releaseLock(
2004
-				$mount->getInternalPath($absolutePath),
2005
-				$type,
2006
-				$this->lockingProvider
2007
-			);
2008
-		}
2009
-
2010
-		return true;
2011
-	}
2012
-
2013
-	/**
2014
-	 * Lock a path and all its parents up to the root of the view
2015
-	 *
2016
-	 * @param string $path the path of the file to lock relative to the view
2017
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2018
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2019
-	 *
2020
-	 * @return bool False if the path is excluded from locking, true otherwise
2021
-	 * @throws LockedException
2022
-	 */
2023
-	public function lockFile($path, $type, $lockMountPoint = false) {
2024
-		$absolutePath = $this->getAbsolutePath($path);
2025
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2026
-		if (!$this->shouldLockFile($absolutePath)) {
2027
-			return false;
2028
-		}
2029
-
2030
-		$this->lockPath($path, $type, $lockMountPoint);
2031
-
2032
-		$parents = $this->getParents($path);
2033
-		foreach ($parents as $parent) {
2034
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2035
-		}
2036
-
2037
-		return true;
2038
-	}
2039
-
2040
-	/**
2041
-	 * Unlock a path and all its parents up to the root of the view
2042
-	 *
2043
-	 * @param string $path the path of the file to lock relative to the view
2044
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2045
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2046
-	 *
2047
-	 * @return bool False if the path is excluded from locking, true otherwise
2048
-	 * @throws LockedException
2049
-	 */
2050
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2051
-		$absolutePath = $this->getAbsolutePath($path);
2052
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2053
-		if (!$this->shouldLockFile($absolutePath)) {
2054
-			return false;
2055
-		}
2056
-
2057
-		$this->unlockPath($path, $type, $lockMountPoint);
2058
-
2059
-		$parents = $this->getParents($path);
2060
-		foreach ($parents as $parent) {
2061
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2062
-		}
2063
-
2064
-		return true;
2065
-	}
2066
-
2067
-	/**
2068
-	 * Only lock files in data/user/files/
2069
-	 *
2070
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2071
-	 * @return bool
2072
-	 */
2073
-	protected function shouldLockFile($path) {
2074
-		$path = Filesystem::normalizePath($path);
2075
-
2076
-		$pathSegments = explode('/', $path);
2077
-		if (isset($pathSegments[2])) {
2078
-			// E.g.: /username/files/path-to-file
2079
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2080
-		}
2081
-
2082
-		return strpos($path, '/appdata_') !== 0;
2083
-	}
2084
-
2085
-	/**
2086
-	 * Shortens the given absolute path to be relative to
2087
-	 * "$user/files".
2088
-	 *
2089
-	 * @param string $absolutePath absolute path which is under "files"
2090
-	 *
2091
-	 * @return string path relative to "files" with trimmed slashes or null
2092
-	 * if the path was NOT relative to files
2093
-	 *
2094
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2095
-	 * @since 8.1.0
2096
-	 */
2097
-	public function getPathRelativeToFiles($absolutePath) {
2098
-		$path = Filesystem::normalizePath($absolutePath);
2099
-		$parts = explode('/', trim($path, '/'), 3);
2100
-		// "$user", "files", "path/to/dir"
2101
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2102
-			$this->logger->error(
2103
-				'$absolutePath must be relative to "files", value is "{absolutePath}"',
2104
-				[
2105
-					'absolutePath' => $absolutePath,
2106
-				]
2107
-			);
2108
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2109
-		}
2110
-		if (isset($parts[2])) {
2111
-			return $parts[2];
2112
-		}
2113
-		return '';
2114
-	}
2115
-
2116
-	/**
2117
-	 * @param string $filename
2118
-	 * @return array
2119
-	 * @throws \OC\User\NoUserException
2120
-	 * @throws NotFoundException
2121
-	 */
2122
-	public function getUidAndFilename($filename) {
2123
-		$info = $this->getFileInfo($filename);
2124
-		if (!$info instanceof \OCP\Files\FileInfo) {
2125
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2126
-		}
2127
-		$uid = $info->getOwner()->getUID();
2128
-		if ($uid != \OC_User::getUser()) {
2129
-			Filesystem::initMountPoints($uid);
2130
-			$ownerView = new View('/' . $uid . '/files');
2131
-			try {
2132
-				$filename = $ownerView->getPath($info['fileid']);
2133
-			} catch (NotFoundException $e) {
2134
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2135
-			}
2136
-		}
2137
-		return [$uid, $filename];
2138
-	}
2139
-
2140
-	/**
2141
-	 * Creates parent non-existing folders
2142
-	 *
2143
-	 * @param string $filePath
2144
-	 * @return bool
2145
-	 */
2146
-	private function createParentDirectories($filePath) {
2147
-		$directoryParts = explode('/', $filePath);
2148
-		$directoryParts = array_filter($directoryParts);
2149
-		foreach ($directoryParts as $key => $part) {
2150
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2151
-			$currentPath = '/' . implode('/', $currentPathElements);
2152
-			if ($this->is_file($currentPath)) {
2153
-				return false;
2154
-			}
2155
-			if (!$this->file_exists($currentPath)) {
2156
-				$this->mkdir($currentPath);
2157
-			}
2158
-		}
2159
-
2160
-		return true;
2161
-	}
90
+    private string $fakeRoot = '';
91
+    private ILockingProvider $lockingProvider;
92
+    private bool $lockingEnabled;
93
+    private bool $updaterEnabled = true;
94
+    private UserManager $userManager;
95
+    private LoggerInterface $logger;
96
+
97
+    /**
98
+     * @throws \Exception If $root contains an invalid path
99
+     */
100
+    public function __construct(string $root = '') {
101
+        if (!Filesystem::isValidPath($root)) {
102
+            throw new \Exception();
103
+        }
104
+
105
+        $this->fakeRoot = $root;
106
+        $this->lockingProvider = \OC::$server->getLockingProvider();
107
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
108
+        $this->userManager = \OC::$server->getUserManager();
109
+        $this->logger = \OC::$server->get(LoggerInterface::class);
110
+    }
111
+
112
+    /**
113
+     * @param ?string $path
114
+     * @psalm-template S as string|null
115
+     * @psalm-param S $path
116
+     * @psalm-return (S is string ? string : null)
117
+     */
118
+    public function getAbsolutePath($path = '/'): ?string {
119
+        if ($path === null) {
120
+            return null;
121
+        }
122
+        $this->assertPathLength($path);
123
+        if ($path === '') {
124
+            $path = '/';
125
+        }
126
+        if ($path[0] !== '/') {
127
+            $path = '/' . $path;
128
+        }
129
+        return $this->fakeRoot . $path;
130
+    }
131
+
132
+    /**
133
+     * Change the root to a fake root
134
+     *
135
+     * @param string $fakeRoot
136
+     */
137
+    public function chroot($fakeRoot): void {
138
+        if (!$fakeRoot == '') {
139
+            if ($fakeRoot[0] !== '/') {
140
+                $fakeRoot = '/' . $fakeRoot;
141
+            }
142
+        }
143
+        $this->fakeRoot = $fakeRoot;
144
+    }
145
+
146
+    /**
147
+     * Get the fake root
148
+     */
149
+    public function getRoot(): string {
150
+        return $this->fakeRoot;
151
+    }
152
+
153
+    /**
154
+     * get path relative to the root of the view
155
+     *
156
+     * @param string $path
157
+     */
158
+    public function getRelativePath($path): ?string {
159
+        $this->assertPathLength($path);
160
+        if ($this->fakeRoot == '') {
161
+            return $path;
162
+        }
163
+
164
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
165
+            return '/';
166
+        }
167
+
168
+        // missing slashes can cause wrong matches!
169
+        $root = rtrim($this->fakeRoot, '/') . '/';
170
+
171
+        if (strpos($path, $root) !== 0) {
172
+            return null;
173
+        } else {
174
+            $path = substr($path, strlen($this->fakeRoot));
175
+            if (strlen($path) === 0) {
176
+                return '/';
177
+            } else {
178
+                return $path;
179
+            }
180
+        }
181
+    }
182
+
183
+    /**
184
+     * Get the mountpoint of the storage object for a path
185
+     * ( note: because a storage is not always mounted inside the fakeroot, the
186
+     * returned mountpoint is relative to the absolute root of the filesystem
187
+     * and does not take the chroot into account )
188
+     *
189
+     * @param string $path
190
+     */
191
+    public function getMountPoint($path): string {
192
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
193
+    }
194
+
195
+    /**
196
+     * Get the mountpoint of the storage object for a path
197
+     * ( note: because a storage is not always mounted inside the fakeroot, the
198
+     * returned mountpoint is relative to the absolute root of the filesystem
199
+     * and does not take the chroot into account )
200
+     *
201
+     * @param string $path
202
+     */
203
+    public function getMount($path): IMountPoint {
204
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
205
+    }
206
+
207
+    /**
208
+     * Resolve a path to a storage and internal path
209
+     *
210
+     * @param string $path
211
+     * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
212
+     */
213
+    public function resolvePath($path): array {
214
+        $a = $this->getAbsolutePath($path);
215
+        $p = Filesystem::normalizePath($a);
216
+        return Filesystem::resolvePath($p);
217
+    }
218
+
219
+    /**
220
+     * Return the path to a local version of the file
221
+     * we need this because we can't know if a file is stored local or not from
222
+     * outside the filestorage and for some purposes a local file is needed
223
+     *
224
+     * @param string $path
225
+     */
226
+    public function getLocalFile($path): string|false {
227
+        $parent = substr($path, 0, strrpos($path, '/') ?: 0);
228
+        $path = $this->getAbsolutePath($path);
229
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
230
+        if (Filesystem::isValidPath($parent) && $storage) {
231
+            return $storage->getLocalFile($internalPath);
232
+        } else {
233
+            return false;
234
+        }
235
+    }
236
+
237
+    /**
238
+     * the following functions operate with arguments and return values identical
239
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
240
+     * for \OC\Files\Storage\Storage via basicOperation().
241
+     */
242
+    public function mkdir($path) {
243
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
244
+    }
245
+
246
+    /**
247
+     * remove mount point
248
+     *
249
+     * @param IMountPoint $mount
250
+     * @param string $path relative to data/
251
+     */
252
+    protected function removeMount($mount, $path): bool {
253
+        if ($mount instanceof MoveableMount) {
254
+            // cut of /user/files to get the relative path to data/user/files
255
+            $pathParts = explode('/', $path, 4);
256
+            $relPath = '/' . $pathParts[3];
257
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
258
+            \OC_Hook::emit(
259
+                Filesystem::CLASSNAME, "umount",
260
+                [Filesystem::signal_param_path => $relPath]
261
+            );
262
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
263
+            $result = $mount->removeMount();
264
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
265
+            if ($result) {
266
+                \OC_Hook::emit(
267
+                    Filesystem::CLASSNAME, "post_umount",
268
+                    [Filesystem::signal_param_path => $relPath]
269
+                );
270
+            }
271
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
272
+            return $result;
273
+        } else {
274
+            // do not allow deleting the storage's root / the mount point
275
+            // because for some storages it might delete the whole contents
276
+            // but isn't supposed to work that way
277
+            return false;
278
+        }
279
+    }
280
+
281
+    public function disableCacheUpdate(): void {
282
+        $this->updaterEnabled = false;
283
+    }
284
+
285
+    public function enableCacheUpdate(): void {
286
+        $this->updaterEnabled = true;
287
+    }
288
+
289
+    protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null): void {
290
+        if ($this->updaterEnabled) {
291
+            if (is_null($time)) {
292
+                $time = time();
293
+            }
294
+            $storage->getUpdater()->update($internalPath, $time);
295
+        }
296
+    }
297
+
298
+    protected function removeUpdate(Storage $storage, string $internalPath): void {
299
+        if ($this->updaterEnabled) {
300
+            $storage->getUpdater()->remove($internalPath);
301
+        }
302
+    }
303
+
304
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
305
+        if ($this->updaterEnabled) {
306
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
307
+        }
308
+    }
309
+
310
+    /**
311
+     * @param string $path
312
+     * @return bool|mixed
313
+     */
314
+    public function rmdir($path) {
315
+        $absolutePath = $this->getAbsolutePath($path);
316
+        $mount = Filesystem::getMountManager()->find($absolutePath);
317
+        if ($mount->getInternalPath($absolutePath) === '') {
318
+            return $this->removeMount($mount, $absolutePath);
319
+        }
320
+        if ($this->is_dir($path)) {
321
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
322
+        } else {
323
+            $result = false;
324
+        }
325
+
326
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
327
+            $storage = $mount->getStorage();
328
+            $internalPath = $mount->getInternalPath($absolutePath);
329
+            $storage->getUpdater()->remove($internalPath);
330
+        }
331
+        return $result;
332
+    }
333
+
334
+    /**
335
+     * @param string $path
336
+     * @return resource|false
337
+     */
338
+    public function opendir($path) {
339
+        return $this->basicOperation('opendir', $path, ['read']);
340
+    }
341
+
342
+    /**
343
+     * @param string $path
344
+     * @return bool|mixed
345
+     */
346
+    public function is_dir($path) {
347
+        if ($path == '/') {
348
+            return true;
349
+        }
350
+        return $this->basicOperation('is_dir', $path);
351
+    }
352
+
353
+    /**
354
+     * @param string $path
355
+     * @return bool|mixed
356
+     */
357
+    public function is_file($path) {
358
+        if ($path == '/') {
359
+            return false;
360
+        }
361
+        return $this->basicOperation('is_file', $path);
362
+    }
363
+
364
+    /**
365
+     * @param string $path
366
+     * @return mixed
367
+     */
368
+    public function stat($path) {
369
+        return $this->basicOperation('stat', $path);
370
+    }
371
+
372
+    /**
373
+     * @param string $path
374
+     * @return mixed
375
+     */
376
+    public function filetype($path) {
377
+        return $this->basicOperation('filetype', $path);
378
+    }
379
+
380
+    /**
381
+     * @param string $path
382
+     * @return mixed
383
+     */
384
+    public function filesize(string $path) {
385
+        return $this->basicOperation('filesize', $path);
386
+    }
387
+
388
+    /**
389
+     * @param string $path
390
+     * @return bool|mixed
391
+     * @throws InvalidPathException
392
+     */
393
+    public function readfile($path) {
394
+        $this->assertPathLength($path);
395
+        if (ob_get_level()) {
396
+            ob_end_clean();
397
+        }
398
+        $handle = $this->fopen($path, 'rb');
399
+        if ($handle) {
400
+            $chunkSize = 524288; // 512 kB chunks
401
+            while (!feof($handle)) {
402
+                echo fread($handle, $chunkSize);
403
+                flush();
404
+            }
405
+            fclose($handle);
406
+            return $this->filesize($path);
407
+        }
408
+        return false;
409
+    }
410
+
411
+    /**
412
+     * @param string $path
413
+     * @param int $from
414
+     * @param int $to
415
+     * @return bool|mixed
416
+     * @throws InvalidPathException
417
+     * @throws \OCP\Files\UnseekableException
418
+     */
419
+    public function readfilePart($path, $from, $to) {
420
+        $this->assertPathLength($path);
421
+        if (ob_get_level()) {
422
+            ob_end_clean();
423
+        }
424
+        $handle = $this->fopen($path, 'rb');
425
+        if ($handle) {
426
+            $chunkSize = 524288; // 512 kB chunks
427
+            $startReading = true;
428
+
429
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
430
+                // forward file handle via chunked fread because fseek seem to have failed
431
+
432
+                $end = $from + 1;
433
+                while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
434
+                    $len = $from - ftell($handle);
435
+                    if ($len > $chunkSize) {
436
+                        $len = $chunkSize;
437
+                    }
438
+                    $result = fread($handle, $len);
439
+
440
+                    if ($result === false) {
441
+                        $startReading = false;
442
+                        break;
443
+                    }
444
+                }
445
+            }
446
+
447
+            if ($startReading) {
448
+                $end = $to + 1;
449
+                while (!feof($handle) && ftell($handle) < $end) {
450
+                    $len = $end - ftell($handle);
451
+                    if ($len > $chunkSize) {
452
+                        $len = $chunkSize;
453
+                    }
454
+                    echo fread($handle, $len);
455
+                    flush();
456
+                }
457
+                return ftell($handle) - $from;
458
+            }
459
+
460
+            throw new \OCP\Files\UnseekableException('fseek error');
461
+        }
462
+        return false;
463
+    }
464
+
465
+    /**
466
+     * @param string $path
467
+     * @return mixed
468
+     */
469
+    public function isCreatable($path) {
470
+        return $this->basicOperation('isCreatable', $path);
471
+    }
472
+
473
+    /**
474
+     * @param string $path
475
+     * @return mixed
476
+     */
477
+    public function isReadable($path) {
478
+        return $this->basicOperation('isReadable', $path);
479
+    }
480
+
481
+    /**
482
+     * @param string $path
483
+     * @return mixed
484
+     */
485
+    public function isUpdatable($path) {
486
+        return $this->basicOperation('isUpdatable', $path);
487
+    }
488
+
489
+    /**
490
+     * @param string $path
491
+     * @return bool|mixed
492
+     */
493
+    public function isDeletable($path) {
494
+        $absolutePath = $this->getAbsolutePath($path);
495
+        $mount = Filesystem::getMountManager()->find($absolutePath);
496
+        if ($mount->getInternalPath($absolutePath) === '') {
497
+            return $mount instanceof MoveableMount;
498
+        }
499
+        return $this->basicOperation('isDeletable', $path);
500
+    }
501
+
502
+    /**
503
+     * @param string $path
504
+     * @return mixed
505
+     */
506
+    public function isSharable($path) {
507
+        return $this->basicOperation('isSharable', $path);
508
+    }
509
+
510
+    /**
511
+     * @param string $path
512
+     * @return bool|mixed
513
+     */
514
+    public function file_exists($path) {
515
+        if ($path == '/') {
516
+            return true;
517
+        }
518
+        return $this->basicOperation('file_exists', $path);
519
+    }
520
+
521
+    /**
522
+     * @param string $path
523
+     * @return mixed
524
+     */
525
+    public function filemtime($path) {
526
+        return $this->basicOperation('filemtime', $path);
527
+    }
528
+
529
+    /**
530
+     * @param string $path
531
+     * @param int|string $mtime
532
+     */
533
+    public function touch($path, $mtime = null): bool {
534
+        if (!is_null($mtime) && !is_numeric($mtime)) {
535
+            $mtime = strtotime($mtime);
536
+        }
537
+
538
+        $hooks = ['touch'];
539
+
540
+        if (!$this->file_exists($path)) {
541
+            $hooks[] = 'create';
542
+            $hooks[] = 'write';
543
+        }
544
+        try {
545
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
546
+        } catch (\Exception $e) {
547
+            $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
548
+            $result = false;
549
+        }
550
+        if (!$result) {
551
+            // If create file fails because of permissions on external storage like SMB folders,
552
+            // check file exists and return false if not.
553
+            if (!$this->file_exists($path)) {
554
+                return false;
555
+            }
556
+            if (is_null($mtime)) {
557
+                $mtime = time();
558
+            }
559
+            //if native touch fails, we emulate it by changing the mtime in the cache
560
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
561
+        }
562
+        return true;
563
+    }
564
+
565
+    /**
566
+     * @param string $path
567
+     * @return string|false
568
+     * @throws LockedException
569
+     */
570
+    public function file_get_contents($path) {
571
+        return $this->basicOperation('file_get_contents', $path, ['read']);
572
+    }
573
+
574
+    protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
575
+        if (!$exists) {
576
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
577
+                Filesystem::signal_param_path => $this->getHookPath($path),
578
+                Filesystem::signal_param_run => &$run,
579
+            ]);
580
+        } else {
581
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
582
+                Filesystem::signal_param_path => $this->getHookPath($path),
583
+                Filesystem::signal_param_run => &$run,
584
+            ]);
585
+        }
586
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
587
+            Filesystem::signal_param_path => $this->getHookPath($path),
588
+            Filesystem::signal_param_run => &$run,
589
+        ]);
590
+    }
591
+
592
+    protected function emit_file_hooks_post(bool $exists, string $path): void {
593
+        if (!$exists) {
594
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
595
+                Filesystem::signal_param_path => $this->getHookPath($path),
596
+            ]);
597
+        } else {
598
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
599
+                Filesystem::signal_param_path => $this->getHookPath($path),
600
+            ]);
601
+        }
602
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
603
+            Filesystem::signal_param_path => $this->getHookPath($path),
604
+        ]);
605
+    }
606
+
607
+    /**
608
+     * @param string $path
609
+     * @param string|resource $data
610
+     * @return bool|mixed
611
+     * @throws LockedException
612
+     */
613
+    public function file_put_contents($path, $data) {
614
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
615
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
616
+            if (Filesystem::isValidPath($path)
617
+                && !Filesystem::isFileBlacklisted($path)
618
+            ) {
619
+                $path = $this->getRelativePath($absolutePath);
620
+                if ($path === null) {
621
+                    throw new InvalidPathException("Path $absolutePath is not in the expected root");
622
+                }
623
+
624
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
625
+
626
+                $exists = $this->file_exists($path);
627
+                $run = true;
628
+                if ($this->shouldEmitHooks($path)) {
629
+                    $this->emit_file_hooks_pre($exists, $path, $run);
630
+                }
631
+                if (!$run) {
632
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
633
+                    return false;
634
+                }
635
+
636
+                try {
637
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
638
+                } catch (\Exception $e) {
639
+                    // Release the shared lock before throwing.
640
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
641
+                    throw $e;
642
+                }
643
+
644
+                /** @var Storage $storage */
645
+                [$storage, $internalPath] = $this->resolvePath($path);
646
+                $target = $storage->fopen($internalPath, 'w');
647
+                if ($target) {
648
+                    [, $result] = \OC_Helper::streamCopy($data, $target);
649
+                    fclose($target);
650
+                    fclose($data);
651
+
652
+                    $this->writeUpdate($storage, $internalPath);
653
+
654
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
655
+
656
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
657
+                        $this->emit_file_hooks_post($exists, $path);
658
+                    }
659
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
660
+                    return $result;
661
+                } else {
662
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
663
+                    return false;
664
+                }
665
+            } else {
666
+                return false;
667
+            }
668
+        } else {
669
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
670
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
671
+        }
672
+    }
673
+
674
+    /**
675
+     * @param string $path
676
+     * @return bool|mixed
677
+     */
678
+    public function unlink($path) {
679
+        if ($path === '' || $path === '/') {
680
+            // do not allow deleting the root
681
+            return false;
682
+        }
683
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
684
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
686
+        if ($mount->getInternalPath($absolutePath) === '') {
687
+            return $this->removeMount($mount, $absolutePath);
688
+        }
689
+        if ($this->is_dir($path)) {
690
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
691
+        } else {
692
+            $result = $this->basicOperation('unlink', $path, ['delete']);
693
+        }
694
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
695
+            $storage = $mount->getStorage();
696
+            $internalPath = $mount->getInternalPath($absolutePath);
697
+            $storage->getUpdater()->remove($internalPath);
698
+            return true;
699
+        } else {
700
+            return $result;
701
+        }
702
+    }
703
+
704
+    /**
705
+     * @param string $directory
706
+     * @return bool|mixed
707
+     */
708
+    public function deleteAll($directory) {
709
+        return $this->rmdir($directory);
710
+    }
711
+
712
+    /**
713
+     * Rename/move a file or folder from the source path to target path.
714
+     *
715
+     * @param string $source source path
716
+     * @param string $target target path
717
+     *
718
+     * @return bool|mixed
719
+     * @throws LockedException
720
+     */
721
+    public function rename($source, $target) {
722
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
723
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
724
+        $result = false;
725
+        if (
726
+            Filesystem::isValidPath($target)
727
+            && Filesystem::isValidPath($source)
728
+            && !Filesystem::isFileBlacklisted($target)
729
+        ) {
730
+            $source = $this->getRelativePath($absolutePath1);
731
+            $target = $this->getRelativePath($absolutePath2);
732
+            $exists = $this->file_exists($target);
733
+
734
+            if ($source == null || $target == null) {
735
+                return false;
736
+            }
737
+
738
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
739
+            try {
740
+                $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
741
+
742
+                $run = true;
743
+                if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
744
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
745
+                    $this->emit_file_hooks_pre($exists, $target, $run);
746
+                } elseif ($this->shouldEmitHooks($source)) {
747
+                    \OC_Hook::emit(
748
+                        Filesystem::CLASSNAME, Filesystem::signal_rename,
749
+                        [
750
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
751
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
752
+                            Filesystem::signal_param_run => &$run
753
+                        ]
754
+                    );
755
+                }
756
+                if ($run) {
757
+                    $this->verifyPath(dirname($target), basename($target));
758
+
759
+                    $manager = Filesystem::getMountManager();
760
+                    $mount1 = $this->getMount($source);
761
+                    $mount2 = $this->getMount($target);
762
+                    $storage1 = $mount1->getStorage();
763
+                    $storage2 = $mount2->getStorage();
764
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
765
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
766
+
767
+                    $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
768
+                    try {
769
+                        $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
770
+
771
+                        if ($internalPath1 === '') {
772
+                            if ($mount1 instanceof MoveableMount) {
773
+                                $sourceParentMount = $this->getMount(dirname($source));
774
+                                if ($sourceParentMount === $mount2 && $this->targetIsNotShared($storage2, $internalPath2)) {
775
+                                    /**
776
+                                     * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
777
+                                     */
778
+                                    $sourceMountPoint = $mount1->getMountPoint();
779
+                                    $result = $mount1->moveMount($absolutePath2);
780
+                                    $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
781
+                                } else {
782
+                                    $result = false;
783
+                                }
784
+                            } else {
785
+                                $result = false;
786
+                            }
787
+                        // moving a file/folder within the same mount point
788
+                        } elseif ($storage1 === $storage2) {
789
+                            if ($storage1) {
790
+                                $result = $storage1->rename($internalPath1, $internalPath2);
791
+                            } else {
792
+                                $result = false;
793
+                            }
794
+                        // moving a file/folder between storages (from $storage1 to $storage2)
795
+                        } else {
796
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
797
+                        }
798
+
799
+                        if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
800
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
801
+                            $this->writeUpdate($storage2, $internalPath2);
802
+                        } elseif ($result) {
803
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
804
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
805
+                            }
806
+                        }
807
+                    } catch (\Exception $e) {
808
+                        throw $e;
809
+                    } finally {
810
+                        $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
811
+                        $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
812
+                    }
813
+
814
+                    if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
815
+                        if ($this->shouldEmitHooks()) {
816
+                            $this->emit_file_hooks_post($exists, $target);
817
+                        }
818
+                    } elseif ($result) {
819
+                        if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
820
+                            \OC_Hook::emit(
821
+                                Filesystem::CLASSNAME,
822
+                                Filesystem::signal_post_rename,
823
+                                [
824
+                                    Filesystem::signal_param_oldpath => $this->getHookPath($source),
825
+                                    Filesystem::signal_param_newpath => $this->getHookPath($target)
826
+                                ]
827
+                            );
828
+                        }
829
+                    }
830
+                }
831
+            } catch (\Exception $e) {
832
+                throw $e;
833
+            } finally {
834
+                $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
835
+                $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
836
+            }
837
+        }
838
+        return $result;
839
+    }
840
+
841
+    /**
842
+     * Copy a file/folder from the source path to target path
843
+     *
844
+     * @param string $source source path
845
+     * @param string $target target path
846
+     * @param bool $preserveMtime whether to preserve mtime on the copy
847
+     *
848
+     * @return bool|mixed
849
+     */
850
+    public function copy($source, $target, $preserveMtime = false) {
851
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
852
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
853
+        $result = false;
854
+        if (
855
+            Filesystem::isValidPath($target)
856
+            && Filesystem::isValidPath($source)
857
+            && !Filesystem::isFileBlacklisted($target)
858
+        ) {
859
+            $source = $this->getRelativePath($absolutePath1);
860
+            $target = $this->getRelativePath($absolutePath2);
861
+
862
+            if ($source == null || $target == null) {
863
+                return false;
864
+            }
865
+            $run = true;
866
+
867
+            $this->lockFile($target, ILockingProvider::LOCK_SHARED);
868
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED);
869
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
870
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
871
+
872
+            try {
873
+                $exists = $this->file_exists($target);
874
+                if ($this->shouldEmitHooks()) {
875
+                    \OC_Hook::emit(
876
+                        Filesystem::CLASSNAME,
877
+                        Filesystem::signal_copy,
878
+                        [
879
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
880
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
881
+                            Filesystem::signal_param_run => &$run
882
+                        ]
883
+                    );
884
+                    $this->emit_file_hooks_pre($exists, $target, $run);
885
+                }
886
+                if ($run) {
887
+                    $mount1 = $this->getMount($source);
888
+                    $mount2 = $this->getMount($target);
889
+                    $storage1 = $mount1->getStorage();
890
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
891
+                    $storage2 = $mount2->getStorage();
892
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
893
+
894
+                    $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
895
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
896
+
897
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
898
+                        if ($storage1) {
899
+                            $result = $storage1->copy($internalPath1, $internalPath2);
900
+                        } else {
901
+                            $result = false;
902
+                        }
903
+                    } else {
904
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
905
+                    }
906
+
907
+                    $this->writeUpdate($storage2, $internalPath2);
908
+
909
+                    $this->changeLock($target, ILockingProvider::LOCK_SHARED);
910
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
911
+
912
+                    if ($this->shouldEmitHooks() && $result !== false) {
913
+                        \OC_Hook::emit(
914
+                            Filesystem::CLASSNAME,
915
+                            Filesystem::signal_post_copy,
916
+                            [
917
+                                Filesystem::signal_param_oldpath => $this->getHookPath($source),
918
+                                Filesystem::signal_param_newpath => $this->getHookPath($target)
919
+                            ]
920
+                        );
921
+                        $this->emit_file_hooks_post($exists, $target);
922
+                    }
923
+                }
924
+            } catch (\Exception $e) {
925
+                $this->unlockFile($target, $lockTypePath2);
926
+                $this->unlockFile($source, $lockTypePath1);
927
+                throw $e;
928
+            }
929
+
930
+            $this->unlockFile($target, $lockTypePath2);
931
+            $this->unlockFile($source, $lockTypePath1);
932
+        }
933
+        return $result;
934
+    }
935
+
936
+    /**
937
+     * @param string $path
938
+     * @param string $mode 'r' or 'w'
939
+     * @return resource|false
940
+     * @throws LockedException
941
+     */
942
+    public function fopen($path, $mode) {
943
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
944
+        $hooks = [];
945
+        switch ($mode) {
946
+            case 'r':
947
+                $hooks[] = 'read';
948
+                break;
949
+            case 'r+':
950
+            case 'w+':
951
+            case 'x+':
952
+            case 'a+':
953
+                $hooks[] = 'read';
954
+                $hooks[] = 'write';
955
+                break;
956
+            case 'w':
957
+            case 'x':
958
+            case 'a':
959
+                $hooks[] = 'write';
960
+                break;
961
+            default:
962
+                $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
963
+        }
964
+
965
+        if ($mode !== 'r' && $mode !== 'w') {
966
+            $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']);
967
+        }
968
+
969
+        $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
970
+        if (!is_resource($handle) && $mode === 'r') {
971
+            // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
972
+            $mount = $this->getMount($path);
973
+            $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
974
+            $storage = $mount->getStorage();
975
+            if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
976
+                $this->writeUpdate($storage, $internalPath);
977
+            }
978
+        }
979
+        return $handle;
980
+    }
981
+
982
+    /**
983
+     * @param string $path
984
+     * @throws InvalidPathException
985
+     */
986
+    public function toTmpFile($path): string|false {
987
+        $this->assertPathLength($path);
988
+        if (Filesystem::isValidPath($path)) {
989
+            $source = $this->fopen($path, 'r');
990
+            if ($source) {
991
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
992
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
993
+                file_put_contents($tmpFile, $source);
994
+                return $tmpFile;
995
+            } else {
996
+                return false;
997
+            }
998
+        } else {
999
+            return false;
1000
+        }
1001
+    }
1002
+
1003
+    /**
1004
+     * @param string $tmpFile
1005
+     * @param string $path
1006
+     * @return bool|mixed
1007
+     * @throws InvalidPathException
1008
+     */
1009
+    public function fromTmpFile($tmpFile, $path) {
1010
+        $this->assertPathLength($path);
1011
+        if (Filesystem::isValidPath($path)) {
1012
+            // Get directory that the file is going into
1013
+            $filePath = dirname($path);
1014
+
1015
+            // Create the directories if any
1016
+            if (!$this->file_exists($filePath)) {
1017
+                $result = $this->createParentDirectories($filePath);
1018
+                if ($result === false) {
1019
+                    return false;
1020
+                }
1021
+            }
1022
+
1023
+            $source = fopen($tmpFile, 'r');
1024
+            if ($source) {
1025
+                $result = $this->file_put_contents($path, $source);
1026
+                /**
1027
+                 * $this->file_put_contents() might have already closed
1028
+                 * the resource, so we check it, before trying to close it
1029
+                 * to avoid messages in the error log.
1030
+                 * @psalm-suppress RedundantCondition false-positive
1031
+                 */
1032
+                if (is_resource($source)) {
1033
+                    fclose($source);
1034
+                }
1035
+                unlink($tmpFile);
1036
+                return $result;
1037
+            } else {
1038
+                return false;
1039
+            }
1040
+        } else {
1041
+            return false;
1042
+        }
1043
+    }
1044
+
1045
+
1046
+    /**
1047
+     * @param string $path
1048
+     * @return mixed
1049
+     * @throws InvalidPathException
1050
+     */
1051
+    public function getMimeType($path) {
1052
+        $this->assertPathLength($path);
1053
+        return $this->basicOperation('getMimeType', $path);
1054
+    }
1055
+
1056
+    /**
1057
+     * @param string $type
1058
+     * @param string $path
1059
+     * @param bool $raw
1060
+     */
1061
+    public function hash($type, $path, $raw = false): string|bool {
1062
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1063
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1064
+        if (Filesystem::isValidPath($path)) {
1065
+            $path = $this->getRelativePath($absolutePath);
1066
+            if ($path == null) {
1067
+                return false;
1068
+            }
1069
+            if ($this->shouldEmitHooks($path)) {
1070
+                \OC_Hook::emit(
1071
+                    Filesystem::CLASSNAME,
1072
+                    Filesystem::signal_read,
1073
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1074
+                );
1075
+            }
1076
+            /** @var Storage|null $storage */
1077
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1078
+            if ($storage) {
1079
+                return $storage->hash($type, $internalPath, $raw);
1080
+            }
1081
+        }
1082
+        return false;
1083
+    }
1084
+
1085
+    /**
1086
+     * @param string $path
1087
+     * @return mixed
1088
+     * @throws InvalidPathException
1089
+     */
1090
+    public function free_space($path = '/') {
1091
+        $this->assertPathLength($path);
1092
+        $result = $this->basicOperation('free_space', $path);
1093
+        if ($result === null) {
1094
+            throw new InvalidPathException();
1095
+        }
1096
+        return $result;
1097
+    }
1098
+
1099
+    /**
1100
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1101
+     *
1102
+     * @param mixed $extraParam (optional)
1103
+     * @return mixed
1104
+     * @throws LockedException
1105
+     *
1106
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1107
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1108
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1109
+     */
1110
+    private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1111
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1112
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1113
+        if (Filesystem::isValidPath($path)
1114
+            && !Filesystem::isFileBlacklisted($path)
1115
+        ) {
1116
+            $path = $this->getRelativePath($absolutePath);
1117
+            if ($path == null) {
1118
+                return false;
1119
+            }
1120
+
1121
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1122
+                // always a shared lock during pre-hooks so the hook can read the file
1123
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1124
+            }
1125
+
1126
+            $run = $this->runHooks($hooks, $path);
1127
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1128
+            if ($run && $storage) {
1129
+                /** @var Storage $storage */
1130
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1131
+                    try {
1132
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1133
+                    } catch (LockedException $e) {
1134
+                        // release the shared lock we acquired before quitting
1135
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1136
+                        throw $e;
1137
+                    }
1138
+                }
1139
+                try {
1140
+                    if (!is_null($extraParam)) {
1141
+                        $result = $storage->$operation($internalPath, $extraParam);
1142
+                    } else {
1143
+                        $result = $storage->$operation($internalPath);
1144
+                    }
1145
+                } catch (\Exception $e) {
1146
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1147
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1148
+                    } elseif (in_array('read', $hooks)) {
1149
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1150
+                    }
1151
+                    throw $e;
1152
+                }
1153
+
1154
+                if ($result !== false && in_array('delete', $hooks)) {
1155
+                    $this->removeUpdate($storage, $internalPath);
1156
+                }
1157
+                if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1158
+                    $this->writeUpdate($storage, $internalPath);
1159
+                }
1160
+                if ($result !== false && in_array('touch', $hooks)) {
1161
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1162
+                }
1163
+
1164
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1165
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1166
+                }
1167
+
1168
+                $unlockLater = false;
1169
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1170
+                    $unlockLater = true;
1171
+                    // make sure our unlocking callback will still be called if connection is aborted
1172
+                    ignore_user_abort(true);
1173
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1174
+                        if (in_array('write', $hooks)) {
1175
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1176
+                        } elseif (in_array('read', $hooks)) {
1177
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1178
+                        }
1179
+                    });
1180
+                }
1181
+
1182
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1183
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1184
+                        $this->runHooks($hooks, $path, true);
1185
+                    }
1186
+                }
1187
+
1188
+                if (!$unlockLater
1189
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1190
+                ) {
1191
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1192
+                }
1193
+                return $result;
1194
+            } else {
1195
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1196
+            }
1197
+        }
1198
+        return null;
1199
+    }
1200
+
1201
+    /**
1202
+     * get the path relative to the default root for hook usage
1203
+     *
1204
+     * @param string $path
1205
+     * @return ?string
1206
+     */
1207
+    private function getHookPath($path): ?string {
1208
+        $view = Filesystem::getView();
1209
+        if (!$view) {
1210
+            return $path;
1211
+        }
1212
+        return $view->getRelativePath($this->getAbsolutePath($path));
1213
+    }
1214
+
1215
+    private function shouldEmitHooks(string $path = ''): bool {
1216
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1217
+            return false;
1218
+        }
1219
+        if (!Filesystem::$loaded) {
1220
+            return false;
1221
+        }
1222
+        $defaultRoot = Filesystem::getRoot();
1223
+        if ($defaultRoot === null) {
1224
+            return false;
1225
+        }
1226
+        if ($this->fakeRoot === $defaultRoot) {
1227
+            return true;
1228
+        }
1229
+        $fullPath = $this->getAbsolutePath($path);
1230
+
1231
+        if ($fullPath === $defaultRoot) {
1232
+            return true;
1233
+        }
1234
+
1235
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1236
+    }
1237
+
1238
+    /**
1239
+     * @param string[] $hooks
1240
+     * @param string $path
1241
+     * @param bool $post
1242
+     * @return bool
1243
+     */
1244
+    private function runHooks($hooks, $path, $post = false) {
1245
+        $relativePath = $path;
1246
+        $path = $this->getHookPath($path);
1247
+        $prefix = $post ? 'post_' : '';
1248
+        $run = true;
1249
+        if ($this->shouldEmitHooks($relativePath)) {
1250
+            foreach ($hooks as $hook) {
1251
+                if ($hook != 'read') {
1252
+                    \OC_Hook::emit(
1253
+                        Filesystem::CLASSNAME,
1254
+                        $prefix . $hook,
1255
+                        [
1256
+                            Filesystem::signal_param_run => &$run,
1257
+                            Filesystem::signal_param_path => $path
1258
+                        ]
1259
+                    );
1260
+                } elseif (!$post) {
1261
+                    \OC_Hook::emit(
1262
+                        Filesystem::CLASSNAME,
1263
+                        $prefix . $hook,
1264
+                        [
1265
+                            Filesystem::signal_param_path => $path
1266
+                        ]
1267
+                    );
1268
+                }
1269
+            }
1270
+        }
1271
+        return $run;
1272
+    }
1273
+
1274
+    /**
1275
+     * check if a file or folder has been updated since $time
1276
+     *
1277
+     * @param string $path
1278
+     * @param int $time
1279
+     * @return bool
1280
+     */
1281
+    public function hasUpdated($path, $time) {
1282
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1283
+    }
1284
+
1285
+    /**
1286
+     * @param string $ownerId
1287
+     * @return IUser
1288
+     */
1289
+    private function getUserObjectForOwner(string $ownerId) {
1290
+        return new LazyUser($ownerId, $this->userManager);
1291
+    }
1292
+
1293
+    /**
1294
+     * Get file info from cache
1295
+     *
1296
+     * If the file is not in cached it will be scanned
1297
+     * If the file has changed on storage the cache will be updated
1298
+     *
1299
+     * @param Storage $storage
1300
+     * @param string $internalPath
1301
+     * @param string $relativePath
1302
+     * @return ICacheEntry|bool
1303
+     */
1304
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1305
+        $cache = $storage->getCache($internalPath);
1306
+        $data = $cache->get($internalPath);
1307
+        $watcher = $storage->getWatcher($internalPath);
1308
+
1309
+        try {
1310
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1311
+            if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1312
+                if (!$storage->file_exists($internalPath)) {
1313
+                    return false;
1314
+                }
1315
+                // don't need to get a lock here since the scanner does it's own locking
1316
+                $scanner = $storage->getScanner($internalPath);
1317
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1318
+                $data = $cache->get($internalPath);
1319
+            } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1320
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1321
+                $watcher->update($internalPath, $data);
1322
+                $storage->getPropagator()->propagateChange($internalPath, time());
1323
+                $data = $cache->get($internalPath);
1324
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1325
+            }
1326
+        } catch (LockedException $e) {
1327
+            // if the file is locked we just use the old cache info
1328
+        }
1329
+
1330
+        return $data;
1331
+    }
1332
+
1333
+    /**
1334
+     * get the filesystem info
1335
+     *
1336
+     * @param string $path
1337
+     * @param bool|string $includeMountPoints true to add mountpoint sizes,
1338
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1339
+     * @return \OC\Files\FileInfo|false False if file does not exist
1340
+     */
1341
+    public function getFileInfo($path, $includeMountPoints = true) {
1342
+        $this->assertPathLength($path);
1343
+        if (!Filesystem::isValidPath($path)) {
1344
+            return false;
1345
+        }
1346
+        if (Cache\Scanner::isPartialFile($path)) {
1347
+            return $this->getPartFileInfo($path);
1348
+        }
1349
+        $relativePath = $path;
1350
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1351
+
1352
+        $mount = Filesystem::getMountManager()->find($path);
1353
+        $storage = $mount->getStorage();
1354
+        $internalPath = $mount->getInternalPath($path);
1355
+        if ($storage) {
1356
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1357
+
1358
+            if (!$data instanceof ICacheEntry) {
1359
+                return false;
1360
+            }
1361
+
1362
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1363
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1364
+            }
1365
+            $ownerId = $storage->getOwner($internalPath);
1366
+            $owner = null;
1367
+            if ($ownerId !== null && $ownerId !== false) {
1368
+                // ownerId might be null if files are accessed with an access token without file system access
1369
+                $owner = $this->getUserObjectForOwner($ownerId);
1370
+            }
1371
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1372
+
1373
+            if (isset($data['fileid'])) {
1374
+                if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1375
+                    //add the sizes of other mount points to the folder
1376
+                    $extOnly = ($includeMountPoints === 'ext');
1377
+                    $this->addSubMounts($info, $extOnly);
1378
+                }
1379
+            }
1380
+
1381
+            return $info;
1382
+        } else {
1383
+            $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1384
+        }
1385
+
1386
+        return false;
1387
+    }
1388
+
1389
+    /**
1390
+     * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1391
+     */
1392
+    public function addSubMounts(FileInfo $info, $extOnly = false): void {
1393
+        $mounts = Filesystem::getMountManager()->findIn($info->getPath());
1394
+        $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1395
+            $subStorage = $mount->getStorage();
1396
+            return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1397
+        }));
1398
+    }
1399
+
1400
+    /**
1401
+     * get the content of a directory
1402
+     *
1403
+     * @param string $directory path under datadirectory
1404
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1405
+     * @return FileInfo[]
1406
+     */
1407
+    public function getDirectoryContent($directory, $mimetype_filter = '', \OCP\Files\FileInfo $directoryInfo = null) {
1408
+        $this->assertPathLength($directory);
1409
+        if (!Filesystem::isValidPath($directory)) {
1410
+            return [];
1411
+        }
1412
+
1413
+        $path = $this->getAbsolutePath($directory);
1414
+        $path = Filesystem::normalizePath($path);
1415
+        $mount = $this->getMount($directory);
1416
+        $storage = $mount->getStorage();
1417
+        $internalPath = $mount->getInternalPath($path);
1418
+        if (!$storage) {
1419
+            return [];
1420
+        }
1421
+
1422
+        $cache = $storage->getCache($internalPath);
1423
+        $user = \OC_User::getUser();
1424
+
1425
+        if (!$directoryInfo) {
1426
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1427
+            if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1428
+                return [];
1429
+            }
1430
+        } else {
1431
+            $data = $directoryInfo;
1432
+        }
1433
+
1434
+        if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1435
+            return [];
1436
+        }
1437
+
1438
+        $folderId = $data->getId();
1439
+        $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1440
+
1441
+        $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1442
+
1443
+        $fileNames = array_map(function (ICacheEntry $content) {
1444
+            return $content->getName();
1445
+        }, $contents);
1446
+        /**
1447
+         * @var \OC\Files\FileInfo[] $fileInfos
1448
+         */
1449
+        $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1450
+            if ($sharingDisabled) {
1451
+                $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1452
+            }
1453
+            $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1454
+            return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1455
+        }, $contents);
1456
+        $files = array_combine($fileNames, $fileInfos);
1457
+
1458
+        //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1459
+        $mounts = Filesystem::getMountManager()->findIn($path);
1460
+        $dirLength = strlen($path);
1461
+        foreach ($mounts as $mount) {
1462
+            $mountPoint = $mount->getMountPoint();
1463
+            $subStorage = $mount->getStorage();
1464
+            if ($subStorage) {
1465
+                $subCache = $subStorage->getCache('');
1466
+
1467
+                $rootEntry = $subCache->get('');
1468
+                if (!$rootEntry) {
1469
+                    $subScanner = $subStorage->getScanner();
1470
+                    try {
1471
+                        $subScanner->scanFile('');
1472
+                    } catch (\OCP\Files\StorageNotAvailableException $e) {
1473
+                        continue;
1474
+                    } catch (\OCP\Files\StorageInvalidException $e) {
1475
+                        continue;
1476
+                    } catch (\Exception $e) {
1477
+                        // sometimes when the storage is not available it can be any exception
1478
+                        $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1479
+                            'exception' => $e,
1480
+                            'app' => 'core',
1481
+                        ]);
1482
+                        continue;
1483
+                    }
1484
+                    $rootEntry = $subCache->get('');
1485
+                }
1486
+
1487
+                if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1488
+                    $relativePath = trim(substr($mountPoint, $dirLength), '/');
1489
+                    if ($pos = strpos($relativePath, '/')) {
1490
+                        //mountpoint inside subfolder add size to the correct folder
1491
+                        $entryName = substr($relativePath, 0, $pos);
1492
+                        if (isset($files[$entryName])) {
1493
+                            $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1494
+                        }
1495
+                    } else { //mountpoint in this folder, add an entry for it
1496
+                        $rootEntry['name'] = $relativePath;
1497
+                        $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1498
+                        $permissions = $rootEntry['permissions'];
1499
+                        // do not allow renaming/deleting the mount point if they are not shared files/folders
1500
+                        // for shared files/folders we use the permissions given by the owner
1501
+                        if ($mount instanceof MoveableMount) {
1502
+                            $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1503
+                        } else {
1504
+                            $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1505
+                        }
1506
+
1507
+                        $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1508
+
1509
+                        // if sharing was disabled for the user we remove the share permissions
1510
+                        if (\OCP\Util::isSharingDisabledForUser()) {
1511
+                            $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1512
+                        }
1513
+
1514
+                        $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1515
+                        $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1516
+                    }
1517
+                }
1518
+            }
1519
+        }
1520
+
1521
+        if ($mimetype_filter) {
1522
+            $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1523
+                if (strpos($mimetype_filter, '/')) {
1524
+                    return $file->getMimetype() === $mimetype_filter;
1525
+                } else {
1526
+                    return $file->getMimePart() === $mimetype_filter;
1527
+                }
1528
+            });
1529
+        }
1530
+
1531
+        return array_values($files);
1532
+    }
1533
+
1534
+    /**
1535
+     * change file metadata
1536
+     *
1537
+     * @param string $path
1538
+     * @param array|\OCP\Files\FileInfo $data
1539
+     * @return int
1540
+     *
1541
+     * returns the fileid of the updated file
1542
+     */
1543
+    public function putFileInfo($path, $data) {
1544
+        $this->assertPathLength($path);
1545
+        if ($data instanceof FileInfo) {
1546
+            $data = $data->getData();
1547
+        }
1548
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1549
+        /**
1550
+         * @var Storage $storage
1551
+         * @var string $internalPath
1552
+         */
1553
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
1554
+        if ($storage) {
1555
+            $cache = $storage->getCache($path);
1556
+
1557
+            if (!$cache->inCache($internalPath)) {
1558
+                $scanner = $storage->getScanner($internalPath);
1559
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1560
+            }
1561
+
1562
+            return $cache->put($internalPath, $data);
1563
+        } else {
1564
+            return -1;
1565
+        }
1566
+    }
1567
+
1568
+    /**
1569
+     * search for files with the name matching $query
1570
+     *
1571
+     * @param string $query
1572
+     * @return FileInfo[]
1573
+     */
1574
+    public function search($query) {
1575
+        return $this->searchCommon('search', ['%' . $query . '%']);
1576
+    }
1577
+
1578
+    /**
1579
+     * search for files with the name matching $query
1580
+     *
1581
+     * @param string $query
1582
+     * @return FileInfo[]
1583
+     */
1584
+    public function searchRaw($query) {
1585
+        return $this->searchCommon('search', [$query]);
1586
+    }
1587
+
1588
+    /**
1589
+     * search for files by mimetype
1590
+     *
1591
+     * @param string $mimetype
1592
+     * @return FileInfo[]
1593
+     */
1594
+    public function searchByMime($mimetype) {
1595
+        return $this->searchCommon('searchByMime', [$mimetype]);
1596
+    }
1597
+
1598
+    /**
1599
+     * search for files by tag
1600
+     *
1601
+     * @param string|int $tag name or tag id
1602
+     * @param string $userId owner of the tags
1603
+     * @return FileInfo[]
1604
+     */
1605
+    public function searchByTag($tag, $userId) {
1606
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1607
+    }
1608
+
1609
+    /**
1610
+     * @param string $method cache method
1611
+     * @param array $args
1612
+     * @return FileInfo[]
1613
+     */
1614
+    private function searchCommon($method, $args) {
1615
+        $files = [];
1616
+        $rootLength = strlen($this->fakeRoot);
1617
+
1618
+        $mount = $this->getMount('');
1619
+        $mountPoint = $mount->getMountPoint();
1620
+        $storage = $mount->getStorage();
1621
+        $userManager = \OC::$server->getUserManager();
1622
+        if ($storage) {
1623
+            $cache = $storage->getCache('');
1624
+
1625
+            $results = call_user_func_array([$cache, $method], $args);
1626
+            foreach ($results as $result) {
1627
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1628
+                    $internalPath = $result['path'];
1629
+                    $path = $mountPoint . $result['path'];
1630
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1631
+                    $owner = $userManager->get($storage->getOwner($internalPath));
1632
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1633
+                }
1634
+            }
1635
+
1636
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1637
+            foreach ($mounts as $mount) {
1638
+                $mountPoint = $mount->getMountPoint();
1639
+                $storage = $mount->getStorage();
1640
+                if ($storage) {
1641
+                    $cache = $storage->getCache('');
1642
+
1643
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1644
+                    $results = call_user_func_array([$cache, $method], $args);
1645
+                    if ($results) {
1646
+                        foreach ($results as $result) {
1647
+                            $internalPath = $result['path'];
1648
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1649
+                            $path = rtrim($mountPoint . $internalPath, '/');
1650
+                            $owner = $userManager->get($storage->getOwner($internalPath));
1651
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652
+                        }
1653
+                    }
1654
+                }
1655
+            }
1656
+        }
1657
+        return $files;
1658
+    }
1659
+
1660
+    /**
1661
+     * Get the owner for a file or folder
1662
+     *
1663
+     * @param string $path
1664
+     * @return string the user id of the owner
1665
+     * @throws NotFoundException
1666
+     */
1667
+    public function getOwner($path) {
1668
+        $info = $this->getFileInfo($path);
1669
+        if (!$info) {
1670
+            throw new NotFoundException($path . ' not found while trying to get owner');
1671
+        }
1672
+
1673
+        if ($info->getOwner() === null) {
1674
+            throw new NotFoundException($path . ' has no owner');
1675
+        }
1676
+
1677
+        return $info->getOwner()->getUID();
1678
+    }
1679
+
1680
+    /**
1681
+     * get the ETag for a file or folder
1682
+     *
1683
+     * @param string $path
1684
+     * @return string|false
1685
+     */
1686
+    public function getETag($path) {
1687
+        [$storage, $internalPath] = $this->resolvePath($path);
1688
+        if ($storage) {
1689
+            return $storage->getETag($internalPath);
1690
+        } else {
1691
+            return false;
1692
+        }
1693
+    }
1694
+
1695
+    /**
1696
+     * Get the path of a file by id, relative to the view
1697
+     *
1698
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1699
+     *
1700
+     * @param int $id
1701
+     * @param int|null $storageId
1702
+     * @return string
1703
+     * @throws NotFoundException
1704
+     */
1705
+    public function getPath($id, int $storageId = null) {
1706
+        $id = (int)$id;
1707
+        $manager = Filesystem::getMountManager();
1708
+        $mounts = $manager->findIn($this->fakeRoot);
1709
+        $mounts[] = $manager->find($this->fakeRoot);
1710
+        $mounts = array_filter($mounts);
1711
+        // reverse the array, so we start with the storage this view is in
1712
+        // which is the most likely to contain the file we're looking for
1713
+        $mounts = array_reverse($mounts);
1714
+
1715
+        // put non-shared mounts in front of the shared mount
1716
+        // this prevents unneeded recursion into shares
1717
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1718
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1719
+        });
1720
+
1721
+        if (!is_null($storageId)) {
1722
+            $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1723
+                return $mount->getNumericStorageId() === $storageId;
1724
+            });
1725
+        }
1726
+
1727
+        foreach ($mounts as $mount) {
1728
+            /**
1729
+             * @var \OC\Files\Mount\MountPoint $mount
1730
+             */
1731
+            if ($mount->getStorage()) {
1732
+                $cache = $mount->getStorage()->getCache();
1733
+                $internalPath = $cache->getPathById($id);
1734
+                if (is_string($internalPath)) {
1735
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1736
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1737
+                        return $path;
1738
+                    }
1739
+                }
1740
+            }
1741
+        }
1742
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1743
+    }
1744
+
1745
+    /**
1746
+     * @param string $path
1747
+     * @throws InvalidPathException
1748
+     */
1749
+    private function assertPathLength($path): void {
1750
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1751
+        // Check for the string length - performed using isset() instead of strlen()
1752
+        // because isset() is about 5x-40x faster.
1753
+        if (isset($path[$maxLen])) {
1754
+            $pathLen = strlen($path);
1755
+            throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1756
+        }
1757
+    }
1758
+
1759
+    /**
1760
+     * check if it is allowed to move a mount point to a given target.
1761
+     * It is not allowed to move a mount point into a different mount point or
1762
+     * into an already shared folder
1763
+     */
1764
+    private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath): bool {
1765
+        // note: cannot use the view because the target is already locked
1766
+        $fileId = $targetStorage->getCache()->getId($targetInternalPath);
1767
+        if ($fileId === -1) {
1768
+            // target might not exist, need to check parent instead
1769
+            $fileId = $targetStorage->getCache()->getId(dirname($targetInternalPath));
1770
+        }
1771
+
1772
+        // check if any of the parents were shared by the current owner (include collections)
1773
+        $shares = Share::getItemShared(
1774
+            'folder',
1775
+            (string)$fileId,
1776
+            \OC\Share\Constants::FORMAT_NONE,
1777
+            null,
1778
+            true
1779
+        );
1780
+
1781
+        if (count($shares) > 0) {
1782
+            $this->logger->debug(
1783
+                'It is not allowed to move one mount point into a shared folder',
1784
+                ['app' => 'files']);
1785
+            return false;
1786
+        }
1787
+
1788
+        return true;
1789
+    }
1790
+
1791
+    /**
1792
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1793
+     */
1794
+    private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1795
+        $mount = $this->getMount($path);
1796
+        $storage = $mount->getStorage();
1797
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1798
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1799
+        return new FileInfo(
1800
+            $this->getAbsolutePath($path),
1801
+            $storage,
1802
+            $internalPath,
1803
+            [
1804
+                'fileid' => null,
1805
+                'mimetype' => $storage->getMimeType($internalPath),
1806
+                'name' => basename($path),
1807
+                'etag' => null,
1808
+                'size' => $storage->filesize($internalPath),
1809
+                'mtime' => $storage->filemtime($internalPath),
1810
+                'encrypted' => false,
1811
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1812
+            ],
1813
+            $mount,
1814
+            $owner
1815
+        );
1816
+    }
1817
+
1818
+    /**
1819
+     * @param string $path
1820
+     * @param string $fileName
1821
+     * @throws InvalidPathException
1822
+     */
1823
+    public function verifyPath($path, $fileName): void {
1824
+        try {
1825
+            /** @type \OCP\Files\Storage $storage */
1826
+            [$storage, $internalPath] = $this->resolvePath($path);
1827
+            $storage->verifyPath($internalPath, $fileName);
1828
+        } catch (ReservedWordException $ex) {
1829
+            $l = \OC::$server->getL10N('lib');
1830
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1831
+        } catch (InvalidCharacterInPathException $ex) {
1832
+            $l = \OC::$server->getL10N('lib');
1833
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1834
+        } catch (FileNameTooLongException $ex) {
1835
+            $l = \OC::$server->getL10N('lib');
1836
+            throw new InvalidPathException($l->t('File name is too long'));
1837
+        } catch (InvalidDirectoryException $ex) {
1838
+            $l = \OC::$server->getL10N('lib');
1839
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1840
+        } catch (EmptyFileNameException $ex) {
1841
+            $l = \OC::$server->getL10N('lib');
1842
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1843
+        }
1844
+    }
1845
+
1846
+    /**
1847
+     * get all parent folders of $path
1848
+     *
1849
+     * @param string $path
1850
+     * @return string[]
1851
+     */
1852
+    private function getParents($path) {
1853
+        $path = trim($path, '/');
1854
+        if (!$path) {
1855
+            return [];
1856
+        }
1857
+
1858
+        $parts = explode('/', $path);
1859
+
1860
+        // remove the single file
1861
+        array_pop($parts);
1862
+        $result = ['/'];
1863
+        $resultPath = '';
1864
+        foreach ($parts as $part) {
1865
+            if ($part) {
1866
+                $resultPath .= '/' . $part;
1867
+                $result[] = $resultPath;
1868
+            }
1869
+        }
1870
+        return $result;
1871
+    }
1872
+
1873
+    /**
1874
+     * Returns the mount point for which to lock
1875
+     *
1876
+     * @param string $absolutePath absolute path
1877
+     * @param bool $useParentMount true to return parent mount instead of whatever
1878
+     * is mounted directly on the given path, false otherwise
1879
+     * @return IMountPoint mount point for which to apply locks
1880
+     */
1881
+    private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
1882
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1883
+
1884
+        if ($useParentMount) {
1885
+            // find out if something is mounted directly on the path
1886
+            $internalPath = $mount->getInternalPath($absolutePath);
1887
+            if ($internalPath === '') {
1888
+                // resolve the parent mount instead
1889
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1890
+            }
1891
+        }
1892
+
1893
+        return $mount;
1894
+    }
1895
+
1896
+    /**
1897
+     * Lock the given path
1898
+     *
1899
+     * @param string $path the path of the file to lock, relative to the view
1900
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1901
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1902
+     *
1903
+     * @return bool False if the path is excluded from locking, true otherwise
1904
+     * @throws LockedException if the path is already locked
1905
+     */
1906
+    private function lockPath($path, $type, $lockMountPoint = false) {
1907
+        $absolutePath = $this->getAbsolutePath($path);
1908
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1909
+        if (!$this->shouldLockFile($absolutePath)) {
1910
+            return false;
1911
+        }
1912
+
1913
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1914
+        try {
1915
+            $storage = $mount->getStorage();
1916
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1917
+                $storage->acquireLock(
1918
+                    $mount->getInternalPath($absolutePath),
1919
+                    $type,
1920
+                    $this->lockingProvider
1921
+                );
1922
+            }
1923
+        } catch (LockedException $e) {
1924
+            // rethrow with the a human-readable path
1925
+            throw new LockedException(
1926
+                $this->getPathRelativeToFiles($absolutePath),
1927
+                $e,
1928
+                $e->getExistingLock()
1929
+            );
1930
+        }
1931
+
1932
+        return true;
1933
+    }
1934
+
1935
+    /**
1936
+     * Change the lock type
1937
+     *
1938
+     * @param string $path the path of the file to lock, relative to the view
1939
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1940
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1941
+     *
1942
+     * @return bool False if the path is excluded from locking, true otherwise
1943
+     * @throws LockedException if the path is already locked
1944
+     */
1945
+    public function changeLock($path, $type, $lockMountPoint = false) {
1946
+        $path = Filesystem::normalizePath($path);
1947
+        $absolutePath = $this->getAbsolutePath($path);
1948
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1949
+        if (!$this->shouldLockFile($absolutePath)) {
1950
+            return false;
1951
+        }
1952
+
1953
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1954
+        try {
1955
+            $storage = $mount->getStorage();
1956
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1957
+                $storage->changeLock(
1958
+                    $mount->getInternalPath($absolutePath),
1959
+                    $type,
1960
+                    $this->lockingProvider
1961
+                );
1962
+            }
1963
+        } catch (LockedException $e) {
1964
+            try {
1965
+                // rethrow with the a human-readable path
1966
+                throw new LockedException(
1967
+                    $this->getPathRelativeToFiles($absolutePath),
1968
+                    $e,
1969
+                    $e->getExistingLock()
1970
+                );
1971
+            } catch (\InvalidArgumentException $ex) {
1972
+                throw new LockedException(
1973
+                    $absolutePath,
1974
+                    $ex,
1975
+                    $e->getExistingLock()
1976
+                );
1977
+            }
1978
+        }
1979
+
1980
+        return true;
1981
+    }
1982
+
1983
+    /**
1984
+     * Unlock the given path
1985
+     *
1986
+     * @param string $path the path of the file to unlock, relative to the view
1987
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1988
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1989
+     *
1990
+     * @return bool False if the path is excluded from locking, true otherwise
1991
+     * @throws LockedException
1992
+     */
1993
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1994
+        $absolutePath = $this->getAbsolutePath($path);
1995
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1996
+        if (!$this->shouldLockFile($absolutePath)) {
1997
+            return false;
1998
+        }
1999
+
2000
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2001
+        $storage = $mount->getStorage();
2002
+        if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2003
+            $storage->releaseLock(
2004
+                $mount->getInternalPath($absolutePath),
2005
+                $type,
2006
+                $this->lockingProvider
2007
+            );
2008
+        }
2009
+
2010
+        return true;
2011
+    }
2012
+
2013
+    /**
2014
+     * Lock a path and all its parents up to the root of the view
2015
+     *
2016
+     * @param string $path the path of the file to lock relative to the view
2017
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2018
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2019
+     *
2020
+     * @return bool False if the path is excluded from locking, true otherwise
2021
+     * @throws LockedException
2022
+     */
2023
+    public function lockFile($path, $type, $lockMountPoint = false) {
2024
+        $absolutePath = $this->getAbsolutePath($path);
2025
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2026
+        if (!$this->shouldLockFile($absolutePath)) {
2027
+            return false;
2028
+        }
2029
+
2030
+        $this->lockPath($path, $type, $lockMountPoint);
2031
+
2032
+        $parents = $this->getParents($path);
2033
+        foreach ($parents as $parent) {
2034
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2035
+        }
2036
+
2037
+        return true;
2038
+    }
2039
+
2040
+    /**
2041
+     * Unlock a path and all its parents up to the root of the view
2042
+     *
2043
+     * @param string $path the path of the file to lock relative to the view
2044
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2045
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2046
+     *
2047
+     * @return bool False if the path is excluded from locking, true otherwise
2048
+     * @throws LockedException
2049
+     */
2050
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2051
+        $absolutePath = $this->getAbsolutePath($path);
2052
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2053
+        if (!$this->shouldLockFile($absolutePath)) {
2054
+            return false;
2055
+        }
2056
+
2057
+        $this->unlockPath($path, $type, $lockMountPoint);
2058
+
2059
+        $parents = $this->getParents($path);
2060
+        foreach ($parents as $parent) {
2061
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2062
+        }
2063
+
2064
+        return true;
2065
+    }
2066
+
2067
+    /**
2068
+     * Only lock files in data/user/files/
2069
+     *
2070
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2071
+     * @return bool
2072
+     */
2073
+    protected function shouldLockFile($path) {
2074
+        $path = Filesystem::normalizePath($path);
2075
+
2076
+        $pathSegments = explode('/', $path);
2077
+        if (isset($pathSegments[2])) {
2078
+            // E.g.: /username/files/path-to-file
2079
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2080
+        }
2081
+
2082
+        return strpos($path, '/appdata_') !== 0;
2083
+    }
2084
+
2085
+    /**
2086
+     * Shortens the given absolute path to be relative to
2087
+     * "$user/files".
2088
+     *
2089
+     * @param string $absolutePath absolute path which is under "files"
2090
+     *
2091
+     * @return string path relative to "files" with trimmed slashes or null
2092
+     * if the path was NOT relative to files
2093
+     *
2094
+     * @throws \InvalidArgumentException if the given path was not under "files"
2095
+     * @since 8.1.0
2096
+     */
2097
+    public function getPathRelativeToFiles($absolutePath) {
2098
+        $path = Filesystem::normalizePath($absolutePath);
2099
+        $parts = explode('/', trim($path, '/'), 3);
2100
+        // "$user", "files", "path/to/dir"
2101
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2102
+            $this->logger->error(
2103
+                '$absolutePath must be relative to "files", value is "{absolutePath}"',
2104
+                [
2105
+                    'absolutePath' => $absolutePath,
2106
+                ]
2107
+            );
2108
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2109
+        }
2110
+        if (isset($parts[2])) {
2111
+            return $parts[2];
2112
+        }
2113
+        return '';
2114
+    }
2115
+
2116
+    /**
2117
+     * @param string $filename
2118
+     * @return array
2119
+     * @throws \OC\User\NoUserException
2120
+     * @throws NotFoundException
2121
+     */
2122
+    public function getUidAndFilename($filename) {
2123
+        $info = $this->getFileInfo($filename);
2124
+        if (!$info instanceof \OCP\Files\FileInfo) {
2125
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2126
+        }
2127
+        $uid = $info->getOwner()->getUID();
2128
+        if ($uid != \OC_User::getUser()) {
2129
+            Filesystem::initMountPoints($uid);
2130
+            $ownerView = new View('/' . $uid . '/files');
2131
+            try {
2132
+                $filename = $ownerView->getPath($info['fileid']);
2133
+            } catch (NotFoundException $e) {
2134
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2135
+            }
2136
+        }
2137
+        return [$uid, $filename];
2138
+    }
2139
+
2140
+    /**
2141
+     * Creates parent non-existing folders
2142
+     *
2143
+     * @param string $filePath
2144
+     * @return bool
2145
+     */
2146
+    private function createParentDirectories($filePath) {
2147
+        $directoryParts = explode('/', $filePath);
2148
+        $directoryParts = array_filter($directoryParts);
2149
+        foreach ($directoryParts as $key => $part) {
2150
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2151
+            $currentPath = '/' . implode('/', $currentPathElements);
2152
+            if ($this->is_file($currentPath)) {
2153
+                return false;
2154
+            }
2155
+            if (!$this->file_exists($currentPath)) {
2156
+                $this->mkdir($currentPath);
2157
+            }
2158
+        }
2159
+
2160
+        return true;
2161
+    }
2162 2162
 }
Please login to merge, or discard this patch.