Completed
Pull Request — master (#2847)
by Morris
38:03 queued 26:02
created
apps/files_sharing/lib/SharedMount.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 *
111 111
 	 * @param string $newPath
112 112
 	 * @param \OCP\Share\IShare $share
113
-	 * @return bool
113
+	 * @return boolean|null
114 114
 	 */
115 115
 	private function updateFileTarget($newPath, &$share) {
116 116
 		$share->setTarget($newPath);
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 	 * @param string $path
127 127
 	 * @param View $view
128 128
 	 * @param SharedMount[] $mountpoints
129
-	 * @return mixed
129
+	 * @return string
130 130
 	 */
131 131
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
132 132
 		$pathinfo = pathinfo($path);
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -66,14 +66,14 @@  discard block
 block discarded – undo
66 66
 	 */
67 67
 	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
68 68
 		$this->user = $arguments['user'];
69
-		$this->recipientView = new View('/' . $this->user . '/files');
69
+		$this->recipientView = new View('/'.$this->user.'/files');
70 70
 
71 71
 		$this->superShare = $arguments['superShare'];
72 72
 		$this->groupedShares = $arguments['groupedShares'];
73 73
 
74 74
 		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
75
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
76
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
75
+		$absMountPoint = '/'.$this->user.'/files'.$newMountPoint;
76
+		$arguments['ownerView'] = new View('/'.$this->superShare->getShareOwner().'/files');
77 77
 		parent::__construct($storage, $absMountPoint, $arguments, $loader);
78 78
 	}
79 79
 
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 		}
95 95
 
96 96
 		$newMountPoint = $this->generateUniqueTarget(
97
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
97
+			\OC\Files\Filesystem::normalizePath($parent.'/'.$mountPoint),
98 98
 			$this->recipientView,
99 99
 			$mountpoints
100 100
 		);
@@ -131,12 +131,12 @@  discard block
 block discarded – undo
131 131
 	 */
132 132
 	private function generateUniqueTarget($path, $view, array $mountpoints) {
133 133
 		$pathinfo = pathinfo($path);
134
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
134
+		$ext = (isset($pathinfo['extension'])) ? '.'.$pathinfo['extension'] : '';
135 135
 		$name = $pathinfo['filename'];
136 136
 		$dir = $pathinfo['dirname'];
137 137
 
138 138
 		// Helper function to find existing mount points
139
-		$mountpointExists = function ($path) use ($mountpoints) {
139
+		$mountpointExists = function($path) use ($mountpoints) {
140 140
 			foreach ($mountpoints as $mountpoint) {
141 141
 				if ($mountpoint->getShare()->getTarget() === $path) {
142 142
 					return true;
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 
148 148
 		$i = 2;
149 149
 		while ($view->file_exists($path) || $mountpointExists($path)) {
150
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
150
+			$path = Filesystem::normalizePath($dir.'/'.$name.' ('.$i.')'.$ext);
151 151
 			$i++;
152 152
 		}
153 153
 
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 		// it is not a file relative to data/user/files
169 169
 		if (count($split) < 3 || $split[1] !== 'files') {
170 170
 			\OCP\Util::writeLog('file sharing',
171
-				'Can not strip userid and "files/" from path: ' . $path,
171
+				'Can not strip userid and "files/" from path: '.$path,
172 172
 				\OCP\Util::ERROR);
173 173
 			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
174 174
 		}
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 		$sliced = array_slice($split, 2);
178 178
 		$relPath = implode('/', $sliced);
179 179
 
180
-		return '/' . $relPath;
180
+		return '/'.$relPath;
181 181
 	}
182 182
 
183 183
 	/**
@@ -191,10 +191,10 @@  discard block
 block discarded – undo
191 191
 	public function isTargetAllowed($target) {
192 192
 		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
193 193
 		// note: cannot use the view because the target is already locked
194
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
194
+		$fileId = (int) $targetStorage->getCache()->getId($targetInternalPath);
195 195
 		if ($fileId === -1) {
196 196
 			// target might not exist, need to check parent instead
197
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
197
+			$fileId = (int) $targetStorage->getCache()->getId(dirname($targetInternalPath));
198 198
 		}
199 199
 
200 200
 		$targetNodes = \OC::$server->getRootFolder()->getById($fileId);
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 			$this->storage->setMountPoint($relTargetPath);
247 247
 		} catch (\Exception $e) {
248 248
 			\OCP\Util::writeLog('file sharing',
249
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
249
+				'Could not rename mount point for shared folder "'.$this->getMountPoint().'" to "'.$target.'"',
250 250
 				\OCP\Util::ERROR);
251 251
 		}
252 252
 
@@ -301,7 +301,7 @@  discard block
 block discarded – undo
301 301
 			$row = $result->fetch();
302 302
 			$result->closeCursor();
303 303
 			if ($row) {
304
-				return (int)$row['storage'];
304
+				return (int) $row['storage'];
305 305
 			}
306 306
 			return -1;
307 307
 		}
Please login to merge, or discard this patch.
Indentation   +273 added lines, -273 removed lines patch added patch discarded remove patch
@@ -37,277 +37,277 @@
 block discarded – undo
37 37
  * Shared mount points can be moved by the user
38 38
  */
39 39
 class SharedMount extends MountPoint implements MoveableMount {
40
-	/**
41
-	 * @var \OCA\Files_Sharing\SharedStorage $storage
42
-	 */
43
-	protected $storage = null;
44
-
45
-	/**
46
-	 * @var \OC\Files\View
47
-	 */
48
-	private $recipientView;
49
-
50
-	/**
51
-	 * @var string
52
-	 */
53
-	private $user;
54
-
55
-	/** @var \OCP\Share\IShare */
56
-	private $superShare;
57
-
58
-	/** @var \OCP\Share\IShare[] */
59
-	private $groupedShares;
60
-
61
-	/**
62
-	 * @param string $storage
63
-	 * @param SharedMount[] $mountpoints
64
-	 * @param array|null $arguments
65
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
66
-	 */
67
-	public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
68
-		$this->user = $arguments['user'];
69
-		$this->recipientView = new View('/' . $this->user . '/files');
70
-
71
-		$this->superShare = $arguments['superShare'];
72
-		$this->groupedShares = $arguments['groupedShares'];
73
-
74
-		$newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
75
-		$absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
76
-		$arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
77
-		parent::__construct($storage, $absMountPoint, $arguments, $loader);
78
-	}
79
-
80
-	/**
81
-	 * check if the parent folder exists otherwise move the mount point up
82
-	 *
83
-	 * @param \OCP\Share\IShare $share
84
-	 * @param SharedMount[] $mountpoints
85
-	 * @return string
86
-	 */
87
-	private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
88
-
89
-		$mountPoint = basename($share->getTarget());
90
-		$parent = dirname($share->getTarget());
91
-
92
-		if (!$this->recipientView->is_dir($parent)) {
93
-			$parent = Helper::getShareFolder($this->recipientView);
94
-		}
95
-
96
-		$newMountPoint = $this->generateUniqueTarget(
97
-			\OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
98
-			$this->recipientView,
99
-			$mountpoints
100
-		);
101
-
102
-		if ($newMountPoint !== $share->getTarget()) {
103
-			$this->updateFileTarget($newMountPoint, $share);
104
-		}
105
-
106
-		return $newMountPoint;
107
-	}
108
-
109
-	/**
110
-	 * update fileTarget in the database if the mount point changed
111
-	 *
112
-	 * @param string $newPath
113
-	 * @param \OCP\Share\IShare $share
114
-	 * @return bool
115
-	 */
116
-	private function updateFileTarget($newPath, &$share) {
117
-		$share->setTarget($newPath);
118
-
119
-		foreach ($this->groupedShares as $tmpShare) {
120
-			$tmpShare->setTarget($newPath);
121
-			\OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
122
-		}
123
-	}
124
-
125
-
126
-	/**
127
-	 * @param string $path
128
-	 * @param View $view
129
-	 * @param SharedMount[] $mountpoints
130
-	 * @return mixed
131
-	 */
132
-	private function generateUniqueTarget($path, $view, array $mountpoints) {
133
-		$pathinfo = pathinfo($path);
134
-		$ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
135
-		$name = $pathinfo['filename'];
136
-		$dir = $pathinfo['dirname'];
137
-
138
-		// Helper function to find existing mount points
139
-		$mountpointExists = function ($path) use ($mountpoints) {
140
-			foreach ($mountpoints as $mountpoint) {
141
-				if ($mountpoint->getShare()->getTarget() === $path) {
142
-					return true;
143
-				}
144
-			}
145
-			return false;
146
-		};
147
-
148
-		$i = 2;
149
-		while ($view->file_exists($path) || $mountpointExists($path)) {
150
-			$path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
151
-			$i++;
152
-		}
153
-
154
-		return $path;
155
-	}
156
-
157
-	/**
158
-	 * Format a path to be relative to the /user/files/ directory
159
-	 *
160
-	 * @param string $path the absolute path
161
-	 * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
162
-	 * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
163
-	 */
164
-	protected function stripUserFilesPath($path) {
165
-		$trimmed = ltrim($path, '/');
166
-		$split = explode('/', $trimmed);
167
-
168
-		// it is not a file relative to data/user/files
169
-		if (count($split) < 3 || $split[1] !== 'files') {
170
-			\OCP\Util::writeLog('file sharing',
171
-				'Can not strip userid and "files/" from path: ' . $path,
172
-				\OCP\Util::ERROR);
173
-			throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
174
-		}
175
-
176
-		// skip 'user' and 'files'
177
-		$sliced = array_slice($split, 2);
178
-		$relPath = implode('/', $sliced);
179
-
180
-		return '/' . $relPath;
181
-	}
182
-
183
-	/**
184
-	 * Check whether it is allowed to move a mount point to a given target.
185
-	 * It is not allowed to move a mount point into a different mount point or
186
-	 * into an already shared folder
187
-	 *
188
-	 * @param string $target absolute target path
189
-	 * @return bool true if allowed, false otherwise
190
-	 */
191
-	public function isTargetAllowed($target) {
192
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
193
-		// note: cannot use the view because the target is already locked
194
-		$fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
195
-		if ($fileId === -1) {
196
-			// target might not exist, need to check parent instead
197
-			$fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
198
-		}
199
-
200
-		$targetNodes = \OC::$server->getRootFolder()->getById($fileId);
201
-		if (empty($targetNodes)) {
202
-			return false;
203
-		}
204
-
205
-		$shareManager = \OC::$server->getShareManager();
206
-		$targetNode = $targetNodes[0];
207
-		// FIXME: make it stop earlier in '/$userId/files'
208
-		while (!is_null($targetNode) && $targetNode->getPath() !== '/') { 
209
-			$shares = $shareManager->getSharesByPath($targetNode);
210
-
211
-			foreach ($shares as $share) {
212
-				if ($this->user === $share->getShareOwner()) {
213
-					\OCP\Util::writeLog('files',
214
-						'It is not allowed to move one mount point into a shared folder',
215
-						\OCP\Util::DEBUG);
216
-					return false;
217
-				}
218
-			}
219
-
220
-			$targetNode = $targetNode->getParent();
221
-		}
222
-
223
-		return true;
224
-	}
225
-
226
-
227
-	/**
228
-	 * Move the mount point to $target
229
-	 *
230
-	 * @param string $target the target mount point
231
-	 * @return bool
232
-	 */
233
-	public function moveMount($target) {
234
-		if (!$this->isTargetAllowed($target)) {
235
-			return false;
236
-		}
237
-
238
-		$relTargetPath = $this->stripUserFilesPath($target);
239
-		$share = $this->storage->getShare();
240
-
241
-		$result = true;
242
-
243
-		try {
244
-			$this->updateFileTarget($relTargetPath, $share);
245
-			$this->setMountPoint($target);
246
-			$this->storage->setMountPoint($relTargetPath);
247
-		} catch (\Exception $e) {
248
-			\OCP\Util::writeLog('file sharing',
249
-				'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
250
-				\OCP\Util::ERROR);
251
-		}
252
-
253
-		return $result;
254
-	}
255
-
256
-	/**
257
-	 * Remove the mount points
258
-	 *
259
-	 * @return bool
260
-	 */
261
-	public function removeMount() {
262
-		$mountManager = \OC\Files\Filesystem::getMountManager();
263
-		/** @var $storage \OCA\Files_Sharing\SharedStorage */
264
-		$storage = $this->getStorage();
265
-		$result = $storage->unshareStorage();
266
-		$mountManager->removeMount($this->mountPoint);
267
-
268
-		return $result;
269
-	}
270
-
271
-	/**
272
-	 * @return \OCP\Share\IShare
273
-	 */
274
-	public function getShare() {
275
-		return $this->superShare;
276
-	}
277
-
278
-	/**
279
-	 * Get the file id of the root of the storage
280
-	 *
281
-	 * @return int
282
-	 */
283
-	public function getStorageRootId() {
284
-		return $this->getShare()->getNodeId();
285
-	}
286
-
287
-	/**
288
-	 * @return int
289
-	 */
290
-	public function getNumericStorageId() {
291
-		if (!is_null($this->getShare()->getNodeCacheEntry())) {
292
-			return $this->getShare()->getNodeCacheEntry()->getStorageId();
293
-		} else {
294
-			$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
295
-
296
-			$query = $builder->select('storage')
297
-				->from('filecache')
298
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
299
-
300
-			$result = $query->execute();
301
-			$row = $result->fetch();
302
-			$result->closeCursor();
303
-			if ($row) {
304
-				return (int)$row['storage'];
305
-			}
306
-			return -1;
307
-		}
308
-	}
309
-
310
-	public function getMountType() {
311
-		return 'shared';
312
-	}
40
+    /**
41
+     * @var \OCA\Files_Sharing\SharedStorage $storage
42
+     */
43
+    protected $storage = null;
44
+
45
+    /**
46
+     * @var \OC\Files\View
47
+     */
48
+    private $recipientView;
49
+
50
+    /**
51
+     * @var string
52
+     */
53
+    private $user;
54
+
55
+    /** @var \OCP\Share\IShare */
56
+    private $superShare;
57
+
58
+    /** @var \OCP\Share\IShare[] */
59
+    private $groupedShares;
60
+
61
+    /**
62
+     * @param string $storage
63
+     * @param SharedMount[] $mountpoints
64
+     * @param array|null $arguments
65
+     * @param \OCP\Files\Storage\IStorageFactory $loader
66
+     */
67
+    public function __construct($storage, array $mountpoints, $arguments = null, $loader = null) {
68
+        $this->user = $arguments['user'];
69
+        $this->recipientView = new View('/' . $this->user . '/files');
70
+
71
+        $this->superShare = $arguments['superShare'];
72
+        $this->groupedShares = $arguments['groupedShares'];
73
+
74
+        $newMountPoint = $this->verifyMountPoint($this->superShare, $mountpoints);
75
+        $absMountPoint = '/' . $this->user . '/files' . $newMountPoint;
76
+        $arguments['ownerView'] = new View('/' . $this->superShare->getShareOwner() . '/files');
77
+        parent::__construct($storage, $absMountPoint, $arguments, $loader);
78
+    }
79
+
80
+    /**
81
+     * check if the parent folder exists otherwise move the mount point up
82
+     *
83
+     * @param \OCP\Share\IShare $share
84
+     * @param SharedMount[] $mountpoints
85
+     * @return string
86
+     */
87
+    private function verifyMountPoint(\OCP\Share\IShare $share, array $mountpoints) {
88
+
89
+        $mountPoint = basename($share->getTarget());
90
+        $parent = dirname($share->getTarget());
91
+
92
+        if (!$this->recipientView->is_dir($parent)) {
93
+            $parent = Helper::getShareFolder($this->recipientView);
94
+        }
95
+
96
+        $newMountPoint = $this->generateUniqueTarget(
97
+            \OC\Files\Filesystem::normalizePath($parent . '/' . $mountPoint),
98
+            $this->recipientView,
99
+            $mountpoints
100
+        );
101
+
102
+        if ($newMountPoint !== $share->getTarget()) {
103
+            $this->updateFileTarget($newMountPoint, $share);
104
+        }
105
+
106
+        return $newMountPoint;
107
+    }
108
+
109
+    /**
110
+     * update fileTarget in the database if the mount point changed
111
+     *
112
+     * @param string $newPath
113
+     * @param \OCP\Share\IShare $share
114
+     * @return bool
115
+     */
116
+    private function updateFileTarget($newPath, &$share) {
117
+        $share->setTarget($newPath);
118
+
119
+        foreach ($this->groupedShares as $tmpShare) {
120
+            $tmpShare->setTarget($newPath);
121
+            \OC::$server->getShareManager()->moveShare($tmpShare, $this->user);
122
+        }
123
+    }
124
+
125
+
126
+    /**
127
+     * @param string $path
128
+     * @param View $view
129
+     * @param SharedMount[] $mountpoints
130
+     * @return mixed
131
+     */
132
+    private function generateUniqueTarget($path, $view, array $mountpoints) {
133
+        $pathinfo = pathinfo($path);
134
+        $ext = (isset($pathinfo['extension'])) ? '.' . $pathinfo['extension'] : '';
135
+        $name = $pathinfo['filename'];
136
+        $dir = $pathinfo['dirname'];
137
+
138
+        // Helper function to find existing mount points
139
+        $mountpointExists = function ($path) use ($mountpoints) {
140
+            foreach ($mountpoints as $mountpoint) {
141
+                if ($mountpoint->getShare()->getTarget() === $path) {
142
+                    return true;
143
+                }
144
+            }
145
+            return false;
146
+        };
147
+
148
+        $i = 2;
149
+        while ($view->file_exists($path) || $mountpointExists($path)) {
150
+            $path = Filesystem::normalizePath($dir . '/' . $name . ' (' . $i . ')' . $ext);
151
+            $i++;
152
+        }
153
+
154
+        return $path;
155
+    }
156
+
157
+    /**
158
+     * Format a path to be relative to the /user/files/ directory
159
+     *
160
+     * @param string $path the absolute path
161
+     * @return string e.g. turns '/admin/files/test.txt' into '/test.txt'
162
+     * @throws \OCA\Files_Sharing\Exceptions\BrokenPath
163
+     */
164
+    protected function stripUserFilesPath($path) {
165
+        $trimmed = ltrim($path, '/');
166
+        $split = explode('/', $trimmed);
167
+
168
+        // it is not a file relative to data/user/files
169
+        if (count($split) < 3 || $split[1] !== 'files') {
170
+            \OCP\Util::writeLog('file sharing',
171
+                'Can not strip userid and "files/" from path: ' . $path,
172
+                \OCP\Util::ERROR);
173
+            throw new \OCA\Files_Sharing\Exceptions\BrokenPath('Path does not start with /user/files', 10);
174
+        }
175
+
176
+        // skip 'user' and 'files'
177
+        $sliced = array_slice($split, 2);
178
+        $relPath = implode('/', $sliced);
179
+
180
+        return '/' . $relPath;
181
+    }
182
+
183
+    /**
184
+     * Check whether it is allowed to move a mount point to a given target.
185
+     * It is not allowed to move a mount point into a different mount point or
186
+     * into an already shared folder
187
+     *
188
+     * @param string $target absolute target path
189
+     * @return bool true if allowed, false otherwise
190
+     */
191
+    public function isTargetAllowed($target) {
192
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
193
+        // note: cannot use the view because the target is already locked
194
+        $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
195
+        if ($fileId === -1) {
196
+            // target might not exist, need to check parent instead
197
+            $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
198
+        }
199
+
200
+        $targetNodes = \OC::$server->getRootFolder()->getById($fileId);
201
+        if (empty($targetNodes)) {
202
+            return false;
203
+        }
204
+
205
+        $shareManager = \OC::$server->getShareManager();
206
+        $targetNode = $targetNodes[0];
207
+        // FIXME: make it stop earlier in '/$userId/files'
208
+        while (!is_null($targetNode) && $targetNode->getPath() !== '/') { 
209
+            $shares = $shareManager->getSharesByPath($targetNode);
210
+
211
+            foreach ($shares as $share) {
212
+                if ($this->user === $share->getShareOwner()) {
213
+                    \OCP\Util::writeLog('files',
214
+                        'It is not allowed to move one mount point into a shared folder',
215
+                        \OCP\Util::DEBUG);
216
+                    return false;
217
+                }
218
+            }
219
+
220
+            $targetNode = $targetNode->getParent();
221
+        }
222
+
223
+        return true;
224
+    }
225
+
226
+
227
+    /**
228
+     * Move the mount point to $target
229
+     *
230
+     * @param string $target the target mount point
231
+     * @return bool
232
+     */
233
+    public function moveMount($target) {
234
+        if (!$this->isTargetAllowed($target)) {
235
+            return false;
236
+        }
237
+
238
+        $relTargetPath = $this->stripUserFilesPath($target);
239
+        $share = $this->storage->getShare();
240
+
241
+        $result = true;
242
+
243
+        try {
244
+            $this->updateFileTarget($relTargetPath, $share);
245
+            $this->setMountPoint($target);
246
+            $this->storage->setMountPoint($relTargetPath);
247
+        } catch (\Exception $e) {
248
+            \OCP\Util::writeLog('file sharing',
249
+                'Could not rename mount point for shared folder "' . $this->getMountPoint() . '" to "' . $target . '"',
250
+                \OCP\Util::ERROR);
251
+        }
252
+
253
+        return $result;
254
+    }
255
+
256
+    /**
257
+     * Remove the mount points
258
+     *
259
+     * @return bool
260
+     */
261
+    public function removeMount() {
262
+        $mountManager = \OC\Files\Filesystem::getMountManager();
263
+        /** @var $storage \OCA\Files_Sharing\SharedStorage */
264
+        $storage = $this->getStorage();
265
+        $result = $storage->unshareStorage();
266
+        $mountManager->removeMount($this->mountPoint);
267
+
268
+        return $result;
269
+    }
270
+
271
+    /**
272
+     * @return \OCP\Share\IShare
273
+     */
274
+    public function getShare() {
275
+        return $this->superShare;
276
+    }
277
+
278
+    /**
279
+     * Get the file id of the root of the storage
280
+     *
281
+     * @return int
282
+     */
283
+    public function getStorageRootId() {
284
+        return $this->getShare()->getNodeId();
285
+    }
286
+
287
+    /**
288
+     * @return int
289
+     */
290
+    public function getNumericStorageId() {
291
+        if (!is_null($this->getShare()->getNodeCacheEntry())) {
292
+            return $this->getShare()->getNodeCacheEntry()->getStorageId();
293
+        } else {
294
+            $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
295
+
296
+            $query = $builder->select('storage')
297
+                ->from('filecache')
298
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($this->getStorageRootId())));
299
+
300
+            $result = $query->execute();
301
+            $row = $result->fetch();
302
+            $result->closeCursor();
303
+            if ($row) {
304
+                return (int)$row['storage'];
305
+            }
306
+            return -1;
307
+        }
308
+    }
309
+
310
+    public function getMountType() {
311
+        return 'shared';
312
+    }
313 313
 }
Please login to merge, or discard this patch.
lib/private/Files/Mount/MoveableMount.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -27,30 +27,30 @@
 block discarded – undo
27 27
  * Defines the mount point to be (re)moved by the user
28 28
  */
29 29
 interface MoveableMount {
30
-	/**
31
-	 * Move the mount point to $target
32
-	 *
33
-	 * @param string $target the target mount point
34
-	 * @return bool
35
-	 */
36
-	public function moveMount($target);
30
+    /**
31
+     * Move the mount point to $target
32
+     *
33
+     * @param string $target the target mount point
34
+     * @return bool
35
+     */
36
+    public function moveMount($target);
37 37
 
38
-	/**
39
-	 * Remove the mount points
40
-	 *
41
-	 * @return mixed
42
-	 * @return bool
43
-	 */
44
-	public function removeMount();
38
+    /**
39
+     * Remove the mount points
40
+     *
41
+     * @return mixed
42
+     * @return bool
43
+     */
44
+    public function removeMount();
45 45
 
46
-	/**
47
-	 * Returns whether this mount point is allowed to be moved into the given absolute target
48
-	 *
49
-	 * @param string $target absolute target path
50
-	 *
51
-	 * @return bool true if allowed, false otherwise
52
-	 *
53
-	 * @since 12.0
54
-	 */
55
-	public function isTargetAllowed($target);
46
+    /**
47
+     * Returns whether this mount point is allowed to be moved into the given absolute target
48
+     *
49
+     * @param string $target absolute target path
50
+     *
51
+     * @return bool true if allowed, false otherwise
52
+     *
53
+     * @since 12.0
54
+     */
55
+    public function isTargetAllowed($target);
56 56
 }
Please login to merge, or discard this patch.
lib/private/Files/View.php 2 patches
Spacing   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -130,9 +130,9 @@  discard block
 block discarded – undo
130 130
 			$path = '/';
131 131
 		}
132 132
 		if ($path[0] !== '/') {
133
-			$path = '/' . $path;
133
+			$path = '/'.$path;
134 134
 		}
135
-		return $this->fakeRoot . $path;
135
+		return $this->fakeRoot.$path;
136 136
 	}
137 137
 
138 138
 	/**
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	public function chroot($fakeRoot) {
145 145
 		if (!$fakeRoot == '') {
146 146
 			if ($fakeRoot[0] !== '/') {
147
-				$fakeRoot = '/' . $fakeRoot;
147
+				$fakeRoot = '/'.$fakeRoot;
148 148
 			}
149 149
 		}
150 150
 		$this->fakeRoot = $fakeRoot;
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		}
177 177
 
178 178
 		// missing slashes can cause wrong matches!
179
-		$root = rtrim($this->fakeRoot, '/') . '/';
179
+		$root = rtrim($this->fakeRoot, '/').'/';
180 180
 
181 181
 		if (strpos($path, $root) !== 0) {
182 182
 			return null;
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
 		if ($mount instanceof MoveableMount) {
283 283
 			// cut of /user/files to get the relative path to data/user/files
284 284
 			$pathParts = explode('/', $path, 4);
285
-			$relPath = '/' . $pathParts[3];
285
+			$relPath = '/'.$pathParts[3];
286 286
 			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
287 287
 			\OC_Hook::emit(
288 288
 				Filesystem::CLASSNAME, "umount",
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
 		}
694 694
 		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
695 695
 		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
696
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
696
+		$mount = Filesystem::getMountManager()->find($absolutePath.$postFix);
697 697
 		if ($mount and $mount->getInternalPath($absolutePath) === '') {
698 698
 			return $this->removeMount($mount, $absolutePath);
699 699
 		}
@@ -963,7 +963,7 @@  discard block
 block discarded – undo
963 963
 				$hooks[] = 'write';
964 964
 				break;
965 965
 			default:
966
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
966
+				\OCP\Util::writeLog('core', 'invalid mode ('.$mode.') for '.$path, \OCP\Util::ERROR);
967 967
 		}
968 968
 
969 969
 		if ($mode !== 'r' && $mode !== 'w') {
@@ -1067,7 +1067,7 @@  discard block
 block discarded – undo
1067 1067
 					array(Filesystem::signal_param_path => $this->getHookPath($path))
1068 1068
 				);
1069 1069
 			}
1070
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1070
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1071 1071
 			if ($storage) {
1072 1072
 				$result = $storage->hash($type, $internalPath, $raw);
1073 1073
 				return $result;
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
 
1119 1119
 			$run = $this->runHooks($hooks, $path);
1120 1120
 			/** @var \OC\Files\Storage\Storage $storage */
1121
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1121
+			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath.$postFix);
1122 1122
 			if ($run and $storage) {
1123 1123
 				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1124 1124
 					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
 					$unlockLater = true;
1158 1158
 					// make sure our unlocking callback will still be called if connection is aborted
1159 1159
 					ignore_user_abort(true);
1160
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1160
+					$result = CallbackWrapper::wrap($result, null, null, function() use ($hooks, $path) {
1161 1161
 						if (in_array('write', $hooks)) {
1162 1162
 							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1163 1163
 						} else if (in_array('read', $hooks)) {
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
 			return true;
1219 1219
 		}
1220 1220
 
1221
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1221
+		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot.'/');
1222 1222
 	}
1223 1223
 
1224 1224
 	/**
@@ -1237,7 +1237,7 @@  discard block
 block discarded – undo
1237 1237
 				if ($hook != 'read') {
1238 1238
 					\OC_Hook::emit(
1239 1239
 						Filesystem::CLASSNAME,
1240
-						$prefix . $hook,
1240
+						$prefix.$hook,
1241 1241
 						array(
1242 1242
 							Filesystem::signal_param_run => &$run,
1243 1243
 							Filesystem::signal_param_path => $path
@@ -1246,7 +1246,7 @@  discard block
 block discarded – undo
1246 1246
 				} elseif (!$post) {
1247 1247
 					\OC_Hook::emit(
1248 1248
 						Filesystem::CLASSNAME,
1249
-						$prefix . $hook,
1249
+						$prefix.$hook,
1250 1250
 						array(
1251 1251
 							Filesystem::signal_param_path => $path
1252 1252
 						)
@@ -1341,7 +1341,7 @@  discard block
 block discarded – undo
1341 1341
 			return $this->getPartFileInfo($path);
1342 1342
 		}
1343 1343
 		$relativePath = $path;
1344
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1344
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1345 1345
 
1346 1346
 		$mount = Filesystem::getMountManager()->find($path);
1347 1347
 		$storage = $mount->getStorage();
@@ -1365,7 +1365,7 @@  discard block
 block discarded – undo
1365 1365
 					//add the sizes of other mount points to the folder
1366 1366
 					$extOnly = ($includeMountPoints === 'ext');
1367 1367
 					$mounts = Filesystem::getMountManager()->findIn($path);
1368
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1368
+					$info->setSubMounts(array_filter($mounts, function(IMountPoint $mount) use ($extOnly) {
1369 1369
 						$subStorage = $mount->getStorage();
1370 1370
 						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1371 1371
 					}));
@@ -1412,12 +1412,12 @@  discard block
 block discarded – undo
1412 1412
 			/**
1413 1413
 			 * @var \OC\Files\FileInfo[] $files
1414 1414
 			 */
1415
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1415
+			$files = array_map(function(ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1416 1416
 				if ($sharingDisabled) {
1417 1417
 					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1418 1418
 				}
1419 1419
 				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1420
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1420
+				return new FileInfo($path.'/'.$content['name'], $storage, $content['path'], $content, $mount, $owner);
1421 1421
 			}, $contents);
1422 1422
 
1423 1423
 			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
@@ -1442,8 +1442,8 @@  discard block
 block discarded – undo
1442 1442
 							// sometimes when the storage is not available it can be any exception
1443 1443
 							\OCP\Util::writeLog(
1444 1444
 								'core',
1445
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1446
-								get_class($e) . ': ' . $e->getMessage(),
1445
+								'Exception while scanning storage "'.$subStorage->getId().'": '.
1446
+								get_class($e).': '.$e->getMessage(),
1447 1447
 								\OCP\Util::ERROR
1448 1448
 							);
1449 1449
 							continue;
@@ -1480,7 +1480,7 @@  discard block
 block discarded – undo
1480 1480
 									break;
1481 1481
 								}
1482 1482
 							}
1483
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1483
+							$rootEntry['path'] = substr(Filesystem::normalizePath($path.'/'.$rootEntry['name']), strlen($user) + 2); // full path without /$user/
1484 1484
 
1485 1485
 							// if sharing was disabled for the user we remove the share permissions
1486 1486
 							if (\OCP\Util::isSharingDisabledForUser()) {
@@ -1488,14 +1488,14 @@  discard block
 block discarded – undo
1488 1488
 							}
1489 1489
 
1490 1490
 							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1491
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1491
+							$files[] = new FileInfo($path.'/'.$rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1492 1492
 						}
1493 1493
 					}
1494 1494
 				}
1495 1495
 			}
1496 1496
 
1497 1497
 			if ($mimetype_filter) {
1498
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1498
+				$files = array_filter($files, function(FileInfo $file) use ($mimetype_filter) {
1499 1499
 					if (strpos($mimetype_filter, '/')) {
1500 1500
 						return $file->getMimetype() === $mimetype_filter;
1501 1501
 					} else {
@@ -1524,7 +1524,7 @@  discard block
 block discarded – undo
1524 1524
 		if ($data instanceof FileInfo) {
1525 1525
 			$data = $data->getData();
1526 1526
 		}
1527
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1527
+		$path = Filesystem::normalizePath($this->fakeRoot.'/'.$path);
1528 1528
 		/**
1529 1529
 		 * @var \OC\Files\Storage\Storage $storage
1530 1530
 		 * @var string $internalPath
@@ -1551,7 +1551,7 @@  discard block
 block discarded – undo
1551 1551
 	 * @return FileInfo[]
1552 1552
 	 */
1553 1553
 	public function search($query) {
1554
-		return $this->searchCommon('search', array('%' . $query . '%'));
1554
+		return $this->searchCommon('search', array('%'.$query.'%'));
1555 1555
 	}
1556 1556
 
1557 1557
 	/**
@@ -1602,10 +1602,10 @@  discard block
 block discarded – undo
1602 1602
 
1603 1603
 			$results = call_user_func_array(array($cache, $method), $args);
1604 1604
 			foreach ($results as $result) {
1605
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1605
+				if (substr($mountPoint.$result['path'], 0, $rootLength + 1) === $this->fakeRoot.'/') {
1606 1606
 					$internalPath = $result['path'];
1607
-					$path = $mountPoint . $result['path'];
1608
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
+					$path = $mountPoint.$result['path'];
1608
+					$result['path'] = substr($mountPoint.$result['path'], $rootLength);
1609 1609
 					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1610 1610
 					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1611 1611
 				}
@@ -1623,8 +1623,8 @@  discard block
 block discarded – undo
1623 1623
 					if ($results) {
1624 1624
 						foreach ($results as $result) {
1625 1625
 							$internalPath = $result['path'];
1626
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1627
-							$path = rtrim($mountPoint . $internalPath, '/');
1626
+							$result['path'] = rtrim($relativeMountPoint.$result['path'], '/');
1627
+							$path = rtrim($mountPoint.$internalPath, '/');
1628 1628
 							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1629 1629
 							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1630 1630
 						}
@@ -1645,7 +1645,7 @@  discard block
 block discarded – undo
1645 1645
 	public function getOwner($path) {
1646 1646
 		$info = $this->getFileInfo($path);
1647 1647
 		if (!$info) {
1648
-			throw new NotFoundException($path . ' not found while trying to get owner');
1648
+			throw new NotFoundException($path.' not found while trying to get owner');
1649 1649
 		}
1650 1650
 		return $info->getOwner()->getUID();
1651 1651
 	}
@@ -1679,7 +1679,7 @@  discard block
 block discarded – undo
1679 1679
 	 * @return string
1680 1680
 	 */
1681 1681
 	public function getPath($id) {
1682
-		$id = (int)$id;
1682
+		$id = (int) $id;
1683 1683
 		$manager = Filesystem::getMountManager();
1684 1684
 		$mounts = $manager->findIn($this->fakeRoot);
1685 1685
 		$mounts[] = $manager->find($this->fakeRoot);
@@ -1694,7 +1694,7 @@  discard block
 block discarded – undo
1694 1694
 				$cache = $mount->getStorage()->getCache();
1695 1695
 				$internalPath = $cache->getPathById($id);
1696 1696
 				if (is_string($internalPath)) {
1697
-					$fullPath = $mount->getMountPoint() . $internalPath;
1697
+					$fullPath = $mount->getMountPoint().$internalPath;
1698 1698
 					if (!is_null($path = $this->getRelativePath($fullPath))) {
1699 1699
 						return $path;
1700 1700
 					}
@@ -1818,7 +1818,7 @@  discard block
 block discarded – undo
1818 1818
 		$resultPath = '';
1819 1819
 		foreach ($parts as $part) {
1820 1820
 			if ($part) {
1821
-				$resultPath .= '/' . $part;
1821
+				$resultPath .= '/'.$part;
1822 1822
 				$result[] = $resultPath;
1823 1823
 			}
1824 1824
 		}
@@ -2074,16 +2074,16 @@  discard block
 block discarded – undo
2074 2074
 	public function getUidAndFilename($filename) {
2075 2075
 		$info = $this->getFileInfo($filename);
2076 2076
 		if (!$info instanceof \OCP\Files\FileInfo) {
2077
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2077
+			throw new NotFoundException($this->getAbsolutePath($filename).' not found');
2078 2078
 		}
2079 2079
 		$uid = $info->getOwner()->getUID();
2080 2080
 		if ($uid != \OCP\User::getUser()) {
2081 2081
 			Filesystem::initMountPoints($uid);
2082
-			$ownerView = new View('/' . $uid . '/files');
2082
+			$ownerView = new View('/'.$uid.'/files');
2083 2083
 			try {
2084 2084
 				$filename = $ownerView->getPath($info['fileid']);
2085 2085
 			} catch (NotFoundException $e) {
2086
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2086
+				throw new NotFoundException('File with id '.$info['fileid'].' not found for user '.$uid);
2087 2087
 			}
2088 2088
 		}
2089 2089
 		return [$uid, $filename];
@@ -2100,7 +2100,7 @@  discard block
 block discarded – undo
2100 2100
 		$directoryParts = array_filter($directoryParts);
2101 2101
 		foreach ($directoryParts as $key => $part) {
2102 2102
 			$currentPathElements = array_slice($directoryParts, 0, $key);
2103
-			$currentPath = '/' . implode('/', $currentPathElements);
2103
+			$currentPath = '/'.implode('/', $currentPathElements);
2104 2104
 			if ($this->is_file($currentPath)) {
2105 2105
 				return false;
2106 2106
 			}
Please login to merge, or discard this patch.
Indentation   +2027 added lines, -2027 removed lines patch added patch discarded remove patch
@@ -82,2031 +82,2031 @@
 block discarded – undo
82 82
  * \OC\Files\Storage\Storage object
83 83
  */
84 84
 class View {
85
-	/** @var string */
86
-	private $fakeRoot = '';
87
-
88
-	/**
89
-	 * @var \OCP\Lock\ILockingProvider
90
-	 */
91
-	protected $lockingProvider;
92
-
93
-	private $lockingEnabled;
94
-
95
-	private $updaterEnabled = true;
96
-
97
-	/** @var \OC\User\Manager */
98
-	private $userManager;
99
-
100
-	/** @var \OCP\ILogger */
101
-	private $logger;
102
-
103
-	/**
104
-	 * @param string $root
105
-	 * @throws \Exception If $root contains an invalid path
106
-	 */
107
-	public function __construct($root = '') {
108
-		if (is_null($root)) {
109
-			throw new \InvalidArgumentException('Root can\'t be null');
110
-		}
111
-		if (!Filesystem::isValidPath($root)) {
112
-			throw new \Exception();
113
-		}
114
-
115
-		$this->fakeRoot = $root;
116
-		$this->lockingProvider = \OC::$server->getLockingProvider();
117
-		$this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
-		$this->userManager = \OC::$server->getUserManager();
119
-		$this->logger = \OC::$server->getLogger();
120
-	}
121
-
122
-	public function getAbsolutePath($path = '/') {
123
-		if ($path === null) {
124
-			return null;
125
-		}
126
-		$this->assertPathLength($path);
127
-		if ($path === '') {
128
-			$path = '/';
129
-		}
130
-		if ($path[0] !== '/') {
131
-			$path = '/' . $path;
132
-		}
133
-		return $this->fakeRoot . $path;
134
-	}
135
-
136
-	/**
137
-	 * change the root to a fake root
138
-	 *
139
-	 * @param string $fakeRoot
140
-	 * @return boolean|null
141
-	 */
142
-	public function chroot($fakeRoot) {
143
-		if (!$fakeRoot == '') {
144
-			if ($fakeRoot[0] !== '/') {
145
-				$fakeRoot = '/' . $fakeRoot;
146
-			}
147
-		}
148
-		$this->fakeRoot = $fakeRoot;
149
-	}
150
-
151
-	/**
152
-	 * get the fake root
153
-	 *
154
-	 * @return string
155
-	 */
156
-	public function getRoot() {
157
-		return $this->fakeRoot;
158
-	}
159
-
160
-	/**
161
-	 * get path relative to the root of the view
162
-	 *
163
-	 * @param string $path
164
-	 * @return string
165
-	 */
166
-	public function getRelativePath($path) {
167
-		$this->assertPathLength($path);
168
-		if ($this->fakeRoot == '') {
169
-			return $path;
170
-		}
171
-
172
-		if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
-			return '/';
174
-		}
175
-
176
-		// missing slashes can cause wrong matches!
177
-		$root = rtrim($this->fakeRoot, '/') . '/';
178
-
179
-		if (strpos($path, $root) !== 0) {
180
-			return null;
181
-		} else {
182
-			$path = substr($path, strlen($this->fakeRoot));
183
-			if (strlen($path) === 0) {
184
-				return '/';
185
-			} else {
186
-				return $path;
187
-			}
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * get the mountpoint of the storage object for a path
193
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
194
-	 * returned mountpoint is relative to the absolute root of the filesystem
195
-	 * and does not take the chroot into account )
196
-	 *
197
-	 * @param string $path
198
-	 * @return string
199
-	 */
200
-	public function getMountPoint($path) {
201
-		return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
-	}
203
-
204
-	/**
205
-	 * get the mountpoint of the storage object for a path
206
-	 * ( note: because a storage is not always mounted inside the fakeroot, the
207
-	 * returned mountpoint is relative to the absolute root of the filesystem
208
-	 * and does not take the chroot into account )
209
-	 *
210
-	 * @param string $path
211
-	 * @return \OCP\Files\Mount\IMountPoint
212
-	 */
213
-	public function getMount($path) {
214
-		return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
-	}
216
-
217
-	/**
218
-	 * resolve a path to a storage and internal path
219
-	 *
220
-	 * @param string $path
221
-	 * @return array an array consisting of the storage and the internal path
222
-	 */
223
-	public function resolvePath($path) {
224
-		$a = $this->getAbsolutePath($path);
225
-		$p = Filesystem::normalizePath($a);
226
-		return Filesystem::resolvePath($p);
227
-	}
228
-
229
-	/**
230
-	 * return the path to a local version of the file
231
-	 * we need this because we can't know if a file is stored local or not from
232
-	 * outside the filestorage and for some purposes a local file is needed
233
-	 *
234
-	 * @param string $path
235
-	 * @return string
236
-	 */
237
-	public function getLocalFile($path) {
238
-		$parent = substr($path, 0, strrpos($path, '/'));
239
-		$path = $this->getAbsolutePath($path);
240
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
241
-		if (Filesystem::isValidPath($parent) and $storage) {
242
-			return $storage->getLocalFile($internalPath);
243
-		} else {
244
-			return null;
245
-		}
246
-	}
247
-
248
-	/**
249
-	 * @param string $path
250
-	 * @return string
251
-	 */
252
-	public function getLocalFolder($path) {
253
-		$parent = substr($path, 0, strrpos($path, '/'));
254
-		$path = $this->getAbsolutePath($path);
255
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
256
-		if (Filesystem::isValidPath($parent) and $storage) {
257
-			return $storage->getLocalFolder($internalPath);
258
-		} else {
259
-			return null;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * the following functions operate with arguments and return values identical
265
-	 * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
-	 * for \OC\Files\Storage\Storage via basicOperation().
267
-	 */
268
-	public function mkdir($path) {
269
-		return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
-	}
271
-
272
-	/**
273
-	 * remove mount point
274
-	 *
275
-	 * @param \OC\Files\Mount\MoveableMount $mount
276
-	 * @param string $path relative to data/
277
-	 * @return boolean
278
-	 */
279
-	protected function removeMount($mount, $path) {
280
-		if ($mount instanceof MoveableMount) {
281
-			// cut of /user/files to get the relative path to data/user/files
282
-			$pathParts = explode('/', $path, 4);
283
-			$relPath = '/' . $pathParts[3];
284
-			$this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
-			\OC_Hook::emit(
286
-				Filesystem::CLASSNAME, "umount",
287
-				array(Filesystem::signal_param_path => $relPath)
288
-			);
289
-			$this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
-			$result = $mount->removeMount();
291
-			$this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
-			if ($result) {
293
-				\OC_Hook::emit(
294
-					Filesystem::CLASSNAME, "post_umount",
295
-					array(Filesystem::signal_param_path => $relPath)
296
-				);
297
-			}
298
-			$this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
-			return $result;
300
-		} else {
301
-			// do not allow deleting the storage's root / the mount point
302
-			// because for some storages it might delete the whole contents
303
-			// but isn't supposed to work that way
304
-			return false;
305
-		}
306
-	}
307
-
308
-	public function disableCacheUpdate() {
309
-		$this->updaterEnabled = false;
310
-	}
311
-
312
-	public function enableCacheUpdate() {
313
-		$this->updaterEnabled = true;
314
-	}
315
-
316
-	protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
-		if ($this->updaterEnabled) {
318
-			if (is_null($time)) {
319
-				$time = time();
320
-			}
321
-			$storage->getUpdater()->update($internalPath, $time);
322
-		}
323
-	}
324
-
325
-	protected function removeUpdate(Storage $storage, $internalPath) {
326
-		if ($this->updaterEnabled) {
327
-			$storage->getUpdater()->remove($internalPath);
328
-		}
329
-	}
330
-
331
-	protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
-		if ($this->updaterEnabled) {
333
-			$targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
-		}
335
-	}
336
-
337
-	/**
338
-	 * @param string $path
339
-	 * @return bool|mixed
340
-	 */
341
-	public function rmdir($path) {
342
-		$absolutePath = $this->getAbsolutePath($path);
343
-		$mount = Filesystem::getMountManager()->find($absolutePath);
344
-		if ($mount->getInternalPath($absolutePath) === '') {
345
-			return $this->removeMount($mount, $absolutePath);
346
-		}
347
-		if ($this->is_dir($path)) {
348
-			$result = $this->basicOperation('rmdir', $path, array('delete'));
349
-		} else {
350
-			$result = false;
351
-		}
352
-
353
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
-			$storage = $mount->getStorage();
355
-			$internalPath = $mount->getInternalPath($absolutePath);
356
-			$storage->getUpdater()->remove($internalPath);
357
-		}
358
-		return $result;
359
-	}
360
-
361
-	/**
362
-	 * @param string $path
363
-	 * @return resource
364
-	 */
365
-	public function opendir($path) {
366
-		return $this->basicOperation('opendir', $path, array('read'));
367
-	}
368
-
369
-	/**
370
-	 * @param $handle
371
-	 * @return mixed
372
-	 */
373
-	public function readdir($handle) {
374
-		$fsLocal = new Storage\Local(array('datadir' => '/'));
375
-		return $fsLocal->readdir($handle);
376
-	}
377
-
378
-	/**
379
-	 * @param string $path
380
-	 * @return bool|mixed
381
-	 */
382
-	public function is_dir($path) {
383
-		if ($path == '/') {
384
-			return true;
385
-		}
386
-		return $this->basicOperation('is_dir', $path);
387
-	}
388
-
389
-	/**
390
-	 * @param string $path
391
-	 * @return bool|mixed
392
-	 */
393
-	public function is_file($path) {
394
-		if ($path == '/') {
395
-			return false;
396
-		}
397
-		return $this->basicOperation('is_file', $path);
398
-	}
399
-
400
-	/**
401
-	 * @param string $path
402
-	 * @return mixed
403
-	 */
404
-	public function stat($path) {
405
-		return $this->basicOperation('stat', $path);
406
-	}
407
-
408
-	/**
409
-	 * @param string $path
410
-	 * @return mixed
411
-	 */
412
-	public function filetype($path) {
413
-		return $this->basicOperation('filetype', $path);
414
-	}
415
-
416
-	/**
417
-	 * @param string $path
418
-	 * @return mixed
419
-	 */
420
-	public function filesize($path) {
421
-		return $this->basicOperation('filesize', $path);
422
-	}
423
-
424
-	/**
425
-	 * @param string $path
426
-	 * @return bool|mixed
427
-	 * @throws \OCP\Files\InvalidPathException
428
-	 */
429
-	public function readfile($path) {
430
-		$this->assertPathLength($path);
431
-		@ob_end_clean();
432
-		$handle = $this->fopen($path, 'rb');
433
-		if ($handle) {
434
-			$chunkSize = 8192; // 8 kB chunks
435
-			while (!feof($handle)) {
436
-				echo fread($handle, $chunkSize);
437
-				flush();
438
-			}
439
-			fclose($handle);
440
-			$size = $this->filesize($path);
441
-			return $size;
442
-		}
443
-		return false;
444
-	}
445
-
446
-	/**
447
-	 * @param string $path
448
-	 * @param int $from
449
-	 * @param int $to
450
-	 * @return bool|mixed
451
-	 * @throws \OCP\Files\InvalidPathException
452
-	 * @throws \OCP\Files\UnseekableException
453
-	 */
454
-	public function readfilePart($path, $from, $to) {
455
-		$this->assertPathLength($path);
456
-		@ob_end_clean();
457
-		$handle = $this->fopen($path, 'rb');
458
-		if ($handle) {
459
-			if (fseek($handle, $from) === 0) {
460
-				$chunkSize = 8192; // 8 kB chunks
461
-				$end = $to + 1;
462
-				while (!feof($handle) && ftell($handle) < $end) {
463
-					$len = $end - ftell($handle);
464
-					if ($len > $chunkSize) {
465
-						$len = $chunkSize;
466
-					}
467
-					echo fread($handle, $len);
468
-					flush();
469
-				}
470
-				$size = ftell($handle) - $from;
471
-				return $size;
472
-			}
473
-
474
-			throw new \OCP\Files\UnseekableException('fseek error');
475
-		}
476
-		return false;
477
-	}
478
-
479
-	/**
480
-	 * @param string $path
481
-	 * @return mixed
482
-	 */
483
-	public function isCreatable($path) {
484
-		return $this->basicOperation('isCreatable', $path);
485
-	}
486
-
487
-	/**
488
-	 * @param string $path
489
-	 * @return mixed
490
-	 */
491
-	public function isReadable($path) {
492
-		return $this->basicOperation('isReadable', $path);
493
-	}
494
-
495
-	/**
496
-	 * @param string $path
497
-	 * @return mixed
498
-	 */
499
-	public function isUpdatable($path) {
500
-		return $this->basicOperation('isUpdatable', $path);
501
-	}
502
-
503
-	/**
504
-	 * @param string $path
505
-	 * @return bool|mixed
506
-	 */
507
-	public function isDeletable($path) {
508
-		$absolutePath = $this->getAbsolutePath($path);
509
-		$mount = Filesystem::getMountManager()->find($absolutePath);
510
-		if ($mount->getInternalPath($absolutePath) === '') {
511
-			return $mount instanceof MoveableMount;
512
-		}
513
-		return $this->basicOperation('isDeletable', $path);
514
-	}
515
-
516
-	/**
517
-	 * @param string $path
518
-	 * @return mixed
519
-	 */
520
-	public function isSharable($path) {
521
-		return $this->basicOperation('isSharable', $path);
522
-	}
523
-
524
-	/**
525
-	 * @param string $path
526
-	 * @return bool|mixed
527
-	 */
528
-	public function file_exists($path) {
529
-		if ($path == '/') {
530
-			return true;
531
-		}
532
-		return $this->basicOperation('file_exists', $path);
533
-	}
534
-
535
-	/**
536
-	 * @param string $path
537
-	 * @return mixed
538
-	 */
539
-	public function filemtime($path) {
540
-		return $this->basicOperation('filemtime', $path);
541
-	}
542
-
543
-	/**
544
-	 * @param string $path
545
-	 * @param int|string $mtime
546
-	 * @return bool
547
-	 */
548
-	public function touch($path, $mtime = null) {
549
-		if (!is_null($mtime) and !is_numeric($mtime)) {
550
-			$mtime = strtotime($mtime);
551
-		}
552
-
553
-		$hooks = array('touch');
554
-
555
-		if (!$this->file_exists($path)) {
556
-			$hooks[] = 'create';
557
-			$hooks[] = 'write';
558
-		}
559
-		$result = $this->basicOperation('touch', $path, $hooks, $mtime);
560
-		if (!$result) {
561
-			// If create file fails because of permissions on external storage like SMB folders,
562
-			// check file exists and return false if not.
563
-			if (!$this->file_exists($path)) {
564
-				return false;
565
-			}
566
-			if (is_null($mtime)) {
567
-				$mtime = time();
568
-			}
569
-			//if native touch fails, we emulate it by changing the mtime in the cache
570
-			$this->putFileInfo($path, array('mtime' => floor($mtime)));
571
-		}
572
-		return true;
573
-	}
574
-
575
-	/**
576
-	 * @param string $path
577
-	 * @return mixed
578
-	 */
579
-	public function file_get_contents($path) {
580
-		return $this->basicOperation('file_get_contents', $path, array('read'));
581
-	}
582
-
583
-	/**
584
-	 * @param bool $exists
585
-	 * @param string $path
586
-	 * @param bool $run
587
-	 */
588
-	protected function emit_file_hooks_pre($exists, $path, &$run) {
589
-		if (!$exists) {
590
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
591
-				Filesystem::signal_param_path => $this->getHookPath($path),
592
-				Filesystem::signal_param_run => &$run,
593
-			));
594
-		} else {
595
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
596
-				Filesystem::signal_param_path => $this->getHookPath($path),
597
-				Filesystem::signal_param_run => &$run,
598
-			));
599
-		}
600
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
601
-			Filesystem::signal_param_path => $this->getHookPath($path),
602
-			Filesystem::signal_param_run => &$run,
603
-		));
604
-	}
605
-
606
-	/**
607
-	 * @param bool $exists
608
-	 * @param string $path
609
-	 */
610
-	protected function emit_file_hooks_post($exists, $path) {
611
-		if (!$exists) {
612
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
613
-				Filesystem::signal_param_path => $this->getHookPath($path),
614
-			));
615
-		} else {
616
-			\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
617
-				Filesystem::signal_param_path => $this->getHookPath($path),
618
-			));
619
-		}
620
-		\OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
621
-			Filesystem::signal_param_path => $this->getHookPath($path),
622
-		));
623
-	}
624
-
625
-	/**
626
-	 * @param string $path
627
-	 * @param mixed $data
628
-	 * @return bool|mixed
629
-	 * @throws \Exception
630
-	 */
631
-	public function file_put_contents($path, $data) {
632
-		if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
633
-			$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
634
-			if (Filesystem::isValidPath($path)
635
-				and !Filesystem::isFileBlacklisted($path)
636
-			) {
637
-				$path = $this->getRelativePath($absolutePath);
638
-
639
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
640
-
641
-				$exists = $this->file_exists($path);
642
-				$run = true;
643
-				if ($this->shouldEmitHooks($path)) {
644
-					$this->emit_file_hooks_pre($exists, $path, $run);
645
-				}
646
-				if (!$run) {
647
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
648
-					return false;
649
-				}
650
-
651
-				$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
652
-
653
-				/** @var \OC\Files\Storage\Storage $storage */
654
-				list($storage, $internalPath) = $this->resolvePath($path);
655
-				$target = $storage->fopen($internalPath, 'w');
656
-				if ($target) {
657
-					list (, $result) = \OC_Helper::streamCopy($data, $target);
658
-					fclose($target);
659
-					fclose($data);
660
-
661
-					$this->writeUpdate($storage, $internalPath);
662
-
663
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
664
-
665
-					if ($this->shouldEmitHooks($path) && $result !== false) {
666
-						$this->emit_file_hooks_post($exists, $path);
667
-					}
668
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
669
-					return $result;
670
-				} else {
671
-					$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
672
-					return false;
673
-				}
674
-			} else {
675
-				return false;
676
-			}
677
-		} else {
678
-			$hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
679
-			return $this->basicOperation('file_put_contents', $path, $hooks, $data);
680
-		}
681
-	}
682
-
683
-	/**
684
-	 * @param string $path
685
-	 * @return bool|mixed
686
-	 */
687
-	public function unlink($path) {
688
-		if ($path === '' || $path === '/') {
689
-			// do not allow deleting the root
690
-			return false;
691
-		}
692
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
693
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
694
-		$mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
695
-		if ($mount and $mount->getInternalPath($absolutePath) === '') {
696
-			return $this->removeMount($mount, $absolutePath);
697
-		}
698
-		if ($this->is_dir($path)) {
699
-			$result = $this->basicOperation('rmdir', $path, ['delete']);
700
-		} else {
701
-			$result = $this->basicOperation('unlink', $path, ['delete']);
702
-		}
703
-		if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
704
-			$storage = $mount->getStorage();
705
-			$internalPath = $mount->getInternalPath($absolutePath);
706
-			$storage->getUpdater()->remove($internalPath);
707
-			return true;
708
-		} else {
709
-			return $result;
710
-		}
711
-	}
712
-
713
-	/**
714
-	 * @param string $directory
715
-	 * @return bool|mixed
716
-	 */
717
-	public function deleteAll($directory) {
718
-		return $this->rmdir($directory);
719
-	}
720
-
721
-	/**
722
-	 * Rename/move a file or folder from the source path to target path.
723
-	 *
724
-	 * @param string $path1 source path
725
-	 * @param string $path2 target path
726
-	 *
727
-	 * @return bool|mixed
728
-	 */
729
-	public function rename($path1, $path2) {
730
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
731
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
732
-		$result = false;
733
-		if (
734
-			Filesystem::isValidPath($path2)
735
-			and Filesystem::isValidPath($path1)
736
-			and !Filesystem::isFileBlacklisted($path2)
737
-		) {
738
-			$path1 = $this->getRelativePath($absolutePath1);
739
-			$path2 = $this->getRelativePath($absolutePath2);
740
-			$exists = $this->file_exists($path2);
741
-
742
-			if ($path1 == null or $path2 == null) {
743
-				return false;
744
-			}
745
-
746
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
747
-			try {
748
-				$this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
749
-			} catch (LockedException $e) {
750
-				$this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
751
-				throw $e;
752
-			}
753
-
754
-			$run = true;
755
-			if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
756
-				// if it was a rename from a part file to a regular file it was a write and not a rename operation
757
-				$this->emit_file_hooks_pre($exists, $path2, $run);
758
-			} elseif ($this->shouldEmitHooks($path1)) {
759
-				\OC_Hook::emit(
760
-					Filesystem::CLASSNAME, Filesystem::signal_rename,
761
-					array(
762
-						Filesystem::signal_param_oldpath => $this->getHookPath($path1),
763
-						Filesystem::signal_param_newpath => $this->getHookPath($path2),
764
-						Filesystem::signal_param_run => &$run
765
-					)
766
-				);
767
-			}
768
-			if ($run) {
769
-				$this->verifyPath(dirname($path2), basename($path2));
770
-
771
-				$manager = Filesystem::getMountManager();
772
-				$mount1 = $this->getMount($path1);
773
-				$mount2 = $this->getMount($path2);
774
-				$storage1 = $mount1->getStorage();
775
-				$storage2 = $mount2->getStorage();
776
-				$internalPath1 = $mount1->getInternalPath($absolutePath1);
777
-				$internalPath2 = $mount2->getInternalPath($absolutePath2);
778
-
779
-				$this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
780
-				$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
781
-
782
-				if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
783
-					if ($this->canMove($mount1, $absolutePath2)) {
784
-						/**
785
-						 * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
786
-						 */
787
-						$sourceMountPoint = $mount1->getMountPoint();
788
-						$result = $mount1->moveMount($absolutePath2);
789
-						$manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
790
-					} else {
791
-						$result = false;
792
-					}
793
-					// moving a file/folder within the same mount point
794
-				} elseif ($storage1 === $storage2) {
795
-					if ($storage1) {
796
-						$result = $storage1->rename($internalPath1, $internalPath2);
797
-					} else {
798
-						$result = false;
799
-					}
800
-					// moving a file/folder between storages (from $storage1 to $storage2)
801
-				} else {
802
-					$result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
803
-				}
804
-
805
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
806
-					// if it was a rename from a part file to a regular file it was a write and not a rename operation
807
-
808
-					$this->writeUpdate($storage2, $internalPath2);
809
-				} else if ($result) {
810
-					if ($internalPath1 !== '') { // don't do a cache update for moved mounts
811
-						$this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
812
-					}
813
-				}
814
-
815
-				$this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
816
-				$this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
817
-
818
-				if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
819
-					if ($this->shouldEmitHooks()) {
820
-						$this->emit_file_hooks_post($exists, $path2);
821
-					}
822
-				} elseif ($result) {
823
-					if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
824
-						\OC_Hook::emit(
825
-							Filesystem::CLASSNAME,
826
-							Filesystem::signal_post_rename,
827
-							array(
828
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
829
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
830
-							)
831
-						);
832
-					}
833
-				}
834
-			}
835
-			$this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
836
-			$this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
837
-		}
838
-		return $result;
839
-	}
840
-
841
-	/**
842
-	 * Copy a file/folder from the source path to target path
843
-	 *
844
-	 * @param string $path1 source path
845
-	 * @param string $path2 target path
846
-	 * @param bool $preserveMtime whether to preserve mtime on the copy
847
-	 *
848
-	 * @return bool|mixed
849
-	 */
850
-	public function copy($path1, $path2, $preserveMtime = false) {
851
-		$absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
852
-		$absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
853
-		$result = false;
854
-		if (
855
-			Filesystem::isValidPath($path2)
856
-			and Filesystem::isValidPath($path1)
857
-			and !Filesystem::isFileBlacklisted($path2)
858
-		) {
859
-			$path1 = $this->getRelativePath($absolutePath1);
860
-			$path2 = $this->getRelativePath($absolutePath2);
861
-
862
-			if ($path1 == null or $path2 == null) {
863
-				return false;
864
-			}
865
-			$run = true;
866
-
867
-			$this->lockFile($path2, ILockingProvider::LOCK_SHARED);
868
-			$this->lockFile($path1, ILockingProvider::LOCK_SHARED);
869
-			$lockTypePath1 = ILockingProvider::LOCK_SHARED;
870
-			$lockTypePath2 = ILockingProvider::LOCK_SHARED;
871
-
872
-			try {
873
-
874
-				$exists = $this->file_exists($path2);
875
-				if ($this->shouldEmitHooks()) {
876
-					\OC_Hook::emit(
877
-						Filesystem::CLASSNAME,
878
-						Filesystem::signal_copy,
879
-						array(
880
-							Filesystem::signal_param_oldpath => $this->getHookPath($path1),
881
-							Filesystem::signal_param_newpath => $this->getHookPath($path2),
882
-							Filesystem::signal_param_run => &$run
883
-						)
884
-					);
885
-					$this->emit_file_hooks_pre($exists, $path2, $run);
886
-				}
887
-				if ($run) {
888
-					$mount1 = $this->getMount($path1);
889
-					$mount2 = $this->getMount($path2);
890
-					$storage1 = $mount1->getStorage();
891
-					$internalPath1 = $mount1->getInternalPath($absolutePath1);
892
-					$storage2 = $mount2->getStorage();
893
-					$internalPath2 = $mount2->getInternalPath($absolutePath2);
894
-
895
-					$this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
896
-					$lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
897
-
898
-					if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
899
-						if ($storage1) {
900
-							$result = $storage1->copy($internalPath1, $internalPath2);
901
-						} else {
902
-							$result = false;
903
-						}
904
-					} else {
905
-						$result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
906
-					}
907
-
908
-					$this->writeUpdate($storage2, $internalPath2);
909
-
910
-					$this->changeLock($path2, ILockingProvider::LOCK_SHARED);
911
-					$lockTypePath2 = ILockingProvider::LOCK_SHARED;
912
-
913
-					if ($this->shouldEmitHooks() && $result !== false) {
914
-						\OC_Hook::emit(
915
-							Filesystem::CLASSNAME,
916
-							Filesystem::signal_post_copy,
917
-							array(
918
-								Filesystem::signal_param_oldpath => $this->getHookPath($path1),
919
-								Filesystem::signal_param_newpath => $this->getHookPath($path2)
920
-							)
921
-						);
922
-						$this->emit_file_hooks_post($exists, $path2);
923
-					}
924
-
925
-				}
926
-			} catch (\Exception $e) {
927
-				$this->unlockFile($path2, $lockTypePath2);
928
-				$this->unlockFile($path1, $lockTypePath1);
929
-				throw $e;
930
-			}
931
-
932
-			$this->unlockFile($path2, $lockTypePath2);
933
-			$this->unlockFile($path1, $lockTypePath1);
934
-
935
-		}
936
-		return $result;
937
-	}
938
-
939
-	/**
940
-	 * @param string $path
941
-	 * @param string $mode 'r' or 'w'
942
-	 * @return resource
943
-	 */
944
-	public function fopen($path, $mode) {
945
-		$mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
946
-		$hooks = array();
947
-		switch ($mode) {
948
-			case 'r':
949
-				$hooks[] = 'read';
950
-				break;
951
-			case 'r+':
952
-			case 'w+':
953
-			case 'x+':
954
-			case 'a+':
955
-				$hooks[] = 'read';
956
-				$hooks[] = 'write';
957
-				break;
958
-			case 'w':
959
-			case 'x':
960
-			case 'a':
961
-				$hooks[] = 'write';
962
-				break;
963
-			default:
964
-				\OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
965
-		}
966
-
967
-		if ($mode !== 'r' && $mode !== 'w') {
968
-			\OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
969
-		}
970
-
971
-		return $this->basicOperation('fopen', $path, $hooks, $mode);
972
-	}
973
-
974
-	/**
975
-	 * @param string $path
976
-	 * @return bool|string
977
-	 * @throws \OCP\Files\InvalidPathException
978
-	 */
979
-	public function toTmpFile($path) {
980
-		$this->assertPathLength($path);
981
-		if (Filesystem::isValidPath($path)) {
982
-			$source = $this->fopen($path, 'r');
983
-			if ($source) {
984
-				$extension = pathinfo($path, PATHINFO_EXTENSION);
985
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
986
-				file_put_contents($tmpFile, $source);
987
-				return $tmpFile;
988
-			} else {
989
-				return false;
990
-			}
991
-		} else {
992
-			return false;
993
-		}
994
-	}
995
-
996
-	/**
997
-	 * @param string $tmpFile
998
-	 * @param string $path
999
-	 * @return bool|mixed
1000
-	 * @throws \OCP\Files\InvalidPathException
1001
-	 */
1002
-	public function fromTmpFile($tmpFile, $path) {
1003
-		$this->assertPathLength($path);
1004
-		if (Filesystem::isValidPath($path)) {
1005
-
1006
-			// Get directory that the file is going into
1007
-			$filePath = dirname($path);
1008
-
1009
-			// Create the directories if any
1010
-			if (!$this->file_exists($filePath)) {
1011
-				$result = $this->createParentDirectories($filePath);
1012
-				if ($result === false) {
1013
-					return false;
1014
-				}
1015
-			}
1016
-
1017
-			$source = fopen($tmpFile, 'r');
1018
-			if ($source) {
1019
-				$result = $this->file_put_contents($path, $source);
1020
-				// $this->file_put_contents() might have already closed
1021
-				// the resource, so we check it, before trying to close it
1022
-				// to avoid messages in the error log.
1023
-				if (is_resource($source)) {
1024
-					fclose($source);
1025
-				}
1026
-				unlink($tmpFile);
1027
-				return $result;
1028
-			} else {
1029
-				return false;
1030
-			}
1031
-		} else {
1032
-			return false;
1033
-		}
1034
-	}
1035
-
1036
-
1037
-	/**
1038
-	 * @param string $path
1039
-	 * @return mixed
1040
-	 * @throws \OCP\Files\InvalidPathException
1041
-	 */
1042
-	public function getMimeType($path) {
1043
-		$this->assertPathLength($path);
1044
-		return $this->basicOperation('getMimeType', $path);
1045
-	}
1046
-
1047
-	/**
1048
-	 * @param string $type
1049
-	 * @param string $path
1050
-	 * @param bool $raw
1051
-	 * @return bool|null|string
1052
-	 */
1053
-	public function hash($type, $path, $raw = false) {
1054
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1055
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1056
-		if (Filesystem::isValidPath($path)) {
1057
-			$path = $this->getRelativePath($absolutePath);
1058
-			if ($path == null) {
1059
-				return false;
1060
-			}
1061
-			if ($this->shouldEmitHooks($path)) {
1062
-				\OC_Hook::emit(
1063
-					Filesystem::CLASSNAME,
1064
-					Filesystem::signal_read,
1065
-					array(Filesystem::signal_param_path => $this->getHookPath($path))
1066
-				);
1067
-			}
1068
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1069
-			if ($storage) {
1070
-				$result = $storage->hash($type, $internalPath, $raw);
1071
-				return $result;
1072
-			}
1073
-		}
1074
-		return null;
1075
-	}
1076
-
1077
-	/**
1078
-	 * @param string $path
1079
-	 * @return mixed
1080
-	 * @throws \OCP\Files\InvalidPathException
1081
-	 */
1082
-	public function free_space($path = '/') {
1083
-		$this->assertPathLength($path);
1084
-		return $this->basicOperation('free_space', $path);
1085
-	}
1086
-
1087
-	/**
1088
-	 * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1089
-	 *
1090
-	 * @param string $operation
1091
-	 * @param string $path
1092
-	 * @param array $hooks (optional)
1093
-	 * @param mixed $extraParam (optional)
1094
-	 * @return mixed
1095
-	 * @throws \Exception
1096
-	 *
1097
-	 * This method takes requests for basic filesystem functions (e.g. reading & writing
1098
-	 * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1099
-	 * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1100
-	 */
1101
-	private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1102
-		$postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1103
-		$absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1104
-		if (Filesystem::isValidPath($path)
1105
-			and !Filesystem::isFileBlacklisted($path)
1106
-		) {
1107
-			$path = $this->getRelativePath($absolutePath);
1108
-			if ($path == null) {
1109
-				return false;
1110
-			}
1111
-
1112
-			if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1113
-				// always a shared lock during pre-hooks so the hook can read the file
1114
-				$this->lockFile($path, ILockingProvider::LOCK_SHARED);
1115
-			}
1116
-
1117
-			$run = $this->runHooks($hooks, $path);
1118
-			/** @var \OC\Files\Storage\Storage $storage */
1119
-			list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1120
-			if ($run and $storage) {
1121
-				if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1122
-					$this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1123
-				}
1124
-				try {
1125
-					if (!is_null($extraParam)) {
1126
-						$result = $storage->$operation($internalPath, $extraParam);
1127
-					} else {
1128
-						$result = $storage->$operation($internalPath);
1129
-					}
1130
-				} catch (\Exception $e) {
1131
-					if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1132
-						$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1133
-					} else if (in_array('read', $hooks)) {
1134
-						$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1135
-					}
1136
-					throw $e;
1137
-				}
1138
-
1139
-				if ($result && in_array('delete', $hooks) and $result) {
1140
-					$this->removeUpdate($storage, $internalPath);
1141
-				}
1142
-				if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1143
-					$this->writeUpdate($storage, $internalPath);
1144
-				}
1145
-				if ($result && in_array('touch', $hooks)) {
1146
-					$this->writeUpdate($storage, $internalPath, $extraParam);
1147
-				}
1148
-
1149
-				if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1150
-					$this->changeLock($path, ILockingProvider::LOCK_SHARED);
1151
-				}
1152
-
1153
-				$unlockLater = false;
1154
-				if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1155
-					$unlockLater = true;
1156
-					// make sure our unlocking callback will still be called if connection is aborted
1157
-					ignore_user_abort(true);
1158
-					$result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1159
-						if (in_array('write', $hooks)) {
1160
-							$this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1161
-						} else if (in_array('read', $hooks)) {
1162
-							$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1163
-						}
1164
-					});
1165
-				}
1166
-
1167
-				if ($this->shouldEmitHooks($path) && $result !== false) {
1168
-					if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1169
-						$this->runHooks($hooks, $path, true);
1170
-					}
1171
-				}
1172
-
1173
-				if (!$unlockLater
1174
-					&& (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1175
-				) {
1176
-					$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1177
-				}
1178
-				return $result;
1179
-			} else {
1180
-				$this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1181
-			}
1182
-		}
1183
-		return null;
1184
-	}
1185
-
1186
-	/**
1187
-	 * get the path relative to the default root for hook usage
1188
-	 *
1189
-	 * @param string $path
1190
-	 * @return string
1191
-	 */
1192
-	private function getHookPath($path) {
1193
-		if (!Filesystem::getView()) {
1194
-			return $path;
1195
-		}
1196
-		return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1197
-	}
1198
-
1199
-	private function shouldEmitHooks($path = '') {
1200
-		if ($path && Cache\Scanner::isPartialFile($path)) {
1201
-			return false;
1202
-		}
1203
-		if (!Filesystem::$loaded) {
1204
-			return false;
1205
-		}
1206
-		$defaultRoot = Filesystem::getRoot();
1207
-		if ($defaultRoot === null) {
1208
-			return false;
1209
-		}
1210
-		if ($this->fakeRoot === $defaultRoot) {
1211
-			return true;
1212
-		}
1213
-		$fullPath = $this->getAbsolutePath($path);
1214
-
1215
-		if ($fullPath === $defaultRoot) {
1216
-			return true;
1217
-		}
1218
-
1219
-		return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1220
-	}
1221
-
1222
-	/**
1223
-	 * @param string[] $hooks
1224
-	 * @param string $path
1225
-	 * @param bool $post
1226
-	 * @return bool
1227
-	 */
1228
-	private function runHooks($hooks, $path, $post = false) {
1229
-		$relativePath = $path;
1230
-		$path = $this->getHookPath($path);
1231
-		$prefix = ($post) ? 'post_' : '';
1232
-		$run = true;
1233
-		if ($this->shouldEmitHooks($relativePath)) {
1234
-			foreach ($hooks as $hook) {
1235
-				if ($hook != 'read') {
1236
-					\OC_Hook::emit(
1237
-						Filesystem::CLASSNAME,
1238
-						$prefix . $hook,
1239
-						array(
1240
-							Filesystem::signal_param_run => &$run,
1241
-							Filesystem::signal_param_path => $path
1242
-						)
1243
-					);
1244
-				} elseif (!$post) {
1245
-					\OC_Hook::emit(
1246
-						Filesystem::CLASSNAME,
1247
-						$prefix . $hook,
1248
-						array(
1249
-							Filesystem::signal_param_path => $path
1250
-						)
1251
-					);
1252
-				}
1253
-			}
1254
-		}
1255
-		return $run;
1256
-	}
1257
-
1258
-	/**
1259
-	 * check if a file or folder has been updated since $time
1260
-	 *
1261
-	 * @param string $path
1262
-	 * @param int $time
1263
-	 * @return bool
1264
-	 */
1265
-	public function hasUpdated($path, $time) {
1266
-		return $this->basicOperation('hasUpdated', $path, array(), $time);
1267
-	}
1268
-
1269
-	/**
1270
-	 * @param string $ownerId
1271
-	 * @return \OC\User\User
1272
-	 */
1273
-	private function getUserObjectForOwner($ownerId) {
1274
-		$owner = $this->userManager->get($ownerId);
1275
-		if ($owner instanceof IUser) {
1276
-			return $owner;
1277
-		} else {
1278
-			return new User($ownerId, null);
1279
-		}
1280
-	}
1281
-
1282
-	/**
1283
-	 * Get file info from cache
1284
-	 *
1285
-	 * If the file is not in cached it will be scanned
1286
-	 * If the file has changed on storage the cache will be updated
1287
-	 *
1288
-	 * @param \OC\Files\Storage\Storage $storage
1289
-	 * @param string $internalPath
1290
-	 * @param string $relativePath
1291
-	 * @return array|bool
1292
-	 */
1293
-	private function getCacheEntry($storage, $internalPath, $relativePath) {
1294
-		$cache = $storage->getCache($internalPath);
1295
-		$data = $cache->get($internalPath);
1296
-		$watcher = $storage->getWatcher($internalPath);
1297
-
1298
-		try {
1299
-			// if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1300
-			if (!$data || $data['size'] === -1) {
1301
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1302
-				if (!$storage->file_exists($internalPath)) {
1303
-					$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1304
-					return false;
1305
-				}
1306
-				$scanner = $storage->getScanner($internalPath);
1307
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1308
-				$data = $cache->get($internalPath);
1309
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1310
-			} else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1311
-				$this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1312
-				$watcher->update($internalPath, $data);
1313
-				$storage->getPropagator()->propagateChange($internalPath, time());
1314
-				$data = $cache->get($internalPath);
1315
-				$this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1316
-			}
1317
-		} catch (LockedException $e) {
1318
-			// if the file is locked we just use the old cache info
1319
-		}
1320
-
1321
-		return $data;
1322
-	}
1323
-
1324
-	/**
1325
-	 * get the filesystem info
1326
-	 *
1327
-	 * @param string $path
1328
-	 * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1329
-	 * 'ext' to add only ext storage mount point sizes. Defaults to true.
1330
-	 * defaults to true
1331
-	 * @return \OC\Files\FileInfo|false False if file does not exist
1332
-	 */
1333
-	public function getFileInfo($path, $includeMountPoints = true) {
1334
-		$this->assertPathLength($path);
1335
-		if (!Filesystem::isValidPath($path)) {
1336
-			return false;
1337
-		}
1338
-		if (Cache\Scanner::isPartialFile($path)) {
1339
-			return $this->getPartFileInfo($path);
1340
-		}
1341
-		$relativePath = $path;
1342
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1343
-
1344
-		$mount = Filesystem::getMountManager()->find($path);
1345
-		$storage = $mount->getStorage();
1346
-		$internalPath = $mount->getInternalPath($path);
1347
-		if ($storage) {
1348
-			$data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1349
-
1350
-			if (!$data instanceof ICacheEntry) {
1351
-				return false;
1352
-			}
1353
-
1354
-			if ($mount instanceof MoveableMount && $internalPath === '') {
1355
-				$data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1356
-			}
1357
-
1358
-			$owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1359
-			$info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1360
-
1361
-			if ($data and isset($data['fileid'])) {
1362
-				if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1363
-					//add the sizes of other mount points to the folder
1364
-					$extOnly = ($includeMountPoints === 'ext');
1365
-					$mounts = Filesystem::getMountManager()->findIn($path);
1366
-					$info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1367
-						$subStorage = $mount->getStorage();
1368
-						return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1369
-					}));
1370
-				}
1371
-			}
1372
-
1373
-			return $info;
1374
-		}
1375
-
1376
-		return false;
1377
-	}
1378
-
1379
-	/**
1380
-	 * get the content of a directory
1381
-	 *
1382
-	 * @param string $directory path under datadirectory
1383
-	 * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1384
-	 * @return FileInfo[]
1385
-	 */
1386
-	public function getDirectoryContent($directory, $mimetype_filter = '') {
1387
-		$this->assertPathLength($directory);
1388
-		if (!Filesystem::isValidPath($directory)) {
1389
-			return [];
1390
-		}
1391
-		$path = $this->getAbsolutePath($directory);
1392
-		$path = Filesystem::normalizePath($path);
1393
-		$mount = $this->getMount($directory);
1394
-		$storage = $mount->getStorage();
1395
-		$internalPath = $mount->getInternalPath($path);
1396
-		if ($storage) {
1397
-			$cache = $storage->getCache($internalPath);
1398
-			$user = \OC_User::getUser();
1399
-
1400
-			$data = $this->getCacheEntry($storage, $internalPath, $directory);
1401
-
1402
-			if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1403
-				return [];
1404
-			}
1405
-
1406
-			$folderId = $data['fileid'];
1407
-			$contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1408
-
1409
-			$sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1410
-			/**
1411
-			 * @var \OC\Files\FileInfo[] $files
1412
-			 */
1413
-			$files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1414
-				if ($sharingDisabled) {
1415
-					$content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1416
-				}
1417
-				$owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1418
-				return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1419
-			}, $contents);
1420
-
1421
-			//add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1422
-			$mounts = Filesystem::getMountManager()->findIn($path);
1423
-			$dirLength = strlen($path);
1424
-			foreach ($mounts as $mount) {
1425
-				$mountPoint = $mount->getMountPoint();
1426
-				$subStorage = $mount->getStorage();
1427
-				if ($subStorage) {
1428
-					$subCache = $subStorage->getCache('');
1429
-
1430
-					$rootEntry = $subCache->get('');
1431
-					if (!$rootEntry) {
1432
-						$subScanner = $subStorage->getScanner('');
1433
-						try {
1434
-							$subScanner->scanFile('');
1435
-						} catch (\OCP\Files\StorageNotAvailableException $e) {
1436
-							continue;
1437
-						} catch (\OCP\Files\StorageInvalidException $e) {
1438
-							continue;
1439
-						} catch (\Exception $e) {
1440
-							// sometimes when the storage is not available it can be any exception
1441
-							\OCP\Util::writeLog(
1442
-								'core',
1443
-								'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1444
-								get_class($e) . ': ' . $e->getMessage(),
1445
-								\OCP\Util::ERROR
1446
-							);
1447
-							continue;
1448
-						}
1449
-						$rootEntry = $subCache->get('');
1450
-					}
1451
-
1452
-					if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1453
-						$relativePath = trim(substr($mountPoint, $dirLength), '/');
1454
-						if ($pos = strpos($relativePath, '/')) {
1455
-							//mountpoint inside subfolder add size to the correct folder
1456
-							$entryName = substr($relativePath, 0, $pos);
1457
-							foreach ($files as &$entry) {
1458
-								if ($entry->getName() === $entryName) {
1459
-									$entry->addSubEntry($rootEntry, $mountPoint);
1460
-								}
1461
-							}
1462
-						} else { //mountpoint in this folder, add an entry for it
1463
-							$rootEntry['name'] = $relativePath;
1464
-							$rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1465
-							$permissions = $rootEntry['permissions'];
1466
-							// do not allow renaming/deleting the mount point if they are not shared files/folders
1467
-							// for shared files/folders we use the permissions given by the owner
1468
-							if ($mount instanceof MoveableMount) {
1469
-								$rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1470
-							} else {
1471
-								$rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1472
-							}
1473
-
1474
-							//remove any existing entry with the same name
1475
-							foreach ($files as $i => $file) {
1476
-								if ($file['name'] === $rootEntry['name']) {
1477
-									unset($files[$i]);
1478
-									break;
1479
-								}
1480
-							}
1481
-							$rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1482
-
1483
-							// if sharing was disabled for the user we remove the share permissions
1484
-							if (\OCP\Util::isSharingDisabledForUser()) {
1485
-								$rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1486
-							}
1487
-
1488
-							$owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1489
-							$files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1490
-						}
1491
-					}
1492
-				}
1493
-			}
1494
-
1495
-			if ($mimetype_filter) {
1496
-				$files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1497
-					if (strpos($mimetype_filter, '/')) {
1498
-						return $file->getMimetype() === $mimetype_filter;
1499
-					} else {
1500
-						return $file->getMimePart() === $mimetype_filter;
1501
-					}
1502
-				});
1503
-			}
1504
-
1505
-			return $files;
1506
-		} else {
1507
-			return [];
1508
-		}
1509
-	}
1510
-
1511
-	/**
1512
-	 * change file metadata
1513
-	 *
1514
-	 * @param string $path
1515
-	 * @param array|\OCP\Files\FileInfo $data
1516
-	 * @return int
1517
-	 *
1518
-	 * returns the fileid of the updated file
1519
-	 */
1520
-	public function putFileInfo($path, $data) {
1521
-		$this->assertPathLength($path);
1522
-		if ($data instanceof FileInfo) {
1523
-			$data = $data->getData();
1524
-		}
1525
-		$path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1526
-		/**
1527
-		 * @var \OC\Files\Storage\Storage $storage
1528
-		 * @var string $internalPath
1529
-		 */
1530
-		list($storage, $internalPath) = Filesystem::resolvePath($path);
1531
-		if ($storage) {
1532
-			$cache = $storage->getCache($path);
1533
-
1534
-			if (!$cache->inCache($internalPath)) {
1535
-				$scanner = $storage->getScanner($internalPath);
1536
-				$scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1537
-			}
1538
-
1539
-			return $cache->put($internalPath, $data);
1540
-		} else {
1541
-			return -1;
1542
-		}
1543
-	}
1544
-
1545
-	/**
1546
-	 * search for files with the name matching $query
1547
-	 *
1548
-	 * @param string $query
1549
-	 * @return FileInfo[]
1550
-	 */
1551
-	public function search($query) {
1552
-		return $this->searchCommon('search', array('%' . $query . '%'));
1553
-	}
1554
-
1555
-	/**
1556
-	 * search for files with the name matching $query
1557
-	 *
1558
-	 * @param string $query
1559
-	 * @return FileInfo[]
1560
-	 */
1561
-	public function searchRaw($query) {
1562
-		return $this->searchCommon('search', array($query));
1563
-	}
1564
-
1565
-	/**
1566
-	 * search for files by mimetype
1567
-	 *
1568
-	 * @param string $mimetype
1569
-	 * @return FileInfo[]
1570
-	 */
1571
-	public function searchByMime($mimetype) {
1572
-		return $this->searchCommon('searchByMime', array($mimetype));
1573
-	}
1574
-
1575
-	/**
1576
-	 * search for files by tag
1577
-	 *
1578
-	 * @param string|int $tag name or tag id
1579
-	 * @param string $userId owner of the tags
1580
-	 * @return FileInfo[]
1581
-	 */
1582
-	public function searchByTag($tag, $userId) {
1583
-		return $this->searchCommon('searchByTag', array($tag, $userId));
1584
-	}
1585
-
1586
-	/**
1587
-	 * @param string $method cache method
1588
-	 * @param array $args
1589
-	 * @return FileInfo[]
1590
-	 */
1591
-	private function searchCommon($method, $args) {
1592
-		$files = array();
1593
-		$rootLength = strlen($this->fakeRoot);
1594
-
1595
-		$mount = $this->getMount('');
1596
-		$mountPoint = $mount->getMountPoint();
1597
-		$storage = $mount->getStorage();
1598
-		if ($storage) {
1599
-			$cache = $storage->getCache('');
1600
-
1601
-			$results = call_user_func_array(array($cache, $method), $args);
1602
-			foreach ($results as $result) {
1603
-				if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1604
-					$internalPath = $result['path'];
1605
-					$path = $mountPoint . $result['path'];
1606
-					$result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
-					$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1608
-					$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1609
-				}
1610
-			}
1611
-
1612
-			$mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1613
-			foreach ($mounts as $mount) {
1614
-				$mountPoint = $mount->getMountPoint();
1615
-				$storage = $mount->getStorage();
1616
-				if ($storage) {
1617
-					$cache = $storage->getCache('');
1618
-
1619
-					$relativeMountPoint = substr($mountPoint, $rootLength);
1620
-					$results = call_user_func_array(array($cache, $method), $args);
1621
-					if ($results) {
1622
-						foreach ($results as $result) {
1623
-							$internalPath = $result['path'];
1624
-							$result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1625
-							$path = rtrim($mountPoint . $internalPath, '/');
1626
-							$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1627
-							$files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1628
-						}
1629
-					}
1630
-				}
1631
-			}
1632
-		}
1633
-		return $files;
1634
-	}
1635
-
1636
-	/**
1637
-	 * Get the owner for a file or folder
1638
-	 *
1639
-	 * @param string $path
1640
-	 * @return string the user id of the owner
1641
-	 * @throws NotFoundException
1642
-	 */
1643
-	public function getOwner($path) {
1644
-		$info = $this->getFileInfo($path);
1645
-		if (!$info) {
1646
-			throw new NotFoundException($path . ' not found while trying to get owner');
1647
-		}
1648
-		return $info->getOwner()->getUID();
1649
-	}
1650
-
1651
-	/**
1652
-	 * get the ETag for a file or folder
1653
-	 *
1654
-	 * @param string $path
1655
-	 * @return string
1656
-	 */
1657
-	public function getETag($path) {
1658
-		/**
1659
-		 * @var Storage\Storage $storage
1660
-		 * @var string $internalPath
1661
-		 */
1662
-		list($storage, $internalPath) = $this->resolvePath($path);
1663
-		if ($storage) {
1664
-			return $storage->getETag($internalPath);
1665
-		} else {
1666
-			return null;
1667
-		}
1668
-	}
1669
-
1670
-	/**
1671
-	 * Get the path of a file by id, relative to the view
1672
-	 *
1673
-	 * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1674
-	 *
1675
-	 * @param int $id
1676
-	 * @throws NotFoundException
1677
-	 * @return string
1678
-	 */
1679
-	public function getPath($id) {
1680
-		$id = (int)$id;
1681
-		$manager = Filesystem::getMountManager();
1682
-		$mounts = $manager->findIn($this->fakeRoot);
1683
-		$mounts[] = $manager->find($this->fakeRoot);
1684
-		// reverse the array so we start with the storage this view is in
1685
-		// which is the most likely to contain the file we're looking for
1686
-		$mounts = array_reverse($mounts);
1687
-		foreach ($mounts as $mount) {
1688
-			/**
1689
-			 * @var \OC\Files\Mount\MountPoint $mount
1690
-			 */
1691
-			if ($mount->getStorage()) {
1692
-				$cache = $mount->getStorage()->getCache();
1693
-				$internalPath = $cache->getPathById($id);
1694
-				if (is_string($internalPath)) {
1695
-					$fullPath = $mount->getMountPoint() . $internalPath;
1696
-					if (!is_null($path = $this->getRelativePath($fullPath))) {
1697
-						return $path;
1698
-					}
1699
-				}
1700
-			}
1701
-		}
1702
-		throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1703
-	}
1704
-
1705
-	/**
1706
-	 * @param string $path
1707
-	 * @throws InvalidPathException
1708
-	 */
1709
-	private function assertPathLength($path) {
1710
-		$maxLen = min(PHP_MAXPATHLEN, 4000);
1711
-		// Check for the string length - performed using isset() instead of strlen()
1712
-		// because isset() is about 5x-40x faster.
1713
-		if (isset($path[$maxLen])) {
1714
-			$pathLen = strlen($path);
1715
-			throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1716
-		}
1717
-	}
1718
-
1719
-	/**
1720
-	 * check if it is allowed to move a mount point to a given target.
1721
-	 * It is not allowed to move a mount point into a different mount point or
1722
-	 * into an already shared folder
1723
-	 *
1724
-	 * @param MoveableMount $mount1 moveable mount
1725
-	 * @param string $target absolute target path
1726
-	 * @return boolean
1727
-	 */
1728
-	private function canMove(MoveableMount $mount1, $target) {
1729
-
1730
-		list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1731
-		if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1732
-			\OCP\Util::writeLog('files',
1733
-				'It is not allowed to move one mount point into another one',
1734
-				\OCP\Util::DEBUG);
1735
-			return false;
1736
-		}
1737
-
1738
-		return $mount1->isTargetAllowed($target);
1739
-	}
1740
-
1741
-	/**
1742
-	 * Get a fileinfo object for files that are ignored in the cache (part files)
1743
-	 *
1744
-	 * @param string $path
1745
-	 * @return \OCP\Files\FileInfo
1746
-	 */
1747
-	private function getPartFileInfo($path) {
1748
-		$mount = $this->getMount($path);
1749
-		$storage = $mount->getStorage();
1750
-		$internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1751
-		$owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1752
-		return new FileInfo(
1753
-			$this->getAbsolutePath($path),
1754
-			$storage,
1755
-			$internalPath,
1756
-			[
1757
-				'fileid' => null,
1758
-				'mimetype' => $storage->getMimeType($internalPath),
1759
-				'name' => basename($path),
1760
-				'etag' => null,
1761
-				'size' => $storage->filesize($internalPath),
1762
-				'mtime' => $storage->filemtime($internalPath),
1763
-				'encrypted' => false,
1764
-				'permissions' => \OCP\Constants::PERMISSION_ALL
1765
-			],
1766
-			$mount,
1767
-			$owner
1768
-		);
1769
-	}
1770
-
1771
-	/**
1772
-	 * @param string $path
1773
-	 * @param string $fileName
1774
-	 * @throws InvalidPathException
1775
-	 */
1776
-	public function verifyPath($path, $fileName) {
1777
-		try {
1778
-			/** @type \OCP\Files\Storage $storage */
1779
-			list($storage, $internalPath) = $this->resolvePath($path);
1780
-			$storage->verifyPath($internalPath, $fileName);
1781
-		} catch (ReservedWordException $ex) {
1782
-			$l = \OC::$server->getL10N('lib');
1783
-			throw new InvalidPathException($l->t('File name is a reserved word'));
1784
-		} catch (InvalidCharacterInPathException $ex) {
1785
-			$l = \OC::$server->getL10N('lib');
1786
-			throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1787
-		} catch (FileNameTooLongException $ex) {
1788
-			$l = \OC::$server->getL10N('lib');
1789
-			throw new InvalidPathException($l->t('File name is too long'));
1790
-		} catch (InvalidDirectoryException $ex) {
1791
-			$l = \OC::$server->getL10N('lib');
1792
-			throw new InvalidPathException($l->t('Dot files are not allowed'));
1793
-		} catch (EmptyFileNameException $ex) {
1794
-			$l = \OC::$server->getL10N('lib');
1795
-			throw new InvalidPathException($l->t('Empty filename is not allowed'));
1796
-		}
1797
-	}
1798
-
1799
-	/**
1800
-	 * get all parent folders of $path
1801
-	 *
1802
-	 * @param string $path
1803
-	 * @return string[]
1804
-	 */
1805
-	private function getParents($path) {
1806
-		$path = trim($path, '/');
1807
-		if (!$path) {
1808
-			return [];
1809
-		}
1810
-
1811
-		$parts = explode('/', $path);
1812
-
1813
-		// remove the single file
1814
-		array_pop($parts);
1815
-		$result = array('/');
1816
-		$resultPath = '';
1817
-		foreach ($parts as $part) {
1818
-			if ($part) {
1819
-				$resultPath .= '/' . $part;
1820
-				$result[] = $resultPath;
1821
-			}
1822
-		}
1823
-		return $result;
1824
-	}
1825
-
1826
-	/**
1827
-	 * Returns the mount point for which to lock
1828
-	 *
1829
-	 * @param string $absolutePath absolute path
1830
-	 * @param bool $useParentMount true to return parent mount instead of whatever
1831
-	 * is mounted directly on the given path, false otherwise
1832
-	 * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1833
-	 */
1834
-	private function getMountForLock($absolutePath, $useParentMount = false) {
1835
-		$results = [];
1836
-		$mount = Filesystem::getMountManager()->find($absolutePath);
1837
-		if (!$mount) {
1838
-			return $results;
1839
-		}
1840
-
1841
-		if ($useParentMount) {
1842
-			// find out if something is mounted directly on the path
1843
-			$internalPath = $mount->getInternalPath($absolutePath);
1844
-			if ($internalPath === '') {
1845
-				// resolve the parent mount instead
1846
-				$mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1847
-			}
1848
-		}
1849
-
1850
-		return $mount;
1851
-	}
1852
-
1853
-	/**
1854
-	 * Lock the given path
1855
-	 *
1856
-	 * @param string $path the path of the file to lock, relative to the view
1857
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1858
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1859
-	 *
1860
-	 * @return bool False if the path is excluded from locking, true otherwise
1861
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1862
-	 */
1863
-	private function lockPath($path, $type, $lockMountPoint = false) {
1864
-		$absolutePath = $this->getAbsolutePath($path);
1865
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1866
-		if (!$this->shouldLockFile($absolutePath)) {
1867
-			return false;
1868
-		}
1869
-
1870
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1871
-		if ($mount) {
1872
-			try {
1873
-				$storage = $mount->getStorage();
1874
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1875
-					$storage->acquireLock(
1876
-						$mount->getInternalPath($absolutePath),
1877
-						$type,
1878
-						$this->lockingProvider
1879
-					);
1880
-				}
1881
-			} catch (\OCP\Lock\LockedException $e) {
1882
-				// rethrow with the a human-readable path
1883
-				throw new \OCP\Lock\LockedException(
1884
-					$this->getPathRelativeToFiles($absolutePath),
1885
-					$e
1886
-				);
1887
-			}
1888
-		}
1889
-
1890
-		return true;
1891
-	}
1892
-
1893
-	/**
1894
-	 * Change the lock type
1895
-	 *
1896
-	 * @param string $path the path of the file to lock, relative to the view
1897
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1898
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1899
-	 *
1900
-	 * @return bool False if the path is excluded from locking, true otherwise
1901
-	 * @throws \OCP\Lock\LockedException if the path is already locked
1902
-	 */
1903
-	public function changeLock($path, $type, $lockMountPoint = false) {
1904
-		$path = Filesystem::normalizePath($path);
1905
-		$absolutePath = $this->getAbsolutePath($path);
1906
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1907
-		if (!$this->shouldLockFile($absolutePath)) {
1908
-			return false;
1909
-		}
1910
-
1911
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1912
-		if ($mount) {
1913
-			try {
1914
-				$storage = $mount->getStorage();
1915
-				if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1916
-					$storage->changeLock(
1917
-						$mount->getInternalPath($absolutePath),
1918
-						$type,
1919
-						$this->lockingProvider
1920
-					);
1921
-				}
1922
-			} catch (\OCP\Lock\LockedException $e) {
1923
-				// rethrow with the a human-readable path
1924
-				throw new \OCP\Lock\LockedException(
1925
-					$this->getPathRelativeToFiles($absolutePath),
1926
-					$e
1927
-				);
1928
-			}
1929
-		}
1930
-
1931
-		return true;
1932
-	}
1933
-
1934
-	/**
1935
-	 * Unlock the given path
1936
-	 *
1937
-	 * @param string $path the path of the file to unlock, relative to the view
1938
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1939
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1940
-	 *
1941
-	 * @return bool False if the path is excluded from locking, true otherwise
1942
-	 */
1943
-	private function unlockPath($path, $type, $lockMountPoint = false) {
1944
-		$absolutePath = $this->getAbsolutePath($path);
1945
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1946
-		if (!$this->shouldLockFile($absolutePath)) {
1947
-			return false;
1948
-		}
1949
-
1950
-		$mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1951
-		if ($mount) {
1952
-			$storage = $mount->getStorage();
1953
-			if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1954
-				$storage->releaseLock(
1955
-					$mount->getInternalPath($absolutePath),
1956
-					$type,
1957
-					$this->lockingProvider
1958
-				);
1959
-			}
1960
-		}
1961
-
1962
-		return true;
1963
-	}
1964
-
1965
-	/**
1966
-	 * Lock a path and all its parents up to the root of the view
1967
-	 *
1968
-	 * @param string $path the path of the file to lock relative to the view
1969
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1970
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1971
-	 *
1972
-	 * @return bool False if the path is excluded from locking, true otherwise
1973
-	 */
1974
-	public function lockFile($path, $type, $lockMountPoint = false) {
1975
-		$absolutePath = $this->getAbsolutePath($path);
1976
-		$absolutePath = Filesystem::normalizePath($absolutePath);
1977
-		if (!$this->shouldLockFile($absolutePath)) {
1978
-			return false;
1979
-		}
1980
-
1981
-		$this->lockPath($path, $type, $lockMountPoint);
1982
-
1983
-		$parents = $this->getParents($path);
1984
-		foreach ($parents as $parent) {
1985
-			$this->lockPath($parent, ILockingProvider::LOCK_SHARED);
1986
-		}
1987
-
1988
-		return true;
1989
-	}
1990
-
1991
-	/**
1992
-	 * Unlock a path and all its parents up to the root of the view
1993
-	 *
1994
-	 * @param string $path the path of the file to lock relative to the view
1995
-	 * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1996
-	 * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1997
-	 *
1998
-	 * @return bool False if the path is excluded from locking, true otherwise
1999
-	 */
2000
-	public function unlockFile($path, $type, $lockMountPoint = false) {
2001
-		$absolutePath = $this->getAbsolutePath($path);
2002
-		$absolutePath = Filesystem::normalizePath($absolutePath);
2003
-		if (!$this->shouldLockFile($absolutePath)) {
2004
-			return false;
2005
-		}
2006
-
2007
-		$this->unlockPath($path, $type, $lockMountPoint);
2008
-
2009
-		$parents = $this->getParents($path);
2010
-		foreach ($parents as $parent) {
2011
-			$this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2012
-		}
2013
-
2014
-		return true;
2015
-	}
2016
-
2017
-	/**
2018
-	 * Only lock files in data/user/files/
2019
-	 *
2020
-	 * @param string $path Absolute path to the file/folder we try to (un)lock
2021
-	 * @return bool
2022
-	 */
2023
-	protected function shouldLockFile($path) {
2024
-		$path = Filesystem::normalizePath($path);
2025
-
2026
-		$pathSegments = explode('/', $path);
2027
-		if (isset($pathSegments[2])) {
2028
-			// E.g.: /username/files/path-to-file
2029
-			return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2030
-		}
2031
-
2032
-		return true;
2033
-	}
2034
-
2035
-	/**
2036
-	 * Shortens the given absolute path to be relative to
2037
-	 * "$user/files".
2038
-	 *
2039
-	 * @param string $absolutePath absolute path which is under "files"
2040
-	 *
2041
-	 * @return string path relative to "files" with trimmed slashes or null
2042
-	 * if the path was NOT relative to files
2043
-	 *
2044
-	 * @throws \InvalidArgumentException if the given path was not under "files"
2045
-	 * @since 8.1.0
2046
-	 */
2047
-	public function getPathRelativeToFiles($absolutePath) {
2048
-		$path = Filesystem::normalizePath($absolutePath);
2049
-		$parts = explode('/', trim($path, '/'), 3);
2050
-		// "$user", "files", "path/to/dir"
2051
-		if (!isset($parts[1]) || $parts[1] !== 'files') {
2052
-			$this->logger->error(
2053
-				'$absolutePath must be relative to "files", value is "%s"',
2054
-				[
2055
-					$absolutePath
2056
-				]
2057
-			);
2058
-			throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2059
-		}
2060
-		if (isset($parts[2])) {
2061
-			return $parts[2];
2062
-		}
2063
-		return '';
2064
-	}
2065
-
2066
-	/**
2067
-	 * @param string $filename
2068
-	 * @return array
2069
-	 * @throws \OC\User\NoUserException
2070
-	 * @throws NotFoundException
2071
-	 */
2072
-	public function getUidAndFilename($filename) {
2073
-		$info = $this->getFileInfo($filename);
2074
-		if (!$info instanceof \OCP\Files\FileInfo) {
2075
-			throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2076
-		}
2077
-		$uid = $info->getOwner()->getUID();
2078
-		if ($uid != \OCP\User::getUser()) {
2079
-			Filesystem::initMountPoints($uid);
2080
-			$ownerView = new View('/' . $uid . '/files');
2081
-			try {
2082
-				$filename = $ownerView->getPath($info['fileid']);
2083
-			} catch (NotFoundException $e) {
2084
-				throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2085
-			}
2086
-		}
2087
-		return [$uid, $filename];
2088
-	}
2089
-
2090
-	/**
2091
-	 * Creates parent non-existing folders
2092
-	 *
2093
-	 * @param string $filePath
2094
-	 * @return bool
2095
-	 */
2096
-	private function createParentDirectories($filePath) {
2097
-		$directoryParts = explode('/', $filePath);
2098
-		$directoryParts = array_filter($directoryParts);
2099
-		foreach ($directoryParts as $key => $part) {
2100
-			$currentPathElements = array_slice($directoryParts, 0, $key);
2101
-			$currentPath = '/' . implode('/', $currentPathElements);
2102
-			if ($this->is_file($currentPath)) {
2103
-				return false;
2104
-			}
2105
-			if (!$this->file_exists($currentPath)) {
2106
-				$this->mkdir($currentPath);
2107
-			}
2108
-		}
2109
-
2110
-		return true;
2111
-	}
85
+    /** @var string */
86
+    private $fakeRoot = '';
87
+
88
+    /**
89
+     * @var \OCP\Lock\ILockingProvider
90
+     */
91
+    protected $lockingProvider;
92
+
93
+    private $lockingEnabled;
94
+
95
+    private $updaterEnabled = true;
96
+
97
+    /** @var \OC\User\Manager */
98
+    private $userManager;
99
+
100
+    /** @var \OCP\ILogger */
101
+    private $logger;
102
+
103
+    /**
104
+     * @param string $root
105
+     * @throws \Exception If $root contains an invalid path
106
+     */
107
+    public function __construct($root = '') {
108
+        if (is_null($root)) {
109
+            throw new \InvalidArgumentException('Root can\'t be null');
110
+        }
111
+        if (!Filesystem::isValidPath($root)) {
112
+            throw new \Exception();
113
+        }
114
+
115
+        $this->fakeRoot = $root;
116
+        $this->lockingProvider = \OC::$server->getLockingProvider();
117
+        $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
118
+        $this->userManager = \OC::$server->getUserManager();
119
+        $this->logger = \OC::$server->getLogger();
120
+    }
121
+
122
+    public function getAbsolutePath($path = '/') {
123
+        if ($path === null) {
124
+            return null;
125
+        }
126
+        $this->assertPathLength($path);
127
+        if ($path === '') {
128
+            $path = '/';
129
+        }
130
+        if ($path[0] !== '/') {
131
+            $path = '/' . $path;
132
+        }
133
+        return $this->fakeRoot . $path;
134
+    }
135
+
136
+    /**
137
+     * change the root to a fake root
138
+     *
139
+     * @param string $fakeRoot
140
+     * @return boolean|null
141
+     */
142
+    public function chroot($fakeRoot) {
143
+        if (!$fakeRoot == '') {
144
+            if ($fakeRoot[0] !== '/') {
145
+                $fakeRoot = '/' . $fakeRoot;
146
+            }
147
+        }
148
+        $this->fakeRoot = $fakeRoot;
149
+    }
150
+
151
+    /**
152
+     * get the fake root
153
+     *
154
+     * @return string
155
+     */
156
+    public function getRoot() {
157
+        return $this->fakeRoot;
158
+    }
159
+
160
+    /**
161
+     * get path relative to the root of the view
162
+     *
163
+     * @param string $path
164
+     * @return string
165
+     */
166
+    public function getRelativePath($path) {
167
+        $this->assertPathLength($path);
168
+        if ($this->fakeRoot == '') {
169
+            return $path;
170
+        }
171
+
172
+        if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
173
+            return '/';
174
+        }
175
+
176
+        // missing slashes can cause wrong matches!
177
+        $root = rtrim($this->fakeRoot, '/') . '/';
178
+
179
+        if (strpos($path, $root) !== 0) {
180
+            return null;
181
+        } else {
182
+            $path = substr($path, strlen($this->fakeRoot));
183
+            if (strlen($path) === 0) {
184
+                return '/';
185
+            } else {
186
+                return $path;
187
+            }
188
+        }
189
+    }
190
+
191
+    /**
192
+     * get the mountpoint of the storage object for a path
193
+     * ( note: because a storage is not always mounted inside the fakeroot, the
194
+     * returned mountpoint is relative to the absolute root of the filesystem
195
+     * and does not take the chroot into account )
196
+     *
197
+     * @param string $path
198
+     * @return string
199
+     */
200
+    public function getMountPoint($path) {
201
+        return Filesystem::getMountPoint($this->getAbsolutePath($path));
202
+    }
203
+
204
+    /**
205
+     * get the mountpoint of the storage object for a path
206
+     * ( note: because a storage is not always mounted inside the fakeroot, the
207
+     * returned mountpoint is relative to the absolute root of the filesystem
208
+     * and does not take the chroot into account )
209
+     *
210
+     * @param string $path
211
+     * @return \OCP\Files\Mount\IMountPoint
212
+     */
213
+    public function getMount($path) {
214
+        return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
215
+    }
216
+
217
+    /**
218
+     * resolve a path to a storage and internal path
219
+     *
220
+     * @param string $path
221
+     * @return array an array consisting of the storage and the internal path
222
+     */
223
+    public function resolvePath($path) {
224
+        $a = $this->getAbsolutePath($path);
225
+        $p = Filesystem::normalizePath($a);
226
+        return Filesystem::resolvePath($p);
227
+    }
228
+
229
+    /**
230
+     * return the path to a local version of the file
231
+     * we need this because we can't know if a file is stored local or not from
232
+     * outside the filestorage and for some purposes a local file is needed
233
+     *
234
+     * @param string $path
235
+     * @return string
236
+     */
237
+    public function getLocalFile($path) {
238
+        $parent = substr($path, 0, strrpos($path, '/'));
239
+        $path = $this->getAbsolutePath($path);
240
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
241
+        if (Filesystem::isValidPath($parent) and $storage) {
242
+            return $storage->getLocalFile($internalPath);
243
+        } else {
244
+            return null;
245
+        }
246
+    }
247
+
248
+    /**
249
+     * @param string $path
250
+     * @return string
251
+     */
252
+    public function getLocalFolder($path) {
253
+        $parent = substr($path, 0, strrpos($path, '/'));
254
+        $path = $this->getAbsolutePath($path);
255
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
256
+        if (Filesystem::isValidPath($parent) and $storage) {
257
+            return $storage->getLocalFolder($internalPath);
258
+        } else {
259
+            return null;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * the following functions operate with arguments and return values identical
265
+     * to those of their PHP built-in equivalents. Mostly they are merely wrappers
266
+     * for \OC\Files\Storage\Storage via basicOperation().
267
+     */
268
+    public function mkdir($path) {
269
+        return $this->basicOperation('mkdir', $path, array('create', 'write'));
270
+    }
271
+
272
+    /**
273
+     * remove mount point
274
+     *
275
+     * @param \OC\Files\Mount\MoveableMount $mount
276
+     * @param string $path relative to data/
277
+     * @return boolean
278
+     */
279
+    protected function removeMount($mount, $path) {
280
+        if ($mount instanceof MoveableMount) {
281
+            // cut of /user/files to get the relative path to data/user/files
282
+            $pathParts = explode('/', $path, 4);
283
+            $relPath = '/' . $pathParts[3];
284
+            $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
285
+            \OC_Hook::emit(
286
+                Filesystem::CLASSNAME, "umount",
287
+                array(Filesystem::signal_param_path => $relPath)
288
+            );
289
+            $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
290
+            $result = $mount->removeMount();
291
+            $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
292
+            if ($result) {
293
+                \OC_Hook::emit(
294
+                    Filesystem::CLASSNAME, "post_umount",
295
+                    array(Filesystem::signal_param_path => $relPath)
296
+                );
297
+            }
298
+            $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
299
+            return $result;
300
+        } else {
301
+            // do not allow deleting the storage's root / the mount point
302
+            // because for some storages it might delete the whole contents
303
+            // but isn't supposed to work that way
304
+            return false;
305
+        }
306
+    }
307
+
308
+    public function disableCacheUpdate() {
309
+        $this->updaterEnabled = false;
310
+    }
311
+
312
+    public function enableCacheUpdate() {
313
+        $this->updaterEnabled = true;
314
+    }
315
+
316
+    protected function writeUpdate(Storage $storage, $internalPath, $time = null) {
317
+        if ($this->updaterEnabled) {
318
+            if (is_null($time)) {
319
+                $time = time();
320
+            }
321
+            $storage->getUpdater()->update($internalPath, $time);
322
+        }
323
+    }
324
+
325
+    protected function removeUpdate(Storage $storage, $internalPath) {
326
+        if ($this->updaterEnabled) {
327
+            $storage->getUpdater()->remove($internalPath);
328
+        }
329
+    }
330
+
331
+    protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, $sourceInternalPath, $targetInternalPath) {
332
+        if ($this->updaterEnabled) {
333
+            $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
334
+        }
335
+    }
336
+
337
+    /**
338
+     * @param string $path
339
+     * @return bool|mixed
340
+     */
341
+    public function rmdir($path) {
342
+        $absolutePath = $this->getAbsolutePath($path);
343
+        $mount = Filesystem::getMountManager()->find($absolutePath);
344
+        if ($mount->getInternalPath($absolutePath) === '') {
345
+            return $this->removeMount($mount, $absolutePath);
346
+        }
347
+        if ($this->is_dir($path)) {
348
+            $result = $this->basicOperation('rmdir', $path, array('delete'));
349
+        } else {
350
+            $result = false;
351
+        }
352
+
353
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
354
+            $storage = $mount->getStorage();
355
+            $internalPath = $mount->getInternalPath($absolutePath);
356
+            $storage->getUpdater()->remove($internalPath);
357
+        }
358
+        return $result;
359
+    }
360
+
361
+    /**
362
+     * @param string $path
363
+     * @return resource
364
+     */
365
+    public function opendir($path) {
366
+        return $this->basicOperation('opendir', $path, array('read'));
367
+    }
368
+
369
+    /**
370
+     * @param $handle
371
+     * @return mixed
372
+     */
373
+    public function readdir($handle) {
374
+        $fsLocal = new Storage\Local(array('datadir' => '/'));
375
+        return $fsLocal->readdir($handle);
376
+    }
377
+
378
+    /**
379
+     * @param string $path
380
+     * @return bool|mixed
381
+     */
382
+    public function is_dir($path) {
383
+        if ($path == '/') {
384
+            return true;
385
+        }
386
+        return $this->basicOperation('is_dir', $path);
387
+    }
388
+
389
+    /**
390
+     * @param string $path
391
+     * @return bool|mixed
392
+     */
393
+    public function is_file($path) {
394
+        if ($path == '/') {
395
+            return false;
396
+        }
397
+        return $this->basicOperation('is_file', $path);
398
+    }
399
+
400
+    /**
401
+     * @param string $path
402
+     * @return mixed
403
+     */
404
+    public function stat($path) {
405
+        return $this->basicOperation('stat', $path);
406
+    }
407
+
408
+    /**
409
+     * @param string $path
410
+     * @return mixed
411
+     */
412
+    public function filetype($path) {
413
+        return $this->basicOperation('filetype', $path);
414
+    }
415
+
416
+    /**
417
+     * @param string $path
418
+     * @return mixed
419
+     */
420
+    public function filesize($path) {
421
+        return $this->basicOperation('filesize', $path);
422
+    }
423
+
424
+    /**
425
+     * @param string $path
426
+     * @return bool|mixed
427
+     * @throws \OCP\Files\InvalidPathException
428
+     */
429
+    public function readfile($path) {
430
+        $this->assertPathLength($path);
431
+        @ob_end_clean();
432
+        $handle = $this->fopen($path, 'rb');
433
+        if ($handle) {
434
+            $chunkSize = 8192; // 8 kB chunks
435
+            while (!feof($handle)) {
436
+                echo fread($handle, $chunkSize);
437
+                flush();
438
+            }
439
+            fclose($handle);
440
+            $size = $this->filesize($path);
441
+            return $size;
442
+        }
443
+        return false;
444
+    }
445
+
446
+    /**
447
+     * @param string $path
448
+     * @param int $from
449
+     * @param int $to
450
+     * @return bool|mixed
451
+     * @throws \OCP\Files\InvalidPathException
452
+     * @throws \OCP\Files\UnseekableException
453
+     */
454
+    public function readfilePart($path, $from, $to) {
455
+        $this->assertPathLength($path);
456
+        @ob_end_clean();
457
+        $handle = $this->fopen($path, 'rb');
458
+        if ($handle) {
459
+            if (fseek($handle, $from) === 0) {
460
+                $chunkSize = 8192; // 8 kB chunks
461
+                $end = $to + 1;
462
+                while (!feof($handle) && ftell($handle) < $end) {
463
+                    $len = $end - ftell($handle);
464
+                    if ($len > $chunkSize) {
465
+                        $len = $chunkSize;
466
+                    }
467
+                    echo fread($handle, $len);
468
+                    flush();
469
+                }
470
+                $size = ftell($handle) - $from;
471
+                return $size;
472
+            }
473
+
474
+            throw new \OCP\Files\UnseekableException('fseek error');
475
+        }
476
+        return false;
477
+    }
478
+
479
+    /**
480
+     * @param string $path
481
+     * @return mixed
482
+     */
483
+    public function isCreatable($path) {
484
+        return $this->basicOperation('isCreatable', $path);
485
+    }
486
+
487
+    /**
488
+     * @param string $path
489
+     * @return mixed
490
+     */
491
+    public function isReadable($path) {
492
+        return $this->basicOperation('isReadable', $path);
493
+    }
494
+
495
+    /**
496
+     * @param string $path
497
+     * @return mixed
498
+     */
499
+    public function isUpdatable($path) {
500
+        return $this->basicOperation('isUpdatable', $path);
501
+    }
502
+
503
+    /**
504
+     * @param string $path
505
+     * @return bool|mixed
506
+     */
507
+    public function isDeletable($path) {
508
+        $absolutePath = $this->getAbsolutePath($path);
509
+        $mount = Filesystem::getMountManager()->find($absolutePath);
510
+        if ($mount->getInternalPath($absolutePath) === '') {
511
+            return $mount instanceof MoveableMount;
512
+        }
513
+        return $this->basicOperation('isDeletable', $path);
514
+    }
515
+
516
+    /**
517
+     * @param string $path
518
+     * @return mixed
519
+     */
520
+    public function isSharable($path) {
521
+        return $this->basicOperation('isSharable', $path);
522
+    }
523
+
524
+    /**
525
+     * @param string $path
526
+     * @return bool|mixed
527
+     */
528
+    public function file_exists($path) {
529
+        if ($path == '/') {
530
+            return true;
531
+        }
532
+        return $this->basicOperation('file_exists', $path);
533
+    }
534
+
535
+    /**
536
+     * @param string $path
537
+     * @return mixed
538
+     */
539
+    public function filemtime($path) {
540
+        return $this->basicOperation('filemtime', $path);
541
+    }
542
+
543
+    /**
544
+     * @param string $path
545
+     * @param int|string $mtime
546
+     * @return bool
547
+     */
548
+    public function touch($path, $mtime = null) {
549
+        if (!is_null($mtime) and !is_numeric($mtime)) {
550
+            $mtime = strtotime($mtime);
551
+        }
552
+
553
+        $hooks = array('touch');
554
+
555
+        if (!$this->file_exists($path)) {
556
+            $hooks[] = 'create';
557
+            $hooks[] = 'write';
558
+        }
559
+        $result = $this->basicOperation('touch', $path, $hooks, $mtime);
560
+        if (!$result) {
561
+            // If create file fails because of permissions on external storage like SMB folders,
562
+            // check file exists and return false if not.
563
+            if (!$this->file_exists($path)) {
564
+                return false;
565
+            }
566
+            if (is_null($mtime)) {
567
+                $mtime = time();
568
+            }
569
+            //if native touch fails, we emulate it by changing the mtime in the cache
570
+            $this->putFileInfo($path, array('mtime' => floor($mtime)));
571
+        }
572
+        return true;
573
+    }
574
+
575
+    /**
576
+     * @param string $path
577
+     * @return mixed
578
+     */
579
+    public function file_get_contents($path) {
580
+        return $this->basicOperation('file_get_contents', $path, array('read'));
581
+    }
582
+
583
+    /**
584
+     * @param bool $exists
585
+     * @param string $path
586
+     * @param bool $run
587
+     */
588
+    protected function emit_file_hooks_pre($exists, $path, &$run) {
589
+        if (!$exists) {
590
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, array(
591
+                Filesystem::signal_param_path => $this->getHookPath($path),
592
+                Filesystem::signal_param_run => &$run,
593
+            ));
594
+        } else {
595
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, array(
596
+                Filesystem::signal_param_path => $this->getHookPath($path),
597
+                Filesystem::signal_param_run => &$run,
598
+            ));
599
+        }
600
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, array(
601
+            Filesystem::signal_param_path => $this->getHookPath($path),
602
+            Filesystem::signal_param_run => &$run,
603
+        ));
604
+    }
605
+
606
+    /**
607
+     * @param bool $exists
608
+     * @param string $path
609
+     */
610
+    protected function emit_file_hooks_post($exists, $path) {
611
+        if (!$exists) {
612
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, array(
613
+                Filesystem::signal_param_path => $this->getHookPath($path),
614
+            ));
615
+        } else {
616
+            \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, array(
617
+                Filesystem::signal_param_path => $this->getHookPath($path),
618
+            ));
619
+        }
620
+        \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, array(
621
+            Filesystem::signal_param_path => $this->getHookPath($path),
622
+        ));
623
+    }
624
+
625
+    /**
626
+     * @param string $path
627
+     * @param mixed $data
628
+     * @return bool|mixed
629
+     * @throws \Exception
630
+     */
631
+    public function file_put_contents($path, $data) {
632
+        if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
633
+            $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
634
+            if (Filesystem::isValidPath($path)
635
+                and !Filesystem::isFileBlacklisted($path)
636
+            ) {
637
+                $path = $this->getRelativePath($absolutePath);
638
+
639
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
640
+
641
+                $exists = $this->file_exists($path);
642
+                $run = true;
643
+                if ($this->shouldEmitHooks($path)) {
644
+                    $this->emit_file_hooks_pre($exists, $path, $run);
645
+                }
646
+                if (!$run) {
647
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
648
+                    return false;
649
+                }
650
+
651
+                $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
652
+
653
+                /** @var \OC\Files\Storage\Storage $storage */
654
+                list($storage, $internalPath) = $this->resolvePath($path);
655
+                $target = $storage->fopen($internalPath, 'w');
656
+                if ($target) {
657
+                    list (, $result) = \OC_Helper::streamCopy($data, $target);
658
+                    fclose($target);
659
+                    fclose($data);
660
+
661
+                    $this->writeUpdate($storage, $internalPath);
662
+
663
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
664
+
665
+                    if ($this->shouldEmitHooks($path) && $result !== false) {
666
+                        $this->emit_file_hooks_post($exists, $path);
667
+                    }
668
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
669
+                    return $result;
670
+                } else {
671
+                    $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
672
+                    return false;
673
+                }
674
+            } else {
675
+                return false;
676
+            }
677
+        } else {
678
+            $hooks = ($this->file_exists($path)) ? array('update', 'write') : array('create', 'write');
679
+            return $this->basicOperation('file_put_contents', $path, $hooks, $data);
680
+        }
681
+    }
682
+
683
+    /**
684
+     * @param string $path
685
+     * @return bool|mixed
686
+     */
687
+    public function unlink($path) {
688
+        if ($path === '' || $path === '/') {
689
+            // do not allow deleting the root
690
+            return false;
691
+        }
692
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
693
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
694
+        $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
695
+        if ($mount and $mount->getInternalPath($absolutePath) === '') {
696
+            return $this->removeMount($mount, $absolutePath);
697
+        }
698
+        if ($this->is_dir($path)) {
699
+            $result = $this->basicOperation('rmdir', $path, ['delete']);
700
+        } else {
701
+            $result = $this->basicOperation('unlink', $path, ['delete']);
702
+        }
703
+        if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
704
+            $storage = $mount->getStorage();
705
+            $internalPath = $mount->getInternalPath($absolutePath);
706
+            $storage->getUpdater()->remove($internalPath);
707
+            return true;
708
+        } else {
709
+            return $result;
710
+        }
711
+    }
712
+
713
+    /**
714
+     * @param string $directory
715
+     * @return bool|mixed
716
+     */
717
+    public function deleteAll($directory) {
718
+        return $this->rmdir($directory);
719
+    }
720
+
721
+    /**
722
+     * Rename/move a file or folder from the source path to target path.
723
+     *
724
+     * @param string $path1 source path
725
+     * @param string $path2 target path
726
+     *
727
+     * @return bool|mixed
728
+     */
729
+    public function rename($path1, $path2) {
730
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
731
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
732
+        $result = false;
733
+        if (
734
+            Filesystem::isValidPath($path2)
735
+            and Filesystem::isValidPath($path1)
736
+            and !Filesystem::isFileBlacklisted($path2)
737
+        ) {
738
+            $path1 = $this->getRelativePath($absolutePath1);
739
+            $path2 = $this->getRelativePath($absolutePath2);
740
+            $exists = $this->file_exists($path2);
741
+
742
+            if ($path1 == null or $path2 == null) {
743
+                return false;
744
+            }
745
+
746
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED, true);
747
+            try {
748
+                $this->lockFile($path2, ILockingProvider::LOCK_SHARED, true);
749
+            } catch (LockedException $e) {
750
+                $this->unlockFile($path1, ILockingProvider::LOCK_SHARED);
751
+                throw $e;
752
+            }
753
+
754
+            $run = true;
755
+            if ($this->shouldEmitHooks($path1) && (Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2))) {
756
+                // if it was a rename from a part file to a regular file it was a write and not a rename operation
757
+                $this->emit_file_hooks_pre($exists, $path2, $run);
758
+            } elseif ($this->shouldEmitHooks($path1)) {
759
+                \OC_Hook::emit(
760
+                    Filesystem::CLASSNAME, Filesystem::signal_rename,
761
+                    array(
762
+                        Filesystem::signal_param_oldpath => $this->getHookPath($path1),
763
+                        Filesystem::signal_param_newpath => $this->getHookPath($path2),
764
+                        Filesystem::signal_param_run => &$run
765
+                    )
766
+                );
767
+            }
768
+            if ($run) {
769
+                $this->verifyPath(dirname($path2), basename($path2));
770
+
771
+                $manager = Filesystem::getMountManager();
772
+                $mount1 = $this->getMount($path1);
773
+                $mount2 = $this->getMount($path2);
774
+                $storage1 = $mount1->getStorage();
775
+                $storage2 = $mount2->getStorage();
776
+                $internalPath1 = $mount1->getInternalPath($absolutePath1);
777
+                $internalPath2 = $mount2->getInternalPath($absolutePath2);
778
+
779
+                $this->changeLock($path1, ILockingProvider::LOCK_EXCLUSIVE, true);
780
+                $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE, true);
781
+
782
+                if ($internalPath1 === '' and $mount1 instanceof MoveableMount) {
783
+                    if ($this->canMove($mount1, $absolutePath2)) {
784
+                        /**
785
+                         * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
786
+                         */
787
+                        $sourceMountPoint = $mount1->getMountPoint();
788
+                        $result = $mount1->moveMount($absolutePath2);
789
+                        $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
790
+                    } else {
791
+                        $result = false;
792
+                    }
793
+                    // moving a file/folder within the same mount point
794
+                } elseif ($storage1 === $storage2) {
795
+                    if ($storage1) {
796
+                        $result = $storage1->rename($internalPath1, $internalPath2);
797
+                    } else {
798
+                        $result = false;
799
+                    }
800
+                    // moving a file/folder between storages (from $storage1 to $storage2)
801
+                } else {
802
+                    $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
803
+                }
804
+
805
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
806
+                    // if it was a rename from a part file to a regular file it was a write and not a rename operation
807
+
808
+                    $this->writeUpdate($storage2, $internalPath2);
809
+                } else if ($result) {
810
+                    if ($internalPath1 !== '') { // don't do a cache update for moved mounts
811
+                        $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
812
+                    }
813
+                }
814
+
815
+                $this->changeLock($path1, ILockingProvider::LOCK_SHARED, true);
816
+                $this->changeLock($path2, ILockingProvider::LOCK_SHARED, true);
817
+
818
+                if ((Cache\Scanner::isPartialFile($path1) && !Cache\Scanner::isPartialFile($path2)) && $result !== false) {
819
+                    if ($this->shouldEmitHooks()) {
820
+                        $this->emit_file_hooks_post($exists, $path2);
821
+                    }
822
+                } elseif ($result) {
823
+                    if ($this->shouldEmitHooks($path1) and $this->shouldEmitHooks($path2)) {
824
+                        \OC_Hook::emit(
825
+                            Filesystem::CLASSNAME,
826
+                            Filesystem::signal_post_rename,
827
+                            array(
828
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
829
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
830
+                            )
831
+                        );
832
+                    }
833
+                }
834
+            }
835
+            $this->unlockFile($path1, ILockingProvider::LOCK_SHARED, true);
836
+            $this->unlockFile($path2, ILockingProvider::LOCK_SHARED, true);
837
+        }
838
+        return $result;
839
+    }
840
+
841
+    /**
842
+     * Copy a file/folder from the source path to target path
843
+     *
844
+     * @param string $path1 source path
845
+     * @param string $path2 target path
846
+     * @param bool $preserveMtime whether to preserve mtime on the copy
847
+     *
848
+     * @return bool|mixed
849
+     */
850
+    public function copy($path1, $path2, $preserveMtime = false) {
851
+        $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($path1));
852
+        $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($path2));
853
+        $result = false;
854
+        if (
855
+            Filesystem::isValidPath($path2)
856
+            and Filesystem::isValidPath($path1)
857
+            and !Filesystem::isFileBlacklisted($path2)
858
+        ) {
859
+            $path1 = $this->getRelativePath($absolutePath1);
860
+            $path2 = $this->getRelativePath($absolutePath2);
861
+
862
+            if ($path1 == null or $path2 == null) {
863
+                return false;
864
+            }
865
+            $run = true;
866
+
867
+            $this->lockFile($path2, ILockingProvider::LOCK_SHARED);
868
+            $this->lockFile($path1, ILockingProvider::LOCK_SHARED);
869
+            $lockTypePath1 = ILockingProvider::LOCK_SHARED;
870
+            $lockTypePath2 = ILockingProvider::LOCK_SHARED;
871
+
872
+            try {
873
+
874
+                $exists = $this->file_exists($path2);
875
+                if ($this->shouldEmitHooks()) {
876
+                    \OC_Hook::emit(
877
+                        Filesystem::CLASSNAME,
878
+                        Filesystem::signal_copy,
879
+                        array(
880
+                            Filesystem::signal_param_oldpath => $this->getHookPath($path1),
881
+                            Filesystem::signal_param_newpath => $this->getHookPath($path2),
882
+                            Filesystem::signal_param_run => &$run
883
+                        )
884
+                    );
885
+                    $this->emit_file_hooks_pre($exists, $path2, $run);
886
+                }
887
+                if ($run) {
888
+                    $mount1 = $this->getMount($path1);
889
+                    $mount2 = $this->getMount($path2);
890
+                    $storage1 = $mount1->getStorage();
891
+                    $internalPath1 = $mount1->getInternalPath($absolutePath1);
892
+                    $storage2 = $mount2->getStorage();
893
+                    $internalPath2 = $mount2->getInternalPath($absolutePath2);
894
+
895
+                    $this->changeLock($path2, ILockingProvider::LOCK_EXCLUSIVE);
896
+                    $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
897
+
898
+                    if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
899
+                        if ($storage1) {
900
+                            $result = $storage1->copy($internalPath1, $internalPath2);
901
+                        } else {
902
+                            $result = false;
903
+                        }
904
+                    } else {
905
+                        $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
906
+                    }
907
+
908
+                    $this->writeUpdate($storage2, $internalPath2);
909
+
910
+                    $this->changeLock($path2, ILockingProvider::LOCK_SHARED);
911
+                    $lockTypePath2 = ILockingProvider::LOCK_SHARED;
912
+
913
+                    if ($this->shouldEmitHooks() && $result !== false) {
914
+                        \OC_Hook::emit(
915
+                            Filesystem::CLASSNAME,
916
+                            Filesystem::signal_post_copy,
917
+                            array(
918
+                                Filesystem::signal_param_oldpath => $this->getHookPath($path1),
919
+                                Filesystem::signal_param_newpath => $this->getHookPath($path2)
920
+                            )
921
+                        );
922
+                        $this->emit_file_hooks_post($exists, $path2);
923
+                    }
924
+
925
+                }
926
+            } catch (\Exception $e) {
927
+                $this->unlockFile($path2, $lockTypePath2);
928
+                $this->unlockFile($path1, $lockTypePath1);
929
+                throw $e;
930
+            }
931
+
932
+            $this->unlockFile($path2, $lockTypePath2);
933
+            $this->unlockFile($path1, $lockTypePath1);
934
+
935
+        }
936
+        return $result;
937
+    }
938
+
939
+    /**
940
+     * @param string $path
941
+     * @param string $mode 'r' or 'w'
942
+     * @return resource
943
+     */
944
+    public function fopen($path, $mode) {
945
+        $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
946
+        $hooks = array();
947
+        switch ($mode) {
948
+            case 'r':
949
+                $hooks[] = 'read';
950
+                break;
951
+            case 'r+':
952
+            case 'w+':
953
+            case 'x+':
954
+            case 'a+':
955
+                $hooks[] = 'read';
956
+                $hooks[] = 'write';
957
+                break;
958
+            case 'w':
959
+            case 'x':
960
+            case 'a':
961
+                $hooks[] = 'write';
962
+                break;
963
+            default:
964
+                \OCP\Util::writeLog('core', 'invalid mode (' . $mode . ') for ' . $path, \OCP\Util::ERROR);
965
+        }
966
+
967
+        if ($mode !== 'r' && $mode !== 'w') {
968
+            \OC::$server->getLogger()->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends');
969
+        }
970
+
971
+        return $this->basicOperation('fopen', $path, $hooks, $mode);
972
+    }
973
+
974
+    /**
975
+     * @param string $path
976
+     * @return bool|string
977
+     * @throws \OCP\Files\InvalidPathException
978
+     */
979
+    public function toTmpFile($path) {
980
+        $this->assertPathLength($path);
981
+        if (Filesystem::isValidPath($path)) {
982
+            $source = $this->fopen($path, 'r');
983
+            if ($source) {
984
+                $extension = pathinfo($path, PATHINFO_EXTENSION);
985
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
986
+                file_put_contents($tmpFile, $source);
987
+                return $tmpFile;
988
+            } else {
989
+                return false;
990
+            }
991
+        } else {
992
+            return false;
993
+        }
994
+    }
995
+
996
+    /**
997
+     * @param string $tmpFile
998
+     * @param string $path
999
+     * @return bool|mixed
1000
+     * @throws \OCP\Files\InvalidPathException
1001
+     */
1002
+    public function fromTmpFile($tmpFile, $path) {
1003
+        $this->assertPathLength($path);
1004
+        if (Filesystem::isValidPath($path)) {
1005
+
1006
+            // Get directory that the file is going into
1007
+            $filePath = dirname($path);
1008
+
1009
+            // Create the directories if any
1010
+            if (!$this->file_exists($filePath)) {
1011
+                $result = $this->createParentDirectories($filePath);
1012
+                if ($result === false) {
1013
+                    return false;
1014
+                }
1015
+            }
1016
+
1017
+            $source = fopen($tmpFile, 'r');
1018
+            if ($source) {
1019
+                $result = $this->file_put_contents($path, $source);
1020
+                // $this->file_put_contents() might have already closed
1021
+                // the resource, so we check it, before trying to close it
1022
+                // to avoid messages in the error log.
1023
+                if (is_resource($source)) {
1024
+                    fclose($source);
1025
+                }
1026
+                unlink($tmpFile);
1027
+                return $result;
1028
+            } else {
1029
+                return false;
1030
+            }
1031
+        } else {
1032
+            return false;
1033
+        }
1034
+    }
1035
+
1036
+
1037
+    /**
1038
+     * @param string $path
1039
+     * @return mixed
1040
+     * @throws \OCP\Files\InvalidPathException
1041
+     */
1042
+    public function getMimeType($path) {
1043
+        $this->assertPathLength($path);
1044
+        return $this->basicOperation('getMimeType', $path);
1045
+    }
1046
+
1047
+    /**
1048
+     * @param string $type
1049
+     * @param string $path
1050
+     * @param bool $raw
1051
+     * @return bool|null|string
1052
+     */
1053
+    public function hash($type, $path, $raw = false) {
1054
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1055
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1056
+        if (Filesystem::isValidPath($path)) {
1057
+            $path = $this->getRelativePath($absolutePath);
1058
+            if ($path == null) {
1059
+                return false;
1060
+            }
1061
+            if ($this->shouldEmitHooks($path)) {
1062
+                \OC_Hook::emit(
1063
+                    Filesystem::CLASSNAME,
1064
+                    Filesystem::signal_read,
1065
+                    array(Filesystem::signal_param_path => $this->getHookPath($path))
1066
+                );
1067
+            }
1068
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1069
+            if ($storage) {
1070
+                $result = $storage->hash($type, $internalPath, $raw);
1071
+                return $result;
1072
+            }
1073
+        }
1074
+        return null;
1075
+    }
1076
+
1077
+    /**
1078
+     * @param string $path
1079
+     * @return mixed
1080
+     * @throws \OCP\Files\InvalidPathException
1081
+     */
1082
+    public function free_space($path = '/') {
1083
+        $this->assertPathLength($path);
1084
+        return $this->basicOperation('free_space', $path);
1085
+    }
1086
+
1087
+    /**
1088
+     * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
1089
+     *
1090
+     * @param string $operation
1091
+     * @param string $path
1092
+     * @param array $hooks (optional)
1093
+     * @param mixed $extraParam (optional)
1094
+     * @return mixed
1095
+     * @throws \Exception
1096
+     *
1097
+     * This method takes requests for basic filesystem functions (e.g. reading & writing
1098
+     * files), processes hooks and proxies, sanitises paths, and finally passes them on to
1099
+     * \OC\Files\Storage\Storage for delegation to a storage backend for execution
1100
+     */
1101
+    private function basicOperation($operation, $path, $hooks = [], $extraParam = null) {
1102
+        $postFix = (substr($path, -1, 1) === '/') ? '/' : '';
1103
+        $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
1104
+        if (Filesystem::isValidPath($path)
1105
+            and !Filesystem::isFileBlacklisted($path)
1106
+        ) {
1107
+            $path = $this->getRelativePath($absolutePath);
1108
+            if ($path == null) {
1109
+                return false;
1110
+            }
1111
+
1112
+            if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
1113
+                // always a shared lock during pre-hooks so the hook can read the file
1114
+                $this->lockFile($path, ILockingProvider::LOCK_SHARED);
1115
+            }
1116
+
1117
+            $run = $this->runHooks($hooks, $path);
1118
+            /** @var \OC\Files\Storage\Storage $storage */
1119
+            list($storage, $internalPath) = Filesystem::resolvePath($absolutePath . $postFix);
1120
+            if ($run and $storage) {
1121
+                if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1122
+                    $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
1123
+                }
1124
+                try {
1125
+                    if (!is_null($extraParam)) {
1126
+                        $result = $storage->$operation($internalPath, $extraParam);
1127
+                    } else {
1128
+                        $result = $storage->$operation($internalPath);
1129
+                    }
1130
+                } catch (\Exception $e) {
1131
+                    if (in_array('write', $hooks) || in_array('delete', $hooks)) {
1132
+                        $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1133
+                    } else if (in_array('read', $hooks)) {
1134
+                        $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1135
+                    }
1136
+                    throw $e;
1137
+                }
1138
+
1139
+                if ($result && in_array('delete', $hooks) and $result) {
1140
+                    $this->removeUpdate($storage, $internalPath);
1141
+                }
1142
+                if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
1143
+                    $this->writeUpdate($storage, $internalPath);
1144
+                }
1145
+                if ($result && in_array('touch', $hooks)) {
1146
+                    $this->writeUpdate($storage, $internalPath, $extraParam);
1147
+                }
1148
+
1149
+                if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
1150
+                    $this->changeLock($path, ILockingProvider::LOCK_SHARED);
1151
+                }
1152
+
1153
+                $unlockLater = false;
1154
+                if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
1155
+                    $unlockLater = true;
1156
+                    // make sure our unlocking callback will still be called if connection is aborted
1157
+                    ignore_user_abort(true);
1158
+                    $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
1159
+                        if (in_array('write', $hooks)) {
1160
+                            $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
1161
+                        } else if (in_array('read', $hooks)) {
1162
+                            $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1163
+                        }
1164
+                    });
1165
+                }
1166
+
1167
+                if ($this->shouldEmitHooks($path) && $result !== false) {
1168
+                    if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
1169
+                        $this->runHooks($hooks, $path, true);
1170
+                    }
1171
+                }
1172
+
1173
+                if (!$unlockLater
1174
+                    && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
1175
+                ) {
1176
+                    $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1177
+                }
1178
+                return $result;
1179
+            } else {
1180
+                $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
1181
+            }
1182
+        }
1183
+        return null;
1184
+    }
1185
+
1186
+    /**
1187
+     * get the path relative to the default root for hook usage
1188
+     *
1189
+     * @param string $path
1190
+     * @return string
1191
+     */
1192
+    private function getHookPath($path) {
1193
+        if (!Filesystem::getView()) {
1194
+            return $path;
1195
+        }
1196
+        return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
1197
+    }
1198
+
1199
+    private function shouldEmitHooks($path = '') {
1200
+        if ($path && Cache\Scanner::isPartialFile($path)) {
1201
+            return false;
1202
+        }
1203
+        if (!Filesystem::$loaded) {
1204
+            return false;
1205
+        }
1206
+        $defaultRoot = Filesystem::getRoot();
1207
+        if ($defaultRoot === null) {
1208
+            return false;
1209
+        }
1210
+        if ($this->fakeRoot === $defaultRoot) {
1211
+            return true;
1212
+        }
1213
+        $fullPath = $this->getAbsolutePath($path);
1214
+
1215
+        if ($fullPath === $defaultRoot) {
1216
+            return true;
1217
+        }
1218
+
1219
+        return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
1220
+    }
1221
+
1222
+    /**
1223
+     * @param string[] $hooks
1224
+     * @param string $path
1225
+     * @param bool $post
1226
+     * @return bool
1227
+     */
1228
+    private function runHooks($hooks, $path, $post = false) {
1229
+        $relativePath = $path;
1230
+        $path = $this->getHookPath($path);
1231
+        $prefix = ($post) ? 'post_' : '';
1232
+        $run = true;
1233
+        if ($this->shouldEmitHooks($relativePath)) {
1234
+            foreach ($hooks as $hook) {
1235
+                if ($hook != 'read') {
1236
+                    \OC_Hook::emit(
1237
+                        Filesystem::CLASSNAME,
1238
+                        $prefix . $hook,
1239
+                        array(
1240
+                            Filesystem::signal_param_run => &$run,
1241
+                            Filesystem::signal_param_path => $path
1242
+                        )
1243
+                    );
1244
+                } elseif (!$post) {
1245
+                    \OC_Hook::emit(
1246
+                        Filesystem::CLASSNAME,
1247
+                        $prefix . $hook,
1248
+                        array(
1249
+                            Filesystem::signal_param_path => $path
1250
+                        )
1251
+                    );
1252
+                }
1253
+            }
1254
+        }
1255
+        return $run;
1256
+    }
1257
+
1258
+    /**
1259
+     * check if a file or folder has been updated since $time
1260
+     *
1261
+     * @param string $path
1262
+     * @param int $time
1263
+     * @return bool
1264
+     */
1265
+    public function hasUpdated($path, $time) {
1266
+        return $this->basicOperation('hasUpdated', $path, array(), $time);
1267
+    }
1268
+
1269
+    /**
1270
+     * @param string $ownerId
1271
+     * @return \OC\User\User
1272
+     */
1273
+    private function getUserObjectForOwner($ownerId) {
1274
+        $owner = $this->userManager->get($ownerId);
1275
+        if ($owner instanceof IUser) {
1276
+            return $owner;
1277
+        } else {
1278
+            return new User($ownerId, null);
1279
+        }
1280
+    }
1281
+
1282
+    /**
1283
+     * Get file info from cache
1284
+     *
1285
+     * If the file is not in cached it will be scanned
1286
+     * If the file has changed on storage the cache will be updated
1287
+     *
1288
+     * @param \OC\Files\Storage\Storage $storage
1289
+     * @param string $internalPath
1290
+     * @param string $relativePath
1291
+     * @return array|bool
1292
+     */
1293
+    private function getCacheEntry($storage, $internalPath, $relativePath) {
1294
+        $cache = $storage->getCache($internalPath);
1295
+        $data = $cache->get($internalPath);
1296
+        $watcher = $storage->getWatcher($internalPath);
1297
+
1298
+        try {
1299
+            // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
1300
+            if (!$data || $data['size'] === -1) {
1301
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1302
+                if (!$storage->file_exists($internalPath)) {
1303
+                    $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1304
+                    return false;
1305
+                }
1306
+                $scanner = $storage->getScanner($internalPath);
1307
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1308
+                $data = $cache->get($internalPath);
1309
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1310
+            } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
1311
+                $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
1312
+                $watcher->update($internalPath, $data);
1313
+                $storage->getPropagator()->propagateChange($internalPath, time());
1314
+                $data = $cache->get($internalPath);
1315
+                $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
1316
+            }
1317
+        } catch (LockedException $e) {
1318
+            // if the file is locked we just use the old cache info
1319
+        }
1320
+
1321
+        return $data;
1322
+    }
1323
+
1324
+    /**
1325
+     * get the filesystem info
1326
+     *
1327
+     * @param string $path
1328
+     * @param boolean|string $includeMountPoints true to add mountpoint sizes,
1329
+     * 'ext' to add only ext storage mount point sizes. Defaults to true.
1330
+     * defaults to true
1331
+     * @return \OC\Files\FileInfo|false False if file does not exist
1332
+     */
1333
+    public function getFileInfo($path, $includeMountPoints = true) {
1334
+        $this->assertPathLength($path);
1335
+        if (!Filesystem::isValidPath($path)) {
1336
+            return false;
1337
+        }
1338
+        if (Cache\Scanner::isPartialFile($path)) {
1339
+            return $this->getPartFileInfo($path);
1340
+        }
1341
+        $relativePath = $path;
1342
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1343
+
1344
+        $mount = Filesystem::getMountManager()->find($path);
1345
+        $storage = $mount->getStorage();
1346
+        $internalPath = $mount->getInternalPath($path);
1347
+        if ($storage) {
1348
+            $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
1349
+
1350
+            if (!$data instanceof ICacheEntry) {
1351
+                return false;
1352
+            }
1353
+
1354
+            if ($mount instanceof MoveableMount && $internalPath === '') {
1355
+                $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
1356
+            }
1357
+
1358
+            $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
1359
+            $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
1360
+
1361
+            if ($data and isset($data['fileid'])) {
1362
+                if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
1363
+                    //add the sizes of other mount points to the folder
1364
+                    $extOnly = ($includeMountPoints === 'ext');
1365
+                    $mounts = Filesystem::getMountManager()->findIn($path);
1366
+                    $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
1367
+                        $subStorage = $mount->getStorage();
1368
+                        return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
1369
+                    }));
1370
+                }
1371
+            }
1372
+
1373
+            return $info;
1374
+        }
1375
+
1376
+        return false;
1377
+    }
1378
+
1379
+    /**
1380
+     * get the content of a directory
1381
+     *
1382
+     * @param string $directory path under datadirectory
1383
+     * @param string $mimetype_filter limit returned content to this mimetype or mimepart
1384
+     * @return FileInfo[]
1385
+     */
1386
+    public function getDirectoryContent($directory, $mimetype_filter = '') {
1387
+        $this->assertPathLength($directory);
1388
+        if (!Filesystem::isValidPath($directory)) {
1389
+            return [];
1390
+        }
1391
+        $path = $this->getAbsolutePath($directory);
1392
+        $path = Filesystem::normalizePath($path);
1393
+        $mount = $this->getMount($directory);
1394
+        $storage = $mount->getStorage();
1395
+        $internalPath = $mount->getInternalPath($path);
1396
+        if ($storage) {
1397
+            $cache = $storage->getCache($internalPath);
1398
+            $user = \OC_User::getUser();
1399
+
1400
+            $data = $this->getCacheEntry($storage, $internalPath, $directory);
1401
+
1402
+            if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
1403
+                return [];
1404
+            }
1405
+
1406
+            $folderId = $data['fileid'];
1407
+            $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
1408
+
1409
+            $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
1410
+            /**
1411
+             * @var \OC\Files\FileInfo[] $files
1412
+             */
1413
+            $files = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
1414
+                if ($sharingDisabled) {
1415
+                    $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1416
+                }
1417
+                $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
1418
+                return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
1419
+            }, $contents);
1420
+
1421
+            //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
1422
+            $mounts = Filesystem::getMountManager()->findIn($path);
1423
+            $dirLength = strlen($path);
1424
+            foreach ($mounts as $mount) {
1425
+                $mountPoint = $mount->getMountPoint();
1426
+                $subStorage = $mount->getStorage();
1427
+                if ($subStorage) {
1428
+                    $subCache = $subStorage->getCache('');
1429
+
1430
+                    $rootEntry = $subCache->get('');
1431
+                    if (!$rootEntry) {
1432
+                        $subScanner = $subStorage->getScanner('');
1433
+                        try {
1434
+                            $subScanner->scanFile('');
1435
+                        } catch (\OCP\Files\StorageNotAvailableException $e) {
1436
+                            continue;
1437
+                        } catch (\OCP\Files\StorageInvalidException $e) {
1438
+                            continue;
1439
+                        } catch (\Exception $e) {
1440
+                            // sometimes when the storage is not available it can be any exception
1441
+                            \OCP\Util::writeLog(
1442
+                                'core',
1443
+                                'Exception while scanning storage "' . $subStorage->getId() . '": ' .
1444
+                                get_class($e) . ': ' . $e->getMessage(),
1445
+                                \OCP\Util::ERROR
1446
+                            );
1447
+                            continue;
1448
+                        }
1449
+                        $rootEntry = $subCache->get('');
1450
+                    }
1451
+
1452
+                    if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
1453
+                        $relativePath = trim(substr($mountPoint, $dirLength), '/');
1454
+                        if ($pos = strpos($relativePath, '/')) {
1455
+                            //mountpoint inside subfolder add size to the correct folder
1456
+                            $entryName = substr($relativePath, 0, $pos);
1457
+                            foreach ($files as &$entry) {
1458
+                                if ($entry->getName() === $entryName) {
1459
+                                    $entry->addSubEntry($rootEntry, $mountPoint);
1460
+                                }
1461
+                            }
1462
+                        } else { //mountpoint in this folder, add an entry for it
1463
+                            $rootEntry['name'] = $relativePath;
1464
+                            $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
1465
+                            $permissions = $rootEntry['permissions'];
1466
+                            // do not allow renaming/deleting the mount point if they are not shared files/folders
1467
+                            // for shared files/folders we use the permissions given by the owner
1468
+                            if ($mount instanceof MoveableMount) {
1469
+                                $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
1470
+                            } else {
1471
+                                $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
1472
+                            }
1473
+
1474
+                            //remove any existing entry with the same name
1475
+                            foreach ($files as $i => $file) {
1476
+                                if ($file['name'] === $rootEntry['name']) {
1477
+                                    unset($files[$i]);
1478
+                                    break;
1479
+                                }
1480
+                            }
1481
+                            $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
1482
+
1483
+                            // if sharing was disabled for the user we remove the share permissions
1484
+                            if (\OCP\Util::isSharingDisabledForUser()) {
1485
+                                $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
1486
+                            }
1487
+
1488
+                            $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
1489
+                            $files[] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
1490
+                        }
1491
+                    }
1492
+                }
1493
+            }
1494
+
1495
+            if ($mimetype_filter) {
1496
+                $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
1497
+                    if (strpos($mimetype_filter, '/')) {
1498
+                        return $file->getMimetype() === $mimetype_filter;
1499
+                    } else {
1500
+                        return $file->getMimePart() === $mimetype_filter;
1501
+                    }
1502
+                });
1503
+            }
1504
+
1505
+            return $files;
1506
+        } else {
1507
+            return [];
1508
+        }
1509
+    }
1510
+
1511
+    /**
1512
+     * change file metadata
1513
+     *
1514
+     * @param string $path
1515
+     * @param array|\OCP\Files\FileInfo $data
1516
+     * @return int
1517
+     *
1518
+     * returns the fileid of the updated file
1519
+     */
1520
+    public function putFileInfo($path, $data) {
1521
+        $this->assertPathLength($path);
1522
+        if ($data instanceof FileInfo) {
1523
+            $data = $data->getData();
1524
+        }
1525
+        $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
1526
+        /**
1527
+         * @var \OC\Files\Storage\Storage $storage
1528
+         * @var string $internalPath
1529
+         */
1530
+        list($storage, $internalPath) = Filesystem::resolvePath($path);
1531
+        if ($storage) {
1532
+            $cache = $storage->getCache($path);
1533
+
1534
+            if (!$cache->inCache($internalPath)) {
1535
+                $scanner = $storage->getScanner($internalPath);
1536
+                $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
1537
+            }
1538
+
1539
+            return $cache->put($internalPath, $data);
1540
+        } else {
1541
+            return -1;
1542
+        }
1543
+    }
1544
+
1545
+    /**
1546
+     * search for files with the name matching $query
1547
+     *
1548
+     * @param string $query
1549
+     * @return FileInfo[]
1550
+     */
1551
+    public function search($query) {
1552
+        return $this->searchCommon('search', array('%' . $query . '%'));
1553
+    }
1554
+
1555
+    /**
1556
+     * search for files with the name matching $query
1557
+     *
1558
+     * @param string $query
1559
+     * @return FileInfo[]
1560
+     */
1561
+    public function searchRaw($query) {
1562
+        return $this->searchCommon('search', array($query));
1563
+    }
1564
+
1565
+    /**
1566
+     * search for files by mimetype
1567
+     *
1568
+     * @param string $mimetype
1569
+     * @return FileInfo[]
1570
+     */
1571
+    public function searchByMime($mimetype) {
1572
+        return $this->searchCommon('searchByMime', array($mimetype));
1573
+    }
1574
+
1575
+    /**
1576
+     * search for files by tag
1577
+     *
1578
+     * @param string|int $tag name or tag id
1579
+     * @param string $userId owner of the tags
1580
+     * @return FileInfo[]
1581
+     */
1582
+    public function searchByTag($tag, $userId) {
1583
+        return $this->searchCommon('searchByTag', array($tag, $userId));
1584
+    }
1585
+
1586
+    /**
1587
+     * @param string $method cache method
1588
+     * @param array $args
1589
+     * @return FileInfo[]
1590
+     */
1591
+    private function searchCommon($method, $args) {
1592
+        $files = array();
1593
+        $rootLength = strlen($this->fakeRoot);
1594
+
1595
+        $mount = $this->getMount('');
1596
+        $mountPoint = $mount->getMountPoint();
1597
+        $storage = $mount->getStorage();
1598
+        if ($storage) {
1599
+            $cache = $storage->getCache('');
1600
+
1601
+            $results = call_user_func_array(array($cache, $method), $args);
1602
+            foreach ($results as $result) {
1603
+                if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
1604
+                    $internalPath = $result['path'];
1605
+                    $path = $mountPoint . $result['path'];
1606
+                    $result['path'] = substr($mountPoint . $result['path'], $rootLength);
1607
+                    $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1608
+                    $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1609
+                }
1610
+            }
1611
+
1612
+            $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
1613
+            foreach ($mounts as $mount) {
1614
+                $mountPoint = $mount->getMountPoint();
1615
+                $storage = $mount->getStorage();
1616
+                if ($storage) {
1617
+                    $cache = $storage->getCache('');
1618
+
1619
+                    $relativeMountPoint = substr($mountPoint, $rootLength);
1620
+                    $results = call_user_func_array(array($cache, $method), $args);
1621
+                    if ($results) {
1622
+                        foreach ($results as $result) {
1623
+                            $internalPath = $result['path'];
1624
+                            $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
1625
+                            $path = rtrim($mountPoint . $internalPath, '/');
1626
+                            $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1627
+                            $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
1628
+                        }
1629
+                    }
1630
+                }
1631
+            }
1632
+        }
1633
+        return $files;
1634
+    }
1635
+
1636
+    /**
1637
+     * Get the owner for a file or folder
1638
+     *
1639
+     * @param string $path
1640
+     * @return string the user id of the owner
1641
+     * @throws NotFoundException
1642
+     */
1643
+    public function getOwner($path) {
1644
+        $info = $this->getFileInfo($path);
1645
+        if (!$info) {
1646
+            throw new NotFoundException($path . ' not found while trying to get owner');
1647
+        }
1648
+        return $info->getOwner()->getUID();
1649
+    }
1650
+
1651
+    /**
1652
+     * get the ETag for a file or folder
1653
+     *
1654
+     * @param string $path
1655
+     * @return string
1656
+     */
1657
+    public function getETag($path) {
1658
+        /**
1659
+         * @var Storage\Storage $storage
1660
+         * @var string $internalPath
1661
+         */
1662
+        list($storage, $internalPath) = $this->resolvePath($path);
1663
+        if ($storage) {
1664
+            return $storage->getETag($internalPath);
1665
+        } else {
1666
+            return null;
1667
+        }
1668
+    }
1669
+
1670
+    /**
1671
+     * Get the path of a file by id, relative to the view
1672
+     *
1673
+     * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
1674
+     *
1675
+     * @param int $id
1676
+     * @throws NotFoundException
1677
+     * @return string
1678
+     */
1679
+    public function getPath($id) {
1680
+        $id = (int)$id;
1681
+        $manager = Filesystem::getMountManager();
1682
+        $mounts = $manager->findIn($this->fakeRoot);
1683
+        $mounts[] = $manager->find($this->fakeRoot);
1684
+        // reverse the array so we start with the storage this view is in
1685
+        // which is the most likely to contain the file we're looking for
1686
+        $mounts = array_reverse($mounts);
1687
+        foreach ($mounts as $mount) {
1688
+            /**
1689
+             * @var \OC\Files\Mount\MountPoint $mount
1690
+             */
1691
+            if ($mount->getStorage()) {
1692
+                $cache = $mount->getStorage()->getCache();
1693
+                $internalPath = $cache->getPathById($id);
1694
+                if (is_string($internalPath)) {
1695
+                    $fullPath = $mount->getMountPoint() . $internalPath;
1696
+                    if (!is_null($path = $this->getRelativePath($fullPath))) {
1697
+                        return $path;
1698
+                    }
1699
+                }
1700
+            }
1701
+        }
1702
+        throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
1703
+    }
1704
+
1705
+    /**
1706
+     * @param string $path
1707
+     * @throws InvalidPathException
1708
+     */
1709
+    private function assertPathLength($path) {
1710
+        $maxLen = min(PHP_MAXPATHLEN, 4000);
1711
+        // Check for the string length - performed using isset() instead of strlen()
1712
+        // because isset() is about 5x-40x faster.
1713
+        if (isset($path[$maxLen])) {
1714
+            $pathLen = strlen($path);
1715
+            throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
1716
+        }
1717
+    }
1718
+
1719
+    /**
1720
+     * check if it is allowed to move a mount point to a given target.
1721
+     * It is not allowed to move a mount point into a different mount point or
1722
+     * into an already shared folder
1723
+     *
1724
+     * @param MoveableMount $mount1 moveable mount
1725
+     * @param string $target absolute target path
1726
+     * @return boolean
1727
+     */
1728
+    private function canMove(MoveableMount $mount1, $target) {
1729
+
1730
+        list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
1731
+        if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
1732
+            \OCP\Util::writeLog('files',
1733
+                'It is not allowed to move one mount point into another one',
1734
+                \OCP\Util::DEBUG);
1735
+            return false;
1736
+        }
1737
+
1738
+        return $mount1->isTargetAllowed($target);
1739
+    }
1740
+
1741
+    /**
1742
+     * Get a fileinfo object for files that are ignored in the cache (part files)
1743
+     *
1744
+     * @param string $path
1745
+     * @return \OCP\Files\FileInfo
1746
+     */
1747
+    private function getPartFileInfo($path) {
1748
+        $mount = $this->getMount($path);
1749
+        $storage = $mount->getStorage();
1750
+        $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
1751
+        $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
1752
+        return new FileInfo(
1753
+            $this->getAbsolutePath($path),
1754
+            $storage,
1755
+            $internalPath,
1756
+            [
1757
+                'fileid' => null,
1758
+                'mimetype' => $storage->getMimeType($internalPath),
1759
+                'name' => basename($path),
1760
+                'etag' => null,
1761
+                'size' => $storage->filesize($internalPath),
1762
+                'mtime' => $storage->filemtime($internalPath),
1763
+                'encrypted' => false,
1764
+                'permissions' => \OCP\Constants::PERMISSION_ALL
1765
+            ],
1766
+            $mount,
1767
+            $owner
1768
+        );
1769
+    }
1770
+
1771
+    /**
1772
+     * @param string $path
1773
+     * @param string $fileName
1774
+     * @throws InvalidPathException
1775
+     */
1776
+    public function verifyPath($path, $fileName) {
1777
+        try {
1778
+            /** @type \OCP\Files\Storage $storage */
1779
+            list($storage, $internalPath) = $this->resolvePath($path);
1780
+            $storage->verifyPath($internalPath, $fileName);
1781
+        } catch (ReservedWordException $ex) {
1782
+            $l = \OC::$server->getL10N('lib');
1783
+            throw new InvalidPathException($l->t('File name is a reserved word'));
1784
+        } catch (InvalidCharacterInPathException $ex) {
1785
+            $l = \OC::$server->getL10N('lib');
1786
+            throw new InvalidPathException($l->t('File name contains at least one invalid character'));
1787
+        } catch (FileNameTooLongException $ex) {
1788
+            $l = \OC::$server->getL10N('lib');
1789
+            throw new InvalidPathException($l->t('File name is too long'));
1790
+        } catch (InvalidDirectoryException $ex) {
1791
+            $l = \OC::$server->getL10N('lib');
1792
+            throw new InvalidPathException($l->t('Dot files are not allowed'));
1793
+        } catch (EmptyFileNameException $ex) {
1794
+            $l = \OC::$server->getL10N('lib');
1795
+            throw new InvalidPathException($l->t('Empty filename is not allowed'));
1796
+        }
1797
+    }
1798
+
1799
+    /**
1800
+     * get all parent folders of $path
1801
+     *
1802
+     * @param string $path
1803
+     * @return string[]
1804
+     */
1805
+    private function getParents($path) {
1806
+        $path = trim($path, '/');
1807
+        if (!$path) {
1808
+            return [];
1809
+        }
1810
+
1811
+        $parts = explode('/', $path);
1812
+
1813
+        // remove the single file
1814
+        array_pop($parts);
1815
+        $result = array('/');
1816
+        $resultPath = '';
1817
+        foreach ($parts as $part) {
1818
+            if ($part) {
1819
+                $resultPath .= '/' . $part;
1820
+                $result[] = $resultPath;
1821
+            }
1822
+        }
1823
+        return $result;
1824
+    }
1825
+
1826
+    /**
1827
+     * Returns the mount point for which to lock
1828
+     *
1829
+     * @param string $absolutePath absolute path
1830
+     * @param bool $useParentMount true to return parent mount instead of whatever
1831
+     * is mounted directly on the given path, false otherwise
1832
+     * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
1833
+     */
1834
+    private function getMountForLock($absolutePath, $useParentMount = false) {
1835
+        $results = [];
1836
+        $mount = Filesystem::getMountManager()->find($absolutePath);
1837
+        if (!$mount) {
1838
+            return $results;
1839
+        }
1840
+
1841
+        if ($useParentMount) {
1842
+            // find out if something is mounted directly on the path
1843
+            $internalPath = $mount->getInternalPath($absolutePath);
1844
+            if ($internalPath === '') {
1845
+                // resolve the parent mount instead
1846
+                $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
1847
+            }
1848
+        }
1849
+
1850
+        return $mount;
1851
+    }
1852
+
1853
+    /**
1854
+     * Lock the given path
1855
+     *
1856
+     * @param string $path the path of the file to lock, relative to the view
1857
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1858
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1859
+     *
1860
+     * @return bool False if the path is excluded from locking, true otherwise
1861
+     * @throws \OCP\Lock\LockedException if the path is already locked
1862
+     */
1863
+    private function lockPath($path, $type, $lockMountPoint = false) {
1864
+        $absolutePath = $this->getAbsolutePath($path);
1865
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1866
+        if (!$this->shouldLockFile($absolutePath)) {
1867
+            return false;
1868
+        }
1869
+
1870
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1871
+        if ($mount) {
1872
+            try {
1873
+                $storage = $mount->getStorage();
1874
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1875
+                    $storage->acquireLock(
1876
+                        $mount->getInternalPath($absolutePath),
1877
+                        $type,
1878
+                        $this->lockingProvider
1879
+                    );
1880
+                }
1881
+            } catch (\OCP\Lock\LockedException $e) {
1882
+                // rethrow with the a human-readable path
1883
+                throw new \OCP\Lock\LockedException(
1884
+                    $this->getPathRelativeToFiles($absolutePath),
1885
+                    $e
1886
+                );
1887
+            }
1888
+        }
1889
+
1890
+        return true;
1891
+    }
1892
+
1893
+    /**
1894
+     * Change the lock type
1895
+     *
1896
+     * @param string $path the path of the file to lock, relative to the view
1897
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1898
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1899
+     *
1900
+     * @return bool False if the path is excluded from locking, true otherwise
1901
+     * @throws \OCP\Lock\LockedException if the path is already locked
1902
+     */
1903
+    public function changeLock($path, $type, $lockMountPoint = false) {
1904
+        $path = Filesystem::normalizePath($path);
1905
+        $absolutePath = $this->getAbsolutePath($path);
1906
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1907
+        if (!$this->shouldLockFile($absolutePath)) {
1908
+            return false;
1909
+        }
1910
+
1911
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1912
+        if ($mount) {
1913
+            try {
1914
+                $storage = $mount->getStorage();
1915
+                if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1916
+                    $storage->changeLock(
1917
+                        $mount->getInternalPath($absolutePath),
1918
+                        $type,
1919
+                        $this->lockingProvider
1920
+                    );
1921
+                }
1922
+            } catch (\OCP\Lock\LockedException $e) {
1923
+                // rethrow with the a human-readable path
1924
+                throw new \OCP\Lock\LockedException(
1925
+                    $this->getPathRelativeToFiles($absolutePath),
1926
+                    $e
1927
+                );
1928
+            }
1929
+        }
1930
+
1931
+        return true;
1932
+    }
1933
+
1934
+    /**
1935
+     * Unlock the given path
1936
+     *
1937
+     * @param string $path the path of the file to unlock, relative to the view
1938
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1939
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1940
+     *
1941
+     * @return bool False if the path is excluded from locking, true otherwise
1942
+     */
1943
+    private function unlockPath($path, $type, $lockMountPoint = false) {
1944
+        $absolutePath = $this->getAbsolutePath($path);
1945
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1946
+        if (!$this->shouldLockFile($absolutePath)) {
1947
+            return false;
1948
+        }
1949
+
1950
+        $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
1951
+        if ($mount) {
1952
+            $storage = $mount->getStorage();
1953
+            if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
1954
+                $storage->releaseLock(
1955
+                    $mount->getInternalPath($absolutePath),
1956
+                    $type,
1957
+                    $this->lockingProvider
1958
+                );
1959
+            }
1960
+        }
1961
+
1962
+        return true;
1963
+    }
1964
+
1965
+    /**
1966
+     * Lock a path and all its parents up to the root of the view
1967
+     *
1968
+     * @param string $path the path of the file to lock relative to the view
1969
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1970
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1971
+     *
1972
+     * @return bool False if the path is excluded from locking, true otherwise
1973
+     */
1974
+    public function lockFile($path, $type, $lockMountPoint = false) {
1975
+        $absolutePath = $this->getAbsolutePath($path);
1976
+        $absolutePath = Filesystem::normalizePath($absolutePath);
1977
+        if (!$this->shouldLockFile($absolutePath)) {
1978
+            return false;
1979
+        }
1980
+
1981
+        $this->lockPath($path, $type, $lockMountPoint);
1982
+
1983
+        $parents = $this->getParents($path);
1984
+        foreach ($parents as $parent) {
1985
+            $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
1986
+        }
1987
+
1988
+        return true;
1989
+    }
1990
+
1991
+    /**
1992
+     * Unlock a path and all its parents up to the root of the view
1993
+     *
1994
+     * @param string $path the path of the file to lock relative to the view
1995
+     * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
1996
+     * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
1997
+     *
1998
+     * @return bool False if the path is excluded from locking, true otherwise
1999
+     */
2000
+    public function unlockFile($path, $type, $lockMountPoint = false) {
2001
+        $absolutePath = $this->getAbsolutePath($path);
2002
+        $absolutePath = Filesystem::normalizePath($absolutePath);
2003
+        if (!$this->shouldLockFile($absolutePath)) {
2004
+            return false;
2005
+        }
2006
+
2007
+        $this->unlockPath($path, $type, $lockMountPoint);
2008
+
2009
+        $parents = $this->getParents($path);
2010
+        foreach ($parents as $parent) {
2011
+            $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
2012
+        }
2013
+
2014
+        return true;
2015
+    }
2016
+
2017
+    /**
2018
+     * Only lock files in data/user/files/
2019
+     *
2020
+     * @param string $path Absolute path to the file/folder we try to (un)lock
2021
+     * @return bool
2022
+     */
2023
+    protected function shouldLockFile($path) {
2024
+        $path = Filesystem::normalizePath($path);
2025
+
2026
+        $pathSegments = explode('/', $path);
2027
+        if (isset($pathSegments[2])) {
2028
+            // E.g.: /username/files/path-to-file
2029
+            return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
2030
+        }
2031
+
2032
+        return true;
2033
+    }
2034
+
2035
+    /**
2036
+     * Shortens the given absolute path to be relative to
2037
+     * "$user/files".
2038
+     *
2039
+     * @param string $absolutePath absolute path which is under "files"
2040
+     *
2041
+     * @return string path relative to "files" with trimmed slashes or null
2042
+     * if the path was NOT relative to files
2043
+     *
2044
+     * @throws \InvalidArgumentException if the given path was not under "files"
2045
+     * @since 8.1.0
2046
+     */
2047
+    public function getPathRelativeToFiles($absolutePath) {
2048
+        $path = Filesystem::normalizePath($absolutePath);
2049
+        $parts = explode('/', trim($path, '/'), 3);
2050
+        // "$user", "files", "path/to/dir"
2051
+        if (!isset($parts[1]) || $parts[1] !== 'files') {
2052
+            $this->logger->error(
2053
+                '$absolutePath must be relative to "files", value is "%s"',
2054
+                [
2055
+                    $absolutePath
2056
+                ]
2057
+            );
2058
+            throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
2059
+        }
2060
+        if (isset($parts[2])) {
2061
+            return $parts[2];
2062
+        }
2063
+        return '';
2064
+    }
2065
+
2066
+    /**
2067
+     * @param string $filename
2068
+     * @return array
2069
+     * @throws \OC\User\NoUserException
2070
+     * @throws NotFoundException
2071
+     */
2072
+    public function getUidAndFilename($filename) {
2073
+        $info = $this->getFileInfo($filename);
2074
+        if (!$info instanceof \OCP\Files\FileInfo) {
2075
+            throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
2076
+        }
2077
+        $uid = $info->getOwner()->getUID();
2078
+        if ($uid != \OCP\User::getUser()) {
2079
+            Filesystem::initMountPoints($uid);
2080
+            $ownerView = new View('/' . $uid . '/files');
2081
+            try {
2082
+                $filename = $ownerView->getPath($info['fileid']);
2083
+            } catch (NotFoundException $e) {
2084
+                throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
2085
+            }
2086
+        }
2087
+        return [$uid, $filename];
2088
+    }
2089
+
2090
+    /**
2091
+     * Creates parent non-existing folders
2092
+     *
2093
+     * @param string $filePath
2094
+     * @return bool
2095
+     */
2096
+    private function createParentDirectories($filePath) {
2097
+        $directoryParts = explode('/', $filePath);
2098
+        $directoryParts = array_filter($directoryParts);
2099
+        foreach ($directoryParts as $key => $part) {
2100
+            $currentPathElements = array_slice($directoryParts, 0, $key);
2101
+            $currentPath = '/' . implode('/', $currentPathElements);
2102
+            if ($this->is_file($currentPath)) {
2103
+                return false;
2104
+            }
2105
+            if (!$this->file_exists($currentPath)) {
2106
+                $this->mkdir($currentPath);
2107
+            }
2108
+        }
2109
+
2110
+        return true;
2111
+    }
2112 2112
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/PersonalMount.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -32,69 +32,69 @@
 block discarded – undo
32 32
  * Person mount points can be moved by the user
33 33
  */
34 34
 class PersonalMount extends MountPoint implements MoveableMount {
35
-	/** @var UserStoragesService */
36
-	protected $storagesService;
35
+    /** @var UserStoragesService */
36
+    protected $storagesService;
37 37
 
38
-	/** @var int */
39
-	protected $numericStorageId;
38
+    /** @var int */
39
+    protected $numericStorageId;
40 40
 
41
-	/**
42
-	 * @param UserStoragesService $storagesService
43
-	 * @param int $storageId
44
-	 * @param \OCP\Files\Storage $storage
45
-	 * @param string $mountpoint
46
-	 * @param array $arguments (optional) configuration for the storage backend
47
-	 * @param \OCP\Files\Storage\IStorageFactory $loader
48
-	 * @param array $mountOptions mount specific options
49
-	 */
50
-	public function __construct(
51
-		UserStoragesService $storagesService,
52
-		$storageId,
53
-		$storage,
54
-		$mountpoint,
55
-		$arguments = null,
56
-		$loader = null,
57
-		$mountOptions = null
58
-	) {
59
-		parent::__construct($storage, $mountpoint, $arguments, $loader, $mountOptions);
60
-		$this->storagesService = $storagesService;
61
-		$this->numericStorageId = $storageId;
62
-	}
41
+    /**
42
+     * @param UserStoragesService $storagesService
43
+     * @param int $storageId
44
+     * @param \OCP\Files\Storage $storage
45
+     * @param string $mountpoint
46
+     * @param array $arguments (optional) configuration for the storage backend
47
+     * @param \OCP\Files\Storage\IStorageFactory $loader
48
+     * @param array $mountOptions mount specific options
49
+     */
50
+    public function __construct(
51
+        UserStoragesService $storagesService,
52
+        $storageId,
53
+        $storage,
54
+        $mountpoint,
55
+        $arguments = null,
56
+        $loader = null,
57
+        $mountOptions = null
58
+    ) {
59
+        parent::__construct($storage, $mountpoint, $arguments, $loader, $mountOptions);
60
+        $this->storagesService = $storagesService;
61
+        $this->numericStorageId = $storageId;
62
+    }
63 63
 
64
-	/**
65
-	 * Move the mount point to $target
66
-	 *
67
-	 * @param string $target the target mount point
68
-	 * @return bool
69
-	 */
70
-	public function moveMount($target) {
71
-		$storage = $this->storagesService->getStorage($this->numericStorageId);
72
-		// remove "/$user/files" prefix
73
-		$targetParts = explode('/', trim($target, '/'), 3);
74
-		$storage->setMountPoint($targetParts[2]);
75
-		$this->storagesService->updateStorage($storage);
76
-		$this->setMountPoint($target);
77
-		return true;
78
-	}
64
+    /**
65
+     * Move the mount point to $target
66
+     *
67
+     * @param string $target the target mount point
68
+     * @return bool
69
+     */
70
+    public function moveMount($target) {
71
+        $storage = $this->storagesService->getStorage($this->numericStorageId);
72
+        // remove "/$user/files" prefix
73
+        $targetParts = explode('/', trim($target, '/'), 3);
74
+        $storage->setMountPoint($targetParts[2]);
75
+        $this->storagesService->updateStorage($storage);
76
+        $this->setMountPoint($target);
77
+        return true;
78
+    }
79 79
 
80
-	/**
81
-	 * Remove the mount points
82
-	 *
83
-	 * @return bool
84
-	 */
85
-	public function removeMount() {
86
-		$this->storagesService->removeStorage($this->numericStorageId);
87
-		return true;
88
-	}
80
+    /**
81
+     * Remove the mount points
82
+     *
83
+     * @return bool
84
+     */
85
+    public function removeMount() {
86
+        $this->storagesService->removeStorage($this->numericStorageId);
87
+        return true;
88
+    }
89 89
 
90
-	/**
91
-	 * Returns true
92
-	 * 
93
-	 * @param string $target unused
94
-	 * @return bool true
95
-	 */
96
-	public function isTargetAllowed($target) {
97
-		// note: home storage check already done in View
98
-		return true;
99
-	}
90
+    /**
91
+     * Returns true
92
+     * 
93
+     * @param string $target unused
94
+     * @return bool true
95
+     */
96
+    public function isTargetAllowed($target) {
97
+        // note: home storage check already done in View
98
+        return true;
99
+    }
100 100
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Mount.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -29,54 +29,54 @@
 block discarded – undo
29 29
 
30 30
 class Mount extends MountPoint implements MoveableMount {
31 31
 
32
-	/**
33
-	 * @var \OCA\Files_Sharing\External\Manager
34
-	 */
35
-	protected $manager;
32
+    /**
33
+     * @var \OCA\Files_Sharing\External\Manager
34
+     */
35
+    protected $manager;
36 36
 
37
-	/**
38
-	 * @param string|\OC\Files\Storage\Storage $storage
39
-	 * @param string $mountpoint
40
-	 * @param array $options
41
-	 * @param \OCA\Files_Sharing\External\Manager $manager
42
-	 * @param \OC\Files\Storage\StorageFactory $loader
43
-	 */
44
-	public function __construct($storage, $mountpoint, $options, $manager, $loader = null) {
45
-		parent::__construct($storage, $mountpoint, $options, $loader);
46
-		$this->manager = $manager;
47
-	}
37
+    /**
38
+     * @param string|\OC\Files\Storage\Storage $storage
39
+     * @param string $mountpoint
40
+     * @param array $options
41
+     * @param \OCA\Files_Sharing\External\Manager $manager
42
+     * @param \OC\Files\Storage\StorageFactory $loader
43
+     */
44
+    public function __construct($storage, $mountpoint, $options, $manager, $loader = null) {
45
+        parent::__construct($storage, $mountpoint, $options, $loader);
46
+        $this->manager = $manager;
47
+    }
48 48
 
49
-	/**
50
-	 * Move the mount point to $target
51
-	 *
52
-	 * @param string $target the target mount point
53
-	 * @return bool
54
-	 */
55
-	public function moveMount($target) {
56
-		$result = $this->manager->setMountPoint($this->mountPoint, $target);
57
-		$this->setMountPoint($target);
49
+    /**
50
+     * Move the mount point to $target
51
+     *
52
+     * @param string $target the target mount point
53
+     * @return bool
54
+     */
55
+    public function moveMount($target) {
56
+        $result = $this->manager->setMountPoint($this->mountPoint, $target);
57
+        $this->setMountPoint($target);
58 58
 
59
-		return $result;
60
-	}
59
+        return $result;
60
+    }
61 61
 
62
-	/**
63
-	 * Remove the mount points
64
-	 *
65
-	 * @return mixed
66
-	 * @return bool
67
-	 */
68
-	public function removeMount() {
69
-		return $this->manager->removeShare($this->mountPoint);
70
-	}
62
+    /**
63
+     * Remove the mount points
64
+     *
65
+     * @return mixed
66
+     * @return bool
67
+     */
68
+    public function removeMount() {
69
+        return $this->manager->removeShare($this->mountPoint);
70
+    }
71 71
 
72
-	/**
73
-	 * Returns true
74
-	 * 
75
-	 * @param string $target unused
76
-	 * @return bool true
77
-	 */
78
-	public function isTargetAllowed($target) {
79
-		// note: home storage check already done in View
80
-		return true;
81
-	}
72
+    /**
73
+     * Returns true
74
+     * 
75
+     * @param string $target unused
76
+     * @return bool true
77
+     */
78
+    public function isTargetAllowed($target) {
79
+        // note: home storage check already done in View
80
+        return true;
81
+    }
82 82
 }
Please login to merge, or discard this patch.
lib/private/Files/Config/UserMountCache.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 
25 25
 namespace OC\Files\Config;
26 26
 
27
-use OCA\Files_Sharing\SharedMount;
28 27
 use OCP\DB\QueryBuilder\IQueryBuilder;
29 28
 use OCP\Files\Config\ICachedMountInfo;
30 29
 use OCP\Files\Config\IUserMountCache;
Please login to merge, or discard this patch.
Indentation   +287 added lines, -287 removed lines patch added patch discarded remove patch
@@ -41,291 +41,291 @@
 block discarded – undo
41 41
  * Cache mounts points per user in the cache so we can easilly look them up
42 42
  */
43 43
 class UserMountCache implements IUserMountCache {
44
-	/**
45
-	 * @var IDBConnection
46
-	 */
47
-	private $connection;
48
-
49
-	/**
50
-	 * @var IUserManager
51
-	 */
52
-	private $userManager;
53
-
54
-	/**
55
-	 * Cached mount info.
56
-	 * Map of $userId to ICachedMountInfo.
57
-	 *
58
-	 * @var ICache
59
-	 **/
60
-	private $mountsForUsers;
61
-
62
-	/**
63
-	 * @var ILogger
64
-	 */
65
-	private $logger;
66
-
67
-	/**
68
-	 * @var ICache
69
-	 */
70
-	private $cacheInfoCache;
71
-
72
-	/**
73
-	 * UserMountCache constructor.
74
-	 *
75
-	 * @param IDBConnection $connection
76
-	 * @param IUserManager $userManager
77
-	 * @param ILogger $logger
78
-	 */
79
-	public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
80
-		$this->connection = $connection;
81
-		$this->userManager = $userManager;
82
-		$this->logger = $logger;
83
-		$this->cacheInfoCache = new CappedMemoryCache();
84
-		$this->mountsForUsers = new CappedMemoryCache();
85
-	}
86
-
87
-	public function registerMounts(IUser $user, array $mounts) {
88
-		/** @var ICachedMountInfo[] $newMounts */
89
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
90
-			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
91
-			if ($mount->getStorageRootId() === -1) {
92
-				return null;
93
-			} else {
94
-				return new LazyStorageMountInfo($user, $mount);
95
-			}
96
-		}, $mounts);
97
-		$newMounts = array_values(array_filter($newMounts));
98
-
99
-		$cachedMounts = $this->getMountsForUser($user);
100
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
101
-			// since we are only looking for mounts for a specific user comparing on root id is enough
102
-			return $mount1->getRootId() - $mount2->getRootId();
103
-		};
104
-
105
-		/** @var ICachedMountInfo[] $addedMounts */
106
-		$addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
107
-		/** @var ICachedMountInfo[] $removedMounts */
108
-		$removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
109
-
110
-		$changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
111
-
112
-		foreach ($addedMounts as $mount) {
113
-			$this->addToCache($mount);
114
-			$this->mountsForUsers[$user->getUID()][] = $mount;
115
-		}
116
-		foreach ($removedMounts as $mount) {
117
-			$this->removeFromCache($mount);
118
-			$index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
119
-			unset($this->mountsForUsers[$user->getUID()][$index]);
120
-		}
121
-		foreach ($changedMounts as $mount) {
122
-			$this->updateCachedMount($mount);
123
-		}
124
-	}
125
-
126
-	/**
127
-	 * @param ICachedMountInfo[] $newMounts
128
-	 * @param ICachedMountInfo[] $cachedMounts
129
-	 * @return ICachedMountInfo[]
130
-	 */
131
-	private function findChangedMounts(array $newMounts, array $cachedMounts) {
132
-		$changed = [];
133
-		foreach ($newMounts as $newMount) {
134
-			foreach ($cachedMounts as $cachedMount) {
135
-				if (
136
-					$newMount->getRootId() === $cachedMount->getRootId() &&
137
-					(
138
-						$newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
139
-						$newMount->getStorageId() !== $cachedMount->getStorageId() ||
140
-						$newMount->getMountId() !== $cachedMount->getMountId()
141
-					)
142
-				) {
143
-					$changed[] = $newMount;
144
-				}
145
-			}
146
-		}
147
-		return $changed;
148
-	}
149
-
150
-	private function addToCache(ICachedMountInfo $mount) {
151
-		if ($mount->getStorageId() !== -1) {
152
-			$this->connection->insertIfNotExist('*PREFIX*mounts', [
153
-				'storage_id' => $mount->getStorageId(),
154
-				'root_id' => $mount->getRootId(),
155
-				'user_id' => $mount->getUser()->getUID(),
156
-				'mount_point' => $mount->getMountPoint(),
157
-				'mount_id' => $mount->getMountId()
158
-			], ['root_id', 'user_id']);
159
-		} else {
160
-			// in some cases this is legitimate, like orphaned shares
161
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
162
-		}
163
-	}
164
-
165
-	private function updateCachedMount(ICachedMountInfo $mount) {
166
-		$builder = $this->connection->getQueryBuilder();
167
-
168
-		$query = $builder->update('mounts')
169
-			->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
170
-			->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
171
-			->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
172
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
173
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
174
-
175
-		$query->execute();
176
-	}
177
-
178
-	private function removeFromCache(ICachedMountInfo $mount) {
179
-		$builder = $this->connection->getQueryBuilder();
180
-
181
-		$query = $builder->delete('mounts')
182
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
183
-			->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
184
-		$query->execute();
185
-	}
186
-
187
-	private function dbRowToMountInfo(array $row) {
188
-		$user = $this->userManager->get($row['user_id']);
189
-		if (is_null($user)) {
190
-			return null;
191
-		}
192
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:'');
193
-	}
194
-
195
-	/**
196
-	 * @param IUser $user
197
-	 * @return ICachedMountInfo[]
198
-	 */
199
-	public function getMountsForUser(IUser $user) {
200
-		if (!isset($this->mountsForUsers[$user->getUID()])) {
201
-			$builder = $this->connection->getQueryBuilder();
202
-			$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
203
-				->from('mounts', 'm')
204
-				->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
205
-				->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
206
-
207
-			$rows = $query->execute()->fetchAll();
208
-
209
-			$this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
210
-		}
211
-		return $this->mountsForUsers[$user->getUID()];
212
-	}
213
-
214
-	/**
215
-	 * @param int $numericStorageId
216
-	 * @param string|null $user limit the results to a single user
217
-	 * @return CachedMountInfo[]
218
-	 */
219
-	public function getMountsForStorageId($numericStorageId, $user = null) {
220
-		$builder = $this->connection->getQueryBuilder();
221
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
222
-			->from('mounts', 'm')
223
-			->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid'))
224
-			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
225
-
226
-		if ($user) {
227
-			$query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
228
-		}
229
-
230
-		$rows = $query->execute()->fetchAll();
231
-
232
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
233
-	}
234
-
235
-	/**
236
-	 * @param int $rootFileId
237
-	 * @return CachedMountInfo[]
238
-	 */
239
-	public function getMountsForRootId($rootFileId) {
240
-		$builder = $this->connection->getQueryBuilder();
241
-		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
242
-			->from('mounts', 'm')
243
-			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
244
-			->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
245
-
246
-		$rows = $query->execute()->fetchAll();
247
-
248
-		return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
249
-	}
250
-
251
-	/**
252
-	 * @param $fileId
253
-	 * @return array
254
-	 * @throws \OCP\Files\NotFoundException
255
-	 */
256
-	private function getCacheInfoFromFileId($fileId) {
257
-		if (!isset($this->cacheInfoCache[$fileId])) {
258
-			$builder = $this->connection->getQueryBuilder();
259
-			$query = $builder->select('storage', 'path', 'mimetype')
260
-				->from('filecache')
261
-				->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
262
-
263
-			$row = $query->execute()->fetch();
264
-			if (is_array($row)) {
265
-				$this->cacheInfoCache[$fileId] = [
266
-					(int)$row['storage'],
267
-					$row['path'],
268
-					(int)$row['mimetype']
269
-				];
270
-			} else {
271
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
272
-			}
273
-		}
274
-		return $this->cacheInfoCache[$fileId];
275
-	}
276
-
277
-	/**
278
-	 * @param int $fileId
279
-	 * @param string|null $user optionally restrict the results to a single user
280
-	 * @return ICachedMountInfo[]
281
-	 * @since 9.0.0
282
-	 */
283
-	public function getMountsForFileId($fileId, $user = null) {
284
-		try {
285
-			list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
286
-		} catch (NotFoundException $e) {
287
-			return [];
288
-		}
289
-		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
290
-
291
-		// filter mounts that are from the same storage but a different directory
292
-		return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
293
-			if ($fileId === $mount->getRootId()) {
294
-				return true;
295
-			}
296
-			$internalMountPath = $mount->getRootInternalPath();
297
-
298
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
299
-		});
300
-	}
301
-
302
-	/**
303
-	 * Remove all cached mounts for a user
304
-	 *
305
-	 * @param IUser $user
306
-	 */
307
-	public function removeUserMounts(IUser $user) {
308
-		$builder = $this->connection->getQueryBuilder();
309
-
310
-		$query = $builder->delete('mounts')
311
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
312
-		$query->execute();
313
-	}
314
-
315
-	public function removeUserStorageMount($storageId, $userId) {
316
-		$builder = $this->connection->getQueryBuilder();
317
-
318
-		$query = $builder->delete('mounts')
319
-			->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
320
-			->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
321
-		$query->execute();
322
-	}
323
-
324
-	public function remoteStorageMounts($storageId) {
325
-		$builder = $this->connection->getQueryBuilder();
326
-
327
-		$query = $builder->delete('mounts')
328
-			->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
329
-		$query->execute();
330
-	}
44
+    /**
45
+     * @var IDBConnection
46
+     */
47
+    private $connection;
48
+
49
+    /**
50
+     * @var IUserManager
51
+     */
52
+    private $userManager;
53
+
54
+    /**
55
+     * Cached mount info.
56
+     * Map of $userId to ICachedMountInfo.
57
+     *
58
+     * @var ICache
59
+     **/
60
+    private $mountsForUsers;
61
+
62
+    /**
63
+     * @var ILogger
64
+     */
65
+    private $logger;
66
+
67
+    /**
68
+     * @var ICache
69
+     */
70
+    private $cacheInfoCache;
71
+
72
+    /**
73
+     * UserMountCache constructor.
74
+     *
75
+     * @param IDBConnection $connection
76
+     * @param IUserManager $userManager
77
+     * @param ILogger $logger
78
+     */
79
+    public function __construct(IDBConnection $connection, IUserManager $userManager, ILogger $logger) {
80
+        $this->connection = $connection;
81
+        $this->userManager = $userManager;
82
+        $this->logger = $logger;
83
+        $this->cacheInfoCache = new CappedMemoryCache();
84
+        $this->mountsForUsers = new CappedMemoryCache();
85
+    }
86
+
87
+    public function registerMounts(IUser $user, array $mounts) {
88
+        /** @var ICachedMountInfo[] $newMounts */
89
+        $newMounts = array_map(function (IMountPoint $mount) use ($user) {
90
+            // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
91
+            if ($mount->getStorageRootId() === -1) {
92
+                return null;
93
+            } else {
94
+                return new LazyStorageMountInfo($user, $mount);
95
+            }
96
+        }, $mounts);
97
+        $newMounts = array_values(array_filter($newMounts));
98
+
99
+        $cachedMounts = $this->getMountsForUser($user);
100
+        $mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
101
+            // since we are only looking for mounts for a specific user comparing on root id is enough
102
+            return $mount1->getRootId() - $mount2->getRootId();
103
+        };
104
+
105
+        /** @var ICachedMountInfo[] $addedMounts */
106
+        $addedMounts = array_udiff($newMounts, $cachedMounts, $mountDiff);
107
+        /** @var ICachedMountInfo[] $removedMounts */
108
+        $removedMounts = array_udiff($cachedMounts, $newMounts, $mountDiff);
109
+
110
+        $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
111
+
112
+        foreach ($addedMounts as $mount) {
113
+            $this->addToCache($mount);
114
+            $this->mountsForUsers[$user->getUID()][] = $mount;
115
+        }
116
+        foreach ($removedMounts as $mount) {
117
+            $this->removeFromCache($mount);
118
+            $index = array_search($mount, $this->mountsForUsers[$user->getUID()]);
119
+            unset($this->mountsForUsers[$user->getUID()][$index]);
120
+        }
121
+        foreach ($changedMounts as $mount) {
122
+            $this->updateCachedMount($mount);
123
+        }
124
+    }
125
+
126
+    /**
127
+     * @param ICachedMountInfo[] $newMounts
128
+     * @param ICachedMountInfo[] $cachedMounts
129
+     * @return ICachedMountInfo[]
130
+     */
131
+    private function findChangedMounts(array $newMounts, array $cachedMounts) {
132
+        $changed = [];
133
+        foreach ($newMounts as $newMount) {
134
+            foreach ($cachedMounts as $cachedMount) {
135
+                if (
136
+                    $newMount->getRootId() === $cachedMount->getRootId() &&
137
+                    (
138
+                        $newMount->getMountPoint() !== $cachedMount->getMountPoint() ||
139
+                        $newMount->getStorageId() !== $cachedMount->getStorageId() ||
140
+                        $newMount->getMountId() !== $cachedMount->getMountId()
141
+                    )
142
+                ) {
143
+                    $changed[] = $newMount;
144
+                }
145
+            }
146
+        }
147
+        return $changed;
148
+    }
149
+
150
+    private function addToCache(ICachedMountInfo $mount) {
151
+        if ($mount->getStorageId() !== -1) {
152
+            $this->connection->insertIfNotExist('*PREFIX*mounts', [
153
+                'storage_id' => $mount->getStorageId(),
154
+                'root_id' => $mount->getRootId(),
155
+                'user_id' => $mount->getUser()->getUID(),
156
+                'mount_point' => $mount->getMountPoint(),
157
+                'mount_id' => $mount->getMountId()
158
+            ], ['root_id', 'user_id']);
159
+        } else {
160
+            // in some cases this is legitimate, like orphaned shares
161
+            $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
162
+        }
163
+    }
164
+
165
+    private function updateCachedMount(ICachedMountInfo $mount) {
166
+        $builder = $this->connection->getQueryBuilder();
167
+
168
+        $query = $builder->update('mounts')
169
+            ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
170
+            ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
171
+            ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
172
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
173
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
174
+
175
+        $query->execute();
176
+    }
177
+
178
+    private function removeFromCache(ICachedMountInfo $mount) {
179
+        $builder = $this->connection->getQueryBuilder();
180
+
181
+        $query = $builder->delete('mounts')
182
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
183
+            ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
184
+        $query->execute();
185
+    }
186
+
187
+    private function dbRowToMountInfo(array $row) {
188
+        $user = $this->userManager->get($row['user_id']);
189
+        if (is_null($user)) {
190
+            return null;
191
+        }
192
+        return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:'');
193
+    }
194
+
195
+    /**
196
+     * @param IUser $user
197
+     * @return ICachedMountInfo[]
198
+     */
199
+    public function getMountsForUser(IUser $user) {
200
+        if (!isset($this->mountsForUsers[$user->getUID()])) {
201
+            $builder = $this->connection->getQueryBuilder();
202
+            $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
203
+                ->from('mounts', 'm')
204
+                ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
205
+                ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($user->getUID())));
206
+
207
+            $rows = $query->execute()->fetchAll();
208
+
209
+            $this->mountsForUsers[$user->getUID()] = array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
210
+        }
211
+        return $this->mountsForUsers[$user->getUID()];
212
+    }
213
+
214
+    /**
215
+     * @param int $numericStorageId
216
+     * @param string|null $user limit the results to a single user
217
+     * @return CachedMountInfo[]
218
+     */
219
+    public function getMountsForStorageId($numericStorageId, $user = null) {
220
+        $builder = $this->connection->getQueryBuilder();
221
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
222
+            ->from('mounts', 'm')
223
+            ->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid'))
224
+            ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
225
+
226
+        if ($user) {
227
+            $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
228
+        }
229
+
230
+        $rows = $query->execute()->fetchAll();
231
+
232
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
233
+    }
234
+
235
+    /**
236
+     * @param int $rootFileId
237
+     * @return CachedMountInfo[]
238
+     */
239
+    public function getMountsForRootId($rootFileId) {
240
+        $builder = $this->connection->getQueryBuilder();
241
+        $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
242
+            ->from('mounts', 'm')
243
+            ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
244
+            ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
245
+
246
+        $rows = $query->execute()->fetchAll();
247
+
248
+        return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
249
+    }
250
+
251
+    /**
252
+     * @param $fileId
253
+     * @return array
254
+     * @throws \OCP\Files\NotFoundException
255
+     */
256
+    private function getCacheInfoFromFileId($fileId) {
257
+        if (!isset($this->cacheInfoCache[$fileId])) {
258
+            $builder = $this->connection->getQueryBuilder();
259
+            $query = $builder->select('storage', 'path', 'mimetype')
260
+                ->from('filecache')
261
+                ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
262
+
263
+            $row = $query->execute()->fetch();
264
+            if (is_array($row)) {
265
+                $this->cacheInfoCache[$fileId] = [
266
+                    (int)$row['storage'],
267
+                    $row['path'],
268
+                    (int)$row['mimetype']
269
+                ];
270
+            } else {
271
+                throw new NotFoundException('File with id "' . $fileId . '" not found');
272
+            }
273
+        }
274
+        return $this->cacheInfoCache[$fileId];
275
+    }
276
+
277
+    /**
278
+     * @param int $fileId
279
+     * @param string|null $user optionally restrict the results to a single user
280
+     * @return ICachedMountInfo[]
281
+     * @since 9.0.0
282
+     */
283
+    public function getMountsForFileId($fileId, $user = null) {
284
+        try {
285
+            list($storageId, $internalPath) = $this->getCacheInfoFromFileId($fileId);
286
+        } catch (NotFoundException $e) {
287
+            return [];
288
+        }
289
+        $mountsForStorage = $this->getMountsForStorageId($storageId, $user);
290
+
291
+        // filter mounts that are from the same storage but a different directory
292
+        return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
293
+            if ($fileId === $mount->getRootId()) {
294
+                return true;
295
+            }
296
+            $internalMountPath = $mount->getRootInternalPath();
297
+
298
+            return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
299
+        });
300
+    }
301
+
302
+    /**
303
+     * Remove all cached mounts for a user
304
+     *
305
+     * @param IUser $user
306
+     */
307
+    public function removeUserMounts(IUser $user) {
308
+        $builder = $this->connection->getQueryBuilder();
309
+
310
+        $query = $builder->delete('mounts')
311
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
312
+        $query->execute();
313
+    }
314
+
315
+    public function removeUserStorageMount($storageId, $userId) {
316
+        $builder = $this->connection->getQueryBuilder();
317
+
318
+        $query = $builder->delete('mounts')
319
+            ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
320
+            ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
321
+        $query->execute();
322
+    }
323
+
324
+    public function remoteStorageMounts($storageId) {
325
+        $builder = $this->connection->getQueryBuilder();
326
+
327
+        $query = $builder->delete('mounts')
328
+            ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
329
+        $query->execute();
330
+    }
331 331
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
 
87 87
 	public function registerMounts(IUser $user, array $mounts) {
88 88
 		/** @var ICachedMountInfo[] $newMounts */
89
-		$newMounts = array_map(function (IMountPoint $mount) use ($user) {
89
+		$newMounts = array_map(function(IMountPoint $mount) use ($user) {
90 90
 			// filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
91 91
 			if ($mount->getStorageRootId() === -1) {
92 92
 				return null;
@@ -97,7 +97,7 @@  discard block
 block discarded – undo
97 97
 		$newMounts = array_values(array_filter($newMounts));
98 98
 
99 99
 		$cachedMounts = $this->getMountsForUser($user);
100
-		$mountDiff = function (ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
100
+		$mountDiff = function(ICachedMountInfo $mount1, ICachedMountInfo $mount2) {
101 101
 			// since we are only looking for mounts for a specific user comparing on root id is enough
102 102
 			return $mount1->getRootId() - $mount2->getRootId();
103 103
 		};
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 			], ['root_id', 'user_id']);
159 159
 		} else {
160 160
 			// in some cases this is legitimate, like orphaned shares
161
-			$this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
161
+			$this->logger->debug('Could not get storage info for mount at '.$mount->getMountPoint());
162 162
 		}
163 163
 	}
164 164
 
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 		if (is_null($user)) {
190 190
 			return null;
191 191
 		}
192
-		return new CachedMountInfo($user, (int)$row['storage_id'], (int)$row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path'])? $row['path']:'');
192
+		return new CachedMountInfo($user, (int) $row['storage_id'], (int) $row['root_id'], $row['mount_point'], $row['mount_id'], isset($row['path']) ? $row['path'] : '');
193 193
 	}
194 194
 
195 195
 	/**
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 		$builder = $this->connection->getQueryBuilder();
221 221
 		$query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path')
222 222
 			->from('mounts', 'm')
223
-			->innerJoin('m', 'filecache', 'f' , $builder->expr()->eq('m.root_id', 'f.fileid'))
223
+			->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
224 224
 			->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
225 225
 
226 226
 		if ($user) {
@@ -263,12 +263,12 @@  discard block
 block discarded – undo
263 263
 			$row = $query->execute()->fetch();
264 264
 			if (is_array($row)) {
265 265
 				$this->cacheInfoCache[$fileId] = [
266
-					(int)$row['storage'],
266
+					(int) $row['storage'],
267 267
 					$row['path'],
268
-					(int)$row['mimetype']
268
+					(int) $row['mimetype']
269 269
 				];
270 270
 			} else {
271
-				throw new NotFoundException('File with id "' . $fileId . '" not found');
271
+				throw new NotFoundException('File with id "'.$fileId.'" not found');
272 272
 			}
273 273
 		}
274 274
 		return $this->cacheInfoCache[$fileId];
@@ -289,13 +289,13 @@  discard block
 block discarded – undo
289 289
 		$mountsForStorage = $this->getMountsForStorageId($storageId, $user);
290 290
 
291 291
 		// filter mounts that are from the same storage but a different directory
292
-		return array_filter($mountsForStorage, function (ICachedMountInfo $mount) use ($internalPath, $fileId) {
292
+		return array_filter($mountsForStorage, function(ICachedMountInfo $mount) use ($internalPath, $fileId) {
293 293
 			if ($fileId === $mount->getRootId()) {
294 294
 				return true;
295 295
 			}
296 296
 			$internalMountPath = $mount->getRootInternalPath();
297 297
 
298
-			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
298
+			return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath.'/';
299 299
 		});
300 300
 	}
301 301
 
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 2 patches
Indentation   +1377 added lines, -1377 removed lines patch added patch discarded remove patch
@@ -56,1405 +56,1405 @@
 block discarded – undo
56 56
  */
57 57
 class Manager implements IManager {
58 58
 
59
-	/** @var IProviderFactory */
60
-	private $factory;
61
-	/** @var ILogger */
62
-	private $logger;
63
-	/** @var IConfig */
64
-	private $config;
65
-	/** @var ISecureRandom */
66
-	private $secureRandom;
67
-	/** @var IHasher */
68
-	private $hasher;
69
-	/** @var IMountManager */
70
-	private $mountManager;
71
-	/** @var IGroupManager */
72
-	private $groupManager;
73
-	/** @var IL10N */
74
-	private $l;
75
-	/** @var IUserManager */
76
-	private $userManager;
77
-	/** @var IRootFolder */
78
-	private $rootFolder;
79
-	/** @var CappedMemoryCache */
80
-	private $sharingDisabledForUsersCache;
81
-	/** @var EventDispatcher */
82
-	private $eventDispatcher;
83
-	/** @var LegacyHooks */
84
-	private $legacyHooks;
85
-
86
-
87
-	/**
88
-	 * Manager constructor.
89
-	 *
90
-	 * @param ILogger $logger
91
-	 * @param IConfig $config
92
-	 * @param ISecureRandom $secureRandom
93
-	 * @param IHasher $hasher
94
-	 * @param IMountManager $mountManager
95
-	 * @param IGroupManager $groupManager
96
-	 * @param IL10N $l
97
-	 * @param IProviderFactory $factory
98
-	 * @param IUserManager $userManager
99
-	 * @param IRootFolder $rootFolder
100
-	 * @param EventDispatcher $eventDispatcher
101
-	 */
102
-	public function __construct(
103
-			ILogger $logger,
104
-			IConfig $config,
105
-			ISecureRandom $secureRandom,
106
-			IHasher $hasher,
107
-			IMountManager $mountManager,
108
-			IGroupManager $groupManager,
109
-			IL10N $l,
110
-			IProviderFactory $factory,
111
-			IUserManager $userManager,
112
-			IRootFolder $rootFolder,
113
-			EventDispatcher $eventDispatcher
114
-	) {
115
-		$this->logger = $logger;
116
-		$this->config = $config;
117
-		$this->secureRandom = $secureRandom;
118
-		$this->hasher = $hasher;
119
-		$this->mountManager = $mountManager;
120
-		$this->groupManager = $groupManager;
121
-		$this->l = $l;
122
-		$this->factory = $factory;
123
-		$this->userManager = $userManager;
124
-		$this->rootFolder = $rootFolder;
125
-		$this->eventDispatcher = $eventDispatcher;
126
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
127
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
128
-	}
129
-
130
-	/**
131
-	 * Convert from a full share id to a tuple (providerId, shareId)
132
-	 *
133
-	 * @param string $id
134
-	 * @return string[]
135
-	 */
136
-	private function splitFullId($id) {
137
-		return explode(':', $id, 2);
138
-	}
139
-
140
-	/**
141
-	 * Verify if a password meets all requirements
142
-	 *
143
-	 * @param string $password
144
-	 * @throws \Exception
145
-	 */
146
-	protected function verifyPassword($password) {
147
-		if ($password === null) {
148
-			// No password is set, check if this is allowed.
149
-			if ($this->shareApiLinkEnforcePassword()) {
150
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
151
-			}
152
-
153
-			return;
154
-		}
155
-
156
-		// Let others verify the password
157
-		try {
158
-			$event = new GenericEvent($password);
159
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
160
-		} catch (HintException $e) {
161
-			throw new \Exception($e->getHint());
162
-		}
163
-	}
164
-
165
-	/**
166
-	 * Check for generic requirements before creating a share
167
-	 *
168
-	 * @param \OCP\Share\IShare $share
169
-	 * @throws \InvalidArgumentException
170
-	 * @throws GenericShareException
171
-	 */
172
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
173
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
174
-			// We expect a valid user as sharedWith for user shares
175
-			if (!$this->userManager->userExists($share->getSharedWith())) {
176
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
177
-			}
178
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
179
-			// We expect a valid group as sharedWith for group shares
180
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
181
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
182
-			}
183
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
184
-			if ($share->getSharedWith() !== null) {
185
-				throw new \InvalidArgumentException('SharedWith should be empty');
186
-			}
187
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
-			if ($share->getSharedWith() === null) {
189
-				throw new \InvalidArgumentException('SharedWith should not be empty');
190
-			}
191
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
-			if ($share->getSharedWith() === null) {
193
-				throw new \InvalidArgumentException('SharedWith should not be empty');
194
-			}
195
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
196
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
197
-			if ($circle === null) {
198
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
199
-			}
200
-		} else {
201
-			// We can't handle other types yet
202
-			throw new \InvalidArgumentException('unknown share type');
203
-		}
204
-
205
-		// Verify the initiator of the share is set
206
-		if ($share->getSharedBy() === null) {
207
-			throw new \InvalidArgumentException('SharedBy should be set');
208
-		}
209
-
210
-		// Cannot share with yourself
211
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
212
-			$share->getSharedWith() === $share->getSharedBy()) {
213
-			throw new \InvalidArgumentException('Can\'t share with yourself');
214
-		}
215
-
216
-		// The path should be set
217
-		if ($share->getNode() === null) {
218
-			throw new \InvalidArgumentException('Path should be set');
219
-		}
220
-
221
-		// And it should be a file or a folder
222
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
223
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
224
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
225
-		}
226
-
227
-		// And you can't share your rootfolder
228
-		if ($this->userManager->userExists($share->getSharedBy())) {
229
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
230
-		} else {
231
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
232
-		}
233
-		if ($sharedPath === $share->getNode()->getPath()) {
234
-			throw new \InvalidArgumentException('You can\'t share your root folder');
235
-		}
236
-
237
-		// Check if we actually have share permissions
238
-		if (!$share->getNode()->isShareable()) {
239
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
240
-			throw new GenericShareException($message_t, $message_t, 404);
241
-		}
242
-
243
-		// Permissions should be set
244
-		if ($share->getPermissions() === null) {
245
-			throw new \InvalidArgumentException('A share requires permissions');
246
-		}
247
-
248
-		/*
59
+    /** @var IProviderFactory */
60
+    private $factory;
61
+    /** @var ILogger */
62
+    private $logger;
63
+    /** @var IConfig */
64
+    private $config;
65
+    /** @var ISecureRandom */
66
+    private $secureRandom;
67
+    /** @var IHasher */
68
+    private $hasher;
69
+    /** @var IMountManager */
70
+    private $mountManager;
71
+    /** @var IGroupManager */
72
+    private $groupManager;
73
+    /** @var IL10N */
74
+    private $l;
75
+    /** @var IUserManager */
76
+    private $userManager;
77
+    /** @var IRootFolder */
78
+    private $rootFolder;
79
+    /** @var CappedMemoryCache */
80
+    private $sharingDisabledForUsersCache;
81
+    /** @var EventDispatcher */
82
+    private $eventDispatcher;
83
+    /** @var LegacyHooks */
84
+    private $legacyHooks;
85
+
86
+
87
+    /**
88
+     * Manager constructor.
89
+     *
90
+     * @param ILogger $logger
91
+     * @param IConfig $config
92
+     * @param ISecureRandom $secureRandom
93
+     * @param IHasher $hasher
94
+     * @param IMountManager $mountManager
95
+     * @param IGroupManager $groupManager
96
+     * @param IL10N $l
97
+     * @param IProviderFactory $factory
98
+     * @param IUserManager $userManager
99
+     * @param IRootFolder $rootFolder
100
+     * @param EventDispatcher $eventDispatcher
101
+     */
102
+    public function __construct(
103
+            ILogger $logger,
104
+            IConfig $config,
105
+            ISecureRandom $secureRandom,
106
+            IHasher $hasher,
107
+            IMountManager $mountManager,
108
+            IGroupManager $groupManager,
109
+            IL10N $l,
110
+            IProviderFactory $factory,
111
+            IUserManager $userManager,
112
+            IRootFolder $rootFolder,
113
+            EventDispatcher $eventDispatcher
114
+    ) {
115
+        $this->logger = $logger;
116
+        $this->config = $config;
117
+        $this->secureRandom = $secureRandom;
118
+        $this->hasher = $hasher;
119
+        $this->mountManager = $mountManager;
120
+        $this->groupManager = $groupManager;
121
+        $this->l = $l;
122
+        $this->factory = $factory;
123
+        $this->userManager = $userManager;
124
+        $this->rootFolder = $rootFolder;
125
+        $this->eventDispatcher = $eventDispatcher;
126
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
127
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
128
+    }
129
+
130
+    /**
131
+     * Convert from a full share id to a tuple (providerId, shareId)
132
+     *
133
+     * @param string $id
134
+     * @return string[]
135
+     */
136
+    private function splitFullId($id) {
137
+        return explode(':', $id, 2);
138
+    }
139
+
140
+    /**
141
+     * Verify if a password meets all requirements
142
+     *
143
+     * @param string $password
144
+     * @throws \Exception
145
+     */
146
+    protected function verifyPassword($password) {
147
+        if ($password === null) {
148
+            // No password is set, check if this is allowed.
149
+            if ($this->shareApiLinkEnforcePassword()) {
150
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
151
+            }
152
+
153
+            return;
154
+        }
155
+
156
+        // Let others verify the password
157
+        try {
158
+            $event = new GenericEvent($password);
159
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
160
+        } catch (HintException $e) {
161
+            throw new \Exception($e->getHint());
162
+        }
163
+    }
164
+
165
+    /**
166
+     * Check for generic requirements before creating a share
167
+     *
168
+     * @param \OCP\Share\IShare $share
169
+     * @throws \InvalidArgumentException
170
+     * @throws GenericShareException
171
+     */
172
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
173
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
174
+            // We expect a valid user as sharedWith for user shares
175
+            if (!$this->userManager->userExists($share->getSharedWith())) {
176
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
177
+            }
178
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
179
+            // We expect a valid group as sharedWith for group shares
180
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
181
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
182
+            }
183
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
184
+            if ($share->getSharedWith() !== null) {
185
+                throw new \InvalidArgumentException('SharedWith should be empty');
186
+            }
187
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
+            if ($share->getSharedWith() === null) {
189
+                throw new \InvalidArgumentException('SharedWith should not be empty');
190
+            }
191
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
+            if ($share->getSharedWith() === null) {
193
+                throw new \InvalidArgumentException('SharedWith should not be empty');
194
+            }
195
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
196
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
197
+            if ($circle === null) {
198
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
199
+            }
200
+        } else {
201
+            // We can't handle other types yet
202
+            throw new \InvalidArgumentException('unknown share type');
203
+        }
204
+
205
+        // Verify the initiator of the share is set
206
+        if ($share->getSharedBy() === null) {
207
+            throw new \InvalidArgumentException('SharedBy should be set');
208
+        }
209
+
210
+        // Cannot share with yourself
211
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
212
+            $share->getSharedWith() === $share->getSharedBy()) {
213
+            throw new \InvalidArgumentException('Can\'t share with yourself');
214
+        }
215
+
216
+        // The path should be set
217
+        if ($share->getNode() === null) {
218
+            throw new \InvalidArgumentException('Path should be set');
219
+        }
220
+
221
+        // And it should be a file or a folder
222
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
223
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
224
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
225
+        }
226
+
227
+        // And you can't share your rootfolder
228
+        if ($this->userManager->userExists($share->getSharedBy())) {
229
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
230
+        } else {
231
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
232
+        }
233
+        if ($sharedPath === $share->getNode()->getPath()) {
234
+            throw new \InvalidArgumentException('You can\'t share your root folder');
235
+        }
236
+
237
+        // Check if we actually have share permissions
238
+        if (!$share->getNode()->isShareable()) {
239
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
240
+            throw new GenericShareException($message_t, $message_t, 404);
241
+        }
242
+
243
+        // Permissions should be set
244
+        if ($share->getPermissions() === null) {
245
+            throw new \InvalidArgumentException('A share requires permissions');
246
+        }
247
+
248
+        /*
249 249
 		 * Quick fix for #23536
250 250
 		 * Non moveable mount points do not have update and delete permissions
251 251
 		 * while we 'most likely' do have that on the storage.
252 252
 		 */
253
-		$permissions = $share->getNode()->getPermissions();
254
-		$mount = $share->getNode()->getMountPoint();
255
-		if (!($mount instanceof MoveableMount)) {
256
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
257
-		}
258
-
259
-		// Check that we do not share with more permissions than we have
260
-		if ($share->getPermissions() & ~$permissions) {
261
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
262
-			throw new GenericShareException($message_t, $message_t, 404);
263
-		}
264
-
265
-
266
-		// Check that read permissions are always set
267
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
268
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
269
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
270
-		if (!$noReadPermissionRequired &&
271
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
272
-			throw new \InvalidArgumentException('Shares need at least read permissions');
273
-		}
274
-
275
-		if ($share->getNode() instanceof \OCP\Files\File) {
276
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
277
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
278
-				throw new GenericShareException($message_t);
279
-			}
280
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
281
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
282
-				throw new GenericShareException($message_t);
283
-			}
284
-		}
285
-	}
286
-
287
-	/**
288
-	 * Validate if the expiration date fits the system settings
289
-	 *
290
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
291
-	 * @return \OCP\Share\IShare The modified share object
292
-	 * @throws GenericShareException
293
-	 * @throws \InvalidArgumentException
294
-	 * @throws \Exception
295
-	 */
296
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
297
-
298
-		$expirationDate = $share->getExpirationDate();
299
-
300
-		if ($expirationDate !== null) {
301
-			//Make sure the expiration date is a date
302
-			$expirationDate->setTime(0, 0, 0);
303
-
304
-			$date = new \DateTime();
305
-			$date->setTime(0, 0, 0);
306
-			if ($date >= $expirationDate) {
307
-				$message = $this->l->t('Expiration date is in the past');
308
-				throw new GenericShareException($message, $message, 404);
309
-			}
310
-		}
311
-
312
-		// If expiredate is empty set a default one if there is a default
313
-		$fullId = null;
314
-		try {
315
-			$fullId = $share->getFullId();
316
-		} catch (\UnexpectedValueException $e) {
317
-			// This is a new share
318
-		}
319
-
320
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
321
-			$expirationDate = new \DateTime();
322
-			$expirationDate->setTime(0,0,0);
323
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
324
-		}
325
-
326
-		// If we enforce the expiration date check that is does not exceed
327
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
328
-			if ($expirationDate === null) {
329
-				throw new \InvalidArgumentException('Expiration date is enforced');
330
-			}
331
-
332
-			$date = new \DateTime();
333
-			$date->setTime(0, 0, 0);
334
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
335
-			if ($date < $expirationDate) {
336
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
337
-				throw new GenericShareException($message, $message, 404);
338
-			}
339
-		}
340
-
341
-		$accepted = true;
342
-		$message = '';
343
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
344
-			'expirationDate' => &$expirationDate,
345
-			'accepted' => &$accepted,
346
-			'message' => &$message,
347
-			'passwordSet' => $share->getPassword() !== null,
348
-		]);
349
-
350
-		if (!$accepted) {
351
-			throw new \Exception($message);
352
-		}
353
-
354
-		$share->setExpirationDate($expirationDate);
355
-
356
-		return $share;
357
-	}
358
-
359
-	/**
360
-	 * Check for pre share requirements for user shares
361
-	 *
362
-	 * @param \OCP\Share\IShare $share
363
-	 * @throws \Exception
364
-	 */
365
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
366
-		// Check if we can share with group members only
367
-		if ($this->shareWithGroupMembersOnly()) {
368
-			$sharedBy = $this->userManager->get($share->getSharedBy());
369
-			$sharedWith = $this->userManager->get($share->getSharedWith());
370
-			// Verify we can share with this user
371
-			$groups = array_intersect(
372
-					$this->groupManager->getUserGroupIds($sharedBy),
373
-					$this->groupManager->getUserGroupIds($sharedWith)
374
-			);
375
-			if (empty($groups)) {
376
-				throw new \Exception('Only sharing with group members is allowed');
377
-			}
378
-		}
379
-
380
-		/*
253
+        $permissions = $share->getNode()->getPermissions();
254
+        $mount = $share->getNode()->getMountPoint();
255
+        if (!($mount instanceof MoveableMount)) {
256
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
257
+        }
258
+
259
+        // Check that we do not share with more permissions than we have
260
+        if ($share->getPermissions() & ~$permissions) {
261
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
262
+            throw new GenericShareException($message_t, $message_t, 404);
263
+        }
264
+
265
+
266
+        // Check that read permissions are always set
267
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
268
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
269
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
270
+        if (!$noReadPermissionRequired &&
271
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
272
+            throw new \InvalidArgumentException('Shares need at least read permissions');
273
+        }
274
+
275
+        if ($share->getNode() instanceof \OCP\Files\File) {
276
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
277
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
278
+                throw new GenericShareException($message_t);
279
+            }
280
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
281
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
282
+                throw new GenericShareException($message_t);
283
+            }
284
+        }
285
+    }
286
+
287
+    /**
288
+     * Validate if the expiration date fits the system settings
289
+     *
290
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
291
+     * @return \OCP\Share\IShare The modified share object
292
+     * @throws GenericShareException
293
+     * @throws \InvalidArgumentException
294
+     * @throws \Exception
295
+     */
296
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
297
+
298
+        $expirationDate = $share->getExpirationDate();
299
+
300
+        if ($expirationDate !== null) {
301
+            //Make sure the expiration date is a date
302
+            $expirationDate->setTime(0, 0, 0);
303
+
304
+            $date = new \DateTime();
305
+            $date->setTime(0, 0, 0);
306
+            if ($date >= $expirationDate) {
307
+                $message = $this->l->t('Expiration date is in the past');
308
+                throw new GenericShareException($message, $message, 404);
309
+            }
310
+        }
311
+
312
+        // If expiredate is empty set a default one if there is a default
313
+        $fullId = null;
314
+        try {
315
+            $fullId = $share->getFullId();
316
+        } catch (\UnexpectedValueException $e) {
317
+            // This is a new share
318
+        }
319
+
320
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
321
+            $expirationDate = new \DateTime();
322
+            $expirationDate->setTime(0,0,0);
323
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
324
+        }
325
+
326
+        // If we enforce the expiration date check that is does not exceed
327
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
328
+            if ($expirationDate === null) {
329
+                throw new \InvalidArgumentException('Expiration date is enforced');
330
+            }
331
+
332
+            $date = new \DateTime();
333
+            $date->setTime(0, 0, 0);
334
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
335
+            if ($date < $expirationDate) {
336
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
337
+                throw new GenericShareException($message, $message, 404);
338
+            }
339
+        }
340
+
341
+        $accepted = true;
342
+        $message = '';
343
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
344
+            'expirationDate' => &$expirationDate,
345
+            'accepted' => &$accepted,
346
+            'message' => &$message,
347
+            'passwordSet' => $share->getPassword() !== null,
348
+        ]);
349
+
350
+        if (!$accepted) {
351
+            throw new \Exception($message);
352
+        }
353
+
354
+        $share->setExpirationDate($expirationDate);
355
+
356
+        return $share;
357
+    }
358
+
359
+    /**
360
+     * Check for pre share requirements for user shares
361
+     *
362
+     * @param \OCP\Share\IShare $share
363
+     * @throws \Exception
364
+     */
365
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
366
+        // Check if we can share with group members only
367
+        if ($this->shareWithGroupMembersOnly()) {
368
+            $sharedBy = $this->userManager->get($share->getSharedBy());
369
+            $sharedWith = $this->userManager->get($share->getSharedWith());
370
+            // Verify we can share with this user
371
+            $groups = array_intersect(
372
+                    $this->groupManager->getUserGroupIds($sharedBy),
373
+                    $this->groupManager->getUserGroupIds($sharedWith)
374
+            );
375
+            if (empty($groups)) {
376
+                throw new \Exception('Only sharing with group members is allowed');
377
+            }
378
+        }
379
+
380
+        /*
381 381
 		 * TODO: Could be costly, fix
382 382
 		 *
383 383
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
384 384
 		 */
385
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
386
-		$existingShares = $provider->getSharesByPath($share->getNode());
387
-		foreach($existingShares as $existingShare) {
388
-			// Ignore if it is the same share
389
-			try {
390
-				if ($existingShare->getFullId() === $share->getFullId()) {
391
-					continue;
392
-				}
393
-			} catch (\UnexpectedValueException $e) {
394
-				//Shares are not identical
395
-			}
396
-
397
-			// Identical share already existst
398
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
399
-				throw new \Exception('Path already shared with this user');
400
-			}
401
-
402
-			// The share is already shared with this user via a group share
403
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
404
-				$group = $this->groupManager->get($existingShare->getSharedWith());
405
-				if (!is_null($group)) {
406
-					$user = $this->userManager->get($share->getSharedWith());
407
-
408
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
409
-						throw new \Exception('Path already shared with this user');
410
-					}
411
-				}
412
-			}
413
-		}
414
-	}
415
-
416
-	/**
417
-	 * Check for pre share requirements for group shares
418
-	 *
419
-	 * @param \OCP\Share\IShare $share
420
-	 * @throws \Exception
421
-	 */
422
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
423
-		// Verify group shares are allowed
424
-		if (!$this->allowGroupSharing()) {
425
-			throw new \Exception('Group sharing is now allowed');
426
-		}
427
-
428
-		// Verify if the user can share with this group
429
-		if ($this->shareWithGroupMembersOnly()) {
430
-			$sharedBy = $this->userManager->get($share->getSharedBy());
431
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
432
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
433
-				throw new \Exception('Only sharing within your own groups is allowed');
434
-			}
435
-		}
436
-
437
-		/*
385
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
386
+        $existingShares = $provider->getSharesByPath($share->getNode());
387
+        foreach($existingShares as $existingShare) {
388
+            // Ignore if it is the same share
389
+            try {
390
+                if ($existingShare->getFullId() === $share->getFullId()) {
391
+                    continue;
392
+                }
393
+            } catch (\UnexpectedValueException $e) {
394
+                //Shares are not identical
395
+            }
396
+
397
+            // Identical share already existst
398
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
399
+                throw new \Exception('Path already shared with this user');
400
+            }
401
+
402
+            // The share is already shared with this user via a group share
403
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
404
+                $group = $this->groupManager->get($existingShare->getSharedWith());
405
+                if (!is_null($group)) {
406
+                    $user = $this->userManager->get($share->getSharedWith());
407
+
408
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
409
+                        throw new \Exception('Path already shared with this user');
410
+                    }
411
+                }
412
+            }
413
+        }
414
+    }
415
+
416
+    /**
417
+     * Check for pre share requirements for group shares
418
+     *
419
+     * @param \OCP\Share\IShare $share
420
+     * @throws \Exception
421
+     */
422
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
423
+        // Verify group shares are allowed
424
+        if (!$this->allowGroupSharing()) {
425
+            throw new \Exception('Group sharing is now allowed');
426
+        }
427
+
428
+        // Verify if the user can share with this group
429
+        if ($this->shareWithGroupMembersOnly()) {
430
+            $sharedBy = $this->userManager->get($share->getSharedBy());
431
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
432
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
433
+                throw new \Exception('Only sharing within your own groups is allowed');
434
+            }
435
+        }
436
+
437
+        /*
438 438
 		 * TODO: Could be costly, fix
439 439
 		 *
440 440
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
441 441
 		 */
442
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
443
-		$existingShares = $provider->getSharesByPath($share->getNode());
444
-		foreach($existingShares as $existingShare) {
445
-			try {
446
-				if ($existingShare->getFullId() === $share->getFullId()) {
447
-					continue;
448
-				}
449
-			} catch (\UnexpectedValueException $e) {
450
-				//It is a new share so just continue
451
-			}
452
-
453
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
454
-				throw new \Exception('Path already shared with this group');
455
-			}
456
-		}
457
-	}
458
-
459
-	/**
460
-	 * Check for pre share requirements for link shares
461
-	 *
462
-	 * @param \OCP\Share\IShare $share
463
-	 * @throws \Exception
464
-	 */
465
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
466
-		// Are link shares allowed?
467
-		if (!$this->shareApiAllowLinks()) {
468
-			throw new \Exception('Link sharing not allowed');
469
-		}
470
-
471
-		// Link shares by definition can't have share permissions
472
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
473
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
474
-		}
475
-
476
-		// Check if public upload is allowed
477
-		if (!$this->shareApiLinkAllowPublicUpload() &&
478
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
479
-			throw new \InvalidArgumentException('Public upload not allowed');
480
-		}
481
-	}
482
-
483
-	/**
484
-	 * To make sure we don't get invisible link shares we set the parent
485
-	 * of a link if it is a reshare. This is a quick word around
486
-	 * until we can properly display multiple link shares in the UI
487
-	 *
488
-	 * See: https://github.com/owncloud/core/issues/22295
489
-	 *
490
-	 * FIXME: Remove once multiple link shares can be properly displayed
491
-	 *
492
-	 * @param \OCP\Share\IShare $share
493
-	 */
494
-	protected function setLinkParent(\OCP\Share\IShare $share) {
495
-
496
-		// No sense in checking if the method is not there.
497
-		if (method_exists($share, 'setParent')) {
498
-			$storage = $share->getNode()->getStorage();
499
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
500
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
501
-				$share->setParent($storage->getShareId());
502
-			}
503
-		};
504
-	}
505
-
506
-	/**
507
-	 * @param File|Folder $path
508
-	 */
509
-	protected function pathCreateChecks($path) {
510
-		// Make sure that we do not share a path that contains a shared mountpoint
511
-		if ($path instanceof \OCP\Files\Folder) {
512
-			$mounts = $this->mountManager->findIn($path->getPath());
513
-			foreach($mounts as $mount) {
514
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
515
-					throw new \InvalidArgumentException('Path contains files shared with you');
516
-				}
517
-			}
518
-		}
519
-	}
520
-
521
-	/**
522
-	 * Check if the user that is sharing can actually share
523
-	 *
524
-	 * @param \OCP\Share\IShare $share
525
-	 * @throws \Exception
526
-	 */
527
-	protected function canShare(\OCP\Share\IShare $share) {
528
-		if (!$this->shareApiEnabled()) {
529
-			throw new \Exception('The share API is disabled');
530
-		}
531
-
532
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
533
-			throw new \Exception('You are not allowed to share');
534
-		}
535
-	}
536
-
537
-	/**
538
-	 * Share a path
539
-	 *
540
-	 * @param \OCP\Share\IShare $share
541
-	 * @return Share The share object
542
-	 * @throws \Exception
543
-	 *
544
-	 * TODO: handle link share permissions or check them
545
-	 */
546
-	public function createShare(\OCP\Share\IShare $share) {
547
-		$this->canShare($share);
548
-
549
-		$this->generalCreateChecks($share);
550
-
551
-		// Verify if there are any issues with the path
552
-		$this->pathCreateChecks($share->getNode());
553
-
554
-		/*
442
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
443
+        $existingShares = $provider->getSharesByPath($share->getNode());
444
+        foreach($existingShares as $existingShare) {
445
+            try {
446
+                if ($existingShare->getFullId() === $share->getFullId()) {
447
+                    continue;
448
+                }
449
+            } catch (\UnexpectedValueException $e) {
450
+                //It is a new share so just continue
451
+            }
452
+
453
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
454
+                throw new \Exception('Path already shared with this group');
455
+            }
456
+        }
457
+    }
458
+
459
+    /**
460
+     * Check for pre share requirements for link shares
461
+     *
462
+     * @param \OCP\Share\IShare $share
463
+     * @throws \Exception
464
+     */
465
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
466
+        // Are link shares allowed?
467
+        if (!$this->shareApiAllowLinks()) {
468
+            throw new \Exception('Link sharing not allowed');
469
+        }
470
+
471
+        // Link shares by definition can't have share permissions
472
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
473
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
474
+        }
475
+
476
+        // Check if public upload is allowed
477
+        if (!$this->shareApiLinkAllowPublicUpload() &&
478
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
479
+            throw new \InvalidArgumentException('Public upload not allowed');
480
+        }
481
+    }
482
+
483
+    /**
484
+     * To make sure we don't get invisible link shares we set the parent
485
+     * of a link if it is a reshare. This is a quick word around
486
+     * until we can properly display multiple link shares in the UI
487
+     *
488
+     * See: https://github.com/owncloud/core/issues/22295
489
+     *
490
+     * FIXME: Remove once multiple link shares can be properly displayed
491
+     *
492
+     * @param \OCP\Share\IShare $share
493
+     */
494
+    protected function setLinkParent(\OCP\Share\IShare $share) {
495
+
496
+        // No sense in checking if the method is not there.
497
+        if (method_exists($share, 'setParent')) {
498
+            $storage = $share->getNode()->getStorage();
499
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
500
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
501
+                $share->setParent($storage->getShareId());
502
+            }
503
+        };
504
+    }
505
+
506
+    /**
507
+     * @param File|Folder $path
508
+     */
509
+    protected function pathCreateChecks($path) {
510
+        // Make sure that we do not share a path that contains a shared mountpoint
511
+        if ($path instanceof \OCP\Files\Folder) {
512
+            $mounts = $this->mountManager->findIn($path->getPath());
513
+            foreach($mounts as $mount) {
514
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
515
+                    throw new \InvalidArgumentException('Path contains files shared with you');
516
+                }
517
+            }
518
+        }
519
+    }
520
+
521
+    /**
522
+     * Check if the user that is sharing can actually share
523
+     *
524
+     * @param \OCP\Share\IShare $share
525
+     * @throws \Exception
526
+     */
527
+    protected function canShare(\OCP\Share\IShare $share) {
528
+        if (!$this->shareApiEnabled()) {
529
+            throw new \Exception('The share API is disabled');
530
+        }
531
+
532
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
533
+            throw new \Exception('You are not allowed to share');
534
+        }
535
+    }
536
+
537
+    /**
538
+     * Share a path
539
+     *
540
+     * @param \OCP\Share\IShare $share
541
+     * @return Share The share object
542
+     * @throws \Exception
543
+     *
544
+     * TODO: handle link share permissions or check them
545
+     */
546
+    public function createShare(\OCP\Share\IShare $share) {
547
+        $this->canShare($share);
548
+
549
+        $this->generalCreateChecks($share);
550
+
551
+        // Verify if there are any issues with the path
552
+        $this->pathCreateChecks($share->getNode());
553
+
554
+        /*
555 555
 		 * On creation of a share the owner is always the owner of the path
556 556
 		 * Except for mounted federated shares.
557 557
 		 */
558
-		$storage = $share->getNode()->getStorage();
559
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
560
-			$parent = $share->getNode()->getParent();
561
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
-				$parent = $parent->getParent();
563
-			}
564
-			$share->setShareOwner($parent->getOwner()->getUID());
565
-		} else {
566
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
567
-		}
568
-
569
-		//Verify share type
570
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
571
-			$this->userCreateChecks($share);
572
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
573
-			$this->groupCreateChecks($share);
574
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
575
-			$this->linkCreateChecks($share);
576
-			$this->setLinkParent($share);
577
-
578
-			/*
558
+        $storage = $share->getNode()->getStorage();
559
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
560
+            $parent = $share->getNode()->getParent();
561
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
+                $parent = $parent->getParent();
563
+            }
564
+            $share->setShareOwner($parent->getOwner()->getUID());
565
+        } else {
566
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
567
+        }
568
+
569
+        //Verify share type
570
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
571
+            $this->userCreateChecks($share);
572
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
573
+            $this->groupCreateChecks($share);
574
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
575
+            $this->linkCreateChecks($share);
576
+            $this->setLinkParent($share);
577
+
578
+            /*
579 579
 			 * For now ignore a set token.
580 580
 			 */
581
-			$share->setToken(
582
-				$this->secureRandom->generate(
583
-					\OC\Share\Constants::TOKEN_LENGTH,
584
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
585
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
586
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
587
-				)
588
-			);
589
-
590
-			//Verify the expiration date
591
-			$this->validateExpirationDate($share);
592
-
593
-			//Verify the password
594
-			$this->verifyPassword($share->getPassword());
595
-
596
-			// If a password is set. Hash it!
597
-			if ($share->getPassword() !== null) {
598
-				$share->setPassword($this->hasher->hash($share->getPassword()));
599
-			}
600
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
601
-			$share->setToken(
602
-				$this->secureRandom->generate(
603
-					\OC\Share\Constants::TOKEN_LENGTH,
604
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
605
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
606
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
607
-				)
608
-			);
609
-		}
610
-
611
-		// Cannot share with the owner
612
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
613
-			$share->getSharedWith() === $share->getShareOwner()) {
614
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
615
-		}
616
-
617
-		// Generate the target
618
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
619
-		$target = \OC\Files\Filesystem::normalizePath($target);
620
-		$share->setTarget($target);
621
-
622
-		// Pre share hook
623
-		$run = true;
624
-		$error = '';
625
-		$preHookData = [
626
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
627
-			'itemSource' => $share->getNode()->getId(),
628
-			'shareType' => $share->getShareType(),
629
-			'uidOwner' => $share->getSharedBy(),
630
-			'permissions' => $share->getPermissions(),
631
-			'fileSource' => $share->getNode()->getId(),
632
-			'expiration' => $share->getExpirationDate(),
633
-			'token' => $share->getToken(),
634
-			'itemTarget' => $share->getTarget(),
635
-			'shareWith' => $share->getSharedWith(),
636
-			'run' => &$run,
637
-			'error' => &$error,
638
-		];
639
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
640
-
641
-		if ($run === false) {
642
-			throw new \Exception($error);
643
-		}
644
-
645
-		$oldShare = $share;
646
-		$provider = $this->factory->getProviderForType($share->getShareType());
647
-		$share = $provider->create($share);
648
-		//reuse the node we already have
649
-		$share->setNode($oldShare->getNode());
650
-
651
-		// Post share hook
652
-		$postHookData = [
653
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
654
-			'itemSource' => $share->getNode()->getId(),
655
-			'shareType' => $share->getShareType(),
656
-			'uidOwner' => $share->getSharedBy(),
657
-			'permissions' => $share->getPermissions(),
658
-			'fileSource' => $share->getNode()->getId(),
659
-			'expiration' => $share->getExpirationDate(),
660
-			'token' => $share->getToken(),
661
-			'id' => $share->getId(),
662
-			'shareWith' => $share->getSharedWith(),
663
-			'itemTarget' => $share->getTarget(),
664
-			'fileTarget' => $share->getTarget(),
665
-		];
666
-
667
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
668
-
669
-		return $share;
670
-	}
671
-
672
-	/**
673
-	 * Update a share
674
-	 *
675
-	 * @param \OCP\Share\IShare $share
676
-	 * @return \OCP\Share\IShare The share object
677
-	 * @throws \InvalidArgumentException
678
-	 */
679
-	public function updateShare(\OCP\Share\IShare $share) {
680
-		$expirationDateUpdated = false;
681
-
682
-		$this->canShare($share);
683
-
684
-		try {
685
-			$originalShare = $this->getShareById($share->getFullId());
686
-		} catch (\UnexpectedValueException $e) {
687
-			throw new \InvalidArgumentException('Share does not have a full id');
688
-		}
689
-
690
-		// We can't change the share type!
691
-		if ($share->getShareType() !== $originalShare->getShareType()) {
692
-			throw new \InvalidArgumentException('Can\'t change share type');
693
-		}
694
-
695
-		// We can only change the recipient on user shares
696
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
697
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
698
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
699
-		}
700
-
701
-		// Cannot share with the owner
702
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
703
-			$share->getSharedWith() === $share->getShareOwner()) {
704
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
705
-		}
706
-
707
-		$this->generalCreateChecks($share);
708
-
709
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
710
-			$this->userCreateChecks($share);
711
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
712
-			$this->groupCreateChecks($share);
713
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
714
-			$this->linkCreateChecks($share);
715
-
716
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
717
-
718
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
719
-				//Verify the expiration date
720
-				$this->validateExpirationDate($share);
721
-				$expirationDateUpdated = true;
722
-			}
723
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
724
-			$plainTextPassword = $share->getPassword();
725
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
726
-				$plainTextPassword = null;
727
-			}
728
-		}
729
-
730
-		$this->pathCreateChecks($share->getNode());
731
-
732
-		// Now update the share!
733
-		$provider = $this->factory->getProviderForType($share->getShareType());
734
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
735
-			$share = $provider->update($share, $plainTextPassword);
736
-		} else {
737
-			$share = $provider->update($share);
738
-		}
739
-
740
-		if ($expirationDateUpdated === true) {
741
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
742
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
743
-				'itemSource' => $share->getNode()->getId(),
744
-				'date' => $share->getExpirationDate(),
745
-				'uidOwner' => $share->getSharedBy(),
746
-			]);
747
-		}
748
-
749
-		if ($share->getPassword() !== $originalShare->getPassword()) {
750
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
751
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
752
-				'itemSource' => $share->getNode()->getId(),
753
-				'uidOwner' => $share->getSharedBy(),
754
-				'token' => $share->getToken(),
755
-				'disabled' => is_null($share->getPassword()),
756
-			]);
757
-		}
758
-
759
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
760
-			if ($this->userManager->userExists($share->getShareOwner())) {
761
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
762
-			} else {
763
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
764
-			}
765
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
766
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
767
-				'itemSource' => $share->getNode()->getId(),
768
-				'shareType' => $share->getShareType(),
769
-				'shareWith' => $share->getSharedWith(),
770
-				'uidOwner' => $share->getSharedBy(),
771
-				'permissions' => $share->getPermissions(),
772
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
773
-			));
774
-		}
775
-
776
-		return $share;
777
-	}
778
-
779
-	/**
780
-	 * Updates the password of the given share if it is not the same as the
781
-	 * password of the original share.
782
-	 *
783
-	 * @param \OCP\Share\IShare $share the share to update its password.
784
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
785
-	 *        password with.
786
-	 * @return boolean whether the password was updated or not.
787
-	 */
788
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
789
-		// Password updated.
790
-		if ($share->getPassword() !== $originalShare->getPassword()) {
791
-			//Verify the password
792
-			$this->verifyPassword($share->getPassword());
793
-
794
-			// If a password is set. Hash it!
795
-			if ($share->getPassword() !== null) {
796
-				$share->setPassword($this->hasher->hash($share->getPassword()));
797
-
798
-				return true;
799
-			}
800
-		}
801
-
802
-		return false;
803
-	}
804
-
805
-	/**
806
-	 * Delete all the children of this share
807
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
808
-	 *
809
-	 * @param \OCP\Share\IShare $share
810
-	 * @return \OCP\Share\IShare[] List of deleted shares
811
-	 */
812
-	protected function deleteChildren(\OCP\Share\IShare $share) {
813
-		$deletedShares = [];
814
-
815
-		$provider = $this->factory->getProviderForType($share->getShareType());
816
-
817
-		foreach ($provider->getChildren($share) as $child) {
818
-			$deletedChildren = $this->deleteChildren($child);
819
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
820
-
821
-			$provider->delete($child);
822
-			$deletedShares[] = $child;
823
-		}
824
-
825
-		return $deletedShares;
826
-	}
827
-
828
-	/**
829
-	 * Delete a share
830
-	 *
831
-	 * @param \OCP\Share\IShare $share
832
-	 * @throws ShareNotFound
833
-	 * @throws \InvalidArgumentException
834
-	 */
835
-	public function deleteShare(\OCP\Share\IShare $share) {
836
-
837
-		try {
838
-			$share->getFullId();
839
-		} catch (\UnexpectedValueException $e) {
840
-			throw new \InvalidArgumentException('Share does not have a full id');
841
-		}
842
-
843
-		$event = new GenericEvent($share);
844
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
845
-
846
-		// Get all children and delete them as well
847
-		$deletedShares = $this->deleteChildren($share);
848
-
849
-		// Do the actual delete
850
-		$provider = $this->factory->getProviderForType($share->getShareType());
851
-		$provider->delete($share);
852
-
853
-		// All the deleted shares caused by this delete
854
-		$deletedShares[] = $share;
855
-
856
-		// Emit post hook
857
-		$event->setArgument('deletedShares', $deletedShares);
858
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
859
-	}
860
-
861
-
862
-	/**
863
-	 * Unshare a file as the recipient.
864
-	 * This can be different from a regular delete for example when one of
865
-	 * the users in a groups deletes that share. But the provider should
866
-	 * handle this.
867
-	 *
868
-	 * @param \OCP\Share\IShare $share
869
-	 * @param string $recipientId
870
-	 */
871
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
872
-		list($providerId, ) = $this->splitFullId($share->getFullId());
873
-		$provider = $this->factory->getProvider($providerId);
874
-
875
-		$provider->deleteFromSelf($share, $recipientId);
876
-	}
877
-
878
-	/**
879
-	 * @inheritdoc
880
-	 */
881
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
882
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
883
-			throw new \InvalidArgumentException('Can\'t change target of link share');
884
-		}
885
-
886
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
887
-			throw new \InvalidArgumentException('Invalid recipient');
888
-		}
889
-
890
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
891
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
892
-			if (is_null($sharedWith)) {
893
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
894
-			}
895
-			$recipient = $this->userManager->get($recipientId);
896
-			if (!$sharedWith->inGroup($recipient)) {
897
-				throw new \InvalidArgumentException('Invalid recipient');
898
-			}
899
-		}
900
-
901
-		list($providerId, ) = $this->splitFullId($share->getFullId());
902
-		$provider = $this->factory->getProvider($providerId);
903
-
904
-		$provider->move($share, $recipientId);
905
-	}
906
-
907
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
908
-		$providers = $this->factory->getAllProviders();
909
-
910
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
911
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
912
-			foreach ($newShares as $fid => $data) {
913
-				if (!isset($shares[$fid])) {
914
-					$shares[$fid] = [];
915
-				}
916
-
917
-				$shares[$fid] = array_merge($shares[$fid], $data);
918
-			}
919
-			return $shares;
920
-		}, []);
921
-	}
922
-
923
-	/**
924
-	 * @inheritdoc
925
-	 */
926
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
927
-		if ($path !== null &&
928
-				!($path instanceof \OCP\Files\File) &&
929
-				!($path instanceof \OCP\Files\Folder)) {
930
-			throw new \InvalidArgumentException('invalid path');
931
-		}
932
-
933
-		try {
934
-			$provider = $this->factory->getProviderForType($shareType);
935
-		} catch (ProviderException $e) {
936
-			return [];
937
-		}
938
-
939
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
940
-
941
-		/*
581
+            $share->setToken(
582
+                $this->secureRandom->generate(
583
+                    \OC\Share\Constants::TOKEN_LENGTH,
584
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
585
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
586
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
587
+                )
588
+            );
589
+
590
+            //Verify the expiration date
591
+            $this->validateExpirationDate($share);
592
+
593
+            //Verify the password
594
+            $this->verifyPassword($share->getPassword());
595
+
596
+            // If a password is set. Hash it!
597
+            if ($share->getPassword() !== null) {
598
+                $share->setPassword($this->hasher->hash($share->getPassword()));
599
+            }
600
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
601
+            $share->setToken(
602
+                $this->secureRandom->generate(
603
+                    \OC\Share\Constants::TOKEN_LENGTH,
604
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
605
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
606
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
607
+                )
608
+            );
609
+        }
610
+
611
+        // Cannot share with the owner
612
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
613
+            $share->getSharedWith() === $share->getShareOwner()) {
614
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
615
+        }
616
+
617
+        // Generate the target
618
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
619
+        $target = \OC\Files\Filesystem::normalizePath($target);
620
+        $share->setTarget($target);
621
+
622
+        // Pre share hook
623
+        $run = true;
624
+        $error = '';
625
+        $preHookData = [
626
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
627
+            'itemSource' => $share->getNode()->getId(),
628
+            'shareType' => $share->getShareType(),
629
+            'uidOwner' => $share->getSharedBy(),
630
+            'permissions' => $share->getPermissions(),
631
+            'fileSource' => $share->getNode()->getId(),
632
+            'expiration' => $share->getExpirationDate(),
633
+            'token' => $share->getToken(),
634
+            'itemTarget' => $share->getTarget(),
635
+            'shareWith' => $share->getSharedWith(),
636
+            'run' => &$run,
637
+            'error' => &$error,
638
+        ];
639
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
640
+
641
+        if ($run === false) {
642
+            throw new \Exception($error);
643
+        }
644
+
645
+        $oldShare = $share;
646
+        $provider = $this->factory->getProviderForType($share->getShareType());
647
+        $share = $provider->create($share);
648
+        //reuse the node we already have
649
+        $share->setNode($oldShare->getNode());
650
+
651
+        // Post share hook
652
+        $postHookData = [
653
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
654
+            'itemSource' => $share->getNode()->getId(),
655
+            'shareType' => $share->getShareType(),
656
+            'uidOwner' => $share->getSharedBy(),
657
+            'permissions' => $share->getPermissions(),
658
+            'fileSource' => $share->getNode()->getId(),
659
+            'expiration' => $share->getExpirationDate(),
660
+            'token' => $share->getToken(),
661
+            'id' => $share->getId(),
662
+            'shareWith' => $share->getSharedWith(),
663
+            'itemTarget' => $share->getTarget(),
664
+            'fileTarget' => $share->getTarget(),
665
+        ];
666
+
667
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
668
+
669
+        return $share;
670
+    }
671
+
672
+    /**
673
+     * Update a share
674
+     *
675
+     * @param \OCP\Share\IShare $share
676
+     * @return \OCP\Share\IShare The share object
677
+     * @throws \InvalidArgumentException
678
+     */
679
+    public function updateShare(\OCP\Share\IShare $share) {
680
+        $expirationDateUpdated = false;
681
+
682
+        $this->canShare($share);
683
+
684
+        try {
685
+            $originalShare = $this->getShareById($share->getFullId());
686
+        } catch (\UnexpectedValueException $e) {
687
+            throw new \InvalidArgumentException('Share does not have a full id');
688
+        }
689
+
690
+        // We can't change the share type!
691
+        if ($share->getShareType() !== $originalShare->getShareType()) {
692
+            throw new \InvalidArgumentException('Can\'t change share type');
693
+        }
694
+
695
+        // We can only change the recipient on user shares
696
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
697
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
698
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
699
+        }
700
+
701
+        // Cannot share with the owner
702
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
703
+            $share->getSharedWith() === $share->getShareOwner()) {
704
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
705
+        }
706
+
707
+        $this->generalCreateChecks($share);
708
+
709
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
710
+            $this->userCreateChecks($share);
711
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
712
+            $this->groupCreateChecks($share);
713
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
714
+            $this->linkCreateChecks($share);
715
+
716
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
717
+
718
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
719
+                //Verify the expiration date
720
+                $this->validateExpirationDate($share);
721
+                $expirationDateUpdated = true;
722
+            }
723
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
724
+            $plainTextPassword = $share->getPassword();
725
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
726
+                $plainTextPassword = null;
727
+            }
728
+        }
729
+
730
+        $this->pathCreateChecks($share->getNode());
731
+
732
+        // Now update the share!
733
+        $provider = $this->factory->getProviderForType($share->getShareType());
734
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
735
+            $share = $provider->update($share, $plainTextPassword);
736
+        } else {
737
+            $share = $provider->update($share);
738
+        }
739
+
740
+        if ($expirationDateUpdated === true) {
741
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
742
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
743
+                'itemSource' => $share->getNode()->getId(),
744
+                'date' => $share->getExpirationDate(),
745
+                'uidOwner' => $share->getSharedBy(),
746
+            ]);
747
+        }
748
+
749
+        if ($share->getPassword() !== $originalShare->getPassword()) {
750
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
751
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
752
+                'itemSource' => $share->getNode()->getId(),
753
+                'uidOwner' => $share->getSharedBy(),
754
+                'token' => $share->getToken(),
755
+                'disabled' => is_null($share->getPassword()),
756
+            ]);
757
+        }
758
+
759
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
760
+            if ($this->userManager->userExists($share->getShareOwner())) {
761
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
762
+            } else {
763
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
764
+            }
765
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
766
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
767
+                'itemSource' => $share->getNode()->getId(),
768
+                'shareType' => $share->getShareType(),
769
+                'shareWith' => $share->getSharedWith(),
770
+                'uidOwner' => $share->getSharedBy(),
771
+                'permissions' => $share->getPermissions(),
772
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
773
+            ));
774
+        }
775
+
776
+        return $share;
777
+    }
778
+
779
+    /**
780
+     * Updates the password of the given share if it is not the same as the
781
+     * password of the original share.
782
+     *
783
+     * @param \OCP\Share\IShare $share the share to update its password.
784
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
785
+     *        password with.
786
+     * @return boolean whether the password was updated or not.
787
+     */
788
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
789
+        // Password updated.
790
+        if ($share->getPassword() !== $originalShare->getPassword()) {
791
+            //Verify the password
792
+            $this->verifyPassword($share->getPassword());
793
+
794
+            // If a password is set. Hash it!
795
+            if ($share->getPassword() !== null) {
796
+                $share->setPassword($this->hasher->hash($share->getPassword()));
797
+
798
+                return true;
799
+            }
800
+        }
801
+
802
+        return false;
803
+    }
804
+
805
+    /**
806
+     * Delete all the children of this share
807
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
808
+     *
809
+     * @param \OCP\Share\IShare $share
810
+     * @return \OCP\Share\IShare[] List of deleted shares
811
+     */
812
+    protected function deleteChildren(\OCP\Share\IShare $share) {
813
+        $deletedShares = [];
814
+
815
+        $provider = $this->factory->getProviderForType($share->getShareType());
816
+
817
+        foreach ($provider->getChildren($share) as $child) {
818
+            $deletedChildren = $this->deleteChildren($child);
819
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
820
+
821
+            $provider->delete($child);
822
+            $deletedShares[] = $child;
823
+        }
824
+
825
+        return $deletedShares;
826
+    }
827
+
828
+    /**
829
+     * Delete a share
830
+     *
831
+     * @param \OCP\Share\IShare $share
832
+     * @throws ShareNotFound
833
+     * @throws \InvalidArgumentException
834
+     */
835
+    public function deleteShare(\OCP\Share\IShare $share) {
836
+
837
+        try {
838
+            $share->getFullId();
839
+        } catch (\UnexpectedValueException $e) {
840
+            throw new \InvalidArgumentException('Share does not have a full id');
841
+        }
842
+
843
+        $event = new GenericEvent($share);
844
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
845
+
846
+        // Get all children and delete them as well
847
+        $deletedShares = $this->deleteChildren($share);
848
+
849
+        // Do the actual delete
850
+        $provider = $this->factory->getProviderForType($share->getShareType());
851
+        $provider->delete($share);
852
+
853
+        // All the deleted shares caused by this delete
854
+        $deletedShares[] = $share;
855
+
856
+        // Emit post hook
857
+        $event->setArgument('deletedShares', $deletedShares);
858
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
859
+    }
860
+
861
+
862
+    /**
863
+     * Unshare a file as the recipient.
864
+     * This can be different from a regular delete for example when one of
865
+     * the users in a groups deletes that share. But the provider should
866
+     * handle this.
867
+     *
868
+     * @param \OCP\Share\IShare $share
869
+     * @param string $recipientId
870
+     */
871
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
872
+        list($providerId, ) = $this->splitFullId($share->getFullId());
873
+        $provider = $this->factory->getProvider($providerId);
874
+
875
+        $provider->deleteFromSelf($share, $recipientId);
876
+    }
877
+
878
+    /**
879
+     * @inheritdoc
880
+     */
881
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
882
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
883
+            throw new \InvalidArgumentException('Can\'t change target of link share');
884
+        }
885
+
886
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
887
+            throw new \InvalidArgumentException('Invalid recipient');
888
+        }
889
+
890
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
891
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
892
+            if (is_null($sharedWith)) {
893
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
894
+            }
895
+            $recipient = $this->userManager->get($recipientId);
896
+            if (!$sharedWith->inGroup($recipient)) {
897
+                throw new \InvalidArgumentException('Invalid recipient');
898
+            }
899
+        }
900
+
901
+        list($providerId, ) = $this->splitFullId($share->getFullId());
902
+        $provider = $this->factory->getProvider($providerId);
903
+
904
+        $provider->move($share, $recipientId);
905
+    }
906
+
907
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
908
+        $providers = $this->factory->getAllProviders();
909
+
910
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
911
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
912
+            foreach ($newShares as $fid => $data) {
913
+                if (!isset($shares[$fid])) {
914
+                    $shares[$fid] = [];
915
+                }
916
+
917
+                $shares[$fid] = array_merge($shares[$fid], $data);
918
+            }
919
+            return $shares;
920
+        }, []);
921
+    }
922
+
923
+    /**
924
+     * @inheritdoc
925
+     */
926
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
927
+        if ($path !== null &&
928
+                !($path instanceof \OCP\Files\File) &&
929
+                !($path instanceof \OCP\Files\Folder)) {
930
+            throw new \InvalidArgumentException('invalid path');
931
+        }
932
+
933
+        try {
934
+            $provider = $this->factory->getProviderForType($shareType);
935
+        } catch (ProviderException $e) {
936
+            return [];
937
+        }
938
+
939
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
940
+
941
+        /*
942 942
 		 * Work around so we don't return expired shares but still follow
943 943
 		 * proper pagination.
944 944
 		 */
945 945
 
946
-		$shares2 = [];
947
-
948
-		while(true) {
949
-			$added = 0;
950
-			foreach ($shares as $share) {
951
-
952
-				try {
953
-					$this->checkExpireDate($share);
954
-				} catch (ShareNotFound $e) {
955
-					//Ignore since this basically means the share is deleted
956
-					continue;
957
-				}
958
-
959
-				$added++;
960
-				$shares2[] = $share;
961
-
962
-				if (count($shares2) === $limit) {
963
-					break;
964
-				}
965
-			}
966
-
967
-			if (count($shares2) === $limit) {
968
-				break;
969
-			}
970
-
971
-			// If there was no limit on the select we are done
972
-			if ($limit === -1) {
973
-				break;
974
-			}
975
-
976
-			$offset += $added;
977
-
978
-			// Fetch again $limit shares
979
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
980
-
981
-			// No more shares means we are done
982
-			if (empty($shares)) {
983
-				break;
984
-			}
985
-		}
986
-
987
-		$shares = $shares2;
988
-
989
-		return $shares;
990
-	}
991
-
992
-	/**
993
-	 * @inheritdoc
994
-	 */
995
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
996
-		try {
997
-			$provider = $this->factory->getProviderForType($shareType);
998
-		} catch (ProviderException $e) {
999
-			return [];
1000
-		}
1001
-
1002
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1003
-
1004
-		// remove all shares which are already expired
1005
-		foreach ($shares as $key => $share) {
1006
-			try {
1007
-				$this->checkExpireDate($share);
1008
-			} catch (ShareNotFound $e) {
1009
-				unset($shares[$key]);
1010
-			}
1011
-		}
1012
-
1013
-		return $shares;
1014
-	}
1015
-
1016
-	/**
1017
-	 * @inheritdoc
1018
-	 */
1019
-	public function getShareById($id, $recipient = null) {
1020
-		if ($id === null) {
1021
-			throw new ShareNotFound();
1022
-		}
1023
-
1024
-		list($providerId, $id) = $this->splitFullId($id);
1025
-
1026
-		try {
1027
-			$provider = $this->factory->getProvider($providerId);
1028
-		} catch (ProviderException $e) {
1029
-			throw new ShareNotFound();
1030
-		}
1031
-
1032
-		$share = $provider->getShareById($id, $recipient);
1033
-
1034
-		$this->checkExpireDate($share);
1035
-
1036
-		return $share;
1037
-	}
1038
-
1039
-	/**
1040
-	 * Get all the shares for a given path
1041
-	 *
1042
-	 * @param \OCP\Files\Node $path
1043
-	 * @param int $page
1044
-	 * @param int $perPage
1045
-	 * @return Share[]
1046
-	 *
1047
-	 * @throws ProviderException
1048
-	 */
1049
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1050
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP];
1051
-		$providers = [];
1052
-		$results = [];
1053
-
1054
-		foreach ($types as $type) {
1055
-			$provider = $this->factory->getProviderForType($type);
1056
-			// store this way to deduplicate entries by id
1057
-			$providers[$provider->identifier()] = $provider;
1058
-		}
1059
-
1060
-		foreach ($providers as $provider) {
1061
-			$results = array_merge($results, $provider->getSharesByPath($path));
1062
-		}
1063
-
1064
-		return $results;
1065
-	}
1066
-
1067
-	/**
1068
-	 * Get the share by token possible with password
1069
-	 *
1070
-	 * @param string $token
1071
-	 * @return Share
1072
-	 *
1073
-	 * @throws ShareNotFound
1074
-	 */
1075
-	public function getShareByToken($token) {
1076
-		$share = null;
1077
-		try {
1078
-			if($this->shareApiAllowLinks()) {
1079
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1080
-				$share = $provider->getShareByToken($token);
1081
-			}
1082
-		} catch (ProviderException $e) {
1083
-		} catch (ShareNotFound $e) {
1084
-		}
1085
-
1086
-
1087
-		// If it is not a link share try to fetch a federated share by token
1088
-		if ($share === null) {
1089
-			try {
1090
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1091
-				$share = $provider->getShareByToken($token);
1092
-			} catch (ProviderException $e) {
1093
-			} catch (ShareNotFound $e) {
1094
-			}
1095
-		}
1096
-
1097
-		// If it is not a link share try to fetch a mail share by token
1098
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1099
-			try {
1100
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1101
-				$share = $provider->getShareByToken($token);
1102
-			} catch (ProviderException $e) {
1103
-			} catch (ShareNotFound $e) {
1104
-			}
1105
-		}
1106
-
1107
-		if ($share === null) {
1108
-			throw new ShareNotFound();
1109
-		}
1110
-
1111
-		$this->checkExpireDate($share);
1112
-
1113
-		/*
946
+        $shares2 = [];
947
+
948
+        while(true) {
949
+            $added = 0;
950
+            foreach ($shares as $share) {
951
+
952
+                try {
953
+                    $this->checkExpireDate($share);
954
+                } catch (ShareNotFound $e) {
955
+                    //Ignore since this basically means the share is deleted
956
+                    continue;
957
+                }
958
+
959
+                $added++;
960
+                $shares2[] = $share;
961
+
962
+                if (count($shares2) === $limit) {
963
+                    break;
964
+                }
965
+            }
966
+
967
+            if (count($shares2) === $limit) {
968
+                break;
969
+            }
970
+
971
+            // If there was no limit on the select we are done
972
+            if ($limit === -1) {
973
+                break;
974
+            }
975
+
976
+            $offset += $added;
977
+
978
+            // Fetch again $limit shares
979
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
980
+
981
+            // No more shares means we are done
982
+            if (empty($shares)) {
983
+                break;
984
+            }
985
+        }
986
+
987
+        $shares = $shares2;
988
+
989
+        return $shares;
990
+    }
991
+
992
+    /**
993
+     * @inheritdoc
994
+     */
995
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
996
+        try {
997
+            $provider = $this->factory->getProviderForType($shareType);
998
+        } catch (ProviderException $e) {
999
+            return [];
1000
+        }
1001
+
1002
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1003
+
1004
+        // remove all shares which are already expired
1005
+        foreach ($shares as $key => $share) {
1006
+            try {
1007
+                $this->checkExpireDate($share);
1008
+            } catch (ShareNotFound $e) {
1009
+                unset($shares[$key]);
1010
+            }
1011
+        }
1012
+
1013
+        return $shares;
1014
+    }
1015
+
1016
+    /**
1017
+     * @inheritdoc
1018
+     */
1019
+    public function getShareById($id, $recipient = null) {
1020
+        if ($id === null) {
1021
+            throw new ShareNotFound();
1022
+        }
1023
+
1024
+        list($providerId, $id) = $this->splitFullId($id);
1025
+
1026
+        try {
1027
+            $provider = $this->factory->getProvider($providerId);
1028
+        } catch (ProviderException $e) {
1029
+            throw new ShareNotFound();
1030
+        }
1031
+
1032
+        $share = $provider->getShareById($id, $recipient);
1033
+
1034
+        $this->checkExpireDate($share);
1035
+
1036
+        return $share;
1037
+    }
1038
+
1039
+    /**
1040
+     * Get all the shares for a given path
1041
+     *
1042
+     * @param \OCP\Files\Node $path
1043
+     * @param int $page
1044
+     * @param int $perPage
1045
+     * @return Share[]
1046
+     *
1047
+     * @throws ProviderException
1048
+     */
1049
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1050
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP];
1051
+        $providers = [];
1052
+        $results = [];
1053
+
1054
+        foreach ($types as $type) {
1055
+            $provider = $this->factory->getProviderForType($type);
1056
+            // store this way to deduplicate entries by id
1057
+            $providers[$provider->identifier()] = $provider;
1058
+        }
1059
+
1060
+        foreach ($providers as $provider) {
1061
+            $results = array_merge($results, $provider->getSharesByPath($path));
1062
+        }
1063
+
1064
+        return $results;
1065
+    }
1066
+
1067
+    /**
1068
+     * Get the share by token possible with password
1069
+     *
1070
+     * @param string $token
1071
+     * @return Share
1072
+     *
1073
+     * @throws ShareNotFound
1074
+     */
1075
+    public function getShareByToken($token) {
1076
+        $share = null;
1077
+        try {
1078
+            if($this->shareApiAllowLinks()) {
1079
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1080
+                $share = $provider->getShareByToken($token);
1081
+            }
1082
+        } catch (ProviderException $e) {
1083
+        } catch (ShareNotFound $e) {
1084
+        }
1085
+
1086
+
1087
+        // If it is not a link share try to fetch a federated share by token
1088
+        if ($share === null) {
1089
+            try {
1090
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1091
+                $share = $provider->getShareByToken($token);
1092
+            } catch (ProviderException $e) {
1093
+            } catch (ShareNotFound $e) {
1094
+            }
1095
+        }
1096
+
1097
+        // If it is not a link share try to fetch a mail share by token
1098
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1099
+            try {
1100
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1101
+                $share = $provider->getShareByToken($token);
1102
+            } catch (ProviderException $e) {
1103
+            } catch (ShareNotFound $e) {
1104
+            }
1105
+        }
1106
+
1107
+        if ($share === null) {
1108
+            throw new ShareNotFound();
1109
+        }
1110
+
1111
+        $this->checkExpireDate($share);
1112
+
1113
+        /*
1114 1114
 		 * Reduce the permissions for link shares if public upload is not enabled
1115 1115
 		 */
1116
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1117
-			!$this->shareApiLinkAllowPublicUpload()) {
1118
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1119
-		}
1120
-
1121
-		return $share;
1122
-	}
1123
-
1124
-	protected function checkExpireDate($share) {
1125
-		if ($share->getExpirationDate() !== null &&
1126
-			$share->getExpirationDate() <= new \DateTime()) {
1127
-			$this->deleteShare($share);
1128
-			throw new ShareNotFound();
1129
-		}
1130
-
1131
-	}
1132
-
1133
-	/**
1134
-	 * Verify the password of a public share
1135
-	 *
1136
-	 * @param \OCP\Share\IShare $share
1137
-	 * @param string $password
1138
-	 * @return bool
1139
-	 */
1140
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1141
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1142
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1143
-		if (!$passwordProtected) {
1144
-			//TODO maybe exception?
1145
-			return false;
1146
-		}
1147
-
1148
-		if ($password === null || $share->getPassword() === null) {
1149
-			return false;
1150
-		}
1151
-
1152
-		$newHash = '';
1153
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1154
-			return false;
1155
-		}
1156
-
1157
-		if (!empty($newHash)) {
1158
-			$share->setPassword($newHash);
1159
-			$provider = $this->factory->getProviderForType($share->getShareType());
1160
-			$provider->update($share);
1161
-		}
1162
-
1163
-		return true;
1164
-	}
1165
-
1166
-	/**
1167
-	 * @inheritdoc
1168
-	 */
1169
-	public function userDeleted($uid) {
1170
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1171
-
1172
-		foreach ($types as $type) {
1173
-			try {
1174
-				$provider = $this->factory->getProviderForType($type);
1175
-			} catch (ProviderException $e) {
1176
-				continue;
1177
-			}
1178
-			$provider->userDeleted($uid, $type);
1179
-		}
1180
-	}
1181
-
1182
-	/**
1183
-	 * @inheritdoc
1184
-	 */
1185
-	public function groupDeleted($gid) {
1186
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1187
-		$provider->groupDeleted($gid);
1188
-	}
1189
-
1190
-	/**
1191
-	 * @inheritdoc
1192
-	 */
1193
-	public function userDeletedFromGroup($uid, $gid) {
1194
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1195
-		$provider->userDeletedFromGroup($uid, $gid);
1196
-	}
1197
-
1198
-	/**
1199
-	 * Get access list to a path. This means
1200
-	 * all the users that can access a given path.
1201
-	 *
1202
-	 * Consider:
1203
-	 * -root
1204
-	 * |-folder1 (23)
1205
-	 *  |-folder2 (32)
1206
-	 *   |-fileA (42)
1207
-	 *
1208
-	 * fileA is shared with user1 and user1@server1
1209
-	 * folder2 is shared with group2 (user4 is a member of group2)
1210
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1211
-	 *
1212
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1213
-	 * [
1214
-	 *  users  => [
1215
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1216
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1217
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1218
-	 *  ],
1219
-	 *  remote => [
1220
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1221
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1222
-	 *  ],
1223
-	 *  public => bool
1224
-	 *  mail => bool
1225
-	 * ]
1226
-	 *
1227
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1228
-	 * [
1229
-	 *  users  => ['user1', 'user2', 'user4'],
1230
-	 *  remote => bool,
1231
-	 *  public => bool
1232
-	 *  mail => bool
1233
-	 * ]
1234
-	 *
1235
-	 * This is required for encryption/activity
1236
-	 *
1237
-	 * @param \OCP\Files\Node $path
1238
-	 * @param bool $recursive Should we check all parent folders as well
1239
-	 * @param bool $currentAccess Should the user have currently access to the file
1240
-	 * @return array
1241
-	 */
1242
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1243
-		$owner = $path->getOwner()->getUID();
1244
-
1245
-		if ($currentAccess) {
1246
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1247
-		} else {
1248
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1249
-		}
1250
-		if (!$this->userManager->userExists($owner)) {
1251
-			return $al;
1252
-		}
1253
-
1254
-		//Get node for the owner
1255
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1256
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1257
-			$path = $userFolder->getById($path->getId())[0];
1258
-		}
1259
-
1260
-		$providers = $this->factory->getAllProviders();
1261
-
1262
-		/** @var Node[] $nodes */
1263
-		$nodes = [];
1264
-
1265
-
1266
-		if ($currentAccess) {
1267
-			$ownerPath = $path->getPath();
1268
-			$ownerPath = explode('/', $ownerPath, 4);
1269
-			if (count($ownerPath) < 4) {
1270
-				$ownerPath = '';
1271
-			} else {
1272
-				$ownerPath = $ownerPath[3];
1273
-			}
1274
-			$al['users'][$owner] = [
1275
-				'node_id' => $path->getId(),
1276
-				'node_path' => '/' . $ownerPath,
1277
-			];
1278
-		} else {
1279
-			$al['users'][] = $owner;
1280
-		}
1281
-
1282
-		// Collect all the shares
1283
-		while ($path->getPath() !== $userFolder->getPath()) {
1284
-			$nodes[] = $path;
1285
-			if (!$recursive) {
1286
-				break;
1287
-			}
1288
-			$path = $path->getParent();
1289
-		}
1290
-
1291
-		foreach ($providers as $provider) {
1292
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1293
-
1294
-			foreach ($tmp as $k => $v) {
1295
-				if (isset($al[$k])) {
1296
-					if (is_array($al[$k])) {
1297
-						$al[$k] = array_merge($al[$k], $v);
1298
-					} else {
1299
-						$al[$k] = $al[$k] || $v;
1300
-					}
1301
-				} else {
1302
-					$al[$k] = $v;
1303
-				}
1304
-			}
1305
-		}
1306
-
1307
-		return $al;
1308
-	}
1309
-
1310
-	/**
1311
-	 * Create a new share
1312
-	 * @return \OCP\Share\IShare;
1313
-	 */
1314
-	public function newShare() {
1315
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1316
-	}
1317
-
1318
-	/**
1319
-	 * Is the share API enabled
1320
-	 *
1321
-	 * @return bool
1322
-	 */
1323
-	public function shareApiEnabled() {
1324
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1325
-	}
1326
-
1327
-	/**
1328
-	 * Is public link sharing enabled
1329
-	 *
1330
-	 * @return bool
1331
-	 */
1332
-	public function shareApiAllowLinks() {
1333
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1334
-	}
1335
-
1336
-	/**
1337
-	 * Is password on public link requires
1338
-	 *
1339
-	 * @return bool
1340
-	 */
1341
-	public function shareApiLinkEnforcePassword() {
1342
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1343
-	}
1344
-
1345
-	/**
1346
-	 * Is default expire date enabled
1347
-	 *
1348
-	 * @return bool
1349
-	 */
1350
-	public function shareApiLinkDefaultExpireDate() {
1351
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1352
-	}
1353
-
1354
-	/**
1355
-	 * Is default expire date enforced
1356
-	 *`
1357
-	 * @return bool
1358
-	 */
1359
-	public function shareApiLinkDefaultExpireDateEnforced() {
1360
-		return $this->shareApiLinkDefaultExpireDate() &&
1361
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1362
-	}
1363
-
1364
-	/**
1365
-	 * Number of default expire days
1366
-	 *shareApiLinkAllowPublicUpload
1367
-	 * @return int
1368
-	 */
1369
-	public function shareApiLinkDefaultExpireDays() {
1370
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1371
-	}
1372
-
1373
-	/**
1374
-	 * Allow public upload on link shares
1375
-	 *
1376
-	 * @return bool
1377
-	 */
1378
-	public function shareApiLinkAllowPublicUpload() {
1379
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1380
-	}
1381
-
1382
-	/**
1383
-	 * check if user can only share with group members
1384
-	 * @return bool
1385
-	 */
1386
-	public function shareWithGroupMembersOnly() {
1387
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1388
-	}
1389
-
1390
-	/**
1391
-	 * Check if users can share with groups
1392
-	 * @return bool
1393
-	 */
1394
-	public function allowGroupSharing() {
1395
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1396
-	}
1397
-
1398
-	/**
1399
-	 * Copied from \OC_Util::isSharingDisabledForUser
1400
-	 *
1401
-	 * TODO: Deprecate fuction from OC_Util
1402
-	 *
1403
-	 * @param string $userId
1404
-	 * @return bool
1405
-	 */
1406
-	public function sharingDisabledForUser($userId) {
1407
-		if ($userId === null) {
1408
-			return false;
1409
-		}
1410
-
1411
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1412
-			return $this->sharingDisabledForUsersCache[$userId];
1413
-		}
1414
-
1415
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1416
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1417
-			$excludedGroups = json_decode($groupsList);
1418
-			if (is_null($excludedGroups)) {
1419
-				$excludedGroups = explode(',', $groupsList);
1420
-				$newValue = json_encode($excludedGroups);
1421
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1422
-			}
1423
-			$user = $this->userManager->get($userId);
1424
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1425
-			if (!empty($usersGroups)) {
1426
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1427
-				// if the user is only in groups which are disabled for sharing then
1428
-				// sharing is also disabled for the user
1429
-				if (empty($remainingGroups)) {
1430
-					$this->sharingDisabledForUsersCache[$userId] = true;
1431
-					return true;
1432
-				}
1433
-			}
1434
-		}
1435
-
1436
-		$this->sharingDisabledForUsersCache[$userId] = false;
1437
-		return false;
1438
-	}
1439
-
1440
-	/**
1441
-	 * @inheritdoc
1442
-	 */
1443
-	public function outgoingServer2ServerSharesAllowed() {
1444
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1445
-	}
1446
-
1447
-	/**
1448
-	 * @inheritdoc
1449
-	 */
1450
-	public function shareProviderExists($shareType) {
1451
-		try {
1452
-			$this->factory->getProviderForType($shareType);
1453
-		} catch (ProviderException $e) {
1454
-			return false;
1455
-		}
1456
-
1457
-		return true;
1458
-	}
1116
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1117
+            !$this->shareApiLinkAllowPublicUpload()) {
1118
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1119
+        }
1120
+
1121
+        return $share;
1122
+    }
1123
+
1124
+    protected function checkExpireDate($share) {
1125
+        if ($share->getExpirationDate() !== null &&
1126
+            $share->getExpirationDate() <= new \DateTime()) {
1127
+            $this->deleteShare($share);
1128
+            throw new ShareNotFound();
1129
+        }
1130
+
1131
+    }
1132
+
1133
+    /**
1134
+     * Verify the password of a public share
1135
+     *
1136
+     * @param \OCP\Share\IShare $share
1137
+     * @param string $password
1138
+     * @return bool
1139
+     */
1140
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1141
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1142
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1143
+        if (!$passwordProtected) {
1144
+            //TODO maybe exception?
1145
+            return false;
1146
+        }
1147
+
1148
+        if ($password === null || $share->getPassword() === null) {
1149
+            return false;
1150
+        }
1151
+
1152
+        $newHash = '';
1153
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1154
+            return false;
1155
+        }
1156
+
1157
+        if (!empty($newHash)) {
1158
+            $share->setPassword($newHash);
1159
+            $provider = $this->factory->getProviderForType($share->getShareType());
1160
+            $provider->update($share);
1161
+        }
1162
+
1163
+        return true;
1164
+    }
1165
+
1166
+    /**
1167
+     * @inheritdoc
1168
+     */
1169
+    public function userDeleted($uid) {
1170
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1171
+
1172
+        foreach ($types as $type) {
1173
+            try {
1174
+                $provider = $this->factory->getProviderForType($type);
1175
+            } catch (ProviderException $e) {
1176
+                continue;
1177
+            }
1178
+            $provider->userDeleted($uid, $type);
1179
+        }
1180
+    }
1181
+
1182
+    /**
1183
+     * @inheritdoc
1184
+     */
1185
+    public function groupDeleted($gid) {
1186
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1187
+        $provider->groupDeleted($gid);
1188
+    }
1189
+
1190
+    /**
1191
+     * @inheritdoc
1192
+     */
1193
+    public function userDeletedFromGroup($uid, $gid) {
1194
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1195
+        $provider->userDeletedFromGroup($uid, $gid);
1196
+    }
1197
+
1198
+    /**
1199
+     * Get access list to a path. This means
1200
+     * all the users that can access a given path.
1201
+     *
1202
+     * Consider:
1203
+     * -root
1204
+     * |-folder1 (23)
1205
+     *  |-folder2 (32)
1206
+     *   |-fileA (42)
1207
+     *
1208
+     * fileA is shared with user1 and user1@server1
1209
+     * folder2 is shared with group2 (user4 is a member of group2)
1210
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1211
+     *
1212
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1213
+     * [
1214
+     *  users  => [
1215
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1216
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1217
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1218
+     *  ],
1219
+     *  remote => [
1220
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1221
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1222
+     *  ],
1223
+     *  public => bool
1224
+     *  mail => bool
1225
+     * ]
1226
+     *
1227
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1228
+     * [
1229
+     *  users  => ['user1', 'user2', 'user4'],
1230
+     *  remote => bool,
1231
+     *  public => bool
1232
+     *  mail => bool
1233
+     * ]
1234
+     *
1235
+     * This is required for encryption/activity
1236
+     *
1237
+     * @param \OCP\Files\Node $path
1238
+     * @param bool $recursive Should we check all parent folders as well
1239
+     * @param bool $currentAccess Should the user have currently access to the file
1240
+     * @return array
1241
+     */
1242
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1243
+        $owner = $path->getOwner()->getUID();
1244
+
1245
+        if ($currentAccess) {
1246
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1247
+        } else {
1248
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1249
+        }
1250
+        if (!$this->userManager->userExists($owner)) {
1251
+            return $al;
1252
+        }
1253
+
1254
+        //Get node for the owner
1255
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1256
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1257
+            $path = $userFolder->getById($path->getId())[0];
1258
+        }
1259
+
1260
+        $providers = $this->factory->getAllProviders();
1261
+
1262
+        /** @var Node[] $nodes */
1263
+        $nodes = [];
1264
+
1265
+
1266
+        if ($currentAccess) {
1267
+            $ownerPath = $path->getPath();
1268
+            $ownerPath = explode('/', $ownerPath, 4);
1269
+            if (count($ownerPath) < 4) {
1270
+                $ownerPath = '';
1271
+            } else {
1272
+                $ownerPath = $ownerPath[3];
1273
+            }
1274
+            $al['users'][$owner] = [
1275
+                'node_id' => $path->getId(),
1276
+                'node_path' => '/' . $ownerPath,
1277
+            ];
1278
+        } else {
1279
+            $al['users'][] = $owner;
1280
+        }
1281
+
1282
+        // Collect all the shares
1283
+        while ($path->getPath() !== $userFolder->getPath()) {
1284
+            $nodes[] = $path;
1285
+            if (!$recursive) {
1286
+                break;
1287
+            }
1288
+            $path = $path->getParent();
1289
+        }
1290
+
1291
+        foreach ($providers as $provider) {
1292
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1293
+
1294
+            foreach ($tmp as $k => $v) {
1295
+                if (isset($al[$k])) {
1296
+                    if (is_array($al[$k])) {
1297
+                        $al[$k] = array_merge($al[$k], $v);
1298
+                    } else {
1299
+                        $al[$k] = $al[$k] || $v;
1300
+                    }
1301
+                } else {
1302
+                    $al[$k] = $v;
1303
+                }
1304
+            }
1305
+        }
1306
+
1307
+        return $al;
1308
+    }
1309
+
1310
+    /**
1311
+     * Create a new share
1312
+     * @return \OCP\Share\IShare;
1313
+     */
1314
+    public function newShare() {
1315
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1316
+    }
1317
+
1318
+    /**
1319
+     * Is the share API enabled
1320
+     *
1321
+     * @return bool
1322
+     */
1323
+    public function shareApiEnabled() {
1324
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1325
+    }
1326
+
1327
+    /**
1328
+     * Is public link sharing enabled
1329
+     *
1330
+     * @return bool
1331
+     */
1332
+    public function shareApiAllowLinks() {
1333
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1334
+    }
1335
+
1336
+    /**
1337
+     * Is password on public link requires
1338
+     *
1339
+     * @return bool
1340
+     */
1341
+    public function shareApiLinkEnforcePassword() {
1342
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1343
+    }
1344
+
1345
+    /**
1346
+     * Is default expire date enabled
1347
+     *
1348
+     * @return bool
1349
+     */
1350
+    public function shareApiLinkDefaultExpireDate() {
1351
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1352
+    }
1353
+
1354
+    /**
1355
+     * Is default expire date enforced
1356
+     *`
1357
+     * @return bool
1358
+     */
1359
+    public function shareApiLinkDefaultExpireDateEnforced() {
1360
+        return $this->shareApiLinkDefaultExpireDate() &&
1361
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1362
+    }
1363
+
1364
+    /**
1365
+     * Number of default expire days
1366
+     *shareApiLinkAllowPublicUpload
1367
+     * @return int
1368
+     */
1369
+    public function shareApiLinkDefaultExpireDays() {
1370
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1371
+    }
1372
+
1373
+    /**
1374
+     * Allow public upload on link shares
1375
+     *
1376
+     * @return bool
1377
+     */
1378
+    public function shareApiLinkAllowPublicUpload() {
1379
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1380
+    }
1381
+
1382
+    /**
1383
+     * check if user can only share with group members
1384
+     * @return bool
1385
+     */
1386
+    public function shareWithGroupMembersOnly() {
1387
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1388
+    }
1389
+
1390
+    /**
1391
+     * Check if users can share with groups
1392
+     * @return bool
1393
+     */
1394
+    public function allowGroupSharing() {
1395
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1396
+    }
1397
+
1398
+    /**
1399
+     * Copied from \OC_Util::isSharingDisabledForUser
1400
+     *
1401
+     * TODO: Deprecate fuction from OC_Util
1402
+     *
1403
+     * @param string $userId
1404
+     * @return bool
1405
+     */
1406
+    public function sharingDisabledForUser($userId) {
1407
+        if ($userId === null) {
1408
+            return false;
1409
+        }
1410
+
1411
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1412
+            return $this->sharingDisabledForUsersCache[$userId];
1413
+        }
1414
+
1415
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1416
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1417
+            $excludedGroups = json_decode($groupsList);
1418
+            if (is_null($excludedGroups)) {
1419
+                $excludedGroups = explode(',', $groupsList);
1420
+                $newValue = json_encode($excludedGroups);
1421
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1422
+            }
1423
+            $user = $this->userManager->get($userId);
1424
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1425
+            if (!empty($usersGroups)) {
1426
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1427
+                // if the user is only in groups which are disabled for sharing then
1428
+                // sharing is also disabled for the user
1429
+                if (empty($remainingGroups)) {
1430
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1431
+                    return true;
1432
+                }
1433
+            }
1434
+        }
1435
+
1436
+        $this->sharingDisabledForUsersCache[$userId] = false;
1437
+        return false;
1438
+    }
1439
+
1440
+    /**
1441
+     * @inheritdoc
1442
+     */
1443
+    public function outgoingServer2ServerSharesAllowed() {
1444
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1445
+    }
1446
+
1447
+    /**
1448
+     * @inheritdoc
1449
+     */
1450
+    public function shareProviderExists($shareType) {
1451
+        try {
1452
+            $this->factory->getProviderForType($shareType);
1453
+        } catch (ProviderException $e) {
1454
+            return false;
1455
+        }
1456
+
1457
+        return true;
1458
+    }
1459 1459
 
1460 1460
 }
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
 
320 320
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
321 321
 			$expirationDate = new \DateTime();
322
-			$expirationDate->setTime(0,0,0);
322
+			$expirationDate->setTime(0, 0, 0);
323 323
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
324 324
 		}
325 325
 
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 
332 332
 			$date = new \DateTime();
333 333
 			$date->setTime(0, 0, 0);
334
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
334
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
335 335
 			if ($date < $expirationDate) {
336 336
 				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
337 337
 				throw new GenericShareException($message, $message, 404);
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 		 */
385 385
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
386 386
 		$existingShares = $provider->getSharesByPath($share->getNode());
387
-		foreach($existingShares as $existingShare) {
387
+		foreach ($existingShares as $existingShare) {
388 388
 			// Ignore if it is the same share
389 389
 			try {
390 390
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -441,7 +441,7 @@  discard block
 block discarded – undo
441 441
 		 */
442 442
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
443 443
 		$existingShares = $provider->getSharesByPath($share->getNode());
444
-		foreach($existingShares as $existingShare) {
444
+		foreach ($existingShares as $existingShare) {
445 445
 			try {
446 446
 				if ($existingShare->getFullId() === $share->getFullId()) {
447 447
 					continue;
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 		// Make sure that we do not share a path that contains a shared mountpoint
511 511
 		if ($path instanceof \OCP\Files\Folder) {
512 512
 			$mounts = $this->mountManager->findIn($path->getPath());
513
-			foreach($mounts as $mount) {
513
+			foreach ($mounts as $mount) {
514 514
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
515 515
 					throw new \InvalidArgumentException('Path contains files shared with you');
516 516
 				}
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 		$storage = $share->getNode()->getStorage();
559 559
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
560 560
 			$parent = $share->getNode()->getParent();
561
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
561
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562 562
 				$parent = $parent->getParent();
563 563
 			}
564 564
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -615,7 +615,7 @@  discard block
 block discarded – undo
615 615
 		}
616 616
 
617 617
 		// Generate the target
618
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
618
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
619 619
 		$target = \OC\Files\Filesystem::normalizePath($target);
620 620
 		$share->setTarget($target);
621 621
 
@@ -869,7 +869,7 @@  discard block
 block discarded – undo
869 869
 	 * @param string $recipientId
870 870
 	 */
871 871
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
872
-		list($providerId, ) = $this->splitFullId($share->getFullId());
872
+		list($providerId,) = $this->splitFullId($share->getFullId());
873 873
 		$provider = $this->factory->getProvider($providerId);
874 874
 
875 875
 		$provider->deleteFromSelf($share, $recipientId);
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
891 891
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
892 892
 			if (is_null($sharedWith)) {
893
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
893
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
894 894
 			}
895 895
 			$recipient = $this->userManager->get($recipientId);
896 896
 			if (!$sharedWith->inGroup($recipient)) {
@@ -898,7 +898,7 @@  discard block
 block discarded – undo
898 898
 			}
899 899
 		}
900 900
 
901
-		list($providerId, ) = $this->splitFullId($share->getFullId());
901
+		list($providerId,) = $this->splitFullId($share->getFullId());
902 902
 		$provider = $this->factory->getProvider($providerId);
903 903
 
904 904
 		$provider->move($share, $recipientId);
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 
946 946
 		$shares2 = [];
947 947
 
948
-		while(true) {
948
+		while (true) {
949 949
 			$added = 0;
950 950
 			foreach ($shares as $share) {
951 951
 
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 	 *
1047 1047
 	 * @throws ProviderException
1048 1048
 	 */
1049
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1049
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1050 1050
 		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP];
1051 1051
 		$providers = [];
1052 1052
 		$results = [];
@@ -1075,7 +1075,7 @@  discard block
 block discarded – undo
1075 1075
 	public function getShareByToken($token) {
1076 1076
 		$share = null;
1077 1077
 		try {
1078
-			if($this->shareApiAllowLinks()) {
1078
+			if ($this->shareApiAllowLinks()) {
1079 1079
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1080 1080
 				$share = $provider->getShareByToken($token);
1081 1081
 			}
@@ -1273,7 +1273,7 @@  discard block
 block discarded – undo
1273 1273
 			}
1274 1274
 			$al['users'][$owner] = [
1275 1275
 				'node_id' => $path->getId(),
1276
-				'node_path' => '/' . $ownerPath,
1276
+				'node_path' => '/'.$ownerPath,
1277 1277
 			];
1278 1278
 		} else {
1279 1279
 			$al['users'][] = $owner;
@@ -1367,7 +1367,7 @@  discard block
 block discarded – undo
1367 1367
 	 * @return int
1368 1368
 	 */
1369 1369
 	public function shareApiLinkDefaultExpireDays() {
1370
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1370
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1371 1371
 	}
1372 1372
 
1373 1373
 	/**
Please login to merge, or discard this patch.