Completed
Push — master ( 85c141...f833e2 )
by
unknown
23:16 queued 15s
created
apps/files/lib/Listener/SyncLivePhotosListener.php 2 patches
Indentation   +213 added lines, -213 removed lines patch added patch discarded remove patch
@@ -33,222 +33,222 @@
 block discarded – undo
33 33
  * @template-implements IEventListener<Event>
34 34
  */
35 35
 class SyncLivePhotosListener implements IEventListener {
36
-	/** @var Array<int> */
37
-	private array $pendingRenames = [];
38
-	/** @var Array<int, bool> */
39
-	private array $pendingDeletion = [];
40
-	/** @var Array<int> */
41
-	private array $pendingCopies = [];
42
-
43
-	public function __construct(
44
-		private ?Folder $userFolder,
45
-		private IFilesMetadataManager $filesMetadataManager,
46
-		private LivePhotosService $livePhotosService,
47
-		private IRootFolder $rootFolder,
48
-		private View $view,
49
-	) {
50
-	}
51
-
52
-	public function handle(Event $event): void {
53
-		if ($this->userFolder === null) {
54
-			return;
55
-		}
56
-
57
-		if ($event instanceof BeforeNodeCopiedEvent || $event instanceof NodeCopiedEvent) {
58
-			$this->handleCopyRecursive($event, $event->getSource(), $event->getTarget());
59
-		} else {
60
-			$peerFileId = null;
61
-
62
-			if ($event instanceof BeforeNodeRenamedEvent) {
63
-				$peerFileId = $this->livePhotosService->getLivePhotoPeerId($event->getSource()->getId());
64
-			} elseif ($event instanceof BeforeNodeDeletedEvent) {
65
-				$peerFileId = $this->livePhotosService->getLivePhotoPeerId($event->getNode()->getId());
66
-			} elseif ($event instanceof CacheEntryRemovedEvent) {
67
-				$peerFileId = $this->livePhotosService->getLivePhotoPeerId($event->getFileId());
68
-			}
69
-
70
-			if ($peerFileId === null) {
71
-				return; // Not a live photo.
72
-			}
73
-
74
-			// Check the user's folder.
75
-			$peerFile = $this->userFolder->getFirstNodeById($peerFileId);
76
-
77
-			if ($peerFile === null) {
78
-				return; // Peer file not found.
79
-			}
80
-
81
-			if ($event instanceof BeforeNodeRenamedEvent) {
82
-				$this->runMoveOrCopyChecks($event->getSource(), $event->getTarget(), $peerFile);
83
-				$this->handleMove($event->getSource(), $event->getTarget(), $peerFile);
84
-			} elseif ($event instanceof BeforeNodeDeletedEvent) {
85
-				$this->handleDeletion($event, $peerFile);
86
-			} elseif ($event instanceof CacheEntryRemovedEvent) {
87
-				$peerFile->delete();
88
-			}
89
-		}
90
-	}
91
-
92
-	private function runMoveOrCopyChecks(Node $sourceFile, Node $targetFile, Node $peerFile): void {
93
-		$targetParent = $targetFile->getParent();
94
-		$sourceExtension = $sourceFile->getExtension();
95
-		$peerFileExtension = $peerFile->getExtension();
96
-		$targetName = $targetFile->getName();
97
-		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
98
-
99
-		if (!str_ends_with($targetName, '.' . $sourceExtension)) {
100
-			throw new AbortedEventException('Cannot change the extension of a Live Photo');
101
-		}
102
-
103
-		try {
104
-			$targetParent->get($targetName);
105
-			throw new AbortedEventException('A file already exist at destination path of the Live Photo');
106
-		} catch (NotFoundException) {
107
-		}
108
-
109
-		if (!($targetParent instanceof NonExistingFolder)) {
110
-			try {
111
-				$targetParent->get($peerTargetName);
112
-				throw new AbortedEventException('A file already exist at destination path of the Live Photo');
113
-			} catch (NotFoundException) {
114
-			}
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * During rename events, which also include move operations,
120
-	 * we rename the peer file using the same name.
121
-	 * The event listener being singleton, we can store the current state
122
-	 * of pending renames inside the 'pendingRenames' property,
123
-	 * to prevent infinite recursive.
124
-	 */
125
-	private function handleMove(Node $sourceFile, Node $targetFile, Node $peerFile): void {
126
-		$targetParent = $targetFile->getParent();
127
-		$sourceExtension = $sourceFile->getExtension();
128
-		$peerFileExtension = $peerFile->getExtension();
129
-		$targetName = $targetFile->getName();
130
-		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
131
-
132
-		// in case the rename was initiated from this listener, we stop right now
133
-		if (in_array($peerFile->getId(), $this->pendingRenames)) {
134
-			return;
135
-		}
136
-
137
-		$this->pendingRenames[] = $sourceFile->getId();
138
-		try {
139
-			$peerFile->move($targetParent->getPath() . '/' . $peerTargetName);
140
-		} catch (\Throwable $ex) {
141
-			throw new AbortedEventException($ex->getMessage());
142
-		}
143
-
144
-		$this->pendingRenames = array_diff($this->pendingRenames, [$sourceFile->getId()]);
145
-	}
146
-
147
-
148
-	/**
149
-	 * handle copy, we already know if it is doable from BeforeNodeCopiedEvent, so we just copy the linked file
150
-	 */
151
-	private function handleCopy(File $sourceFile, File $targetFile, File $peerFile): void {
152
-		$sourceExtension = $sourceFile->getExtension();
153
-		$peerFileExtension = $peerFile->getExtension();
154
-		$targetParent = $targetFile->getParent();
155
-		$targetName = $targetFile->getName();
156
-		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
157
-
158
-		if ($targetParent->nodeExists($peerTargetName)) {
159
-			// If the copy was a folder copy, then the peer file already exists.
160
-			$targetPeerFile = $targetParent->get($peerTargetName);
161
-		} else {
162
-			// If the copy was a file copy, then we need to create the peer file.
163
-			$targetPeerFile = $peerFile->copy($targetParent->getPath() . '/' . $peerTargetName);
164
-		}
165
-
166
-		/** @var FilesMetadata $targetMetadata */
167
-		$targetMetadata = $this->filesMetadataManager->getMetadata($targetFile->getId(), true);
168
-		$targetMetadata->setStorageId($targetFile->getStorage()->getCache()->getNumericStorageId());
169
-		$targetMetadata->setString('files-live-photo', (string)$targetPeerFile->getId());
170
-		$this->filesMetadataManager->saveMetadata($targetMetadata);
171
-		/** @var FilesMetadata $peerMetadata */
172
-		$peerMetadata = $this->filesMetadataManager->getMetadata($targetPeerFile->getId(), true);
173
-		$peerMetadata->setStorageId($targetPeerFile->getStorage()->getCache()->getNumericStorageId());
174
-		$peerMetadata->setString('files-live-photo', (string)$targetFile->getId());
175
-		$this->filesMetadataManager->saveMetadata($peerMetadata);
176
-	}
177
-
178
-	/**
179
-	 * During deletion event, we trigger another recursive delete on the peer file.
180
-	 * Delete operations on the .mov file directly are currently blocked.
181
-	 * The event listener being singleton, we can store the current state
182
-	 * of pending deletions inside the 'pendingDeletions' property,
183
-	 * to prevent infinite recursivity.
184
-	 */
185
-	private function handleDeletion(BeforeNodeDeletedEvent $event, Node $peerFile): void {
186
-		$deletedFile = $event->getNode();
187
-		if ($deletedFile->getMimetype() === 'video/quicktime') {
188
-			if (isset($this->pendingDeletion[$peerFile->getId()])) {
189
-				unset($this->pendingDeletion[$peerFile->getId()]);
190
-				return;
191
-			} else {
192
-				throw new AbortedEventException('Cannot delete the video part of a live photo');
193
-			}
194
-		} else {
195
-			$this->pendingDeletion[$deletedFile->getId()] = true;
196
-			try {
197
-				$peerFile->delete();
198
-			} catch (\Throwable $ex) {
199
-				throw new AbortedEventException($ex->getMessage());
200
-			}
201
-		}
202
-		return;
203
-	}
204
-
205
-	/*
36
+    /** @var Array<int> */
37
+    private array $pendingRenames = [];
38
+    /** @var Array<int, bool> */
39
+    private array $pendingDeletion = [];
40
+    /** @var Array<int> */
41
+    private array $pendingCopies = [];
42
+
43
+    public function __construct(
44
+        private ?Folder $userFolder,
45
+        private IFilesMetadataManager $filesMetadataManager,
46
+        private LivePhotosService $livePhotosService,
47
+        private IRootFolder $rootFolder,
48
+        private View $view,
49
+    ) {
50
+    }
51
+
52
+    public function handle(Event $event): void {
53
+        if ($this->userFolder === null) {
54
+            return;
55
+        }
56
+
57
+        if ($event instanceof BeforeNodeCopiedEvent || $event instanceof NodeCopiedEvent) {
58
+            $this->handleCopyRecursive($event, $event->getSource(), $event->getTarget());
59
+        } else {
60
+            $peerFileId = null;
61
+
62
+            if ($event instanceof BeforeNodeRenamedEvent) {
63
+                $peerFileId = $this->livePhotosService->getLivePhotoPeerId($event->getSource()->getId());
64
+            } elseif ($event instanceof BeforeNodeDeletedEvent) {
65
+                $peerFileId = $this->livePhotosService->getLivePhotoPeerId($event->getNode()->getId());
66
+            } elseif ($event instanceof CacheEntryRemovedEvent) {
67
+                $peerFileId = $this->livePhotosService->getLivePhotoPeerId($event->getFileId());
68
+            }
69
+
70
+            if ($peerFileId === null) {
71
+                return; // Not a live photo.
72
+            }
73
+
74
+            // Check the user's folder.
75
+            $peerFile = $this->userFolder->getFirstNodeById($peerFileId);
76
+
77
+            if ($peerFile === null) {
78
+                return; // Peer file not found.
79
+            }
80
+
81
+            if ($event instanceof BeforeNodeRenamedEvent) {
82
+                $this->runMoveOrCopyChecks($event->getSource(), $event->getTarget(), $peerFile);
83
+                $this->handleMove($event->getSource(), $event->getTarget(), $peerFile);
84
+            } elseif ($event instanceof BeforeNodeDeletedEvent) {
85
+                $this->handleDeletion($event, $peerFile);
86
+            } elseif ($event instanceof CacheEntryRemovedEvent) {
87
+                $peerFile->delete();
88
+            }
89
+        }
90
+    }
91
+
92
+    private function runMoveOrCopyChecks(Node $sourceFile, Node $targetFile, Node $peerFile): void {
93
+        $targetParent = $targetFile->getParent();
94
+        $sourceExtension = $sourceFile->getExtension();
95
+        $peerFileExtension = $peerFile->getExtension();
96
+        $targetName = $targetFile->getName();
97
+        $peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
98
+
99
+        if (!str_ends_with($targetName, '.' . $sourceExtension)) {
100
+            throw new AbortedEventException('Cannot change the extension of a Live Photo');
101
+        }
102
+
103
+        try {
104
+            $targetParent->get($targetName);
105
+            throw new AbortedEventException('A file already exist at destination path of the Live Photo');
106
+        } catch (NotFoundException) {
107
+        }
108
+
109
+        if (!($targetParent instanceof NonExistingFolder)) {
110
+            try {
111
+                $targetParent->get($peerTargetName);
112
+                throw new AbortedEventException('A file already exist at destination path of the Live Photo');
113
+            } catch (NotFoundException) {
114
+            }
115
+        }
116
+    }
117
+
118
+    /**
119
+     * During rename events, which also include move operations,
120
+     * we rename the peer file using the same name.
121
+     * The event listener being singleton, we can store the current state
122
+     * of pending renames inside the 'pendingRenames' property,
123
+     * to prevent infinite recursive.
124
+     */
125
+    private function handleMove(Node $sourceFile, Node $targetFile, Node $peerFile): void {
126
+        $targetParent = $targetFile->getParent();
127
+        $sourceExtension = $sourceFile->getExtension();
128
+        $peerFileExtension = $peerFile->getExtension();
129
+        $targetName = $targetFile->getName();
130
+        $peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
131
+
132
+        // in case the rename was initiated from this listener, we stop right now
133
+        if (in_array($peerFile->getId(), $this->pendingRenames)) {
134
+            return;
135
+        }
136
+
137
+        $this->pendingRenames[] = $sourceFile->getId();
138
+        try {
139
+            $peerFile->move($targetParent->getPath() . '/' . $peerTargetName);
140
+        } catch (\Throwable $ex) {
141
+            throw new AbortedEventException($ex->getMessage());
142
+        }
143
+
144
+        $this->pendingRenames = array_diff($this->pendingRenames, [$sourceFile->getId()]);
145
+    }
146
+
147
+
148
+    /**
149
+     * handle copy, we already know if it is doable from BeforeNodeCopiedEvent, so we just copy the linked file
150
+     */
151
+    private function handleCopy(File $sourceFile, File $targetFile, File $peerFile): void {
152
+        $sourceExtension = $sourceFile->getExtension();
153
+        $peerFileExtension = $peerFile->getExtension();
154
+        $targetParent = $targetFile->getParent();
155
+        $targetName = $targetFile->getName();
156
+        $peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
157
+
158
+        if ($targetParent->nodeExists($peerTargetName)) {
159
+            // If the copy was a folder copy, then the peer file already exists.
160
+            $targetPeerFile = $targetParent->get($peerTargetName);
161
+        } else {
162
+            // If the copy was a file copy, then we need to create the peer file.
163
+            $targetPeerFile = $peerFile->copy($targetParent->getPath() . '/' . $peerTargetName);
164
+        }
165
+
166
+        /** @var FilesMetadata $targetMetadata */
167
+        $targetMetadata = $this->filesMetadataManager->getMetadata($targetFile->getId(), true);
168
+        $targetMetadata->setStorageId($targetFile->getStorage()->getCache()->getNumericStorageId());
169
+        $targetMetadata->setString('files-live-photo', (string)$targetPeerFile->getId());
170
+        $this->filesMetadataManager->saveMetadata($targetMetadata);
171
+        /** @var FilesMetadata $peerMetadata */
172
+        $peerMetadata = $this->filesMetadataManager->getMetadata($targetPeerFile->getId(), true);
173
+        $peerMetadata->setStorageId($targetPeerFile->getStorage()->getCache()->getNumericStorageId());
174
+        $peerMetadata->setString('files-live-photo', (string)$targetFile->getId());
175
+        $this->filesMetadataManager->saveMetadata($peerMetadata);
176
+    }
177
+
178
+    /**
179
+     * During deletion event, we trigger another recursive delete on the peer file.
180
+     * Delete operations on the .mov file directly are currently blocked.
181
+     * The event listener being singleton, we can store the current state
182
+     * of pending deletions inside the 'pendingDeletions' property,
183
+     * to prevent infinite recursivity.
184
+     */
185
+    private function handleDeletion(BeforeNodeDeletedEvent $event, Node $peerFile): void {
186
+        $deletedFile = $event->getNode();
187
+        if ($deletedFile->getMimetype() === 'video/quicktime') {
188
+            if (isset($this->pendingDeletion[$peerFile->getId()])) {
189
+                unset($this->pendingDeletion[$peerFile->getId()]);
190
+                return;
191
+            } else {
192
+                throw new AbortedEventException('Cannot delete the video part of a live photo');
193
+            }
194
+        } else {
195
+            $this->pendingDeletion[$deletedFile->getId()] = true;
196
+            try {
197
+                $peerFile->delete();
198
+            } catch (\Throwable $ex) {
199
+                throw new AbortedEventException($ex->getMessage());
200
+            }
201
+        }
202
+        return;
203
+    }
204
+
205
+    /*
206 206
 	 * Recursively get all the peer ids of a live photo.
207 207
 	 * Needed when coping a folder.
208 208
 	 *
209 209
 	 * @param BeforeNodeCopiedEvent|NodeCopiedEvent $event
210 210
 	 */
211
-	private function handleCopyRecursive(Event $event, Node $sourceNode, Node $targetNode): void {
212
-		if ($sourceNode instanceof Folder && $targetNode instanceof Folder) {
213
-			foreach ($sourceNode->getDirectoryListing() as $sourceChild) {
214
-				if ($event instanceof BeforeNodeCopiedEvent) {
215
-					if ($sourceChild instanceof Folder) {
216
-						$targetChild = new NonExistingFolder($this->rootFolder, $this->view, $targetNode->getPath() . '/' . $sourceChild->getName(), null, $targetNode);
217
-					} else {
218
-						$targetChild = new NonExistingFile($this->rootFolder, $this->view, $targetNode->getPath() . '/' . $sourceChild->getName(), null, $targetNode);
219
-					}
220
-				} elseif ($event instanceof NodeCopiedEvent) {
221
-					$targetChild = $targetNode->get($sourceChild->getName());
222
-				} else {
223
-					throw new Exception('Event is type is not supported');
224
-				}
225
-
226
-				$this->handleCopyRecursive($event, $sourceChild, $targetChild);
227
-			}
228
-		} elseif ($sourceNode instanceof File && $targetNode instanceof File) {
229
-			// in case the copy was initiated from this listener, we stop right now
230
-			if (in_array($sourceNode->getId(), $this->pendingCopies)) {
231
-				return;
232
-			}
233
-
234
-			$peerFileId = $this->livePhotosService->getLivePhotoPeerId($sourceNode->getId());
235
-			if ($peerFileId === null) {
236
-				return;
237
-			}
238
-			$peerFile = $this->userFolder->getFirstNodeById($peerFileId);
239
-			if ($peerFile === null) {
240
-				return;
241
-			}
242
-
243
-			$this->pendingCopies[] = $peerFileId;
244
-			if ($event instanceof BeforeNodeCopiedEvent) {
245
-				$this->runMoveOrCopyChecks($sourceNode, $targetNode, $peerFile);
246
-			} elseif ($event instanceof NodeCopiedEvent) {
247
-				$this->handleCopy($sourceNode, $targetNode, $peerFile);
248
-			}
249
-			$this->pendingCopies = array_diff($this->pendingCopies, [$peerFileId]);
250
-		} else {
251
-			throw new Exception('Source and target type are not matching');
252
-		}
253
-	}
211
+    private function handleCopyRecursive(Event $event, Node $sourceNode, Node $targetNode): void {
212
+        if ($sourceNode instanceof Folder && $targetNode instanceof Folder) {
213
+            foreach ($sourceNode->getDirectoryListing() as $sourceChild) {
214
+                if ($event instanceof BeforeNodeCopiedEvent) {
215
+                    if ($sourceChild instanceof Folder) {
216
+                        $targetChild = new NonExistingFolder($this->rootFolder, $this->view, $targetNode->getPath() . '/' . $sourceChild->getName(), null, $targetNode);
217
+                    } else {
218
+                        $targetChild = new NonExistingFile($this->rootFolder, $this->view, $targetNode->getPath() . '/' . $sourceChild->getName(), null, $targetNode);
219
+                    }
220
+                } elseif ($event instanceof NodeCopiedEvent) {
221
+                    $targetChild = $targetNode->get($sourceChild->getName());
222
+                } else {
223
+                    throw new Exception('Event is type is not supported');
224
+                }
225
+
226
+                $this->handleCopyRecursive($event, $sourceChild, $targetChild);
227
+            }
228
+        } elseif ($sourceNode instanceof File && $targetNode instanceof File) {
229
+            // in case the copy was initiated from this listener, we stop right now
230
+            if (in_array($sourceNode->getId(), $this->pendingCopies)) {
231
+                return;
232
+            }
233
+
234
+            $peerFileId = $this->livePhotosService->getLivePhotoPeerId($sourceNode->getId());
235
+            if ($peerFileId === null) {
236
+                return;
237
+            }
238
+            $peerFile = $this->userFolder->getFirstNodeById($peerFileId);
239
+            if ($peerFile === null) {
240
+                return;
241
+            }
242
+
243
+            $this->pendingCopies[] = $peerFileId;
244
+            if ($event instanceof BeforeNodeCopiedEvent) {
245
+                $this->runMoveOrCopyChecks($sourceNode, $targetNode, $peerFile);
246
+            } elseif ($event instanceof NodeCopiedEvent) {
247
+                $this->handleCopy($sourceNode, $targetNode, $peerFile);
248
+            }
249
+            $this->pendingCopies = array_diff($this->pendingCopies, [$peerFileId]);
250
+        } else {
251
+            throw new Exception('Source and target type are not matching');
252
+        }
253
+    }
254 254
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -94,9 +94,9 @@  discard block
 block discarded – undo
94 94
 		$sourceExtension = $sourceFile->getExtension();
95 95
 		$peerFileExtension = $peerFile->getExtension();
96 96
 		$targetName = $targetFile->getName();
97
-		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
97
+		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)).$peerFileExtension;
98 98
 
99
-		if (!str_ends_with($targetName, '.' . $sourceExtension)) {
99
+		if (!str_ends_with($targetName, '.'.$sourceExtension)) {
100 100
 			throw new AbortedEventException('Cannot change the extension of a Live Photo');
101 101
 		}
102 102
 
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 		$sourceExtension = $sourceFile->getExtension();
128 128
 		$peerFileExtension = $peerFile->getExtension();
129 129
 		$targetName = $targetFile->getName();
130
-		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
130
+		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)).$peerFileExtension;
131 131
 
132 132
 		// in case the rename was initiated from this listener, we stop right now
133 133
 		if (in_array($peerFile->getId(), $this->pendingRenames)) {
@@ -136,7 +136,7 @@  discard block
 block discarded – undo
136 136
 
137 137
 		$this->pendingRenames[] = $sourceFile->getId();
138 138
 		try {
139
-			$peerFile->move($targetParent->getPath() . '/' . $peerTargetName);
139
+			$peerFile->move($targetParent->getPath().'/'.$peerTargetName);
140 140
 		} catch (\Throwable $ex) {
141 141
 			throw new AbortedEventException($ex->getMessage());
142 142
 		}
@@ -153,25 +153,25 @@  discard block
 block discarded – undo
153 153
 		$peerFileExtension = $peerFile->getExtension();
154 154
 		$targetParent = $targetFile->getParent();
155 155
 		$targetName = $targetFile->getName();
156
-		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)) . $peerFileExtension;
156
+		$peerTargetName = substr($targetName, 0, -strlen($sourceExtension)).$peerFileExtension;
157 157
 
158 158
 		if ($targetParent->nodeExists($peerTargetName)) {
159 159
 			// If the copy was a folder copy, then the peer file already exists.
160 160
 			$targetPeerFile = $targetParent->get($peerTargetName);
161 161
 		} else {
162 162
 			// If the copy was a file copy, then we need to create the peer file.
163
-			$targetPeerFile = $peerFile->copy($targetParent->getPath() . '/' . $peerTargetName);
163
+			$targetPeerFile = $peerFile->copy($targetParent->getPath().'/'.$peerTargetName);
164 164
 		}
165 165
 
166 166
 		/** @var FilesMetadata $targetMetadata */
167 167
 		$targetMetadata = $this->filesMetadataManager->getMetadata($targetFile->getId(), true);
168 168
 		$targetMetadata->setStorageId($targetFile->getStorage()->getCache()->getNumericStorageId());
169
-		$targetMetadata->setString('files-live-photo', (string)$targetPeerFile->getId());
169
+		$targetMetadata->setString('files-live-photo', (string) $targetPeerFile->getId());
170 170
 		$this->filesMetadataManager->saveMetadata($targetMetadata);
171 171
 		/** @var FilesMetadata $peerMetadata */
172 172
 		$peerMetadata = $this->filesMetadataManager->getMetadata($targetPeerFile->getId(), true);
173 173
 		$peerMetadata->setStorageId($targetPeerFile->getStorage()->getCache()->getNumericStorageId());
174
-		$peerMetadata->setString('files-live-photo', (string)$targetFile->getId());
174
+		$peerMetadata->setString('files-live-photo', (string) $targetFile->getId());
175 175
 		$this->filesMetadataManager->saveMetadata($peerMetadata);
176 176
 	}
177 177
 
@@ -213,9 +213,9 @@  discard block
 block discarded – undo
213 213
 			foreach ($sourceNode->getDirectoryListing() as $sourceChild) {
214 214
 				if ($event instanceof BeforeNodeCopiedEvent) {
215 215
 					if ($sourceChild instanceof Folder) {
216
-						$targetChild = new NonExistingFolder($this->rootFolder, $this->view, $targetNode->getPath() . '/' . $sourceChild->getName(), null, $targetNode);
216
+						$targetChild = new NonExistingFolder($this->rootFolder, $this->view, $targetNode->getPath().'/'.$sourceChild->getName(), null, $targetNode);
217 217
 					} else {
218
-						$targetChild = new NonExistingFile($this->rootFolder, $this->view, $targetNode->getPath() . '/' . $sourceChild->getName(), null, $targetNode);
218
+						$targetChild = new NonExistingFile($this->rootFolder, $this->view, $targetNode->getPath().'/'.$sourceChild->getName(), null, $targetNode);
219 219
 					}
220 220
 				} elseif ($event instanceof NodeCopiedEvent) {
221 221
 					$targetChild = $targetNode->get($sourceChild->getName());
Please login to merge, or discard this patch.
lib/private/Files/View.php 1 patch
Indentation   +2244 added lines, -2244 removed lines patch added patch discarded remove patch
@@ -57,2248 +57,2248 @@
 block discarded – undo
57 57
  * \OC\Files\Storage\Storage object
58 58
  */
59 59
 class View {
60
-	private string $fakeRoot = '';
61
-	private ILockingProvider $lockingProvider;
62
-	private bool $lockingEnabled;
63
-	private bool $updaterEnabled = true;
64
-	private UserManager $userManager;
65
-	private LoggerInterface $logger;
66
-
67
-	/**
68
-	 * @throws \Exception If $root contains an invalid path
69
-	 */
70
-	public function __construct(string $root = '') {
71
-		if (!Filesystem::isValidPath($root)) {
72
-			throw new \Exception();
73
-		}
74
-
75
-		$this->fakeRoot = $root;
76
-		$this->lockingProvider = \OC::$server->get(ILockingProvider::class);
77
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
78
-		$this->userManager = \OC::$server->getUserManager();
79
-		$this->logger = \OC::$server->get(LoggerInterface::class);
80
-	}
81
-
82
-	/**
83
-	 * @param ?string $path
84
-	 * @psalm-template S as string|null
85
-	 * @psalm-param S $path
86
-	 * @psalm-return (S is string ? string : null)
87
-	 */
88
-	public function getAbsolutePath($path = '/'): ?string {
89
-		if ($path === null) {
90
-			return null;
91
-		}
92
-		$this->assertPathLength($path);
93
-		if ($path === '') {
94
-			$path = '/';
95
-		}
96
-		if ($path[0] !== '/') {
97
-			$path = '/' . $path;
98
-		}
99
-		return $this->fakeRoot . $path;
100
-	}
101
-
102
-	/**
103
-	 * Change the root to a fake root
104
-	 *
105
-	 * @param string $fakeRoot
106
-	 */
107
-	public function chroot($fakeRoot): void {
108
-		if (!$fakeRoot == '') {
109
-			if ($fakeRoot[0] !== '/') {
110
-				$fakeRoot = '/' . $fakeRoot;
111
-			}
112
-		}
113
-		$this->fakeRoot = $fakeRoot;
114
-	}
115
-
116
-	/**
117
-	 * Get the fake root
118
-	 */
119
-	public function getRoot(): string {
120
-		return $this->fakeRoot;
121
-	}
122
-
123
-	/**
124
-	 * get path relative to the root of the view
125
-	 *
126
-	 * @param string $path
127
-	 */
128
-	public function getRelativePath($path): ?string {
129
-		$this->assertPathLength($path);
130
-		if ($this->fakeRoot == '') {
131
-			return $path;
132
-		}
133
-
134
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
135
-			return '/';
136
-		}
137
-
138
-		// missing slashes can cause wrong matches!
139
-		$root = rtrim($this->fakeRoot, '/') . '/';
140
-
141
-		if (!str_starts_with($path, $root)) {
142
-			return null;
143
-		} else {
144
-			$path = substr($path, strlen($this->fakeRoot));
145
-			if (strlen($path) === 0) {
146
-				return '/';
147
-			} else {
148
-				return $path;
149
-			}
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * Get the mountpoint of the storage object for a path
155
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
156
-	 * returned mountpoint is relative to the absolute root of the filesystem
157
-	 * and does not take the chroot into account )
158
-	 *
159
-	 * @param string $path
160
-	 */
161
-	public function getMountPoint($path): string {
162
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
163
-	}
164
-
165
-	/**
166
-	 * Get the mountpoint of the storage object for a path
167
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
168
-	 * returned mountpoint is relative to the absolute root of the filesystem
169
-	 * and does not take the chroot into account )
170
-	 *
171
-	 * @param string $path
172
-	 */
173
-	public function getMount($path): IMountPoint {
174
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
175
-	}
176
-
177
-	/**
178
-	 * Resolve a path to a storage and internal path
179
-	 *
180
-	 * @param string $path
181
-	 * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
182
-	 */
183
-	public function resolvePath($path): array {
184
-		$a = $this->getAbsolutePath($path);
185
-		$p = Filesystem::normalizePath($a);
186
-		return Filesystem::resolvePath($p);
187
-	}
188
-
189
-	/**
190
-	 * Return the path to a local version of the file
191
-	 * we need this because we can't know if a file is stored local or not from
192
-	 * outside the filestorage and for some purposes a local file is needed
193
-	 *
194
-	 * @param string $path
195
-	 */
196
-	public function getLocalFile($path): string|false {
197
-		$parent = substr($path, 0, strrpos($path, '/') ?: 0);
198
-		$path = $this->getAbsolutePath($path);
199
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
200
-		if (Filesystem::isValidPath($parent) && $storage) {
201
-			return $storage->getLocalFile($internalPath);
202
-		} else {
203
-			return false;
204
-		}
205
-	}
206
-
207
-	/**
208
-	 * the following functions operate with arguments and return values identical
209
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
210
-	 * for \OC\Files\Storage\Storage via basicOperation().
211
-	 */
212
-	public function mkdir($path) {
213
-		return $this->basicOperation('mkdir', $path, ['create', 'write']);
214
-	}
215
-
216
-	/**
217
-	 * remove mount point
218
-	 *
219
-	 * @param IMountPoint $mount
220
-	 * @param string $path relative to data/
221
-	 */
222
-	protected function removeMount($mount, $path): bool {
223
-		if ($mount instanceof MoveableMount) {
224
-			// cut of /user/files to get the relative path to data/user/files
225
-			$pathParts = explode('/', $path, 4);
226
-			$relPath = '/' . $pathParts[3];
227
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
228
-			\OC_Hook::emit(
229
-				Filesystem::CLASSNAME, 'umount',
230
-				[Filesystem::signal_param_path => $relPath]
231
-			);
232
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
233
-			$result = $mount->removeMount();
234
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
235
-			if ($result) {
236
-				\OC_Hook::emit(
237
-					Filesystem::CLASSNAME, 'post_umount',
238
-					[Filesystem::signal_param_path => $relPath]
239
-				);
240
-			}
241
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
242
-			return $result;
243
-		} else {
244
-			// do not allow deleting the storage's root / the mount point
245
-			// because for some storages it might delete the whole contents
246
-			// but isn't supposed to work that way
247
-			return false;
248
-		}
249
-	}
250
-
251
-	public function disableCacheUpdate(): void {
252
-		$this->updaterEnabled = false;
253
-	}
254
-
255
-	public function enableCacheUpdate(): void {
256
-		$this->updaterEnabled = true;
257
-	}
258
-
259
-	protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
260
-		if ($this->updaterEnabled) {
261
-			if (is_null($time)) {
262
-				$time = time();
263
-			}
264
-			$storage->getUpdater()->update($internalPath, $time, $sizeDifference);
265
-		}
266
-	}
267
-
268
-	protected function removeUpdate(Storage $storage, string $internalPath): void {
269
-		if ($this->updaterEnabled) {
270
-			$storage->getUpdater()->remove($internalPath);
271
-		}
272
-	}
273
-
274
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
275
-		if ($this->updaterEnabled) {
276
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
277
-		}
278
-	}
279
-
280
-	protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
281
-		if ($this->updaterEnabled) {
282
-			$targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
283
-		}
284
-	}
285
-
286
-	/**
287
-	 * @param string $path
288
-	 * @return bool|mixed
289
-	 */
290
-	public function rmdir($path) {
291
-		$absolutePath = $this->getAbsolutePath($path);
292
-		$mount = Filesystem::getMountManager()->find($absolutePath);
293
-		if ($mount->getInternalPath($absolutePath) === '') {
294
-			return $this->removeMount($mount, $absolutePath);
295
-		}
296
-		if ($this->is_dir($path)) {
297
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
298
-		} else {
299
-			$result = false;
300
-		}
301
-
302
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
303
-			$storage = $mount->getStorage();
304
-			$internalPath = $mount->getInternalPath($absolutePath);
305
-			$storage->getUpdater()->remove($internalPath);
306
-		}
307
-		return $result;
308
-	}
309
-
310
-	/**
311
-	 * @param string $path
312
-	 * @return resource|false
313
-	 */
314
-	public function opendir($path) {
315
-		return $this->basicOperation('opendir', $path, ['read']);
316
-	}
317
-
318
-	/**
319
-	 * @param string $path
320
-	 * @return bool|mixed
321
-	 */
322
-	public function is_dir($path) {
323
-		if ($path == '/') {
324
-			return true;
325
-		}
326
-		return $this->basicOperation('is_dir', $path);
327
-	}
328
-
329
-	/**
330
-	 * @param string $path
331
-	 * @return bool|mixed
332
-	 */
333
-	public function is_file($path) {
334
-		if ($path == '/') {
335
-			return false;
336
-		}
337
-		return $this->basicOperation('is_file', $path);
338
-	}
339
-
340
-	/**
341
-	 * @param string $path
342
-	 * @return mixed
343
-	 */
344
-	public function stat($path) {
345
-		return $this->basicOperation('stat', $path);
346
-	}
347
-
348
-	/**
349
-	 * @param string $path
350
-	 * @return mixed
351
-	 */
352
-	public function filetype($path) {
353
-		return $this->basicOperation('filetype', $path);
354
-	}
355
-
356
-	/**
357
-	 * @param string $path
358
-	 * @return mixed
359
-	 */
360
-	public function filesize(string $path) {
361
-		return $this->basicOperation('filesize', $path);
362
-	}
363
-
364
-	/**
365
-	 * @param string $path
366
-	 * @return bool|mixed
367
-	 * @throws InvalidPathException
368
-	 */
369
-	public function readfile($path) {
370
-		$this->assertPathLength($path);
371
-		if (ob_get_level()) {
372
-			ob_end_clean();
373
-		}
374
-		$handle = $this->fopen($path, 'rb');
375
-		if ($handle) {
376
-			$chunkSize = 524288; // 512 kiB chunks
377
-			while (!feof($handle)) {
378
-				echo fread($handle, $chunkSize);
379
-				flush();
380
-				$this->checkConnectionStatus();
381
-			}
382
-			fclose($handle);
383
-			return $this->filesize($path);
384
-		}
385
-		return false;
386
-	}
387
-
388
-	/**
389
-	 * @param string $path
390
-	 * @param int $from
391
-	 * @param int $to
392
-	 * @return bool|mixed
393
-	 * @throws InvalidPathException
394
-	 * @throws \OCP\Files\UnseekableException
395
-	 */
396
-	public function readfilePart($path, $from, $to) {
397
-		$this->assertPathLength($path);
398
-		if (ob_get_level()) {
399
-			ob_end_clean();
400
-		}
401
-		$handle = $this->fopen($path, 'rb');
402
-		if ($handle) {
403
-			$chunkSize = 524288; // 512 kiB chunks
404
-			$startReading = true;
405
-
406
-			if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
407
-				// forward file handle via chunked fread because fseek seem to have failed
408
-
409
-				$end = $from + 1;
410
-				while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
411
-					$len = $from - ftell($handle);
412
-					if ($len > $chunkSize) {
413
-						$len = $chunkSize;
414
-					}
415
-					$result = fread($handle, $len);
416
-
417
-					if ($result === false) {
418
-						$startReading = false;
419
-						break;
420
-					}
421
-				}
422
-			}
423
-
424
-			if ($startReading) {
425
-				$end = $to + 1;
426
-				while (!feof($handle) && ftell($handle) < $end) {
427
-					$len = $end - ftell($handle);
428
-					if ($len > $chunkSize) {
429
-						$len = $chunkSize;
430
-					}
431
-					echo fread($handle, $len);
432
-					flush();
433
-					$this->checkConnectionStatus();
434
-				}
435
-				return ftell($handle) - $from;
436
-			}
437
-
438
-			throw new \OCP\Files\UnseekableException('fseek error');
439
-		}
440
-		return false;
441
-	}
442
-
443
-	private function checkConnectionStatus(): void {
444
-		$connectionStatus = \connection_status();
445
-		if ($connectionStatus !== CONNECTION_NORMAL) {
446
-			throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * @param string $path
452
-	 * @return mixed
453
-	 */
454
-	public function isCreatable($path) {
455
-		return $this->basicOperation('isCreatable', $path);
456
-	}
457
-
458
-	/**
459
-	 * @param string $path
460
-	 * @return mixed
461
-	 */
462
-	public function isReadable($path) {
463
-		return $this->basicOperation('isReadable', $path);
464
-	}
465
-
466
-	/**
467
-	 * @param string $path
468
-	 * @return mixed
469
-	 */
470
-	public function isUpdatable($path) {
471
-		return $this->basicOperation('isUpdatable', $path);
472
-	}
473
-
474
-	/**
475
-	 * @param string $path
476
-	 * @return bool|mixed
477
-	 */
478
-	public function isDeletable($path) {
479
-		$absolutePath = $this->getAbsolutePath($path);
480
-		$mount = Filesystem::getMountManager()->find($absolutePath);
481
-		if ($mount->getInternalPath($absolutePath) === '') {
482
-			return $mount instanceof MoveableMount;
483
-		}
484
-		return $this->basicOperation('isDeletable', $path);
485
-	}
486
-
487
-	/**
488
-	 * @param string $path
489
-	 * @return mixed
490
-	 */
491
-	public function isSharable($path) {
492
-		return $this->basicOperation('isSharable', $path);
493
-	}
494
-
495
-	/**
496
-	 * @param string $path
497
-	 * @return bool|mixed
498
-	 */
499
-	public function file_exists($path) {
500
-		if ($path == '/') {
501
-			return true;
502
-		}
503
-		return $this->basicOperation('file_exists', $path);
504
-	}
505
-
506
-	/**
507
-	 * @param string $path
508
-	 * @return mixed
509
-	 */
510
-	public function filemtime($path) {
511
-		return $this->basicOperation('filemtime', $path);
512
-	}
513
-
514
-	/**
515
-	 * @param string $path
516
-	 * @param int|string $mtime
517
-	 */
518
-	public function touch($path, $mtime = null): bool {
519
-		if (!is_null($mtime) && !is_numeric($mtime)) {
520
-			$mtime = strtotime($mtime);
521
-		}
522
-
523
-		$hooks = ['touch'];
524
-
525
-		if (!$this->file_exists($path)) {
526
-			$hooks[] = 'create';
527
-			$hooks[] = 'write';
528
-		}
529
-		try {
530
-			$result = $this->basicOperation('touch', $path, $hooks, $mtime);
531
-		} catch (\Exception $e) {
532
-			$this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
533
-			$result = false;
534
-		}
535
-		if (!$result) {
536
-			// If create file fails because of permissions on external storage like SMB folders,
537
-			// check file exists and return false if not.
538
-			if (!$this->file_exists($path)) {
539
-				return false;
540
-			}
541
-			if (is_null($mtime)) {
542
-				$mtime = time();
543
-			}
544
-			//if native touch fails, we emulate it by changing the mtime in the cache
545
-			$this->putFileInfo($path, ['mtime' => floor($mtime)]);
546
-		}
547
-		return true;
548
-	}
549
-
550
-	/**
551
-	 * @param string $path
552
-	 * @return string|false
553
-	 * @throws LockedException
554
-	 */
555
-	public function file_get_contents($path) {
556
-		return $this->basicOperation('file_get_contents', $path, ['read']);
557
-	}
558
-
559
-	protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
560
-		if (!$exists) {
561
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
562
-				Filesystem::signal_param_path => $this->getHookPath($path),
563
-				Filesystem::signal_param_run => &$run,
564
-			]);
565
-		} else {
566
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
567
-				Filesystem::signal_param_path => $this->getHookPath($path),
568
-				Filesystem::signal_param_run => &$run,
569
-			]);
570
-		}
571
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
572
-			Filesystem::signal_param_path => $this->getHookPath($path),
573
-			Filesystem::signal_param_run => &$run,
574
-		]);
575
-	}
576
-
577
-	protected function emit_file_hooks_post(bool $exists, string $path): void {
578
-		if (!$exists) {
579
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
580
-				Filesystem::signal_param_path => $this->getHookPath($path),
581
-			]);
582
-		} else {
583
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
584
-				Filesystem::signal_param_path => $this->getHookPath($path),
585
-			]);
586
-		}
587
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
588
-			Filesystem::signal_param_path => $this->getHookPath($path),
589
-		]);
590
-	}
591
-
592
-	/**
593
-	 * @param string $path
594
-	 * @param string|resource $data
595
-	 * @return bool|mixed
596
-	 * @throws LockedException
597
-	 */
598
-	public function file_put_contents($path, $data) {
599
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
600
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
601
-			if (Filesystem::isValidPath($path)
602
-				&& !Filesystem::isFileBlacklisted($path)
603
-			) {
604
-				$path = $this->getRelativePath($absolutePath);
605
-				if ($path === null) {
606
-					throw new InvalidPathException("Path $absolutePath is not in the expected root");
607
-				}
608
-
609
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
610
-
611
-				$exists = $this->file_exists($path);
612
-				if ($this->shouldEmitHooks($path)) {
613
-					$run = true;
614
-					$this->emit_file_hooks_pre($exists, $path, $run);
615
-					if (!$run) {
616
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
617
-						return false;
618
-					}
619
-				}
620
-
621
-				try {
622
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
623
-				} catch (\Exception $e) {
624
-					// Release the shared lock before throwing.
625
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
626
-					throw $e;
627
-				}
628
-
629
-				/** @var Storage $storage */
630
-				[$storage, $internalPath] = $this->resolvePath($path);
631
-				$target = $storage->fopen($internalPath, 'w');
632
-				if ($target) {
633
-					[, $result] = Files::streamCopy($data, $target, true);
634
-					fclose($target);
635
-					fclose($data);
636
-
637
-					$this->writeUpdate($storage, $internalPath);
638
-
639
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
640
-
641
-					if ($this->shouldEmitHooks($path) && $result !== false) {
642
-						$this->emit_file_hooks_post($exists, $path);
643
-					}
644
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
645
-					return $result;
646
-				} else {
647
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
648
-					return false;
649
-				}
650
-			} else {
651
-				return false;
652
-			}
653
-		} else {
654
-			$hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
655
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
656
-		}
657
-	}
658
-
659
-	/**
660
-	 * @param string $path
661
-	 * @return bool|mixed
662
-	 */
663
-	public function unlink($path) {
664
-		if ($path === '' || $path === '/') {
665
-			// do not allow deleting the root
666
-			return false;
667
-		}
668
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
669
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
670
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
671
-		if ($mount->getInternalPath($absolutePath) === '') {
672
-			return $this->removeMount($mount, $absolutePath);
673
-		}
674
-		if ($this->is_dir($path)) {
675
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
676
-		} else {
677
-			$result = $this->basicOperation('unlink', $path, ['delete']);
678
-		}
679
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
680
-			$storage = $mount->getStorage();
681
-			$internalPath = $mount->getInternalPath($absolutePath);
682
-			$storage->getUpdater()->remove($internalPath);
683
-			return true;
684
-		} else {
685
-			return $result;
686
-		}
687
-	}
688
-
689
-	/**
690
-	 * @param string $directory
691
-	 * @return bool|mixed
692
-	 */
693
-	public function deleteAll($directory) {
694
-		return $this->rmdir($directory);
695
-	}
696
-
697
-	/**
698
-	 * Rename/move a file or folder from the source path to target path.
699
-	 *
700
-	 * @param string $source source path
701
-	 * @param string $target target path
702
-	 * @param array $options
703
-	 *
704
-	 * @return bool|mixed
705
-	 * @throws LockedException
706
-	 */
707
-	public function rename($source, $target, array $options = []) {
708
-		$checkSubMounts = $options['checkSubMounts'] ?? true;
709
-
710
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
711
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
712
-
713
-		if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
714
-			throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
715
-		}
716
-
717
-		/** @var IMountManager $mountManager */
718
-		$mountManager = \OC::$server->get(IMountManager::class);
719
-
720
-		$targetParts = explode('/', $absolutePath2);
721
-		$targetUser = $targetParts[1] ?? null;
722
-		$result = false;
723
-		if (
724
-			Filesystem::isValidPath($target)
725
-			&& Filesystem::isValidPath($source)
726
-			&& !Filesystem::isFileBlacklisted($target)
727
-		) {
728
-			$source = $this->getRelativePath($absolutePath1);
729
-			$target = $this->getRelativePath($absolutePath2);
730
-			$exists = $this->file_exists($target);
731
-
732
-			if ($source == null || $target == null) {
733
-				return false;
734
-			}
735
-
736
-			try {
737
-				$this->verifyPath(dirname($target), basename($target));
738
-			} catch (InvalidPathException) {
739
-				return false;
740
-			}
741
-
742
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
743
-			try {
744
-				$this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
745
-
746
-				$run = true;
747
-				if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
748
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
749
-					$this->emit_file_hooks_pre($exists, $target, $run);
750
-				} elseif ($this->shouldEmitHooks($source)) {
751
-					$sourcePath = $this->getHookPath($source);
752
-					$targetPath = $this->getHookPath($target);
753
-					if ($sourcePath !== null && $targetPath !== null) {
754
-						\OC_Hook::emit(
755
-							Filesystem::CLASSNAME, Filesystem::signal_rename,
756
-							[
757
-								Filesystem::signal_param_oldpath => $sourcePath,
758
-								Filesystem::signal_param_newpath => $targetPath,
759
-								Filesystem::signal_param_run => &$run
760
-							]
761
-						);
762
-					}
763
-				}
764
-				if ($run) {
765
-					$manager = Filesystem::getMountManager();
766
-					$mount1 = $this->getMount($source);
767
-					$mount2 = $this->getMount($target);
768
-					$storage1 = $mount1->getStorage();
769
-					$storage2 = $mount2->getStorage();
770
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
771
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
772
-
773
-					$this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
774
-					try {
775
-						$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
776
-
777
-						if ($checkSubMounts) {
778
-							$movedMounts = $mountManager->findIn($this->getAbsolutePath($source));
779
-						} else {
780
-							$movedMounts = [];
781
-						}
782
-
783
-						if ($internalPath1 === '') {
784
-							$sourceParentMount = $this->getMount(dirname($source));
785
-							$movedMounts[] = $mount1;
786
-							$this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
787
-							/**
788
-							 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
789
-							 */
790
-							$sourceMountPoint = $mount1->getMountPoint();
791
-							$result = $mount1->moveMount($absolutePath2);
792
-							$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
793
-
794
-							// moving a file/folder within the same mount point
795
-						} elseif ($storage1 === $storage2) {
796
-							if (count($movedMounts) > 0) {
797
-								$this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
798
-							}
799
-							if ($storage1) {
800
-								$result = $storage1->rename($internalPath1, $internalPath2);
801
-							} else {
802
-								$result = false;
803
-							}
804
-							// moving a file/folder between storages (from $storage1 to $storage2)
805
-						} else {
806
-							if (count($movedMounts) > 0) {
807
-								$this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
808
-							}
809
-							$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
810
-						}
811
-
812
-						if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
813
-							// if it was a rename from a part file to a regular file it was a write and not a rename operation
814
-							$this->writeUpdate($storage2, $internalPath2);
815
-						} elseif ($result) {
816
-							if ($internalPath1 !== '') { // don't do a cache update for moved mounts
817
-								$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
818
-							}
819
-						}
820
-					} catch (\Exception $e) {
821
-						throw $e;
822
-					} finally {
823
-						$this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
824
-						$this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
825
-					}
826
-
827
-					if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
828
-						if ($this->shouldEmitHooks()) {
829
-							$this->emit_file_hooks_post($exists, $target);
830
-						}
831
-					} elseif ($result) {
832
-						if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
833
-							$sourcePath = $this->getHookPath($source);
834
-							$targetPath = $this->getHookPath($target);
835
-							if ($sourcePath !== null && $targetPath !== null) {
836
-								\OC_Hook::emit(
837
-									Filesystem::CLASSNAME,
838
-									Filesystem::signal_post_rename,
839
-									[
840
-										Filesystem::signal_param_oldpath => $sourcePath,
841
-										Filesystem::signal_param_newpath => $targetPath,
842
-									]
843
-								);
844
-							}
845
-						}
846
-					}
847
-				}
848
-			} catch (\Exception $e) {
849
-				throw $e;
850
-			} finally {
851
-				$this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
852
-				$this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
853
-			}
854
-		}
855
-		return $result;
856
-	}
857
-
858
-	/**
859
-	 * @throws ForbiddenException
860
-	 */
861
-	private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMountPoint $targetMount, bool $targetIsShared): void {
862
-		$targetPath = $this->getRelativePath($targetMount->getMountPoint());
863
-		if ($targetPath) {
864
-			$targetPath = trim($targetPath, '/');
865
-		} else {
866
-			$targetPath = $targetMount->getMountPoint();
867
-		}
868
-
869
-		$l = \OC::$server->get(IFactory::class)->get('files');
870
-		foreach ($mounts as $mount) {
871
-			$sourcePath = $this->getRelativePath($mount->getMountPoint());
872
-			if ($sourcePath) {
873
-				$sourcePath = trim($sourcePath, '/');
874
-			} else {
875
-				$sourcePath = $mount->getMountPoint();
876
-			}
877
-
878
-			if (!$mount instanceof MoveableMount) {
879
-				throw new ForbiddenException($l->t('Storage %s cannot be moved', [$sourcePath]), false);
880
-			}
881
-
882
-			if ($targetIsShared) {
883
-				if ($sourceMount instanceof SharedMount) {
884
-					throw new ForbiddenException($l->t('Moving a share (%s) into a shared folder is not allowed', [$sourcePath]), false);
885
-				} else {
886
-					throw new ForbiddenException($l->t('Moving a storage (%s) into a shared folder is not allowed', [$sourcePath]), false);
887
-				}
888
-			}
889
-
890
-			if ($sourceMount !== $targetMount) {
891
-				if ($sourceMount instanceof SharedMount) {
892
-					if ($targetMount instanceof SharedMount) {
893
-						throw new ForbiddenException($l->t('Moving a share (%s) into another share (%s) is not allowed', [$sourcePath, $targetPath]), false);
894
-					} else {
895
-						throw new ForbiddenException($l->t('Moving a share (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
896
-					}
897
-				} else {
898
-					if ($targetMount instanceof SharedMount) {
899
-						throw new ForbiddenException($l->t('Moving a storage (%s) into a share (%s) is not allowed', [$sourcePath, $targetPath]), false);
900
-					} else {
901
-						throw new ForbiddenException($l->t('Moving a storage (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
902
-					}
903
-				}
904
-			}
905
-		}
906
-	}
907
-
908
-	/**
909
-	 * Copy a file/folder from the source path to target path
910
-	 *
911
-	 * @param string $source source path
912
-	 * @param string $target target path
913
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
914
-	 *
915
-	 * @return bool|mixed
916
-	 */
917
-	public function copy($source, $target, $preserveMtime = false) {
918
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
919
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
920
-		$result = false;
921
-		if (
922
-			Filesystem::isValidPath($target)
923
-			&& Filesystem::isValidPath($source)
924
-			&& !Filesystem::isFileBlacklisted($target)
925
-		) {
926
-			$source = $this->getRelativePath($absolutePath1);
927
-			$target = $this->getRelativePath($absolutePath2);
928
-
929
-			if ($source == null || $target == null) {
930
-				return false;
931
-			}
932
-			$run = true;
933
-
934
-			$this->lockFile($target, ILockingProvider::LOCK_SHARED);
935
-			$this->lockFile($source, ILockingProvider::LOCK_SHARED);
936
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
937
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
938
-
939
-			try {
940
-				$exists = $this->file_exists($target);
941
-				if ($this->shouldEmitHooks($target)) {
942
-					\OC_Hook::emit(
943
-						Filesystem::CLASSNAME,
944
-						Filesystem::signal_copy,
945
-						[
946
-							Filesystem::signal_param_oldpath => $this->getHookPath($source),
947
-							Filesystem::signal_param_newpath => $this->getHookPath($target),
948
-							Filesystem::signal_param_run => &$run
949
-						]
950
-					);
951
-					$this->emit_file_hooks_pre($exists, $target, $run);
952
-				}
953
-				if ($run) {
954
-					$mount1 = $this->getMount($source);
955
-					$mount2 = $this->getMount($target);
956
-					$storage1 = $mount1->getStorage();
957
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
958
-					$storage2 = $mount2->getStorage();
959
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
960
-
961
-					$this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
962
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
963
-
964
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
965
-						if ($storage1) {
966
-							$result = $storage1->copy($internalPath1, $internalPath2);
967
-						} else {
968
-							$result = false;
969
-						}
970
-					} else {
971
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
972
-					}
973
-
974
-					if ($result) {
975
-						$this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
976
-					}
977
-
978
-					$this->changeLock($target, ILockingProvider::LOCK_SHARED);
979
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
980
-
981
-					if ($this->shouldEmitHooks($target) && $result !== false) {
982
-						\OC_Hook::emit(
983
-							Filesystem::CLASSNAME,
984
-							Filesystem::signal_post_copy,
985
-							[
986
-								Filesystem::signal_param_oldpath => $this->getHookPath($source),
987
-								Filesystem::signal_param_newpath => $this->getHookPath($target)
988
-							]
989
-						);
990
-						$this->emit_file_hooks_post($exists, $target);
991
-					}
992
-				}
993
-			} catch (\Exception $e) {
994
-				$this->unlockFile($target, $lockTypePath2);
995
-				$this->unlockFile($source, $lockTypePath1);
996
-				throw $e;
997
-			}
998
-
999
-			$this->unlockFile($target, $lockTypePath2);
1000
-			$this->unlockFile($source, $lockTypePath1);
1001
-		}
1002
-		return $result;
1003
-	}
1004
-
1005
-	/**
1006
-	 * @param string $path
1007
-	 * @param string $mode 'r' or 'w'
1008
-	 * @return resource|false
1009
-	 * @throws LockedException
1010
-	 */
1011
-	public function fopen($path, $mode) {
1012
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
1013
-		$hooks = [];
1014
-		switch ($mode) {
1015
-			case 'r':
1016
-				$hooks[] = 'read';
1017
-				break;
1018
-			case 'r+':
1019
-			case 'w+':
1020
-			case 'x+':
1021
-			case 'a+':
1022
-				$hooks[] = 'read';
1023
-				$hooks[] = 'write';
1024
-				break;
1025
-			case 'w':
1026
-			case 'x':
1027
-			case 'a':
1028
-				$hooks[] = 'write';
1029
-				break;
1030
-			default:
1031
-				$this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1032
-		}
1033
-
1034
-		if ($mode !== 'r' && $mode !== 'w') {
1035
-			$this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1036
-		}
1037
-
1038
-		$handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1039
-		if (!is_resource($handle) && $mode === 'r') {
1040
-			// trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1041
-			$mount = $this->getMount($path);
1042
-			$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1043
-			$storage = $mount->getStorage();
1044
-			if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1045
-				$this->writeUpdate($storage, $internalPath);
1046
-			}
1047
-		}
1048
-		return $handle;
1049
-	}
1050
-
1051
-	/**
1052
-	 * @param string $path
1053
-	 * @throws InvalidPathException
1054
-	 */
1055
-	public function toTmpFile($path): string|false {
1056
-		$this->assertPathLength($path);
1057
-		if (Filesystem::isValidPath($path)) {
1058
-			$source = $this->fopen($path, 'r');
1059
-			if ($source) {
1060
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
1061
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1062
-				file_put_contents($tmpFile, $source);
1063
-				return $tmpFile;
1064
-			} else {
1065
-				return false;
1066
-			}
1067
-		} else {
1068
-			return false;
1069
-		}
1070
-	}
1071
-
1072
-	/**
1073
-	 * @param string $tmpFile
1074
-	 * @param string $path
1075
-	 * @return bool|mixed
1076
-	 * @throws InvalidPathException
1077
-	 */
1078
-	public function fromTmpFile($tmpFile, $path) {
1079
-		$this->assertPathLength($path);
1080
-		if (Filesystem::isValidPath($path)) {
1081
-			// Get directory that the file is going into
1082
-			$filePath = dirname($path);
1083
-
1084
-			// Create the directories if any
1085
-			if (!$this->file_exists($filePath)) {
1086
-				$result = $this->createParentDirectories($filePath);
1087
-				if ($result === false) {
1088
-					return false;
1089
-				}
1090
-			}
1091
-
1092
-			$source = fopen($tmpFile, 'r');
1093
-			if ($source) {
1094
-				$result = $this->file_put_contents($path, $source);
1095
-				/**
1096
-				 * $this->file_put_contents() might have already closed
1097
-				 * the resource, so we check it, before trying to close it
1098
-				 * to avoid messages in the error log.
1099
-				 * @psalm-suppress RedundantCondition false-positive
1100
-				 */
1101
-				if (is_resource($source)) {
1102
-					fclose($source);
1103
-				}
1104
-				unlink($tmpFile);
1105
-				return $result;
1106
-			} else {
1107
-				return false;
1108
-			}
1109
-		} else {
1110
-			return false;
1111
-		}
1112
-	}
1113
-
1114
-
1115
-	/**
1116
-	 * @param string $path
1117
-	 * @return mixed
1118
-	 * @throws InvalidPathException
1119
-	 */
1120
-	public function getMimeType($path) {
1121
-		$this->assertPathLength($path);
1122
-		return $this->basicOperation('getMimeType', $path);
1123
-	}
1124
-
1125
-	/**
1126
-	 * @param string $type
1127
-	 * @param string $path
1128
-	 * @param bool $raw
1129
-	 */
1130
-	public function hash($type, $path, $raw = false): string|bool {
1131
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1132
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
-		if (Filesystem::isValidPath($path)) {
1134
-			$path = $this->getRelativePath($absolutePath);
1135
-			if ($path == null) {
1136
-				return false;
1137
-			}
1138
-			if ($this->shouldEmitHooks($path)) {
1139
-				\OC_Hook::emit(
1140
-					Filesystem::CLASSNAME,
1141
-					Filesystem::signal_read,
1142
-					[Filesystem::signal_param_path => $this->getHookPath($path)]
1143
-				);
1144
-			}
1145
-			/** @var Storage|null $storage */
1146
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1147
-			if ($storage) {
1148
-				return $storage->hash($type, $internalPath, $raw);
1149
-			}
1150
-		}
1151
-		return false;
1152
-	}
1153
-
1154
-	/**
1155
-	 * @param string $path
1156
-	 * @return mixed
1157
-	 * @throws InvalidPathException
1158
-	 */
1159
-	public function free_space($path = '/') {
1160
-		$this->assertPathLength($path);
1161
-		$result = $this->basicOperation('free_space', $path);
1162
-		if ($result === null) {
1163
-			throw new InvalidPathException();
1164
-		}
1165
-		return $result;
1166
-	}
1167
-
1168
-	/**
1169
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1170
-	 *
1171
-	 * @param mixed $extraParam (optional)
1172
-	 * @return mixed
1173
-	 * @throws LockedException
1174
-	 *
1175
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1176
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1177
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1178
-	 */
1179
-	private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1180
-		$postFix = (substr($path, -1) === '/') ? '/' : '';
1181
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1182
-		if (Filesystem::isValidPath($path)
1183
-			&& !Filesystem::isFileBlacklisted($path)
1184
-		) {
1185
-			$path = $this->getRelativePath($absolutePath);
1186
-			if ($path == null) {
1187
-				return false;
1188
-			}
1189
-
1190
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1191
-				// always a shared lock during pre-hooks so the hook can read the file
1192
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1193
-			}
1194
-
1195
-			$run = $this->runHooks($hooks, $path);
1196
-			[$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1197
-			if ($run && $storage) {
1198
-				/** @var Storage $storage */
1199
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1200
-					try {
1201
-						$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1202
-					} catch (LockedException $e) {
1203
-						// release the shared lock we acquired before quitting
1204
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1205
-						throw $e;
1206
-					}
1207
-				}
1208
-				try {
1209
-					if (!is_null($extraParam)) {
1210
-						$result = $storage->$operation($internalPath, $extraParam);
1211
-					} else {
1212
-						$result = $storage->$operation($internalPath);
1213
-					}
1214
-				} catch (\Exception $e) {
1215
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1216
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1217
-					} elseif (in_array('read', $hooks)) {
1218
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1219
-					}
1220
-					throw $e;
1221
-				}
1222
-
1223
-				if ($result !== false && in_array('delete', $hooks)) {
1224
-					$this->removeUpdate($storage, $internalPath);
1225
-				}
1226
-				if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1227
-					$isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
1228
-					$sizeDifference = $operation === 'mkdir' ? 0 : $result;
1229
-					$this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
1230
-				}
1231
-				if ($result !== false && in_array('touch', $hooks)) {
1232
-					$this->writeUpdate($storage, $internalPath, $extraParam, 0);
1233
-				}
1234
-
1235
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1236
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1237
-				}
1238
-
1239
-				$unlockLater = false;
1240
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1241
-					$unlockLater = true;
1242
-					// make sure our unlocking callback will still be called if connection is aborted
1243
-					ignore_user_abort(true);
1244
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1245
-						if (in_array('write', $hooks)) {
1246
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1247
-						} elseif (in_array('read', $hooks)) {
1248
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1249
-						}
1250
-					});
1251
-				}
1252
-
1253
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1254
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1255
-						$this->runHooks($hooks, $path, true);
1256
-					}
1257
-				}
1258
-
1259
-				if (!$unlockLater
1260
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1261
-				) {
1262
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1263
-				}
1264
-				return $result;
1265
-			} else {
1266
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1267
-			}
1268
-		}
1269
-		return null;
1270
-	}
1271
-
1272
-	/**
1273
-	 * get the path relative to the default root for hook usage
1274
-	 *
1275
-	 * @param string $path
1276
-	 * @return ?string
1277
-	 */
1278
-	private function getHookPath($path): ?string {
1279
-		$view = Filesystem::getView();
1280
-		if (!$view) {
1281
-			return $path;
1282
-		}
1283
-		return $view->getRelativePath($this->getAbsolutePath($path));
1284
-	}
1285
-
1286
-	private function shouldEmitHooks(string $path = ''): bool {
1287
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1288
-			return false;
1289
-		}
1290
-		if (!Filesystem::$loaded) {
1291
-			return false;
1292
-		}
1293
-		$defaultRoot = Filesystem::getRoot();
1294
-		if ($defaultRoot === null) {
1295
-			return false;
1296
-		}
1297
-		if ($this->fakeRoot === $defaultRoot) {
1298
-			return true;
1299
-		}
1300
-		$fullPath = $this->getAbsolutePath($path);
1301
-
1302
-		if ($fullPath === $defaultRoot) {
1303
-			return true;
1304
-		}
1305
-
1306
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1307
-	}
1308
-
1309
-	/**
1310
-	 * @param string[] $hooks
1311
-	 * @param string $path
1312
-	 * @param bool $post
1313
-	 * @return bool
1314
-	 */
1315
-	private function runHooks($hooks, $path, $post = false) {
1316
-		$relativePath = $path;
1317
-		$path = $this->getHookPath($path);
1318
-		$prefix = $post ? 'post_' : '';
1319
-		$run = true;
1320
-		if ($this->shouldEmitHooks($relativePath)) {
1321
-			foreach ($hooks as $hook) {
1322
-				if ($hook != 'read') {
1323
-					\OC_Hook::emit(
1324
-						Filesystem::CLASSNAME,
1325
-						$prefix . $hook,
1326
-						[
1327
-							Filesystem::signal_param_run => &$run,
1328
-							Filesystem::signal_param_path => $path
1329
-						]
1330
-					);
1331
-				} elseif (!$post) {
1332
-					\OC_Hook::emit(
1333
-						Filesystem::CLASSNAME,
1334
-						$prefix . $hook,
1335
-						[
1336
-							Filesystem::signal_param_path => $path
1337
-						]
1338
-					);
1339
-				}
1340
-			}
1341
-		}
1342
-		return $run;
1343
-	}
1344
-
1345
-	/**
1346
-	 * check if a file or folder has been updated since $time
1347
-	 *
1348
-	 * @param string $path
1349
-	 * @param int $time
1350
-	 * @return bool
1351
-	 */
1352
-	public function hasUpdated($path, $time) {
1353
-		return $this->basicOperation('hasUpdated', $path, [], $time);
1354
-	}
1355
-
1356
-	/**
1357
-	 * @param string $ownerId
1358
-	 * @return IUser
1359
-	 */
1360
-	private function getUserObjectForOwner(string $ownerId) {
1361
-		return new LazyUser($ownerId, $this->userManager);
1362
-	}
1363
-
1364
-	/**
1365
-	 * Get file info from cache
1366
-	 *
1367
-	 * If the file is not in cached it will be scanned
1368
-	 * If the file has changed on storage the cache will be updated
1369
-	 *
1370
-	 * @param Storage $storage
1371
-	 * @param string $internalPath
1372
-	 * @param string $relativePath
1373
-	 * @return ICacheEntry|bool
1374
-	 */
1375
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1376
-		$cache = $storage->getCache($internalPath);
1377
-		$data = $cache->get($internalPath);
1378
-		$watcher = $storage->getWatcher($internalPath);
1379
-
1380
-		try {
1381
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1382
-			if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1383
-				if (!$storage->file_exists($internalPath)) {
1384
-					return false;
1385
-				}
1386
-				// don't need to get a lock here since the scanner does it's own locking
1387
-				$scanner = $storage->getScanner($internalPath);
1388
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1389
-				$data = $cache->get($internalPath);
1390
-			} elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1391
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1392
-				$watcher->update($internalPath, $data);
1393
-				$storage->getPropagator()->propagateChange($internalPath, time());
1394
-				$data = $cache->get($internalPath);
1395
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1396
-			}
1397
-		} catch (LockedException $e) {
1398
-			// if the file is locked we just use the old cache info
1399
-		}
1400
-
1401
-		return $data;
1402
-	}
1403
-
1404
-	/**
1405
-	 * get the filesystem info
1406
-	 *
1407
-	 * @param string $path
1408
-	 * @param bool|string $includeMountPoints true to add mountpoint sizes,
1409
-	 *                                        'ext' to add only ext storage mount point sizes. Defaults to true.
1410
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1411
-	 */
1412
-	public function getFileInfo($path, $includeMountPoints = true) {
1413
-		$this->assertPathLength($path);
1414
-		if (!Filesystem::isValidPath($path)) {
1415
-			return false;
1416
-		}
1417
-		$relativePath = $path;
1418
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1419
-
1420
-		$mount = Filesystem::getMountManager()->find($path);
1421
-		$storage = $mount->getStorage();
1422
-		$internalPath = $mount->getInternalPath($path);
1423
-		if ($storage) {
1424
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1425
-
1426
-			if (!$data instanceof ICacheEntry) {
1427
-				if (Cache\Scanner::isPartialFile($relativePath)) {
1428
-					return $this->getPartFileInfo($relativePath);
1429
-				}
1430
-
1431
-				return false;
1432
-			}
1433
-
1434
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1435
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1436
-			}
1437
-			if ($internalPath === '' && $data['name']) {
1438
-				$data['name'] = basename($path);
1439
-			}
1440
-
1441
-			$ownerId = $storage->getOwner($internalPath);
1442
-			$owner = null;
1443
-			if ($ownerId !== false) {
1444
-				// ownerId might be null if files are accessed with an access token without file system access
1445
-				$owner = $this->getUserObjectForOwner($ownerId);
1446
-			}
1447
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1448
-
1449
-			if (isset($data['fileid'])) {
1450
-				if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1451
-					//add the sizes of other mount points to the folder
1452
-					$extOnly = ($includeMountPoints === 'ext');
1453
-					$this->addSubMounts($info, $extOnly);
1454
-				}
1455
-			}
1456
-
1457
-			return $info;
1458
-		} else {
1459
-			$this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1460
-		}
1461
-
1462
-		return false;
1463
-	}
1464
-
1465
-	/**
1466
-	 * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1467
-	 */
1468
-	public function addSubMounts(FileInfo $info, $extOnly = false): void {
1469
-		$mounts = Filesystem::getMountManager()->findIn($info->getPath());
1470
-		$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1471
-			return !($extOnly && $mount instanceof SharedMount);
1472
-		}));
1473
-	}
1474
-
1475
-	/**
1476
-	 * get the content of a directory
1477
-	 *
1478
-	 * @param string $directory path under datadirectory
1479
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1480
-	 * @return FileInfo[]
1481
-	 */
1482
-	public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
1483
-		$this->assertPathLength($directory);
1484
-		if (!Filesystem::isValidPath($directory)) {
1485
-			return [];
1486
-		}
1487
-
1488
-		$path = $this->getAbsolutePath($directory);
1489
-		$path = Filesystem::normalizePath($path);
1490
-		$mount = $this->getMount($directory);
1491
-		$storage = $mount->getStorage();
1492
-		$internalPath = $mount->getInternalPath($path);
1493
-		if (!$storage) {
1494
-			return [];
1495
-		}
1496
-
1497
-		$cache = $storage->getCache($internalPath);
1498
-		$user = \OC_User::getUser();
1499
-
1500
-		if (!$directoryInfo) {
1501
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1502
-			if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1503
-				return [];
1504
-			}
1505
-		} else {
1506
-			$data = $directoryInfo;
1507
-		}
1508
-
1509
-		if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1510
-			return [];
1511
-		}
1512
-
1513
-		$folderId = $data->getId();
1514
-		$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1515
-
1516
-		$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1517
-
1518
-		$fileNames = array_map(function (ICacheEntry $content) {
1519
-			return $content->getName();
1520
-		}, $contents);
1521
-		/**
1522
-		 * @var \OC\Files\FileInfo[] $fileInfos
1523
-		 */
1524
-		$fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1525
-			if ($sharingDisabled) {
1526
-				$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1527
-			}
1528
-			$ownerId = $storage->getOwner($content['path']);
1529
-			if ($ownerId !== false) {
1530
-				$owner = $this->getUserObjectForOwner($ownerId);
1531
-			} else {
1532
-				$owner = null;
1533
-			}
1534
-			return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1535
-		}, $contents);
1536
-		$files = array_combine($fileNames, $fileInfos);
1537
-
1538
-		//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1539
-		$mounts = Filesystem::getMountManager()->findIn($path);
1540
-
1541
-		// make sure nested mounts are sorted after their parent mounts
1542
-		// otherwise doesn't propagate the etag across storage boundaries correctly
1543
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1544
-			return $a->getMountPoint() <=> $b->getMountPoint();
1545
-		});
1546
-
1547
-		$dirLength = strlen($path);
1548
-		foreach ($mounts as $mount) {
1549
-			$mountPoint = $mount->getMountPoint();
1550
-			$subStorage = $mount->getStorage();
1551
-			if ($subStorage) {
1552
-				$subCache = $subStorage->getCache('');
1553
-
1554
-				$rootEntry = $subCache->get('');
1555
-				if (!$rootEntry) {
1556
-					$subScanner = $subStorage->getScanner();
1557
-					try {
1558
-						$subScanner->scanFile('');
1559
-					} catch (\OCP\Files\StorageNotAvailableException $e) {
1560
-						continue;
1561
-					} catch (\OCP\Files\StorageInvalidException $e) {
1562
-						continue;
1563
-					} catch (\Exception $e) {
1564
-						// sometimes when the storage is not available it can be any exception
1565
-						$this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1566
-							'exception' => $e,
1567
-							'app' => 'core',
1568
-						]);
1569
-						continue;
1570
-					}
1571
-					$rootEntry = $subCache->get('');
1572
-				}
1573
-
1574
-				if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1575
-					$relativePath = trim(substr($mountPoint, $dirLength), '/');
1576
-					if ($pos = strpos($relativePath, '/')) {
1577
-						//mountpoint inside subfolder add size to the correct folder
1578
-						$entryName = substr($relativePath, 0, $pos);
1579
-
1580
-						// Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1581
-						if (!isset($files[$entryName])) {
1582
-							try {
1583
-								[$storage, ] = $this->resolvePath($path . '/' . $entryName);
1584
-								// make sure we can create the mountpoint folder, even if the user has a quota of 0
1585
-								if ($storage->instanceOfStorage(Quota::class)) {
1586
-									$storage->enableQuota(false);
1587
-								}
1588
-
1589
-								if ($this->mkdir($path . '/' . $entryName) !== false) {
1590
-									$info = $this->getFileInfo($path . '/' . $entryName);
1591
-									if ($info !== false) {
1592
-										$files[$entryName] = $info;
1593
-									}
1594
-								}
1595
-
1596
-								if ($storage->instanceOfStorage(Quota::class)) {
1597
-									$storage->enableQuota(true);
1598
-								}
1599
-							} catch (\Exception $e) {
1600
-								// Creating the parent folder might not be possible, for example due to a lack of permissions.
1601
-								$this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1602
-							}
1603
-						}
1604
-
1605
-						if (isset($files[$entryName])) {
1606
-							$files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1607
-						}
1608
-					} else { //mountpoint in this folder, add an entry for it
1609
-						$rootEntry['name'] = $relativePath;
1610
-						$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1611
-						$permissions = $rootEntry['permissions'];
1612
-						// do not allow renaming/deleting the mount point if they are not shared files/folders
1613
-						// for shared files/folders we use the permissions given by the owner
1614
-						if ($mount instanceof MoveableMount) {
1615
-							$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1616
-						} else {
1617
-							$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1618
-						}
1619
-
1620
-						$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1621
-
1622
-						// if sharing was disabled for the user we remove the share permissions
1623
-						if ($sharingDisabled) {
1624
-							$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1625
-						}
1626
-
1627
-						$ownerId = $subStorage->getOwner('');
1628
-						if ($ownerId !== false) {
1629
-							$owner = $this->getUserObjectForOwner($ownerId);
1630
-						} else {
1631
-							$owner = null;
1632
-						}
1633
-						$files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1634
-					}
1635
-				}
1636
-			}
1637
-		}
1638
-
1639
-		if ($mimetype_filter) {
1640
-			$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1641
-				if (strpos($mimetype_filter, '/')) {
1642
-					return $file->getMimetype() === $mimetype_filter;
1643
-				} else {
1644
-					return $file->getMimePart() === $mimetype_filter;
1645
-				}
1646
-			});
1647
-		}
1648
-
1649
-		return array_values($files);
1650
-	}
1651
-
1652
-	/**
1653
-	 * change file metadata
1654
-	 *
1655
-	 * @param string $path
1656
-	 * @param array|\OCP\Files\FileInfo $data
1657
-	 * @return int
1658
-	 *
1659
-	 * returns the fileid of the updated file
1660
-	 */
1661
-	public function putFileInfo($path, $data) {
1662
-		$this->assertPathLength($path);
1663
-		if ($data instanceof FileInfo) {
1664
-			$data = $data->getData();
1665
-		}
1666
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1667
-		/**
1668
-		 * @var Storage $storage
1669
-		 * @var string $internalPath
1670
-		 */
1671
-		[$storage, $internalPath] = Filesystem::resolvePath($path);
1672
-		if ($storage) {
1673
-			$cache = $storage->getCache($path);
1674
-
1675
-			if (!$cache->inCache($internalPath)) {
1676
-				$scanner = $storage->getScanner($internalPath);
1677
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1678
-			}
1679
-
1680
-			return $cache->put($internalPath, $data);
1681
-		} else {
1682
-			return -1;
1683
-		}
1684
-	}
1685
-
1686
-	/**
1687
-	 * search for files with the name matching $query
1688
-	 *
1689
-	 * @param string $query
1690
-	 * @return FileInfo[]
1691
-	 */
1692
-	public function search($query) {
1693
-		return $this->searchCommon('search', ['%' . $query . '%']);
1694
-	}
1695
-
1696
-	/**
1697
-	 * search for files with the name matching $query
1698
-	 *
1699
-	 * @param string $query
1700
-	 * @return FileInfo[]
1701
-	 */
1702
-	public function searchRaw($query) {
1703
-		return $this->searchCommon('search', [$query]);
1704
-	}
1705
-
1706
-	/**
1707
-	 * search for files by mimetype
1708
-	 *
1709
-	 * @param string $mimetype
1710
-	 * @return FileInfo[]
1711
-	 */
1712
-	public function searchByMime($mimetype) {
1713
-		return $this->searchCommon('searchByMime', [$mimetype]);
1714
-	}
1715
-
1716
-	/**
1717
-	 * search for files by tag
1718
-	 *
1719
-	 * @param string|int $tag name or tag id
1720
-	 * @param string $userId owner of the tags
1721
-	 * @return FileInfo[]
1722
-	 */
1723
-	public function searchByTag($tag, $userId) {
1724
-		return $this->searchCommon('searchByTag', [$tag, $userId]);
1725
-	}
1726
-
1727
-	/**
1728
-	 * @param string $method cache method
1729
-	 * @param array $args
1730
-	 * @return FileInfo[]
1731
-	 */
1732
-	private function searchCommon($method, $args) {
1733
-		$files = [];
1734
-		$rootLength = strlen($this->fakeRoot);
1735
-
1736
-		$mount = $this->getMount('');
1737
-		$mountPoint = $mount->getMountPoint();
1738
-		$storage = $mount->getStorage();
1739
-		$userManager = \OC::$server->getUserManager();
1740
-		if ($storage) {
1741
-			$cache = $storage->getCache('');
1742
-
1743
-			$results = call_user_func_array([$cache, $method], $args);
1744
-			foreach ($results as $result) {
1745
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1746
-					$internalPath = $result['path'];
1747
-					$path = $mountPoint . $result['path'];
1748
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1749
-					$ownerId = $storage->getOwner($internalPath);
1750
-					if ($ownerId !== false) {
1751
-						$owner = $userManager->get($ownerId);
1752
-					} else {
1753
-						$owner = null;
1754
-					}
1755
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1756
-				}
1757
-			}
1758
-
1759
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1760
-			foreach ($mounts as $mount) {
1761
-				$mountPoint = $mount->getMountPoint();
1762
-				$storage = $mount->getStorage();
1763
-				if ($storage) {
1764
-					$cache = $storage->getCache('');
1765
-
1766
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1767
-					$results = call_user_func_array([$cache, $method], $args);
1768
-					if ($results) {
1769
-						foreach ($results as $result) {
1770
-							$internalPath = $result['path'];
1771
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1772
-							$path = rtrim($mountPoint . $internalPath, '/');
1773
-							$ownerId = $storage->getOwner($internalPath);
1774
-							if ($ownerId !== false) {
1775
-								$owner = $userManager->get($ownerId);
1776
-							} else {
1777
-								$owner = null;
1778
-							}
1779
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1780
-						}
1781
-					}
1782
-				}
1783
-			}
1784
-		}
1785
-		return $files;
1786
-	}
1787
-
1788
-	/**
1789
-	 * Get the owner for a file or folder
1790
-	 *
1791
-	 * @throws NotFoundException
1792
-	 */
1793
-	public function getOwner(string $path): string {
1794
-		$info = $this->getFileInfo($path);
1795
-		if (!$info) {
1796
-			throw new NotFoundException($path . ' not found while trying to get owner');
1797
-		}
1798
-
1799
-		if ($info->getOwner() === null) {
1800
-			throw new NotFoundException($path . ' has no owner');
1801
-		}
1802
-
1803
-		return $info->getOwner()->getUID();
1804
-	}
1805
-
1806
-	/**
1807
-	 * get the ETag for a file or folder
1808
-	 *
1809
-	 * @param string $path
1810
-	 * @return string|false
1811
-	 */
1812
-	public function getETag($path) {
1813
-		[$storage, $internalPath] = $this->resolvePath($path);
1814
-		if ($storage) {
1815
-			return $storage->getETag($internalPath);
1816
-		} else {
1817
-			return false;
1818
-		}
1819
-	}
1820
-
1821
-	/**
1822
-	 * Get the path of a file by id, relative to the view
1823
-	 *
1824
-	 * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1825
-	 *
1826
-	 * @param int $id
1827
-	 * @param int|null $storageId
1828
-	 * @return string
1829
-	 * @throws NotFoundException
1830
-	 */
1831
-	public function getPath($id, ?int $storageId = null) {
1832
-		$id = (int)$id;
1833
-		$manager = Filesystem::getMountManager();
1834
-		$mounts = $manager->findIn($this->fakeRoot);
1835
-		$mounts[] = $manager->find($this->fakeRoot);
1836
-		$mounts = array_filter($mounts);
1837
-		// reverse the array, so we start with the storage this view is in
1838
-		// which is the most likely to contain the file we're looking for
1839
-		$mounts = array_reverse($mounts);
1840
-
1841
-		// put non-shared mounts in front of the shared mount
1842
-		// this prevents unneeded recursion into shares
1843
-		usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1844
-			return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1845
-		});
1846
-
1847
-		if (!is_null($storageId)) {
1848
-			$mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1849
-				return $mount->getNumericStorageId() === $storageId;
1850
-			});
1851
-		}
1852
-
1853
-		foreach ($mounts as $mount) {
1854
-			/**
1855
-			 * @var \OC\Files\Mount\MountPoint $mount
1856
-			 */
1857
-			if ($mount->getStorage()) {
1858
-				$cache = $mount->getStorage()->getCache();
1859
-				$internalPath = $cache->getPathById($id);
1860
-				if (is_string($internalPath)) {
1861
-					$fullPath = $mount->getMountPoint() . $internalPath;
1862
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1863
-						return $path;
1864
-					}
1865
-				}
1866
-			}
1867
-		}
1868
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1869
-	}
1870
-
1871
-	/**
1872
-	 * @param string $path
1873
-	 * @throws InvalidPathException
1874
-	 */
1875
-	private function assertPathLength($path): void {
1876
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1877
-		// Check for the string length - performed using isset() instead of strlen()
1878
-		// because isset() is about 5x-40x faster.
1879
-		if (isset($path[$maxLen])) {
1880
-			$pathLen = strlen($path);
1881
-			throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1882
-		}
1883
-	}
1884
-
1885
-	/**
1886
-	 * check if it is allowed to move a mount point to a given target.
1887
-	 * It is not allowed to move a mount point into a different mount point or
1888
-	 * into an already shared folder
1889
-	 */
1890
-	private function targetIsNotShared(string $user, string $targetPath): bool {
1891
-		$providers = [
1892
-			IShare::TYPE_USER,
1893
-			IShare::TYPE_GROUP,
1894
-			IShare::TYPE_EMAIL,
1895
-			IShare::TYPE_CIRCLE,
1896
-			IShare::TYPE_ROOM,
1897
-			IShare::TYPE_DECK,
1898
-			IShare::TYPE_SCIENCEMESH
1899
-		];
1900
-		$shareManager = Server::get(IManager::class);
1901
-		/** @var IShare[] $shares */
1902
-		$shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1903
-			return $shareManager->getSharesBy($user, $type);
1904
-		}, $providers));
1905
-
1906
-		foreach ($shares as $share) {
1907
-			$sharedPath = $share->getNode()->getPath();
1908
-			if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1909
-				$this->logger->debug(
1910
-					'It is not allowed to move one mount point into a shared folder',
1911
-					['app' => 'files']);
1912
-				return false;
1913
-			}
1914
-		}
1915
-
1916
-		return true;
1917
-	}
1918
-
1919
-	/**
1920
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1921
-	 */
1922
-	private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1923
-		$mount = $this->getMount($path);
1924
-		$storage = $mount->getStorage();
1925
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1926
-		$ownerId = $storage->getOwner($internalPath);
1927
-		if ($ownerId !== false) {
1928
-			$owner = Server::get(IUserManager::class)->get($ownerId);
1929
-		} else {
1930
-			$owner = null;
1931
-		}
1932
-		return new FileInfo(
1933
-			$this->getAbsolutePath($path),
1934
-			$storage,
1935
-			$internalPath,
1936
-			[
1937
-				'fileid' => null,
1938
-				'mimetype' => $storage->getMimeType($internalPath),
1939
-				'name' => basename($path),
1940
-				'etag' => null,
1941
-				'size' => $storage->filesize($internalPath),
1942
-				'mtime' => $storage->filemtime($internalPath),
1943
-				'encrypted' => false,
1944
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1945
-			],
1946
-			$mount,
1947
-			$owner
1948
-		);
1949
-	}
1950
-
1951
-	/**
1952
-	 * @param string $path
1953
-	 * @param string $fileName
1954
-	 * @param bool $readonly Check only if the path is allowed for read-only access
1955
-	 * @throws InvalidPathException
1956
-	 */
1957
-	public function verifyPath($path, $fileName, $readonly = false): void {
1958
-		// All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
1959
-		if (!Filesystem::isValidPath($path ?: '/')) {
1960
-			$l = \OCP\Util::getL10N('lib');
1961
-			throw new InvalidPathException($l->t('Path contains invalid segments'));
1962
-		}
1963
-
1964
-		// Short cut for read-only validation
1965
-		if ($readonly) {
1966
-			$validator = Server::get(FilenameValidator::class);
1967
-			if ($validator->isForbidden($fileName)) {
1968
-				$l = \OCP\Util::getL10N('lib');
1969
-				throw new InvalidPathException($l->t('Filename is a reserved word'));
1970
-			}
1971
-			return;
1972
-		}
1973
-
1974
-		try {
1975
-			/** @type \OCP\Files\Storage $storage */
1976
-			[$storage, $internalPath] = $this->resolvePath($path);
1977
-			$storage->verifyPath($internalPath, $fileName);
1978
-		} catch (ReservedWordException $ex) {
1979
-			$l = \OCP\Util::getL10N('lib');
1980
-			throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
1981
-		} catch (InvalidCharacterInPathException $ex) {
1982
-			$l = \OCP\Util::getL10N('lib');
1983
-			throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
1984
-		} catch (FileNameTooLongException $ex) {
1985
-			$l = \OCP\Util::getL10N('lib');
1986
-			throw new InvalidPathException($l->t('Filename is too long'));
1987
-		} catch (InvalidDirectoryException $ex) {
1988
-			$l = \OCP\Util::getL10N('lib');
1989
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1990
-		} catch (EmptyFileNameException $ex) {
1991
-			$l = \OCP\Util::getL10N('lib');
1992
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1993
-		}
1994
-	}
1995
-
1996
-	/**
1997
-	 * get all parent folders of $path
1998
-	 *
1999
-	 * @param string $path
2000
-	 * @return string[]
2001
-	 */
2002
-	private function getParents($path) {
2003
-		$path = trim($path, '/');
2004
-		if (!$path) {
2005
-			return [];
2006
-		}
2007
-
2008
-		$parts = explode('/', $path);
2009
-
2010
-		// remove the single file
2011
-		array_pop($parts);
2012
-		$result = ['/'];
2013
-		$resultPath = '';
2014
-		foreach ($parts as $part) {
2015
-			if ($part) {
2016
-				$resultPath .= '/' . $part;
2017
-				$result[] = $resultPath;
2018
-			}
2019
-		}
2020
-		return $result;
2021
-	}
2022
-
2023
-	/**
2024
-	 * Returns the mount point for which to lock
2025
-	 *
2026
-	 * @param string $absolutePath absolute path
2027
-	 * @param bool $useParentMount true to return parent mount instead of whatever
2028
-	 *                             is mounted directly on the given path, false otherwise
2029
-	 * @return IMountPoint mount point for which to apply locks
2030
-	 */
2031
-	private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
2032
-		$mount = Filesystem::getMountManager()->find($absolutePath);
2033
-
2034
-		if ($useParentMount) {
2035
-			// find out if something is mounted directly on the path
2036
-			$internalPath = $mount->getInternalPath($absolutePath);
2037
-			if ($internalPath === '') {
2038
-				// resolve the parent mount instead
2039
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
2040
-			}
2041
-		}
2042
-
2043
-		return $mount;
2044
-	}
2045
-
2046
-	/**
2047
-	 * Lock the given path
2048
-	 *
2049
-	 * @param string $path the path of the file to lock, relative to the view
2050
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
-	 *
2053
-	 * @return bool False if the path is excluded from locking, true otherwise
2054
-	 * @throws LockedException if the path is already locked
2055
-	 */
2056
-	private function lockPath($path, $type, $lockMountPoint = false) {
2057
-		$absolutePath = $this->getAbsolutePath($path);
2058
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2059
-		if (!$this->shouldLockFile($absolutePath)) {
2060
-			return false;
2061
-		}
2062
-
2063
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2064
-		try {
2065
-			$storage = $mount->getStorage();
2066
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2067
-				$storage->acquireLock(
2068
-					$mount->getInternalPath($absolutePath),
2069
-					$type,
2070
-					$this->lockingProvider
2071
-				);
2072
-			}
2073
-		} catch (LockedException $e) {
2074
-			// rethrow with the human-readable path
2075
-			throw new LockedException(
2076
-				$path,
2077
-				$e,
2078
-				$e->getExistingLock()
2079
-			);
2080
-		}
2081
-
2082
-		return true;
2083
-	}
2084
-
2085
-	/**
2086
-	 * Change the lock type
2087
-	 *
2088
-	 * @param string $path the path of the file to lock, relative to the view
2089
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2090
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2091
-	 *
2092
-	 * @return bool False if the path is excluded from locking, true otherwise
2093
-	 * @throws LockedException if the path is already locked
2094
-	 */
2095
-	public function changeLock($path, $type, $lockMountPoint = false) {
2096
-		$path = Filesystem::normalizePath($path);
2097
-		$absolutePath = $this->getAbsolutePath($path);
2098
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2099
-		if (!$this->shouldLockFile($absolutePath)) {
2100
-			return false;
2101
-		}
2102
-
2103
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2104
-		try {
2105
-			$storage = $mount->getStorage();
2106
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2107
-				$storage->changeLock(
2108
-					$mount->getInternalPath($absolutePath),
2109
-					$type,
2110
-					$this->lockingProvider
2111
-				);
2112
-			}
2113
-		} catch (LockedException $e) {
2114
-			// rethrow with the a human-readable path
2115
-			throw new LockedException(
2116
-				$path,
2117
-				$e,
2118
-				$e->getExistingLock()
2119
-			);
2120
-		}
2121
-
2122
-		return true;
2123
-	}
2124
-
2125
-	/**
2126
-	 * Unlock the given path
2127
-	 *
2128
-	 * @param string $path the path of the file to unlock, relative to the view
2129
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2130
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2131
-	 *
2132
-	 * @return bool False if the path is excluded from locking, true otherwise
2133
-	 * @throws LockedException
2134
-	 */
2135
-	private function unlockPath($path, $type, $lockMountPoint = false) {
2136
-		$absolutePath = $this->getAbsolutePath($path);
2137
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2138
-		if (!$this->shouldLockFile($absolutePath)) {
2139
-			return false;
2140
-		}
2141
-
2142
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2143
-		$storage = $mount->getStorage();
2144
-		if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2145
-			$storage->releaseLock(
2146
-				$mount->getInternalPath($absolutePath),
2147
-				$type,
2148
-				$this->lockingProvider
2149
-			);
2150
-		}
2151
-
2152
-		return true;
2153
-	}
2154
-
2155
-	/**
2156
-	 * Lock a path and all its parents up to the root of the view
2157
-	 *
2158
-	 * @param string $path the path of the file to lock relative to the view
2159
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2160
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2161
-	 *
2162
-	 * @return bool False if the path is excluded from locking, true otherwise
2163
-	 * @throws LockedException
2164
-	 */
2165
-	public function lockFile($path, $type, $lockMountPoint = false) {
2166
-		$absolutePath = $this->getAbsolutePath($path);
2167
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2168
-		if (!$this->shouldLockFile($absolutePath)) {
2169
-			return false;
2170
-		}
2171
-
2172
-		$this->lockPath($path, $type, $lockMountPoint);
2173
-
2174
-		$parents = $this->getParents($path);
2175
-		foreach ($parents as $parent) {
2176
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2177
-		}
2178
-
2179
-		return true;
2180
-	}
2181
-
2182
-	/**
2183
-	 * Unlock a path and all its parents up to the root of the view
2184
-	 *
2185
-	 * @param string $path the path of the file to lock relative to the view
2186
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2187
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2188
-	 *
2189
-	 * @return bool False if the path is excluded from locking, true otherwise
2190
-	 * @throws LockedException
2191
-	 */
2192
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2193
-		$absolutePath = $this->getAbsolutePath($path);
2194
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2195
-		if (!$this->shouldLockFile($absolutePath)) {
2196
-			return false;
2197
-		}
2198
-
2199
-		$this->unlockPath($path, $type, $lockMountPoint);
2200
-
2201
-		$parents = $this->getParents($path);
2202
-		foreach ($parents as $parent) {
2203
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2204
-		}
2205
-
2206
-		return true;
2207
-	}
2208
-
2209
-	/**
2210
-	 * Only lock files in data/user/files/
2211
-	 *
2212
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2213
-	 * @return bool
2214
-	 */
2215
-	protected function shouldLockFile($path) {
2216
-		$path = Filesystem::normalizePath($path);
2217
-
2218
-		$pathSegments = explode('/', $path);
2219
-		if (isset($pathSegments[2])) {
2220
-			// E.g.: /username/files/path-to-file
2221
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2222
-		}
2223
-
2224
-		return !str_starts_with($path, '/appdata_');
2225
-	}
2226
-
2227
-	/**
2228
-	 * Shortens the given absolute path to be relative to
2229
-	 * "$user/files".
2230
-	 *
2231
-	 * @param string $absolutePath absolute path which is under "files"
2232
-	 *
2233
-	 * @return string path relative to "files" with trimmed slashes or null
2234
-	 *                if the path was NOT relative to files
2235
-	 *
2236
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2237
-	 * @since 8.1.0
2238
-	 */
2239
-	public function getPathRelativeToFiles($absolutePath) {
2240
-		$path = Filesystem::normalizePath($absolutePath);
2241
-		$parts = explode('/', trim($path, '/'), 3);
2242
-		// "$user", "files", "path/to/dir"
2243
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2244
-			$this->logger->error(
2245
-				'$absolutePath must be relative to "files", value is "{absolutePath}"',
2246
-				[
2247
-					'absolutePath' => $absolutePath,
2248
-				]
2249
-			);
2250
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2251
-		}
2252
-		if (isset($parts[2])) {
2253
-			return $parts[2];
2254
-		}
2255
-		return '';
2256
-	}
2257
-
2258
-	/**
2259
-	 * @param string $filename
2260
-	 * @return array
2261
-	 * @throws \OC\User\NoUserException
2262
-	 * @throws NotFoundException
2263
-	 */
2264
-	public function getUidAndFilename($filename) {
2265
-		$info = $this->getFileInfo($filename);
2266
-		if (!$info instanceof \OCP\Files\FileInfo) {
2267
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2268
-		}
2269
-		$uid = $info->getOwner()->getUID();
2270
-		if ($uid != \OC_User::getUser()) {
2271
-			Filesystem::initMountPoints($uid);
2272
-			$ownerView = new View('/' . $uid . '/files');
2273
-			try {
2274
-				$filename = $ownerView->getPath($info['fileid']);
2275
-			} catch (NotFoundException $e) {
2276
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2277
-			}
2278
-		}
2279
-		return [$uid, $filename];
2280
-	}
2281
-
2282
-	/**
2283
-	 * Creates parent non-existing folders
2284
-	 *
2285
-	 * @param string $filePath
2286
-	 * @return bool
2287
-	 */
2288
-	private function createParentDirectories($filePath) {
2289
-		$directoryParts = explode('/', $filePath);
2290
-		$directoryParts = array_filter($directoryParts);
2291
-		foreach ($directoryParts as $key => $part) {
2292
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2293
-			$currentPath = '/' . implode('/', $currentPathElements);
2294
-			if ($this->is_file($currentPath)) {
2295
-				return false;
2296
-			}
2297
-			if (!$this->file_exists($currentPath)) {
2298
-				$this->mkdir($currentPath);
2299
-			}
2300
-		}
2301
-
2302
-		return true;
2303
-	}
60
+    private string $fakeRoot = '';
61
+    private ILockingProvider $lockingProvider;
62
+    private bool $lockingEnabled;
63
+    private bool $updaterEnabled = true;
64
+    private UserManager $userManager;
65
+    private LoggerInterface $logger;
66
+
67
+    /**
68
+     * @throws \Exception If $root contains an invalid path
69
+     */
70
+    public function __construct(string $root = '') {
71
+        if (!Filesystem::isValidPath($root)) {
72
+            throw new \Exception();
73
+        }
74
+
75
+        $this->fakeRoot = $root;
76
+        $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
77
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
78
+        $this->userManager = \OC::$server->getUserManager();
79
+        $this->logger = \OC::$server->get(LoggerInterface::class);
80
+    }
81
+
82
+    /**
83
+     * @param ?string $path
84
+     * @psalm-template S as string|null
85
+     * @psalm-param S $path
86
+     * @psalm-return (S is string ? string : null)
87
+     */
88
+    public function getAbsolutePath($path = '/'): ?string {
89
+        if ($path === null) {
90
+            return null;
91
+        }
92
+        $this->assertPathLength($path);
93
+        if ($path === '') {
94
+            $path = '/';
95
+        }
96
+        if ($path[0] !== '/') {
97
+            $path = '/' . $path;
98
+        }
99
+        return $this->fakeRoot . $path;
100
+    }
101
+
102
+    /**
103
+     * Change the root to a fake root
104
+     *
105
+     * @param string $fakeRoot
106
+     */
107
+    public function chroot($fakeRoot): void {
108
+        if (!$fakeRoot == '') {
109
+            if ($fakeRoot[0] !== '/') {
110
+                $fakeRoot = '/' . $fakeRoot;
111
+            }
112
+        }
113
+        $this->fakeRoot = $fakeRoot;
114
+    }
115
+
116
+    /**
117
+     * Get the fake root
118
+     */
119
+    public function getRoot(): string {
120
+        return $this->fakeRoot;
121
+    }
122
+
123
+    /**
124
+     * get path relative to the root of the view
125
+     *
126
+     * @param string $path
127
+     */
128
+    public function getRelativePath($path): ?string {
129
+        $this->assertPathLength($path);
130
+        if ($this->fakeRoot == '') {
131
+            return $path;
132
+        }
133
+
134
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
135
+            return '/';
136
+        }
137
+
138
+        // missing slashes can cause wrong matches!
139
+        $root = rtrim($this->fakeRoot, '/') . '/';
140
+
141
+        if (!str_starts_with($path, $root)) {
142
+            return null;
143
+        } else {
144
+            $path = substr($path, strlen($this->fakeRoot));
145
+            if (strlen($path) === 0) {
146
+                return '/';
147
+            } else {
148
+                return $path;
149
+            }
150
+        }
151
+    }
152
+
153
+    /**
154
+     * Get the mountpoint of the storage object for a path
155
+     * ( note: because a storage is not always mounted inside the fakeroot, the
156
+     * returned mountpoint is relative to the absolute root of the filesystem
157
+     * and does not take the chroot into account )
158
+     *
159
+     * @param string $path
160
+     */
161
+    public function getMountPoint($path): string {
162
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
163
+    }
164
+
165
+    /**
166
+     * Get the mountpoint of the storage object for a path
167
+     * ( note: because a storage is not always mounted inside the fakeroot, the
168
+     * returned mountpoint is relative to the absolute root of the filesystem
169
+     * and does not take the chroot into account )
170
+     *
171
+     * @param string $path
172
+     */
173
+    public function getMount($path): IMountPoint {
174
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
175
+    }
176
+
177
+    /**
178
+     * Resolve a path to a storage and internal path
179
+     *
180
+     * @param string $path
181
+     * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
182
+     */
183
+    public function resolvePath($path): array {
184
+        $a = $this->getAbsolutePath($path);
185
+        $p = Filesystem::normalizePath($a);
186
+        return Filesystem::resolvePath($p);
187
+    }
188
+
189
+    /**
190
+     * Return the path to a local version of the file
191
+     * we need this because we can't know if a file is stored local or not from
192
+     * outside the filestorage and for some purposes a local file is needed
193
+     *
194
+     * @param string $path
195
+     */
196
+    public function getLocalFile($path): string|false {
197
+        $parent = substr($path, 0, strrpos($path, '/') ?: 0);
198
+        $path = $this->getAbsolutePath($path);
199
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
200
+        if (Filesystem::isValidPath($parent) && $storage) {
201
+            return $storage->getLocalFile($internalPath);
202
+        } else {
203
+            return false;
204
+        }
205
+    }
206
+
207
+    /**
208
+     * the following functions operate with arguments and return values identical
209
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
210
+     * for \OC\Files\Storage\Storage via basicOperation().
211
+     */
212
+    public function mkdir($path) {
213
+        return $this->basicOperation('mkdir', $path, ['create', 'write']);
214
+    }
215
+
216
+    /**
217
+     * remove mount point
218
+     *
219
+     * @param IMountPoint $mount
220
+     * @param string $path relative to data/
221
+     */
222
+    protected function removeMount($mount, $path): bool {
223
+        if ($mount instanceof MoveableMount) {
224
+            // cut of /user/files to get the relative path to data/user/files
225
+            $pathParts = explode('/', $path, 4);
226
+            $relPath = '/' . $pathParts[3];
227
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
228
+            \OC_Hook::emit(
229
+                Filesystem::CLASSNAME, 'umount',
230
+                [Filesystem::signal_param_path => $relPath]
231
+            );
232
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
233
+            $result = $mount->removeMount();
234
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
235
+            if ($result) {
236
+                \OC_Hook::emit(
237
+                    Filesystem::CLASSNAME, 'post_umount',
238
+                    [Filesystem::signal_param_path => $relPath]
239
+                );
240
+            }
241
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
242
+            return $result;
243
+        } else {
244
+            // do not allow deleting the storage's root / the mount point
245
+            // because for some storages it might delete the whole contents
246
+            // but isn't supposed to work that way
247
+            return false;
248
+        }
249
+    }
250
+
251
+    public function disableCacheUpdate(): void {
252
+        $this->updaterEnabled = false;
253
+    }
254
+
255
+    public function enableCacheUpdate(): void {
256
+        $this->updaterEnabled = true;
257
+    }
258
+
259
+    protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
260
+        if ($this->updaterEnabled) {
261
+            if (is_null($time)) {
262
+                $time = time();
263
+            }
264
+            $storage->getUpdater()->update($internalPath, $time, $sizeDifference);
265
+        }
266
+    }
267
+
268
+    protected function removeUpdate(Storage $storage, string $internalPath): void {
269
+        if ($this->updaterEnabled) {
270
+            $storage->getUpdater()->remove($internalPath);
271
+        }
272
+    }
273
+
274
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
275
+        if ($this->updaterEnabled) {
276
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
277
+        }
278
+    }
279
+
280
+    protected function copyUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
281
+        if ($this->updaterEnabled) {
282
+            $targetStorage->getUpdater()->copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
283
+        }
284
+    }
285
+
286
+    /**
287
+     * @param string $path
288
+     * @return bool|mixed
289
+     */
290
+    public function rmdir($path) {
291
+        $absolutePath = $this->getAbsolutePath($path);
292
+        $mount = Filesystem::getMountManager()->find($absolutePath);
293
+        if ($mount->getInternalPath($absolutePath) === '') {
294
+            return $this->removeMount($mount, $absolutePath);
295
+        }
296
+        if ($this->is_dir($path)) {
297
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
298
+        } else {
299
+            $result = false;
300
+        }
301
+
302
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
303
+            $storage = $mount->getStorage();
304
+            $internalPath = $mount->getInternalPath($absolutePath);
305
+            $storage->getUpdater()->remove($internalPath);
306
+        }
307
+        return $result;
308
+    }
309
+
310
+    /**
311
+     * @param string $path
312
+     * @return resource|false
313
+     */
314
+    public function opendir($path) {
315
+        return $this->basicOperation('opendir', $path, ['read']);
316
+    }
317
+
318
+    /**
319
+     * @param string $path
320
+     * @return bool|mixed
321
+     */
322
+    public function is_dir($path) {
323
+        if ($path == '/') {
324
+            return true;
325
+        }
326
+        return $this->basicOperation('is_dir', $path);
327
+    }
328
+
329
+    /**
330
+     * @param string $path
331
+     * @return bool|mixed
332
+     */
333
+    public function is_file($path) {
334
+        if ($path == '/') {
335
+            return false;
336
+        }
337
+        return $this->basicOperation('is_file', $path);
338
+    }
339
+
340
+    /**
341
+     * @param string $path
342
+     * @return mixed
343
+     */
344
+    public function stat($path) {
345
+        return $this->basicOperation('stat', $path);
346
+    }
347
+
348
+    /**
349
+     * @param string $path
350
+     * @return mixed
351
+     */
352
+    public function filetype($path) {
353
+        return $this->basicOperation('filetype', $path);
354
+    }
355
+
356
+    /**
357
+     * @param string $path
358
+     * @return mixed
359
+     */
360
+    public function filesize(string $path) {
361
+        return $this->basicOperation('filesize', $path);
362
+    }
363
+
364
+    /**
365
+     * @param string $path
366
+     * @return bool|mixed
367
+     * @throws InvalidPathException
368
+     */
369
+    public function readfile($path) {
370
+        $this->assertPathLength($path);
371
+        if (ob_get_level()) {
372
+            ob_end_clean();
373
+        }
374
+        $handle = $this->fopen($path, 'rb');
375
+        if ($handle) {
376
+            $chunkSize = 524288; // 512 kiB chunks
377
+            while (!feof($handle)) {
378
+                echo fread($handle, $chunkSize);
379
+                flush();
380
+                $this->checkConnectionStatus();
381
+            }
382
+            fclose($handle);
383
+            return $this->filesize($path);
384
+        }
385
+        return false;
386
+    }
387
+
388
+    /**
389
+     * @param string $path
390
+     * @param int $from
391
+     * @param int $to
392
+     * @return bool|mixed
393
+     * @throws InvalidPathException
394
+     * @throws \OCP\Files\UnseekableException
395
+     */
396
+    public function readfilePart($path, $from, $to) {
397
+        $this->assertPathLength($path);
398
+        if (ob_get_level()) {
399
+            ob_end_clean();
400
+        }
401
+        $handle = $this->fopen($path, 'rb');
402
+        if ($handle) {
403
+            $chunkSize = 524288; // 512 kiB chunks
404
+            $startReading = true;
405
+
406
+            if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
407
+                // forward file handle via chunked fread because fseek seem to have failed
408
+
409
+                $end = $from + 1;
410
+                while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
411
+                    $len = $from - ftell($handle);
412
+                    if ($len > $chunkSize) {
413
+                        $len = $chunkSize;
414
+                    }
415
+                    $result = fread($handle, $len);
416
+
417
+                    if ($result === false) {
418
+                        $startReading = false;
419
+                        break;
420
+                    }
421
+                }
422
+            }
423
+
424
+            if ($startReading) {
425
+                $end = $to + 1;
426
+                while (!feof($handle) && ftell($handle) < $end) {
427
+                    $len = $end - ftell($handle);
428
+                    if ($len > $chunkSize) {
429
+                        $len = $chunkSize;
430
+                    }
431
+                    echo fread($handle, $len);
432
+                    flush();
433
+                    $this->checkConnectionStatus();
434
+                }
435
+                return ftell($handle) - $from;
436
+            }
437
+
438
+            throw new \OCP\Files\UnseekableException('fseek error');
439
+        }
440
+        return false;
441
+    }
442
+
443
+    private function checkConnectionStatus(): void {
444
+        $connectionStatus = \connection_status();
445
+        if ($connectionStatus !== CONNECTION_NORMAL) {
446
+            throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
447
+        }
448
+    }
449
+
450
+    /**
451
+     * @param string $path
452
+     * @return mixed
453
+     */
454
+    public function isCreatable($path) {
455
+        return $this->basicOperation('isCreatable', $path);
456
+    }
457
+
458
+    /**
459
+     * @param string $path
460
+     * @return mixed
461
+     */
462
+    public function isReadable($path) {
463
+        return $this->basicOperation('isReadable', $path);
464
+    }
465
+
466
+    /**
467
+     * @param string $path
468
+     * @return mixed
469
+     */
470
+    public function isUpdatable($path) {
471
+        return $this->basicOperation('isUpdatable', $path);
472
+    }
473
+
474
+    /**
475
+     * @param string $path
476
+     * @return bool|mixed
477
+     */
478
+    public function isDeletable($path) {
479
+        $absolutePath = $this->getAbsolutePath($path);
480
+        $mount = Filesystem::getMountManager()->find($absolutePath);
481
+        if ($mount->getInternalPath($absolutePath) === '') {
482
+            return $mount instanceof MoveableMount;
483
+        }
484
+        return $this->basicOperation('isDeletable', $path);
485
+    }
486
+
487
+    /**
488
+     * @param string $path
489
+     * @return mixed
490
+     */
491
+    public function isSharable($path) {
492
+        return $this->basicOperation('isSharable', $path);
493
+    }
494
+
495
+    /**
496
+     * @param string $path
497
+     * @return bool|mixed
498
+     */
499
+    public function file_exists($path) {
500
+        if ($path == '/') {
501
+            return true;
502
+        }
503
+        return $this->basicOperation('file_exists', $path);
504
+    }
505
+
506
+    /**
507
+     * @param string $path
508
+     * @return mixed
509
+     */
510
+    public function filemtime($path) {
511
+        return $this->basicOperation('filemtime', $path);
512
+    }
513
+
514
+    /**
515
+     * @param string $path
516
+     * @param int|string $mtime
517
+     */
518
+    public function touch($path, $mtime = null): bool {
519
+        if (!is_null($mtime) && !is_numeric($mtime)) {
520
+            $mtime = strtotime($mtime);
521
+        }
522
+
523
+        $hooks = ['touch'];
524
+
525
+        if (!$this->file_exists($path)) {
526
+            $hooks[] = 'create';
527
+            $hooks[] = 'write';
528
+        }
529
+        try {
530
+            $result = $this->basicOperation('touch', $path, $hooks, $mtime);
531
+        } catch (\Exception $e) {
532
+            $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
533
+            $result = false;
534
+        }
535
+        if (!$result) {
536
+            // If create file fails because of permissions on external storage like SMB folders,
537
+            // check file exists and return false if not.
538
+            if (!$this->file_exists($path)) {
539
+                return false;
540
+            }
541
+            if (is_null($mtime)) {
542
+                $mtime = time();
543
+            }
544
+            //if native touch fails, we emulate it by changing the mtime in the cache
545
+            $this->putFileInfo($path, ['mtime' => floor($mtime)]);
546
+        }
547
+        return true;
548
+    }
549
+
550
+    /**
551
+     * @param string $path
552
+     * @return string|false
553
+     * @throws LockedException
554
+     */
555
+    public function file_get_contents($path) {
556
+        return $this->basicOperation('file_get_contents', $path, ['read']);
557
+    }
558
+
559
+    protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
560
+        if (!$exists) {
561
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
562
+                Filesystem::signal_param_path => $this->getHookPath($path),
563
+                Filesystem::signal_param_run => &$run,
564
+            ]);
565
+        } else {
566
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
567
+                Filesystem::signal_param_path => $this->getHookPath($path),
568
+                Filesystem::signal_param_run => &$run,
569
+            ]);
570
+        }
571
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
572
+            Filesystem::signal_param_path => $this->getHookPath($path),
573
+            Filesystem::signal_param_run => &$run,
574
+        ]);
575
+    }
576
+
577
+    protected function emit_file_hooks_post(bool $exists, string $path): void {
578
+        if (!$exists) {
579
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
580
+                Filesystem::signal_param_path => $this->getHookPath($path),
581
+            ]);
582
+        } else {
583
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
584
+                Filesystem::signal_param_path => $this->getHookPath($path),
585
+            ]);
586
+        }
587
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
588
+            Filesystem::signal_param_path => $this->getHookPath($path),
589
+        ]);
590
+    }
591
+
592
+    /**
593
+     * @param string $path
594
+     * @param string|resource $data
595
+     * @return bool|mixed
596
+     * @throws LockedException
597
+     */
598
+    public function file_put_contents($path, $data) {
599
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
600
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
601
+            if (Filesystem::isValidPath($path)
602
+                && !Filesystem::isFileBlacklisted($path)
603
+            ) {
604
+                $path = $this->getRelativePath($absolutePath);
605
+                if ($path === null) {
606
+                    throw new InvalidPathException("Path $absolutePath is not in the expected root");
607
+                }
608
+
609
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
610
+
611
+                $exists = $this->file_exists($path);
612
+                if ($this->shouldEmitHooks($path)) {
613
+                    $run = true;
614
+                    $this->emit_file_hooks_pre($exists, $path, $run);
615
+                    if (!$run) {
616
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
617
+                        return false;
618
+                    }
619
+                }
620
+
621
+                try {
622
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
623
+                } catch (\Exception $e) {
624
+                    // Release the shared lock before throwing.
625
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
626
+                    throw $e;
627
+                }
628
+
629
+                /** @var Storage $storage */
630
+                [$storage, $internalPath] = $this->resolvePath($path);
631
+                $target = $storage->fopen($internalPath, 'w');
632
+                if ($target) {
633
+                    [, $result] = Files::streamCopy($data, $target, true);
634
+                    fclose($target);
635
+                    fclose($data);
636
+
637
+                    $this->writeUpdate($storage, $internalPath);
638
+
639
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
640
+
641
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
642
+                        $this->emit_file_hooks_post($exists, $path);
643
+                    }
644
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
645
+                    return $result;
646
+                } else {
647
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
648
+                    return false;
649
+                }
650
+            } else {
651
+                return false;
652
+            }
653
+        } else {
654
+            $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
655
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
656
+        }
657
+    }
658
+
659
+    /**
660
+     * @param string $path
661
+     * @return bool|mixed
662
+     */
663
+    public function unlink($path) {
664
+        if ($path === '' || $path === '/') {
665
+            // do not allow deleting the root
666
+            return false;
667
+        }
668
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
669
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
670
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
671
+        if ($mount->getInternalPath($absolutePath) === '') {
672
+            return $this->removeMount($mount, $absolutePath);
673
+        }
674
+        if ($this->is_dir($path)) {
675
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
676
+        } else {
677
+            $result = $this->basicOperation('unlink', $path, ['delete']);
678
+        }
679
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
680
+            $storage = $mount->getStorage();
681
+            $internalPath = $mount->getInternalPath($absolutePath);
682
+            $storage->getUpdater()->remove($internalPath);
683
+            return true;
684
+        } else {
685
+            return $result;
686
+        }
687
+    }
688
+
689
+    /**
690
+     * @param string $directory
691
+     * @return bool|mixed
692
+     */
693
+    public function deleteAll($directory) {
694
+        return $this->rmdir($directory);
695
+    }
696
+
697
+    /**
698
+     * Rename/move a file or folder from the source path to target path.
699
+     *
700
+     * @param string $source source path
701
+     * @param string $target target path
702
+     * @param array $options
703
+     *
704
+     * @return bool|mixed
705
+     * @throws LockedException
706
+     */
707
+    public function rename($source, $target, array $options = []) {
708
+        $checkSubMounts = $options['checkSubMounts'] ?? true;
709
+
710
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
711
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
712
+
713
+        if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
714
+            throw new ForbiddenException('Moving a folder into a child folder is forbidden', false);
715
+        }
716
+
717
+        /** @var IMountManager $mountManager */
718
+        $mountManager = \OC::$server->get(IMountManager::class);
719
+
720
+        $targetParts = explode('/', $absolutePath2);
721
+        $targetUser = $targetParts[1] ?? null;
722
+        $result = false;
723
+        if (
724
+            Filesystem::isValidPath($target)
725
+            && Filesystem::isValidPath($source)
726
+            && !Filesystem::isFileBlacklisted($target)
727
+        ) {
728
+            $source = $this->getRelativePath($absolutePath1);
729
+            $target = $this->getRelativePath($absolutePath2);
730
+            $exists = $this->file_exists($target);
731
+
732
+            if ($source == null || $target == null) {
733
+                return false;
734
+            }
735
+
736
+            try {
737
+                $this->verifyPath(dirname($target), basename($target));
738
+            } catch (InvalidPathException) {
739
+                return false;
740
+            }
741
+
742
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
743
+            try {
744
+                $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
745
+
746
+                $run = true;
747
+                if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
748
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
749
+                    $this->emit_file_hooks_pre($exists, $target, $run);
750
+                } elseif ($this->shouldEmitHooks($source)) {
751
+                    $sourcePath = $this->getHookPath($source);
752
+                    $targetPath = $this->getHookPath($target);
753
+                    if ($sourcePath !== null && $targetPath !== null) {
754
+                        \OC_Hook::emit(
755
+                            Filesystem::CLASSNAME, Filesystem::signal_rename,
756
+                            [
757
+                                Filesystem::signal_param_oldpath => $sourcePath,
758
+                                Filesystem::signal_param_newpath => $targetPath,
759
+                                Filesystem::signal_param_run => &$run
760
+                            ]
761
+                        );
762
+                    }
763
+                }
764
+                if ($run) {
765
+                    $manager = Filesystem::getMountManager();
766
+                    $mount1 = $this->getMount($source);
767
+                    $mount2 = $this->getMount($target);
768
+                    $storage1 = $mount1->getStorage();
769
+                    $storage2 = $mount2->getStorage();
770
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
771
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
772
+
773
+                    $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
774
+                    try {
775
+                        $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
776
+
777
+                        if ($checkSubMounts) {
778
+                            $movedMounts = $mountManager->findIn($this->getAbsolutePath($source));
779
+                        } else {
780
+                            $movedMounts = [];
781
+                        }
782
+
783
+                        if ($internalPath1 === '') {
784
+                            $sourceParentMount = $this->getMount(dirname($source));
785
+                            $movedMounts[] = $mount1;
786
+                            $this->validateMountMove($movedMounts, $sourceParentMount, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
787
+                            /**
788
+                             * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
789
+                             */
790
+                            $sourceMountPoint = $mount1->getMountPoint();
791
+                            $result = $mount1->moveMount($absolutePath2);
792
+                            $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
793
+
794
+                            // moving a file/folder within the same mount point
795
+                        } elseif ($storage1 === $storage2) {
796
+                            if (count($movedMounts) > 0) {
797
+                                $this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
798
+                            }
799
+                            if ($storage1) {
800
+                                $result = $storage1->rename($internalPath1, $internalPath2);
801
+                            } else {
802
+                                $result = false;
803
+                            }
804
+                            // moving a file/folder between storages (from $storage1 to $storage2)
805
+                        } else {
806
+                            if (count($movedMounts) > 0) {
807
+                                $this->validateMountMove($movedMounts, $mount1, $mount2, !$this->targetIsNotShared($targetUser, $absolutePath2));
808
+                            }
809
+                            $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
810
+                        }
811
+
812
+                        if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
813
+                            // if it was a rename from a part file to a regular file it was a write and not a rename operation
814
+                            $this->writeUpdate($storage2, $internalPath2);
815
+                        } elseif ($result) {
816
+                            if ($internalPath1 !== '') { // don't do a cache update for moved mounts
817
+                                $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
818
+                            }
819
+                        }
820
+                    } catch (\Exception $e) {
821
+                        throw $e;
822
+                    } finally {
823
+                        $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
824
+                        $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
825
+                    }
826
+
827
+                    if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
828
+                        if ($this->shouldEmitHooks()) {
829
+                            $this->emit_file_hooks_post($exists, $target);
830
+                        }
831
+                    } elseif ($result) {
832
+                        if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
833
+                            $sourcePath = $this->getHookPath($source);
834
+                            $targetPath = $this->getHookPath($target);
835
+                            if ($sourcePath !== null && $targetPath !== null) {
836
+                                \OC_Hook::emit(
837
+                                    Filesystem::CLASSNAME,
838
+                                    Filesystem::signal_post_rename,
839
+                                    [
840
+                                        Filesystem::signal_param_oldpath => $sourcePath,
841
+                                        Filesystem::signal_param_newpath => $targetPath,
842
+                                    ]
843
+                                );
844
+                            }
845
+                        }
846
+                    }
847
+                }
848
+            } catch (\Exception $e) {
849
+                throw $e;
850
+            } finally {
851
+                $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
852
+                $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
853
+            }
854
+        }
855
+        return $result;
856
+    }
857
+
858
+    /**
859
+     * @throws ForbiddenException
860
+     */
861
+    private function validateMountMove(array $mounts, IMountPoint $sourceMount, IMountPoint $targetMount, bool $targetIsShared): void {
862
+        $targetPath = $this->getRelativePath($targetMount->getMountPoint());
863
+        if ($targetPath) {
864
+            $targetPath = trim($targetPath, '/');
865
+        } else {
866
+            $targetPath = $targetMount->getMountPoint();
867
+        }
868
+
869
+        $l = \OC::$server->get(IFactory::class)->get('files');
870
+        foreach ($mounts as $mount) {
871
+            $sourcePath = $this->getRelativePath($mount->getMountPoint());
872
+            if ($sourcePath) {
873
+                $sourcePath = trim($sourcePath, '/');
874
+            } else {
875
+                $sourcePath = $mount->getMountPoint();
876
+            }
877
+
878
+            if (!$mount instanceof MoveableMount) {
879
+                throw new ForbiddenException($l->t('Storage %s cannot be moved', [$sourcePath]), false);
880
+            }
881
+
882
+            if ($targetIsShared) {
883
+                if ($sourceMount instanceof SharedMount) {
884
+                    throw new ForbiddenException($l->t('Moving a share (%s) into a shared folder is not allowed', [$sourcePath]), false);
885
+                } else {
886
+                    throw new ForbiddenException($l->t('Moving a storage (%s) into a shared folder is not allowed', [$sourcePath]), false);
887
+                }
888
+            }
889
+
890
+            if ($sourceMount !== $targetMount) {
891
+                if ($sourceMount instanceof SharedMount) {
892
+                    if ($targetMount instanceof SharedMount) {
893
+                        throw new ForbiddenException($l->t('Moving a share (%s) into another share (%s) is not allowed', [$sourcePath, $targetPath]), false);
894
+                    } else {
895
+                        throw new ForbiddenException($l->t('Moving a share (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
896
+                    }
897
+                } else {
898
+                    if ($targetMount instanceof SharedMount) {
899
+                        throw new ForbiddenException($l->t('Moving a storage (%s) into a share (%s) is not allowed', [$sourcePath, $targetPath]), false);
900
+                    } else {
901
+                        throw new ForbiddenException($l->t('Moving a storage (%s) into another storage (%s) is not allowed', [$sourcePath, $targetPath]), false);
902
+                    }
903
+                }
904
+            }
905
+        }
906
+    }
907
+
908
+    /**
909
+     * Copy a file/folder from the source path to target path
910
+     *
911
+     * @param string $source source path
912
+     * @param string $target target path
913
+     * @param bool $preserveMtime whether to preserve mtime on the copy
914
+     *
915
+     * @return bool|mixed
916
+     */
917
+    public function copy($source, $target, $preserveMtime = false) {
918
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
919
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
920
+        $result = false;
921
+        if (
922
+            Filesystem::isValidPath($target)
923
+            && Filesystem::isValidPath($source)
924
+            && !Filesystem::isFileBlacklisted($target)
925
+        ) {
926
+            $source = $this->getRelativePath($absolutePath1);
927
+            $target = $this->getRelativePath($absolutePath2);
928
+
929
+            if ($source == null || $target == null) {
930
+                return false;
931
+            }
932
+            $run = true;
933
+
934
+            $this->lockFile($target, ILockingProvider::LOCK_SHARED);
935
+            $this->lockFile($source, ILockingProvider::LOCK_SHARED);
936
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
937
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
938
+
939
+            try {
940
+                $exists = $this->file_exists($target);
941
+                if ($this->shouldEmitHooks($target)) {
942
+                    \OC_Hook::emit(
943
+                        Filesystem::CLASSNAME,
944
+                        Filesystem::signal_copy,
945
+                        [
946
+                            Filesystem::signal_param_oldpath => $this->getHookPath($source),
947
+                            Filesystem::signal_param_newpath => $this->getHookPath($target),
948
+                            Filesystem::signal_param_run => &$run
949
+                        ]
950
+                    );
951
+                    $this->emit_file_hooks_pre($exists, $target, $run);
952
+                }
953
+                if ($run) {
954
+                    $mount1 = $this->getMount($source);
955
+                    $mount2 = $this->getMount($target);
956
+                    $storage1 = $mount1->getStorage();
957
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
958
+                    $storage2 = $mount2->getStorage();
959
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
960
+
961
+                    $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
962
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
963
+
964
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
965
+                        if ($storage1) {
966
+                            $result = $storage1->copy($internalPath1, $internalPath2);
967
+                        } else {
968
+                            $result = false;
969
+                        }
970
+                    } else {
971
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
972
+                    }
973
+
974
+                    if ($result) {
975
+                        $this->copyUpdate($storage1, $storage2, $internalPath1, $internalPath2);
976
+                    }
977
+
978
+                    $this->changeLock($target, ILockingProvider::LOCK_SHARED);
979
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
980
+
981
+                    if ($this->shouldEmitHooks($target) && $result !== false) {
982
+                        \OC_Hook::emit(
983
+                            Filesystem::CLASSNAME,
984
+                            Filesystem::signal_post_copy,
985
+                            [
986
+                                Filesystem::signal_param_oldpath => $this->getHookPath($source),
987
+                                Filesystem::signal_param_newpath => $this->getHookPath($target)
988
+                            ]
989
+                        );
990
+                        $this->emit_file_hooks_post($exists, $target);
991
+                    }
992
+                }
993
+            } catch (\Exception $e) {
994
+                $this->unlockFile($target, $lockTypePath2);
995
+                $this->unlockFile($source, $lockTypePath1);
996
+                throw $e;
997
+            }
998
+
999
+            $this->unlockFile($target, $lockTypePath2);
1000
+            $this->unlockFile($source, $lockTypePath1);
1001
+        }
1002
+        return $result;
1003
+    }
1004
+
1005
+    /**
1006
+     * @param string $path
1007
+     * @param string $mode 'r' or 'w'
1008
+     * @return resource|false
1009
+     * @throws LockedException
1010
+     */
1011
+    public function fopen($path, $mode) {
1012
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
1013
+        $hooks = [];
1014
+        switch ($mode) {
1015
+            case 'r':
1016
+                $hooks[] = 'read';
1017
+                break;
1018
+            case 'r+':
1019
+            case 'w+':
1020
+            case 'x+':
1021
+            case 'a+':
1022
+                $hooks[] = 'read';
1023
+                $hooks[] = 'write';
1024
+                break;
1025
+            case 'w':
1026
+            case 'x':
1027
+            case 'a':
1028
+                $hooks[] = 'write';
1029
+                break;
1030
+            default:
1031
+                $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
1032
+        }
1033
+
1034
+        if ($mode !== 'r' && $mode !== 'w') {
1035
+            $this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
1036
+        }
1037
+
1038
+        $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
1039
+        if (!is_resource($handle) && $mode === 'r') {
1040
+            // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
1041
+            $mount = $this->getMount($path);
1042
+            $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1043
+            $storage = $mount->getStorage();
1044
+            if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
1045
+                $this->writeUpdate($storage, $internalPath);
1046
+            }
1047
+        }
1048
+        return $handle;
1049
+    }
1050
+
1051
+    /**
1052
+     * @param string $path
1053
+     * @throws InvalidPathException
1054
+     */
1055
+    public function toTmpFile($path): string|false {
1056
+        $this->assertPathLength($path);
1057
+        if (Filesystem::isValidPath($path)) {
1058
+            $source = $this->fopen($path, 'r');
1059
+            if ($source) {
1060
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
1061
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
1062
+                file_put_contents($tmpFile, $source);
1063
+                return $tmpFile;
1064
+            } else {
1065
+                return false;
1066
+            }
1067
+        } else {
1068
+            return false;
1069
+        }
1070
+    }
1071
+
1072
+    /**
1073
+     * @param string $tmpFile
1074
+     * @param string $path
1075
+     * @return bool|mixed
1076
+     * @throws InvalidPathException
1077
+     */
1078
+    public function fromTmpFile($tmpFile, $path) {
1079
+        $this->assertPathLength($path);
1080
+        if (Filesystem::isValidPath($path)) {
1081
+            // Get directory that the file is going into
1082
+            $filePath = dirname($path);
1083
+
1084
+            // Create the directories if any
1085
+            if (!$this->file_exists($filePath)) {
1086
+                $result = $this->createParentDirectories($filePath);
1087
+                if ($result === false) {
1088
+                    return false;
1089
+                }
1090
+            }
1091
+
1092
+            $source = fopen($tmpFile, 'r');
1093
+            if ($source) {
1094
+                $result = $this->file_put_contents($path, $source);
1095
+                /**
1096
+                 * $this->file_put_contents() might have already closed
1097
+                 * the resource, so we check it, before trying to close it
1098
+                 * to avoid messages in the error log.
1099
+                 * @psalm-suppress RedundantCondition false-positive
1100
+                 */
1101
+                if (is_resource($source)) {
1102
+                    fclose($source);
1103
+                }
1104
+                unlink($tmpFile);
1105
+                return $result;
1106
+            } else {
1107
+                return false;
1108
+            }
1109
+        } else {
1110
+            return false;
1111
+        }
1112
+    }
1113
+
1114
+
1115
+    /**
1116
+     * @param string $path
1117
+     * @return mixed
1118
+     * @throws InvalidPathException
1119
+     */
1120
+    public function getMimeType($path) {
1121
+        $this->assertPathLength($path);
1122
+        return $this->basicOperation('getMimeType', $path);
1123
+    }
1124
+
1125
+    /**
1126
+     * @param string $type
1127
+     * @param string $path
1128
+     * @param bool $raw
1129
+     */
1130
+    public function hash($type, $path, $raw = false): string|bool {
1131
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1132
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1133
+        if (Filesystem::isValidPath($path)) {
1134
+            $path = $this->getRelativePath($absolutePath);
1135
+            if ($path == null) {
1136
+                return false;
1137
+            }
1138
+            if ($this->shouldEmitHooks($path)) {
1139
+                \OC_Hook::emit(
1140
+                    Filesystem::CLASSNAME,
1141
+                    Filesystem::signal_read,
1142
+                    [Filesystem::signal_param_path => $this->getHookPath($path)]
1143
+                );
1144
+            }
1145
+            /** @var Storage|null $storage */
1146
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1147
+            if ($storage) {
1148
+                return $storage->hash($type, $internalPath, $raw);
1149
+            }
1150
+        }
1151
+        return false;
1152
+    }
1153
+
1154
+    /**
1155
+     * @param string $path
1156
+     * @return mixed
1157
+     * @throws InvalidPathException
1158
+     */
1159
+    public function free_space($path = '/') {
1160
+        $this->assertPathLength($path);
1161
+        $result = $this->basicOperation('free_space', $path);
1162
+        if ($result === null) {
1163
+            throw new InvalidPathException();
1164
+        }
1165
+        return $result;
1166
+    }
1167
+
1168
+    /**
1169
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1170
+     *
1171
+     * @param mixed $extraParam (optional)
1172
+     * @return mixed
1173
+     * @throws LockedException
1174
+     *
1175
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1176
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1177
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1178
+     */
1179
+    private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
1180
+        $postFix = (substr($path, -1) === '/') ? '/' : '';
1181
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1182
+        if (Filesystem::isValidPath($path)
1183
+            && !Filesystem::isFileBlacklisted($path)
1184
+        ) {
1185
+            $path = $this->getRelativePath($absolutePath);
1186
+            if ($path == null) {
1187
+                return false;
1188
+            }
1189
+
1190
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1191
+                // always a shared lock during pre-hooks so the hook can read the file
1192
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1193
+            }
1194
+
1195
+            $run = $this->runHooks($hooks, $path);
1196
+            [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
1197
+            if ($run && $storage) {
1198
+                /** @var Storage $storage */
1199
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1200
+                    try {
1201
+                        $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1202
+                    } catch (LockedException $e) {
1203
+                        // release the shared lock we acquired before quitting
1204
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1205
+                        throw $e;
1206
+                    }
1207
+                }
1208
+                try {
1209
+                    if (!is_null($extraParam)) {
1210
+                        $result = $storage->$operation($internalPath, $extraParam);
1211
+                    } else {
1212
+                        $result = $storage->$operation($internalPath);
1213
+                    }
1214
+                } catch (\Exception $e) {
1215
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1216
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1217
+                    } elseif (in_array('read', $hooks)) {
1218
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1219
+                    }
1220
+                    throw $e;
1221
+                }
1222
+
1223
+                if ($result !== false && in_array('delete', $hooks)) {
1224
+                    $this->removeUpdate($storage, $internalPath);
1225
+                }
1226
+                if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
1227
+                    $isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
1228
+                    $sizeDifference = $operation === 'mkdir' ? 0 : $result;
1229
+                    $this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
1230
+                }
1231
+                if ($result !== false && in_array('touch', $hooks)) {
1232
+                    $this->writeUpdate($storage, $internalPath, $extraParam, 0);
1233
+                }
1234
+
1235
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1236
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1237
+                }
1238
+
1239
+                $unlockLater = false;
1240
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1241
+                    $unlockLater = true;
1242
+                    // make sure our unlocking callback will still be called if connection is aborted
1243
+                    ignore_user_abort(true);
1244
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1245
+                        if (in_array('write', $hooks)) {
1246
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1247
+                        } elseif (in_array('read', $hooks)) {
1248
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1249
+                        }
1250
+                    });
1251
+                }
1252
+
1253
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1254
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1255
+                        $this->runHooks($hooks, $path, true);
1256
+                    }
1257
+                }
1258
+
1259
+                if (!$unlockLater
1260
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1261
+                ) {
1262
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1263
+                }
1264
+                return $result;
1265
+            } else {
1266
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1267
+            }
1268
+        }
1269
+        return null;
1270
+    }
1271
+
1272
+    /**
1273
+     * get the path relative to the default root for hook usage
1274
+     *
1275
+     * @param string $path
1276
+     * @return ?string
1277
+     */
1278
+    private function getHookPath($path): ?string {
1279
+        $view = Filesystem::getView();
1280
+        if (!$view) {
1281
+            return $path;
1282
+        }
1283
+        return $view->getRelativePath($this->getAbsolutePath($path));
1284
+    }
1285
+
1286
+    private function shouldEmitHooks(string $path = ''): bool {
1287
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1288
+            return false;
1289
+        }
1290
+        if (!Filesystem::$loaded) {
1291
+            return false;
1292
+        }
1293
+        $defaultRoot = Filesystem::getRoot();
1294
+        if ($defaultRoot === null) {
1295
+            return false;
1296
+        }
1297
+        if ($this->fakeRoot === $defaultRoot) {
1298
+            return true;
1299
+        }
1300
+        $fullPath = $this->getAbsolutePath($path);
1301
+
1302
+        if ($fullPath === $defaultRoot) {
1303
+            return true;
1304
+        }
1305
+
1306
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1307
+    }
1308
+
1309
+    /**
1310
+     * @param string[] $hooks
1311
+     * @param string $path
1312
+     * @param bool $post
1313
+     * @return bool
1314
+     */
1315
+    private function runHooks($hooks, $path, $post = false) {
1316
+        $relativePath = $path;
1317
+        $path = $this->getHookPath($path);
1318
+        $prefix = $post ? 'post_' : '';
1319
+        $run = true;
1320
+        if ($this->shouldEmitHooks($relativePath)) {
1321
+            foreach ($hooks as $hook) {
1322
+                if ($hook != 'read') {
1323
+                    \OC_Hook::emit(
1324
+                        Filesystem::CLASSNAME,
1325
+                        $prefix . $hook,
1326
+                        [
1327
+                            Filesystem::signal_param_run => &$run,
1328
+                            Filesystem::signal_param_path => $path
1329
+                        ]
1330
+                    );
1331
+                } elseif (!$post) {
1332
+                    \OC_Hook::emit(
1333
+                        Filesystem::CLASSNAME,
1334
+                        $prefix . $hook,
1335
+                        [
1336
+                            Filesystem::signal_param_path => $path
1337
+                        ]
1338
+                    );
1339
+                }
1340
+            }
1341
+        }
1342
+        return $run;
1343
+    }
1344
+
1345
+    /**
1346
+     * check if a file or folder has been updated since $time
1347
+     *
1348
+     * @param string $path
1349
+     * @param int $time
1350
+     * @return bool
1351
+     */
1352
+    public function hasUpdated($path, $time) {
1353
+        return $this->basicOperation('hasUpdated', $path, [], $time);
1354
+    }
1355
+
1356
+    /**
1357
+     * @param string $ownerId
1358
+     * @return IUser
1359
+     */
1360
+    private function getUserObjectForOwner(string $ownerId) {
1361
+        return new LazyUser($ownerId, $this->userManager);
1362
+    }
1363
+
1364
+    /**
1365
+     * Get file info from cache
1366
+     *
1367
+     * If the file is not in cached it will be scanned
1368
+     * If the file has changed on storage the cache will be updated
1369
+     *
1370
+     * @param Storage $storage
1371
+     * @param string $internalPath
1372
+     * @param string $relativePath
1373
+     * @return ICacheEntry|bool
1374
+     */
1375
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1376
+        $cache = $storage->getCache($internalPath);
1377
+        $data = $cache->get($internalPath);
1378
+        $watcher = $storage->getWatcher($internalPath);
1379
+
1380
+        try {
1381
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1382
+            if (!$data || (isset($data['size']) && $data['size'] === -1)) {
1383
+                if (!$storage->file_exists($internalPath)) {
1384
+                    return false;
1385
+                }
1386
+                // don't need to get a lock here since the scanner does it's own locking
1387
+                $scanner = $storage->getScanner($internalPath);
1388
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1389
+                $data = $cache->get($internalPath);
1390
+            } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1391
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1392
+                $watcher->update($internalPath, $data);
1393
+                $storage->getPropagator()->propagateChange($internalPath, time());
1394
+                $data = $cache->get($internalPath);
1395
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1396
+            }
1397
+        } catch (LockedException $e) {
1398
+            // if the file is locked we just use the old cache info
1399
+        }
1400
+
1401
+        return $data;
1402
+    }
1403
+
1404
+    /**
1405
+     * get the filesystem info
1406
+     *
1407
+     * @param string $path
1408
+     * @param bool|string $includeMountPoints true to add mountpoint sizes,
1409
+     *                                        'ext' to add only ext storage mount point sizes. Defaults to true.
1410
+     * @return \OC\Files\FileInfo|false False if file does not exist
1411
+     */
1412
+    public function getFileInfo($path, $includeMountPoints = true) {
1413
+        $this->assertPathLength($path);
1414
+        if (!Filesystem::isValidPath($path)) {
1415
+            return false;
1416
+        }
1417
+        $relativePath = $path;
1418
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1419
+
1420
+        $mount = Filesystem::getMountManager()->find($path);
1421
+        $storage = $mount->getStorage();
1422
+        $internalPath = $mount->getInternalPath($path);
1423
+        if ($storage) {
1424
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1425
+
1426
+            if (!$data instanceof ICacheEntry) {
1427
+                if (Cache\Scanner::isPartialFile($relativePath)) {
1428
+                    return $this->getPartFileInfo($relativePath);
1429
+                }
1430
+
1431
+                return false;
1432
+            }
1433
+
1434
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1435
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1436
+            }
1437
+            if ($internalPath === '' && $data['name']) {
1438
+                $data['name'] = basename($path);
1439
+            }
1440
+
1441
+            $ownerId = $storage->getOwner($internalPath);
1442
+            $owner = null;
1443
+            if ($ownerId !== false) {
1444
+                // ownerId might be null if files are accessed with an access token without file system access
1445
+                $owner = $this->getUserObjectForOwner($ownerId);
1446
+            }
1447
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1448
+
1449
+            if (isset($data['fileid'])) {
1450
+                if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
1451
+                    //add the sizes of other mount points to the folder
1452
+                    $extOnly = ($includeMountPoints === 'ext');
1453
+                    $this->addSubMounts($info, $extOnly);
1454
+                }
1455
+            }
1456
+
1457
+            return $info;
1458
+        } else {
1459
+            $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
1460
+        }
1461
+
1462
+        return false;
1463
+    }
1464
+
1465
+    /**
1466
+     * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
1467
+     */
1468
+    public function addSubMounts(FileInfo $info, $extOnly = false): void {
1469
+        $mounts = Filesystem::getMountManager()->findIn($info->getPath());
1470
+        $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1471
+            return !($extOnly && $mount instanceof SharedMount);
1472
+        }));
1473
+    }
1474
+
1475
+    /**
1476
+     * get the content of a directory
1477
+     *
1478
+     * @param string $directory path under datadirectory
1479
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1480
+     * @return FileInfo[]
1481
+     */
1482
+    public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
1483
+        $this->assertPathLength($directory);
1484
+        if (!Filesystem::isValidPath($directory)) {
1485
+            return [];
1486
+        }
1487
+
1488
+        $path = $this->getAbsolutePath($directory);
1489
+        $path = Filesystem::normalizePath($path);
1490
+        $mount = $this->getMount($directory);
1491
+        $storage = $mount->getStorage();
1492
+        $internalPath = $mount->getInternalPath($path);
1493
+        if (!$storage) {
1494
+            return [];
1495
+        }
1496
+
1497
+        $cache = $storage->getCache($internalPath);
1498
+        $user = \OC_User::getUser();
1499
+
1500
+        if (!$directoryInfo) {
1501
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1502
+            if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
1503
+                return [];
1504
+            }
1505
+        } else {
1506
+            $data = $directoryInfo;
1507
+        }
1508
+
1509
+        if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
1510
+            return [];
1511
+        }
1512
+
1513
+        $folderId = $data->getId();
1514
+        $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1515
+
1516
+        $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1517
+
1518
+        $fileNames = array_map(function (ICacheEntry $content) {
1519
+            return $content->getName();
1520
+        }, $contents);
1521
+        /**
1522
+         * @var \OC\Files\FileInfo[] $fileInfos
1523
+         */
1524
+        $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1525
+            if ($sharingDisabled) {
1526
+                $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1527
+            }
1528
+            $ownerId = $storage->getOwner($content['path']);
1529
+            if ($ownerId !== false) {
1530
+                $owner = $this->getUserObjectForOwner($ownerId);
1531
+            } else {
1532
+                $owner = null;
1533
+            }
1534
+            return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1535
+        }, $contents);
1536
+        $files = array_combine($fileNames, $fileInfos);
1537
+
1538
+        //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1539
+        $mounts = Filesystem::getMountManager()->findIn($path);
1540
+
1541
+        // make sure nested mounts are sorted after their parent mounts
1542
+        // otherwise doesn't propagate the etag across storage boundaries correctly
1543
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1544
+            return $a->getMountPoint() <=> $b->getMountPoint();
1545
+        });
1546
+
1547
+        $dirLength = strlen($path);
1548
+        foreach ($mounts as $mount) {
1549
+            $mountPoint = $mount->getMountPoint();
1550
+            $subStorage = $mount->getStorage();
1551
+            if ($subStorage) {
1552
+                $subCache = $subStorage->getCache('');
1553
+
1554
+                $rootEntry = $subCache->get('');
1555
+                if (!$rootEntry) {
1556
+                    $subScanner = $subStorage->getScanner();
1557
+                    try {
1558
+                        $subScanner->scanFile('');
1559
+                    } catch (\OCP\Files\StorageNotAvailableException $e) {
1560
+                        continue;
1561
+                    } catch (\OCP\Files\StorageInvalidException $e) {
1562
+                        continue;
1563
+                    } catch (\Exception $e) {
1564
+                        // sometimes when the storage is not available it can be any exception
1565
+                        $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
1566
+                            'exception' => $e,
1567
+                            'app' => 'core',
1568
+                        ]);
1569
+                        continue;
1570
+                    }
1571
+                    $rootEntry = $subCache->get('');
1572
+                }
1573
+
1574
+                if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
1575
+                    $relativePath = trim(substr($mountPoint, $dirLength), '/');
1576
+                    if ($pos = strpos($relativePath, '/')) {
1577
+                        //mountpoint inside subfolder add size to the correct folder
1578
+                        $entryName = substr($relativePath, 0, $pos);
1579
+
1580
+                        // Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
1581
+                        if (!isset($files[$entryName])) {
1582
+                            try {
1583
+                                [$storage, ] = $this->resolvePath($path . '/' . $entryName);
1584
+                                // make sure we can create the mountpoint folder, even if the user has a quota of 0
1585
+                                if ($storage->instanceOfStorage(Quota::class)) {
1586
+                                    $storage->enableQuota(false);
1587
+                                }
1588
+
1589
+                                if ($this->mkdir($path . '/' . $entryName) !== false) {
1590
+                                    $info = $this->getFileInfo($path . '/' . $entryName);
1591
+                                    if ($info !== false) {
1592
+                                        $files[$entryName] = $info;
1593
+                                    }
1594
+                                }
1595
+
1596
+                                if ($storage->instanceOfStorage(Quota::class)) {
1597
+                                    $storage->enableQuota(true);
1598
+                                }
1599
+                            } catch (\Exception $e) {
1600
+                                // Creating the parent folder might not be possible, for example due to a lack of permissions.
1601
+                                $this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
1602
+                            }
1603
+                        }
1604
+
1605
+                        if (isset($files[$entryName])) {
1606
+                            $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
1607
+                        }
1608
+                    } else { //mountpoint in this folder, add an entry for it
1609
+                        $rootEntry['name'] = $relativePath;
1610
+                        $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1611
+                        $permissions = $rootEntry['permissions'];
1612
+                        // do not allow renaming/deleting the mount point if they are not shared files/folders
1613
+                        // for shared files/folders we use the permissions given by the owner
1614
+                        if ($mount instanceof MoveableMount) {
1615
+                            $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1616
+                        } else {
1617
+                            $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1618
+                        }
1619
+
1620
+                        $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1621
+
1622
+                        // if sharing was disabled for the user we remove the share permissions
1623
+                        if ($sharingDisabled) {
1624
+                            $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1625
+                        }
1626
+
1627
+                        $ownerId = $subStorage->getOwner('');
1628
+                        if ($ownerId !== false) {
1629
+                            $owner = $this->getUserObjectForOwner($ownerId);
1630
+                        } else {
1631
+                            $owner = null;
1632
+                        }
1633
+                        $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1634
+                    }
1635
+                }
1636
+            }
1637
+        }
1638
+
1639
+        if ($mimetype_filter) {
1640
+            $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1641
+                if (strpos($mimetype_filter, '/')) {
1642
+                    return $file->getMimetype() === $mimetype_filter;
1643
+                } else {
1644
+                    return $file->getMimePart() === $mimetype_filter;
1645
+                }
1646
+            });
1647
+        }
1648
+
1649
+        return array_values($files);
1650
+    }
1651
+
1652
+    /**
1653
+     * change file metadata
1654
+     *
1655
+     * @param string $path
1656
+     * @param array|\OCP\Files\FileInfo $data
1657
+     * @return int
1658
+     *
1659
+     * returns the fileid of the updated file
1660
+     */
1661
+    public function putFileInfo($path, $data) {
1662
+        $this->assertPathLength($path);
1663
+        if ($data instanceof FileInfo) {
1664
+            $data = $data->getData();
1665
+        }
1666
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1667
+        /**
1668
+         * @var Storage $storage
1669
+         * @var string $internalPath
1670
+         */
1671
+        [$storage, $internalPath] = Filesystem::resolvePath($path);
1672
+        if ($storage) {
1673
+            $cache = $storage->getCache($path);
1674
+
1675
+            if (!$cache->inCache($internalPath)) {
1676
+                $scanner = $storage->getScanner($internalPath);
1677
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1678
+            }
1679
+
1680
+            return $cache->put($internalPath, $data);
1681
+        } else {
1682
+            return -1;
1683
+        }
1684
+    }
1685
+
1686
+    /**
1687
+     * search for files with the name matching $query
1688
+     *
1689
+     * @param string $query
1690
+     * @return FileInfo[]
1691
+     */
1692
+    public function search($query) {
1693
+        return $this->searchCommon('search', ['%' . $query . '%']);
1694
+    }
1695
+
1696
+    /**
1697
+     * search for files with the name matching $query
1698
+     *
1699
+     * @param string $query
1700
+     * @return FileInfo[]
1701
+     */
1702
+    public function searchRaw($query) {
1703
+        return $this->searchCommon('search', [$query]);
1704
+    }
1705
+
1706
+    /**
1707
+     * search for files by mimetype
1708
+     *
1709
+     * @param string $mimetype
1710
+     * @return FileInfo[]
1711
+     */
1712
+    public function searchByMime($mimetype) {
1713
+        return $this->searchCommon('searchByMime', [$mimetype]);
1714
+    }
1715
+
1716
+    /**
1717
+     * search for files by tag
1718
+     *
1719
+     * @param string|int $tag name or tag id
1720
+     * @param string $userId owner of the tags
1721
+     * @return FileInfo[]
1722
+     */
1723
+    public function searchByTag($tag, $userId) {
1724
+        return $this->searchCommon('searchByTag', [$tag, $userId]);
1725
+    }
1726
+
1727
+    /**
1728
+     * @param string $method cache method
1729
+     * @param array $args
1730
+     * @return FileInfo[]
1731
+     */
1732
+    private function searchCommon($method, $args) {
1733
+        $files = [];
1734
+        $rootLength = strlen($this->fakeRoot);
1735
+
1736
+        $mount = $this->getMount('');
1737
+        $mountPoint = $mount->getMountPoint();
1738
+        $storage = $mount->getStorage();
1739
+        $userManager = \OC::$server->getUserManager();
1740
+        if ($storage) {
1741
+            $cache = $storage->getCache('');
1742
+
1743
+            $results = call_user_func_array([$cache, $method], $args);
1744
+            foreach ($results as $result) {
1745
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1746
+                    $internalPath = $result['path'];
1747
+                    $path = $mountPoint . $result['path'];
1748
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1749
+                    $ownerId = $storage->getOwner($internalPath);
1750
+                    if ($ownerId !== false) {
1751
+                        $owner = $userManager->get($ownerId);
1752
+                    } else {
1753
+                        $owner = null;
1754
+                    }
1755
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1756
+                }
1757
+            }
1758
+
1759
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1760
+            foreach ($mounts as $mount) {
1761
+                $mountPoint = $mount->getMountPoint();
1762
+                $storage = $mount->getStorage();
1763
+                if ($storage) {
1764
+                    $cache = $storage->getCache('');
1765
+
1766
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1767
+                    $results = call_user_func_array([$cache, $method], $args);
1768
+                    if ($results) {
1769
+                        foreach ($results as $result) {
1770
+                            $internalPath = $result['path'];
1771
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1772
+                            $path = rtrim($mountPoint . $internalPath, '/');
1773
+                            $ownerId = $storage->getOwner($internalPath);
1774
+                            if ($ownerId !== false) {
1775
+                                $owner = $userManager->get($ownerId);
1776
+                            } else {
1777
+                                $owner = null;
1778
+                            }
1779
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1780
+                        }
1781
+                    }
1782
+                }
1783
+            }
1784
+        }
1785
+        return $files;
1786
+    }
1787
+
1788
+    /**
1789
+     * Get the owner for a file or folder
1790
+     *
1791
+     * @throws NotFoundException
1792
+     */
1793
+    public function getOwner(string $path): string {
1794
+        $info = $this->getFileInfo($path);
1795
+        if (!$info) {
1796
+            throw new NotFoundException($path . ' not found while trying to get owner');
1797
+        }
1798
+
1799
+        if ($info->getOwner() === null) {
1800
+            throw new NotFoundException($path . ' has no owner');
1801
+        }
1802
+
1803
+        return $info->getOwner()->getUID();
1804
+    }
1805
+
1806
+    /**
1807
+     * get the ETag for a file or folder
1808
+     *
1809
+     * @param string $path
1810
+     * @return string|false
1811
+     */
1812
+    public function getETag($path) {
1813
+        [$storage, $internalPath] = $this->resolvePath($path);
1814
+        if ($storage) {
1815
+            return $storage->getETag($internalPath);
1816
+        } else {
1817
+            return false;
1818
+        }
1819
+    }
1820
+
1821
+    /**
1822
+     * Get the path of a file by id, relative to the view
1823
+     *
1824
+     * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
1825
+     *
1826
+     * @param int $id
1827
+     * @param int|null $storageId
1828
+     * @return string
1829
+     * @throws NotFoundException
1830
+     */
1831
+    public function getPath($id, ?int $storageId = null) {
1832
+        $id = (int)$id;
1833
+        $manager = Filesystem::getMountManager();
1834
+        $mounts = $manager->findIn($this->fakeRoot);
1835
+        $mounts[] = $manager->find($this->fakeRoot);
1836
+        $mounts = array_filter($mounts);
1837
+        // reverse the array, so we start with the storage this view is in
1838
+        // which is the most likely to contain the file we're looking for
1839
+        $mounts = array_reverse($mounts);
1840
+
1841
+        // put non-shared mounts in front of the shared mount
1842
+        // this prevents unneeded recursion into shares
1843
+        usort($mounts, function (IMountPoint $a, IMountPoint $b) {
1844
+            return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
1845
+        });
1846
+
1847
+        if (!is_null($storageId)) {
1848
+            $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
1849
+                return $mount->getNumericStorageId() === $storageId;
1850
+            });
1851
+        }
1852
+
1853
+        foreach ($mounts as $mount) {
1854
+            /**
1855
+             * @var \OC\Files\Mount\MountPoint $mount
1856
+             */
1857
+            if ($mount->getStorage()) {
1858
+                $cache = $mount->getStorage()->getCache();
1859
+                $internalPath = $cache->getPathById($id);
1860
+                if (is_string($internalPath)) {
1861
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1862
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1863
+                        return $path;
1864
+                    }
1865
+                }
1866
+            }
1867
+        }
1868
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1869
+    }
1870
+
1871
+    /**
1872
+     * @param string $path
1873
+     * @throws InvalidPathException
1874
+     */
1875
+    private function assertPathLength($path): void {
1876
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1877
+        // Check for the string length - performed using isset() instead of strlen()
1878
+        // because isset() is about 5x-40x faster.
1879
+        if (isset($path[$maxLen])) {
1880
+            $pathLen = strlen($path);
1881
+            throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1882
+        }
1883
+    }
1884
+
1885
+    /**
1886
+     * check if it is allowed to move a mount point to a given target.
1887
+     * It is not allowed to move a mount point into a different mount point or
1888
+     * into an already shared folder
1889
+     */
1890
+    private function targetIsNotShared(string $user, string $targetPath): bool {
1891
+        $providers = [
1892
+            IShare::TYPE_USER,
1893
+            IShare::TYPE_GROUP,
1894
+            IShare::TYPE_EMAIL,
1895
+            IShare::TYPE_CIRCLE,
1896
+            IShare::TYPE_ROOM,
1897
+            IShare::TYPE_DECK,
1898
+            IShare::TYPE_SCIENCEMESH
1899
+        ];
1900
+        $shareManager = Server::get(IManager::class);
1901
+        /** @var IShare[] $shares */
1902
+        $shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
1903
+            return $shareManager->getSharesBy($user, $type);
1904
+        }, $providers));
1905
+
1906
+        foreach ($shares as $share) {
1907
+            $sharedPath = $share->getNode()->getPath();
1908
+            if ($targetPath === $sharedPath || str_starts_with($targetPath, $sharedPath . '/')) {
1909
+                $this->logger->debug(
1910
+                    'It is not allowed to move one mount point into a shared folder',
1911
+                    ['app' => 'files']);
1912
+                return false;
1913
+            }
1914
+        }
1915
+
1916
+        return true;
1917
+    }
1918
+
1919
+    /**
1920
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1921
+     */
1922
+    private function getPartFileInfo(string $path): \OC\Files\FileInfo {
1923
+        $mount = $this->getMount($path);
1924
+        $storage = $mount->getStorage();
1925
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1926
+        $ownerId = $storage->getOwner($internalPath);
1927
+        if ($ownerId !== false) {
1928
+            $owner = Server::get(IUserManager::class)->get($ownerId);
1929
+        } else {
1930
+            $owner = null;
1931
+        }
1932
+        return new FileInfo(
1933
+            $this->getAbsolutePath($path),
1934
+            $storage,
1935
+            $internalPath,
1936
+            [
1937
+                'fileid' => null,
1938
+                'mimetype' => $storage->getMimeType($internalPath),
1939
+                'name' => basename($path),
1940
+                'etag' => null,
1941
+                'size' => $storage->filesize($internalPath),
1942
+                'mtime' => $storage->filemtime($internalPath),
1943
+                'encrypted' => false,
1944
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1945
+            ],
1946
+            $mount,
1947
+            $owner
1948
+        );
1949
+    }
1950
+
1951
+    /**
1952
+     * @param string $path
1953
+     * @param string $fileName
1954
+     * @param bool $readonly Check only if the path is allowed for read-only access
1955
+     * @throws InvalidPathException
1956
+     */
1957
+    public function verifyPath($path, $fileName, $readonly = false): void {
1958
+        // All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
1959
+        if (!Filesystem::isValidPath($path ?: '/')) {
1960
+            $l = \OCP\Util::getL10N('lib');
1961
+            throw new InvalidPathException($l->t('Path contains invalid segments'));
1962
+        }
1963
+
1964
+        // Short cut for read-only validation
1965
+        if ($readonly) {
1966
+            $validator = Server::get(FilenameValidator::class);
1967
+            if ($validator->isForbidden($fileName)) {
1968
+                $l = \OCP\Util::getL10N('lib');
1969
+                throw new InvalidPathException($l->t('Filename is a reserved word'));
1970
+            }
1971
+            return;
1972
+        }
1973
+
1974
+        try {
1975
+            /** @type \OCP\Files\Storage $storage */
1976
+            [$storage, $internalPath] = $this->resolvePath($path);
1977
+            $storage->verifyPath($internalPath, $fileName);
1978
+        } catch (ReservedWordException $ex) {
1979
+            $l = \OCP\Util::getL10N('lib');
1980
+            throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename is a reserved word'));
1981
+        } catch (InvalidCharacterInPathException $ex) {
1982
+            $l = \OCP\Util::getL10N('lib');
1983
+            throw new InvalidPathException($ex->getMessage() ?: $l->t('Filename contains at least one invalid character'));
1984
+        } catch (FileNameTooLongException $ex) {
1985
+            $l = \OCP\Util::getL10N('lib');
1986
+            throw new InvalidPathException($l->t('Filename is too long'));
1987
+        } catch (InvalidDirectoryException $ex) {
1988
+            $l = \OCP\Util::getL10N('lib');
1989
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1990
+        } catch (EmptyFileNameException $ex) {
1991
+            $l = \OCP\Util::getL10N('lib');
1992
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1993
+        }
1994
+    }
1995
+
1996
+    /**
1997
+     * get all parent folders of $path
1998
+     *
1999
+     * @param string $path
2000
+     * @return string[]
2001
+     */
2002
+    private function getParents($path) {
2003
+        $path = trim($path, '/');
2004
+        if (!$path) {
2005
+            return [];
2006
+        }
2007
+
2008
+        $parts = explode('/', $path);
2009
+
2010
+        // remove the single file
2011
+        array_pop($parts);
2012
+        $result = ['/'];
2013
+        $resultPath = '';
2014
+        foreach ($parts as $part) {
2015
+            if ($part) {
2016
+                $resultPath .= '/' . $part;
2017
+                $result[] = $resultPath;
2018
+            }
2019
+        }
2020
+        return $result;
2021
+    }
2022
+
2023
+    /**
2024
+     * Returns the mount point for which to lock
2025
+     *
2026
+     * @param string $absolutePath absolute path
2027
+     * @param bool $useParentMount true to return parent mount instead of whatever
2028
+     *                             is mounted directly on the given path, false otherwise
2029
+     * @return IMountPoint mount point for which to apply locks
2030
+     */
2031
+    private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
2032
+        $mount = Filesystem::getMountManager()->find($absolutePath);
2033
+
2034
+        if ($useParentMount) {
2035
+            // find out if something is mounted directly on the path
2036
+            $internalPath = $mount->getInternalPath($absolutePath);
2037
+            if ($internalPath === '') {
2038
+                // resolve the parent mount instead
2039
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
2040
+            }
2041
+        }
2042
+
2043
+        return $mount;
2044
+    }
2045
+
2046
+    /**
2047
+     * Lock the given path
2048
+     *
2049
+     * @param string $path the path of the file to lock, relative to the view
2050
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2051
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2052
+     *
2053
+     * @return bool False if the path is excluded from locking, true otherwise
2054
+     * @throws LockedException if the path is already locked
2055
+     */
2056
+    private function lockPath($path, $type, $lockMountPoint = false) {
2057
+        $absolutePath = $this->getAbsolutePath($path);
2058
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2059
+        if (!$this->shouldLockFile($absolutePath)) {
2060
+            return false;
2061
+        }
2062
+
2063
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2064
+        try {
2065
+            $storage = $mount->getStorage();
2066
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2067
+                $storage->acquireLock(
2068
+                    $mount->getInternalPath($absolutePath),
2069
+                    $type,
2070
+                    $this->lockingProvider
2071
+                );
2072
+            }
2073
+        } catch (LockedException $e) {
2074
+            // rethrow with the human-readable path
2075
+            throw new LockedException(
2076
+                $path,
2077
+                $e,
2078
+                $e->getExistingLock()
2079
+            );
2080
+        }
2081
+
2082
+        return true;
2083
+    }
2084
+
2085
+    /**
2086
+     * Change the lock type
2087
+     *
2088
+     * @param string $path the path of the file to lock, relative to the view
2089
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2090
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2091
+     *
2092
+     * @return bool False if the path is excluded from locking, true otherwise
2093
+     * @throws LockedException if the path is already locked
2094
+     */
2095
+    public function changeLock($path, $type, $lockMountPoint = false) {
2096
+        $path = Filesystem::normalizePath($path);
2097
+        $absolutePath = $this->getAbsolutePath($path);
2098
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2099
+        if (!$this->shouldLockFile($absolutePath)) {
2100
+            return false;
2101
+        }
2102
+
2103
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2104
+        try {
2105
+            $storage = $mount->getStorage();
2106
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2107
+                $storage->changeLock(
2108
+                    $mount->getInternalPath($absolutePath),
2109
+                    $type,
2110
+                    $this->lockingProvider
2111
+                );
2112
+            }
2113
+        } catch (LockedException $e) {
2114
+            // rethrow with the a human-readable path
2115
+            throw new LockedException(
2116
+                $path,
2117
+                $e,
2118
+                $e->getExistingLock()
2119
+            );
2120
+        }
2121
+
2122
+        return true;
2123
+    }
2124
+
2125
+    /**
2126
+     * Unlock the given path
2127
+     *
2128
+     * @param string $path the path of the file to unlock, relative to the view
2129
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2130
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2131
+     *
2132
+     * @return bool False if the path is excluded from locking, true otherwise
2133
+     * @throws LockedException
2134
+     */
2135
+    private function unlockPath($path, $type, $lockMountPoint = false) {
2136
+        $absolutePath = $this->getAbsolutePath($path);
2137
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2138
+        if (!$this->shouldLockFile($absolutePath)) {
2139
+            return false;
2140
+        }
2141
+
2142
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
2143
+        $storage = $mount->getStorage();
2144
+        if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
2145
+            $storage->releaseLock(
2146
+                $mount->getInternalPath($absolutePath),
2147
+                $type,
2148
+                $this->lockingProvider
2149
+            );
2150
+        }
2151
+
2152
+        return true;
2153
+    }
2154
+
2155
+    /**
2156
+     * Lock a path and all its parents up to the root of the view
2157
+     *
2158
+     * @param string $path the path of the file to lock relative to the view
2159
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2160
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2161
+     *
2162
+     * @return bool False if the path is excluded from locking, true otherwise
2163
+     * @throws LockedException
2164
+     */
2165
+    public function lockFile($path, $type, $lockMountPoint = false) {
2166
+        $absolutePath = $this->getAbsolutePath($path);
2167
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2168
+        if (!$this->shouldLockFile($absolutePath)) {
2169
+            return false;
2170
+        }
2171
+
2172
+        $this->lockPath($path, $type, $lockMountPoint);
2173
+
2174
+        $parents = $this->getParents($path);
2175
+        foreach ($parents as $parent) {
2176
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
2177
+        }
2178
+
2179
+        return true;
2180
+    }
2181
+
2182
+    /**
2183
+     * Unlock a path and all its parents up to the root of the view
2184
+     *
2185
+     * @param string $path the path of the file to lock relative to the view
2186
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
2187
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
2188
+     *
2189
+     * @return bool False if the path is excluded from locking, true otherwise
2190
+     * @throws LockedException
2191
+     */
2192
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2193
+        $absolutePath = $this->getAbsolutePath($path);
2194
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2195
+        if (!$this->shouldLockFile($absolutePath)) {
2196
+            return false;
2197
+        }
2198
+
2199
+        $this->unlockPath($path, $type, $lockMountPoint);
2200
+
2201
+        $parents = $this->getParents($path);
2202
+        foreach ($parents as $parent) {
2203
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2204
+        }
2205
+
2206
+        return true;
2207
+    }
2208
+
2209
+    /**
2210
+     * Only lock files in data/user/files/
2211
+     *
2212
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2213
+     * @return bool
2214
+     */
2215
+    protected function shouldLockFile($path) {
2216
+        $path = Filesystem::normalizePath($path);
2217
+
2218
+        $pathSegments = explode('/', $path);
2219
+        if (isset($pathSegments[2])) {
2220
+            // E.g.: /username/files/path-to-file
2221
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2222
+        }
2223
+
2224
+        return !str_starts_with($path, '/appdata_');
2225
+    }
2226
+
2227
+    /**
2228
+     * Shortens the given absolute path to be relative to
2229
+     * "$user/files".
2230
+     *
2231
+     * @param string $absolutePath absolute path which is under "files"
2232
+     *
2233
+     * @return string path relative to "files" with trimmed slashes or null
2234
+     *                if the path was NOT relative to files
2235
+     *
2236
+     * @throws \InvalidArgumentException if the given path was not under "files"
2237
+     * @since 8.1.0
2238
+     */
2239
+    public function getPathRelativeToFiles($absolutePath) {
2240
+        $path = Filesystem::normalizePath($absolutePath);
2241
+        $parts = explode('/', trim($path, '/'), 3);
2242
+        // "$user", "files", "path/to/dir"
2243
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2244
+            $this->logger->error(
2245
+                '$absolutePath must be relative to "files", value is "{absolutePath}"',
2246
+                [
2247
+                    'absolutePath' => $absolutePath,
2248
+                ]
2249
+            );
2250
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2251
+        }
2252
+        if (isset($parts[2])) {
2253
+            return $parts[2];
2254
+        }
2255
+        return '';
2256
+    }
2257
+
2258
+    /**
2259
+     * @param string $filename
2260
+     * @return array
2261
+     * @throws \OC\User\NoUserException
2262
+     * @throws NotFoundException
2263
+     */
2264
+    public function getUidAndFilename($filename) {
2265
+        $info = $this->getFileInfo($filename);
2266
+        if (!$info instanceof \OCP\Files\FileInfo) {
2267
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2268
+        }
2269
+        $uid = $info->getOwner()->getUID();
2270
+        if ($uid != \OC_User::getUser()) {
2271
+            Filesystem::initMountPoints($uid);
2272
+            $ownerView = new View('/' . $uid . '/files');
2273
+            try {
2274
+                $filename = $ownerView->getPath($info['fileid']);
2275
+            } catch (NotFoundException $e) {
2276
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2277
+            }
2278
+        }
2279
+        return [$uid, $filename];
2280
+    }
2281
+
2282
+    /**
2283
+     * Creates parent non-existing folders
2284
+     *
2285
+     * @param string $filePath
2286
+     * @return bool
2287
+     */
2288
+    private function createParentDirectories($filePath) {
2289
+        $directoryParts = explode('/', $filePath);
2290
+        $directoryParts = array_filter($directoryParts);
2291
+        foreach ($directoryParts as $key => $part) {
2292
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2293
+            $currentPath = '/' . implode('/', $currentPathElements);
2294
+            if ($this->is_file($currentPath)) {
2295
+                return false;
2296
+            }
2297
+            if (!$this->file_exists($currentPath)) {
2298
+                $this->mkdir($currentPath);
2299
+            }
2300
+        }
2301
+
2302
+        return true;
2303
+    }
2304 2304
 }
Please login to merge, or discard this patch.