Completed
Pull Request — master (#9224)
by Jan-Christoph
28:56 queued 04:45
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.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 	public function showAuthenticate($token) {
157 157
 		$share = $this->shareManager->getShareByToken($token);
158 158
 
159
-		if($this->linkShareAuth($share)) {
159
+		if ($this->linkShareAuth($share)) {
160 160
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161 161
 		}
162 162
 
@@ -217,15 +217,15 @@  discard block
 block discarded – undo
217 217
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
218 218
 		if ($password !== null) {
219 219
 			if ($this->shareManager->checkPassword($share, $password)) {
220
-				$this->session->set('public_link_authenticated', (string)$share->getId());
220
+				$this->session->set('public_link_authenticated', (string) $share->getId());
221 221
 			} else {
222 222
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
223 223
 				return false;
224 224
 			}
225 225
 		} else {
226 226
 			// not authenticated ?
227
-			if ( ! $this->session->exists('public_link_authenticated')
228
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
227
+			if (!$this->session->exists('public_link_authenticated')
228
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
229 229
 				return false;
230 230
 			}
231 231
 		}
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		$itemType = $itemSource = $uidOwner = '';
247 247
 		$token = $share;
248 248
 		$exception = null;
249
-		if($share instanceof \OCP\Share\IShare) {
249
+		if ($share instanceof \OCP\Share\IShare) {
250 250
 			try {
251 251
 				$token = $share->getToken();
252 252
 				$uidOwner = $share->getSharedBy();
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 			'errorCode' => $errorCode,
266 266
 			'errorMessage' => $errorMessage,
267 267
 		]);
268
-		if(!is_null($exception)) {
268
+		if (!is_null($exception)) {
269 269
 			throw $exception;
270 270
 		}
271 271
 	}
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
 		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
392 392
 		$ogPreview = '';
393 393
 		if ($shareTmpl['previewSupported']) {
394
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
394
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
395 395
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
396 396
 			$ogPreview = $shareTmpl['previewImage'];
397 397
 
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 
440 440
 		// OpenGraph Support: http://ogp.me/
441 441
 		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
442
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
442
+		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName().($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '')]);
443 443
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
444 444
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
445 445
 		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 
484 484
 		$share = $this->shareManager->getShareByToken($token);
485 485
 
486
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
486
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
487 487
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
488 488
 		}
489 489
 
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 
566 566
 		$this->emitAccessShareHook($share);
567 567
 
568
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
568
+		$server_params = array('head' => $this->request->getMethod() === 'HEAD');
569 569
 
570 570
 		/**
571 571
 		 * Http range requests support
Please login to merge, or discard this patch.
Indentation   +595 added lines, -595 removed lines patch added patch discarded remove patch
@@ -70,603 +70,603 @@
 block discarded – undo
70 70
  */
71 71
 class ShareController extends Controller {
72 72
 
73
-	/** @var IConfig */
74
-	protected $config;
75
-	/** @var IURLGenerator */
76
-	protected $urlGenerator;
77
-	/** @var IUserManager */
78
-	protected $userManager;
79
-	/** @var ILogger */
80
-	protected $logger;
81
-	/** @var \OCP\Activity\IManager */
82
-	protected $activityManager;
83
-	/** @var \OCP\Share\IManager */
84
-	protected $shareManager;
85
-	/** @var ISession */
86
-	protected $session;
87
-	/** @var IPreview */
88
-	protected $previewManager;
89
-	/** @var IRootFolder */
90
-	protected $rootFolder;
91
-	/** @var FederatedShareProvider */
92
-	protected $federatedShareProvider;
93
-	/** @var EventDispatcherInterface */
94
-	protected $eventDispatcher;
95
-	/** @var IL10N */
96
-	protected $l10n;
97
-	/** @var Defaults */
98
-	protected $defaults;
99
-
100
-	/**
101
-	 * @param string $appName
102
-	 * @param IRequest $request
103
-	 * @param IConfig $config
104
-	 * @param IURLGenerator $urlGenerator
105
-	 * @param IUserManager $userManager
106
-	 * @param ILogger $logger
107
-	 * @param \OCP\Activity\IManager $activityManager
108
-	 * @param \OCP\Share\IManager $shareManager
109
-	 * @param ISession $session
110
-	 * @param IPreview $previewManager
111
-	 * @param IRootFolder $rootFolder
112
-	 * @param FederatedShareProvider $federatedShareProvider
113
-	 * @param EventDispatcherInterface $eventDispatcher
114
-	 * @param IL10N $l10n
115
-	 * @param Defaults $defaults
116
-	 */
117
-	public function __construct($appName,
118
-								IRequest $request,
119
-								IConfig $config,
120
-								IURLGenerator $urlGenerator,
121
-								IUserManager $userManager,
122
-								ILogger $logger,
123
-								\OCP\Activity\IManager $activityManager,
124
-								\OCP\Share\IManager $shareManager,
125
-								ISession $session,
126
-								IPreview $previewManager,
127
-								IRootFolder $rootFolder,
128
-								FederatedShareProvider $federatedShareProvider,
129
-								EventDispatcherInterface $eventDispatcher,
130
-								IL10N $l10n,
131
-								Defaults $defaults) {
132
-		parent::__construct($appName, $request);
133
-
134
-		$this->config = $config;
135
-		$this->urlGenerator = $urlGenerator;
136
-		$this->userManager = $userManager;
137
-		$this->logger = $logger;
138
-		$this->activityManager = $activityManager;
139
-		$this->shareManager = $shareManager;
140
-		$this->session = $session;
141
-		$this->previewManager = $previewManager;
142
-		$this->rootFolder = $rootFolder;
143
-		$this->federatedShareProvider = $federatedShareProvider;
144
-		$this->eventDispatcher = $eventDispatcher;
145
-		$this->l10n = $l10n;
146
-		$this->defaults = $defaults;
147
-	}
148
-
149
-	/**
150
-	 * @PublicPage
151
-	 * @NoCSRFRequired
152
-	 *
153
-	 * @param string $token
154
-	 * @return TemplateResponse|RedirectResponse
155
-	 */
156
-	public function showAuthenticate($token) {
157
-		$share = $this->shareManager->getShareByToken($token);
158
-
159
-		if($this->linkShareAuth($share)) {
160
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161
-		}
162
-
163
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
164
-	}
165
-
166
-	/**
167
-	 * @PublicPage
168
-	 * @UseSession
169
-	 * @BruteForceProtection(action=publicLinkAuth)
170
-	 *
171
-	 * Authenticates against password-protected shares
172
-	 * @param string $token
173
-	 * @param string $redirect
174
-	 * @param string $password
175
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
176
-	 */
177
-	public function authenticate($token, $redirect, $password = '') {
178
-
179
-		// Check whether share exists
180
-		try {
181
-			$share = $this->shareManager->getShareByToken($token);
182
-		} catch (ShareNotFound $e) {
183
-			return new NotFoundResponse();
184
-		}
185
-
186
-		$authenticate = $this->linkShareAuth($share, $password);
187
-
188
-		// if download was requested before auth, redirect to download
189
-		if ($authenticate === true && $redirect === 'download') {
190
-			return new RedirectResponse($this->urlGenerator->linkToRoute(
191
-				'files_sharing.sharecontroller.downloadShare',
192
-				array('token' => $token))
193
-			);
194
-		} else if ($authenticate === true) {
195
-			return new RedirectResponse($this->urlGenerator->linkToRoute(
196
-				'files_sharing.sharecontroller.showShare',
197
-				array('token' => $token))
198
-			);
199
-		}
200
-
201
-		$response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
202
-		$response->throttle();
203
-		return $response;
204
-	}
205
-
206
-	/**
207
-	 * Authenticate a link item with the given password.
208
-	 * Or use the session if no password is provided.
209
-	 *
210
-	 * This is a modified version of Helper::authenticate
211
-	 * TODO: Try to merge back eventually with Helper::authenticate
212
-	 *
213
-	 * @param \OCP\Share\IShare $share
214
-	 * @param string|null $password
215
-	 * @return bool
216
-	 */
217
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
218
-		if ($password !== null) {
219
-			if ($this->shareManager->checkPassword($share, $password)) {
220
-				$this->session->set('public_link_authenticated', (string)$share->getId());
221
-			} else {
222
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
223
-				return false;
224
-			}
225
-		} else {
226
-			// not authenticated ?
227
-			if ( ! $this->session->exists('public_link_authenticated')
228
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
229
-				return false;
230
-			}
231
-		}
232
-		return true;
233
-	}
234
-
235
-	/**
236
-	 * throws hooks when a share is attempted to be accessed
237
-	 *
238
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
239
-	 * otherwise token
240
-	 * @param int $errorCode
241
-	 * @param string $errorMessage
242
-	 * @throws \OC\HintException
243
-	 * @throws \OC\ServerNotAvailableException
244
-	 */
245
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
246
-		$itemType = $itemSource = $uidOwner = '';
247
-		$token = $share;
248
-		$exception = null;
249
-		if($share instanceof \OCP\Share\IShare) {
250
-			try {
251
-				$token = $share->getToken();
252
-				$uidOwner = $share->getSharedBy();
253
-				$itemType = $share->getNodeType();
254
-				$itemSource = $share->getNodeId();
255
-			} catch (\Exception $e) {
256
-				// we log what we know and pass on the exception afterwards
257
-				$exception = $e;
258
-			}
259
-		}
260
-		\OC_Hook::emit(Share::class, 'share_link_access', [
261
-			'itemType' => $itemType,
262
-			'itemSource' => $itemSource,
263
-			'uidOwner' => $uidOwner,
264
-			'token' => $token,
265
-			'errorCode' => $errorCode,
266
-			'errorMessage' => $errorMessage,
267
-		]);
268
-		if(!is_null($exception)) {
269
-			throw $exception;
270
-		}
271
-	}
272
-
273
-	/**
274
-	 * Validate the permissions of the share
275
-	 *
276
-	 * @param Share\IShare $share
277
-	 * @return bool
278
-	 */
279
-	private function validateShare(\OCP\Share\IShare $share) {
280
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
281
-	}
282
-
283
-	/**
284
-	 * @PublicPage
285
-	 * @NoCSRFRequired
286
-	 *
287
-	 * @param string $token
288
-	 * @param string $path
289
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
290
-	 * @throws NotFoundException
291
-	 * @throws \Exception
292
-	 */
293
-	public function showShare($token, $path = '') {
294
-		\OC_User::setIncognitoMode(true);
295
-
296
-		// Check whether share exists
297
-		try {
298
-			$share = $this->shareManager->getShareByToken($token);
299
-		} catch (ShareNotFound $e) {
300
-			$this->emitAccessShareHook($token, 404, 'Share not found');
301
-			return new NotFoundResponse();
302
-		}
303
-
304
-		// Share is password protected - check whether the user is permitted to access the share
305
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
306
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
307
-				array('token' => $token, 'redirect' => 'preview')));
308
-		}
309
-
310
-		if (!$this->validateShare($share)) {
311
-			throw new NotFoundException();
312
-		}
313
-		// We can't get the path of a file share
314
-		try {
315
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
316
-				$this->emitAccessShareHook($share, 404, 'Share not found');
317
-				throw new NotFoundException();
318
-			}
319
-		} catch (\Exception $e) {
320
-			$this->emitAccessShareHook($share, 404, 'Share not found');
321
-			throw $e;
322
-		}
323
-
324
-		$shareTmpl = [];
325
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
326
-		$shareTmpl['owner'] = $share->getShareOwner();
327
-		$shareTmpl['filename'] = $share->getNode()->getName();
328
-		$shareTmpl['directory_path'] = $share->getTarget();
329
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
330
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
331
-		$shareTmpl['dirToken'] = $token;
332
-		$shareTmpl['sharingToken'] = $token;
333
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
334
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
335
-		$shareTmpl['dir'] = '';
336
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
337
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
338
-
339
-		// Show file list
340
-		$hideFileList = false;
341
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
342
-			/** @var \OCP\Files\Folder $rootFolder */
343
-			$rootFolder = $share->getNode();
344
-
345
-			try {
346
-				$folderNode = $rootFolder->get($path);
347
-			} catch (\OCP\Files\NotFoundException $e) {
348
-				$this->emitAccessShareHook($share, 404, 'Share not found');
349
-				throw new NotFoundException();
350
-			}
351
-
352
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
353
-
354
-			/*
73
+    /** @var IConfig */
74
+    protected $config;
75
+    /** @var IURLGenerator */
76
+    protected $urlGenerator;
77
+    /** @var IUserManager */
78
+    protected $userManager;
79
+    /** @var ILogger */
80
+    protected $logger;
81
+    /** @var \OCP\Activity\IManager */
82
+    protected $activityManager;
83
+    /** @var \OCP\Share\IManager */
84
+    protected $shareManager;
85
+    /** @var ISession */
86
+    protected $session;
87
+    /** @var IPreview */
88
+    protected $previewManager;
89
+    /** @var IRootFolder */
90
+    protected $rootFolder;
91
+    /** @var FederatedShareProvider */
92
+    protected $federatedShareProvider;
93
+    /** @var EventDispatcherInterface */
94
+    protected $eventDispatcher;
95
+    /** @var IL10N */
96
+    protected $l10n;
97
+    /** @var Defaults */
98
+    protected $defaults;
99
+
100
+    /**
101
+     * @param string $appName
102
+     * @param IRequest $request
103
+     * @param IConfig $config
104
+     * @param IURLGenerator $urlGenerator
105
+     * @param IUserManager $userManager
106
+     * @param ILogger $logger
107
+     * @param \OCP\Activity\IManager $activityManager
108
+     * @param \OCP\Share\IManager $shareManager
109
+     * @param ISession $session
110
+     * @param IPreview $previewManager
111
+     * @param IRootFolder $rootFolder
112
+     * @param FederatedShareProvider $federatedShareProvider
113
+     * @param EventDispatcherInterface $eventDispatcher
114
+     * @param IL10N $l10n
115
+     * @param Defaults $defaults
116
+     */
117
+    public function __construct($appName,
118
+                                IRequest $request,
119
+                                IConfig $config,
120
+                                IURLGenerator $urlGenerator,
121
+                                IUserManager $userManager,
122
+                                ILogger $logger,
123
+                                \OCP\Activity\IManager $activityManager,
124
+                                \OCP\Share\IManager $shareManager,
125
+                                ISession $session,
126
+                                IPreview $previewManager,
127
+                                IRootFolder $rootFolder,
128
+                                FederatedShareProvider $federatedShareProvider,
129
+                                EventDispatcherInterface $eventDispatcher,
130
+                                IL10N $l10n,
131
+                                Defaults $defaults) {
132
+        parent::__construct($appName, $request);
133
+
134
+        $this->config = $config;
135
+        $this->urlGenerator = $urlGenerator;
136
+        $this->userManager = $userManager;
137
+        $this->logger = $logger;
138
+        $this->activityManager = $activityManager;
139
+        $this->shareManager = $shareManager;
140
+        $this->session = $session;
141
+        $this->previewManager = $previewManager;
142
+        $this->rootFolder = $rootFolder;
143
+        $this->federatedShareProvider = $federatedShareProvider;
144
+        $this->eventDispatcher = $eventDispatcher;
145
+        $this->l10n = $l10n;
146
+        $this->defaults = $defaults;
147
+    }
148
+
149
+    /**
150
+     * @PublicPage
151
+     * @NoCSRFRequired
152
+     *
153
+     * @param string $token
154
+     * @return TemplateResponse|RedirectResponse
155
+     */
156
+    public function showAuthenticate($token) {
157
+        $share = $this->shareManager->getShareByToken($token);
158
+
159
+        if($this->linkShareAuth($share)) {
160
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
161
+        }
162
+
163
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
164
+    }
165
+
166
+    /**
167
+     * @PublicPage
168
+     * @UseSession
169
+     * @BruteForceProtection(action=publicLinkAuth)
170
+     *
171
+     * Authenticates against password-protected shares
172
+     * @param string $token
173
+     * @param string $redirect
174
+     * @param string $password
175
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
176
+     */
177
+    public function authenticate($token, $redirect, $password = '') {
178
+
179
+        // Check whether share exists
180
+        try {
181
+            $share = $this->shareManager->getShareByToken($token);
182
+        } catch (ShareNotFound $e) {
183
+            return new NotFoundResponse();
184
+        }
185
+
186
+        $authenticate = $this->linkShareAuth($share, $password);
187
+
188
+        // if download was requested before auth, redirect to download
189
+        if ($authenticate === true && $redirect === 'download') {
190
+            return new RedirectResponse($this->urlGenerator->linkToRoute(
191
+                'files_sharing.sharecontroller.downloadShare',
192
+                array('token' => $token))
193
+            );
194
+        } else if ($authenticate === true) {
195
+            return new RedirectResponse($this->urlGenerator->linkToRoute(
196
+                'files_sharing.sharecontroller.showShare',
197
+                array('token' => $token))
198
+            );
199
+        }
200
+
201
+        $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
202
+        $response->throttle();
203
+        return $response;
204
+    }
205
+
206
+    /**
207
+     * Authenticate a link item with the given password.
208
+     * Or use the session if no password is provided.
209
+     *
210
+     * This is a modified version of Helper::authenticate
211
+     * TODO: Try to merge back eventually with Helper::authenticate
212
+     *
213
+     * @param \OCP\Share\IShare $share
214
+     * @param string|null $password
215
+     * @return bool
216
+     */
217
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
218
+        if ($password !== null) {
219
+            if ($this->shareManager->checkPassword($share, $password)) {
220
+                $this->session->set('public_link_authenticated', (string)$share->getId());
221
+            } else {
222
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
223
+                return false;
224
+            }
225
+        } else {
226
+            // not authenticated ?
227
+            if ( ! $this->session->exists('public_link_authenticated')
228
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
229
+                return false;
230
+            }
231
+        }
232
+        return true;
233
+    }
234
+
235
+    /**
236
+     * throws hooks when a share is attempted to be accessed
237
+     *
238
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
239
+     * otherwise token
240
+     * @param int $errorCode
241
+     * @param string $errorMessage
242
+     * @throws \OC\HintException
243
+     * @throws \OC\ServerNotAvailableException
244
+     */
245
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
246
+        $itemType = $itemSource = $uidOwner = '';
247
+        $token = $share;
248
+        $exception = null;
249
+        if($share instanceof \OCP\Share\IShare) {
250
+            try {
251
+                $token = $share->getToken();
252
+                $uidOwner = $share->getSharedBy();
253
+                $itemType = $share->getNodeType();
254
+                $itemSource = $share->getNodeId();
255
+            } catch (\Exception $e) {
256
+                // we log what we know and pass on the exception afterwards
257
+                $exception = $e;
258
+            }
259
+        }
260
+        \OC_Hook::emit(Share::class, 'share_link_access', [
261
+            'itemType' => $itemType,
262
+            'itemSource' => $itemSource,
263
+            'uidOwner' => $uidOwner,
264
+            'token' => $token,
265
+            'errorCode' => $errorCode,
266
+            'errorMessage' => $errorMessage,
267
+        ]);
268
+        if(!is_null($exception)) {
269
+            throw $exception;
270
+        }
271
+    }
272
+
273
+    /**
274
+     * Validate the permissions of the share
275
+     *
276
+     * @param Share\IShare $share
277
+     * @return bool
278
+     */
279
+    private function validateShare(\OCP\Share\IShare $share) {
280
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
281
+    }
282
+
283
+    /**
284
+     * @PublicPage
285
+     * @NoCSRFRequired
286
+     *
287
+     * @param string $token
288
+     * @param string $path
289
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
290
+     * @throws NotFoundException
291
+     * @throws \Exception
292
+     */
293
+    public function showShare($token, $path = '') {
294
+        \OC_User::setIncognitoMode(true);
295
+
296
+        // Check whether share exists
297
+        try {
298
+            $share = $this->shareManager->getShareByToken($token);
299
+        } catch (ShareNotFound $e) {
300
+            $this->emitAccessShareHook($token, 404, 'Share not found');
301
+            return new NotFoundResponse();
302
+        }
303
+
304
+        // Share is password protected - check whether the user is permitted to access the share
305
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
306
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
307
+                array('token' => $token, 'redirect' => 'preview')));
308
+        }
309
+
310
+        if (!$this->validateShare($share)) {
311
+            throw new NotFoundException();
312
+        }
313
+        // We can't get the path of a file share
314
+        try {
315
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
316
+                $this->emitAccessShareHook($share, 404, 'Share not found');
317
+                throw new NotFoundException();
318
+            }
319
+        } catch (\Exception $e) {
320
+            $this->emitAccessShareHook($share, 404, 'Share not found');
321
+            throw $e;
322
+        }
323
+
324
+        $shareTmpl = [];
325
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
326
+        $shareTmpl['owner'] = $share->getShareOwner();
327
+        $shareTmpl['filename'] = $share->getNode()->getName();
328
+        $shareTmpl['directory_path'] = $share->getTarget();
329
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
330
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
331
+        $shareTmpl['dirToken'] = $token;
332
+        $shareTmpl['sharingToken'] = $token;
333
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
334
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
335
+        $shareTmpl['dir'] = '';
336
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
337
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
338
+
339
+        // Show file list
340
+        $hideFileList = false;
341
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
342
+            /** @var \OCP\Files\Folder $rootFolder */
343
+            $rootFolder = $share->getNode();
344
+
345
+            try {
346
+                $folderNode = $rootFolder->get($path);
347
+            } catch (\OCP\Files\NotFoundException $e) {
348
+                $this->emitAccessShareHook($share, 404, 'Share not found');
349
+                throw new NotFoundException();
350
+            }
351
+
352
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
353
+
354
+            /*
355 355
 			 * The OC_Util methods require a view. This just uses the node API
356 356
 			 */
357
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
358
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
359
-				$freeSpace = max($freeSpace, 0);
360
-			} else {
361
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
362
-			}
363
-
364
-			$hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
365
-			$maxUploadFilesize = $freeSpace;
366
-
367
-			$folder = new Template('files', 'list', '');
368
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
369
-			$folder->assign('dirToken', $token);
370
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
371
-			$folder->assign('isPublic', true);
372
-			$folder->assign('hideFileList', $hideFileList);
373
-			$folder->assign('publicUploadEnabled', 'no');
374
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
375
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
376
-			$folder->assign('freeSpace', $freeSpace);
377
-			$folder->assign('usedSpacePercent', 0);
378
-			$folder->assign('trash', false);
379
-			$shareTmpl['folder'] = $folder->fetchPage();
380
-		}
381
-
382
-		$shareTmpl['hideFileList'] = $hideFileList;
383
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
384
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
385
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
386
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
387
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
388
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
389
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
390
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
391
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
392
-		$ogPreview = '';
393
-		if ($shareTmpl['previewSupported']) {
394
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
395
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
396
-			$ogPreview = $shareTmpl['previewImage'];
397
-
398
-			// We just have direct previews for image files
399
-			if ($share->getNode()->getMimePart() === 'image') {
400
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
401
-
402
-				$ogPreview = $shareTmpl['previewURL'];
403
-
404
-				//Whatapp is kind of picky about their size requirements
405
-				if ($this->request->isUserAgent(['/^WhatsApp/'])) {
406
-					$ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
407
-						't' => $token,
408
-						'x' => 256,
409
-						'y' => 256,
410
-						'a' => true,
411
-					]);
412
-				}
413
-			}
414
-		} else {
415
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
416
-			$ogPreview = $shareTmpl['previewImage'];
417
-		}
418
-
419
-		// Load files we need
420
-		\OCP\Util::addScript('files', 'file-upload');
421
-		\OCP\Util::addStyle('files_sharing', 'publicView');
422
-		\OCP\Util::addScript('files_sharing', 'public');
423
-		\OCP\Util::addScript('files', 'fileactions');
424
-		\OCP\Util::addScript('files', 'fileactionsmenu');
425
-		\OCP\Util::addScript('files', 'jquery.fileupload');
426
-		\OCP\Util::addScript('files_sharing', 'files_drop');
427
-
428
-		if (isset($shareTmpl['folder'])) {
429
-			// JS required for folders
430
-			\OCP\Util::addStyle('files', 'merged');
431
-			\OCP\Util::addScript('files', 'filesummary');
432
-			\OCP\Util::addScript('files', 'breadcrumb');
433
-			\OCP\Util::addScript('files', 'fileinfomodel');
434
-			\OCP\Util::addScript('files', 'newfilemenu');
435
-			\OCP\Util::addScript('files', 'files');
436
-			\OCP\Util::addScript('files', 'filelist');
437
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
438
-		}
439
-
440
-		// OpenGraph Support: http://ogp.me/
441
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
442
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
443
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
444
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
445
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
446
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
447
-
448
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
449
-
450
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
451
-		$csp->addAllowedFrameDomain('\'self\'');
452
-
453
-		$response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
454
-		$response->setHeaderTitle($shareTmpl['filename']);
455
-		$response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
456
-		$response->setHeaderActions([
457
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
458
-			new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
459
-			new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
460
-			new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
461
-		]);
462
-
463
-		$response->setContentSecurityPolicy($csp);
464
-
465
-		$this->emitAccessShareHook($share);
466
-
467
-		return $response;
468
-	}
469
-
470
-	/**
471
-	 * @PublicPage
472
-	 * @NoCSRFRequired
473
-	 *
474
-	 * @param string $token
475
-	 * @param string $files
476
-	 * @param string $path
477
-	 * @param string $downloadStartSecret
478
-	 * @return void|\OCP\AppFramework\Http\Response
479
-	 * @throws NotFoundException
480
-	 */
481
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
482
-		\OC_User::setIncognitoMode(true);
483
-
484
-		$share = $this->shareManager->getShareByToken($token);
485
-
486
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
487
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
488
-		}
489
-
490
-		// Share is password protected - check whether the user is permitted to access the share
491
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
492
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
493
-				['token' => $token, 'redirect' => 'download']));
494
-		}
495
-
496
-		$files_list = null;
497
-		if (!is_null($files)) { // download selected files
498
-			$files_list = json_decode($files);
499
-			// in case we get only a single file
500
-			if ($files_list === null) {
501
-				$files_list = [$files];
502
-			}
503
-			// Just in case $files is a single int like '1234'
504
-			if (!is_array($files_list)) {
505
-				$files_list = [$files_list];
506
-			}
507
-		}
508
-
509
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
510
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
511
-
512
-		if (!$this->validateShare($share)) {
513
-			throw new NotFoundException();
514
-		}
515
-
516
-		// Single file share
517
-		if ($share->getNode() instanceof \OCP\Files\File) {
518
-			// Single file download
519
-			$this->singleFileDownloaded($share, $share->getNode());
520
-		}
521
-		// Directory share
522
-		else {
523
-			/** @var \OCP\Files\Folder $node */
524
-			$node = $share->getNode();
525
-
526
-			// Try to get the path
527
-			if ($path !== '') {
528
-				try {
529
-					$node = $node->get($path);
530
-				} catch (NotFoundException $e) {
531
-					$this->emitAccessShareHook($share, 404, 'Share not found');
532
-					return new NotFoundResponse();
533
-				}
534
-			}
535
-
536
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
537
-
538
-			if ($node instanceof \OCP\Files\File) {
539
-				// Single file download
540
-				$this->singleFileDownloaded($share, $share->getNode());
541
-			} else if (!empty($files_list)) {
542
-				$this->fileListDownloaded($share, $files_list, $node);
543
-			} else {
544
-				// The folder is downloaded
545
-				$this->singleFileDownloaded($share, $share->getNode());
546
-			}
547
-		}
548
-
549
-		/* FIXME: We should do this all nicely in OCP */
550
-		OC_Util::tearDownFS();
551
-		OC_Util::setupFS($share->getShareOwner());
552
-
553
-		/**
554
-		 * this sets a cookie to be able to recognize the start of the download
555
-		 * the content must not be longer than 32 characters and must only contain
556
-		 * alphanumeric characters
557
-		 */
558
-		if (!empty($downloadStartSecret)
559
-			&& !isset($downloadStartSecret[32])
560
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
561
-
562
-			// FIXME: set on the response once we use an actual app framework response
563
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
564
-		}
565
-
566
-		$this->emitAccessShareHook($share);
567
-
568
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
569
-
570
-		/**
571
-		 * Http range requests support
572
-		 */
573
-		if (isset($_SERVER['HTTP_RANGE'])) {
574
-			$server_params['range'] = $this->request->getHeader('Range');
575
-		}
576
-
577
-		// download selected files
578
-		if (!is_null($files) && $files !== '') {
579
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
580
-			// after dispatching the request which results in a "Cannot modify header information" notice.
581
-			OC_Files::get($originalSharePath, $files_list, $server_params);
582
-			exit();
583
-		} else {
584
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
585
-			// after dispatching the request which results in a "Cannot modify header information" notice.
586
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
587
-			exit();
588
-		}
589
-	}
590
-
591
-	/**
592
-	 * create activity for every downloaded file
593
-	 *
594
-	 * @param Share\IShare $share
595
-	 * @param array $files_list
596
-	 * @param \OCP\Files\Folder $node
597
-	 */
598
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
599
-		foreach ($files_list as $file) {
600
-			$subNode = $node->get($file);
601
-			$this->singleFileDownloaded($share, $subNode);
602
-		}
603
-
604
-	}
605
-
606
-	/**
607
-	 * create activity if a single file was downloaded from a link share
608
-	 *
609
-	 * @param Share\IShare $share
610
-	 */
611
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
612
-
613
-		$fileId = $node->getId();
614
-
615
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
616
-		$userNodeList = $userFolder->getById($fileId);
617
-		$userNode = $userNodeList[0];
618
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
619
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
620
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
621
-
622
-		$parameters = [$userPath];
623
-
624
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
-			if ($node instanceof \OCP\Files\File) {
626
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
627
-			} else {
628
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
629
-			}
630
-			$parameters[] = $share->getSharedWith();
631
-		} else {
632
-			if ($node instanceof \OCP\Files\File) {
633
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
634
-			} else {
635
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
636
-			}
637
-		}
638
-
639
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
640
-
641
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
642
-			$parameters[0] = $ownerPath;
643
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
644
-		}
645
-	}
646
-
647
-	/**
648
-	 * publish activity
649
-	 *
650
-	 * @param string $subject
651
-	 * @param array $parameters
652
-	 * @param string $affectedUser
653
-	 * @param int $fileId
654
-	 * @param string $filePath
655
-	 */
656
-	protected function publishActivity($subject,
657
-										array $parameters,
658
-										$affectedUser,
659
-										$fileId,
660
-										$filePath) {
661
-
662
-		$event = $this->activityManager->generateEvent();
663
-		$event->setApp('files_sharing')
664
-			->setType('public_links')
665
-			->setSubject($subject, $parameters)
666
-			->setAffectedUser($affectedUser)
667
-			->setObject('files', $fileId, $filePath);
668
-		$this->activityManager->publish($event);
669
-	}
357
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
358
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
359
+                $freeSpace = max($freeSpace, 0);
360
+            } else {
361
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
362
+            }
363
+
364
+            $hideFileList = !($share->getPermissions() & \OCP\Constants::PERMISSION_READ);
365
+            $maxUploadFilesize = $freeSpace;
366
+
367
+            $folder = new Template('files', 'list', '');
368
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
369
+            $folder->assign('dirToken', $token);
370
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
371
+            $folder->assign('isPublic', true);
372
+            $folder->assign('hideFileList', $hideFileList);
373
+            $folder->assign('publicUploadEnabled', 'no');
374
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
375
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
376
+            $folder->assign('freeSpace', $freeSpace);
377
+            $folder->assign('usedSpacePercent', 0);
378
+            $folder->assign('trash', false);
379
+            $shareTmpl['folder'] = $folder->fetchPage();
380
+        }
381
+
382
+        $shareTmpl['hideFileList'] = $hideFileList;
383
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
384
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
385
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
386
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
387
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
388
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
389
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
390
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
391
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
392
+        $ogPreview = '';
393
+        if ($shareTmpl['previewSupported']) {
394
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
395
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
396
+            $ogPreview = $shareTmpl['previewImage'];
397
+
398
+            // We just have direct previews for image files
399
+            if ($share->getNode()->getMimePart() === 'image') {
400
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
401
+
402
+                $ogPreview = $shareTmpl['previewURL'];
403
+
404
+                //Whatapp is kind of picky about their size requirements
405
+                if ($this->request->isUserAgent(['/^WhatsApp/'])) {
406
+                    $ogPreview = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview', [
407
+                        't' => $token,
408
+                        'x' => 256,
409
+                        'y' => 256,
410
+                        'a' => true,
411
+                    ]);
412
+                }
413
+            }
414
+        } else {
415
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
416
+            $ogPreview = $shareTmpl['previewImage'];
417
+        }
418
+
419
+        // Load files we need
420
+        \OCP\Util::addScript('files', 'file-upload');
421
+        \OCP\Util::addStyle('files_sharing', 'publicView');
422
+        \OCP\Util::addScript('files_sharing', 'public');
423
+        \OCP\Util::addScript('files', 'fileactions');
424
+        \OCP\Util::addScript('files', 'fileactionsmenu');
425
+        \OCP\Util::addScript('files', 'jquery.fileupload');
426
+        \OCP\Util::addScript('files_sharing', 'files_drop');
427
+
428
+        if (isset($shareTmpl['folder'])) {
429
+            // JS required for folders
430
+            \OCP\Util::addStyle('files', 'merged');
431
+            \OCP\Util::addScript('files', 'filesummary');
432
+            \OCP\Util::addScript('files', 'breadcrumb');
433
+            \OCP\Util::addScript('files', 'fileinfomodel');
434
+            \OCP\Util::addScript('files', 'newfilemenu');
435
+            \OCP\Util::addScript('files', 'files');
436
+            \OCP\Util::addScript('files', 'filelist');
437
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
438
+        }
439
+
440
+        // OpenGraph Support: http://ogp.me/
441
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
442
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
443
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
444
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
445
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
446
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
447
+
448
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
449
+
450
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
451
+        $csp->addAllowedFrameDomain('\'self\'');
452
+
453
+        $response = new PublicTemplateResponse($this->appName, 'public', $shareTmpl);
454
+        $response->setHeaderTitle($shareTmpl['filename']);
455
+        $response->setHeaderDetails($this->l10n->t('shared by %s', [$shareTmpl['displayName']]));
456
+        $response->setHeaderActions([
457
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download-white', $shareTmpl['downloadURL'], 0),
458
+            new SimpleMenuAction('download', $this->l10n->t('Download'), 'icon-download', $shareTmpl['downloadURL'], 10, $shareTmpl['fileSize']),
459
+            new LinkMenuAction($this->l10n->t('Direct link'), 'icon-public', $shareTmpl['previewURL']),
460
+            new ExternalShareMenuAction($this->l10n->t('Add to your Nextcloud'), 'icon-external', $shareTmpl['owner'], $shareTmpl['displayName'], $shareTmpl['filename']),
461
+        ]);
462
+
463
+        $response->setContentSecurityPolicy($csp);
464
+
465
+        $this->emitAccessShareHook($share);
466
+
467
+        return $response;
468
+    }
469
+
470
+    /**
471
+     * @PublicPage
472
+     * @NoCSRFRequired
473
+     *
474
+     * @param string $token
475
+     * @param string $files
476
+     * @param string $path
477
+     * @param string $downloadStartSecret
478
+     * @return void|\OCP\AppFramework\Http\Response
479
+     * @throws NotFoundException
480
+     */
481
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
482
+        \OC_User::setIncognitoMode(true);
483
+
484
+        $share = $this->shareManager->getShareByToken($token);
485
+
486
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
487
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
488
+        }
489
+
490
+        // Share is password protected - check whether the user is permitted to access the share
491
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
492
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
493
+                ['token' => $token, 'redirect' => 'download']));
494
+        }
495
+
496
+        $files_list = null;
497
+        if (!is_null($files)) { // download selected files
498
+            $files_list = json_decode($files);
499
+            // in case we get only a single file
500
+            if ($files_list === null) {
501
+                $files_list = [$files];
502
+            }
503
+            // Just in case $files is a single int like '1234'
504
+            if (!is_array($files_list)) {
505
+                $files_list = [$files_list];
506
+            }
507
+        }
508
+
509
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
510
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
511
+
512
+        if (!$this->validateShare($share)) {
513
+            throw new NotFoundException();
514
+        }
515
+
516
+        // Single file share
517
+        if ($share->getNode() instanceof \OCP\Files\File) {
518
+            // Single file download
519
+            $this->singleFileDownloaded($share, $share->getNode());
520
+        }
521
+        // Directory share
522
+        else {
523
+            /** @var \OCP\Files\Folder $node */
524
+            $node = $share->getNode();
525
+
526
+            // Try to get the path
527
+            if ($path !== '') {
528
+                try {
529
+                    $node = $node->get($path);
530
+                } catch (NotFoundException $e) {
531
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
532
+                    return new NotFoundResponse();
533
+                }
534
+            }
535
+
536
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
537
+
538
+            if ($node instanceof \OCP\Files\File) {
539
+                // Single file download
540
+                $this->singleFileDownloaded($share, $share->getNode());
541
+            } else if (!empty($files_list)) {
542
+                $this->fileListDownloaded($share, $files_list, $node);
543
+            } else {
544
+                // The folder is downloaded
545
+                $this->singleFileDownloaded($share, $share->getNode());
546
+            }
547
+        }
548
+
549
+        /* FIXME: We should do this all nicely in OCP */
550
+        OC_Util::tearDownFS();
551
+        OC_Util::setupFS($share->getShareOwner());
552
+
553
+        /**
554
+         * this sets a cookie to be able to recognize the start of the download
555
+         * the content must not be longer than 32 characters and must only contain
556
+         * alphanumeric characters
557
+         */
558
+        if (!empty($downloadStartSecret)
559
+            && !isset($downloadStartSecret[32])
560
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
561
+
562
+            // FIXME: set on the response once we use an actual app framework response
563
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
564
+        }
565
+
566
+        $this->emitAccessShareHook($share);
567
+
568
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
569
+
570
+        /**
571
+         * Http range requests support
572
+         */
573
+        if (isset($_SERVER['HTTP_RANGE'])) {
574
+            $server_params['range'] = $this->request->getHeader('Range');
575
+        }
576
+
577
+        // download selected files
578
+        if (!is_null($files) && $files !== '') {
579
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
580
+            // after dispatching the request which results in a "Cannot modify header information" notice.
581
+            OC_Files::get($originalSharePath, $files_list, $server_params);
582
+            exit();
583
+        } else {
584
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
585
+            // after dispatching the request which results in a "Cannot modify header information" notice.
586
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
587
+            exit();
588
+        }
589
+    }
590
+
591
+    /**
592
+     * create activity for every downloaded file
593
+     *
594
+     * @param Share\IShare $share
595
+     * @param array $files_list
596
+     * @param \OCP\Files\Folder $node
597
+     */
598
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
599
+        foreach ($files_list as $file) {
600
+            $subNode = $node->get($file);
601
+            $this->singleFileDownloaded($share, $subNode);
602
+        }
603
+
604
+    }
605
+
606
+    /**
607
+     * create activity if a single file was downloaded from a link share
608
+     *
609
+     * @param Share\IShare $share
610
+     */
611
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
612
+
613
+        $fileId = $node->getId();
614
+
615
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
616
+        $userNodeList = $userFolder->getById($fileId);
617
+        $userNode = $userNodeList[0];
618
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
619
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
620
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
621
+
622
+        $parameters = [$userPath];
623
+
624
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
625
+            if ($node instanceof \OCP\Files\File) {
626
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
627
+            } else {
628
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
629
+            }
630
+            $parameters[] = $share->getSharedWith();
631
+        } else {
632
+            if ($node instanceof \OCP\Files\File) {
633
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
634
+            } else {
635
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
636
+            }
637
+        }
638
+
639
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
640
+
641
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
642
+            $parameters[0] = $ownerPath;
643
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
644
+        }
645
+    }
646
+
647
+    /**
648
+     * publish activity
649
+     *
650
+     * @param string $subject
651
+     * @param array $parameters
652
+     * @param string $affectedUser
653
+     * @param int $fileId
654
+     * @param string $filePath
655
+     */
656
+    protected function publishActivity($subject,
657
+                                        array $parameters,
658
+                                        $affectedUser,
659
+                                        $fileId,
660
+                                        $filePath) {
661
+
662
+        $event = $this->activityManager->generateEvent();
663
+        $event->setApp('files_sharing')
664
+            ->setType('public_links')
665
+            ->setSubject($subject, $parameters)
666
+            ->setAffectedUser($affectedUser)
667
+            ->setObject('files', $fileId, $filePath);
668
+        $this->activityManager->publish($event);
669
+    }
670 670
 
671 671
 
672 672
 }
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)) {
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)) {
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
@@ -85,8 +85,8 @@  discard block
 block discarded – undo
85 85
 			$this->share = $this->server->getShare(trim($params['share'], '/'));
86 86
 
87 87
 			$this->root = $params['root'] ?? '/';
88
-			$this->root = '/' . ltrim($this->root, '/');
89
-			$this->root = rtrim($this->root, '/') . '/';
88
+			$this->root = '/'.ltrim($this->root, '/');
89
+			$this->root = rtrim($this->root, '/').'/';
90 90
 		} else {
91 91
 			throw new \Exception('Invalid configuration');
92 92
 		}
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
 		// FIXME: double slash to keep compatible with the old storage ids,
102 102
 		// failure to do so will lead to creation of a new storage id and
103 103
 		// loss of shares from the storage
104
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
104
+		return 'smb::'.$this->server->getUser().'@'.$this->server->getHost().'//'.$this->share->getName().'/'.$this->root;
105 105
 	}
106 106
 
107 107
 	/**
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 	 * @return string
110 110
 	 */
111 111
 	protected function buildPath($path) {
112
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
112
+		return Filesystem::normalizePath($this->root.'/'.$path, true, false, true);
113 113
 	}
114 114
 
115 115
 	protected function relativePath($fullPath) {
@@ -149,9 +149,9 @@  discard block
 block discarded – undo
149 149
 			$path = $this->buildPath($path);
150 150
 			$files = $this->share->dir($path);
151 151
 			foreach ($files as $file) {
152
-				$this->statCache[$path . '/' . $file->getName()] = $file;
152
+				$this->statCache[$path.'/'.$file->getName()] = $file;
153 153
 			}
154
-			return array_filter($files, function (IFileInfo $file) {
154
+			return array_filter($files, function(IFileInfo $file) {
155 155
 				try {
156 156
 					return !$file->isHidden();
157 157
 				} catch (ForbiddenException $e) {
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 				case 'w':
326 326
 				case 'wb':
327 327
 					$source = $this->share->write($fullPath);
328
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
328
+					return CallBackWrapper::wrap($source, null, null, function() use ($fullPath) {
329 329
 						unset($this->statCache[$fullPath]);
330 330
 					});
331 331
 				case 'a':
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 					}
358 358
 					$source = fopen($tmpFile, $mode);
359 359
 					$share = $this->share;
360
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
360
+					return CallbackWrapper::wrap($source, null, null, function() use ($tmpFile, $fullPath, $share) {
361 361
 						unset($this->statCache[$fullPath]);
362 362
 						$share->put($tmpFile, $fullPath);
363 363
 						unlink($tmpFile);
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 			$content = $this->share->dir($this->buildPath($path));
384 384
 			foreach ($content as $file) {
385 385
 				if ($file->isDirectory()) {
386
-					$this->rmdir($path . '/' . $file->getName());
386
+					$this->rmdir($path.'/'.$file->getName());
387 387
 				} else {
388 388
 					$this->share->del($file->getPath());
389 389
 				}
@@ -420,7 +420,7 @@  discard block
 block discarded – undo
420 420
 		} catch (ForbiddenException $e) {
421 421
 			return false;
422 422
 		}
423
-		$names = array_map(function ($info) {
423
+		$names = array_map(function($info) {
424 424
 			/** @var \Icewind\SMB\IFileInfo $info */
425 425
 			return $info->getName();
426 426
 		}, $files);
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 	 */
503 503
 	public static function checkDependencies() {
504 504
 		return (
505
-			(bool)\OC_Helper::findBinaryPath('smbclient')
505
+			(bool) \OC_Helper::findBinaryPath('smbclient')
506 506
 			|| Server::NativeAvailable()
507 507
 		) ? true : ['smbclient'];
508 508
 	}
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 	}
522 522
 
523 523
 	public function listen($path, callable $callback) {
524
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
524
+		$this->notify($path)->listen(function(IChange $change) use ($callback) {
525 525
 			if ($change instanceof IRenameChange) {
526 526
 				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
527 527
 			} else {
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 	}
532 532
 
533 533
 	public function notify($path) {
534
-		$path = '/' . ltrim($path, '/');
534
+		$path = '/'.ltrim($path, '/');
535 535
 		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
536 536
 		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
537 537
 	}
Please login to merge, or discard this patch.
Indentation   +480 added lines, -480 removed lines patch added patch discarded remove patch
@@ -55,484 +55,484 @@
 block discarded – undo
55 55
 use OCP\Util;
56 56
 
57 57
 class SMB extends Common implements INotifyStorage {
58
-	/**
59
-	 * @var \Icewind\SMB\Server
60
-	 */
61
-	protected $server;
62
-
63
-	/**
64
-	 * @var \Icewind\SMB\Share
65
-	 */
66
-	protected $share;
67
-
68
-	/**
69
-	 * @var string
70
-	 */
71
-	protected $root;
72
-
73
-	/**
74
-	 * @var \Icewind\SMB\FileInfo[]
75
-	 */
76
-	protected $statCache;
77
-
78
-	public function __construct($params) {
79
-		if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
80
-			if (Server::NativeAvailable()) {
81
-				$this->server = new NativeServer($params['host'], $params['user'], $params['password']);
82
-			} else {
83
-				$this->server = new Server($params['host'], $params['user'], $params['password']);
84
-			}
85
-			$this->share = $this->server->getShare(trim($params['share'], '/'));
86
-
87
-			$this->root = $params['root'] ?? '/';
88
-			$this->root = '/' . ltrim($this->root, '/');
89
-			$this->root = rtrim($this->root, '/') . '/';
90
-		} else {
91
-			throw new \Exception('Invalid configuration');
92
-		}
93
-		$this->statCache = new CappedMemoryCache();
94
-		parent::__construct($params);
95
-	}
96
-
97
-	/**
98
-	 * @return string
99
-	 */
100
-	public function getId() {
101
-		// FIXME: double slash to keep compatible with the old storage ids,
102
-		// failure to do so will lead to creation of a new storage id and
103
-		// loss of shares from the storage
104
-		return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
105
-	}
106
-
107
-	/**
108
-	 * @param string $path
109
-	 * @return string
110
-	 */
111
-	protected function buildPath($path) {
112
-		return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
113
-	}
114
-
115
-	protected function relativePath($fullPath) {
116
-		if ($fullPath === $this->root) {
117
-			return '';
118
-		} else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
119
-			return substr($fullPath, strlen($this->root));
120
-		} else {
121
-			return null;
122
-		}
123
-	}
124
-
125
-	/**
126
-	 * @param string $path
127
-	 * @return \Icewind\SMB\IFileInfo
128
-	 * @throws StorageNotAvailableException
129
-	 */
130
-	protected function getFileInfo($path) {
131
-		try {
132
-			$path = $this->buildPath($path);
133
-			if (!isset($this->statCache[$path])) {
134
-				$this->statCache[$path] = $this->share->stat($path);
135
-			}
136
-			return $this->statCache[$path];
137
-		} catch (ConnectException $e) {
138
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * @param string $path
144
-	 * @return \Icewind\SMB\IFileInfo[]
145
-	 * @throws StorageNotAvailableException
146
-	 */
147
-	protected function getFolderContents($path) {
148
-		try {
149
-			$path = $this->buildPath($path);
150
-			$files = $this->share->dir($path);
151
-			foreach ($files as $file) {
152
-				$this->statCache[$path . '/' . $file->getName()] = $file;
153
-			}
154
-			return array_filter($files, function (IFileInfo $file) {
155
-				try {
156
-					return !$file->isHidden();
157
-				} catch (ForbiddenException $e) {
158
-					return false;
159
-				} catch (NotFoundException $e) {
160
-					return false;
161
-				}
162
-			});
163
-		} catch (ConnectException $e) {
164
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
165
-		}
166
-	}
167
-
168
-	/**
169
-	 * @param \Icewind\SMB\IFileInfo $info
170
-	 * @return array
171
-	 */
172
-	protected function formatInfo($info) {
173
-		$result = [
174
-			'size' => $info->getSize(),
175
-			'mtime' => $info->getMTime(),
176
-		];
177
-		if ($info->isDirectory()) {
178
-			$result['type'] = 'dir';
179
-		} else {
180
-			$result['type'] = 'file';
181
-		}
182
-		return $result;
183
-	}
184
-
185
-	/**
186
-	 * Rename the files. If the source or the target is the root, the rename won't happen.
187
-	 *
188
-	 * @param string $source the old name of the path
189
-	 * @param string $target the new name of the path
190
-	 * @return bool true if the rename is successful, false otherwise
191
-	 */
192
-	public function rename($source, $target) {
193
-		if ($this->isRootDir($source) || $this->isRootDir($target)) {
194
-			return false;
195
-		}
196
-
197
-		$absoluteSource = $this->buildPath($source);
198
-		$absoluteTarget = $this->buildPath($target);
199
-		try {
200
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
201
-		} catch (AlreadyExistsException $e) {
202
-			$this->remove($target);
203
-			$result = $this->share->rename($absoluteSource, $absoluteTarget);
204
-		} catch (\Exception $e) {
205
-			\OC::$server->getLogger()->logException($e, ['level' => Util::WARN]);
206
-			return false;
207
-		}
208
-		unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
209
-		return $result;
210
-	}
211
-
212
-	public function stat($path) {
213
-		try {
214
-			$result = $this->formatInfo($this->getFileInfo($path));
215
-		} catch (ForbiddenException $e) {
216
-			return false;
217
-		} catch (NotFoundException $e) {
218
-			return false;
219
-		}
220
-		if ($this->remoteIsShare() && $this->isRootDir($path)) {
221
-			$result['mtime'] = $this->shareMTime();
222
-		}
223
-		return $result;
224
-	}
225
-
226
-	/**
227
-	 * get the best guess for the modification time of the share
228
-	 *
229
-	 * @return int
230
-	 */
231
-	private function shareMTime() {
232
-		$highestMTime = 0;
233
-		$files = $this->share->dir($this->root);
234
-		foreach ($files as $fileInfo) {
235
-			try {
236
-				if ($fileInfo->getMTime() > $highestMTime) {
237
-					$highestMTime = $fileInfo->getMTime();
238
-				}
239
-			} catch (NotFoundException $e) {
240
-				// Ignore this, can happen on unavailable DFS shares
241
-			}
242
-		}
243
-		return $highestMTime;
244
-	}
245
-
246
-	/**
247
-	 * Check if the path is our root dir (not the smb one)
248
-	 *
249
-	 * @param string $path the path
250
-	 * @return bool
251
-	 */
252
-	private function isRootDir($path) {
253
-		return $path === '' || $path === '/' || $path === '.';
254
-	}
255
-
256
-	/**
257
-	 * Check if our root points to a smb share
258
-	 *
259
-	 * @return bool true if our root points to a share false otherwise
260
-	 */
261
-	private function remoteIsShare() {
262
-		return $this->share->getName() && (!$this->root || $this->root === '/');
263
-	}
264
-
265
-	/**
266
-	 * @param string $path
267
-	 * @return bool
268
-	 */
269
-	public function unlink($path) {
270
-		if ($this->isRootDir($path)) {
271
-			return false;
272
-		}
273
-
274
-		try {
275
-			if ($this->is_dir($path)) {
276
-				return $this->rmdir($path);
277
-			} else {
278
-				$path = $this->buildPath($path);
279
-				unset($this->statCache[$path]);
280
-				$this->share->del($path);
281
-				return true;
282
-			}
283
-		} catch (NotFoundException $e) {
284
-			return false;
285
-		} catch (ForbiddenException $e) {
286
-			return false;
287
-		} catch (ConnectException $e) {
288
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
289
-		}
290
-	}
291
-
292
-	/**
293
-	 * check if a file or folder has been updated since $time
294
-	 *
295
-	 * @param string $path
296
-	 * @param int $time
297
-	 * @return bool
298
-	 */
299
-	public function hasUpdated($path, $time) {
300
-		if (!$path and $this->root === '/') {
301
-			// mtime doesn't work for shares, but giving the nature of the backend,
302
-			// doing a full update is still just fast enough
303
-			return true;
304
-		} else {
305
-			$actualTime = $this->filemtime($path);
306
-			return $actualTime > $time;
307
-		}
308
-	}
309
-
310
-	/**
311
-	 * @param string $path
312
-	 * @param string $mode
313
-	 * @return resource|false
314
-	 */
315
-	public function fopen($path, $mode) {
316
-		$fullPath = $this->buildPath($path);
317
-		try {
318
-			switch ($mode) {
319
-				case 'r':
320
-				case 'rb':
321
-					if (!$this->file_exists($path)) {
322
-						return false;
323
-					}
324
-					return $this->share->read($fullPath);
325
-				case 'w':
326
-				case 'wb':
327
-					$source = $this->share->write($fullPath);
328
-					return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
329
-						unset($this->statCache[$fullPath]);
330
-					});
331
-				case 'a':
332
-				case 'ab':
333
-				case 'r+':
334
-				case 'w+':
335
-				case 'wb+':
336
-				case 'a+':
337
-				case 'x':
338
-				case 'x+':
339
-				case 'c':
340
-				case 'c+':
341
-					//emulate these
342
-					if (strrpos($path, '.') !== false) {
343
-						$ext = substr($path, strrpos($path, '.'));
344
-					} else {
345
-						$ext = '';
346
-					}
347
-					if ($this->file_exists($path)) {
348
-						if (!$this->isUpdatable($path)) {
349
-							return false;
350
-						}
351
-						$tmpFile = $this->getCachedFile($path);
352
-					} else {
353
-						if (!$this->isCreatable(dirname($path))) {
354
-							return false;
355
-						}
356
-						$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
357
-					}
358
-					$source = fopen($tmpFile, $mode);
359
-					$share = $this->share;
360
-					return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
361
-						unset($this->statCache[$fullPath]);
362
-						$share->put($tmpFile, $fullPath);
363
-						unlink($tmpFile);
364
-					});
365
-			}
366
-			return false;
367
-		} catch (NotFoundException $e) {
368
-			return false;
369
-		} catch (ForbiddenException $e) {
370
-			return false;
371
-		} catch (ConnectException $e) {
372
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
373
-		}
374
-	}
375
-
376
-	public function rmdir($path) {
377
-		if ($this->isRootDir($path)) {
378
-			return false;
379
-		}
380
-
381
-		try {
382
-			$this->statCache = array();
383
-			$content = $this->share->dir($this->buildPath($path));
384
-			foreach ($content as $file) {
385
-				if ($file->isDirectory()) {
386
-					$this->rmdir($path . '/' . $file->getName());
387
-				} else {
388
-					$this->share->del($file->getPath());
389
-				}
390
-			}
391
-			$this->share->rmdir($this->buildPath($path));
392
-			return true;
393
-		} catch (NotFoundException $e) {
394
-			return false;
395
-		} catch (ForbiddenException $e) {
396
-			return false;
397
-		} catch (ConnectException $e) {
398
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
399
-		}
400
-	}
401
-
402
-	public function touch($path, $time = null) {
403
-		try {
404
-			if (!$this->file_exists($path)) {
405
-				$fh = $this->share->write($this->buildPath($path));
406
-				fclose($fh);
407
-				return true;
408
-			}
409
-			return false;
410
-		} catch (ConnectException $e) {
411
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
412
-		}
413
-	}
414
-
415
-	public function opendir($path) {
416
-		try {
417
-			$files = $this->getFolderContents($path);
418
-		} catch (NotFoundException $e) {
419
-			return false;
420
-		} catch (ForbiddenException $e) {
421
-			return false;
422
-		}
423
-		$names = array_map(function ($info) {
424
-			/** @var \Icewind\SMB\IFileInfo $info */
425
-			return $info->getName();
426
-		}, $files);
427
-		return IteratorDirectory::wrap($names);
428
-	}
429
-
430
-	public function filetype($path) {
431
-		try {
432
-			return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
433
-		} catch (NotFoundException $e) {
434
-			return false;
435
-		} catch (ForbiddenException $e) {
436
-			return false;
437
-		}
438
-	}
439
-
440
-	public function mkdir($path) {
441
-		$path = $this->buildPath($path);
442
-		try {
443
-			$this->share->mkdir($path);
444
-			return true;
445
-		} catch (ConnectException $e) {
446
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
447
-		} catch (Exception $e) {
448
-			return false;
449
-		}
450
-	}
451
-
452
-	public function file_exists($path) {
453
-		try {
454
-			$this->getFileInfo($path);
455
-			return true;
456
-		} catch (NotFoundException $e) {
457
-			return false;
458
-		} catch (ForbiddenException $e) {
459
-			return false;
460
-		} catch (ConnectException $e) {
461
-			throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
462
-		}
463
-	}
464
-
465
-	public function isReadable($path) {
466
-		try {
467
-			$info = $this->getFileInfo($path);
468
-			return !$info->isHidden();
469
-		} catch (NotFoundException $e) {
470
-			return false;
471
-		} catch (ForbiddenException $e) {
472
-			return false;
473
-		}
474
-	}
475
-
476
-	public function isUpdatable($path) {
477
-		try {
478
-			$info = $this->getFileInfo($path);
479
-			// following windows behaviour for read-only folders: they can be written into
480
-			// (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
481
-			return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
482
-		} catch (NotFoundException $e) {
483
-			return false;
484
-		} catch (ForbiddenException $e) {
485
-			return false;
486
-		}
487
-	}
488
-
489
-	public function isDeletable($path) {
490
-		try {
491
-			$info = $this->getFileInfo($path);
492
-			return !$info->isHidden() && !$info->isReadOnly();
493
-		} catch (NotFoundException $e) {
494
-			return false;
495
-		} catch (ForbiddenException $e) {
496
-			return false;
497
-		}
498
-	}
499
-
500
-	/**
501
-	 * check if smbclient is installed
502
-	 */
503
-	public static function checkDependencies() {
504
-		return (
505
-			(bool)\OC_Helper::findBinaryPath('smbclient')
506
-			|| Server::NativeAvailable()
507
-		) ? true : ['smbclient'];
508
-	}
509
-
510
-	/**
511
-	 * Test a storage for availability
512
-	 *
513
-	 * @return bool
514
-	 */
515
-	public function test() {
516
-		try {
517
-			return parent::test();
518
-		} catch (Exception $e) {
519
-			return false;
520
-		}
521
-	}
522
-
523
-	public function listen($path, callable $callback) {
524
-		$this->notify($path)->listen(function (IChange $change) use ($callback) {
525
-			if ($change instanceof IRenameChange) {
526
-				return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
527
-			} else {
528
-				return $callback($change->getType(), $change->getPath());
529
-			}
530
-		});
531
-	}
532
-
533
-	public function notify($path) {
534
-		$path = '/' . ltrim($path, '/');
535
-		$shareNotifyHandler = $this->share->notify($this->buildPath($path));
536
-		return new SMBNotifyHandler($shareNotifyHandler, $this->root);
537
-	}
58
+    /**
59
+     * @var \Icewind\SMB\Server
60
+     */
61
+    protected $server;
62
+
63
+    /**
64
+     * @var \Icewind\SMB\Share
65
+     */
66
+    protected $share;
67
+
68
+    /**
69
+     * @var string
70
+     */
71
+    protected $root;
72
+
73
+    /**
74
+     * @var \Icewind\SMB\FileInfo[]
75
+     */
76
+    protected $statCache;
77
+
78
+    public function __construct($params) {
79
+        if (isset($params['host']) && isset($params['user']) && isset($params['password']) && isset($params['share'])) {
80
+            if (Server::NativeAvailable()) {
81
+                $this->server = new NativeServer($params['host'], $params['user'], $params['password']);
82
+            } else {
83
+                $this->server = new Server($params['host'], $params['user'], $params['password']);
84
+            }
85
+            $this->share = $this->server->getShare(trim($params['share'], '/'));
86
+
87
+            $this->root = $params['root'] ?? '/';
88
+            $this->root = '/' . ltrim($this->root, '/');
89
+            $this->root = rtrim($this->root, '/') . '/';
90
+        } else {
91
+            throw new \Exception('Invalid configuration');
92
+        }
93
+        $this->statCache = new CappedMemoryCache();
94
+        parent::__construct($params);
95
+    }
96
+
97
+    /**
98
+     * @return string
99
+     */
100
+    public function getId() {
101
+        // FIXME: double slash to keep compatible with the old storage ids,
102
+        // failure to do so will lead to creation of a new storage id and
103
+        // loss of shares from the storage
104
+        return 'smb::' . $this->server->getUser() . '@' . $this->server->getHost() . '//' . $this->share->getName() . '/' . $this->root;
105
+    }
106
+
107
+    /**
108
+     * @param string $path
109
+     * @return string
110
+     */
111
+    protected function buildPath($path) {
112
+        return Filesystem::normalizePath($this->root . '/' . $path, true, false, true);
113
+    }
114
+
115
+    protected function relativePath($fullPath) {
116
+        if ($fullPath === $this->root) {
117
+            return '';
118
+        } else if (substr($fullPath, 0, strlen($this->root)) === $this->root) {
119
+            return substr($fullPath, strlen($this->root));
120
+        } else {
121
+            return null;
122
+        }
123
+    }
124
+
125
+    /**
126
+     * @param string $path
127
+     * @return \Icewind\SMB\IFileInfo
128
+     * @throws StorageNotAvailableException
129
+     */
130
+    protected function getFileInfo($path) {
131
+        try {
132
+            $path = $this->buildPath($path);
133
+            if (!isset($this->statCache[$path])) {
134
+                $this->statCache[$path] = $this->share->stat($path);
135
+            }
136
+            return $this->statCache[$path];
137
+        } catch (ConnectException $e) {
138
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
139
+        }
140
+    }
141
+
142
+    /**
143
+     * @param string $path
144
+     * @return \Icewind\SMB\IFileInfo[]
145
+     * @throws StorageNotAvailableException
146
+     */
147
+    protected function getFolderContents($path) {
148
+        try {
149
+            $path = $this->buildPath($path);
150
+            $files = $this->share->dir($path);
151
+            foreach ($files as $file) {
152
+                $this->statCache[$path . '/' . $file->getName()] = $file;
153
+            }
154
+            return array_filter($files, function (IFileInfo $file) {
155
+                try {
156
+                    return !$file->isHidden();
157
+                } catch (ForbiddenException $e) {
158
+                    return false;
159
+                } catch (NotFoundException $e) {
160
+                    return false;
161
+                }
162
+            });
163
+        } catch (ConnectException $e) {
164
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
165
+        }
166
+    }
167
+
168
+    /**
169
+     * @param \Icewind\SMB\IFileInfo $info
170
+     * @return array
171
+     */
172
+    protected function formatInfo($info) {
173
+        $result = [
174
+            'size' => $info->getSize(),
175
+            'mtime' => $info->getMTime(),
176
+        ];
177
+        if ($info->isDirectory()) {
178
+            $result['type'] = 'dir';
179
+        } else {
180
+            $result['type'] = 'file';
181
+        }
182
+        return $result;
183
+    }
184
+
185
+    /**
186
+     * Rename the files. If the source or the target is the root, the rename won't happen.
187
+     *
188
+     * @param string $source the old name of the path
189
+     * @param string $target the new name of the path
190
+     * @return bool true if the rename is successful, false otherwise
191
+     */
192
+    public function rename($source, $target) {
193
+        if ($this->isRootDir($source) || $this->isRootDir($target)) {
194
+            return false;
195
+        }
196
+
197
+        $absoluteSource = $this->buildPath($source);
198
+        $absoluteTarget = $this->buildPath($target);
199
+        try {
200
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
201
+        } catch (AlreadyExistsException $e) {
202
+            $this->remove($target);
203
+            $result = $this->share->rename($absoluteSource, $absoluteTarget);
204
+        } catch (\Exception $e) {
205
+            \OC::$server->getLogger()->logException($e, ['level' => Util::WARN]);
206
+            return false;
207
+        }
208
+        unset($this->statCache[$absoluteSource], $this->statCache[$absoluteTarget]);
209
+        return $result;
210
+    }
211
+
212
+    public function stat($path) {
213
+        try {
214
+            $result = $this->formatInfo($this->getFileInfo($path));
215
+        } catch (ForbiddenException $e) {
216
+            return false;
217
+        } catch (NotFoundException $e) {
218
+            return false;
219
+        }
220
+        if ($this->remoteIsShare() && $this->isRootDir($path)) {
221
+            $result['mtime'] = $this->shareMTime();
222
+        }
223
+        return $result;
224
+    }
225
+
226
+    /**
227
+     * get the best guess for the modification time of the share
228
+     *
229
+     * @return int
230
+     */
231
+    private function shareMTime() {
232
+        $highestMTime = 0;
233
+        $files = $this->share->dir($this->root);
234
+        foreach ($files as $fileInfo) {
235
+            try {
236
+                if ($fileInfo->getMTime() > $highestMTime) {
237
+                    $highestMTime = $fileInfo->getMTime();
238
+                }
239
+            } catch (NotFoundException $e) {
240
+                // Ignore this, can happen on unavailable DFS shares
241
+            }
242
+        }
243
+        return $highestMTime;
244
+    }
245
+
246
+    /**
247
+     * Check if the path is our root dir (not the smb one)
248
+     *
249
+     * @param string $path the path
250
+     * @return bool
251
+     */
252
+    private function isRootDir($path) {
253
+        return $path === '' || $path === '/' || $path === '.';
254
+    }
255
+
256
+    /**
257
+     * Check if our root points to a smb share
258
+     *
259
+     * @return bool true if our root points to a share false otherwise
260
+     */
261
+    private function remoteIsShare() {
262
+        return $this->share->getName() && (!$this->root || $this->root === '/');
263
+    }
264
+
265
+    /**
266
+     * @param string $path
267
+     * @return bool
268
+     */
269
+    public function unlink($path) {
270
+        if ($this->isRootDir($path)) {
271
+            return false;
272
+        }
273
+
274
+        try {
275
+            if ($this->is_dir($path)) {
276
+                return $this->rmdir($path);
277
+            } else {
278
+                $path = $this->buildPath($path);
279
+                unset($this->statCache[$path]);
280
+                $this->share->del($path);
281
+                return true;
282
+            }
283
+        } catch (NotFoundException $e) {
284
+            return false;
285
+        } catch (ForbiddenException $e) {
286
+            return false;
287
+        } catch (ConnectException $e) {
288
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
289
+        }
290
+    }
291
+
292
+    /**
293
+     * check if a file or folder has been updated since $time
294
+     *
295
+     * @param string $path
296
+     * @param int $time
297
+     * @return bool
298
+     */
299
+    public function hasUpdated($path, $time) {
300
+        if (!$path and $this->root === '/') {
301
+            // mtime doesn't work for shares, but giving the nature of the backend,
302
+            // doing a full update is still just fast enough
303
+            return true;
304
+        } else {
305
+            $actualTime = $this->filemtime($path);
306
+            return $actualTime > $time;
307
+        }
308
+    }
309
+
310
+    /**
311
+     * @param string $path
312
+     * @param string $mode
313
+     * @return resource|false
314
+     */
315
+    public function fopen($path, $mode) {
316
+        $fullPath = $this->buildPath($path);
317
+        try {
318
+            switch ($mode) {
319
+                case 'r':
320
+                case 'rb':
321
+                    if (!$this->file_exists($path)) {
322
+                        return false;
323
+                    }
324
+                    return $this->share->read($fullPath);
325
+                case 'w':
326
+                case 'wb':
327
+                    $source = $this->share->write($fullPath);
328
+                    return CallBackWrapper::wrap($source, null, null, function () use ($fullPath) {
329
+                        unset($this->statCache[$fullPath]);
330
+                    });
331
+                case 'a':
332
+                case 'ab':
333
+                case 'r+':
334
+                case 'w+':
335
+                case 'wb+':
336
+                case 'a+':
337
+                case 'x':
338
+                case 'x+':
339
+                case 'c':
340
+                case 'c+':
341
+                    //emulate these
342
+                    if (strrpos($path, '.') !== false) {
343
+                        $ext = substr($path, strrpos($path, '.'));
344
+                    } else {
345
+                        $ext = '';
346
+                    }
347
+                    if ($this->file_exists($path)) {
348
+                        if (!$this->isUpdatable($path)) {
349
+                            return false;
350
+                        }
351
+                        $tmpFile = $this->getCachedFile($path);
352
+                    } else {
353
+                        if (!$this->isCreatable(dirname($path))) {
354
+                            return false;
355
+                        }
356
+                        $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
357
+                    }
358
+                    $source = fopen($tmpFile, $mode);
359
+                    $share = $this->share;
360
+                    return CallbackWrapper::wrap($source, null, null, function () use ($tmpFile, $fullPath, $share) {
361
+                        unset($this->statCache[$fullPath]);
362
+                        $share->put($tmpFile, $fullPath);
363
+                        unlink($tmpFile);
364
+                    });
365
+            }
366
+            return false;
367
+        } catch (NotFoundException $e) {
368
+            return false;
369
+        } catch (ForbiddenException $e) {
370
+            return false;
371
+        } catch (ConnectException $e) {
372
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
373
+        }
374
+    }
375
+
376
+    public function rmdir($path) {
377
+        if ($this->isRootDir($path)) {
378
+            return false;
379
+        }
380
+
381
+        try {
382
+            $this->statCache = array();
383
+            $content = $this->share->dir($this->buildPath($path));
384
+            foreach ($content as $file) {
385
+                if ($file->isDirectory()) {
386
+                    $this->rmdir($path . '/' . $file->getName());
387
+                } else {
388
+                    $this->share->del($file->getPath());
389
+                }
390
+            }
391
+            $this->share->rmdir($this->buildPath($path));
392
+            return true;
393
+        } catch (NotFoundException $e) {
394
+            return false;
395
+        } catch (ForbiddenException $e) {
396
+            return false;
397
+        } catch (ConnectException $e) {
398
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
399
+        }
400
+    }
401
+
402
+    public function touch($path, $time = null) {
403
+        try {
404
+            if (!$this->file_exists($path)) {
405
+                $fh = $this->share->write($this->buildPath($path));
406
+                fclose($fh);
407
+                return true;
408
+            }
409
+            return false;
410
+        } catch (ConnectException $e) {
411
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
412
+        }
413
+    }
414
+
415
+    public function opendir($path) {
416
+        try {
417
+            $files = $this->getFolderContents($path);
418
+        } catch (NotFoundException $e) {
419
+            return false;
420
+        } catch (ForbiddenException $e) {
421
+            return false;
422
+        }
423
+        $names = array_map(function ($info) {
424
+            /** @var \Icewind\SMB\IFileInfo $info */
425
+            return $info->getName();
426
+        }, $files);
427
+        return IteratorDirectory::wrap($names);
428
+    }
429
+
430
+    public function filetype($path) {
431
+        try {
432
+            return $this->getFileInfo($path)->isDirectory() ? 'dir' : 'file';
433
+        } catch (NotFoundException $e) {
434
+            return false;
435
+        } catch (ForbiddenException $e) {
436
+            return false;
437
+        }
438
+    }
439
+
440
+    public function mkdir($path) {
441
+        $path = $this->buildPath($path);
442
+        try {
443
+            $this->share->mkdir($path);
444
+            return true;
445
+        } catch (ConnectException $e) {
446
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
447
+        } catch (Exception $e) {
448
+            return false;
449
+        }
450
+    }
451
+
452
+    public function file_exists($path) {
453
+        try {
454
+            $this->getFileInfo($path);
455
+            return true;
456
+        } catch (NotFoundException $e) {
457
+            return false;
458
+        } catch (ForbiddenException $e) {
459
+            return false;
460
+        } catch (ConnectException $e) {
461
+            throw new StorageNotAvailableException($e->getMessage(), $e->getCode(), $e);
462
+        }
463
+    }
464
+
465
+    public function isReadable($path) {
466
+        try {
467
+            $info = $this->getFileInfo($path);
468
+            return !$info->isHidden();
469
+        } catch (NotFoundException $e) {
470
+            return false;
471
+        } catch (ForbiddenException $e) {
472
+            return false;
473
+        }
474
+    }
475
+
476
+    public function isUpdatable($path) {
477
+        try {
478
+            $info = $this->getFileInfo($path);
479
+            // following windows behaviour for read-only folders: they can be written into
480
+            // (https://support.microsoft.com/en-us/kb/326549 - "cause" section)
481
+            return !$info->isHidden() && (!$info->isReadOnly() || $this->is_dir($path));
482
+        } catch (NotFoundException $e) {
483
+            return false;
484
+        } catch (ForbiddenException $e) {
485
+            return false;
486
+        }
487
+    }
488
+
489
+    public function isDeletable($path) {
490
+        try {
491
+            $info = $this->getFileInfo($path);
492
+            return !$info->isHidden() && !$info->isReadOnly();
493
+        } catch (NotFoundException $e) {
494
+            return false;
495
+        } catch (ForbiddenException $e) {
496
+            return false;
497
+        }
498
+    }
499
+
500
+    /**
501
+     * check if smbclient is installed
502
+     */
503
+    public static function checkDependencies() {
504
+        return (
505
+            (bool)\OC_Helper::findBinaryPath('smbclient')
506
+            || Server::NativeAvailable()
507
+        ) ? true : ['smbclient'];
508
+    }
509
+
510
+    /**
511
+     * Test a storage for availability
512
+     *
513
+     * @return bool
514
+     */
515
+    public function test() {
516
+        try {
517
+            return parent::test();
518
+        } catch (Exception $e) {
519
+            return false;
520
+        }
521
+    }
522
+
523
+    public function listen($path, callable $callback) {
524
+        $this->notify($path)->listen(function (IChange $change) use ($callback) {
525
+            if ($change instanceof IRenameChange) {
526
+                return $callback($change->getType(), $change->getPath(), $change->getTargetPath());
527
+            } else {
528
+                return $callback($change->getType(), $change->getPath());
529
+            }
530
+        });
531
+    }
532
+
533
+    public function notify($path) {
534
+        $path = '/' . ltrim($path, '/');
535
+        $shareNotifyHandler = $this->share->notify($this->buildPath($path));
536
+        return new SMBNotifyHandler($shareNotifyHandler, $this->root);
537
+    }
538 538
 }
Please login to merge, or discard this patch.