Completed
Pull Request — master (#10075)
by
unknown
66:02 queued 36:49
created
lib/private/Files/Node/Folder.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@
 block discarded – undo
37 37
 	 * Creates a Folder that represents a non-existing path
38 38
 	 *
39 39
 	 * @param string $path path
40
-	 * @return string non-existing node class
40
+	 * @return NonExistingFolder non-existing node class
41 41
 	 */
42 42
 	protected function createNonExistingNode($path) {
43 43
 		return new NonExistingFolder($this->root, $this->view, $path);
Please login to merge, or discard this patch.
Indentation   +394 added lines, -394 removed lines patch added patch discarded remove patch
@@ -36,398 +36,398 @@
 block discarded – undo
36 36
 use OCP\Files\Search\ISearchOperator;
37 37
 
38 38
 class Folder extends Node implements \OCP\Files\Folder {
39
-	/**
40
-	 * Creates a Folder that represents a non-existing path
41
-	 *
42
-	 * @param string $path path
43
-	 * @return string non-existing node class
44
-	 */
45
-	protected function createNonExistingNode($path) {
46
-		return new NonExistingFolder($this->root, $this->view, $path);
47
-	}
48
-
49
-	/**
50
-	 * @param string $path path relative to the folder
51
-	 * @return string
52
-	 * @throws \OCP\Files\NotPermittedException
53
-	 */
54
-	public function getFullPath($path) {
55
-		if (!$this->isValidPath($path)) {
56
-			throw new NotPermittedException('Invalid path');
57
-		}
58
-		return $this->path . $this->normalizePath($path);
59
-	}
60
-
61
-	/**
62
-	 * @param string $path
63
-	 * @return string
64
-	 */
65
-	public function getRelativePath($path) {
66
-		if ($this->path === '' or $this->path === '/') {
67
-			return $this->normalizePath($path);
68
-		}
69
-		if ($path === $this->path) {
70
-			return '/';
71
-		} else if (strpos($path, $this->path . '/') !== 0) {
72
-			return null;
73
-		} else {
74
-			$path = substr($path, strlen($this->path));
75
-			return $this->normalizePath($path);
76
-		}
77
-	}
78
-
79
-	/**
80
-	 * check if a node is a (grand-)child of the folder
81
-	 *
82
-	 * @param \OC\Files\Node\Node $node
83
-	 * @return bool
84
-	 */
85
-	public function isSubNode($node) {
86
-		return strpos($node->getPath(), $this->path . '/') === 0;
87
-	}
88
-
89
-	/**
90
-	 * get the content of this directory
91
-	 *
92
-	 * @throws \OCP\Files\NotFoundException
93
-	 * @return Node[]
94
-	 */
95
-	public function getDirectoryListing() {
96
-		$folderContent = $this->view->getDirectoryContent($this->path);
97
-
98
-		return array_map(function (FileInfo $info) {
99
-			if ($info->getMimetype() === 'httpd/unix-directory') {
100
-				return new Folder($this->root, $this->view, $info->getPath(), $info);
101
-			} else {
102
-				return new File($this->root, $this->view, $info->getPath(), $info);
103
-			}
104
-		}, $folderContent);
105
-	}
106
-
107
-	/**
108
-	 * @param string $path
109
-	 * @param FileInfo $info
110
-	 * @return File|Folder
111
-	 */
112
-	protected function createNode($path, FileInfo $info = null) {
113
-		if (is_null($info)) {
114
-			$isDir = $this->view->is_dir($path);
115
-		} else {
116
-			$isDir = $info->getType() === FileInfo::TYPE_FOLDER;
117
-		}
118
-		if ($isDir) {
119
-			return new Folder($this->root, $this->view, $path, $info);
120
-		} else {
121
-			return new File($this->root, $this->view, $path, $info);
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * Get the node at $path
127
-	 *
128
-	 * @param string $path
129
-	 * @return \OC\Files\Node\Node
130
-	 * @throws \OCP\Files\NotFoundException
131
-	 */
132
-	public function get($path) {
133
-		return $this->root->get($this->getFullPath($path));
134
-	}
135
-
136
-	/**
137
-	 * @param string $path
138
-	 * @return bool
139
-	 */
140
-	public function nodeExists($path) {
141
-		try {
142
-			$this->get($path);
143
-			return true;
144
-		} catch (NotFoundException $e) {
145
-			return false;
146
-		}
147
-	}
148
-
149
-	/**
150
-	 * @param string $path
151
-	 * @return \OC\Files\Node\Folder
152
-	 * @throws \OCP\Files\NotPermittedException
153
-	 */
154
-	public function newFolder($path) {
155
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
156
-			$fullPath = $this->getFullPath($path);
157
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
158
-			$this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
159
-			$this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
160
-			$this->view->mkdir($fullPath);
161
-			$node = new Folder($this->root, $this->view, $fullPath);
162
-			$this->root->emit('\OC\Files', 'postWrite', array($node));
163
-			$this->root->emit('\OC\Files', 'postCreate', array($node));
164
-			return $node;
165
-		} else {
166
-			throw new NotPermittedException('No create permission for folder');
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param string $path
172
-	 * @return \OC\Files\Node\File
173
-	 * @throws \OCP\Files\NotPermittedException
174
-	 */
175
-	public function newFile($path) {
176
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
177
-			$fullPath = $this->getFullPath($path);
178
-			$nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
179
-			$this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
180
-			$this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
181
-			$this->view->touch($fullPath);
182
-			$node = new File($this->root, $this->view, $fullPath);
183
-			$this->root->emit('\OC\Files', 'postWrite', array($node));
184
-			$this->root->emit('\OC\Files', 'postCreate', array($node));
185
-			return $node;
186
-		} else {
187
-			throw new NotPermittedException('No create permission for path');
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * search for files with the name matching $query
193
-	 *
194
-	 * @param string|ISearchOperator $query
195
-	 * @return \OC\Files\Node\Node[]
196
-	 */
197
-	public function search($query) {
198
-		if (is_string($query)) {
199
-			return $this->searchCommon('search', array('%' . $query . '%'));
200
-		} else {
201
-			return $this->searchCommon('searchQuery', array($query));
202
-		}
203
-	}
204
-
205
-	/**
206
-	 * search for files by mimetype
207
-	 *
208
-	 * @param string $mimetype
209
-	 * @return Node[]
210
-	 */
211
-	public function searchByMime($mimetype) {
212
-		return $this->searchCommon('searchByMime', array($mimetype));
213
-	}
214
-
215
-	/**
216
-	 * search for files by tag
217
-	 *
218
-	 * @param string|int $tag name or tag id
219
-	 * @param string $userId owner of the tags
220
-	 * @return Node[]
221
-	 */
222
-	public function searchByTag($tag, $userId) {
223
-		return $this->searchCommon('searchByTag', array($tag, $userId));
224
-	}
225
-
226
-	/**
227
-	 * @param string $method cache method
228
-	 * @param array $args call args
229
-	 * @return \OC\Files\Node\Node[]
230
-	 */
231
-	private function searchCommon($method, $args) {
232
-		$files = array();
233
-		$rootLength = strlen($this->path);
234
-		$mount = $this->root->getMount($this->path);
235
-		$storage = $mount->getStorage();
236
-		$internalPath = $mount->getInternalPath($this->path);
237
-		$internalPath = rtrim($internalPath, '/');
238
-		if ($internalPath !== '') {
239
-			$internalPath = $internalPath . '/';
240
-		}
241
-		$internalRootLength = strlen($internalPath);
242
-
243
-		$cache = $storage->getCache('');
244
-
245
-		$results = call_user_func_array(array($cache, $method), $args);
246
-		foreach ($results as $result) {
247
-			if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
248
-				$result['internalPath'] = $result['path'];
249
-				$result['path'] = substr($result['path'], $internalRootLength);
250
-				$result['storage'] = $storage;
251
-				$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
252
-			}
253
-		}
254
-
255
-		$mounts = $this->root->getMountsIn($this->path);
256
-		foreach ($mounts as $mount) {
257
-			$storage = $mount->getStorage();
258
-			if ($storage) {
259
-				$cache = $storage->getCache('');
260
-
261
-				$relativeMountPoint = substr($mount->getMountPoint(), $rootLength);
262
-				$results = call_user_func_array(array($cache, $method), $args);
263
-				foreach ($results as $result) {
264
-					$result['internalPath'] = $result['path'];
265
-					$result['path'] = $relativeMountPoint . $result['path'];
266
-					$result['storage'] = $storage;
267
-					$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
268
-				}
269
-			}
270
-		}
271
-
272
-		return array_map(function (FileInfo $file) {
273
-			return $this->createNode($file->getPath(), $file);
274
-		}, $files);
275
-	}
276
-
277
-	/**
278
-	 * @param int $id
279
-	 * @return \OC\Files\Node\Node[]
280
-	 */
281
-	public function getById($id) {
282
-		$mountCache = $this->root->getUserMountCache();
283
-		if (strpos($this->getPath(), '/', 1) > 0) {
284
-			list(, $user) = explode('/', $this->getPath());
285
-		} else {
286
-			$user = null;
287
-		}
288
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
289
-		$mounts = $this->root->getMountsIn($this->path);
290
-		$mounts[] = $this->root->getMount($this->path);
291
-		/** @var IMountPoint[] $folderMounts */
292
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
293
-			return $mountPoint->getMountPoint();
294
-		}, $mounts), $mounts);
295
-
296
-		/** @var ICachedMountInfo[] $mountsContainingFile */
297
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
298
-			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
299
-		}));
300
-
301
-		if (count($mountsContainingFile) === 0) {
302
-			return [];
303
-		}
304
-
305
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
306
-			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
307
-			$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
308
-			if (!$cacheEntry) {
309
-				return null;
310
-			}
311
-
312
-			// cache jails will hide the "true" internal path
313
-			$internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
314
-			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
315
-			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
316
-			$absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
317
-			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
318
-				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
319
-				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
320
-			));
321
-		}, $mountsContainingFile);
322
-
323
-		$nodes = array_filter($nodes);
324
-
325
-		return array_filter($nodes, function (Node $node) {
326
-			return $this->getRelativePath($node->getPath());
327
-		});
328
-	}
329
-
330
-	public function getFreeSpace() {
331
-		return $this->view->free_space($this->path);
332
-	}
333
-
334
-	public function delete() {
335
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
336
-			$this->sendHooks(array('preDelete'));
337
-			$fileInfo = $this->getFileInfo();
338
-			$this->view->rmdir($this->path);
339
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
340
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
341
-			$this->exists = false;
342
-		} else {
343
-			throw new NotPermittedException('No delete permission for path');
344
-		}
345
-	}
346
-
347
-	/**
348
-	 * Add a suffix to the name in case the file exists
349
-	 *
350
-	 * @param string $name
351
-	 * @return string
352
-	 * @throws NotPermittedException
353
-	 */
354
-	public function getNonExistingName($name) {
355
-		$uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
356
-		return trim($this->getRelativePath($uniqueName), '/');
357
-	}
358
-
359
-	/**
360
-	 * @param int $limit
361
-	 * @param int $offset
362
-	 * @return \OCP\Files\Node[]
363
-	 */
364
-	public function getRecent($limit, $offset = 0) {
365
-		$mimetypeLoader = \OC::$server->getMimeTypeLoader();
366
-		$mounts = $this->root->getMountsIn($this->path);
367
-		$mounts[] = $this->getMountPoint();
368
-
369
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
370
-			return $mount->getStorage();
371
-		});
372
-		$storageIds = array_map(function (IMountPoint $mount) {
373
-			return $mount->getStorage()->getCache()->getNumericStorageId();
374
-		}, $mounts);
375
-		/** @var IMountPoint[] $mountMap */
376
-		$mountMap = array_combine($storageIds, $mounts);
377
-		$folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
378
-
379
-		//todo look into options of filtering path based on storage id (only search in files/ for home storage, filter by share root for shared, etc)
380
-
381
-		$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
382
-		$query = $builder
383
-			->select('f.*')
384
-			->from('filecache', 'f')
385
-			->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
386
-			->andWhere($builder->expr()->orX(
387
-			// handle non empty folders separate
388
-				$builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
389
-				$builder->expr()->eq('f.size', new Literal(0))
390
-			))
391
-			->orderBy('f.mtime', 'DESC')
392
-			->setMaxResults($limit)
393
-			->setFirstResult($offset);
394
-
395
-		$result = $query->execute()->fetchAll();
396
-
397
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
398
-			$mount = $mountMap[$entry['storage']];
399
-			$entry['internalPath'] = $entry['path'];
400
-			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
401
-			$entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
402
-			$path = $this->getAbsolutePath($mount, $entry['path']);
403
-			if (is_null($path)) {
404
-				return null;
405
-			}
406
-			$fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
407
-			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
408
-		}, $result));
409
-
410
-		return array_values(array_filter($files, function (Node $node) {
411
-			$relative = $this->getRelativePath($node->getPath());
412
-			return $relative !== null && $relative !== '/';
413
-		}));
414
-	}
415
-
416
-	private function getAbsolutePath(IMountPoint $mount, $path) {
417
-		$storage = $mount->getStorage();
418
-		if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
419
-			/** @var \OC\Files\Storage\Wrapper\Jail $storage */
420
-			$jailRoot = $storage->getUnjailedPath('');
421
-			$rootLength = strlen($jailRoot) + 1;
422
-			if ($path === $jailRoot) {
423
-				return $mount->getMountPoint();
424
-			} else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
425
-				return $mount->getMountPoint() . substr($path, $rootLength);
426
-			} else {
427
-				return null;
428
-			}
429
-		} else {
430
-			return $mount->getMountPoint() . $path;
431
-		}
432
-	}
39
+    /**
40
+     * Creates a Folder that represents a non-existing path
41
+     *
42
+     * @param string $path path
43
+     * @return string non-existing node class
44
+     */
45
+    protected function createNonExistingNode($path) {
46
+        return new NonExistingFolder($this->root, $this->view, $path);
47
+    }
48
+
49
+    /**
50
+     * @param string $path path relative to the folder
51
+     * @return string
52
+     * @throws \OCP\Files\NotPermittedException
53
+     */
54
+    public function getFullPath($path) {
55
+        if (!$this->isValidPath($path)) {
56
+            throw new NotPermittedException('Invalid path');
57
+        }
58
+        return $this->path . $this->normalizePath($path);
59
+    }
60
+
61
+    /**
62
+     * @param string $path
63
+     * @return string
64
+     */
65
+    public function getRelativePath($path) {
66
+        if ($this->path === '' or $this->path === '/') {
67
+            return $this->normalizePath($path);
68
+        }
69
+        if ($path === $this->path) {
70
+            return '/';
71
+        } else if (strpos($path, $this->path . '/') !== 0) {
72
+            return null;
73
+        } else {
74
+            $path = substr($path, strlen($this->path));
75
+            return $this->normalizePath($path);
76
+        }
77
+    }
78
+
79
+    /**
80
+     * check if a node is a (grand-)child of the folder
81
+     *
82
+     * @param \OC\Files\Node\Node $node
83
+     * @return bool
84
+     */
85
+    public function isSubNode($node) {
86
+        return strpos($node->getPath(), $this->path . '/') === 0;
87
+    }
88
+
89
+    /**
90
+     * get the content of this directory
91
+     *
92
+     * @throws \OCP\Files\NotFoundException
93
+     * @return Node[]
94
+     */
95
+    public function getDirectoryListing() {
96
+        $folderContent = $this->view->getDirectoryContent($this->path);
97
+
98
+        return array_map(function (FileInfo $info) {
99
+            if ($info->getMimetype() === 'httpd/unix-directory') {
100
+                return new Folder($this->root, $this->view, $info->getPath(), $info);
101
+            } else {
102
+                return new File($this->root, $this->view, $info->getPath(), $info);
103
+            }
104
+        }, $folderContent);
105
+    }
106
+
107
+    /**
108
+     * @param string $path
109
+     * @param FileInfo $info
110
+     * @return File|Folder
111
+     */
112
+    protected function createNode($path, FileInfo $info = null) {
113
+        if (is_null($info)) {
114
+            $isDir = $this->view->is_dir($path);
115
+        } else {
116
+            $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
117
+        }
118
+        if ($isDir) {
119
+            return new Folder($this->root, $this->view, $path, $info);
120
+        } else {
121
+            return new File($this->root, $this->view, $path, $info);
122
+        }
123
+    }
124
+
125
+    /**
126
+     * Get the node at $path
127
+     *
128
+     * @param string $path
129
+     * @return \OC\Files\Node\Node
130
+     * @throws \OCP\Files\NotFoundException
131
+     */
132
+    public function get($path) {
133
+        return $this->root->get($this->getFullPath($path));
134
+    }
135
+
136
+    /**
137
+     * @param string $path
138
+     * @return bool
139
+     */
140
+    public function nodeExists($path) {
141
+        try {
142
+            $this->get($path);
143
+            return true;
144
+        } catch (NotFoundException $e) {
145
+            return false;
146
+        }
147
+    }
148
+
149
+    /**
150
+     * @param string $path
151
+     * @return \OC\Files\Node\Folder
152
+     * @throws \OCP\Files\NotPermittedException
153
+     */
154
+    public function newFolder($path) {
155
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
156
+            $fullPath = $this->getFullPath($path);
157
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
158
+            $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
159
+            $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
160
+            $this->view->mkdir($fullPath);
161
+            $node = new Folder($this->root, $this->view, $fullPath);
162
+            $this->root->emit('\OC\Files', 'postWrite', array($node));
163
+            $this->root->emit('\OC\Files', 'postCreate', array($node));
164
+            return $node;
165
+        } else {
166
+            throw new NotPermittedException('No create permission for folder');
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param string $path
172
+     * @return \OC\Files\Node\File
173
+     * @throws \OCP\Files\NotPermittedException
174
+     */
175
+    public function newFile($path) {
176
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
177
+            $fullPath = $this->getFullPath($path);
178
+            $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
179
+            $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
180
+            $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
181
+            $this->view->touch($fullPath);
182
+            $node = new File($this->root, $this->view, $fullPath);
183
+            $this->root->emit('\OC\Files', 'postWrite', array($node));
184
+            $this->root->emit('\OC\Files', 'postCreate', array($node));
185
+            return $node;
186
+        } else {
187
+            throw new NotPermittedException('No create permission for path');
188
+        }
189
+    }
190
+
191
+    /**
192
+     * search for files with the name matching $query
193
+     *
194
+     * @param string|ISearchOperator $query
195
+     * @return \OC\Files\Node\Node[]
196
+     */
197
+    public function search($query) {
198
+        if (is_string($query)) {
199
+            return $this->searchCommon('search', array('%' . $query . '%'));
200
+        } else {
201
+            return $this->searchCommon('searchQuery', array($query));
202
+        }
203
+    }
204
+
205
+    /**
206
+     * search for files by mimetype
207
+     *
208
+     * @param string $mimetype
209
+     * @return Node[]
210
+     */
211
+    public function searchByMime($mimetype) {
212
+        return $this->searchCommon('searchByMime', array($mimetype));
213
+    }
214
+
215
+    /**
216
+     * search for files by tag
217
+     *
218
+     * @param string|int $tag name or tag id
219
+     * @param string $userId owner of the tags
220
+     * @return Node[]
221
+     */
222
+    public function searchByTag($tag, $userId) {
223
+        return $this->searchCommon('searchByTag', array($tag, $userId));
224
+    }
225
+
226
+    /**
227
+     * @param string $method cache method
228
+     * @param array $args call args
229
+     * @return \OC\Files\Node\Node[]
230
+     */
231
+    private function searchCommon($method, $args) {
232
+        $files = array();
233
+        $rootLength = strlen($this->path);
234
+        $mount = $this->root->getMount($this->path);
235
+        $storage = $mount->getStorage();
236
+        $internalPath = $mount->getInternalPath($this->path);
237
+        $internalPath = rtrim($internalPath, '/');
238
+        if ($internalPath !== '') {
239
+            $internalPath = $internalPath . '/';
240
+        }
241
+        $internalRootLength = strlen($internalPath);
242
+
243
+        $cache = $storage->getCache('');
244
+
245
+        $results = call_user_func_array(array($cache, $method), $args);
246
+        foreach ($results as $result) {
247
+            if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
248
+                $result['internalPath'] = $result['path'];
249
+                $result['path'] = substr($result['path'], $internalRootLength);
250
+                $result['storage'] = $storage;
251
+                $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
252
+            }
253
+        }
254
+
255
+        $mounts = $this->root->getMountsIn($this->path);
256
+        foreach ($mounts as $mount) {
257
+            $storage = $mount->getStorage();
258
+            if ($storage) {
259
+                $cache = $storage->getCache('');
260
+
261
+                $relativeMountPoint = substr($mount->getMountPoint(), $rootLength);
262
+                $results = call_user_func_array(array($cache, $method), $args);
263
+                foreach ($results as $result) {
264
+                    $result['internalPath'] = $result['path'];
265
+                    $result['path'] = $relativeMountPoint . $result['path'];
266
+                    $result['storage'] = $storage;
267
+                    $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
268
+                }
269
+            }
270
+        }
271
+
272
+        return array_map(function (FileInfo $file) {
273
+            return $this->createNode($file->getPath(), $file);
274
+        }, $files);
275
+    }
276
+
277
+    /**
278
+     * @param int $id
279
+     * @return \OC\Files\Node\Node[]
280
+     */
281
+    public function getById($id) {
282
+        $mountCache = $this->root->getUserMountCache();
283
+        if (strpos($this->getPath(), '/', 1) > 0) {
284
+            list(, $user) = explode('/', $this->getPath());
285
+        } else {
286
+            $user = null;
287
+        }
288
+        $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
289
+        $mounts = $this->root->getMountsIn($this->path);
290
+        $mounts[] = $this->root->getMount($this->path);
291
+        /** @var IMountPoint[] $folderMounts */
292
+        $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
293
+            return $mountPoint->getMountPoint();
294
+        }, $mounts), $mounts);
295
+
296
+        /** @var ICachedMountInfo[] $mountsContainingFile */
297
+        $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
298
+            return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
299
+        }));
300
+
301
+        if (count($mountsContainingFile) === 0) {
302
+            return [];
303
+        }
304
+
305
+        $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
306
+            $mount = $folderMounts[$cachedMountInfo->getMountPoint()];
307
+            $cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
308
+            if (!$cacheEntry) {
309
+                return null;
310
+            }
311
+
312
+            // cache jails will hide the "true" internal path
313
+            $internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
314
+            $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
315
+            $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
316
+            $absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
317
+            return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
318
+                $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
319
+                \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
320
+            ));
321
+        }, $mountsContainingFile);
322
+
323
+        $nodes = array_filter($nodes);
324
+
325
+        return array_filter($nodes, function (Node $node) {
326
+            return $this->getRelativePath($node->getPath());
327
+        });
328
+    }
329
+
330
+    public function getFreeSpace() {
331
+        return $this->view->free_space($this->path);
332
+    }
333
+
334
+    public function delete() {
335
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
336
+            $this->sendHooks(array('preDelete'));
337
+            $fileInfo = $this->getFileInfo();
338
+            $this->view->rmdir($this->path);
339
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
340
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
341
+            $this->exists = false;
342
+        } else {
343
+            throw new NotPermittedException('No delete permission for path');
344
+        }
345
+    }
346
+
347
+    /**
348
+     * Add a suffix to the name in case the file exists
349
+     *
350
+     * @param string $name
351
+     * @return string
352
+     * @throws NotPermittedException
353
+     */
354
+    public function getNonExistingName($name) {
355
+        $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
356
+        return trim($this->getRelativePath($uniqueName), '/');
357
+    }
358
+
359
+    /**
360
+     * @param int $limit
361
+     * @param int $offset
362
+     * @return \OCP\Files\Node[]
363
+     */
364
+    public function getRecent($limit, $offset = 0) {
365
+        $mimetypeLoader = \OC::$server->getMimeTypeLoader();
366
+        $mounts = $this->root->getMountsIn($this->path);
367
+        $mounts[] = $this->getMountPoint();
368
+
369
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
370
+            return $mount->getStorage();
371
+        });
372
+        $storageIds = array_map(function (IMountPoint $mount) {
373
+            return $mount->getStorage()->getCache()->getNumericStorageId();
374
+        }, $mounts);
375
+        /** @var IMountPoint[] $mountMap */
376
+        $mountMap = array_combine($storageIds, $mounts);
377
+        $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
378
+
379
+        //todo look into options of filtering path based on storage id (only search in files/ for home storage, filter by share root for shared, etc)
380
+
381
+        $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
382
+        $query = $builder
383
+            ->select('f.*')
384
+            ->from('filecache', 'f')
385
+            ->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
386
+            ->andWhere($builder->expr()->orX(
387
+            // handle non empty folders separate
388
+                $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
389
+                $builder->expr()->eq('f.size', new Literal(0))
390
+            ))
391
+            ->orderBy('f.mtime', 'DESC')
392
+            ->setMaxResults($limit)
393
+            ->setFirstResult($offset);
394
+
395
+        $result = $query->execute()->fetchAll();
396
+
397
+        $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
398
+            $mount = $mountMap[$entry['storage']];
399
+            $entry['internalPath'] = $entry['path'];
400
+            $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
401
+            $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
402
+            $path = $this->getAbsolutePath($mount, $entry['path']);
403
+            if (is_null($path)) {
404
+                return null;
405
+            }
406
+            $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
407
+            return $this->root->createNode($fileInfo->getPath(), $fileInfo);
408
+        }, $result));
409
+
410
+        return array_values(array_filter($files, function (Node $node) {
411
+            $relative = $this->getRelativePath($node->getPath());
412
+            return $relative !== null && $relative !== '/';
413
+        }));
414
+    }
415
+
416
+    private function getAbsolutePath(IMountPoint $mount, $path) {
417
+        $storage = $mount->getStorage();
418
+        if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
419
+            /** @var \OC\Files\Storage\Wrapper\Jail $storage */
420
+            $jailRoot = $storage->getUnjailedPath('');
421
+            $rootLength = strlen($jailRoot) + 1;
422
+            if ($path === $jailRoot) {
423
+                return $mount->getMountPoint();
424
+            } else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
425
+                return $mount->getMountPoint() . substr($path, $rootLength);
426
+            } else {
427
+                return null;
428
+            }
429
+        } else {
430
+            return $mount->getMountPoint() . $path;
431
+        }
432
+    }
433 433
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 		if (!$this->isValidPath($path)) {
56 56
 			throw new NotPermittedException('Invalid path');
57 57
 		}
58
-		return $this->path . $this->normalizePath($path);
58
+		return $this->path.$this->normalizePath($path);
59 59
 	}
60 60
 
61 61
 	/**
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
 		}
69 69
 		if ($path === $this->path) {
70 70
 			return '/';
71
-		} else if (strpos($path, $this->path . '/') !== 0) {
71
+		} else if (strpos($path, $this->path.'/') !== 0) {
72 72
 			return null;
73 73
 		} else {
74 74
 			$path = substr($path, strlen($this->path));
@@ -83,7 +83,7 @@  discard block
 block discarded – undo
83 83
 	 * @return bool
84 84
 	 */
85 85
 	public function isSubNode($node) {
86
-		return strpos($node->getPath(), $this->path . '/') === 0;
86
+		return strpos($node->getPath(), $this->path.'/') === 0;
87 87
 	}
88 88
 
89 89
 	/**
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	public function getDirectoryListing() {
96 96
 		$folderContent = $this->view->getDirectoryContent($this->path);
97 97
 
98
-		return array_map(function (FileInfo $info) {
98
+		return array_map(function(FileInfo $info) {
99 99
 			if ($info->getMimetype() === 'httpd/unix-directory') {
100 100
 				return new Folder($this->root, $this->view, $info->getPath(), $info);
101 101
 			} else {
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
 	 */
197 197
 	public function search($query) {
198 198
 		if (is_string($query)) {
199
-			return $this->searchCommon('search', array('%' . $query . '%'));
199
+			return $this->searchCommon('search', array('%'.$query.'%'));
200 200
 		} else {
201 201
 			return $this->searchCommon('searchQuery', array($query));
202 202
 		}
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
 		$internalPath = $mount->getInternalPath($this->path);
237 237
 		$internalPath = rtrim($internalPath, '/');
238 238
 		if ($internalPath !== '') {
239
-			$internalPath = $internalPath . '/';
239
+			$internalPath = $internalPath.'/';
240 240
 		}
241 241
 		$internalRootLength = strlen($internalPath);
242 242
 
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 				$result['internalPath'] = $result['path'];
249 249
 				$result['path'] = substr($result['path'], $internalRootLength);
250 250
 				$result['storage'] = $storage;
251
-				$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
251
+				$files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount);
252 252
 			}
253 253
 		}
254 254
 
@@ -262,14 +262,14 @@  discard block
 block discarded – undo
262 262
 				$results = call_user_func_array(array($cache, $method), $args);
263 263
 				foreach ($results as $result) {
264 264
 					$result['internalPath'] = $result['path'];
265
-					$result['path'] = $relativeMountPoint . $result['path'];
265
+					$result['path'] = $relativeMountPoint.$result['path'];
266 266
 					$result['storage'] = $storage;
267
-					$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
267
+					$files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount);
268 268
 				}
269 269
 			}
270 270
 		}
271 271
 
272
-		return array_map(function (FileInfo $file) {
272
+		return array_map(function(FileInfo $file) {
273 273
 			return $this->createNode($file->getPath(), $file);
274 274
 		}, $files);
275 275
 	}
@@ -285,16 +285,16 @@  discard block
 block discarded – undo
285 285
 		} else {
286 286
 			$user = null;
287 287
 		}
288
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user);
288
+		$mountsContainingFile = $mountCache->getMountsForFileId((int) $id, $user);
289 289
 		$mounts = $this->root->getMountsIn($this->path);
290 290
 		$mounts[] = $this->root->getMount($this->path);
291 291
 		/** @var IMountPoint[] $folderMounts */
292
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
292
+		$folderMounts = array_combine(array_map(function(IMountPoint $mountPoint) {
293 293
 			return $mountPoint->getMountPoint();
294 294
 		}, $mounts), $mounts);
295 295
 
296 296
 		/** @var ICachedMountInfo[] $mountsContainingFile */
297
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
297
+		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function(ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
298 298
 			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
299 299
 		}));
300 300
 
@@ -302,18 +302,18 @@  discard block
 block discarded – undo
302 302
 			return [];
303 303
 		}
304 304
 
305
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
305
+		$nodes = array_map(function(ICachedMountInfo $cachedMountInfo) use ($folderMounts, $id) {
306 306
 			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
307
-			$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
307
+			$cacheEntry = $mount->getStorage()->getCache()->get((int) $id);
308 308
 			if (!$cacheEntry) {
309 309
 				return null;
310 310
 			}
311 311
 
312 312
 			// cache jails will hide the "true" internal path
313
-			$internalPath = ltrim($cachedMountInfo->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
313
+			$internalPath = ltrim($cachedMountInfo->getRootInternalPath().'/'.$cacheEntry->getPath(), '/');
314 314
 			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
315 315
 			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
316
-			$absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
316
+			$absolutePath = $cachedMountInfo->getMountPoint().$pathRelativeToMount;
317 317
 			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
318 318
 				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
319 319
 				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 
323 323
 		$nodes = array_filter($nodes);
324 324
 
325
-		return array_filter($nodes, function (Node $node) {
325
+		return array_filter($nodes, function(Node $node) {
326 326
 			return $this->getRelativePath($node->getPath());
327 327
 		});
328 328
 	}
@@ -366,10 +366,10 @@  discard block
 block discarded – undo
366 366
 		$mounts = $this->root->getMountsIn($this->path);
367 367
 		$mounts[] = $this->getMountPoint();
368 368
 
369
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
369
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
370 370
 			return $mount->getStorage();
371 371
 		});
372
-		$storageIds = array_map(function (IMountPoint $mount) {
372
+		$storageIds = array_map(function(IMountPoint $mount) {
373 373
 			return $mount->getStorage()->getCache()->getNumericStorageId();
374 374
 		}, $mounts);
375 375
 		/** @var IMountPoint[] $mountMap */
@@ -394,7 +394,7 @@  discard block
 block discarded – undo
394 394
 
395 395
 		$result = $query->execute()->fetchAll();
396 396
 
397
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
397
+		$files = array_filter(array_map(function(array $entry) use ($mountMap, $mimetypeLoader) {
398 398
 			$mount = $mountMap[$entry['storage']];
399 399
 			$entry['internalPath'] = $entry['path'];
400 400
 			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
 			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
408 408
 		}, $result));
409 409
 
410
-		return array_values(array_filter($files, function (Node $node) {
410
+		return array_values(array_filter($files, function(Node $node) {
411 411
 			$relative = $this->getRelativePath($node->getPath());
412 412
 			return $relative !== null && $relative !== '/';
413 413
 		}));
@@ -421,13 +421,13 @@  discard block
 block discarded – undo
421 421
 			$rootLength = strlen($jailRoot) + 1;
422 422
 			if ($path === $jailRoot) {
423 423
 				return $mount->getMountPoint();
424
-			} else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
425
-				return $mount->getMountPoint() . substr($path, $rootLength);
424
+			} else if (substr($path, 0, $rootLength) === $jailRoot.'/') {
425
+				return $mount->getMountPoint().substr($path, $rootLength);
426 426
 			} else {
427 427
 				return null;
428 428
 			}
429 429
 		} else {
430
-			return $mount->getMountPoint() . $path;
430
+			return $mount->getMountPoint().$path;
431 431
 		}
432 432
 	}
433 433
 }
Please login to merge, or discard this patch.
lib/public/Settings/IIconSection.php 2 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -33,6 +33,7 @@
 block discarded – undo
33 33
 	 *
34 34
 	 * @returns string
35 35
 	 * @since 12
36
+	 * @return string
36 37
 	 */
37 38
 	public function getIcon();
38 39
 }
Please login to merge, or discard this patch.
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@
 block discarded – undo
27 27
  * @since 12
28 28
  */
29 29
 interface IIconSection extends ISection {
30
-	/**
31
-	 * returns the relative path to an 16*16 icon describing the section.
32
-	 * e.g. '/core/img/places/files.svg'
33
-	 *
34
-	 * @returns string
35
-	 * @since 12
36
-	 */
37
-	public function getIcon();
30
+    /**
31
+     * returns the relative path to an 16*16 icon describing the section.
32
+     * e.g. '/core/img/places/files.svg'
33
+     *
34
+     * @returns string
35
+     * @since 12
36
+     */
37
+    public function getIcon();
38 38
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/FTP.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -139,6 +139,9 @@
 block discarded – undo
139 139
 		return false;
140 140
 	}
141 141
 
142
+	/**
143
+	 * @param string $path
144
+	 */
142 145
 	public function writeBack($tmpFile, $path) {
143 146
 		$this->uploadFile($tmpFile, $path);
144 147
 		unlink($tmpFile);
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,8 +93,7 @@
 block discarded – undo
93 93
 	public function unlink($path) {
94 94
 		if ($this->is_dir($path)) {
95 95
 			return $this->rmdir($path);
96
-		}
97
-		else {
96
+		} else {
98 97
 			$url = $this->constructUrl($path);
99 98
 			$result = unlink($url);
100 99
 			clearstatcache(true, $url);
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -38,122 +38,122 @@
 block discarded – undo
38 38
 use Icewind\Streams\RetryWrapper;
39 39
 
40 40
 class FTP extends StreamWrapper{
41
-	private $password;
42
-	private $user;
43
-	private $host;
44
-	private $secure;
45
-	private $root;
41
+    private $password;
42
+    private $user;
43
+    private $host;
44
+    private $secure;
45
+    private $root;
46 46
 
47
-	private static $tempFiles=array();
47
+    private static $tempFiles=array();
48 48
 
49
-	public function __construct($params) {
50
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
-			$this->host=$params['host'];
52
-			$this->user=$params['user'];
53
-			$this->password=$params['password'];
54
-			if (isset($params['secure'])) {
55
-				$this->secure = $params['secure'];
56
-			} else {
57
-				$this->secure = false;
58
-			}
59
-			$this->root=isset($params['root'])?$params['root']:'/';
60
-			if ( ! $this->root || $this->root[0]!=='/') {
61
-				$this->root='/'.$this->root;
62
-			}
63
-			if (substr($this->root, -1) !== '/') {
64
-				$this->root .= '/';
65
-			}
66
-		} else {
67
-			throw new \Exception('Creating FTP storage failed');
68
-		}
49
+    public function __construct($params) {
50
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
+            $this->host=$params['host'];
52
+            $this->user=$params['user'];
53
+            $this->password=$params['password'];
54
+            if (isset($params['secure'])) {
55
+                $this->secure = $params['secure'];
56
+            } else {
57
+                $this->secure = false;
58
+            }
59
+            $this->root=isset($params['root'])?$params['root']:'/';
60
+            if ( ! $this->root || $this->root[0]!=='/') {
61
+                $this->root='/'.$this->root;
62
+            }
63
+            if (substr($this->root, -1) !== '/') {
64
+                $this->root .= '/';
65
+            }
66
+        } else {
67
+            throw new \Exception('Creating FTP storage failed');
68
+        }
69 69
 		
70
-	}
70
+    }
71 71
 
72
-	public function getId(){
73
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
74
-	}
72
+    public function getId(){
73
+        return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
74
+    }
75 75
 
76
-	/**
77
-	 * construct the ftp url
78
-	 * @param string $path
79
-	 * @return string
80
-	 */
81
-	public function constructUrl($path) {
82
-		$url='ftp';
83
-		if ($this->secure) {
84
-			$url.='s';
85
-		}
86
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87
-		return $url;
88
-	}
76
+    /**
77
+     * construct the ftp url
78
+     * @param string $path
79
+     * @return string
80
+     */
81
+    public function constructUrl($path) {
82
+        $url='ftp';
83
+        if ($this->secure) {
84
+            $url.='s';
85
+        }
86
+        $url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87
+        return $url;
88
+    }
89 89
 
90
-	/**
91
-	 * Unlinks file or directory
92
-	 * @param string $path
93
-	 */
94
-	public function unlink($path) {
95
-		if ($this->is_dir($path)) {
96
-			return $this->rmdir($path);
97
-		}
98
-		else {
99
-			$url = $this->constructUrl($path);
100
-			$result = unlink($url);
101
-			clearstatcache(true, $url);
102
-			return $result;
103
-		}
104
-	}
105
-	public function fopen($path,$mode) {
106
-		switch($mode) {
107
-			case 'r':
108
-			case 'rb':
109
-			case 'w':
110
-			case 'wb':
111
-			case 'a':
112
-			case 'ab':
113
-				//these are supported by the wrapper
114
-				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
115
-				$handle = fopen($this->constructUrl($path), $mode, false, $context);
116
-				return RetryWrapper::wrap($handle);
117
-			case 'r+':
118
-			case 'w+':
119
-			case 'wb+':
120
-			case 'a+':
121
-			case 'x':
122
-			case 'x+':
123
-			case 'c':
124
-			case 'c+':
125
-				//emulate these
126
-				if (strrpos($path, '.')!==false) {
127
-					$ext=substr($path, strrpos($path, '.'));
128
-				} else {
129
-					$ext='';
130
-				}
131
-				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
132
-				if ($this->file_exists($path)) {
133
-					$this->getFile($path, $tmpFile);
134
-				}
135
-				$handle = fopen($tmpFile, $mode);
136
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
137
-					$this->writeBack($tmpFile, $path);
138
-				});
139
-		}
140
-		return false;
141
-	}
90
+    /**
91
+     * Unlinks file or directory
92
+     * @param string $path
93
+     */
94
+    public function unlink($path) {
95
+        if ($this->is_dir($path)) {
96
+            return $this->rmdir($path);
97
+        }
98
+        else {
99
+            $url = $this->constructUrl($path);
100
+            $result = unlink($url);
101
+            clearstatcache(true, $url);
102
+            return $result;
103
+        }
104
+    }
105
+    public function fopen($path,$mode) {
106
+        switch($mode) {
107
+            case 'r':
108
+            case 'rb':
109
+            case 'w':
110
+            case 'wb':
111
+            case 'a':
112
+            case 'ab':
113
+                //these are supported by the wrapper
114
+                $context = stream_context_create(array('ftp' => array('overwrite' => true)));
115
+                $handle = fopen($this->constructUrl($path), $mode, false, $context);
116
+                return RetryWrapper::wrap($handle);
117
+            case 'r+':
118
+            case 'w+':
119
+            case 'wb+':
120
+            case 'a+':
121
+            case 'x':
122
+            case 'x+':
123
+            case 'c':
124
+            case 'c+':
125
+                //emulate these
126
+                if (strrpos($path, '.')!==false) {
127
+                    $ext=substr($path, strrpos($path, '.'));
128
+                } else {
129
+                    $ext='';
130
+                }
131
+                $tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
132
+                if ($this->file_exists($path)) {
133
+                    $this->getFile($path, $tmpFile);
134
+                }
135
+                $handle = fopen($tmpFile, $mode);
136
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
137
+                    $this->writeBack($tmpFile, $path);
138
+                });
139
+        }
140
+        return false;
141
+    }
142 142
 
143
-	public function writeBack($tmpFile, $path) {
144
-		$this->uploadFile($tmpFile, $path);
145
-		unlink($tmpFile);
146
-	}
143
+    public function writeBack($tmpFile, $path) {
144
+        $this->uploadFile($tmpFile, $path);
145
+        unlink($tmpFile);
146
+    }
147 147
 
148
-	/**
149
-	 * check if php-ftp is installed
150
-	 */
151
-	public static function checkDependencies() {
152
-		if (function_exists('ftp_login')) {
153
-			return true;
154
-		} else {
155
-			return array('ftp');
156
-		}
157
-	}
148
+    /**
149
+     * check if php-ftp is installed
150
+     */
151
+    public static function checkDependencies() {
152
+        if (function_exists('ftp_login')) {
153
+            return true;
154
+        } else {
155
+            return array('ftp');
156
+        }
157
+    }
158 158
 
159 159
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -37,28 +37,28 @@  discard block
 block discarded – undo
37 37
 use Icewind\Streams\CallbackWrapper;
38 38
 use Icewind\Streams\RetryWrapper;
39 39
 
40
-class FTP extends StreamWrapper{
40
+class FTP extends StreamWrapper {
41 41
 	private $password;
42 42
 	private $user;
43 43
 	private $host;
44 44
 	private $secure;
45 45
 	private $root;
46 46
 
47
-	private static $tempFiles=array();
47
+	private static $tempFiles = array();
48 48
 
49 49
 	public function __construct($params) {
50 50
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
51
-			$this->host=$params['host'];
52
-			$this->user=$params['user'];
53
-			$this->password=$params['password'];
51
+			$this->host = $params['host'];
52
+			$this->user = $params['user'];
53
+			$this->password = $params['password'];
54 54
 			if (isset($params['secure'])) {
55 55
 				$this->secure = $params['secure'];
56 56
 			} else {
57 57
 				$this->secure = false;
58 58
 			}
59
-			$this->root=isset($params['root'])?$params['root']:'/';
60
-			if ( ! $this->root || $this->root[0]!=='/') {
61
-				$this->root='/'.$this->root;
59
+			$this->root = isset($params['root']) ? $params['root'] : '/';
60
+			if (!$this->root || $this->root[0] !== '/') {
61
+				$this->root = '/'.$this->root;
62 62
 			}
63 63
 			if (substr($this->root, -1) !== '/') {
64 64
 				$this->root .= '/';
@@ -69,8 +69,8 @@  discard block
 block discarded – undo
69 69
 		
70 70
 	}
71 71
 
72
-	public function getId(){
73
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
72
+	public function getId() {
73
+		return 'ftp::'.$this->user.'@'.$this->host.'/'.$this->root;
74 74
 	}
75 75
 
76 76
 	/**
@@ -79,11 +79,11 @@  discard block
 block discarded – undo
79 79
 	 * @return string
80 80
 	 */
81 81
 	public function constructUrl($path) {
82
-		$url='ftp';
82
+		$url = 'ftp';
83 83
 		if ($this->secure) {
84
-			$url.='s';
84
+			$url .= 's';
85 85
 		}
86
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
+		$url .= '://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
87 87
 		return $url;
88 88
 	}
89 89
 
@@ -102,8 +102,8 @@  discard block
 block discarded – undo
102 102
 			return $result;
103 103
 		}
104 104
 	}
105
-	public function fopen($path,$mode) {
106
-		switch($mode) {
105
+	public function fopen($path, $mode) {
106
+		switch ($mode) {
107 107
 			case 'r':
108 108
 			case 'rb':
109 109
 			case 'w':
@@ -123,17 +123,17 @@  discard block
 block discarded – undo
123 123
 			case 'c':
124 124
 			case 'c+':
125 125
 				//emulate these
126
-				if (strrpos($path, '.')!==false) {
127
-					$ext=substr($path, strrpos($path, '.'));
126
+				if (strrpos($path, '.') !== false) {
127
+					$ext = substr($path, strrpos($path, '.'));
128 128
 				} else {
129
-					$ext='';
129
+					$ext = '';
130 130
 				}
131 131
 				$tmpFile = \OC::$server->getTempManager()->getTemporaryFile();
132 132
 				if ($this->file_exists($path)) {
133 133
 					$this->getFile($path, $tmpFile);
134 134
 				}
135 135
 				$handle = fopen($tmpFile, $mode);
136
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
137 137
 					$this->writeBack($tmpFile, $path);
138 138
 				});
139 139
 		}
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Indentation   +526 added lines, -527 removed lines patch added patch discarded remove patch
@@ -70,535 +70,534 @@
 block discarded – undo
70 70
  */
71 71
 class ShareController extends AuthPublicShareController {
72 72
 
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var IUserManager */
76
-	protected $userManager;
77
-	/** @var ILogger */
78
-	protected $logger;
79
-	/** @var \OCP\Activity\IManager */
80
-	protected $activityManager;
81
-	/** @var IPreview */
82
-	protected $previewManager;
83
-	/** @var IRootFolder */
84
-	protected $rootFolder;
85
-	/** @var FederatedShareProvider */
86
-	protected $federatedShareProvider;
87
-	/** @var EventDispatcherInterface */
88
-	protected $eventDispatcher;
89
-	/** @var IL10N */
90
-	protected $l10n;
91
-	/** @var Defaults */
92
-	protected $defaults;
93
-	/** @var ShareManager */
94
-	protected $shareManager;
95
-
96
-	/** @var Share\IShare */
97
-	protected $share;
98
-
99
-	/**
100
-	 * @param string $appName
101
-	 * @param IRequest $request
102
-	 * @param IConfig $config
103
-	 * @param IURLGenerator $urlGenerator
104
-	 * @param IUserManager $userManager
105
-	 * @param ILogger $logger
106
-	 * @param \OCP\Activity\IManager $activityManager
107
-	 * @param \OCP\Share\IManager $shareManager
108
-	 * @param ISession $session
109
-	 * @param IPreview $previewManager
110
-	 * @param IRootFolder $rootFolder
111
-	 * @param FederatedShareProvider $federatedShareProvider
112
-	 * @param EventDispatcherInterface $eventDispatcher
113
-	 * @param IL10N $l10n
114
-	 * @param Defaults $defaults
115
-	 */
116
-	public function __construct(string $appName,
117
-								IRequest $request,
118
-								IConfig $config,
119
-								IURLGenerator $urlGenerator,
120
-								IUserManager $userManager,
121
-								ILogger $logger,
122
-								\OCP\Activity\IManager $activityManager,
123
-								ShareManager $shareManager,
124
-								ISession $session,
125
-								IPreview $previewManager,
126
-								IRootFolder $rootFolder,
127
-								FederatedShareProvider $federatedShareProvider,
128
-								EventDispatcherInterface $eventDispatcher,
129
-								IL10N $l10n,
130
-								Defaults $defaults) {
131
-		parent::__construct($appName, $request, $session, $urlGenerator);
132
-
133
-		$this->config = $config;
134
-		$this->userManager = $userManager;
135
-		$this->logger = $logger;
136
-		$this->activityManager = $activityManager;
137
-		$this->previewManager = $previewManager;
138
-		$this->rootFolder = $rootFolder;
139
-		$this->federatedShareProvider = $federatedShareProvider;
140
-		$this->eventDispatcher = $eventDispatcher;
141
-		$this->l10n = $l10n;
142
-		$this->defaults = $defaults;
143
-		$this->shareManager = $shareManager;
144
-	}
145
-
146
-	protected function verifyPassword(string $password): bool {
147
-		return $this->shareManager->checkPassword($this->share, $password);
148
-	}
149
-
150
-	protected function getPasswordHash(): string {
151
-		return $this->share->getPassword();
152
-	}
153
-
154
-	public function isValidToken(): bool {
155
-		try {
156
-			$this->share = $this->shareManager->getShareByToken($this->getToken());
157
-		} catch (ShareNotFound $e) {
158
-			return false;
159
-		}
160
-
161
-		return true;
162
-	}
163
-
164
-	protected function isPasswordProtected(): bool {
165
-		return $this->share->getPassword() !== null;
166
-	}
167
-
168
-	protected function authSucceeded() {
169
-		// For share this was always set so it is still used in other apps
170
-		$this->session->set('public_link_authenticated', (string)$this->share->getId());
171
-	}
172
-
173
-	protected function authFailed() {
174
-		$this->emitAccessShareHook($this->share, 403, 'Wrong password');
175
-	}
176
-
177
-	/**
178
-	 * throws hooks when a share is attempted to be accessed
179
-	 *
180
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
181
-	 * otherwise token
182
-	 * @param int $errorCode
183
-	 * @param string $errorMessage
184
-	 * @throws \OC\HintException
185
-	 * @throws \OC\ServerNotAvailableException
186
-	 */
187
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
188
-		$itemType = $itemSource = $uidOwner = '';
189
-		$token = $share;
190
-		$exception = null;
191
-		if($share instanceof \OCP\Share\IShare) {
192
-			try {
193
-				$token = $share->getToken();
194
-				$uidOwner = $share->getSharedBy();
195
-				$itemType = $share->getNodeType();
196
-				$itemSource = $share->getNodeId();
197
-			} catch (\Exception $e) {
198
-				// we log what we know and pass on the exception afterwards
199
-				$exception = $e;
200
-			}
201
-		}
202
-		\OC_Hook::emit(Share::class, 'share_link_access', [
203
-			'itemType' => $itemType,
204
-			'itemSource' => $itemSource,
205
-			'uidOwner' => $uidOwner,
206
-			'token' => $token,
207
-			'errorCode' => $errorCode,
208
-			'errorMessage' => $errorMessage,
209
-		]);
210
-		if(!is_null($exception)) {
211
-			throw $exception;
212
-		}
213
-	}
214
-
215
-	/**
216
-	 * Validate the permissions of the share
217
-	 *
218
-	 * @param Share\IShare $share
219
-	 * @return bool
220
-	 */
221
-	private function validateShare(\OCP\Share\IShare $share) {
222
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
223
-	}
224
-
225
-	/**
226
-	 * @PublicPage
227
-	 * @NoCSRFRequired
228
-	 *
229
-
230
-	 * @param string $path
231
-	 * @return TemplateResponse
232
-	 * @throws NotFoundException
233
-	 * @throws \Exception
234
-	 */
235
-	public function showShare($path = ''): TemplateResponse {
236
-		\OC_User::setIncognitoMode(true);
237
-
238
-		// Check whether share exists
239
-		try {
240
-			$share = $this->shareManager->getShareByToken($this->getToken());
241
-		} catch (ShareNotFound $e) {
242
-			$this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
243
-			throw new NotFoundException();
244
-		}
245
-
246
-		if (!$this->validateShare($share)) {
247
-			throw new NotFoundException();
248
-		}
249
-		// We can't get the path of a file share
250
-		try {
251
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
252
-				$this->emitAccessShareHook($share, 404, 'Share not found');
253
-				throw new NotFoundException();
254
-			}
255
-		} catch (\Exception $e) {
256
-			$this->emitAccessShareHook($share, 404, 'Share not found');
257
-			throw $e;
258
-		}
259
-
260
-		$shareTmpl = [];
261
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
262
-		$shareTmpl['owner'] = $share->getShareOwner();
263
-		$shareTmpl['filename'] = $share->getNode()->getName();
264
-		$shareTmpl['directory_path'] = $share->getTarget();
265
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
266
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
267
-		$shareTmpl['dirToken'] = $this->getToken();
268
-		$shareTmpl['sharingToken'] = $this->getToken();
269
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
270
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
271
-		$shareTmpl['dir'] = '';
272
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
273
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
274
-
275
-		// Show file list
276
-		$hideFileList = false;
277
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
278
-			/** @var \OCP\Files\Folder $rootFolder */
279
-			$rootFolder = $share->getNode();
280
-
281
-			try {
282
-				$folderNode = $rootFolder->get($path);
283
-			} catch (\OCP\Files\NotFoundException $e) {
284
-				$this->emitAccessShareHook($share, 404, 'Share not found');
285
-				throw new NotFoundException();
286
-			}
287
-
288
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
289
-
290
-			/*
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var IUserManager */
76
+    protected $userManager;
77
+    /** @var ILogger */
78
+    protected $logger;
79
+    /** @var \OCP\Activity\IManager */
80
+    protected $activityManager;
81
+    /** @var IPreview */
82
+    protected $previewManager;
83
+    /** @var IRootFolder */
84
+    protected $rootFolder;
85
+    /** @var FederatedShareProvider */
86
+    protected $federatedShareProvider;
87
+    /** @var EventDispatcherInterface */
88
+    protected $eventDispatcher;
89
+    /** @var IL10N */
90
+    protected $l10n;
91
+    /** @var Defaults */
92
+    protected $defaults;
93
+    /** @var ShareManager */
94
+    protected $shareManager;
95
+
96
+    /** @var Share\IShare */
97
+    protected $share;
98
+
99
+    /**
100
+     * @param string $appName
101
+     * @param IRequest $request
102
+     * @param IConfig $config
103
+     * @param IURLGenerator $urlGenerator
104
+     * @param IUserManager $userManager
105
+     * @param ILogger $logger
106
+     * @param \OCP\Activity\IManager $activityManager
107
+     * @param \OCP\Share\IManager $shareManager
108
+     * @param ISession $session
109
+     * @param IPreview $previewManager
110
+     * @param IRootFolder $rootFolder
111
+     * @param FederatedShareProvider $federatedShareProvider
112
+     * @param EventDispatcherInterface $eventDispatcher
113
+     * @param IL10N $l10n
114
+     * @param Defaults $defaults
115
+     */
116
+    public function __construct(string $appName,
117
+                                IRequest $request,
118
+                                IConfig $config,
119
+                                IURLGenerator $urlGenerator,
120
+                                IUserManager $userManager,
121
+                                ILogger $logger,
122
+                                \OCP\Activity\IManager $activityManager,
123
+                                ShareManager $shareManager,
124
+                                ISession $session,
125
+                                IPreview $previewManager,
126
+                                IRootFolder $rootFolder,
127
+                                FederatedShareProvider $federatedShareProvider,
128
+                                EventDispatcherInterface $eventDispatcher,
129
+                                IL10N $l10n,
130
+                                Defaults $defaults) {
131
+        parent::__construct($appName, $request, $session, $urlGenerator);
132
+
133
+        $this->config = $config;
134
+        $this->userManager = $userManager;
135
+        $this->logger = $logger;
136
+        $this->activityManager = $activityManager;
137
+        $this->previewManager = $previewManager;
138
+        $this->rootFolder = $rootFolder;
139
+        $this->federatedShareProvider = $federatedShareProvider;
140
+        $this->eventDispatcher = $eventDispatcher;
141
+        $this->l10n = $l10n;
142
+        $this->defaults = $defaults;
143
+        $this->shareManager = $shareManager;
144
+    }
145
+
146
+    protected function verifyPassword(string $password): bool {
147
+        return $this->shareManager->checkPassword($this->share, $password);
148
+    }
149
+
150
+    protected function getPasswordHash(): string {
151
+        return $this->share->getPassword();
152
+    }
153
+
154
+    public function isValidToken(): bool {
155
+        try {
156
+            $this->share = $this->shareManager->getShareByToken($this->getToken());
157
+        } catch (ShareNotFound $e) {
158
+            return false;
159
+        }
160
+
161
+        return true;
162
+    }
163
+
164
+    protected function isPasswordProtected(): bool {
165
+        return $this->share->getPassword() !== null;
166
+    }
167
+
168
+    protected function authSucceeded() {
169
+        // For share this was always set so it is still used in other apps
170
+        $this->session->set('public_link_authenticated', (string)$this->share->getId());
171
+    }
172
+
173
+    protected function authFailed() {
174
+        $this->emitAccessShareHook($this->share, 403, 'Wrong password');
175
+    }
176
+
177
+    /**
178
+     * throws hooks when a share is attempted to be accessed
179
+     *
180
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
181
+     * otherwise token
182
+     * @param int $errorCode
183
+     * @param string $errorMessage
184
+     * @throws \OC\HintException
185
+     * @throws \OC\ServerNotAvailableException
186
+     */
187
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
188
+        $itemType = $itemSource = $uidOwner = '';
189
+        $token = $share;
190
+        $exception = null;
191
+        if($share instanceof \OCP\Share\IShare) {
192
+            try {
193
+                $token = $share->getToken();
194
+                $uidOwner = $share->getSharedBy();
195
+                $itemType = $share->getNodeType();
196
+                $itemSource = $share->getNodeId();
197
+            } catch (\Exception $e) {
198
+                // we log what we know and pass on the exception afterwards
199
+                $exception = $e;
200
+            }
201
+        }
202
+        \OC_Hook::emit(Share::class, 'share_link_access', [
203
+            'itemType' => $itemType,
204
+            'itemSource' => $itemSource,
205
+            'uidOwner' => $uidOwner,
206
+            'token' => $token,
207
+            'errorCode' => $errorCode,
208
+            'errorMessage' => $errorMessage,
209
+        ]);
210
+        if(!is_null($exception)) {
211
+            throw $exception;
212
+        }
213
+    }
214
+
215
+    /**
216
+     * Validate the permissions of the share
217
+     *
218
+     * @param Share\IShare $share
219
+     * @return bool
220
+     */
221
+    private function validateShare(\OCP\Share\IShare $share) {
222
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
223
+    }
224
+
225
+    /**
226
+     * @PublicPage
227
+     * @NoCSRFRequired
228
+     *
229
+     * @param string $path
230
+     * @return TemplateResponse
231
+     * @throws NotFoundException
232
+     * @throws \Exception
233
+     */
234
+    public function showShare($path = ''): TemplateResponse {
235
+        \OC_User::setIncognitoMode(true);
236
+
237
+        // Check whether share exists
238
+        try {
239
+            $share = $this->shareManager->getShareByToken($this->getToken());
240
+        } catch (ShareNotFound $e) {
241
+            $this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
242
+            throw new NotFoundException();
243
+        }
244
+
245
+        if (!$this->validateShare($share)) {
246
+            throw new NotFoundException();
247
+        }
248
+        // We can't get the path of a file share
249
+        try {
250
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
251
+                $this->emitAccessShareHook($share, 404, 'Share not found');
252
+                throw new NotFoundException();
253
+            }
254
+        } catch (\Exception $e) {
255
+            $this->emitAccessShareHook($share, 404, 'Share not found');
256
+            throw $e;
257
+        }
258
+
259
+        $shareTmpl = [];
260
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
261
+        $shareTmpl['owner'] = $share->getShareOwner();
262
+        $shareTmpl['filename'] = $share->getNode()->getName();
263
+        $shareTmpl['directory_path'] = $share->getTarget();
264
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
265
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
266
+        $shareTmpl['dirToken'] = $this->getToken();
267
+        $shareTmpl['sharingToken'] = $this->getToken();
268
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
269
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
270
+        $shareTmpl['dir'] = '';
271
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
272
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
273
+
274
+        // Show file list
275
+        $hideFileList = false;
276
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
277
+            /** @var \OCP\Files\Folder $rootFolder */
278
+            $rootFolder = $share->getNode();
279
+
280
+            try {
281
+                $folderNode = $rootFolder->get($path);
282
+            } catch (\OCP\Files\NotFoundException $e) {
283
+                $this->emitAccessShareHook($share, 404, 'Share not found');
284
+                throw new NotFoundException();
285
+            }
286
+
287
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
288
+
289
+            /*
291 290
 			 * The OC_Util methods require a view. This just uses the node API
292 291
 			 */
293
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
294
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
295
-				$freeSpace = max($freeSpace, 0);
296
-			} else {
297
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
298
-			}
299
-
300
-			$hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
301
-			$maxUploadFilesize = $freeSpace;
302
-
303
-			$folder = new Template('files', 'list', '');
304
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
305
-			$folder->assign('dirToken', $this->getToken());
306
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
307
-			$folder->assign('isPublic', true);
308
-			$folder->assign('hideFileList', $hideFileList);
309
-			$folder->assign('publicUploadEnabled', 'no');
310
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
311
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
312
-			$folder->assign('freeSpace', $freeSpace);
313
-			$folder->assign('usedSpacePercent', 0);
314
-			$folder->assign('trash', false);
315
-			$shareTmpl['folder'] = $folder->fetchPage();
316
-		}
317
-
318
-		$shareTmpl['hideFileList'] = $hideFileList;
319
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
320
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $this->getToken()]);
321
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
322
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
323
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
324
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
325
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
326
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
327
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
328
-		$ogPreview = '';
329
-		if ($shareTmpl['previewSupported']) {
330
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
331
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
332
-			$ogPreview = $shareTmpl['previewImage'];
333
-
334
-			// We just have direct previews for image files
335
-			if ($share->getNode()->getMimePart() === 'image') {
336
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
337
-
338
-				$ogPreview = $shareTmpl['previewURL'];
339
-
340
-				//Whatapp is kind of picky about their size requirements
341
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
342
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
343
-						'token' => $this->getToken(),
344
-						'x' => 256,
345
-						'y' => 256,
346
-						'a' => true,
347
-					]);
348
-				}
349
-			}
350
-		} else {
351
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
352
-			$ogPreview = $shareTmpl['previewImage'];
353
-		}
354
-
355
-		// Load files we need
356
-		\OCP\Util::addScript('files', 'file-upload');
357
-		\OCP\Util::addStyle('files_sharing', 'publicView');
358
-		\OCP\Util::addScript('files_sharing', 'public');
359
-		\OCP\Util::addScript('files', 'fileactions');
360
-		\OCP\Util::addScript('files', 'fileactionsmenu');
361
-		\OCP\Util::addScript('files', 'jquery.fileupload');
362
-		\OCP\Util::addScript('files_sharing', 'files_drop');
363
-
364
-		if (isset($shareTmpl['folder'])) {
365
-			// JS required for folders
366
-			\OCP\Util::addStyle('files', 'merged');
367
-			\OCP\Util::addScript('files', 'filesummary');
368
-			\OCP\Util::addScript('files', 'breadcrumb');
369
-			\OCP\Util::addScript('files', 'fileinfomodel');
370
-			\OCP\Util::addScript('files', 'newfilemenu');
371
-			\OCP\Util::addScript('files', 'files');
372
-			\OCP\Util::addScript('files', 'filelist');
373
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
374
-		}
375
-
376
-		// OpenGraph Support: http://ogp.me/
377
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
378
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
379
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
380
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
381
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
382
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
383
-
384
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
385
-
386
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
387
-		$csp->addAllowedFrameDomain('\'self\'');
388
-
389
-		$response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
390
-		$response->setHeaderTitle($shareTmpl['filename']);
391
-		$response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
392
-		$response->setHeaderActions([
393
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
394
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
395
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
396
-			new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
397
-		]);
398
-
399
-		$response->setContentSecurityPolicy($csp);
400
-
401
-		$this->emitAccessShareHook($share);
402
-
403
-		return $response;
404
-	}
405
-
406
-	/**
407
-	 * @PublicPage
408
-	 * @NoCSRFRequired
409
-	 *
410
-	 * @param string $token
411
-	 * @param string $files
412
-	 * @param string $path
413
-	 * @param string $downloadStartSecret
414
-	 * @return void|\OCP\AppFramework\Http\Response
415
-	 * @throws NotFoundException
416
-	 */
417
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
418
-		\OC_User::setIncognitoMode(true);
419
-
420
-		$share = $this->shareManager->getShareByToken($token);
421
-
422
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
423
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
424
-		}
425
-
426
-		$files_list = null;
427
-		if (!is_null($files)) { // download selected files
428
-			$files_list = json_decode($files);
429
-			// in case we get only a single file
430
-			if ($files_list === null) {
431
-				$files_list = [$files];
432
-			}
433
-			// Just in case $files is a single int like '1234'
434
-			if (!is_array($files_list)) {
435
-				$files_list = [$files_list];
436
-			}
437
-		}
438
-
439
-
440
-		if (!$this->validateShare($share)) {
441
-			throw new NotFoundException();
442
-		}
443
-
444
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
445
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
446
-
447
-
448
-		// Single file share
449
-		if ($share->getNode() instanceof \OCP\Files\File) {
450
-			// Single file download
451
-			$this->singleFileDownloaded($share, $share->getNode());
452
-		}
453
-		// Directory share
454
-		else {
455
-			/** @var \OCP\Files\Folder $node */
456
-			$node = $share->getNode();
457
-
458
-			// Try to get the path
459
-			if ($path !== '') {
460
-				try {
461
-					$node = $node->get($path);
462
-				} catch (NotFoundException $e) {
463
-					$this->emitAccessShareHook($share, 404, 'Share not found');
464
-					return new NotFoundResponse();
465
-				}
466
-			}
467
-
468
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
469
-
470
-			if ($node instanceof \OCP\Files\File) {
471
-				// Single file download
472
-				$this->singleFileDownloaded($share, $share->getNode());
473
-			} else if (!empty($files_list)) {
474
-				$this->fileListDownloaded($share, $files_list, $node);
475
-			} else {
476
-				// The folder is downloaded
477
-				$this->singleFileDownloaded($share, $share->getNode());
478
-			}
479
-		}
480
-
481
-		/* FIXME: We should do this all nicely in OCP */
482
-		OC_Util::tearDownFS();
483
-		OC_Util::setupFS($share->getShareOwner());
484
-
485
-		/**
486
-		 * this sets a cookie to be able to recognize the start of the download
487
-		 * the content must not be longer than 32 characters and must only contain
488
-		 * alphanumeric characters
489
-		 */
490
-		if (!empty($downloadStartSecret)
491
-			&& !isset($downloadStartSecret[32])
492
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
493
-
494
-			// FIXME: set on the response once we use an actual app framework response
495
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
496
-		}
497
-
498
-		$this->emitAccessShareHook($share);
499
-
500
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
501
-
502
-		/**
503
-		 * Http range requests support
504
-		 */
505
-		if (isset($_SERVER['HTTP_RANGE'])) {
506
-			$server_params['range'] = $this->request->getHeader('Range');
507
-		}
508
-
509
-		// download selected files
510
-		if (!is_null($files) && $files !== '') {
511
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
512
-			// after dispatching the request which results in a "Cannot modify header information" notice.
513
-			OC_Files::get($originalSharePath, $files_list, $server_params);
514
-			exit();
515
-		} else {
516
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
517
-			// after dispatching the request which results in a "Cannot modify header information" notice.
518
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
519
-			exit();
520
-		}
521
-	}
522
-
523
-	/**
524
-	 * create activity for every downloaded file
525
-	 *
526
-	 * @param Share\IShare $share
527
-	 * @param array $files_list
528
-	 * @param \OCP\Files\Folder $node
529
-	 */
530
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
531
-		foreach ($files_list as $file) {
532
-			$subNode = $node->get($file);
533
-			$this->singleFileDownloaded($share, $subNode);
534
-		}
535
-
536
-	}
537
-
538
-	/**
539
-	 * create activity if a single file was downloaded from a link share
540
-	 *
541
-	 * @param Share\IShare $share
542
-	 */
543
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
544
-
545
-		$fileId = $node->getId();
546
-
547
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
548
-		$userNodeList = $userFolder->getById($fileId);
549
-		$userNode = $userNodeList[0];
550
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
551
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
552
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
553
-
554
-		$parameters = [$userPath];
555
-
556
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
557
-			if ($node instanceof \OCP\Files\File) {
558
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
559
-			} else {
560
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
561
-			}
562
-			$parameters[] = $share->getSharedWith();
563
-		} else {
564
-			if ($node instanceof \OCP\Files\File) {
565
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
566
-			} else {
567
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
568
-			}
569
-		}
570
-
571
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
572
-
573
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
574
-			$parameters[0] = $ownerPath;
575
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
576
-		}
577
-	}
578
-
579
-	/**
580
-	 * publish activity
581
-	 *
582
-	 * @param string $subject
583
-	 * @param array $parameters
584
-	 * @param string $affectedUser
585
-	 * @param int $fileId
586
-	 * @param string $filePath
587
-	 */
588
-	protected function publishActivity($subject,
589
-										array $parameters,
590
-										$affectedUser,
591
-										$fileId,
592
-										$filePath) {
593
-
594
-		$event = $this->activityManager->generateEvent();
595
-		$event->setApp('files_sharing')
596
-			->setType('public_links')
597
-			->setSubject($subject, $parameters)
598
-			->setAffectedUser($affectedUser)
599
-			->setObject('files', $fileId, $filePath);
600
-		$this->activityManager->publish($event);
601
-	}
292
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
293
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
294
+                $freeSpace = max($freeSpace, 0);
295
+            } else {
296
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
297
+            }
298
+
299
+            $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
300
+            $maxUploadFilesize = $freeSpace;
301
+
302
+            $folder = new Template('files', 'list', '');
303
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
304
+            $folder->assign('dirToken', $this->getToken());
305
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
306
+            $folder->assign('isPublic', true);
307
+            $folder->assign('hideFileList', $hideFileList);
308
+            $folder->assign('publicUploadEnabled', 'no');
309
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
310
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
311
+            $folder->assign('freeSpace', $freeSpace);
312
+            $folder->assign('usedSpacePercent', 0);
313
+            $folder->assign('trash', false);
314
+            $shareTmpl['folder'] = $folder->fetchPage();
315
+        }
316
+
317
+        $shareTmpl['hideFileList'] = $hideFileList;
318
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
319
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $this->getToken()]);
320
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $this->getToken()]);
321
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
322
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
323
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
324
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
325
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
326
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
327
+        $ogPreview = '';
328
+        if ($shareTmpl['previewSupported']) {
329
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
330
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
331
+            $ogPreview = $shareTmpl['previewImage'];
332
+
333
+            // We just have direct previews for image files
334
+            if ($share->getNode()->getMimePart() === 'image') {
335
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $this->getToken()]);
336
+
337
+                $ogPreview = $shareTmpl['previewURL'];
338
+
339
+                //Whatapp is kind of picky about their size requirements
340
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
341
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
342
+                        'token' => $this->getToken(),
343
+                        'x' => 256,
344
+                        'y' => 256,
345
+                        'a' => true,
346
+                    ]);
347
+                }
348
+            }
349
+        } else {
350
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
351
+            $ogPreview = $shareTmpl['previewImage'];
352
+        }
353
+
354
+        // Load files we need
355
+        \OCP\Util::addScript('files', 'file-upload');
356
+        \OCP\Util::addStyle('files_sharing', 'publicView');
357
+        \OCP\Util::addScript('files_sharing', 'public');
358
+        \OCP\Util::addScript('files', 'fileactions');
359
+        \OCP\Util::addScript('files', 'fileactionsmenu');
360
+        \OCP\Util::addScript('files', 'jquery.fileupload');
361
+        \OCP\Util::addScript('files_sharing', 'files_drop');
362
+
363
+        if (isset($shareTmpl['folder'])) {
364
+            // JS required for folders
365
+            \OCP\Util::addStyle('files', 'merged');
366
+            \OCP\Util::addScript('files', 'filesummary');
367
+            \OCP\Util::addScript('files', 'breadcrumb');
368
+            \OCP\Util::addScript('files', 'fileinfomodel');
369
+            \OCP\Util::addScript('files', 'newfilemenu');
370
+            \OCP\Util::addScript('files', 'files');
371
+            \OCP\Util::addScript('files', 'filelist');
372
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
373
+        }
374
+
375
+        // OpenGraph Support: http://ogp.me/
376
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
377
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
378
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
379
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
380
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
381
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
382
+
383
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
384
+
385
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
386
+        $csp->addAllowedFrameDomain('\'self\'');
387
+
388
+        $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
389
+        $response->setHeaderTitle($shareTmpl['filename']);
390
+        $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
391
+        $response->setHeaderActions([
392
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
393
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
394
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
395
+            new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
396
+        ]);
397
+
398
+        $response->setContentSecurityPolicy($csp);
399
+
400
+        $this->emitAccessShareHook($share);
401
+
402
+        return $response;
403
+    }
404
+
405
+    /**
406
+     * @PublicPage
407
+     * @NoCSRFRequired
408
+     *
409
+     * @param string $token
410
+     * @param string $files
411
+     * @param string $path
412
+     * @param string $downloadStartSecret
413
+     * @return void|\OCP\AppFramework\Http\Response
414
+     * @throws NotFoundException
415
+     */
416
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
417
+        \OC_User::setIncognitoMode(true);
418
+
419
+        $share = $this->shareManager->getShareByToken($token);
420
+
421
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
422
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
423
+        }
424
+
425
+        $files_list = null;
426
+        if (!is_null($files)) { // download selected files
427
+            $files_list = json_decode($files);
428
+            // in case we get only a single file
429
+            if ($files_list === null) {
430
+                $files_list = [$files];
431
+            }
432
+            // Just in case $files is a single int like '1234'
433
+            if (!is_array($files_list)) {
434
+                $files_list = [$files_list];
435
+            }
436
+        }
437
+
438
+
439
+        if (!$this->validateShare($share)) {
440
+            throw new NotFoundException();
441
+        }
442
+
443
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
444
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
445
+
446
+
447
+        // Single file share
448
+        if ($share->getNode() instanceof \OCP\Files\File) {
449
+            // Single file download
450
+            $this->singleFileDownloaded($share, $share->getNode());
451
+        }
452
+        // Directory share
453
+        else {
454
+            /** @var \OCP\Files\Folder $node */
455
+            $node = $share->getNode();
456
+
457
+            // Try to get the path
458
+            if ($path !== '') {
459
+                try {
460
+                    $node = $node->get($path);
461
+                } catch (NotFoundException $e) {
462
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
463
+                    return new NotFoundResponse();
464
+                }
465
+            }
466
+
467
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
468
+
469
+            if ($node instanceof \OCP\Files\File) {
470
+                // Single file download
471
+                $this->singleFileDownloaded($share, $share->getNode());
472
+            } else if (!empty($files_list)) {
473
+                $this->fileListDownloaded($share, $files_list, $node);
474
+            } else {
475
+                // The folder is downloaded
476
+                $this->singleFileDownloaded($share, $share->getNode());
477
+            }
478
+        }
479
+
480
+        /* FIXME: We should do this all nicely in OCP */
481
+        OC_Util::tearDownFS();
482
+        OC_Util::setupFS($share->getShareOwner());
483
+
484
+        /**
485
+         * this sets a cookie to be able to recognize the start of the download
486
+         * the content must not be longer than 32 characters and must only contain
487
+         * alphanumeric characters
488
+         */
489
+        if (!empty($downloadStartSecret)
490
+            && !isset($downloadStartSecret[32])
491
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
492
+
493
+            // FIXME: set on the response once we use an actual app framework response
494
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
495
+        }
496
+
497
+        $this->emitAccessShareHook($share);
498
+
499
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
500
+
501
+        /**
502
+         * Http range requests support
503
+         */
504
+        if (isset($_SERVER['HTTP_RANGE'])) {
505
+            $server_params['range'] = $this->request->getHeader('Range');
506
+        }
507
+
508
+        // download selected files
509
+        if (!is_null($files) && $files !== '') {
510
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
511
+            // after dispatching the request which results in a "Cannot modify header information" notice.
512
+            OC_Files::get($originalSharePath, $files_list, $server_params);
513
+            exit();
514
+        } else {
515
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
516
+            // after dispatching the request which results in a "Cannot modify header information" notice.
517
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
518
+            exit();
519
+        }
520
+    }
521
+
522
+    /**
523
+     * create activity for every downloaded file
524
+     *
525
+     * @param Share\IShare $share
526
+     * @param array $files_list
527
+     * @param \OCP\Files\Folder $node
528
+     */
529
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
530
+        foreach ($files_list as $file) {
531
+            $subNode = $node->get($file);
532
+            $this->singleFileDownloaded($share, $subNode);
533
+        }
534
+
535
+    }
536
+
537
+    /**
538
+     * create activity if a single file was downloaded from a link share
539
+     *
540
+     * @param Share\IShare $share
541
+     */
542
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
543
+
544
+        $fileId = $node->getId();
545
+
546
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
547
+        $userNodeList = $userFolder->getById($fileId);
548
+        $userNode = $userNodeList[0];
549
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
550
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
551
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
552
+
553
+        $parameters = [$userPath];
554
+
555
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
556
+            if ($node instanceof \OCP\Files\File) {
557
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
558
+            } else {
559
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
560
+            }
561
+            $parameters[] = $share->getSharedWith();
562
+        } else {
563
+            if ($node instanceof \OCP\Files\File) {
564
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
565
+            } else {
566
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
567
+            }
568
+        }
569
+
570
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
571
+
572
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
573
+            $parameters[0] = $ownerPath;
574
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
575
+        }
576
+    }
577
+
578
+    /**
579
+     * publish activity
580
+     *
581
+     * @param string $subject
582
+     * @param array $parameters
583
+     * @param string $affectedUser
584
+     * @param int $fileId
585
+     * @param string $filePath
586
+     */
587
+    protected function publishActivity($subject,
588
+                                        array $parameters,
589
+                                        $affectedUser,
590
+                                        $fileId,
591
+                                        $filePath) {
592
+
593
+        $event = $this->activityManager->generateEvent();
594
+        $event->setApp('files_sharing')
595
+            ->setType('public_links')
596
+            ->setSubject($subject, $parameters)
597
+            ->setAffectedUser($affectedUser)
598
+            ->setObject('files', $fileId, $filePath);
599
+        $this->activityManager->publish($event);
600
+    }
602 601
 
603 602
 
604 603
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 
168 168
 	protected function authSucceeded() {
169 169
 		// For share this was always set so it is still used in other apps
170
-		$this->session->set('public_link_authenticated', (string)$this->share->getId());
170
+		$this->session->set('public_link_authenticated', (string) $this->share->getId());
171 171
 	}
172 172
 
173 173
 	protected function authFailed() {
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 		$itemType = $itemSource = $uidOwner = '';
189 189
 		$token = $share;
190 190
 		$exception = null;
191
-		if($share instanceof \OCP\Share\IShare) {
191
+		if ($share instanceof \OCP\Share\IShare) {
192 192
 			try {
193 193
 				$token = $share->getToken();
194 194
 				$uidOwner = $share->getSharedBy();
@@ -207,7 +207,7 @@  discard block
 block discarded – undo
207 207
 			'errorCode' => $errorCode,
208 208
 			'errorMessage' => $errorMessage,
209 209
 		]);
210
-		if(!is_null($exception)) {
210
+		if (!is_null($exception)) {
211 211
 			throw $exception;
212 212
 		}
213 213
 	}
@@ -327,7 +327,7 @@  discard block
 block discarded – undo
327 327
 		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
328 328
 		$ogPreview = '';
329 329
 		if ($shareTmpl['previewSupported']) {
330
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
330
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
331 331
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 'token' => $shareTmpl['dirToken']]);
332 332
 			$ogPreview = $shareTmpl['previewImage'];
333 333
 
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 
376 376
 		// OpenGraph Support: http://ogp.me/
377 377
 		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
378
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
378
+		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName().($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '')]);
379 379
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
380 380
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
381 381
 		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 
420 420
 		$share = $this->shareManager->getShareByToken($token);
421 421
 
422
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
422
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
423 423
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
424 424
 		}
425 425
 
@@ -497,7 +497,7 @@  discard block
 block discarded – undo
497 497
 
498 498
 		$this->emitAccessShareHook($share);
499 499
 
500
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
500
+		$server_params = array('head' => $this->request->getMethod() === 'HEAD');
501 501
 
502 502
 		/**
503 503
 		 * Http range requests support
Please login to merge, or discard this patch.
lib/private/Files/Cache/Wrapper/CacheJail.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -194,6 +194,9 @@
 block discarded – undo
194 194
 		return $this->getCache()->getStatus($this->getSourcePath($file));
195 195
 	}
196 196
 
197
+	/**
198
+	 * @param ICacheEntry[] $results
199
+	 */
197 200
 	private function formatSearchResults($results) {
198 201
 		$results = array_filter($results, array($this, 'filterCacheEntry'));
199 202
 		$results = array_values($results);
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 		if ($path === '') {
59 59
 			return $this->getRoot();
60 60
 		} else {
61
-			return $this->getRoot() . '/' . ltrim($path, '/');
61
+			return $this->getRoot().'/'.ltrim($path, '/');
62 62
 		}
63 63
 	}
64 64
 
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		$rootLength = strlen($this->getRoot()) + 1;
74 74
 		if ($path === $this->getRoot()) {
75 75
 			return '';
76
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
76
+		} else if (substr($path, 0, $rootLength) === $this->getRoot().'/') {
77 77
 			return substr($path, $rootLength);
78 78
 		} else {
79 79
 			return null;
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 
94 94
 	protected function filterCacheEntry($entry) {
95 95
 		$rootLength = strlen($this->getRoot()) + 1;
96
-		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
96
+		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot().'/');
97 97
 	}
98 98
 
99 99
 	/**
Please login to merge, or discard this patch.
Indentation   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -37,308 +37,308 @@
 block discarded – undo
37 37
  * Jail to a subdirectory of the wrapped cache
38 38
  */
39 39
 class CacheJail extends CacheWrapper {
40
-	/**
41
-	 * @var string
42
-	 */
43
-	protected $root;
44
-
45
-	/**
46
-	 * @param \OCP\Files\Cache\ICache $cache
47
-	 * @param string $root
48
-	 */
49
-	public function __construct($cache, $root) {
50
-		parent::__construct($cache);
51
-		$this->root = $root;
52
-	}
53
-
54
-	protected function getRoot() {
55
-		return $this->root;
56
-	}
57
-
58
-	protected function getSourcePath($path) {
59
-		if ($path === '') {
60
-			return $this->getRoot();
61
-		} else {
62
-			return $this->getRoot() . '/' . ltrim($path, '/');
63
-		}
64
-	}
65
-
66
-	/**
67
-	 * @param string $path
68
-	 * @return null|string the jailed path or null if the path is outside the jail
69
-	 */
70
-	protected function getJailedPath($path) {
71
-		if ($this->getRoot() === '') {
72
-			return $path;
73
-		}
74
-		$rootLength = strlen($this->getRoot()) + 1;
75
-		if ($path === $this->getRoot()) {
76
-			return '';
77
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
78
-			return substr($path, $rootLength);
79
-		} else {
80
-			return null;
81
-		}
82
-	}
83
-
84
-	/**
85
-	 * @param ICacheEntry|array $entry
86
-	 * @return array
87
-	 */
88
-	protected function formatCacheEntry($entry) {
89
-		if (isset($entry['path'])) {
90
-			$entry['path'] = $this->getJailedPath($entry['path']);
91
-		}
92
-		return $entry;
93
-	}
94
-
95
-	protected function filterCacheEntry($entry) {
96
-		$rootLength = strlen($this->getRoot()) + 1;
97
-		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
98
-	}
99
-
100
-	/**
101
-	 * get the stored metadata of a file or folder
102
-	 *
103
-	 * @param string /int $file
104
-	 * @return ICacheEntry|false
105
-	 */
106
-	public function get($file) {
107
-		if (is_string($file) or $file == '') {
108
-			$file = $this->getSourcePath($file);
109
-		}
110
-		return parent::get($file);
111
-	}
112
-
113
-	/**
114
-	 * insert meta data for a new file or folder
115
-	 *
116
-	 * @param string $file
117
-	 * @param array $data
118
-	 *
119
-	 * @return int file id
120
-	 * @throws \RuntimeException
121
-	 */
122
-	public function insert($file, array $data) {
123
-		return $this->getCache()->insert($this->getSourcePath($file), $data);
124
-	}
125
-
126
-	/**
127
-	 * update the metadata in the cache
128
-	 *
129
-	 * @param int $id
130
-	 * @param array $data
131
-	 */
132
-	public function update($id, array $data) {
133
-		$this->getCache()->update($id, $data);
134
-	}
135
-
136
-	/**
137
-	 * get the file id for a file
138
-	 *
139
-	 * @param string $file
140
-	 * @return int
141
-	 */
142
-	public function getId($file) {
143
-		return $this->getCache()->getId($this->getSourcePath($file));
144
-	}
145
-
146
-	/**
147
-	 * get the id of the parent folder of a file
148
-	 *
149
-	 * @param string $file
150
-	 * @return int
151
-	 */
152
-	public function getParentId($file) {
153
-		return $this->getCache()->getParentId($this->getSourcePath($file));
154
-	}
155
-
156
-	/**
157
-	 * check if a file is available in the cache
158
-	 *
159
-	 * @param string $file
160
-	 * @return bool
161
-	 */
162
-	public function inCache($file) {
163
-		return $this->getCache()->inCache($this->getSourcePath($file));
164
-	}
165
-
166
-	/**
167
-	 * remove a file or folder from the cache
168
-	 *
169
-	 * @param string $file
170
-	 */
171
-	public function remove($file) {
172
-		$this->getCache()->remove($this->getSourcePath($file));
173
-	}
174
-
175
-	/**
176
-	 * Move a file or folder in the cache
177
-	 *
178
-	 * @param string $source
179
-	 * @param string $target
180
-	 */
181
-	public function move($source, $target) {
182
-		$this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
183
-	}
184
-
185
-	/**
186
-	 * Get the storage id and path needed for a move
187
-	 *
188
-	 * @param string $path
189
-	 * @return array [$storageId, $internalPath]
190
-	 */
191
-	protected function getMoveInfo($path) {
192
-		return [$this->getNumericStorageId(), $this->getSourcePath($path)];
193
-	}
194
-
195
-	/**
196
-	 * remove all entries for files that are stored on the storage from the cache
197
-	 */
198
-	public function clear() {
199
-		$this->getCache()->remove($this->getRoot());
200
-	}
201
-
202
-	/**
203
-	 * @param string $file
204
-	 *
205
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
206
-	 */
207
-	public function getStatus($file) {
208
-		return $this->getCache()->getStatus($this->getSourcePath($file));
209
-	}
210
-
211
-	private function formatSearchResults($results) {
212
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
213
-		$results = array_values($results);
214
-		return array_map(array($this, 'formatCacheEntry'), $results);
215
-	}
216
-
217
-	/**
218
-	 * search for files matching $pattern
219
-	 *
220
-	 * @param string $pattern
221
-	 * @return array an array of file data
222
-	 */
223
-	public function search($pattern) {
224
-		$results = $this->getCache()->search($pattern);
225
-		return $this->formatSearchResults($results);
226
-	}
227
-
228
-	/**
229
-	 * search for files by mimetype
230
-	 *
231
-	 * @param string $mimetype
232
-	 * @return array
233
-	 */
234
-	public function searchByMime($mimetype) {
235
-		$results = $this->getCache()->searchByMime($mimetype);
236
-		return $this->formatSearchResults($results);
237
-	}
238
-
239
-	public function searchQuery(ISearchQuery $query) {
240
-		$simpleQuery = new SearchQuery($query->getSearchOperation(), 0, 0, $query->getOrder(), $query->getUser());
241
-		$results = $this->getCache()->searchQuery($simpleQuery);
242
-		$results = $this->formatSearchResults($results);
243
-
244
-		$limit = $query->getLimit() === 0 ? NULL : $query->getLimit();
245
-		$results = array_slice($results, $query->getOffset(), $limit);
246
-
247
-		return $results;
248
-	}
249
-
250
-	/**
251
-	 * search for files by mimetype
252
-	 *
253
-	 * @param string|int $tag name or tag id
254
-	 * @param string $userId owner of the tags
255
-	 * @return array
256
-	 */
257
-	public function searchByTag($tag, $userId) {
258
-		$results = $this->getCache()->searchByTag($tag, $userId);
259
-		return $this->formatSearchResults($results);
260
-	}
261
-
262
-	/**
263
-	 * update the folder size and the size of all parent folders
264
-	 *
265
-	 * @param string|boolean $path
266
-	 * @param array $data (optional) meta data of the folder
267
-	 */
268
-	public function correctFolderSize($path, $data = null) {
269
-		if ($this->getCache() instanceof Cache) {
270
-			$this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * get the size of a folder and set it in the cache
276
-	 *
277
-	 * @param string $path
278
-	 * @param array $entry (optional) meta data of the folder
279
-	 * @return int
280
-	 */
281
-	public function calculateFolderSize($path, $entry = null) {
282
-		if ($this->getCache() instanceof Cache) {
283
-			return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
284
-		} else {
285
-			return 0;
286
-		}
287
-
288
-	}
289
-
290
-	/**
291
-	 * get all file ids on the files on the storage
292
-	 *
293
-	 * @return int[]
294
-	 */
295
-	public function getAll() {
296
-		// not supported
297
-		return array();
298
-	}
299
-
300
-	/**
301
-	 * find a folder in the cache which has not been fully scanned
302
-	 *
303
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
304
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
305
-	 * likely the folder where we stopped scanning previously
306
-	 *
307
-	 * @return string|bool the path of the folder or false when no folder matched
308
-	 */
309
-	public function getIncomplete() {
310
-		// not supported
311
-		return false;
312
-	}
313
-
314
-	/**
315
-	 * get the path of a file on this storage by it's id
316
-	 *
317
-	 * @param int $id
318
-	 * @return string|null
319
-	 */
320
-	public function getPathById($id) {
321
-		$path = $this->getCache()->getPathById($id);
322
-		if ($path === null) {
323
-			return null;
324
-		}
325
-
326
-		return $this->getJailedPath($path);
327
-	}
328
-
329
-	/**
330
-	 * Move a file or folder in the cache
331
-	 *
332
-	 * Note that this should make sure the entries are removed from the source cache
333
-	 *
334
-	 * @param \OCP\Files\Cache\ICache $sourceCache
335
-	 * @param string $sourcePath
336
-	 * @param string $targetPath
337
-	 */
338
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
339
-		if ($sourceCache === $this) {
340
-			return $this->move($sourcePath, $targetPath);
341
-		}
342
-		return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
343
-	}
40
+    /**
41
+     * @var string
42
+     */
43
+    protected $root;
44
+
45
+    /**
46
+     * @param \OCP\Files\Cache\ICache $cache
47
+     * @param string $root
48
+     */
49
+    public function __construct($cache, $root) {
50
+        parent::__construct($cache);
51
+        $this->root = $root;
52
+    }
53
+
54
+    protected function getRoot() {
55
+        return $this->root;
56
+    }
57
+
58
+    protected function getSourcePath($path) {
59
+        if ($path === '') {
60
+            return $this->getRoot();
61
+        } else {
62
+            return $this->getRoot() . '/' . ltrim($path, '/');
63
+        }
64
+    }
65
+
66
+    /**
67
+     * @param string $path
68
+     * @return null|string the jailed path or null if the path is outside the jail
69
+     */
70
+    protected function getJailedPath($path) {
71
+        if ($this->getRoot() === '') {
72
+            return $path;
73
+        }
74
+        $rootLength = strlen($this->getRoot()) + 1;
75
+        if ($path === $this->getRoot()) {
76
+            return '';
77
+        } else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
78
+            return substr($path, $rootLength);
79
+        } else {
80
+            return null;
81
+        }
82
+    }
83
+
84
+    /**
85
+     * @param ICacheEntry|array $entry
86
+     * @return array
87
+     */
88
+    protected function formatCacheEntry($entry) {
89
+        if (isset($entry['path'])) {
90
+            $entry['path'] = $this->getJailedPath($entry['path']);
91
+        }
92
+        return $entry;
93
+    }
94
+
95
+    protected function filterCacheEntry($entry) {
96
+        $rootLength = strlen($this->getRoot()) + 1;
97
+        return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
98
+    }
99
+
100
+    /**
101
+     * get the stored metadata of a file or folder
102
+     *
103
+     * @param string /int $file
104
+     * @return ICacheEntry|false
105
+     */
106
+    public function get($file) {
107
+        if (is_string($file) or $file == '') {
108
+            $file = $this->getSourcePath($file);
109
+        }
110
+        return parent::get($file);
111
+    }
112
+
113
+    /**
114
+     * insert meta data for a new file or folder
115
+     *
116
+     * @param string $file
117
+     * @param array $data
118
+     *
119
+     * @return int file id
120
+     * @throws \RuntimeException
121
+     */
122
+    public function insert($file, array $data) {
123
+        return $this->getCache()->insert($this->getSourcePath($file), $data);
124
+    }
125
+
126
+    /**
127
+     * update the metadata in the cache
128
+     *
129
+     * @param int $id
130
+     * @param array $data
131
+     */
132
+    public function update($id, array $data) {
133
+        $this->getCache()->update($id, $data);
134
+    }
135
+
136
+    /**
137
+     * get the file id for a file
138
+     *
139
+     * @param string $file
140
+     * @return int
141
+     */
142
+    public function getId($file) {
143
+        return $this->getCache()->getId($this->getSourcePath($file));
144
+    }
145
+
146
+    /**
147
+     * get the id of the parent folder of a file
148
+     *
149
+     * @param string $file
150
+     * @return int
151
+     */
152
+    public function getParentId($file) {
153
+        return $this->getCache()->getParentId($this->getSourcePath($file));
154
+    }
155
+
156
+    /**
157
+     * check if a file is available in the cache
158
+     *
159
+     * @param string $file
160
+     * @return bool
161
+     */
162
+    public function inCache($file) {
163
+        return $this->getCache()->inCache($this->getSourcePath($file));
164
+    }
165
+
166
+    /**
167
+     * remove a file or folder from the cache
168
+     *
169
+     * @param string $file
170
+     */
171
+    public function remove($file) {
172
+        $this->getCache()->remove($this->getSourcePath($file));
173
+    }
174
+
175
+    /**
176
+     * Move a file or folder in the cache
177
+     *
178
+     * @param string $source
179
+     * @param string $target
180
+     */
181
+    public function move($source, $target) {
182
+        $this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
183
+    }
184
+
185
+    /**
186
+     * Get the storage id and path needed for a move
187
+     *
188
+     * @param string $path
189
+     * @return array [$storageId, $internalPath]
190
+     */
191
+    protected function getMoveInfo($path) {
192
+        return [$this->getNumericStorageId(), $this->getSourcePath($path)];
193
+    }
194
+
195
+    /**
196
+     * remove all entries for files that are stored on the storage from the cache
197
+     */
198
+    public function clear() {
199
+        $this->getCache()->remove($this->getRoot());
200
+    }
201
+
202
+    /**
203
+     * @param string $file
204
+     *
205
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
206
+     */
207
+    public function getStatus($file) {
208
+        return $this->getCache()->getStatus($this->getSourcePath($file));
209
+    }
210
+
211
+    private function formatSearchResults($results) {
212
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
213
+        $results = array_values($results);
214
+        return array_map(array($this, 'formatCacheEntry'), $results);
215
+    }
216
+
217
+    /**
218
+     * search for files matching $pattern
219
+     *
220
+     * @param string $pattern
221
+     * @return array an array of file data
222
+     */
223
+    public function search($pattern) {
224
+        $results = $this->getCache()->search($pattern);
225
+        return $this->formatSearchResults($results);
226
+    }
227
+
228
+    /**
229
+     * search for files by mimetype
230
+     *
231
+     * @param string $mimetype
232
+     * @return array
233
+     */
234
+    public function searchByMime($mimetype) {
235
+        $results = $this->getCache()->searchByMime($mimetype);
236
+        return $this->formatSearchResults($results);
237
+    }
238
+
239
+    public function searchQuery(ISearchQuery $query) {
240
+        $simpleQuery = new SearchQuery($query->getSearchOperation(), 0, 0, $query->getOrder(), $query->getUser());
241
+        $results = $this->getCache()->searchQuery($simpleQuery);
242
+        $results = $this->formatSearchResults($results);
243
+
244
+        $limit = $query->getLimit() === 0 ? NULL : $query->getLimit();
245
+        $results = array_slice($results, $query->getOffset(), $limit);
246
+
247
+        return $results;
248
+    }
249
+
250
+    /**
251
+     * search for files by mimetype
252
+     *
253
+     * @param string|int $tag name or tag id
254
+     * @param string $userId owner of the tags
255
+     * @return array
256
+     */
257
+    public function searchByTag($tag, $userId) {
258
+        $results = $this->getCache()->searchByTag($tag, $userId);
259
+        return $this->formatSearchResults($results);
260
+    }
261
+
262
+    /**
263
+     * update the folder size and the size of all parent folders
264
+     *
265
+     * @param string|boolean $path
266
+     * @param array $data (optional) meta data of the folder
267
+     */
268
+    public function correctFolderSize($path, $data = null) {
269
+        if ($this->getCache() instanceof Cache) {
270
+            $this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
271
+        }
272
+    }
273
+
274
+    /**
275
+     * get the size of a folder and set it in the cache
276
+     *
277
+     * @param string $path
278
+     * @param array $entry (optional) meta data of the folder
279
+     * @return int
280
+     */
281
+    public function calculateFolderSize($path, $entry = null) {
282
+        if ($this->getCache() instanceof Cache) {
283
+            return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
284
+        } else {
285
+            return 0;
286
+        }
287
+
288
+    }
289
+
290
+    /**
291
+     * get all file ids on the files on the storage
292
+     *
293
+     * @return int[]
294
+     */
295
+    public function getAll() {
296
+        // not supported
297
+        return array();
298
+    }
299
+
300
+    /**
301
+     * find a folder in the cache which has not been fully scanned
302
+     *
303
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
304
+     * use the one with the highest id gives the best result with the background scanner, since that is most
305
+     * likely the folder where we stopped scanning previously
306
+     *
307
+     * @return string|bool the path of the folder or false when no folder matched
308
+     */
309
+    public function getIncomplete() {
310
+        // not supported
311
+        return false;
312
+    }
313
+
314
+    /**
315
+     * get the path of a file on this storage by it's id
316
+     *
317
+     * @param int $id
318
+     * @return string|null
319
+     */
320
+    public function getPathById($id) {
321
+        $path = $this->getCache()->getPathById($id);
322
+        if ($path === null) {
323
+            return null;
324
+        }
325
+
326
+        return $this->getJailedPath($path);
327
+    }
328
+
329
+    /**
330
+     * Move a file or folder in the cache
331
+     *
332
+     * Note that this should make sure the entries are removed from the source cache
333
+     *
334
+     * @param \OCP\Files\Cache\ICache $sourceCache
335
+     * @param string $sourcePath
336
+     * @param string $targetPath
337
+     */
338
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
339
+        if ($sourceCache === $this) {
340
+            return $this->move($sourcePath, $targetPath);
341
+        }
342
+        return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
343
+    }
344 344
 }
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@
 block discarded – undo
156 156
 	/**
157 157
 	 * @param string $gid
158 158
 	 * @param string $displayName
159
-	 * @return \OCP\IGroup
159
+	 * @return null|Group
160 160
 	 */
161 161
 	protected function getGroupObject($gid, $displayName = null) {
162 162
 		$backends = array();
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 	 * @param IUser|null $user
250 250
 	 * @return \OC\Group\Group[]
251 251
 	 */
252
-	public function getUserGroups(IUser $user= null) {
252
+	public function getUserGroups(IUser $user = null) {
253 253
 		if (!$user instanceof IUser) {
254 254
 			return [];
255 255
 		}
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362 362
 		}
363 363
 		return $matchingUsers;
Please login to merge, or discard this patch.
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -61,348 +61,348 @@
 block discarded – undo
61 61
  * @package OC\Group
62 62
  */
63 63
 class Manager extends PublicEmitter implements IGroupManager {
64
-	/**
65
-	 * @var GroupInterface[] $backends
66
-	 */
67
-	private $backends = array();
68
-
69
-	/**
70
-	 * @var \OC\User\Manager $userManager
71
-	 */
72
-	private $userManager;
73
-
74
-	/**
75
-	 * @var \OC\Group\Group[]
76
-	 */
77
-	private $cachedGroups = array();
78
-
79
-	/**
80
-	 * @var \OC\Group\Group[]
81
-	 */
82
-	private $cachedUserGroups = array();
83
-
84
-	/** @var \OC\SubAdmin */
85
-	private $subAdmin = null;
86
-
87
-	/** @var ILogger */
88
-	private $logger;
89
-
90
-	/**
91
-	 * @param \OC\User\Manager $userManager
92
-	 * @param ILogger $logger
93
-	 */
94
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
95
-		$this->userManager = $userManager;
96
-		$this->logger = $logger;
97
-		$cachedGroups = & $this->cachedGroups;
98
-		$cachedUserGroups = & $this->cachedUserGroups;
99
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
100
-			/**
101
-			 * @var \OC\Group\Group $group
102
-			 */
103
-			unset($cachedGroups[$group->getGID()]);
104
-			$cachedUserGroups = array();
105
-		});
106
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
107
-			/**
108
-			 * @var \OC\Group\Group $group
109
-			 */
110
-			$cachedUserGroups = array();
111
-		});
112
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
113
-			/**
114
-			 * @var \OC\Group\Group $group
115
-			 */
116
-			$cachedUserGroups = array();
117
-		});
118
-	}
119
-
120
-	/**
121
-	 * Checks whether a given backend is used
122
-	 *
123
-	 * @param string $backendClass Full classname including complete namespace
124
-	 * @return bool
125
-	 */
126
-	public function isBackendUsed($backendClass) {
127
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
128
-
129
-		foreach ($this->backends as $backend) {
130
-			if (strtolower(get_class($backend)) === $backendClass) {
131
-				return true;
132
-			}
133
-		}
134
-
135
-		return false;
136
-	}
137
-
138
-	/**
139
-	 * @param \OCP\GroupInterface $backend
140
-	 */
141
-	public function addBackend($backend) {
142
-		$this->backends[] = $backend;
143
-		$this->clearCaches();
144
-	}
145
-
146
-	public function clearBackends() {
147
-		$this->backends = array();
148
-		$this->clearCaches();
149
-	}
150
-
151
-	/**
152
-	 * Get the active backends
153
-	 * @return \OCP\GroupInterface[]
154
-	 */
155
-	public function getBackends() {
156
-		return $this->backends;
157
-	}
158
-
159
-
160
-	protected function clearCaches() {
161
-		$this->cachedGroups = array();
162
-		$this->cachedUserGroups = array();
163
-	}
164
-
165
-	/**
166
-	 * @param string $gid
167
-	 * @return \OC\Group\Group
168
-	 */
169
-	public function get($gid) {
170
-		if (isset($this->cachedGroups[$gid])) {
171
-			return $this->cachedGroups[$gid];
172
-		}
173
-		return $this->getGroupObject($gid);
174
-	}
175
-
176
-	/**
177
-	 * @param string $gid
178
-	 * @param string $displayName
179
-	 * @return \OCP\IGroup
180
-	 */
181
-	protected function getGroupObject($gid, $displayName = null) {
182
-		$backends = array();
183
-		foreach ($this->backends as $backend) {
184
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
185
-				$groupData = $backend->getGroupDetails($gid);
186
-				if (is_array($groupData) && !empty($groupData)) {
187
-					// take the display name from the first backend that has a non-null one
188
-					if (is_null($displayName) && isset($groupData['displayName'])) {
189
-						$displayName = $groupData['displayName'];
190
-					}
191
-					$backends[] = $backend;
192
-				}
193
-			} else if ($backend->groupExists($gid)) {
194
-				$backends[] = $backend;
195
-			}
196
-		}
197
-		if (count($backends) === 0) {
198
-			return null;
199
-		}
200
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
201
-		return $this->cachedGroups[$gid];
202
-	}
203
-
204
-	/**
205
-	 * @param string $gid
206
-	 * @return bool
207
-	 */
208
-	public function groupExists($gid) {
209
-		return $this->get($gid) instanceof IGroup;
210
-	}
211
-
212
-	/**
213
-	 * @param string $gid
214
-	 * @return \OC\Group\Group
215
-	 */
216
-	public function createGroup($gid) {
217
-		if ($gid === '' || $gid === null) {
218
-			return false;
219
-		} else if ($group = $this->get($gid)) {
220
-			return $group;
221
-		} else {
222
-			$this->emit('\OC\Group', 'preCreate', array($gid));
223
-			foreach ($this->backends as $backend) {
224
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
225
-					$backend->createGroup($gid);
226
-					$group = $this->getGroupObject($gid);
227
-					$this->emit('\OC\Group', 'postCreate', array($group));
228
-					return $group;
229
-				}
230
-			}
231
-			return null;
232
-		}
233
-	}
234
-
235
-	/**
236
-	 * @param string $search
237
-	 * @param int $limit
238
-	 * @param int $offset
239
-	 * @return \OC\Group\Group[]
240
-	 */
241
-	public function search($search, $limit = null, $offset = null) {
242
-		$groups = array();
243
-		foreach ($this->backends as $backend) {
244
-			$groupIds = $backend->getGroups($search, $limit, $offset);
245
-			foreach ($groupIds as $groupId) {
246
-				$aGroup = $this->get($groupId);
247
-				if ($aGroup instanceof IGroup) {
248
-					$groups[$groupId] = $aGroup;
249
-				} else {
250
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
251
-				}
252
-			}
253
-			if (!is_null($limit) and $limit <= 0) {
254
-				return array_values($groups);
255
-			}
256
-		}
257
-		return array_values($groups);
258
-	}
259
-
260
-	/**
261
-	 * @param IUser|null $user
262
-	 * @return \OC\Group\Group[]
263
-	 */
264
-	public function getUserGroups(IUser $user= null) {
265
-		if (!$user instanceof IUser) {
266
-			return [];
267
-		}
268
-		return $this->getUserIdGroups($user->getUID());
269
-	}
270
-
271
-	/**
272
-	 * @param string $uid the user id
273
-	 * @return \OC\Group\Group[]
274
-	 */
275
-	public function getUserIdGroups($uid) {
276
-		if (isset($this->cachedUserGroups[$uid])) {
277
-			return $this->cachedUserGroups[$uid];
278
-		}
279
-		$groups = array();
280
-		foreach ($this->backends as $backend) {
281
-			$groupIds = $backend->getUserGroups($uid);
282
-			if (is_array($groupIds)) {
283
-				foreach ($groupIds as $groupId) {
284
-					$aGroup = $this->get($groupId);
285
-					if ($aGroup instanceof IGroup) {
286
-						$groups[$groupId] = $aGroup;
287
-					} else {
288
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
289
-					}
290
-				}
291
-			}
292
-		}
293
-		$this->cachedUserGroups[$uid] = $groups;
294
-		return $this->cachedUserGroups[$uid];
295
-	}
296
-
297
-	/**
298
-	 * Checks if a userId is in the admin group
299
-	 * @param string $userId
300
-	 * @return bool if admin
301
-	 */
302
-	public function isAdmin($userId) {
303
-		foreach ($this->backends as $backend) {
304
-			if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
305
-				return true;
306
-			}
307
-		}
308
-		return $this->isInGroup($userId, 'admin');
309
-	}
310
-
311
-	/**
312
-	 * Checks if a userId is in a group
313
-	 * @param string $userId
314
-	 * @param string $group
315
-	 * @return bool if in group
316
-	 */
317
-	public function isInGroup($userId, $group) {
318
-		return array_key_exists($group, $this->getUserIdGroups($userId));
319
-	}
320
-
321
-	/**
322
-	 * get a list of group ids for a user
323
-	 * @param IUser $user
324
-	 * @return array with group ids
325
-	 */
326
-	public function getUserGroupIds(IUser $user) {
327
-		return array_map(function($value) {
328
-			return (string) $value;
329
-		}, array_keys($this->getUserGroups($user)));
330
-	}
331
-
332
-	/**
333
-	 * get an array of groupid and displayName for a user
334
-	 * @param IUser $user
335
-	 * @return array ['displayName' => displayname]
336
-	 */
337
-	public function getUserGroupNames(IUser $user) {
338
-		return array_map(function($group) {
339
-			return array('displayName' => $group->getDisplayName());
340
-		}, $this->getUserGroups($user));
341
-	}
342
-
343
-	/**
344
-	 * get a list of all display names in a group
345
-	 * @param string $gid
346
-	 * @param string $search
347
-	 * @param int $limit
348
-	 * @param int $offset
349
-	 * @return array an array of display names (value) and user ids (key)
350
-	 */
351
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
352
-		$group = $this->get($gid);
353
-		if(is_null($group)) {
354
-			return array();
355
-		}
356
-
357
-		$search = trim($search);
358
-		$groupUsers = array();
359
-
360
-		if(!empty($search)) {
361
-			// only user backends have the capability to do a complex search for users
362
-			$searchOffset = 0;
363
-			$searchLimit = $limit * 100;
364
-			if($limit === -1) {
365
-				$searchLimit = 500;
366
-			}
367
-
368
-			do {
369
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
370
-				foreach($filteredUsers as $filteredUser) {
371
-					if($group->inGroup($filteredUser)) {
372
-						$groupUsers[]= $filteredUser;
373
-					}
374
-				}
375
-				$searchOffset += $searchLimit;
376
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
377
-
378
-			if($limit === -1) {
379
-				$groupUsers = array_slice($groupUsers, $offset);
380
-			} else {
381
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
382
-			}
383
-		} else {
384
-			$groupUsers = $group->searchUsers('', $limit, $offset);
385
-		}
386
-
387
-		$matchingUsers = array();
388
-		foreach($groupUsers as $groupUser) {
389
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
390
-		}
391
-		return $matchingUsers;
392
-	}
393
-
394
-	/**
395
-	 * @return \OC\SubAdmin
396
-	 */
397
-	public function getSubAdmin() {
398
-		if (!$this->subAdmin) {
399
-			$this->subAdmin = new \OC\SubAdmin(
400
-				$this->userManager,
401
-				$this,
402
-				\OC::$server->getDatabaseConnection()
403
-			);
404
-		}
405
-
406
-		return $this->subAdmin;
407
-	}
64
+    /**
65
+     * @var GroupInterface[] $backends
66
+     */
67
+    private $backends = array();
68
+
69
+    /**
70
+     * @var \OC\User\Manager $userManager
71
+     */
72
+    private $userManager;
73
+
74
+    /**
75
+     * @var \OC\Group\Group[]
76
+     */
77
+    private $cachedGroups = array();
78
+
79
+    /**
80
+     * @var \OC\Group\Group[]
81
+     */
82
+    private $cachedUserGroups = array();
83
+
84
+    /** @var \OC\SubAdmin */
85
+    private $subAdmin = null;
86
+
87
+    /** @var ILogger */
88
+    private $logger;
89
+
90
+    /**
91
+     * @param \OC\User\Manager $userManager
92
+     * @param ILogger $logger
93
+     */
94
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
95
+        $this->userManager = $userManager;
96
+        $this->logger = $logger;
97
+        $cachedGroups = & $this->cachedGroups;
98
+        $cachedUserGroups = & $this->cachedUserGroups;
99
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
100
+            /**
101
+             * @var \OC\Group\Group $group
102
+             */
103
+            unset($cachedGroups[$group->getGID()]);
104
+            $cachedUserGroups = array();
105
+        });
106
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
107
+            /**
108
+             * @var \OC\Group\Group $group
109
+             */
110
+            $cachedUserGroups = array();
111
+        });
112
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
113
+            /**
114
+             * @var \OC\Group\Group $group
115
+             */
116
+            $cachedUserGroups = array();
117
+        });
118
+    }
119
+
120
+    /**
121
+     * Checks whether a given backend is used
122
+     *
123
+     * @param string $backendClass Full classname including complete namespace
124
+     * @return bool
125
+     */
126
+    public function isBackendUsed($backendClass) {
127
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
128
+
129
+        foreach ($this->backends as $backend) {
130
+            if (strtolower(get_class($backend)) === $backendClass) {
131
+                return true;
132
+            }
133
+        }
134
+
135
+        return false;
136
+    }
137
+
138
+    /**
139
+     * @param \OCP\GroupInterface $backend
140
+     */
141
+    public function addBackend($backend) {
142
+        $this->backends[] = $backend;
143
+        $this->clearCaches();
144
+    }
145
+
146
+    public function clearBackends() {
147
+        $this->backends = array();
148
+        $this->clearCaches();
149
+    }
150
+
151
+    /**
152
+     * Get the active backends
153
+     * @return \OCP\GroupInterface[]
154
+     */
155
+    public function getBackends() {
156
+        return $this->backends;
157
+    }
158
+
159
+
160
+    protected function clearCaches() {
161
+        $this->cachedGroups = array();
162
+        $this->cachedUserGroups = array();
163
+    }
164
+
165
+    /**
166
+     * @param string $gid
167
+     * @return \OC\Group\Group
168
+     */
169
+    public function get($gid) {
170
+        if (isset($this->cachedGroups[$gid])) {
171
+            return $this->cachedGroups[$gid];
172
+        }
173
+        return $this->getGroupObject($gid);
174
+    }
175
+
176
+    /**
177
+     * @param string $gid
178
+     * @param string $displayName
179
+     * @return \OCP\IGroup
180
+     */
181
+    protected function getGroupObject($gid, $displayName = null) {
182
+        $backends = array();
183
+        foreach ($this->backends as $backend) {
184
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
185
+                $groupData = $backend->getGroupDetails($gid);
186
+                if (is_array($groupData) && !empty($groupData)) {
187
+                    // take the display name from the first backend that has a non-null one
188
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
189
+                        $displayName = $groupData['displayName'];
190
+                    }
191
+                    $backends[] = $backend;
192
+                }
193
+            } else if ($backend->groupExists($gid)) {
194
+                $backends[] = $backend;
195
+            }
196
+        }
197
+        if (count($backends) === 0) {
198
+            return null;
199
+        }
200
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
201
+        return $this->cachedGroups[$gid];
202
+    }
203
+
204
+    /**
205
+     * @param string $gid
206
+     * @return bool
207
+     */
208
+    public function groupExists($gid) {
209
+        return $this->get($gid) instanceof IGroup;
210
+    }
211
+
212
+    /**
213
+     * @param string $gid
214
+     * @return \OC\Group\Group
215
+     */
216
+    public function createGroup($gid) {
217
+        if ($gid === '' || $gid === null) {
218
+            return false;
219
+        } else if ($group = $this->get($gid)) {
220
+            return $group;
221
+        } else {
222
+            $this->emit('\OC\Group', 'preCreate', array($gid));
223
+            foreach ($this->backends as $backend) {
224
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
225
+                    $backend->createGroup($gid);
226
+                    $group = $this->getGroupObject($gid);
227
+                    $this->emit('\OC\Group', 'postCreate', array($group));
228
+                    return $group;
229
+                }
230
+            }
231
+            return null;
232
+        }
233
+    }
234
+
235
+    /**
236
+     * @param string $search
237
+     * @param int $limit
238
+     * @param int $offset
239
+     * @return \OC\Group\Group[]
240
+     */
241
+    public function search($search, $limit = null, $offset = null) {
242
+        $groups = array();
243
+        foreach ($this->backends as $backend) {
244
+            $groupIds = $backend->getGroups($search, $limit, $offset);
245
+            foreach ($groupIds as $groupId) {
246
+                $aGroup = $this->get($groupId);
247
+                if ($aGroup instanceof IGroup) {
248
+                    $groups[$groupId] = $aGroup;
249
+                } else {
250
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
251
+                }
252
+            }
253
+            if (!is_null($limit) and $limit <= 0) {
254
+                return array_values($groups);
255
+            }
256
+        }
257
+        return array_values($groups);
258
+    }
259
+
260
+    /**
261
+     * @param IUser|null $user
262
+     * @return \OC\Group\Group[]
263
+     */
264
+    public function getUserGroups(IUser $user= null) {
265
+        if (!$user instanceof IUser) {
266
+            return [];
267
+        }
268
+        return $this->getUserIdGroups($user->getUID());
269
+    }
270
+
271
+    /**
272
+     * @param string $uid the user id
273
+     * @return \OC\Group\Group[]
274
+     */
275
+    public function getUserIdGroups($uid) {
276
+        if (isset($this->cachedUserGroups[$uid])) {
277
+            return $this->cachedUserGroups[$uid];
278
+        }
279
+        $groups = array();
280
+        foreach ($this->backends as $backend) {
281
+            $groupIds = $backend->getUserGroups($uid);
282
+            if (is_array($groupIds)) {
283
+                foreach ($groupIds as $groupId) {
284
+                    $aGroup = $this->get($groupId);
285
+                    if ($aGroup instanceof IGroup) {
286
+                        $groups[$groupId] = $aGroup;
287
+                    } else {
288
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
289
+                    }
290
+                }
291
+            }
292
+        }
293
+        $this->cachedUserGroups[$uid] = $groups;
294
+        return $this->cachedUserGroups[$uid];
295
+    }
296
+
297
+    /**
298
+     * Checks if a userId is in the admin group
299
+     * @param string $userId
300
+     * @return bool if admin
301
+     */
302
+    public function isAdmin($userId) {
303
+        foreach ($this->backends as $backend) {
304
+            if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
305
+                return true;
306
+            }
307
+        }
308
+        return $this->isInGroup($userId, 'admin');
309
+    }
310
+
311
+    /**
312
+     * Checks if a userId is in a group
313
+     * @param string $userId
314
+     * @param string $group
315
+     * @return bool if in group
316
+     */
317
+    public function isInGroup($userId, $group) {
318
+        return array_key_exists($group, $this->getUserIdGroups($userId));
319
+    }
320
+
321
+    /**
322
+     * get a list of group ids for a user
323
+     * @param IUser $user
324
+     * @return array with group ids
325
+     */
326
+    public function getUserGroupIds(IUser $user) {
327
+        return array_map(function($value) {
328
+            return (string) $value;
329
+        }, array_keys($this->getUserGroups($user)));
330
+    }
331
+
332
+    /**
333
+     * get an array of groupid and displayName for a user
334
+     * @param IUser $user
335
+     * @return array ['displayName' => displayname]
336
+     */
337
+    public function getUserGroupNames(IUser $user) {
338
+        return array_map(function($group) {
339
+            return array('displayName' => $group->getDisplayName());
340
+        }, $this->getUserGroups($user));
341
+    }
342
+
343
+    /**
344
+     * get a list of all display names in a group
345
+     * @param string $gid
346
+     * @param string $search
347
+     * @param int $limit
348
+     * @param int $offset
349
+     * @return array an array of display names (value) and user ids (key)
350
+     */
351
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
352
+        $group = $this->get($gid);
353
+        if(is_null($group)) {
354
+            return array();
355
+        }
356
+
357
+        $search = trim($search);
358
+        $groupUsers = array();
359
+
360
+        if(!empty($search)) {
361
+            // only user backends have the capability to do a complex search for users
362
+            $searchOffset = 0;
363
+            $searchLimit = $limit * 100;
364
+            if($limit === -1) {
365
+                $searchLimit = 500;
366
+            }
367
+
368
+            do {
369
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
370
+                foreach($filteredUsers as $filteredUser) {
371
+                    if($group->inGroup($filteredUser)) {
372
+                        $groupUsers[]= $filteredUser;
373
+                    }
374
+                }
375
+                $searchOffset += $searchLimit;
376
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
377
+
378
+            if($limit === -1) {
379
+                $groupUsers = array_slice($groupUsers, $offset);
380
+            } else {
381
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
382
+            }
383
+        } else {
384
+            $groupUsers = $group->searchUsers('', $limit, $offset);
385
+        }
386
+
387
+        $matchingUsers = array();
388
+        foreach($groupUsers as $groupUser) {
389
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
390
+        }
391
+        return $matchingUsers;
392
+    }
393
+
394
+    /**
395
+     * @return \OC\SubAdmin
396
+     */
397
+    public function getSubAdmin() {
398
+        if (!$this->subAdmin) {
399
+            $this->subAdmin = new \OC\SubAdmin(
400
+                $this->userManager,
401
+                $this,
402
+                \OC::$server->getDatabaseConnection()
403
+            );
404
+        }
405
+
406
+        return $this->subAdmin;
407
+    }
408 408
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc') ?: '0.0.0', '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu') ?: '0.0.0', '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
lib/private/Memcache/ArrayCache.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +117 added lines, -117 removed lines patch added patch discarded remove patch
@@ -27,133 +27,133 @@
 block discarded – undo
27 27
 use OCP\IMemcache;
28 28
 
29 29
 class ArrayCache extends Cache implements IMemcache {
30
-	/** @var array Array with the cached data */
31
-	protected $cachedData = array();
30
+    /** @var array Array with the cached data */
31
+    protected $cachedData = array();
32 32
 
33
-	use CADTrait;
33
+    use CADTrait;
34 34
 
35
-	/**
36
-	 * {@inheritDoc}
37
-	 */
38
-	public function get($key) {
39
-		if ($this->hasKey($key)) {
40
-			return $this->cachedData[$key];
41
-		}
42
-		return null;
43
-	}
35
+    /**
36
+     * {@inheritDoc}
37
+     */
38
+    public function get($key) {
39
+        if ($this->hasKey($key)) {
40
+            return $this->cachedData[$key];
41
+        }
42
+        return null;
43
+    }
44 44
 
45
-	/**
46
-	 * {@inheritDoc}
47
-	 */
48
-	public function set($key, $value, $ttl = 0) {
49
-		$this->cachedData[$key] = $value;
50
-		return true;
51
-	}
45
+    /**
46
+     * {@inheritDoc}
47
+     */
48
+    public function set($key, $value, $ttl = 0) {
49
+        $this->cachedData[$key] = $value;
50
+        return true;
51
+    }
52 52
 
53
-	/**
54
-	 * {@inheritDoc}
55
-	 */
56
-	public function hasKey($key) {
57
-		return isset($this->cachedData[$key]);
58
-	}
53
+    /**
54
+     * {@inheritDoc}
55
+     */
56
+    public function hasKey($key) {
57
+        return isset($this->cachedData[$key]);
58
+    }
59 59
 
60
-	/**
61
-	 * {@inheritDoc}
62
-	 */
63
-	public function remove($key) {
64
-		unset($this->cachedData[$key]);
65
-		return true;
66
-	}
60
+    /**
61
+     * {@inheritDoc}
62
+     */
63
+    public function remove($key) {
64
+        unset($this->cachedData[$key]);
65
+        return true;
66
+    }
67 67
 
68
-	/**
69
-	 * {@inheritDoc}
70
-	 */
71
-	public function clear($prefix = '') {
72
-		if ($prefix === '') {
73
-			$this->cachedData = [];
74
-			return true;
75
-		}
68
+    /**
69
+     * {@inheritDoc}
70
+     */
71
+    public function clear($prefix = '') {
72
+        if ($prefix === '') {
73
+            $this->cachedData = [];
74
+            return true;
75
+        }
76 76
 
77
-		foreach ($this->cachedData as $key => $value) {
78
-			if (strpos($key, $prefix) === 0) {
79
-				$this->remove($key);
80
-			}
81
-		}
82
-		return true;
83
-	}
77
+        foreach ($this->cachedData as $key => $value) {
78
+            if (strpos($key, $prefix) === 0) {
79
+                $this->remove($key);
80
+            }
81
+        }
82
+        return true;
83
+    }
84 84
 
85
-	/**
86
-	 * Set a value in the cache if it's not already stored
87
-	 *
88
-	 * @param string $key
89
-	 * @param mixed $value
90
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
-	 * @return bool
92
-	 */
93
-	public function add($key, $value, $ttl = 0) {
94
-		// since this cache is not shared race conditions aren't an issue
95
-		if ($this->hasKey($key)) {
96
-			return false;
97
-		} else {
98
-			return $this->set($key, $value, $ttl);
99
-		}
100
-	}
85
+    /**
86
+     * Set a value in the cache if it's not already stored
87
+     *
88
+     * @param string $key
89
+     * @param mixed $value
90
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
91
+     * @return bool
92
+     */
93
+    public function add($key, $value, $ttl = 0) {
94
+        // since this cache is not shared race conditions aren't an issue
95
+        if ($this->hasKey($key)) {
96
+            return false;
97
+        } else {
98
+            return $this->set($key, $value, $ttl);
99
+        }
100
+    }
101 101
 
102
-	/**
103
-	 * Increase a stored number
104
-	 *
105
-	 * @param string $key
106
-	 * @param int $step
107
-	 * @return int | bool
108
-	 */
109
-	public function inc($key, $step = 1) {
110
-		$oldValue = $this->get($key);
111
-		if (is_int($oldValue)) {
112
-			$this->set($key, $oldValue + $step);
113
-			return $oldValue + $step;
114
-		} else {
115
-			$success = $this->add($key, $step);
116
-			return $success ? $step : false;
117
-		}
118
-	}
102
+    /**
103
+     * Increase a stored number
104
+     *
105
+     * @param string $key
106
+     * @param int $step
107
+     * @return int | bool
108
+     */
109
+    public function inc($key, $step = 1) {
110
+        $oldValue = $this->get($key);
111
+        if (is_int($oldValue)) {
112
+            $this->set($key, $oldValue + $step);
113
+            return $oldValue + $step;
114
+        } else {
115
+            $success = $this->add($key, $step);
116
+            return $success ? $step : false;
117
+        }
118
+    }
119 119
 
120
-	/**
121
-	 * Decrease a stored number
122
-	 *
123
-	 * @param string $key
124
-	 * @param int $step
125
-	 * @return int | bool
126
-	 */
127
-	public function dec($key, $step = 1) {
128
-		$oldValue = $this->get($key);
129
-		if (is_int($oldValue)) {
130
-			$this->set($key, $oldValue - $step);
131
-			return $oldValue - $step;
132
-		} else {
133
-			return false;
134
-		}
135
-	}
120
+    /**
121
+     * Decrease a stored number
122
+     *
123
+     * @param string $key
124
+     * @param int $step
125
+     * @return int | bool
126
+     */
127
+    public function dec($key, $step = 1) {
128
+        $oldValue = $this->get($key);
129
+        if (is_int($oldValue)) {
130
+            $this->set($key, $oldValue - $step);
131
+            return $oldValue - $step;
132
+        } else {
133
+            return false;
134
+        }
135
+    }
136 136
 
137
-	/**
138
-	 * Compare and set
139
-	 *
140
-	 * @param string $key
141
-	 * @param mixed $old
142
-	 * @param mixed $new
143
-	 * @return bool
144
-	 */
145
-	public function cas($key, $old, $new) {
146
-		if ($this->get($key) === $old) {
147
-			return $this->set($key, $new);
148
-		} else {
149
-			return false;
150
-		}
151
-	}
137
+    /**
138
+     * Compare and set
139
+     *
140
+     * @param string $key
141
+     * @param mixed $old
142
+     * @param mixed $new
143
+     * @return bool
144
+     */
145
+    public function cas($key, $old, $new) {
146
+        if ($this->get($key) === $old) {
147
+            return $this->set($key, $new);
148
+        } else {
149
+            return false;
150
+        }
151
+    }
152 152
 
153
-	/**
154
-	 * {@inheritDoc}
155
-	 */
156
-	static public function isAvailable() {
157
-		return true;
158
-	}
153
+    /**
154
+     * {@inheritDoc}
155
+     */
156
+    static public function isAvailable() {
157
+        return true;
158
+    }
159 159
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/SMB.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -498,6 +498,9 @@
 block discarded – undo
498 498
 		});
499 499
 	}
500 500
 
501
+	/**
502
+	 * @param string $path
503
+	 */
501 504
 	public function notify($path) {
502 505
 		$path = '/' . ltrim($path, '/');
503 506
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -95,8 +95,8 @@  discard block
 block discarded – undo
95 95
 		$this->share = $this->server->getShare(trim($params['share'], '/'));
96 96
 
97 97
 		$this->root = $params['root'] ?? '/';
98
-		$this->root = '/' . ltrim($this->root, '/');
99
-		$this->root = rtrim($this->root, '/') . '/';
98
+		$this->root = '/'.ltrim($this->root, '/');
99
+		$this->root = rtrim($this->root, '/').'/';
100 100
 
101 101
 		$this->statCache = new CappedMemoryCache();
102 102
 		parent::__construct($params);
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		// FIXME: double slash to keep compatible with the old storage ids,
110 110
 		// failure to do so will lead to creation of a new storage id and
111 111
 		// loss of shares from the storage
112
-		return 'smb::' . $this->server->getAuth()->getUsername() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
112
+		return 'smb::'.$this->server->getAuth()->getUsername().'@'.$this->server->getHost().'//'.$this->share->getName().'/'.$this->root;
113 113
 	}
114 114
 
115 115
 	/**
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 	 * @return string
118 118
 	 */
119 119
 	protected function buildPath($path) {
120
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
120
+		return Filesystem::normalizePath($this->root.'/'.$path, true, false, true);
121 121
 	}
122 122
 
123 123
 	protected function relativePath($fullPath) {
@@ -157,9 +157,9 @@  discard block
 block discarded – undo
157 157
 			$path = $this->buildPath($path);
158 158
 			$files = $this->share->dir($path);
159 159
 			foreach ($files as $file) {
160
-				$this->statCache[$path . '/' . $file->getName()] = $file;
160
+				$this->statCache[$path.'/'.$file->getName()] = $file;
161 161
 			}
162
-			return array_filter($files, function (IFileInfo $file) {
162
+			return array_filter($files, function(IFileInfo $file) {
163 163
 				try {
164 164
 					return !$file->isHidden();
165 165
 				} catch (ForbiddenException $e) {
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 				case 'w':
334 334
 				case 'wb':
335 335
 					$source = $this->share->write($fullPath);
336
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
336
+					return CallBackWrapper::wrap($source, null, null, function() use ($fullPath) {
337 337
 						unset($this->statCache[$fullPath]);
338 338
 					});
339 339
 				case 'a':
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 					}
366 366
 					$source = fopen($tmpFile, $mode);
367 367
 					$share = $this->share;
368
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
368
+					return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath, $share) {
369 369
 						unset($this->statCache[$fullPath]);
370 370
 						$share->put($tmpFile, $fullPath);
371 371
 						unlink($tmpFile);
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
 			$content = $this->share->dir($this->buildPath($path));
392 392
 			foreach ($content as $file) {
393 393
 				if ($file->isDirectory()) {
394
-					$this->rmdir($path . '/' . $file->getName());
394
+					$this->rmdir($path.'/'.$file->getName());
395 395
 				} else {
396 396
 					$this->share->del($file->getPath());
397 397
 				}
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 		} catch (ForbiddenException $e) {
429 429
 			return false;
430 430
 		}
431
-		$names = array_map(function ($info) {
431
+		$names = array_map(function($info) {
432 432
 			/** @var \Icewind\SMB\IFileInfo $info */
433 433
 			return $info->getName();
434 434
 		}, $files);
@@ -510,7 +510,7 @@  discard block
 block discarded – undo
510 510
 	 */
511 511
 	public static function checkDependencies() {
512 512
 		return (
513
-			(bool)\OC_Helper::findBinaryPath('smbclient')
513
+			(bool) \OC_Helper::findBinaryPath('smbclient')
514 514
 			|| NativeServer::available(new System())
515 515
 		) ? true : ['smbclient'];
516 516
 	}
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 	}
530 530
 
531 531
 	public function listen($path, callable $callback) {
532
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
532
+		$this->notify($path)->listen(function(IChange $change) use ($callback) {
533 533
 			if ($change instanceof IRenameChange) {
534 534
 				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
535 535
 			} else {
@@ -539,7 +539,7 @@  discard block
 block discarded – undo
539 539
 	}
540 540
 
541 541
 	public function notify($path) {
542
-		$path = '/' . ltrim($path, '/');
542
+		$path = '/'.ltrim($path, '/');
543 543
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
544 544
 		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
545 545
 	}
Please login to merge, or discard this patch.
Indentation   +497 added lines, -497 removed lines patch added patch discarded remove patch
@@ -57,501 +57,501 @@
 block discarded – undo
57 57
 use OCP\ILogger;
58 58
 
59 59
 class SMB extends Common implements INotifyStorage {
60
-	/**
61
-	 * @var \Icewind\SMB\IServer
62
-	 */
63
-	protected $server;
64
-
65
-	/**
66
-	 * @var \Icewind\SMB\IShare
67
-	 */
68
-	protected $share;
69
-
70
-	/**
71
-	 * @var string
72
-	 */
73
-	protected $root;
74
-
75
-	/**
76
-	 * @var \Icewind\SMB\IFileInfo[]
77
-	 */
78
-	protected $statCache;
79
-
80
-	public function __construct($params) {
81
-		if (!isset($params['host'])) {
82
-			throw new \Exception('Invalid configuration, no host provided');
83
-		}
84
-
85
-		if (isset($params['auth'])) {
86
-			$auth = $params['auth'];
87
-		} else if (isset($params['user']) && isset($params['password']) && isset($params['share'])) {
88
-			list($workgroup, $user) = $this->splitUser($params['user']);
89
-			$auth = new BasicAuth($user, $workgroup, $params['password']);
90
-		} else {
91
-			throw new \Exception('Invalid configuration, no credentials provided');
92
-		}
93
-
94
-		$serverFactory = new ServerFactory();
95
-		$this->server = $serverFactory->createServer($params['host'], $auth);
96
-		$this->share = $this->server->getShare(trim($params['share'], '/'));
97
-
98
-		$this->root = $params['root'] ?? '/';
99
-		$this->root = '/' . ltrim($this->root, '/');
100
-		$this->root = rtrim($this->root, '/') . '/';
101
-
102
-		$this->statCache = new CappedMemoryCache();
103
-		parent::__construct($params);
104
-	}
105
-
106
-	private function splitUser($user) {
107
-		if (strpos($user, '/')) {
108
-			return explode('/', $user, 2);
109
-		} elseif (strpos($user, '\\')) {
110
-			return explode('\\', $user);
111
-		} else {
112
-			return [null, $user];
113
-		}
114
-	}
115
-
116
-	/**
117
-	 * @return string
118
-	 */
119
-	public function getId() {
120
-		// FIXME: double slash to keep compatible with the old storage ids,
121
-		// failure to do so will lead to creation of a new storage id and
122
-		// loss of shares from the storage
123
-		return 'smb::' . $this->server->getAuth()->getUsername() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
124
-	}
125
-
126
-	/**
127
-	 * @param string $path
128
-	 * @return string
129
-	 */
130
-	protected function buildPath($path) {
131
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
132
-	}
133
-
134
-	protected function relativePath($fullPath) {
135
-		if ($fullPath === $this->root) {
136
-			return '';
137
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
138
-			return substr($fullPath, strlen($this->root));
139
-		} else {
140
-			return null;
141
-		}
142
-	}
143
-
144
-	/**
145
-	 * @param string $path
146
-	 * @return \Icewind\SMB\IFileInfo
147
-	 * @throws StorageNotAvailableException
148
-	 */
149
-	protected function getFileInfo($path) {
150
-		try {
151
-			$path = $this->buildPath($path);
152
-			if (!isset($this->statCache[$path])) {
153
-				$this->statCache[$path] = $this->share->stat($path);
154
-			}
155
-			return $this->statCache[$path];
156
-		} catch (ConnectException $e) {
157
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
158
-		}
159
-	}
160
-
161
-	/**
162
-	 * @param string $path
163
-	 * @return \Icewind\SMB\IFileInfo[]
164
-	 * @throws StorageNotAvailableException
165
-	 */
166
-	protected function getFolderContents($path) {
167
-		try {
168
-			$path = $this->buildPath($path);
169
-			$files = $this->share->dir($path);
170
-			foreach ($files as $file) {
171
-				$this->statCache[$path . '/' . $file->getName()] = $file;
172
-			}
173
-			return array_filter($files, function (IFileInfo $file) {
174
-				try {
175
-					return !$file->isHidden();
176
-				} catch (ForbiddenException $e) {
177
-					return false;
178
-				} catch (NotFoundException $e) {
179
-					return false;
180
-				}
181
-			});
182
-		} catch (ConnectException $e) {
183
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
184
-		}
185
-	}
186
-
187
-	/**
188
-	 * @param \Icewind\SMB\IFileInfo $info
189
-	 * @return array
190
-	 */
191
-	protected function formatInfo($info) {
192
-		$result = [
193
-			'size' => $info->getSize(),
194
-			'mtime' => $info->getMTime(),
195
-		];
196
-		if ($info->isDirectory()) {
197
-			$result['type'] = 'dir';
198
-		} else {
199
-			$result['type'] = 'file';
200
-		}
201
-		return $result;
202
-	}
203
-
204
-	/**
205
-	 * Rename the files. If the source or the target is the root, the rename won't happen.
206
-	 *
207
-	 * @param string $source the old name of the path
208
-	 * @param string $target the new name of the path
209
-	 * @return bool true if the rename is successful, false otherwise
210
-	 */
211
-	public function rename($source, $target) {
212
-		if ($this->isRootDir($source) || $this->isRootDir($target)) {
213
-			return false;
214
-		}
215
-
216
-		$absoluteSource = $this->buildPath($source);
217
-		$absoluteTarget = $this->buildPath($target);
218
-		try {
219
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
220
-		} catch (AlreadyExistsException $e) {
221
-			$this->remove($target);
222
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
223
-		} catch (\Exception $e) {
224
-			\OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
225
-			return false;
226
-		}
227
-		unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
228
-		return $result;
229
-	}
230
-
231
-	public function stat($path) {
232
-		try {
233
-			$result = $this->formatInfo($this->getFileInfo($path));
234
-		} catch (ForbiddenException $e) {
235
-			return false;
236
-		} catch (NotFoundException $e) {
237
-			return false;
238
-		}
239
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
240
-			$result['mtime'] = $this->shareMTime();
241
-		}
242
-		return $result;
243
-	}
244
-
245
-	/**
246
-	 * get the best guess for the modification time of the share
247
-	 *
248
-	 * @return int
249
-	 */
250
-	private function shareMTime() {
251
-		$highestMTime = 0;
252
-		$files = $this->share->dir($this->root);
253
-		foreach ($files as $fileInfo) {
254
-			try {
255
-				if ($fileInfo->getMTime() > $highestMTime) {
256
-					$highestMTime = $fileInfo->getMTime();
257
-				}
258
-			} catch (NotFoundException $e) {
259
-				// Ignore this, can happen on unavailable DFS shares
260
-			}
261
-		}
262
-		return $highestMTime;
263
-	}
264
-
265
-	/**
266
-	 * Check if the path is our root dir (not the smb one)
267
-	 *
268
-	 * @param string $path the path
269
-	 * @return bool
270
-	 */
271
-	private function isRootDir($path) {
272
-		return $path === '' || $path === '/' || $path === '.';
273
-	}
274
-
275
-	/**
276
-	 * Check if our root points to a smb share
277
-	 *
278
-	 * @return bool true if our root points to a share false otherwise
279
-	 */
280
-	private function remoteIsShare() {
281
-		return $this->share->getName() && (!$this->root || $this->root === '/');
282
-	}
283
-
284
-	/**
285
-	 * @param string $path
286
-	 * @return bool
287
-	 */
288
-	public function unlink($path) {
289
-		if ($this->isRootDir($path)) {
290
-			return false;
291
-		}
292
-
293
-		try {
294
-			if ($this->is_dir($path)) {
295
-				return $this->rmdir($path);
296
-			} else {
297
-				$path = $this->buildPath($path);
298
-				unset($this->statCache[$path]);
299
-				$this->share->del($path);
300
-				return true;
301
-			}
302
-		} catch (NotFoundException $e) {
303
-			return false;
304
-		} catch (ForbiddenException $e) {
305
-			return false;
306
-		} catch (ConnectException $e) {
307
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
308
-		}
309
-	}
310
-
311
-	/**
312
-	 * check if a file or folder has been updated since $time
313
-	 *
314
-	 * @param string $path
315
-	 * @param int $time
316
-	 * @return bool
317
-	 */
318
-	public function hasUpdated($path, $time) {
319
-		if (!$path and $this->root === '/') {
320
-			// mtime doesn't work for shares, but giving the nature of the backend,
321
-			// doing a full update is still just fast enough
322
-			return true;
323
-		} else {
324
-			$actualTime = $this->filemtime($path);
325
-			return $actualTime > $time;
326
-		}
327
-	}
328
-
329
-	/**
330
-	 * @param string $path
331
-	 * @param string $mode
332
-	 * @return resource|false
333
-	 */
334
-	public function fopen($path, $mode) {
335
-		$fullPath = $this->buildPath($path);
336
-		try {
337
-			switch ($mode) {
338
-				case 'r':
339
-				case 'rb':
340
-					if (!$this->file_exists($path)) {
341
-						return false;
342
-					}
343
-					return $this->share->read($fullPath);
344
-				case 'w':
345
-				case 'wb':
346
-					$source = $this->share->write($fullPath);
347
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
348
-						unset($this->statCache[$fullPath]);
349
-					});
350
-				case 'a':
351
-				case 'ab':
352
-				case 'r+':
353
-				case 'w+':
354
-				case 'wb+':
355
-				case 'a+':
356
-				case 'x':
357
-				case 'x+':
358
-				case 'c':
359
-				case 'c+':
360
-					//emulate these
361
-					if (strrpos($path, '.') !== false) {
362
-						$ext = substr($path, strrpos($path, '.'));
363
-					} else {
364
-						$ext = '';
365
-					}
366
-					if ($this->file_exists($path)) {
367
-						if (!$this->isUpdatable($path)) {
368
-							return false;
369
-						}
370
-						$tmpFile = $this->getCachedFile($path);
371
-					} else {
372
-						if (!$this->isCreatable(dirname($path))) {
373
-							return false;
374
-						}
375
-						$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
376
-					}
377
-					$source = fopen($tmpFile, $mode);
378
-					$share = $this->share;
379
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
380
-						unset($this->statCache[$fullPath]);
381
-						$share->put($tmpFile, $fullPath);
382
-						unlink($tmpFile);
383
-					});
384
-			}
385
-			return false;
386
-		} catch (NotFoundException $e) {
387
-			return false;
388
-		} catch (ForbiddenException $e) {
389
-			return false;
390
-		} catch (ConnectException $e) {
391
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
392
-		}
393
-	}
394
-
395
-	public function rmdir($path) {
396
-		if ($this->isRootDir($path)) {
397
-			return false;
398
-		}
399
-
400
-		try {
401
-			$this->statCache = array();
402
-			$content = $this->share->dir($this->buildPath($path));
403
-			foreach ($content as $file) {
404
-				if ($file->isDirectory()) {
405
-					$this->rmdir($path . '/' . $file->getName());
406
-				} else {
407
-					$this->share->del($file->getPath());
408
-				}
409
-			}
410
-			$this->share->rmdir($this->buildPath($path));
411
-			return true;
412
-		} catch (NotFoundException $e) {
413
-			return false;
414
-		} catch (ForbiddenException $e) {
415
-			return false;
416
-		} catch (ConnectException $e) {
417
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
418
-		}
419
-	}
420
-
421
-	public function touch($path, $time = null) {
422
-		try {
423
-			if (!$this->file_exists($path)) {
424
-				$fh = $this->share->write($this->buildPath($path));
425
-				fclose($fh);
426
-				return true;
427
-			}
428
-			return false;
429
-		} catch (ConnectException $e) {
430
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
431
-		}
432
-	}
433
-
434
-	public function opendir($path) {
435
-		try {
436
-			$files = $this->getFolderContents($path);
437
-		} catch (NotFoundException $e) {
438
-			return false;
439
-		} catch (ForbiddenException $e) {
440
-			return false;
441
-		}
442
-		$names = array_map(function ($info) {
443
-			/** @var \Icewind\SMB\IFileInfo $info */
444
-			return $info->getName();
445
-		}, $files);
446
-		return IteratorDirectory::wrap($names);
447
-	}
448
-
449
-	public function filetype($path) {
450
-		try {
451
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
452
-		} catch (NotFoundException $e) {
453
-			return false;
454
-		} catch (ForbiddenException $e) {
455
-			return false;
456
-		}
457
-	}
458
-
459
-	public function mkdir($path) {
460
-		$path = $this->buildPath($path);
461
-		try {
462
-			$this->share->mkdir($path);
463
-			return true;
464
-		} catch (ConnectException $e) {
465
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
466
-		} catch (Exception $e) {
467
-			return false;
468
-		}
469
-	}
470
-
471
-	public function file_exists($path) {
472
-		try {
473
-			$this->getFileInfo($path);
474
-			return true;
475
-		} catch (NotFoundException $e) {
476
-			return false;
477
-		} catch (ForbiddenException $e) {
478
-			return false;
479
-		} catch (ConnectException $e) {
480
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
481
-		}
482
-	}
483
-
484
-	public function isReadable($path) {
485
-		try {
486
-			$info = $this->getFileInfo($path);
487
-			return !$info->isHidden();
488
-		} catch (NotFoundException $e) {
489
-			return false;
490
-		} catch (ForbiddenException $e) {
491
-			return false;
492
-		}
493
-	}
494
-
495
-	public function isUpdatable($path) {
496
-		try {
497
-			$info = $this->getFileInfo($path);
498
-			// following windows behaviour for read-only folders: they can be written into
499
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
500
-			return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
501
-		} catch (NotFoundException $e) {
502
-			return false;
503
-		} catch (ForbiddenException $e) {
504
-			return false;
505
-		}
506
-	}
507
-
508
-	public function isDeletable($path) {
509
-		try {
510
-			$info = $this->getFileInfo($path);
511
-			return !$info->isHidden() && !$info->isReadOnly();
512
-		} catch (NotFoundException $e) {
513
-			return false;
514
-		} catch (ForbiddenException $e) {
515
-			return false;
516
-		}
517
-	}
518
-
519
-	/**
520
-	 * check if smbclient is installed
521
-	 */
522
-	public static function checkDependencies() {
523
-		return (
524
-			(bool)\OC_Helper::findBinaryPath('smbclient')
525
-			|| NativeServer::available(new System())
526
-		) ? true : ['smbclient'];
527
-	}
528
-
529
-	/**
530
-	 * Test a storage for availability
531
-	 *
532
-	 * @return bool
533
-	 */
534
-	public function test() {
535
-		try {
536
-			return parent::test();
537
-		} catch (Exception $e) {
538
-			return false;
539
-		}
540
-	}
541
-
542
-	public function listen($path, callable $callback) {
543
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
544
-			if ($change instanceof IRenameChange) {
545
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
546
-			} else {
547
-				return $callback($change->getType(), $change->getPath());
548
-			}
549
-		});
550
-	}
551
-
552
-	public function notify($path) {
553
-		$path = '/' . ltrim($path, '/');
554
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
555
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
556
-	}
60
+    /**
61
+     * @var \Icewind\SMB\IServer
62
+     */
63
+    protected $server;
64
+
65
+    /**
66
+     * @var \Icewind\SMB\IShare
67
+     */
68
+    protected $share;
69
+
70
+    /**
71
+     * @var string
72
+     */
73
+    protected $root;
74
+
75
+    /**
76
+     * @var \Icewind\SMB\IFileInfo[]
77
+     */
78
+    protected $statCache;
79
+
80
+    public function __construct($params) {
81
+        if (!isset($params['host'])) {
82
+            throw new \Exception('Invalid configuration, no host provided');
83
+        }
84
+
85
+        if (isset($params['auth'])) {
86
+            $auth = $params['auth'];
87
+        } else if (isset($params['user']) && isset($params['password']) && isset($params['share'])) {
88
+            list($workgroup, $user) = $this->splitUser($params['user']);
89
+            $auth = new BasicAuth($user, $workgroup, $params['password']);
90
+        } else {
91
+            throw new \Exception('Invalid configuration, no credentials provided');
92
+        }
93
+
94
+        $serverFactory = new ServerFactory();
95
+        $this->server = $serverFactory->createServer($params['host'], $auth);
96
+        $this->share = $this->server->getShare(trim($params['share'], '/'));
97
+
98
+        $this->root = $params['root'] ?? '/';
99
+        $this->root = '/' . ltrim($this->root, '/');
100
+        $this->root = rtrim($this->root, '/') . '/';
101
+
102
+        $this->statCache = new CappedMemoryCache();
103
+        parent::__construct($params);
104
+    }
105
+
106
+    private function splitUser($user) {
107
+        if (strpos($user, '/')) {
108
+            return explode('/', $user, 2);
109
+        } elseif (strpos($user, '\\')) {
110
+            return explode('\\', $user);
111
+        } else {
112
+            return [null, $user];
113
+        }
114
+    }
115
+
116
+    /**
117
+     * @return string
118
+     */
119
+    public function getId() {
120
+        // FIXME: double slash to keep compatible with the old storage ids,
121
+        // failure to do so will lead to creation of a new storage id and
122
+        // loss of shares from the storage
123
+        return 'smb::' . $this->server->getAuth()->getUsername() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
124
+    }
125
+
126
+    /**
127
+     * @param string $path
128
+     * @return string
129
+     */
130
+    protected function buildPath($path) {
131
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
132
+    }
133
+
134
+    protected function relativePath($fullPath) {
135
+        if ($fullPath === $this->root) {
136
+            return '';
137
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
138
+            return substr($fullPath, strlen($this->root));
139
+        } else {
140
+            return null;
141
+        }
142
+    }
143
+
144
+    /**
145
+     * @param string $path
146
+     * @return \Icewind\SMB\IFileInfo
147
+     * @throws StorageNotAvailableException
148
+     */
149
+    protected function getFileInfo($path) {
150
+        try {
151
+            $path = $this->buildPath($path);
152
+            if (!isset($this->statCache[$path])) {
153
+                $this->statCache[$path] = $this->share->stat($path);
154
+            }
155
+            return $this->statCache[$path];
156
+        } catch (ConnectException $e) {
157
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
158
+        }
159
+    }
160
+
161
+    /**
162
+     * @param string $path
163
+     * @return \Icewind\SMB\IFileInfo[]
164
+     * @throws StorageNotAvailableException
165
+     */
166
+    protected function getFolderContents($path) {
167
+        try {
168
+            $path = $this->buildPath($path);
169
+            $files = $this->share->dir($path);
170
+            foreach ($files as $file) {
171
+                $this->statCache[$path . '/' . $file->getName()] = $file;
172
+            }
173
+            return array_filter($files, function (IFileInfo $file) {
174
+                try {
175
+                    return !$file->isHidden();
176
+                } catch (ForbiddenException $e) {
177
+                    return false;
178
+                } catch (NotFoundException $e) {
179
+                    return false;
180
+                }
181
+            });
182
+        } catch (ConnectException $e) {
183
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
184
+        }
185
+    }
186
+
187
+    /**
188
+     * @param \Icewind\SMB\IFileInfo $info
189
+     * @return array
190
+     */
191
+    protected function formatInfo($info) {
192
+        $result = [
193
+            'size' => $info->getSize(),
194
+            'mtime' => $info->getMTime(),
195
+        ];
196
+        if ($info->isDirectory()) {
197
+            $result['type'] = 'dir';
198
+        } else {
199
+            $result['type'] = 'file';
200
+        }
201
+        return $result;
202
+    }
203
+
204
+    /**
205
+     * Rename the files. If the source or the target is the root, the rename won't happen.
206
+     *
207
+     * @param string $source the old name of the path
208
+     * @param string $target the new name of the path
209
+     * @return bool true if the rename is successful, false otherwise
210
+     */
211
+    public function rename($source, $target) {
212
+        if ($this->isRootDir($source) || $this->isRootDir($target)) {
213
+            return false;
214
+        }
215
+
216
+        $absoluteSource = $this->buildPath($source);
217
+        $absoluteTarget = $this->buildPath($target);
218
+        try {
219
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
220
+        } catch (AlreadyExistsException $e) {
221
+            $this->remove($target);
222
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
223
+        } catch (\Exception $e) {
224
+            \OC::$server->getLogger()->logException($e, ['level' => ILogger::WARN]);
225
+            return false;
226
+        }
227
+        unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
228
+        return $result;
229
+    }
230
+
231
+    public function stat($path) {
232
+        try {
233
+            $result = $this->formatInfo($this->getFileInfo($path));
234
+        } catch (ForbiddenException $e) {
235
+            return false;
236
+        } catch (NotFoundException $e) {
237
+            return false;
238
+        }
239
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
240
+            $result['mtime'] = $this->shareMTime();
241
+        }
242
+        return $result;
243
+    }
244
+
245
+    /**
246
+     * get the best guess for the modification time of the share
247
+     *
248
+     * @return int
249
+     */
250
+    private function shareMTime() {
251
+        $highestMTime = 0;
252
+        $files = $this->share->dir($this->root);
253
+        foreach ($files as $fileInfo) {
254
+            try {
255
+                if ($fileInfo->getMTime() > $highestMTime) {
256
+                    $highestMTime = $fileInfo->getMTime();
257
+                }
258
+            } catch (NotFoundException $e) {
259
+                // Ignore this, can happen on unavailable DFS shares
260
+            }
261
+        }
262
+        return $highestMTime;
263
+    }
264
+
265
+    /**
266
+     * Check if the path is our root dir (not the smb one)
267
+     *
268
+     * @param string $path the path
269
+     * @return bool
270
+     */
271
+    private function isRootDir($path) {
272
+        return $path === '' || $path === '/' || $path === '.';
273
+    }
274
+
275
+    /**
276
+     * Check if our root points to a smb share
277
+     *
278
+     * @return bool true if our root points to a share false otherwise
279
+     */
280
+    private function remoteIsShare() {
281
+        return $this->share->getName() && (!$this->root || $this->root === '/');
282
+    }
283
+
284
+    /**
285
+     * @param string $path
286
+     * @return bool
287
+     */
288
+    public function unlink($path) {
289
+        if ($this->isRootDir($path)) {
290
+            return false;
291
+        }
292
+
293
+        try {
294
+            if ($this->is_dir($path)) {
295
+                return $this->rmdir($path);
296
+            } else {
297
+                $path = $this->buildPath($path);
298
+                unset($this->statCache[$path]);
299
+                $this->share->del($path);
300
+                return true;
301
+            }
302
+        } catch (NotFoundException $e) {
303
+            return false;
304
+        } catch (ForbiddenException $e) {
305
+            return false;
306
+        } catch (ConnectException $e) {
307
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
308
+        }
309
+    }
310
+
311
+    /**
312
+     * check if a file or folder has been updated since $time
313
+     *
314
+     * @param string $path
315
+     * @param int $time
316
+     * @return bool
317
+     */
318
+    public function hasUpdated($path, $time) {
319
+        if (!$path and $this->root === '/') {
320
+            // mtime doesn't work for shares, but giving the nature of the backend,
321
+            // doing a full update is still just fast enough
322
+            return true;
323
+        } else {
324
+            $actualTime = $this->filemtime($path);
325
+            return $actualTime > $time;
326
+        }
327
+    }
328
+
329
+    /**
330
+     * @param string $path
331
+     * @param string $mode
332
+     * @return resource|false
333
+     */
334
+    public function fopen($path, $mode) {
335
+        $fullPath = $this->buildPath($path);
336
+        try {
337
+            switch ($mode) {
338
+                case 'r':
339
+                case 'rb':
340
+                    if (!$this->file_exists($path)) {
341
+                        return false;
342
+                    }
343
+                    return $this->share->read($fullPath);
344
+                case 'w':
345
+                case 'wb':
346
+                    $source = $this->share->write($fullPath);
347
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
348
+                        unset($this->statCache[$fullPath]);
349
+                    });
350
+                case 'a':
351
+                case 'ab':
352
+                case 'r+':
353
+                case 'w+':
354
+                case 'wb+':
355
+                case 'a+':
356
+                case 'x':
357
+                case 'x+':
358
+                case 'c':
359
+                case 'c+':
360
+                    //emulate these
361
+                    if (strrpos($path, '.') !== false) {
362
+                        $ext = substr($path, strrpos($path, '.'));
363
+                    } else {
364
+                        $ext = '';
365
+                    }
366
+                    if ($this->file_exists($path)) {
367
+                        if (!$this->isUpdatable($path)) {
368
+                            return false;
369
+                        }
370
+                        $tmpFile = $this->getCachedFile($path);
371
+                    } else {
372
+                        if (!$this->isCreatable(dirname($path))) {
373
+                            return false;
374
+                        }
375
+                        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
376
+                    }
377
+                    $source = fopen($tmpFile, $mode);
378
+                    $share = $this->share;
379
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
380
+                        unset($this->statCache[$fullPath]);
381
+                        $share->put($tmpFile, $fullPath);
382
+                        unlink($tmpFile);
383
+                    });
384
+            }
385
+            return false;
386
+        } catch (NotFoundException $e) {
387
+            return false;
388
+        } catch (ForbiddenException $e) {
389
+            return false;
390
+        } catch (ConnectException $e) {
391
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
392
+        }
393
+    }
394
+
395
+    public function rmdir($path) {
396
+        if ($this->isRootDir($path)) {
397
+            return false;
398
+        }
399
+
400
+        try {
401
+            $this->statCache = array();
402
+            $content = $this->share->dir($this->buildPath($path));
403
+            foreach ($content as $file) {
404
+                if ($file->isDirectory()) {
405
+                    $this->rmdir($path . '/' . $file->getName());
406
+                } else {
407
+                    $this->share->del($file->getPath());
408
+                }
409
+            }
410
+            $this->share->rmdir($this->buildPath($path));
411
+            return true;
412
+        } catch (NotFoundException $e) {
413
+            return false;
414
+        } catch (ForbiddenException $e) {
415
+            return false;
416
+        } catch (ConnectException $e) {
417
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
418
+        }
419
+    }
420
+
421
+    public function touch($path, $time = null) {
422
+        try {
423
+            if (!$this->file_exists($path)) {
424
+                $fh = $this->share->write($this->buildPath($path));
425
+                fclose($fh);
426
+                return true;
427
+            }
428
+            return false;
429
+        } catch (ConnectException $e) {
430
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
431
+        }
432
+    }
433
+
434
+    public function opendir($path) {
435
+        try {
436
+            $files = $this->getFolderContents($path);
437
+        } catch (NotFoundException $e) {
438
+            return false;
439
+        } catch (ForbiddenException $e) {
440
+            return false;
441
+        }
442
+        $names = array_map(function ($info) {
443
+            /** @var \Icewind\SMB\IFileInfo $info */
444
+            return $info->getName();
445
+        }, $files);
446
+        return IteratorDirectory::wrap($names);
447
+    }
448
+
449
+    public function filetype($path) {
450
+        try {
451
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
452
+        } catch (NotFoundException $e) {
453
+            return false;
454
+        } catch (ForbiddenException $e) {
455
+            return false;
456
+        }
457
+    }
458
+
459
+    public function mkdir($path) {
460
+        $path = $this->buildPath($path);
461
+        try {
462
+            $this->share->mkdir($path);
463
+            return true;
464
+        } catch (ConnectException $e) {
465
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
466
+        } catch (Exception $e) {
467
+            return false;
468
+        }
469
+    }
470
+
471
+    public function file_exists($path) {
472
+        try {
473
+            $this->getFileInfo($path);
474
+            return true;
475
+        } catch (NotFoundException $e) {
476
+            return false;
477
+        } catch (ForbiddenException $e) {
478
+            return false;
479
+        } catch (ConnectException $e) {
480
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
481
+        }
482
+    }
483
+
484
+    public function isReadable($path) {
485
+        try {
486
+            $info = $this->getFileInfo($path);
487
+            return !$info->isHidden();
488
+        } catch (NotFoundException $e) {
489
+            return false;
490
+        } catch (ForbiddenException $e) {
491
+            return false;
492
+        }
493
+    }
494
+
495
+    public function isUpdatable($path) {
496
+        try {
497
+            $info = $this->getFileInfo($path);
498
+            // following windows behaviour for read-only folders: they can be written into
499
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
500
+            return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
501
+        } catch (NotFoundException $e) {
502
+            return false;
503
+        } catch (ForbiddenException $e) {
504
+            return false;
505
+        }
506
+    }
507
+
508
+    public function isDeletable($path) {
509
+        try {
510
+            $info = $this->getFileInfo($path);
511
+            return !$info->isHidden() && !$info->isReadOnly();
512
+        } catch (NotFoundException $e) {
513
+            return false;
514
+        } catch (ForbiddenException $e) {
515
+            return false;
516
+        }
517
+    }
518
+
519
+    /**
520
+     * check if smbclient is installed
521
+     */
522
+    public static function checkDependencies() {
523
+        return (
524
+            (bool)\OC_Helper::findBinaryPath('smbclient')
525
+            || NativeServer::available(new System())
526
+        ) ? true : ['smbclient'];
527
+    }
528
+
529
+    /**
530
+     * Test a storage for availability
531
+     *
532
+     * @return bool
533
+     */
534
+    public function test() {
535
+        try {
536
+            return parent::test();
537
+        } catch (Exception $e) {
538
+            return false;
539
+        }
540
+    }
541
+
542
+    public function listen($path, callable $callback) {
543
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
544
+            if ($change instanceof IRenameChange) {
545
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
546
+            } else {
547
+                return $callback($change->getType(), $change->getPath());
548
+            }
549
+        });
550
+    }
551
+
552
+    public function notify($path) {
553
+        $path = '/' . ltrim($path, '/');
554
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
555
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
556
+    }
557 557
 }
Please login to merge, or discard this patch.