Passed
Push — master ( e81fdf...9f1d49 )
by Robin
16:12 queued 13s
created
lib/private/Files/Storage/Common.php 1 patch
Indentation   +826 added lines, -826 removed lines patch added patch discarded remove patch
@@ -77,834 +77,834 @@
 block discarded – undo
77 77
  * in classes which extend it, e.g. $this->stat() .
78 78
  */
79 79
 abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage {
80
-	use LocalTempFileTrait;
81
-
82
-	protected $cache;
83
-	protected $scanner;
84
-	protected $watcher;
85
-	protected $propagator;
86
-	protected $storageCache;
87
-	protected $updater;
88
-
89
-	protected $mountOptions = [];
90
-	protected $owner = null;
91
-
92
-	/** @var ?bool */
93
-	private $shouldLogLocks = null;
94
-	/** @var ?LoggerInterface */
95
-	private $logger;
96
-
97
-	public function __construct($parameters) {
98
-	}
99
-
100
-	/**
101
-	 * Remove a file or folder
102
-	 *
103
-	 * @param string $path
104
-	 * @return bool
105
-	 */
106
-	protected function remove($path) {
107
-		if ($this->is_dir($path)) {
108
-			return $this->rmdir($path);
109
-		} elseif ($this->is_file($path)) {
110
-			return $this->unlink($path);
111
-		} else {
112
-			return false;
113
-		}
114
-	}
115
-
116
-	public function is_dir($path) {
117
-		return $this->filetype($path) === 'dir';
118
-	}
119
-
120
-	public function is_file($path) {
121
-		return $this->filetype($path) === 'file';
122
-	}
123
-
124
-	public function filesize($path): false|int|float {
125
-		if ($this->is_dir($path)) {
126
-			return 0; //by definition
127
-		} else {
128
-			$stat = $this->stat($path);
129
-			if (isset($stat['size'])) {
130
-				return $stat['size'];
131
-			} else {
132
-				return 0;
133
-			}
134
-		}
135
-	}
136
-
137
-	public function isReadable($path) {
138
-		// at least check whether it exists
139
-		// subclasses might want to implement this more thoroughly
140
-		return $this->file_exists($path);
141
-	}
142
-
143
-	public function isUpdatable($path) {
144
-		// at least check whether it exists
145
-		// subclasses might want to implement this more thoroughly
146
-		// a non-existing file/folder isn't updatable
147
-		return $this->file_exists($path);
148
-	}
149
-
150
-	public function isCreatable($path) {
151
-		if ($this->is_dir($path) && $this->isUpdatable($path)) {
152
-			return true;
153
-		}
154
-		return false;
155
-	}
156
-
157
-	public function isDeletable($path) {
158
-		if ($path === '' || $path === '/') {
159
-			return $this->isUpdatable($path);
160
-		}
161
-		$parent = dirname($path);
162
-		return $this->isUpdatable($parent) && $this->isUpdatable($path);
163
-	}
164
-
165
-	public function isSharable($path) {
166
-		return $this->isReadable($path);
167
-	}
168
-
169
-	public function getPermissions($path) {
170
-		$permissions = 0;
171
-		if ($this->isCreatable($path)) {
172
-			$permissions |= \OCP\Constants::PERMISSION_CREATE;
173
-		}
174
-		if ($this->isReadable($path)) {
175
-			$permissions |= \OCP\Constants::PERMISSION_READ;
176
-		}
177
-		if ($this->isUpdatable($path)) {
178
-			$permissions |= \OCP\Constants::PERMISSION_UPDATE;
179
-		}
180
-		if ($this->isDeletable($path)) {
181
-			$permissions |= \OCP\Constants::PERMISSION_DELETE;
182
-		}
183
-		if ($this->isSharable($path)) {
184
-			$permissions |= \OCP\Constants::PERMISSION_SHARE;
185
-		}
186
-		return $permissions;
187
-	}
188
-
189
-	public function filemtime($path) {
190
-		$stat = $this->stat($path);
191
-		if (isset($stat['mtime']) && $stat['mtime'] > 0) {
192
-			return $stat['mtime'];
193
-		} else {
194
-			return 0;
195
-		}
196
-	}
197
-
198
-	public function file_get_contents($path) {
199
-		$handle = $this->fopen($path, "r");
200
-		if (!$handle) {
201
-			return false;
202
-		}
203
-		$data = stream_get_contents($handle);
204
-		fclose($handle);
205
-		return $data;
206
-	}
207
-
208
-	public function file_put_contents($path, $data) {
209
-		$handle = $this->fopen($path, "w");
210
-		if (!$handle) {
211
-			return false;
212
-		}
213
-		$this->removeCachedFile($path);
214
-		$count = fwrite($handle, $data);
215
-		fclose($handle);
216
-		return $count;
217
-	}
218
-
219
-	public function rename($source, $target) {
220
-		$this->remove($target);
221
-
222
-		$this->removeCachedFile($source);
223
-		return $this->copy($source, $target) and $this->remove($source);
224
-	}
225
-
226
-	public function copy($source, $target) {
227
-		if ($this->is_dir($source)) {
228
-			$this->remove($target);
229
-			$dir = $this->opendir($source);
230
-			$this->mkdir($target);
231
-			while ($file = readdir($dir)) {
232
-				if (!Filesystem::isIgnoredDir($file)) {
233
-					if (!$this->copy($source . '/' . $file, $target . '/' . $file)) {
234
-						closedir($dir);
235
-						return false;
236
-					}
237
-				}
238
-			}
239
-			closedir($dir);
240
-			return true;
241
-		} else {
242
-			$sourceStream = $this->fopen($source, 'r');
243
-			$targetStream = $this->fopen($target, 'w');
244
-			[, $result] = \OC_Helper::streamCopy($sourceStream, $targetStream);
245
-			if (!$result) {
246
-				\OCP\Server::get(LoggerInterface::class)->warning("Failed to write data while copying $source to $target");
247
-			}
248
-			$this->removeCachedFile($target);
249
-			return $result;
250
-		}
251
-	}
252
-
253
-	public function getMimeType($path) {
254
-		if ($this->is_dir($path)) {
255
-			return 'httpd/unix-directory';
256
-		} elseif ($this->file_exists($path)) {
257
-			return \OC::$server->getMimeTypeDetector()->detectPath($path);
258
-		} else {
259
-			return false;
260
-		}
261
-	}
262
-
263
-	public function hash($type, $path, $raw = false) {
264
-		$fh = $this->fopen($path, 'rb');
265
-		$ctx = hash_init($type);
266
-		hash_update_stream($ctx, $fh);
267
-		fclose($fh);
268
-		return hash_final($ctx, $raw);
269
-	}
270
-
271
-	public function search($query) {
272
-		return $this->searchInDir($query);
273
-	}
274
-
275
-	public function getLocalFile($path) {
276
-		return $this->getCachedFile($path);
277
-	}
278
-
279
-	/**
280
-	 * @param string $path
281
-	 * @param string $target
282
-	 */
283
-	private function addLocalFolder($path, $target) {
284
-		$dh = $this->opendir($path);
285
-		if (is_resource($dh)) {
286
-			while (($file = readdir($dh)) !== false) {
287
-				if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
288
-					if ($this->is_dir($path . '/' . $file)) {
289
-						mkdir($target . '/' . $file);
290
-						$this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
291
-					} else {
292
-						$tmp = $this->toTmpFile($path . '/' . $file);
293
-						rename($tmp, $target . '/' . $file);
294
-					}
295
-				}
296
-			}
297
-		}
298
-	}
299
-
300
-	/**
301
-	 * @param string $query
302
-	 * @param string $dir
303
-	 * @return array
304
-	 */
305
-	protected function searchInDir($query, $dir = '') {
306
-		$files = [];
307
-		$dh = $this->opendir($dir);
308
-		if (is_resource($dh)) {
309
-			while (($item = readdir($dh)) !== false) {
310
-				if (\OC\Files\Filesystem::isIgnoredDir($item)) {
311
-					continue;
312
-				}
313
-				if (strstr(strtolower($item), strtolower($query)) !== false) {
314
-					$files[] = $dir . '/' . $item;
315
-				}
316
-				if ($this->is_dir($dir . '/' . $item)) {
317
-					$files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
318
-				}
319
-			}
320
-		}
321
-		closedir($dh);
322
-		return $files;
323
-	}
324
-
325
-	/**
326
-	 * Check if a file or folder has been updated since $time
327
-	 *
328
-	 * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
329
-	 * the mtime should always return false here. As a result storage implementations that always return false expect
330
-	 * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
331
-	 * Nextcloud filesystem.
332
-	 *
333
-	 * @param string $path
334
-	 * @param int $time
335
-	 * @return bool
336
-	 */
337
-	public function hasUpdated($path, $time) {
338
-		return $this->filemtime($path) > $time;
339
-	}
340
-
341
-	public function getCache($path = '', $storage = null) {
342
-		if (!$storage) {
343
-			$storage = $this;
344
-		}
345
-		if (!isset($storage->cache)) {
346
-			$storage->cache = new Cache($storage);
347
-		}
348
-		return $storage->cache;
349
-	}
350
-
351
-	public function getScanner($path = '', $storage = null) {
352
-		if (!$storage) {
353
-			$storage = $this;
354
-		}
355
-		if (!isset($storage->scanner)) {
356
-			$storage->scanner = new Scanner($storage);
357
-		}
358
-		return $storage->scanner;
359
-	}
360
-
361
-	public function getWatcher($path = '', $storage = null) {
362
-		if (!$storage) {
363
-			$storage = $this;
364
-		}
365
-		if (!isset($this->watcher)) {
366
-			$this->watcher = new Watcher($storage);
367
-			$globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
368
-			$this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
369
-		}
370
-		return $this->watcher;
371
-	}
372
-
373
-	/**
374
-	 * get a propagator instance for the cache
375
-	 *
376
-	 * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
377
-	 * @return \OC\Files\Cache\Propagator
378
-	 */
379
-	public function getPropagator($storage = null) {
380
-		if (!$storage) {
381
-			$storage = $this;
382
-		}
383
-		if (!isset($storage->propagator)) {
384
-			$config = \OC::$server->getSystemConfig();
385
-			$storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getValue('instanceid')]);
386
-		}
387
-		return $storage->propagator;
388
-	}
389
-
390
-	public function getUpdater($storage = null) {
391
-		if (!$storage) {
392
-			$storage = $this;
393
-		}
394
-		if (!isset($storage->updater)) {
395
-			$storage->updater = new Updater($storage);
396
-		}
397
-		return $storage->updater;
398
-	}
399
-
400
-	public function getStorageCache($storage = null) {
401
-		if (!$storage) {
402
-			$storage = $this;
403
-		}
404
-		if (!isset($this->storageCache)) {
405
-			$this->storageCache = new \OC\Files\Cache\Storage($storage);
406
-		}
407
-		return $this->storageCache;
408
-	}
409
-
410
-	/**
411
-	 * get the owner of a path
412
-	 *
413
-	 * @param string $path The path to get the owner
414
-	 * @return string|false uid or false
415
-	 */
416
-	public function getOwner($path) {
417
-		if ($this->owner === null) {
418
-			$this->owner = \OC_User::getUser();
419
-		}
420
-
421
-		return $this->owner;
422
-	}
423
-
424
-	/**
425
-	 * get the ETag for a file or folder
426
-	 *
427
-	 * @param string $path
428
-	 * @return string
429
-	 */
430
-	public function getETag($path) {
431
-		return uniqid();
432
-	}
433
-
434
-	/**
435
-	 * clean a path, i.e. remove all redundant '.' and '..'
436
-	 * making sure that it can't point to higher than '/'
437
-	 *
438
-	 * @param string $path The path to clean
439
-	 * @return string cleaned path
440
-	 */
441
-	public function cleanPath($path) {
442
-		if (strlen($path) == 0 or $path[0] != '/') {
443
-			$path = '/' . $path;
444
-		}
445
-
446
-		$output = [];
447
-		foreach (explode('/', $path) as $chunk) {
448
-			if ($chunk == '..') {
449
-				array_pop($output);
450
-			} elseif ($chunk == '.') {
451
-			} else {
452
-				$output[] = $chunk;
453
-			}
454
-		}
455
-		return implode('/', $output);
456
-	}
457
-
458
-	/**
459
-	 * Test a storage for availability
460
-	 *
461
-	 * @return bool
462
-	 */
463
-	public function test() {
464
-		try {
465
-			if ($this->stat('')) {
466
-				return true;
467
-			}
468
-			\OC::$server->get(LoggerInterface::class)->info("External storage not available: stat() failed");
469
-			return false;
470
-		} catch (\Exception $e) {
471
-			\OC::$server->get(LoggerInterface::class)->warning(
472
-				"External storage not available: " . $e->getMessage(),
473
-				['exception' => $e]
474
-			);
475
-			return false;
476
-		}
477
-	}
478
-
479
-	/**
480
-	 * get the free space in the storage
481
-	 *
482
-	 * @param string $path
483
-	 * @return int|float|false
484
-	 */
485
-	public function free_space($path) {
486
-		return \OCP\Files\FileInfo::SPACE_UNKNOWN;
487
-	}
488
-
489
-	/**
490
-	 * {@inheritdoc}
491
-	 */
492
-	public function isLocal() {
493
-		// the common implementation returns a temporary file by
494
-		// default, which is not local
495
-		return false;
496
-	}
497
-
498
-	/**
499
-	 * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
500
-	 *
501
-	 * @param string $class
502
-	 * @return bool
503
-	 */
504
-	public function instanceOfStorage($class) {
505
-		if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
506
-			// FIXME Temporary fix to keep existing checks working
507
-			$class = '\OCA\Files_Sharing\SharedStorage';
508
-		}
509
-		return is_a($this, $class);
510
-	}
511
-
512
-	/**
513
-	 * A custom storage implementation can return an url for direct download of a give file.
514
-	 *
515
-	 * For now the returned array can hold the parameter url - in future more attributes might follow.
516
-	 *
517
-	 * @param string $path
518
-	 * @return array|false
519
-	 */
520
-	public function getDirectDownload($path) {
521
-		return [];
522
-	}
523
-
524
-	/**
525
-	 * @inheritdoc
526
-	 * @throws InvalidPathException
527
-	 */
528
-	public function verifyPath($path, $fileName) {
529
-		// verify empty and dot files
530
-		$trimmed = trim($fileName);
531
-		if ($trimmed === '') {
532
-			throw new EmptyFileNameException();
533
-		}
534
-
535
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
536
-			throw new InvalidDirectoryException();
537
-		}
538
-
539
-		if (!\OC::$server->getDatabaseConnection()->supports4ByteText()) {
540
-			// verify database - e.g. mysql only 3-byte chars
541
-			if (preg_match('%(?:
80
+    use LocalTempFileTrait;
81
+
82
+    protected $cache;
83
+    protected $scanner;
84
+    protected $watcher;
85
+    protected $propagator;
86
+    protected $storageCache;
87
+    protected $updater;
88
+
89
+    protected $mountOptions = [];
90
+    protected $owner = null;
91
+
92
+    /** @var ?bool */
93
+    private $shouldLogLocks = null;
94
+    /** @var ?LoggerInterface */
95
+    private $logger;
96
+
97
+    public function __construct($parameters) {
98
+    }
99
+
100
+    /**
101
+     * Remove a file or folder
102
+     *
103
+     * @param string $path
104
+     * @return bool
105
+     */
106
+    protected function remove($path) {
107
+        if ($this->is_dir($path)) {
108
+            return $this->rmdir($path);
109
+        } elseif ($this->is_file($path)) {
110
+            return $this->unlink($path);
111
+        } else {
112
+            return false;
113
+        }
114
+    }
115
+
116
+    public function is_dir($path) {
117
+        return $this->filetype($path) === 'dir';
118
+    }
119
+
120
+    public function is_file($path) {
121
+        return $this->filetype($path) === 'file';
122
+    }
123
+
124
+    public function filesize($path): false|int|float {
125
+        if ($this->is_dir($path)) {
126
+            return 0; //by definition
127
+        } else {
128
+            $stat = $this->stat($path);
129
+            if (isset($stat['size'])) {
130
+                return $stat['size'];
131
+            } else {
132
+                return 0;
133
+            }
134
+        }
135
+    }
136
+
137
+    public function isReadable($path) {
138
+        // at least check whether it exists
139
+        // subclasses might want to implement this more thoroughly
140
+        return $this->file_exists($path);
141
+    }
142
+
143
+    public function isUpdatable($path) {
144
+        // at least check whether it exists
145
+        // subclasses might want to implement this more thoroughly
146
+        // a non-existing file/folder isn't updatable
147
+        return $this->file_exists($path);
148
+    }
149
+
150
+    public function isCreatable($path) {
151
+        if ($this->is_dir($path) && $this->isUpdatable($path)) {
152
+            return true;
153
+        }
154
+        return false;
155
+    }
156
+
157
+    public function isDeletable($path) {
158
+        if ($path === '' || $path === '/') {
159
+            return $this->isUpdatable($path);
160
+        }
161
+        $parent = dirname($path);
162
+        return $this->isUpdatable($parent) && $this->isUpdatable($path);
163
+    }
164
+
165
+    public function isSharable($path) {
166
+        return $this->isReadable($path);
167
+    }
168
+
169
+    public function getPermissions($path) {
170
+        $permissions = 0;
171
+        if ($this->isCreatable($path)) {
172
+            $permissions |= \OCP\Constants::PERMISSION_CREATE;
173
+        }
174
+        if ($this->isReadable($path)) {
175
+            $permissions |= \OCP\Constants::PERMISSION_READ;
176
+        }
177
+        if ($this->isUpdatable($path)) {
178
+            $permissions |= \OCP\Constants::PERMISSION_UPDATE;
179
+        }
180
+        if ($this->isDeletable($path)) {
181
+            $permissions |= \OCP\Constants::PERMISSION_DELETE;
182
+        }
183
+        if ($this->isSharable($path)) {
184
+            $permissions |= \OCP\Constants::PERMISSION_SHARE;
185
+        }
186
+        return $permissions;
187
+    }
188
+
189
+    public function filemtime($path) {
190
+        $stat = $this->stat($path);
191
+        if (isset($stat['mtime']) && $stat['mtime'] > 0) {
192
+            return $stat['mtime'];
193
+        } else {
194
+            return 0;
195
+        }
196
+    }
197
+
198
+    public function file_get_contents($path) {
199
+        $handle = $this->fopen($path, "r");
200
+        if (!$handle) {
201
+            return false;
202
+        }
203
+        $data = stream_get_contents($handle);
204
+        fclose($handle);
205
+        return $data;
206
+    }
207
+
208
+    public function file_put_contents($path, $data) {
209
+        $handle = $this->fopen($path, "w");
210
+        if (!$handle) {
211
+            return false;
212
+        }
213
+        $this->removeCachedFile($path);
214
+        $count = fwrite($handle, $data);
215
+        fclose($handle);
216
+        return $count;
217
+    }
218
+
219
+    public function rename($source, $target) {
220
+        $this->remove($target);
221
+
222
+        $this->removeCachedFile($source);
223
+        return $this->copy($source, $target) and $this->remove($source);
224
+    }
225
+
226
+    public function copy($source, $target) {
227
+        if ($this->is_dir($source)) {
228
+            $this->remove($target);
229
+            $dir = $this->opendir($source);
230
+            $this->mkdir($target);
231
+            while ($file = readdir($dir)) {
232
+                if (!Filesystem::isIgnoredDir($file)) {
233
+                    if (!$this->copy($source . '/' . $file, $target . '/' . $file)) {
234
+                        closedir($dir);
235
+                        return false;
236
+                    }
237
+                }
238
+            }
239
+            closedir($dir);
240
+            return true;
241
+        } else {
242
+            $sourceStream = $this->fopen($source, 'r');
243
+            $targetStream = $this->fopen($target, 'w');
244
+            [, $result] = \OC_Helper::streamCopy($sourceStream, $targetStream);
245
+            if (!$result) {
246
+                \OCP\Server::get(LoggerInterface::class)->warning("Failed to write data while copying $source to $target");
247
+            }
248
+            $this->removeCachedFile($target);
249
+            return $result;
250
+        }
251
+    }
252
+
253
+    public function getMimeType($path) {
254
+        if ($this->is_dir($path)) {
255
+            return 'httpd/unix-directory';
256
+        } elseif ($this->file_exists($path)) {
257
+            return \OC::$server->getMimeTypeDetector()->detectPath($path);
258
+        } else {
259
+            return false;
260
+        }
261
+    }
262
+
263
+    public function hash($type, $path, $raw = false) {
264
+        $fh = $this->fopen($path, 'rb');
265
+        $ctx = hash_init($type);
266
+        hash_update_stream($ctx, $fh);
267
+        fclose($fh);
268
+        return hash_final($ctx, $raw);
269
+    }
270
+
271
+    public function search($query) {
272
+        return $this->searchInDir($query);
273
+    }
274
+
275
+    public function getLocalFile($path) {
276
+        return $this->getCachedFile($path);
277
+    }
278
+
279
+    /**
280
+     * @param string $path
281
+     * @param string $target
282
+     */
283
+    private function addLocalFolder($path, $target) {
284
+        $dh = $this->opendir($path);
285
+        if (is_resource($dh)) {
286
+            while (($file = readdir($dh)) !== false) {
287
+                if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
288
+                    if ($this->is_dir($path . '/' . $file)) {
289
+                        mkdir($target . '/' . $file);
290
+                        $this->addLocalFolder($path . '/' . $file, $target . '/' . $file);
291
+                    } else {
292
+                        $tmp = $this->toTmpFile($path . '/' . $file);
293
+                        rename($tmp, $target . '/' . $file);
294
+                    }
295
+                }
296
+            }
297
+        }
298
+    }
299
+
300
+    /**
301
+     * @param string $query
302
+     * @param string $dir
303
+     * @return array
304
+     */
305
+    protected function searchInDir($query, $dir = '') {
306
+        $files = [];
307
+        $dh = $this->opendir($dir);
308
+        if (is_resource($dh)) {
309
+            while (($item = readdir($dh)) !== false) {
310
+                if (\OC\Files\Filesystem::isIgnoredDir($item)) {
311
+                    continue;
312
+                }
313
+                if (strstr(strtolower($item), strtolower($query)) !== false) {
314
+                    $files[] = $dir . '/' . $item;
315
+                }
316
+                if ($this->is_dir($dir . '/' . $item)) {
317
+                    $files = array_merge($files, $this->searchInDir($query, $dir . '/' . $item));
318
+                }
319
+            }
320
+        }
321
+        closedir($dh);
322
+        return $files;
323
+    }
324
+
325
+    /**
326
+     * Check if a file or folder has been updated since $time
327
+     *
328
+     * The method is only used to check if the cache needs to be updated. Storage backends that don't support checking
329
+     * the mtime should always return false here. As a result storage implementations that always return false expect
330
+     * exclusive access to the backend and will not pick up files that have been added in a way that circumvents
331
+     * Nextcloud filesystem.
332
+     *
333
+     * @param string $path
334
+     * @param int $time
335
+     * @return bool
336
+     */
337
+    public function hasUpdated($path, $time) {
338
+        return $this->filemtime($path) > $time;
339
+    }
340
+
341
+    public function getCache($path = '', $storage = null) {
342
+        if (!$storage) {
343
+            $storage = $this;
344
+        }
345
+        if (!isset($storage->cache)) {
346
+            $storage->cache = new Cache($storage);
347
+        }
348
+        return $storage->cache;
349
+    }
350
+
351
+    public function getScanner($path = '', $storage = null) {
352
+        if (!$storage) {
353
+            $storage = $this;
354
+        }
355
+        if (!isset($storage->scanner)) {
356
+            $storage->scanner = new Scanner($storage);
357
+        }
358
+        return $storage->scanner;
359
+    }
360
+
361
+    public function getWatcher($path = '', $storage = null) {
362
+        if (!$storage) {
363
+            $storage = $this;
364
+        }
365
+        if (!isset($this->watcher)) {
366
+            $this->watcher = new Watcher($storage);
367
+            $globalPolicy = \OC::$server->getConfig()->getSystemValue('filesystem_check_changes', Watcher::CHECK_NEVER);
368
+            $this->watcher->setPolicy((int)$this->getMountOption('filesystem_check_changes', $globalPolicy));
369
+        }
370
+        return $this->watcher;
371
+    }
372
+
373
+    /**
374
+     * get a propagator instance for the cache
375
+     *
376
+     * @param \OC\Files\Storage\Storage (optional) the storage to pass to the watcher
377
+     * @return \OC\Files\Cache\Propagator
378
+     */
379
+    public function getPropagator($storage = null) {
380
+        if (!$storage) {
381
+            $storage = $this;
382
+        }
383
+        if (!isset($storage->propagator)) {
384
+            $config = \OC::$server->getSystemConfig();
385
+            $storage->propagator = new Propagator($storage, \OC::$server->getDatabaseConnection(), ['appdata_' . $config->getValue('instanceid')]);
386
+        }
387
+        return $storage->propagator;
388
+    }
389
+
390
+    public function getUpdater($storage = null) {
391
+        if (!$storage) {
392
+            $storage = $this;
393
+        }
394
+        if (!isset($storage->updater)) {
395
+            $storage->updater = new Updater($storage);
396
+        }
397
+        return $storage->updater;
398
+    }
399
+
400
+    public function getStorageCache($storage = null) {
401
+        if (!$storage) {
402
+            $storage = $this;
403
+        }
404
+        if (!isset($this->storageCache)) {
405
+            $this->storageCache = new \OC\Files\Cache\Storage($storage);
406
+        }
407
+        return $this->storageCache;
408
+    }
409
+
410
+    /**
411
+     * get the owner of a path
412
+     *
413
+     * @param string $path The path to get the owner
414
+     * @return string|false uid or false
415
+     */
416
+    public function getOwner($path) {
417
+        if ($this->owner === null) {
418
+            $this->owner = \OC_User::getUser();
419
+        }
420
+
421
+        return $this->owner;
422
+    }
423
+
424
+    /**
425
+     * get the ETag for a file or folder
426
+     *
427
+     * @param string $path
428
+     * @return string
429
+     */
430
+    public function getETag($path) {
431
+        return uniqid();
432
+    }
433
+
434
+    /**
435
+     * clean a path, i.e. remove all redundant '.' and '..'
436
+     * making sure that it can't point to higher than '/'
437
+     *
438
+     * @param string $path The path to clean
439
+     * @return string cleaned path
440
+     */
441
+    public function cleanPath($path) {
442
+        if (strlen($path) == 0 or $path[0] != '/') {
443
+            $path = '/' . $path;
444
+        }
445
+
446
+        $output = [];
447
+        foreach (explode('/', $path) as $chunk) {
448
+            if ($chunk == '..') {
449
+                array_pop($output);
450
+            } elseif ($chunk == '.') {
451
+            } else {
452
+                $output[] = $chunk;
453
+            }
454
+        }
455
+        return implode('/', $output);
456
+    }
457
+
458
+    /**
459
+     * Test a storage for availability
460
+     *
461
+     * @return bool
462
+     */
463
+    public function test() {
464
+        try {
465
+            if ($this->stat('')) {
466
+                return true;
467
+            }
468
+            \OC::$server->get(LoggerInterface::class)->info("External storage not available: stat() failed");
469
+            return false;
470
+        } catch (\Exception $e) {
471
+            \OC::$server->get(LoggerInterface::class)->warning(
472
+                "External storage not available: " . $e->getMessage(),
473
+                ['exception' => $e]
474
+            );
475
+            return false;
476
+        }
477
+    }
478
+
479
+    /**
480
+     * get the free space in the storage
481
+     *
482
+     * @param string $path
483
+     * @return int|float|false
484
+     */
485
+    public function free_space($path) {
486
+        return \OCP\Files\FileInfo::SPACE_UNKNOWN;
487
+    }
488
+
489
+    /**
490
+     * {@inheritdoc}
491
+     */
492
+    public function isLocal() {
493
+        // the common implementation returns a temporary file by
494
+        // default, which is not local
495
+        return false;
496
+    }
497
+
498
+    /**
499
+     * Check if the storage is an instance of $class or is a wrapper for a storage that is an instance of $class
500
+     *
501
+     * @param string $class
502
+     * @return bool
503
+     */
504
+    public function instanceOfStorage($class) {
505
+        if (ltrim($class, '\\') === 'OC\Files\Storage\Shared') {
506
+            // FIXME Temporary fix to keep existing checks working
507
+            $class = '\OCA\Files_Sharing\SharedStorage';
508
+        }
509
+        return is_a($this, $class);
510
+    }
511
+
512
+    /**
513
+     * A custom storage implementation can return an url for direct download of a give file.
514
+     *
515
+     * For now the returned array can hold the parameter url - in future more attributes might follow.
516
+     *
517
+     * @param string $path
518
+     * @return array|false
519
+     */
520
+    public function getDirectDownload($path) {
521
+        return [];
522
+    }
523
+
524
+    /**
525
+     * @inheritdoc
526
+     * @throws InvalidPathException
527
+     */
528
+    public function verifyPath($path, $fileName) {
529
+        // verify empty and dot files
530
+        $trimmed = trim($fileName);
531
+        if ($trimmed === '') {
532
+            throw new EmptyFileNameException();
533
+        }
534
+
535
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
536
+            throw new InvalidDirectoryException();
537
+        }
538
+
539
+        if (!\OC::$server->getDatabaseConnection()->supports4ByteText()) {
540
+            // verify database - e.g. mysql only 3-byte chars
541
+            if (preg_match('%(?:
542 542
       \xF0[\x90-\xBF][\x80-\xBF]{2}      # planes 1-3
543 543
     | [\xF1-\xF3][\x80-\xBF]{3}          # planes 4-15
544 544
     | \xF4[\x80-\x8F][\x80-\xBF]{2}      # plane 16
545 545
 )%xs', $fileName)) {
546
-				throw new InvalidCharacterInPathException();
547
-			}
548
-		}
549
-
550
-		// 255 characters is the limit on common file systems (ext/xfs)
551
-		// oc_filecache has a 250 char length limit for the filename
552
-		if (isset($fileName[250])) {
553
-			throw new FileNameTooLongException();
554
-		}
555
-
556
-		// NOTE: $path will remain unverified for now
557
-		$this->verifyPosixPath($fileName);
558
-	}
559
-
560
-	/**
561
-	 * @param string $fileName
562
-	 * @throws InvalidPathException
563
-	 */
564
-	protected function verifyPosixPath($fileName) {
565
-		$this->scanForInvalidCharacters($fileName, "\\/");
566
-		$fileName = trim($fileName);
567
-		$reservedNames = ['*'];
568
-		if (in_array($fileName, $reservedNames)) {
569
-			throw new ReservedWordException();
570
-		}
571
-	}
572
-
573
-	/**
574
-	 * @param string $fileName
575
-	 * @param string $invalidChars
576
-	 * @throws InvalidPathException
577
-	 */
578
-	private function scanForInvalidCharacters($fileName, $invalidChars) {
579
-		foreach (str_split($invalidChars) as $char) {
580
-			if (str_contains($fileName, $char)) {
581
-				throw new InvalidCharacterInPathException();
582
-			}
583
-		}
584
-
585
-		$sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
586
-		if ($sanitizedFileName !== $fileName) {
587
-			throw new InvalidCharacterInPathException();
588
-		}
589
-	}
590
-
591
-	/**
592
-	 * @param array $options
593
-	 */
594
-	public function setMountOptions(array $options) {
595
-		$this->mountOptions = $options;
596
-	}
597
-
598
-	/**
599
-	 * @param string $name
600
-	 * @param mixed $default
601
-	 * @return mixed
602
-	 */
603
-	public function getMountOption($name, $default = null) {
604
-		return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
605
-	}
606
-
607
-	/**
608
-	 * @param IStorage $sourceStorage
609
-	 * @param string $sourceInternalPath
610
-	 * @param string $targetInternalPath
611
-	 * @param bool $preserveMtime
612
-	 * @return bool
613
-	 */
614
-	public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
615
-		if ($sourceStorage === $this) {
616
-			return $this->copy($sourceInternalPath, $targetInternalPath);
617
-		}
618
-
619
-		if ($sourceStorage->is_dir($sourceInternalPath)) {
620
-			$dh = $sourceStorage->opendir($sourceInternalPath);
621
-			$result = $this->mkdir($targetInternalPath);
622
-			if (is_resource($dh)) {
623
-				$result = true;
624
-				while ($result and ($file = readdir($dh)) !== false) {
625
-					if (!Filesystem::isIgnoredDir($file)) {
626
-						$result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
627
-					}
628
-				}
629
-			}
630
-		} else {
631
-			$source = $sourceStorage->fopen($sourceInternalPath, 'r');
632
-			$result = false;
633
-			if ($source) {
634
-				try {
635
-					$this->writeStream($targetInternalPath, $source);
636
-					$result = true;
637
-				} catch (\Exception $e) {
638
-					\OC::$server->get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
639
-				}
640
-			}
641
-
642
-			if ($result && $preserveMtime) {
643
-				$mtime = $sourceStorage->filemtime($sourceInternalPath);
644
-				$this->touch($targetInternalPath, is_int($mtime) ? $mtime : null);
645
-			}
646
-
647
-			if (!$result) {
648
-				// delete partially written target file
649
-				$this->unlink($targetInternalPath);
650
-				// delete cache entry that was created by fopen
651
-				$this->getCache()->remove($targetInternalPath);
652
-			}
653
-		}
654
-		return (bool)$result;
655
-	}
656
-
657
-	/**
658
-	 * Check if a storage is the same as the current one, including wrapped storages
659
-	 *
660
-	 * @param IStorage $storage
661
-	 * @return bool
662
-	 */
663
-	private function isSameStorage(IStorage $storage): bool {
664
-		while ($storage->instanceOfStorage(Wrapper::class)) {
665
-			/**
666
-			 * @var Wrapper $sourceStorage
667
-			 */
668
-			$storage = $storage->getWrapperStorage();
669
-		}
670
-
671
-		return $storage === $this;
672
-	}
673
-
674
-	/**
675
-	 * @param IStorage $sourceStorage
676
-	 * @param string $sourceInternalPath
677
-	 * @param string $targetInternalPath
678
-	 * @return bool
679
-	 */
680
-	public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
681
-		if ($this->isSameStorage($sourceStorage)) {
682
-			// resolve any jailed paths
683
-			while ($sourceStorage->instanceOfStorage(Jail::class)) {
684
-				/**
685
-				 * @var Jail $sourceStorage
686
-				 */
687
-				$sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
688
-				$sourceStorage = $sourceStorage->getUnjailedStorage();
689
-			}
690
-
691
-			return $this->rename($sourceInternalPath, $targetInternalPath);
692
-		}
693
-
694
-		if (!$sourceStorage->isDeletable($sourceInternalPath)) {
695
-			return false;
696
-		}
697
-
698
-		$result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
699
-		if ($result) {
700
-			if ($sourceStorage->is_dir($sourceInternalPath)) {
701
-				$result = $sourceStorage->rmdir($sourceInternalPath);
702
-			} else {
703
-				$result = $sourceStorage->unlink($sourceInternalPath);
704
-			}
705
-		}
706
-		return $result;
707
-	}
708
-
709
-	/**
710
-	 * @inheritdoc
711
-	 */
712
-	public function getMetaData($path) {
713
-		if (Filesystem::isFileBlacklisted($path)) {
714
-			throw new ForbiddenException('Invalid path: ' . $path, false);
715
-		}
716
-
717
-		$permissions = $this->getPermissions($path);
718
-		if (!$permissions & \OCP\Constants::PERMISSION_READ) {
719
-			//can't read, nothing we can do
720
-			return null;
721
-		}
722
-
723
-		$data = [];
724
-		$data['mimetype'] = $this->getMimeType($path);
725
-		$data['mtime'] = $this->filemtime($path);
726
-		if ($data['mtime'] === false) {
727
-			$data['mtime'] = time();
728
-		}
729
-		if ($data['mimetype'] == 'httpd/unix-directory') {
730
-			$data['size'] = -1; //unknown
731
-		} else {
732
-			$data['size'] = $this->filesize($path);
733
-		}
734
-		$data['etag'] = $this->getETag($path);
735
-		$data['storage_mtime'] = $data['mtime'];
736
-		$data['permissions'] = $permissions;
737
-		$data['name'] = basename($path);
738
-
739
-		return $data;
740
-	}
741
-
742
-	/**
743
-	 * @param string $path
744
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
745
-	 * @param \OCP\Lock\ILockingProvider $provider
746
-	 * @throws \OCP\Lock\LockedException
747
-	 */
748
-	public function acquireLock($path, $type, ILockingProvider $provider) {
749
-		$logger = $this->getLockLogger();
750
-		if ($logger) {
751
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
752
-			$logger->info(
753
-				sprintf(
754
-					'acquire %s lock on "%s" on storage "%s"',
755
-					$typeString,
756
-					$path,
757
-					$this->getId()
758
-				),
759
-				[
760
-					'app' => 'locking',
761
-				]
762
-			);
763
-		}
764
-		try {
765
-			$provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type, $this->getId() . '::' . $path);
766
-		} catch (LockedException $e) {
767
-			$e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
768
-			if ($logger) {
769
-				$logger->info($e->getMessage(), ['exception' => $e]);
770
-			}
771
-			throw $e;
772
-		}
773
-	}
774
-
775
-	/**
776
-	 * @param string $path
777
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
778
-	 * @param \OCP\Lock\ILockingProvider $provider
779
-	 * @throws \OCP\Lock\LockedException
780
-	 */
781
-	public function releaseLock($path, $type, ILockingProvider $provider) {
782
-		$logger = $this->getLockLogger();
783
-		if ($logger) {
784
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
785
-			$logger->info(
786
-				sprintf(
787
-					'release %s lock on "%s" on storage "%s"',
788
-					$typeString,
789
-					$path,
790
-					$this->getId()
791
-				),
792
-				[
793
-					'app' => 'locking',
794
-				]
795
-			);
796
-		}
797
-		try {
798
-			$provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
799
-		} catch (LockedException $e) {
800
-			$e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
801
-			if ($logger) {
802
-				$logger->info($e->getMessage(), ['exception' => $e]);
803
-			}
804
-			throw $e;
805
-		}
806
-	}
807
-
808
-	/**
809
-	 * @param string $path
810
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
811
-	 * @param \OCP\Lock\ILockingProvider $provider
812
-	 * @throws \OCP\Lock\LockedException
813
-	 */
814
-	public function changeLock($path, $type, ILockingProvider $provider) {
815
-		$logger = $this->getLockLogger();
816
-		if ($logger) {
817
-			$typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
818
-			$logger->info(
819
-				sprintf(
820
-					'change lock on "%s" to %s on storage "%s"',
821
-					$path,
822
-					$typeString,
823
-					$this->getId()
824
-				),
825
-				[
826
-					'app' => 'locking',
827
-				]
828
-			);
829
-		}
830
-		try {
831
-			$provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
832
-		} catch (LockedException $e) {
833
-			$e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
834
-			if ($logger) {
835
-				$logger->info($e->getMessage(), ['exception' => $e]);
836
-			}
837
-			throw $e;
838
-		}
839
-	}
840
-
841
-	private function getLockLogger(): ?LoggerInterface {
842
-		if (is_null($this->shouldLogLocks)) {
843
-			$this->shouldLogLocks = \OC::$server->getConfig()->getSystemValueBool('filelocking.debug', false);
844
-			$this->logger = $this->shouldLogLocks ? \OC::$server->get(LoggerInterface::class) : null;
845
-		}
846
-		return $this->logger;
847
-	}
848
-
849
-	/**
850
-	 * @return array [ available, last_checked ]
851
-	 */
852
-	public function getAvailability() {
853
-		return $this->getStorageCache()->getAvailability();
854
-	}
855
-
856
-	/**
857
-	 * @param bool $isAvailable
858
-	 */
859
-	public function setAvailability($isAvailable) {
860
-		$this->getStorageCache()->setAvailability($isAvailable);
861
-	}
862
-
863
-	/**
864
-	 * @return bool
865
-	 */
866
-	public function needsPartFile() {
867
-		return true;
868
-	}
869
-
870
-	/**
871
-	 * fallback implementation
872
-	 *
873
-	 * @param string $path
874
-	 * @param resource $stream
875
-	 * @param int $size
876
-	 * @return int
877
-	 */
878
-	public function writeStream(string $path, $stream, int $size = null): int {
879
-		$target = $this->fopen($path, 'w');
880
-		if (!$target) {
881
-			throw new GenericFileException("Failed to open $path for writing");
882
-		}
883
-		try {
884
-			[$count, $result] = \OC_Helper::streamCopy($stream, $target);
885
-			if (!$result) {
886
-				throw new GenericFileException("Failed to copy stream");
887
-			}
888
-		} finally {
889
-			fclose($target);
890
-			fclose($stream);
891
-		}
892
-		return $count;
893
-	}
894
-
895
-	public function getDirectoryContent($directory): \Traversable {
896
-		$dh = $this->opendir($directory);
897
-		if (is_resource($dh)) {
898
-			$basePath = rtrim($directory, '/');
899
-			while (($file = readdir($dh)) !== false) {
900
-				if (!Filesystem::isIgnoredDir($file)) {
901
-					$childPath = $basePath . '/' . trim($file, '/');
902
-					$metadata = $this->getMetaData($childPath);
903
-					if ($metadata !== null) {
904
-						yield $metadata;
905
-					}
906
-				}
907
-			}
908
-		}
909
-	}
546
+                throw new InvalidCharacterInPathException();
547
+            }
548
+        }
549
+
550
+        // 255 characters is the limit on common file systems (ext/xfs)
551
+        // oc_filecache has a 250 char length limit for the filename
552
+        if (isset($fileName[250])) {
553
+            throw new FileNameTooLongException();
554
+        }
555
+
556
+        // NOTE: $path will remain unverified for now
557
+        $this->verifyPosixPath($fileName);
558
+    }
559
+
560
+    /**
561
+     * @param string $fileName
562
+     * @throws InvalidPathException
563
+     */
564
+    protected function verifyPosixPath($fileName) {
565
+        $this->scanForInvalidCharacters($fileName, "\\/");
566
+        $fileName = trim($fileName);
567
+        $reservedNames = ['*'];
568
+        if (in_array($fileName, $reservedNames)) {
569
+            throw new ReservedWordException();
570
+        }
571
+    }
572
+
573
+    /**
574
+     * @param string $fileName
575
+     * @param string $invalidChars
576
+     * @throws InvalidPathException
577
+     */
578
+    private function scanForInvalidCharacters($fileName, $invalidChars) {
579
+        foreach (str_split($invalidChars) as $char) {
580
+            if (str_contains($fileName, $char)) {
581
+                throw new InvalidCharacterInPathException();
582
+            }
583
+        }
584
+
585
+        $sanitizedFileName = filter_var($fileName, FILTER_UNSAFE_RAW, FILTER_FLAG_STRIP_LOW);
586
+        if ($sanitizedFileName !== $fileName) {
587
+            throw new InvalidCharacterInPathException();
588
+        }
589
+    }
590
+
591
+    /**
592
+     * @param array $options
593
+     */
594
+    public function setMountOptions(array $options) {
595
+        $this->mountOptions = $options;
596
+    }
597
+
598
+    /**
599
+     * @param string $name
600
+     * @param mixed $default
601
+     * @return mixed
602
+     */
603
+    public function getMountOption($name, $default = null) {
604
+        return isset($this->mountOptions[$name]) ? $this->mountOptions[$name] : $default;
605
+    }
606
+
607
+    /**
608
+     * @param IStorage $sourceStorage
609
+     * @param string $sourceInternalPath
610
+     * @param string $targetInternalPath
611
+     * @param bool $preserveMtime
612
+     * @return bool
613
+     */
614
+    public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = false) {
615
+        if ($sourceStorage === $this) {
616
+            return $this->copy($sourceInternalPath, $targetInternalPath);
617
+        }
618
+
619
+        if ($sourceStorage->is_dir($sourceInternalPath)) {
620
+            $dh = $sourceStorage->opendir($sourceInternalPath);
621
+            $result = $this->mkdir($targetInternalPath);
622
+            if (is_resource($dh)) {
623
+                $result = true;
624
+                while ($result and ($file = readdir($dh)) !== false) {
625
+                    if (!Filesystem::isIgnoredDir($file)) {
626
+                        $result &= $this->copyFromStorage($sourceStorage, $sourceInternalPath . '/' . $file, $targetInternalPath . '/' . $file);
627
+                    }
628
+                }
629
+            }
630
+        } else {
631
+            $source = $sourceStorage->fopen($sourceInternalPath, 'r');
632
+            $result = false;
633
+            if ($source) {
634
+                try {
635
+                    $this->writeStream($targetInternalPath, $source);
636
+                    $result = true;
637
+                } catch (\Exception $e) {
638
+                    \OC::$server->get(LoggerInterface::class)->warning('Failed to copy stream to storage', ['exception' => $e]);
639
+                }
640
+            }
641
+
642
+            if ($result && $preserveMtime) {
643
+                $mtime = $sourceStorage->filemtime($sourceInternalPath);
644
+                $this->touch($targetInternalPath, is_int($mtime) ? $mtime : null);
645
+            }
646
+
647
+            if (!$result) {
648
+                // delete partially written target file
649
+                $this->unlink($targetInternalPath);
650
+                // delete cache entry that was created by fopen
651
+                $this->getCache()->remove($targetInternalPath);
652
+            }
653
+        }
654
+        return (bool)$result;
655
+    }
656
+
657
+    /**
658
+     * Check if a storage is the same as the current one, including wrapped storages
659
+     *
660
+     * @param IStorage $storage
661
+     * @return bool
662
+     */
663
+    private function isSameStorage(IStorage $storage): bool {
664
+        while ($storage->instanceOfStorage(Wrapper::class)) {
665
+            /**
666
+             * @var Wrapper $sourceStorage
667
+             */
668
+            $storage = $storage->getWrapperStorage();
669
+        }
670
+
671
+        return $storage === $this;
672
+    }
673
+
674
+    /**
675
+     * @param IStorage $sourceStorage
676
+     * @param string $sourceInternalPath
677
+     * @param string $targetInternalPath
678
+     * @return bool
679
+     */
680
+    public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
681
+        if ($this->isSameStorage($sourceStorage)) {
682
+            // resolve any jailed paths
683
+            while ($sourceStorage->instanceOfStorage(Jail::class)) {
684
+                /**
685
+                 * @var Jail $sourceStorage
686
+                 */
687
+                $sourceInternalPath = $sourceStorage->getUnjailedPath($sourceInternalPath);
688
+                $sourceStorage = $sourceStorage->getUnjailedStorage();
689
+            }
690
+
691
+            return $this->rename($sourceInternalPath, $targetInternalPath);
692
+        }
693
+
694
+        if (!$sourceStorage->isDeletable($sourceInternalPath)) {
695
+            return false;
696
+        }
697
+
698
+        $result = $this->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, true);
699
+        if ($result) {
700
+            if ($sourceStorage->is_dir($sourceInternalPath)) {
701
+                $result = $sourceStorage->rmdir($sourceInternalPath);
702
+            } else {
703
+                $result = $sourceStorage->unlink($sourceInternalPath);
704
+            }
705
+        }
706
+        return $result;
707
+    }
708
+
709
+    /**
710
+     * @inheritdoc
711
+     */
712
+    public function getMetaData($path) {
713
+        if (Filesystem::isFileBlacklisted($path)) {
714
+            throw new ForbiddenException('Invalid path: ' . $path, false);
715
+        }
716
+
717
+        $permissions = $this->getPermissions($path);
718
+        if (!$permissions & \OCP\Constants::PERMISSION_READ) {
719
+            //can't read, nothing we can do
720
+            return null;
721
+        }
722
+
723
+        $data = [];
724
+        $data['mimetype'] = $this->getMimeType($path);
725
+        $data['mtime'] = $this->filemtime($path);
726
+        if ($data['mtime'] === false) {
727
+            $data['mtime'] = time();
728
+        }
729
+        if ($data['mimetype'] == 'httpd/unix-directory') {
730
+            $data['size'] = -1; //unknown
731
+        } else {
732
+            $data['size'] = $this->filesize($path);
733
+        }
734
+        $data['etag'] = $this->getETag($path);
735
+        $data['storage_mtime'] = $data['mtime'];
736
+        $data['permissions'] = $permissions;
737
+        $data['name'] = basename($path);
738
+
739
+        return $data;
740
+    }
741
+
742
+    /**
743
+     * @param string $path
744
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
745
+     * @param \OCP\Lock\ILockingProvider $provider
746
+     * @throws \OCP\Lock\LockedException
747
+     */
748
+    public function acquireLock($path, $type, ILockingProvider $provider) {
749
+        $logger = $this->getLockLogger();
750
+        if ($logger) {
751
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
752
+            $logger->info(
753
+                sprintf(
754
+                    'acquire %s lock on "%s" on storage "%s"',
755
+                    $typeString,
756
+                    $path,
757
+                    $this->getId()
758
+                ),
759
+                [
760
+                    'app' => 'locking',
761
+                ]
762
+            );
763
+        }
764
+        try {
765
+            $provider->acquireLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type, $this->getId() . '::' . $path);
766
+        } catch (LockedException $e) {
767
+            $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
768
+            if ($logger) {
769
+                $logger->info($e->getMessage(), ['exception' => $e]);
770
+            }
771
+            throw $e;
772
+        }
773
+    }
774
+
775
+    /**
776
+     * @param string $path
777
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
778
+     * @param \OCP\Lock\ILockingProvider $provider
779
+     * @throws \OCP\Lock\LockedException
780
+     */
781
+    public function releaseLock($path, $type, ILockingProvider $provider) {
782
+        $logger = $this->getLockLogger();
783
+        if ($logger) {
784
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
785
+            $logger->info(
786
+                sprintf(
787
+                    'release %s lock on "%s" on storage "%s"',
788
+                    $typeString,
789
+                    $path,
790
+                    $this->getId()
791
+                ),
792
+                [
793
+                    'app' => 'locking',
794
+                ]
795
+            );
796
+        }
797
+        try {
798
+            $provider->releaseLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
799
+        } catch (LockedException $e) {
800
+            $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
801
+            if ($logger) {
802
+                $logger->info($e->getMessage(), ['exception' => $e]);
803
+            }
804
+            throw $e;
805
+        }
806
+    }
807
+
808
+    /**
809
+     * @param string $path
810
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
811
+     * @param \OCP\Lock\ILockingProvider $provider
812
+     * @throws \OCP\Lock\LockedException
813
+     */
814
+    public function changeLock($path, $type, ILockingProvider $provider) {
815
+        $logger = $this->getLockLogger();
816
+        if ($logger) {
817
+            $typeString = ($type === ILockingProvider::LOCK_SHARED) ? 'shared' : 'exclusive';
818
+            $logger->info(
819
+                sprintf(
820
+                    'change lock on "%s" to %s on storage "%s"',
821
+                    $path,
822
+                    $typeString,
823
+                    $this->getId()
824
+                ),
825
+                [
826
+                    'app' => 'locking',
827
+                ]
828
+            );
829
+        }
830
+        try {
831
+            $provider->changeLock('files/' . md5($this->getId() . '::' . trim($path, '/')), $type);
832
+        } catch (LockedException $e) {
833
+            $e = new LockedException($e->getPath(), $e, $e->getExistingLock(), $path);
834
+            if ($logger) {
835
+                $logger->info($e->getMessage(), ['exception' => $e]);
836
+            }
837
+            throw $e;
838
+        }
839
+    }
840
+
841
+    private function getLockLogger(): ?LoggerInterface {
842
+        if (is_null($this->shouldLogLocks)) {
843
+            $this->shouldLogLocks = \OC::$server->getConfig()->getSystemValueBool('filelocking.debug', false);
844
+            $this->logger = $this->shouldLogLocks ? \OC::$server->get(LoggerInterface::class) : null;
845
+        }
846
+        return $this->logger;
847
+    }
848
+
849
+    /**
850
+     * @return array [ available, last_checked ]
851
+     */
852
+    public function getAvailability() {
853
+        return $this->getStorageCache()->getAvailability();
854
+    }
855
+
856
+    /**
857
+     * @param bool $isAvailable
858
+     */
859
+    public function setAvailability($isAvailable) {
860
+        $this->getStorageCache()->setAvailability($isAvailable);
861
+    }
862
+
863
+    /**
864
+     * @return bool
865
+     */
866
+    public function needsPartFile() {
867
+        return true;
868
+    }
869
+
870
+    /**
871
+     * fallback implementation
872
+     *
873
+     * @param string $path
874
+     * @param resource $stream
875
+     * @param int $size
876
+     * @return int
877
+     */
878
+    public function writeStream(string $path, $stream, int $size = null): int {
879
+        $target = $this->fopen($path, 'w');
880
+        if (!$target) {
881
+            throw new GenericFileException("Failed to open $path for writing");
882
+        }
883
+        try {
884
+            [$count, $result] = \OC_Helper::streamCopy($stream, $target);
885
+            if (!$result) {
886
+                throw new GenericFileException("Failed to copy stream");
887
+            }
888
+        } finally {
889
+            fclose($target);
890
+            fclose($stream);
891
+        }
892
+        return $count;
893
+    }
894
+
895
+    public function getDirectoryContent($directory): \Traversable {
896
+        $dh = $this->opendir($directory);
897
+        if (is_resource($dh)) {
898
+            $basePath = rtrim($directory, '/');
899
+            while (($file = readdir($dh)) !== false) {
900
+                if (!Filesystem::isIgnoredDir($file)) {
901
+                    $childPath = $basePath . '/' . trim($file, '/');
902
+                    $metadata = $this->getMetaData($childPath);
903
+                    if ($metadata !== null) {
904
+                        yield $metadata;
905
+                    }
906
+                }
907
+            }
908
+        }
909
+    }
910 910
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 2 patches
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 (!str_starts_with($path, $root)) {
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 !str_starts_with($path, '/appdata_');
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 (!str_starts_with($path, $root)) {
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 !str_starts_with($path, '/appdata_');
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.
Spacing   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -124,9 +124,9 @@  discard block
 block discarded – undo
124 124
 			$path = '/';
125 125
 		}
126 126
 		if ($path[0] !== '/') {
127
-			$path = '/' . $path;
127
+			$path = '/'.$path;
128 128
 		}
129
-		return $this->fakeRoot . $path;
129
+		return $this->fakeRoot.$path;
130 130
 	}
131 131
 
132 132
 	/**
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	public function chroot($fakeRoot): void {
138 138
 		if (!$fakeRoot == '') {
139 139
 			if ($fakeRoot[0] !== '/') {
140
-				$fakeRoot = '/' . $fakeRoot;
140
+				$fakeRoot = '/'.$fakeRoot;
141 141
 			}
142 142
 		}
143 143
 		$this->fakeRoot = $fakeRoot;
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 		}
167 167
 
168 168
 		// missing slashes can cause wrong matches!
169
-		$root = rtrim($this->fakeRoot, '/') . '/';
169
+		$root = rtrim($this->fakeRoot, '/').'/';
170 170
 
171 171
 		if (!str_starts_with($path, $root)) {
172 172
 			return null;
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 *
224 224
 	 * @param string $path
225 225
 	 */
226
-	public function getLocalFile($path): string|false {
226
+	public function getLocalFile($path): string | false {
227 227
 		$parent = substr($path, 0, strrpos($path, '/') ?: 0);
228 228
 		$path = $this->getAbsolutePath($path);
229 229
 		[$storage, $internalPath] = Filesystem::resolvePath($path);
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
 		if ($mount instanceof MoveableMount) {
254 254
 			// cut of /user/files to get the relative path to data/user/files
255 255
 			$pathParts = explode('/', $path, 4);
256
-			$relPath = '/' . $pathParts[3];
256
+			$relPath = '/'.$pathParts[3];
257 257
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
258 258
 			\OC_Hook::emit(
259 259
 				Filesystem::CLASSNAME, "umount",
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 		}
683 683
 		$postFix = (substr($path, -1) === '/') ? '/' : '';
684 684
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
685
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
685
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
686 686
 		if ($mount->getInternalPath($absolutePath) === '') {
687 687
 			return $this->removeMount($mount, $absolutePath);
688 688
 		}
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 				$hooks[] = 'write';
960 960
 				break;
961 961
 			default:
962
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
962
+				$this->logger->error('invalid mode ('.$mode.') for '.$path, ['app' => 'core']);
963 963
 		}
964 964
 
965 965
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -983,7 +983,7 @@  discard block
 block discarded – undo
983 983
 	 * @param string $path
984 984
 	 * @throws InvalidPathException
985 985
 	 */
986
-	public function toTmpFile($path): string|false {
986
+	public function toTmpFile($path): string | false {
987 987
 		$this->assertPathLength($path);
988 988
 		if (Filesystem::isValidPath($path)) {
989 989
 			$source = $this->fopen($path, 'r');
@@ -1058,7 +1058,7 @@  discard block
 block discarded – undo
1058 1058
 	 * @param string $path
1059 1059
 	 * @param bool $raw
1060 1060
 	 */
1061
-	public function hash($type, $path, $raw = false): string|bool {
1061
+	public function hash($type, $path, $raw = false): string | bool {
1062 1062
 		$postFix = (substr($path, -1) === '/') ? '/' : '';
1063 1063
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1064 1064
 		if (Filesystem::isValidPath($path)) {
@@ -1074,7 +1074,7 @@  discard block
 block discarded – undo
1074 1074
 				);
1075 1075
 			}
1076 1076
 			/** @var Storage|null $storage */
1077
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1077
+			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath.$postFix);
1078 1078
 			if ($storage) {
1079 1079
 				return $storage->hash($type, $internalPath, $raw);
1080 1080
 			}
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
 			}
1125 1125
 
1126 1126
 			$run = $this->runHooks($hooks, $path);
1127
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1127
+			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath.$postFix);
1128 1128
 			if ($run && $storage) {
1129 1129
 				/** @var Storage $storage */
1130 1130
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
@@ -1170,7 +1170,7 @@  discard block
 block discarded – undo
1170 1170
 					$unlockLater = true;
1171 1171
 					// make sure our unlocking callback will still be called if connection is aborted
1172 1172
 					ignore_user_abort(true);
1173
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1173
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1174 1174
 						if (in_array('write', $hooks)) {
1175 1175
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1176 1176
 						} elseif (in_array('read', $hooks)) {
@@ -1232,7 +1232,7 @@  discard block
 block discarded – undo
1232 1232
 			return true;
1233 1233
 		}
1234 1234
 
1235
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1235
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1236 1236
 	}
1237 1237
 
1238 1238
 	/**
@@ -1251,7 +1251,7 @@  discard block
 block discarded – undo
1251 1251
 				if ($hook != 'read') {
1252 1252
 					\OC_Hook::emit(
1253 1253
 						Filesystem::CLASSNAME,
1254
-						$prefix . $hook,
1254
+						$prefix.$hook,
1255 1255
 						[
1256 1256
 							Filesystem::signal_param_run => &$run,
1257 1257
 							Filesystem::signal_param_path => $path
@@ -1260,7 +1260,7 @@  discard block
 block discarded – undo
1260 1260
 				} elseif (!$post) {
1261 1261
 					\OC_Hook::emit(
1262 1262
 						Filesystem::CLASSNAME,
1263
-						$prefix . $hook,
1263
+						$prefix.$hook,
1264 1264
 						[
1265 1265
 							Filesystem::signal_param_path => $path
1266 1266
 						]
@@ -1347,7 +1347,7 @@  discard block
 block discarded – undo
1347 1347
 			return $this->getPartFileInfo($path);
1348 1348
 		}
1349 1349
 		$relativePath = $path;
1350
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1350
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1351 1351
 
1352 1352
 		$mount = Filesystem::getMountManager()->find($path);
1353 1353
 		$storage = $mount->getStorage();
@@ -1380,7 +1380,7 @@  discard block
 block discarded – undo
1380 1380
 
1381 1381
 			return $info;
1382 1382
 		} else {
1383
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1383
+			$this->logger->warning('Storage not valid for mountpoint: '.$mount->getMountPoint(), ['app' => 'core']);
1384 1384
 		}
1385 1385
 
1386 1386
 		return false;
@@ -1391,7 +1391,7 @@  discard block
 block discarded – undo
1391 1391
 	 */
1392 1392
 	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1393 1393
 		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1394
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1394
+		$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1395 1395
 			$subStorage = $mount->getStorage();
1396 1396
 			return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1397 1397
 		}));
@@ -1440,18 +1440,18 @@  discard block
 block discarded – undo
1440 1440
 
1441 1441
 		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1442 1442
 
1443
-		$fileNames = array_map(function (ICacheEntry $content) {
1443
+		$fileNames = array_map(function(ICacheEntry $content) {
1444 1444
 			return $content->getName();
1445 1445
 		}, $contents);
1446 1446
 		/**
1447 1447
 		 * @var \OC\Files\FileInfo[] $fileInfos
1448 1448
 		 */
1449
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1449
+		$fileInfos = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1450 1450
 			if ($sharingDisabled) {
1451 1451
 				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1452 1452
 			}
1453 1453
 			$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1454
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1454
+			return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1455 1455
 		}, $contents);
1456 1456
 		$files = array_combine($fileNames, $fileInfos);
1457 1457
 
@@ -1475,7 +1475,7 @@  discard block
 block discarded – undo
1475 1475
 						continue;
1476 1476
 					} catch (\Exception $e) {
1477 1477
 						// sometimes when the storage is not available it can be any exception
1478
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1478
+						$this->logger->error('Exception while scanning storage "'.$subStorage->getId().'"', [
1479 1479
 							'exception' => $e,
1480 1480
 							'app' => 'core',
1481 1481
 						]);
@@ -1504,7 +1504,7 @@  discard block
 block discarded – undo
1504 1504
 							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1505 1505
 						}
1506 1506
 
1507
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1507
+						$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1508 1508
 
1509 1509
 						// if sharing was disabled for the user we remove the share permissions
1510 1510
 						if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1512,14 +1512,14 @@  discard block
 block discarded – undo
1512 1512
 						}
1513 1513
 
1514 1514
 						$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1515
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1515
+						$files[$rootEntry->getName()] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1516 1516
 					}
1517 1517
 				}
1518 1518
 			}
1519 1519
 		}
1520 1520
 
1521 1521
 		if ($mimetype_filter) {
1522
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1522
+			$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1523 1523
 				if (strpos($mimetype_filter, '/')) {
1524 1524
 					return $file->getMimetype() === $mimetype_filter;
1525 1525
 				} else {
@@ -1545,7 +1545,7 @@  discard block
 block discarded – undo
1545 1545
 		if ($data instanceof FileInfo) {
1546 1546
 			$data = $data->getData();
1547 1547
 		}
1548
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1548
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1549 1549
 		/**
1550 1550
 		 * @var Storage $storage
1551 1551
 		 * @var string $internalPath
@@ -1572,7 +1572,7 @@  discard block
 block discarded – undo
1572 1572
 	 * @return FileInfo[]
1573 1573
 	 */
1574 1574
 	public function search($query) {
1575
-		return $this->searchCommon('search', ['%' . $query . '%']);
1575
+		return $this->searchCommon('search', ['%'.$query.'%']);
1576 1576
 	}
1577 1577
 
1578 1578
 	/**
@@ -1624,10 +1624,10 @@  discard block
 block discarded – undo
1624 1624
 
1625 1625
 			$results = call_user_func_array([$cache, $method], $args);
1626 1626
 			foreach ($results as $result) {
1627
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1627
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1628 1628
 					$internalPath = $result['path'];
1629
-					$path = $mountPoint . $result['path'];
1630
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1629
+					$path = $mountPoint.$result['path'];
1630
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1631 1631
 					$owner = $userManager->get($storage->getOwner($internalPath));
1632 1632
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1633 1633
 				}
@@ -1645,8 +1645,8 @@  discard block
 block discarded – undo
1645 1645
 					if ($results) {
1646 1646
 						foreach ($results as $result) {
1647 1647
 							$internalPath = $result['path'];
1648
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1649
-							$path = rtrim($mountPoint . $internalPath, '/');
1648
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1649
+							$path = rtrim($mountPoint.$internalPath, '/');
1650 1650
 							$owner = $userManager->get($storage->getOwner($internalPath));
1651 1651
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1652 1652
 						}
@@ -1667,11 +1667,11 @@  discard block
 block discarded – undo
1667 1667
 	public function getOwner($path) {
1668 1668
 		$info = $this->getFileInfo($path);
1669 1669
 		if (!$info) {
1670
-			throw new NotFoundException($path . ' not found while trying to get owner');
1670
+			throw new NotFoundException($path.' not found while trying to get owner');
1671 1671
 		}
1672 1672
 
1673 1673
 		if ($info->getOwner() === null) {
1674
-			throw new NotFoundException($path . ' has no owner');
1674
+			throw new NotFoundException($path.' has no owner');
1675 1675
 		}
1676 1676
 
1677 1677
 		return $info->getOwner()->getUID();
@@ -1703,7 +1703,7 @@  discard block
 block discarded – undo
1703 1703
 	 * @throws NotFoundException
1704 1704
 	 */
1705 1705
 	public function getPath($id, int $storageId = null) {
1706
-		$id = (int)$id;
1706
+		$id = (int) $id;
1707 1707
 		$manager = Filesystem::getMountManager();
1708 1708
 		$mounts = $manager->findIn($this->fakeRoot);
1709 1709
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1714,12 +1714,12 @@  discard block
 block discarded – undo
1714 1714
 
1715 1715
 		// put non-shared mounts in front of the shared mount
1716 1716
 		// this prevents unneeded recursion into shares
1717
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1717
+		usort($mounts, function(IMountPoint $a, IMountPoint $b) {
1718 1718
 			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1719 1719
 		});
1720 1720
 
1721 1721
 		if (!is_null($storageId)) {
1722
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1722
+			$mounts = array_filter($mounts, function(IMountPoint $mount) use ($storageId) {
1723 1723
 				return $mount->getNumericStorageId() === $storageId;
1724 1724
 			});
1725 1725
 		}
@@ -1732,7 +1732,7 @@  discard block
 block discarded – undo
1732 1732
 				$cache = $mount->getStorage()->getCache();
1733 1733
 				$internalPath = $cache->getPathById($id);
1734 1734
 				if (is_string($internalPath)) {
1735
-					$fullPath = $mount->getMountPoint() . $internalPath;
1735
+					$fullPath = $mount->getMountPoint().$internalPath;
1736 1736
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1737 1737
 						return $path;
1738 1738
 					}
@@ -1772,7 +1772,7 @@  discard block
 block discarded – undo
1772 1772
 		// check if any of the parents were shared by the current owner (include collections)
1773 1773
 		$shares = Share::getItemShared(
1774 1774
 			'folder',
1775
-			(string)$fileId,
1775
+			(string) $fileId,
1776 1776
 			\OC\Share\Constants::FORMAT_NONE,
1777 1777
 			null,
1778 1778
 			true
@@ -1863,7 +1863,7 @@  discard block
 block discarded – undo
1863 1863
 		$resultPath = '';
1864 1864
 		foreach ($parts as $part) {
1865 1865
 			if ($part) {
1866
-				$resultPath .= '/' . $part;
1866
+				$resultPath .= '/'.$part;
1867 1867
 				$result[] = $resultPath;
1868 1868
 			}
1869 1869
 		}
@@ -2122,16 +2122,16 @@  discard block
 block discarded – undo
2122 2122
 	public function getUidAndFilename($filename) {
2123 2123
 		$info = $this->getFileInfo($filename);
2124 2124
 		if (!$info instanceof \OCP\Files\FileInfo) {
2125
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2125
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2126 2126
 		}
2127 2127
 		$uid = $info->getOwner()->getUID();
2128 2128
 		if ($uid != \OC_User::getUser()) {
2129 2129
 			Filesystem::initMountPoints($uid);
2130
-			$ownerView = new View('/' . $uid . '/files');
2130
+			$ownerView = new View('/'.$uid.'/files');
2131 2131
 			try {
2132 2132
 				$filename = $ownerView->getPath($info['fileid']);
2133 2133
 			} catch (NotFoundException $e) {
2134
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2134
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2135 2135
 			}
2136 2136
 		}
2137 2137
 		return [$uid, $filename];
@@ -2148,7 +2148,7 @@  discard block
 block discarded – undo
2148 2148
 		$directoryParts = array_filter($directoryParts);
2149 2149
 		foreach ($directoryParts as $key => $part) {
2150 2150
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2151
-			$currentPath = '/' . implode('/', $currentPathElements);
2151
+			$currentPath = '/'.implode('/', $currentPathElements);
2152 2152
 			if ($this->is_file($currentPath)) {
2153 2153
 				return false;
2154 2154
 			}
Please login to merge, or discard this patch.
lib/private/Federation/CloudIdManager.php 1 patch
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -43,209 +43,209 @@
 block discarded – undo
43 43
 use OCP\User\Events\UserChangedEvent;
44 44
 
45 45
 class CloudIdManager implements ICloudIdManager {
46
-	/** @var IManager */
47
-	private $contactsManager;
48
-	/** @var IURLGenerator */
49
-	private $urlGenerator;
50
-	/** @var IUserManager */
51
-	private $userManager;
52
-	private ICache $memCache;
53
-	/** @var array[] */
54
-	private array $cache = [];
55
-
56
-	public function __construct(
57
-		IManager $contactsManager,
58
-		IURLGenerator $urlGenerator,
59
-		IUserManager $userManager,
60
-		ICacheFactory $cacheFactory,
61
-		IEventDispatcher $eventDispatcher
62
-	) {
63
-		$this->contactsManager = $contactsManager;
64
-		$this->urlGenerator = $urlGenerator;
65
-		$this->userManager = $userManager;
66
-		$this->memCache = $cacheFactory->createDistributed('cloud_id_');
67
-		$eventDispatcher->addListener(UserChangedEvent::class, [$this, 'handleUserEvent']);
68
-		$eventDispatcher->addListener(CardUpdatedEvent::class, [$this, 'handleCardEvent']);
69
-	}
70
-
71
-	public function handleUserEvent(Event $event): void {
72
-		if ($event instanceof UserChangedEvent && $event->getFeature() === 'displayName') {
73
-			$userId = $event->getUser()->getUID();
74
-			$key = $userId . '@local';
75
-			unset($this->cache[$key]);
76
-			$this->memCache->remove($key);
77
-		}
78
-	}
79
-
80
-	public function handleCardEvent(Event $event): void {
81
-		if ($event instanceof CardUpdatedEvent) {
82
-			$data = $event->getCardData()['carddata'];
83
-			foreach (explode("\r\n", $data) as $line) {
84
-				if (str_starts_with($line, "CLOUD;")) {
85
-					$parts = explode(':', $line, 2);
86
-					if (isset($parts[1])) {
87
-						$key = $parts[1];
88
-						unset($this->cache[$key]);
89
-						$this->memCache->remove($key);
90
-					}
91
-				}
92
-			}
93
-		}
94
-	}
95
-
96
-	/**
97
-	 * @param string $cloudId
98
-	 * @return ICloudId
99
-	 * @throws \InvalidArgumentException
100
-	 */
101
-	public function resolveCloudId(string $cloudId): ICloudId {
102
-		// TODO magic here to get the url and user instead of just splitting on @
103
-
104
-		if (!$this->isValidCloudId($cloudId)) {
105
-			throw new \InvalidArgumentException('Invalid cloud id');
106
-		}
107
-
108
-		// Find the first character that is not allowed in user names
109
-		$id = $this->fixRemoteURL($cloudId);
110
-		$posSlash = strpos($id, '/');
111
-		$posColon = strpos($id, ':');
112
-
113
-		if ($posSlash === false && $posColon === false) {
114
-			$invalidPos = \strlen($id);
115
-		} elseif ($posSlash === false) {
116
-			$invalidPos = $posColon;
117
-		} elseif ($posColon === false) {
118
-			$invalidPos = $posSlash;
119
-		} else {
120
-			$invalidPos = min($posSlash, $posColon);
121
-		}
122
-
123
-		$lastValidAtPos = strrpos($id, '@', $invalidPos - strlen($id));
124
-
125
-		if ($lastValidAtPos !== false) {
126
-			$user = substr($id, 0, $lastValidAtPos);
127
-			$remote = substr($id, $lastValidAtPos + 1);
128
-
129
-			$this->userManager->validateUserId($user);
130
-
131
-			if (!empty($user) && !empty($remote)) {
132
-				return new CloudId($id, $user, $remote, $this->getDisplayNameFromContact($id));
133
-			}
134
-		}
135
-		throw new \InvalidArgumentException('Invalid cloud id');
136
-	}
137
-
138
-	protected function getDisplayNameFromContact(string $cloudId): ?string {
139
-		$addressBookEntries = $this->contactsManager->search($cloudId, ['CLOUD'], [
140
-			'limit' => 1,
141
-			'enumeration' => false,
142
-			'fullmatch' => false,
143
-			'strict_search' => true,
144
-		]);
145
-		foreach ($addressBookEntries as $entry) {
146
-			if (isset($entry['CLOUD'])) {
147
-				foreach ($entry['CLOUD'] as $cloudID) {
148
-					if ($cloudID === $cloudId) {
149
-						// Warning, if user decides to make his full name local only,
150
-						// no FN is found on federated servers
151
-						if (isset($entry['FN'])) {
152
-							return $entry['FN'];
153
-						} else {
154
-							return $cloudID;
155
-						}
156
-					}
157
-				}
158
-			}
159
-		}
160
-		return null;
161
-	}
162
-
163
-	/**
164
-	 * @param string $user
165
-	 * @param string|null $remote
166
-	 * @return CloudId
167
-	 */
168
-	public function getCloudId(string $user, ?string $remote): ICloudId {
169
-		$isLocal = $remote === null;
170
-		if ($isLocal) {
171
-			$remote = rtrim($this->removeProtocolFromUrl($this->urlGenerator->getAbsoluteURL('/')), '/');
172
-			$fixedRemote = $this->fixRemoteURL($remote);
173
-			$host = $fixedRemote;
174
-		} else {
175
-			// note that for remote id's we don't strip the protocol for the remote we use to construct the CloudId
176
-			// this way if a user has an explicit non-https cloud id this will be preserved
177
-			// we do still use the version without protocol for looking up the display name
178
-			$fixedRemote = $this->fixRemoteURL($remote);
179
-			$host = $this->removeProtocolFromUrl($fixedRemote);
180
-		}
181
-
182
-		$key = $user . '@' . ($isLocal ? 'local' : $host);
183
-		$cached = $this->cache[$key] ?? $this->memCache->get($key);
184
-		if ($cached) {
185
-			$this->cache[$key] = $cached; // put items from memcache into local cache
186
-			return new CloudId($cached['id'], $cached['user'], $cached['remote'], $cached['displayName']);
187
-		}
188
-
189
-		if ($isLocal) {
190
-			$localUser = $this->userManager->get($user);
191
-			$displayName = $localUser ? $localUser->getDisplayName() : '';
192
-		} else {
193
-			$displayName = $this->getDisplayNameFromContact($user . '@' . $host);
194
-		}
195
-		$id = $user . '@' . $remote;
196
-
197
-		$data = [
198
-			'id' => $id,
199
-			'user' => $user,
200
-			'remote' => $fixedRemote,
201
-			'displayName' => $displayName,
202
-		];
203
-		$this->cache[$key] = $data;
204
-		$this->memCache->set($key, $data, 15 * 60);
205
-		return new CloudId($id, $user, $fixedRemote, $displayName);
206
-	}
207
-
208
-	/**
209
-	 * @param string $url
210
-	 * @return string
211
-	 */
212
-	private function removeProtocolFromUrl($url) {
213
-		if (str_starts_with($url, 'https://')) {
214
-			return substr($url, strlen('https://'));
215
-		} elseif (str_starts_with($url, 'http://')) {
216
-			return substr($url, strlen('http://'));
217
-		}
218
-
219
-		return $url;
220
-	}
221
-
222
-	/**
223
-	 * Strips away a potential file names and trailing slashes:
224
-	 * - http://localhost
225
-	 * - http://localhost/
226
-	 * - http://localhost/index.php
227
-	 * - http://localhost/index.php/s/{shareToken}
228
-	 *
229
-	 * all return: http://localhost
230
-	 *
231
-	 * @param string $remote
232
-	 * @return string
233
-	 */
234
-	protected function fixRemoteURL(string $remote): string {
235
-		$remote = str_replace('\\', '/', $remote);
236
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
237
-			$remote = substr($remote, 0, $fileNamePosition);
238
-		}
239
-		$remote = rtrim($remote, '/');
240
-
241
-		return $remote;
242
-	}
243
-
244
-	/**
245
-	 * @param string $cloudId
246
-	 * @return bool
247
-	 */
248
-	public function isValidCloudId(string $cloudId): bool {
249
-		return str_contains($cloudId, '@');
250
-	}
46
+    /** @var IManager */
47
+    private $contactsManager;
48
+    /** @var IURLGenerator */
49
+    private $urlGenerator;
50
+    /** @var IUserManager */
51
+    private $userManager;
52
+    private ICache $memCache;
53
+    /** @var array[] */
54
+    private array $cache = [];
55
+
56
+    public function __construct(
57
+        IManager $contactsManager,
58
+        IURLGenerator $urlGenerator,
59
+        IUserManager $userManager,
60
+        ICacheFactory $cacheFactory,
61
+        IEventDispatcher $eventDispatcher
62
+    ) {
63
+        $this->contactsManager = $contactsManager;
64
+        $this->urlGenerator = $urlGenerator;
65
+        $this->userManager = $userManager;
66
+        $this->memCache = $cacheFactory->createDistributed('cloud_id_');
67
+        $eventDispatcher->addListener(UserChangedEvent::class, [$this, 'handleUserEvent']);
68
+        $eventDispatcher->addListener(CardUpdatedEvent::class, [$this, 'handleCardEvent']);
69
+    }
70
+
71
+    public function handleUserEvent(Event $event): void {
72
+        if ($event instanceof UserChangedEvent && $event->getFeature() === 'displayName') {
73
+            $userId = $event->getUser()->getUID();
74
+            $key = $userId . '@local';
75
+            unset($this->cache[$key]);
76
+            $this->memCache->remove($key);
77
+        }
78
+    }
79
+
80
+    public function handleCardEvent(Event $event): void {
81
+        if ($event instanceof CardUpdatedEvent) {
82
+            $data = $event->getCardData()['carddata'];
83
+            foreach (explode("\r\n", $data) as $line) {
84
+                if (str_starts_with($line, "CLOUD;")) {
85
+                    $parts = explode(':', $line, 2);
86
+                    if (isset($parts[1])) {
87
+                        $key = $parts[1];
88
+                        unset($this->cache[$key]);
89
+                        $this->memCache->remove($key);
90
+                    }
91
+                }
92
+            }
93
+        }
94
+    }
95
+
96
+    /**
97
+     * @param string $cloudId
98
+     * @return ICloudId
99
+     * @throws \InvalidArgumentException
100
+     */
101
+    public function resolveCloudId(string $cloudId): ICloudId {
102
+        // TODO magic here to get the url and user instead of just splitting on @
103
+
104
+        if (!$this->isValidCloudId($cloudId)) {
105
+            throw new \InvalidArgumentException('Invalid cloud id');
106
+        }
107
+
108
+        // Find the first character that is not allowed in user names
109
+        $id = $this->fixRemoteURL($cloudId);
110
+        $posSlash = strpos($id, '/');
111
+        $posColon = strpos($id, ':');
112
+
113
+        if ($posSlash === false && $posColon === false) {
114
+            $invalidPos = \strlen($id);
115
+        } elseif ($posSlash === false) {
116
+            $invalidPos = $posColon;
117
+        } elseif ($posColon === false) {
118
+            $invalidPos = $posSlash;
119
+        } else {
120
+            $invalidPos = min($posSlash, $posColon);
121
+        }
122
+
123
+        $lastValidAtPos = strrpos($id, '@', $invalidPos - strlen($id));
124
+
125
+        if ($lastValidAtPos !== false) {
126
+            $user = substr($id, 0, $lastValidAtPos);
127
+            $remote = substr($id, $lastValidAtPos + 1);
128
+
129
+            $this->userManager->validateUserId($user);
130
+
131
+            if (!empty($user) && !empty($remote)) {
132
+                return new CloudId($id, $user, $remote, $this->getDisplayNameFromContact($id));
133
+            }
134
+        }
135
+        throw new \InvalidArgumentException('Invalid cloud id');
136
+    }
137
+
138
+    protected function getDisplayNameFromContact(string $cloudId): ?string {
139
+        $addressBookEntries = $this->contactsManager->search($cloudId, ['CLOUD'], [
140
+            'limit' => 1,
141
+            'enumeration' => false,
142
+            'fullmatch' => false,
143
+            'strict_search' => true,
144
+        ]);
145
+        foreach ($addressBookEntries as $entry) {
146
+            if (isset($entry['CLOUD'])) {
147
+                foreach ($entry['CLOUD'] as $cloudID) {
148
+                    if ($cloudID === $cloudId) {
149
+                        // Warning, if user decides to make his full name local only,
150
+                        // no FN is found on federated servers
151
+                        if (isset($entry['FN'])) {
152
+                            return $entry['FN'];
153
+                        } else {
154
+                            return $cloudID;
155
+                        }
156
+                    }
157
+                }
158
+            }
159
+        }
160
+        return null;
161
+    }
162
+
163
+    /**
164
+     * @param string $user
165
+     * @param string|null $remote
166
+     * @return CloudId
167
+     */
168
+    public function getCloudId(string $user, ?string $remote): ICloudId {
169
+        $isLocal = $remote === null;
170
+        if ($isLocal) {
171
+            $remote = rtrim($this->removeProtocolFromUrl($this->urlGenerator->getAbsoluteURL('/')), '/');
172
+            $fixedRemote = $this->fixRemoteURL($remote);
173
+            $host = $fixedRemote;
174
+        } else {
175
+            // note that for remote id's we don't strip the protocol for the remote we use to construct the CloudId
176
+            // this way if a user has an explicit non-https cloud id this will be preserved
177
+            // we do still use the version without protocol for looking up the display name
178
+            $fixedRemote = $this->fixRemoteURL($remote);
179
+            $host = $this->removeProtocolFromUrl($fixedRemote);
180
+        }
181
+
182
+        $key = $user . '@' . ($isLocal ? 'local' : $host);
183
+        $cached = $this->cache[$key] ?? $this->memCache->get($key);
184
+        if ($cached) {
185
+            $this->cache[$key] = $cached; // put items from memcache into local cache
186
+            return new CloudId($cached['id'], $cached['user'], $cached['remote'], $cached['displayName']);
187
+        }
188
+
189
+        if ($isLocal) {
190
+            $localUser = $this->userManager->get($user);
191
+            $displayName = $localUser ? $localUser->getDisplayName() : '';
192
+        } else {
193
+            $displayName = $this->getDisplayNameFromContact($user . '@' . $host);
194
+        }
195
+        $id = $user . '@' . $remote;
196
+
197
+        $data = [
198
+            'id' => $id,
199
+            'user' => $user,
200
+            'remote' => $fixedRemote,
201
+            'displayName' => $displayName,
202
+        ];
203
+        $this->cache[$key] = $data;
204
+        $this->memCache->set($key, $data, 15 * 60);
205
+        return new CloudId($id, $user, $fixedRemote, $displayName);
206
+    }
207
+
208
+    /**
209
+     * @param string $url
210
+     * @return string
211
+     */
212
+    private function removeProtocolFromUrl($url) {
213
+        if (str_starts_with($url, 'https://')) {
214
+            return substr($url, strlen('https://'));
215
+        } elseif (str_starts_with($url, 'http://')) {
216
+            return substr($url, strlen('http://'));
217
+        }
218
+
219
+        return $url;
220
+    }
221
+
222
+    /**
223
+     * Strips away a potential file names and trailing slashes:
224
+     * - http://localhost
225
+     * - http://localhost/
226
+     * - http://localhost/index.php
227
+     * - http://localhost/index.php/s/{shareToken}
228
+     *
229
+     * all return: http://localhost
230
+     *
231
+     * @param string $remote
232
+     * @return string
233
+     */
234
+    protected function fixRemoteURL(string $remote): string {
235
+        $remote = str_replace('\\', '/', $remote);
236
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
237
+            $remote = substr($remote, 0, $fileNamePosition);
238
+        }
239
+        $remote = rtrim($remote, '/');
240
+
241
+        return $remote;
242
+    }
243
+
244
+    /**
245
+     * @param string $cloudId
246
+     * @return bool
247
+     */
248
+    public function isValidCloudId(string $cloudId): bool {
249
+        return str_contains($cloudId, '@');
250
+    }
251 251
 }
Please login to merge, or discard this patch.
lib/private/Profiler/FileProfilerStorage.php 1 patch
Indentation   +252 added lines, -252 removed lines patch added patch discarded remove patch
@@ -32,256 +32,256 @@
 block discarded – undo
32 32
  * Storage for profiler using files.
33 33
  */
34 34
 class FileProfilerStorage {
35
-	// Folder where profiler data are stored.
36
-	private string $folder;
37
-
38
-	/**
39
-	 * Constructs the file storage using a "dsn-like" path.
40
-	 *
41
-	 * Example : "file:/path/to/the/storage/folder"
42
-	 *
43
-	 * @throws \RuntimeException
44
-	 */
45
-	public function __construct(string $folder) {
46
-		$this->folder = $folder;
47
-
48
-		if (!is_dir($this->folder) && false === @mkdir($this->folder, 0777, true) && !is_dir($this->folder)) {
49
-			throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $this->folder));
50
-		}
51
-	}
52
-
53
-	public function find(?string $url, ?int $limit, ?string $method, int $start = null, int $end = null, string $statusCode = null): array {
54
-		$file = $this->getIndexFilename();
55
-
56
-		if (!file_exists($file)) {
57
-			return [];
58
-		}
59
-
60
-		$file = fopen($file, 'r');
61
-		fseek($file, 0, \SEEK_END);
62
-
63
-		$result = [];
64
-		while (\count($result) < $limit && $line = $this->readLineFromFile($file)) {
65
-			$values = str_getcsv($line);
66
-			[$csvToken, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode] = $values;
67
-			$csvTime = (int) $csvTime;
68
-
69
-			if ($url && !str_contains($csvUrl, $url) || $method && !str_contains($csvMethod, $method) || $statusCode && !str_contains($csvStatusCode, $statusCode)) {
70
-				continue;
71
-			}
72
-
73
-			if (!empty($start) && $csvTime < $start) {
74
-				continue;
75
-			}
76
-
77
-			if (!empty($end) && $csvTime > $end) {
78
-				continue;
79
-			}
80
-
81
-			$result[$csvToken] = [
82
-				'token' => $csvToken,
83
-				'method' => $csvMethod,
84
-				'url' => $csvUrl,
85
-				'time' => $csvTime,
86
-				'parent' => $csvParent,
87
-				'status_code' => $csvStatusCode,
88
-			];
89
-		}
90
-
91
-		fclose($file);
92
-
93
-		return array_values($result);
94
-	}
95
-
96
-	public function purge(): void {
97
-		$flags = \FilesystemIterator::SKIP_DOTS;
98
-		$iterator = new \RecursiveDirectoryIterator($this->folder, $flags);
99
-		$iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST);
100
-
101
-		foreach ($iterator as $file) {
102
-			$file = (string)$file->getPathInfo();
103
-			if (is_file($file)) {
104
-				unlink($file);
105
-			} else {
106
-				rmdir($file);
107
-			}
108
-		}
109
-	}
110
-
111
-	public function read(string $token): ?IProfile {
112
-		if (!$token || !file_exists($file = $this->getFilename($token))) {
113
-			return null;
114
-		}
115
-
116
-		if (\function_exists('gzcompress')) {
117
-			$file = 'compress.zlib://'.$file;
118
-		}
119
-
120
-		return $this->createProfileFromData($token, unserialize(file_get_contents($file)));
121
-	}
122
-
123
-	/**
124
-	 * @throws \RuntimeException
125
-	 */
126
-	public function write(IProfile $profile): bool {
127
-		$file = $this->getFilename($profile->getToken());
128
-
129
-		$profileIndexed = is_file($file);
130
-		if (!$profileIndexed) {
131
-			// Create directory
132
-			$dir = \dirname($file);
133
-			if (!is_dir($dir) && false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
134
-				throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));
135
-			}
136
-		}
137
-
138
-		$profileToken = $profile->getToken();
139
-		// when there are errors in sub-requests, the parent and/or children tokens
140
-		// may equal the profile token, resulting in infinite loops
141
-		$parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null;
142
-		$childrenToken = array_filter(array_map(function (IProfile $p) use ($profileToken) {
143
-			return $profileToken !== $p->getToken() ? $p->getToken() : null;
144
-		}, $profile->getChildren()));
145
-
146
-		// Store profile
147
-		$data = [
148
-			'token' => $profileToken,
149
-			'parent' => $parentToken,
150
-			'children' => $childrenToken,
151
-			'data' => $profile->getCollectors(),
152
-			'method' => $profile->getMethod(),
153
-			'url' => $profile->getUrl(),
154
-			'time' => $profile->getTime(),
155
-			'status_code' => $profile->getStatusCode(),
156
-		];
157
-
158
-		$context = stream_context_create();
159
-
160
-		if (\function_exists('gzcompress')) {
161
-			$file = 'compress.zlib://'.$file;
162
-			stream_context_set_option($context, 'zlib', 'level', 3);
163
-		}
164
-
165
-		if (false === file_put_contents($file, serialize($data), 0, $context)) {
166
-			return false;
167
-		}
168
-
169
-		if (!$profileIndexed) {
170
-			// Add to index
171
-			if (false === $file = fopen($this->getIndexFilename(), 'a')) {
172
-				return false;
173
-			}
174
-
175
-			fputcsv($file, [
176
-				$profile->getToken(),
177
-				$profile->getMethod(),
178
-				$profile->getUrl(),
179
-				$profile->getTime(),
180
-				$profile->getParentToken(),
181
-				$profile->getStatusCode(),
182
-			]);
183
-			fclose($file);
184
-		}
185
-
186
-		return true;
187
-	}
188
-
189
-	/**
190
-	 * Gets filename to store data, associated to the token.
191
-	 *
192
-	 * @return string The profile filename
193
-	 */
194
-	protected function getFilename(string $token): string {
195
-		// Uses 4 last characters, because first are mostly the same.
196
-		$folderA = substr($token, -2, 2);
197
-		$folderB = substr($token, -4, 2);
198
-
199
-		return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token;
200
-	}
201
-
202
-	/**
203
-	 * Gets the index filename.
204
-	 *
205
-	 * @return string The index filename
206
-	 */
207
-	protected function getIndexFilename(): string {
208
-		return $this->folder.'/index.csv';
209
-	}
210
-
211
-	/**
212
-	 * Reads a line in the file, backward.
213
-	 *
214
-	 * This function automatically skips the empty lines and do not include the line return in result value.
215
-	 *
216
-	 * @param resource $file The file resource, with the pointer placed at the end of the line to read
217
-	 *
218
-	 * @return ?string A string representing the line or null if beginning of file is reached
219
-	 */
220
-	protected function readLineFromFile($file): ?string {
221
-		$line = '';
222
-		$position = ftell($file);
223
-
224
-		if (0 === $position) {
225
-			return null;
226
-		}
227
-
228
-		while (true) {
229
-			$chunkSize = min($position, 1024);
230
-			$position -= $chunkSize;
231
-			fseek($file, $position);
232
-
233
-			if (0 === $chunkSize) {
234
-				// bof reached
235
-				break;
236
-			}
237
-
238
-			$buffer = fread($file, $chunkSize);
239
-
240
-			if (false === ($upTo = strrpos($buffer, "\n"))) {
241
-				$line = $buffer.$line;
242
-				continue;
243
-			}
244
-
245
-			$position += $upTo;
246
-			$line = substr($buffer, $upTo + 1).$line;
247
-			fseek($file, max(0, $position), \SEEK_SET);
248
-
249
-			if ('' !== $line) {
250
-				break;
251
-			}
252
-		}
253
-
254
-		return '' === $line ? null : $line;
255
-	}
256
-
257
-	protected function createProfileFromData(string $token, array $data, IProfile $parent = null): IProfile {
258
-		$profile = new Profile($token);
259
-		$profile->setMethod($data['method']);
260
-		$profile->setUrl($data['url']);
261
-		$profile->setTime($data['time']);
262
-		$profile->setStatusCode($data['status_code']);
263
-		$profile->setCollectors($data['data']);
264
-
265
-		if (!$parent && $data['parent']) {
266
-			$parent = $this->read($data['parent']);
267
-		}
268
-
269
-		if ($parent) {
270
-			$profile->setParent($parent);
271
-		}
272
-
273
-		foreach ($data['children'] as $token) {
274
-			if (!$token || !file_exists($file = $this->getFilename($token))) {
275
-				continue;
276
-			}
277
-
278
-			if (\function_exists('gzcompress')) {
279
-				$file = 'compress.zlib://'.$file;
280
-			}
281
-
282
-			$profile->addChild($this->createProfileFromData($token, unserialize(file_get_contents($file)), $profile));
283
-		}
284
-
285
-		return $profile;
286
-	}
35
+    // Folder where profiler data are stored.
36
+    private string $folder;
37
+
38
+    /**
39
+     * Constructs the file storage using a "dsn-like" path.
40
+     *
41
+     * Example : "file:/path/to/the/storage/folder"
42
+     *
43
+     * @throws \RuntimeException
44
+     */
45
+    public function __construct(string $folder) {
46
+        $this->folder = $folder;
47
+
48
+        if (!is_dir($this->folder) && false === @mkdir($this->folder, 0777, true) && !is_dir($this->folder)) {
49
+            throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $this->folder));
50
+        }
51
+    }
52
+
53
+    public function find(?string $url, ?int $limit, ?string $method, int $start = null, int $end = null, string $statusCode = null): array {
54
+        $file = $this->getIndexFilename();
55
+
56
+        if (!file_exists($file)) {
57
+            return [];
58
+        }
59
+
60
+        $file = fopen($file, 'r');
61
+        fseek($file, 0, \SEEK_END);
62
+
63
+        $result = [];
64
+        while (\count($result) < $limit && $line = $this->readLineFromFile($file)) {
65
+            $values = str_getcsv($line);
66
+            [$csvToken, $csvMethod, $csvUrl, $csvTime, $csvParent, $csvStatusCode] = $values;
67
+            $csvTime = (int) $csvTime;
68
+
69
+            if ($url && !str_contains($csvUrl, $url) || $method && !str_contains($csvMethod, $method) || $statusCode && !str_contains($csvStatusCode, $statusCode)) {
70
+                continue;
71
+            }
72
+
73
+            if (!empty($start) && $csvTime < $start) {
74
+                continue;
75
+            }
76
+
77
+            if (!empty($end) && $csvTime > $end) {
78
+                continue;
79
+            }
80
+
81
+            $result[$csvToken] = [
82
+                'token' => $csvToken,
83
+                'method' => $csvMethod,
84
+                'url' => $csvUrl,
85
+                'time' => $csvTime,
86
+                'parent' => $csvParent,
87
+                'status_code' => $csvStatusCode,
88
+            ];
89
+        }
90
+
91
+        fclose($file);
92
+
93
+        return array_values($result);
94
+    }
95
+
96
+    public function purge(): void {
97
+        $flags = \FilesystemIterator::SKIP_DOTS;
98
+        $iterator = new \RecursiveDirectoryIterator($this->folder, $flags);
99
+        $iterator = new \RecursiveIteratorIterator($iterator, \RecursiveIteratorIterator::CHILD_FIRST);
100
+
101
+        foreach ($iterator as $file) {
102
+            $file = (string)$file->getPathInfo();
103
+            if (is_file($file)) {
104
+                unlink($file);
105
+            } else {
106
+                rmdir($file);
107
+            }
108
+        }
109
+    }
110
+
111
+    public function read(string $token): ?IProfile {
112
+        if (!$token || !file_exists($file = $this->getFilename($token))) {
113
+            return null;
114
+        }
115
+
116
+        if (\function_exists('gzcompress')) {
117
+            $file = 'compress.zlib://'.$file;
118
+        }
119
+
120
+        return $this->createProfileFromData($token, unserialize(file_get_contents($file)));
121
+    }
122
+
123
+    /**
124
+     * @throws \RuntimeException
125
+     */
126
+    public function write(IProfile $profile): bool {
127
+        $file = $this->getFilename($profile->getToken());
128
+
129
+        $profileIndexed = is_file($file);
130
+        if (!$profileIndexed) {
131
+            // Create directory
132
+            $dir = \dirname($file);
133
+            if (!is_dir($dir) && false === @mkdir($dir, 0777, true) && !is_dir($dir)) {
134
+                throw new \RuntimeException(sprintf('Unable to create the storage directory (%s).', $dir));
135
+            }
136
+        }
137
+
138
+        $profileToken = $profile->getToken();
139
+        // when there are errors in sub-requests, the parent and/or children tokens
140
+        // may equal the profile token, resulting in infinite loops
141
+        $parentToken = $profile->getParentToken() !== $profileToken ? $profile->getParentToken() : null;
142
+        $childrenToken = array_filter(array_map(function (IProfile $p) use ($profileToken) {
143
+            return $profileToken !== $p->getToken() ? $p->getToken() : null;
144
+        }, $profile->getChildren()));
145
+
146
+        // Store profile
147
+        $data = [
148
+            'token' => $profileToken,
149
+            'parent' => $parentToken,
150
+            'children' => $childrenToken,
151
+            'data' => $profile->getCollectors(),
152
+            'method' => $profile->getMethod(),
153
+            'url' => $profile->getUrl(),
154
+            'time' => $profile->getTime(),
155
+            'status_code' => $profile->getStatusCode(),
156
+        ];
157
+
158
+        $context = stream_context_create();
159
+
160
+        if (\function_exists('gzcompress')) {
161
+            $file = 'compress.zlib://'.$file;
162
+            stream_context_set_option($context, 'zlib', 'level', 3);
163
+        }
164
+
165
+        if (false === file_put_contents($file, serialize($data), 0, $context)) {
166
+            return false;
167
+        }
168
+
169
+        if (!$profileIndexed) {
170
+            // Add to index
171
+            if (false === $file = fopen($this->getIndexFilename(), 'a')) {
172
+                return false;
173
+            }
174
+
175
+            fputcsv($file, [
176
+                $profile->getToken(),
177
+                $profile->getMethod(),
178
+                $profile->getUrl(),
179
+                $profile->getTime(),
180
+                $profile->getParentToken(),
181
+                $profile->getStatusCode(),
182
+            ]);
183
+            fclose($file);
184
+        }
185
+
186
+        return true;
187
+    }
188
+
189
+    /**
190
+     * Gets filename to store data, associated to the token.
191
+     *
192
+     * @return string The profile filename
193
+     */
194
+    protected function getFilename(string $token): string {
195
+        // Uses 4 last characters, because first are mostly the same.
196
+        $folderA = substr($token, -2, 2);
197
+        $folderB = substr($token, -4, 2);
198
+
199
+        return $this->folder.'/'.$folderA.'/'.$folderB.'/'.$token;
200
+    }
201
+
202
+    /**
203
+     * Gets the index filename.
204
+     *
205
+     * @return string The index filename
206
+     */
207
+    protected function getIndexFilename(): string {
208
+        return $this->folder.'/index.csv';
209
+    }
210
+
211
+    /**
212
+     * Reads a line in the file, backward.
213
+     *
214
+     * This function automatically skips the empty lines and do not include the line return in result value.
215
+     *
216
+     * @param resource $file The file resource, with the pointer placed at the end of the line to read
217
+     *
218
+     * @return ?string A string representing the line or null if beginning of file is reached
219
+     */
220
+    protected function readLineFromFile($file): ?string {
221
+        $line = '';
222
+        $position = ftell($file);
223
+
224
+        if (0 === $position) {
225
+            return null;
226
+        }
227
+
228
+        while (true) {
229
+            $chunkSize = min($position, 1024);
230
+            $position -= $chunkSize;
231
+            fseek($file, $position);
232
+
233
+            if (0 === $chunkSize) {
234
+                // bof reached
235
+                break;
236
+            }
237
+
238
+            $buffer = fread($file, $chunkSize);
239
+
240
+            if (false === ($upTo = strrpos($buffer, "\n"))) {
241
+                $line = $buffer.$line;
242
+                continue;
243
+            }
244
+
245
+            $position += $upTo;
246
+            $line = substr($buffer, $upTo + 1).$line;
247
+            fseek($file, max(0, $position), \SEEK_SET);
248
+
249
+            if ('' !== $line) {
250
+                break;
251
+            }
252
+        }
253
+
254
+        return '' === $line ? null : $line;
255
+    }
256
+
257
+    protected function createProfileFromData(string $token, array $data, IProfile $parent = null): IProfile {
258
+        $profile = new Profile($token);
259
+        $profile->setMethod($data['method']);
260
+        $profile->setUrl($data['url']);
261
+        $profile->setTime($data['time']);
262
+        $profile->setStatusCode($data['status_code']);
263
+        $profile->setCollectors($data['data']);
264
+
265
+        if (!$parent && $data['parent']) {
266
+            $parent = $this->read($data['parent']);
267
+        }
268
+
269
+        if ($parent) {
270
+            $profile->setParent($parent);
271
+        }
272
+
273
+        foreach ($data['children'] as $token) {
274
+            if (!$token || !file_exists($file = $this->getFilename($token))) {
275
+                continue;
276
+            }
277
+
278
+            if (\function_exists('gzcompress')) {
279
+                $file = 'compress.zlib://'.$file;
280
+            }
281
+
282
+            $profile->addChild($this->createProfileFromData($token, unserialize(file_get_contents($file)), $profile));
283
+        }
284
+
285
+        return $profile;
286
+    }
287 287
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/Search.php 1 patch
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -35,111 +35,111 @@
 block discarded – undo
35 35
 use OCP\Share;
36 36
 
37 37
 class Search implements ISearch {
38
-	/** @var IContainer */
39
-	private $c;
40
-
41
-	protected $pluginList = [];
42
-
43
-	public function __construct(IContainer $c) {
44
-		$this->c = $c;
45
-	}
46
-
47
-	/**
48
-	 * @param string $search
49
-	 * @param array $shareTypes
50
-	 * @param bool $lookup
51
-	 * @param int|null $limit
52
-	 * @param int|null $offset
53
-	 * @return array
54
-	 * @throws \OCP\AppFramework\QueryException
55
-	 */
56
-	public function search($search, array $shareTypes, $lookup, $limit, $offset) {
57
-		$hasMoreResults = false;
58
-
59
-		// Trim leading and trailing whitespace characters, e.g. when query is copy-pasted
60
-		$search = trim($search);
61
-
62
-		/** @var ISearchResult $searchResult */
63
-		$searchResult = $this->c->resolve(SearchResult::class);
64
-
65
-		foreach ($shareTypes as $type) {
66
-			if (!isset($this->pluginList[$type])) {
67
-				continue;
68
-			}
69
-			foreach ($this->pluginList[$type] as $plugin) {
70
-				/** @var ISearchPlugin $searchPlugin */
71
-				$searchPlugin = $this->c->resolve($plugin);
72
-				$hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
73
-			}
74
-		}
75
-
76
-		// Get from lookup server, not a separate share type
77
-		if ($lookup) {
78
-			$searchPlugin = $this->c->resolve(LookupPlugin::class);
79
-			$hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
80
-		}
81
-
82
-		// sanitizing, could go into the plugins as well
83
-
84
-		// if we have an exact match, either for the federated cloud id or for the
85
-		// email address, we only return the exact match. It is highly unlikely
86
-		// that the exact same email address and federated cloud id exists
87
-		$emailType = new SearchResultType('emails');
88
-		$remoteType = new SearchResultType('remotes');
89
-		if ($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) {
90
-			$searchResult->unsetResult($remoteType);
91
-		} elseif (!$searchResult->hasExactIdMatch($emailType) && $searchResult->hasExactIdMatch($remoteType)) {
92
-			$searchResult->unsetResult($emailType);
93
-		}
94
-
95
-		$this->dropMailSharesWhereRemoteShareIsPossible($searchResult);
96
-
97
-		// if we have an exact local user match with an email-a-like query,
98
-		// there is no need to show the remote and email matches.
99
-		$userType = new SearchResultType('users');
100
-		if (str_contains($search, '@') && $searchResult->hasExactIdMatch($userType)) {
101
-			$searchResult->unsetResult($remoteType);
102
-			$searchResult->unsetResult($emailType);
103
-		}
104
-
105
-		return [$searchResult->asArray(), $hasMoreResults];
106
-	}
107
-
108
-	public function registerPlugin(array $pluginInfo) {
109
-		$shareType = constant(Share::class . '::' . $pluginInfo['shareType']);
110
-		if ($shareType === null) {
111
-			throw new \InvalidArgumentException('Provided ShareType is invalid');
112
-		}
113
-		$this->pluginList[$shareType][] = $pluginInfo['class'];
114
-	}
115
-
116
-	protected function dropMailSharesWhereRemoteShareIsPossible(ISearchResult $searchResult): void {
117
-		$allResults = $searchResult->asArray();
118
-
119
-		$emailType = new SearchResultType('emails');
120
-		$remoteType = new SearchResultType('remotes');
121
-
122
-		if (!isset($allResults[$remoteType->getLabel()])
123
-			|| !isset($allResults[$emailType->getLabel()])) {
124
-			return;
125
-		}
126
-
127
-		$mailIdMap = [];
128
-		foreach ($allResults[$emailType->getLabel()] as $mailRow) {
129
-			// sure, array_reduce looks nicer, but foreach needs less resources and is faster
130
-			if (!isset($mailRow['uuid'])) {
131
-				continue;
132
-			}
133
-			$mailIdMap[$mailRow['uuid']] = $mailRow['value']['shareWith'];
134
-		}
135
-
136
-		foreach ($allResults[$remoteType->getLabel()] as $resultRow) {
137
-			if (!isset($resultRow['uuid'])) {
138
-				continue;
139
-			}
140
-			if (isset($mailIdMap[$resultRow['uuid']])) {
141
-				$searchResult->removeCollaboratorResult($emailType, $mailIdMap[$resultRow['uuid']]);
142
-			}
143
-		}
144
-	}
38
+    /** @var IContainer */
39
+    private $c;
40
+
41
+    protected $pluginList = [];
42
+
43
+    public function __construct(IContainer $c) {
44
+        $this->c = $c;
45
+    }
46
+
47
+    /**
48
+     * @param string $search
49
+     * @param array $shareTypes
50
+     * @param bool $lookup
51
+     * @param int|null $limit
52
+     * @param int|null $offset
53
+     * @return array
54
+     * @throws \OCP\AppFramework\QueryException
55
+     */
56
+    public function search($search, array $shareTypes, $lookup, $limit, $offset) {
57
+        $hasMoreResults = false;
58
+
59
+        // Trim leading and trailing whitespace characters, e.g. when query is copy-pasted
60
+        $search = trim($search);
61
+
62
+        /** @var ISearchResult $searchResult */
63
+        $searchResult = $this->c->resolve(SearchResult::class);
64
+
65
+        foreach ($shareTypes as $type) {
66
+            if (!isset($this->pluginList[$type])) {
67
+                continue;
68
+            }
69
+            foreach ($this->pluginList[$type] as $plugin) {
70
+                /** @var ISearchPlugin $searchPlugin */
71
+                $searchPlugin = $this->c->resolve($plugin);
72
+                $hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
73
+            }
74
+        }
75
+
76
+        // Get from lookup server, not a separate share type
77
+        if ($lookup) {
78
+            $searchPlugin = $this->c->resolve(LookupPlugin::class);
79
+            $hasMoreResults = $searchPlugin->search($search, $limit, $offset, $searchResult) || $hasMoreResults;
80
+        }
81
+
82
+        // sanitizing, could go into the plugins as well
83
+
84
+        // if we have an exact match, either for the federated cloud id or for the
85
+        // email address, we only return the exact match. It is highly unlikely
86
+        // that the exact same email address and federated cloud id exists
87
+        $emailType = new SearchResultType('emails');
88
+        $remoteType = new SearchResultType('remotes');
89
+        if ($searchResult->hasExactIdMatch($emailType) && !$searchResult->hasExactIdMatch($remoteType)) {
90
+            $searchResult->unsetResult($remoteType);
91
+        } elseif (!$searchResult->hasExactIdMatch($emailType) && $searchResult->hasExactIdMatch($remoteType)) {
92
+            $searchResult->unsetResult($emailType);
93
+        }
94
+
95
+        $this->dropMailSharesWhereRemoteShareIsPossible($searchResult);
96
+
97
+        // if we have an exact local user match with an email-a-like query,
98
+        // there is no need to show the remote and email matches.
99
+        $userType = new SearchResultType('users');
100
+        if (str_contains($search, '@') && $searchResult->hasExactIdMatch($userType)) {
101
+            $searchResult->unsetResult($remoteType);
102
+            $searchResult->unsetResult($emailType);
103
+        }
104
+
105
+        return [$searchResult->asArray(), $hasMoreResults];
106
+    }
107
+
108
+    public function registerPlugin(array $pluginInfo) {
109
+        $shareType = constant(Share::class . '::' . $pluginInfo['shareType']);
110
+        if ($shareType === null) {
111
+            throw new \InvalidArgumentException('Provided ShareType is invalid');
112
+        }
113
+        $this->pluginList[$shareType][] = $pluginInfo['class'];
114
+    }
115
+
116
+    protected function dropMailSharesWhereRemoteShareIsPossible(ISearchResult $searchResult): void {
117
+        $allResults = $searchResult->asArray();
118
+
119
+        $emailType = new SearchResultType('emails');
120
+        $remoteType = new SearchResultType('remotes');
121
+
122
+        if (!isset($allResults[$remoteType->getLabel()])
123
+            || !isset($allResults[$emailType->getLabel()])) {
124
+            return;
125
+        }
126
+
127
+        $mailIdMap = [];
128
+        foreach ($allResults[$emailType->getLabel()] as $mailRow) {
129
+            // sure, array_reduce looks nicer, but foreach needs less resources and is faster
130
+            if (!isset($mailRow['uuid'])) {
131
+                continue;
132
+            }
133
+            $mailIdMap[$mailRow['uuid']] = $mailRow['value']['shareWith'];
134
+        }
135
+
136
+        foreach ($allResults[$remoteType->getLabel()] as $resultRow) {
137
+            if (!isset($resultRow['uuid'])) {
138
+                continue;
139
+            }
140
+            if (isset($mailIdMap[$resultRow['uuid']])) {
141
+                $searchResult->removeCollaboratorResult($emailType, $mailIdMap[$resultRow['uuid']]);
142
+            }
143
+        }
144
+    }
145 145
 }
Please login to merge, or discard this patch.