Completed
Pull Request — master (#3590)
by Individual IT
11:38
created
lib/private/Files/Node/File.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@
 block discarded – undo
31 31
 	 * Creates a Folder that represents a non-existing path
32 32
 	 *
33 33
 	 * @param string $path path
34
-	 * @return string non-existing node class
34
+	 * @return NonExistingFile non-existing node class
35 35
 	 */
36 36
 	protected function createNonExistingNode($path) {
37 37
 		return new NonExistingFile($this->root, $this->view, $path);
Please login to merge, or discard this patch.
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -29,113 +29,113 @@
 block discarded – undo
29 29
 use OCP\Files\NotPermittedException;
30 30
 
31 31
 class File extends Node implements \OCP\Files\File {
32
-	/**
33
-	 * Creates a Folder that represents a non-existing path
34
-	 *
35
-	 * @param string $path path
36
-	 * @return string non-existing node class
37
-	 */
38
-	protected function createNonExistingNode($path) {
39
-		return new NonExistingFile($this->root, $this->view, $path);
40
-	}
32
+    /**
33
+     * Creates a Folder that represents a non-existing path
34
+     *
35
+     * @param string $path path
36
+     * @return string non-existing node class
37
+     */
38
+    protected function createNonExistingNode($path) {
39
+        return new NonExistingFile($this->root, $this->view, $path);
40
+    }
41 41
 
42
-	/**
43
-	 * @return string
44
-	 * @throws \OCP\Files\NotPermittedException
45
-	 */
46
-	public function getContent() {
47
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
48
-			/**
49
-			 * @var \OC\Files\Storage\Storage $storage;
50
-			 */
51
-			return $this->view->file_get_contents($this->path);
52
-		} else {
53
-			throw new NotPermittedException();
54
-		}
55
-	}
42
+    /**
43
+     * @return string
44
+     * @throws \OCP\Files\NotPermittedException
45
+     */
46
+    public function getContent() {
47
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_READ)) {
48
+            /**
49
+             * @var \OC\Files\Storage\Storage $storage;
50
+             */
51
+            return $this->view->file_get_contents($this->path);
52
+        } else {
53
+            throw new NotPermittedException();
54
+        }
55
+    }
56 56
 
57
-	/**
58
-	 * @param string $data
59
-	 * @throws \OCP\Files\NotPermittedException
60
-	 */
61
-	public function putContent($data) {
62
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
63
-			$this->sendHooks(array('preWrite'));
64
-			$this->view->file_put_contents($this->path, $data);
65
-			$this->fileInfo = null;
66
-			$this->sendHooks(array('postWrite'));
67
-		} else {
68
-			throw new NotPermittedException();
69
-		}
70
-	}
57
+    /**
58
+     * @param string $data
59
+     * @throws \OCP\Files\NotPermittedException
60
+     */
61
+    public function putContent($data) {
62
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_UPDATE)) {
63
+            $this->sendHooks(array('preWrite'));
64
+            $this->view->file_put_contents($this->path, $data);
65
+            $this->fileInfo = null;
66
+            $this->sendHooks(array('postWrite'));
67
+        } else {
68
+            throw new NotPermittedException();
69
+        }
70
+    }
71 71
 
72
-	/**
73
-	 * @param string $mode
74
-	 * @return resource
75
-	 * @throws \OCP\Files\NotPermittedException
76
-	 */
77
-	public function fopen($mode) {
78
-		$preHooks = array();
79
-		$postHooks = array();
80
-		$requiredPermissions = \OCP\Constants::PERMISSION_READ;
81
-		switch ($mode) {
82
-			case 'r+':
83
-			case 'rb+':
84
-			case 'w+':
85
-			case 'wb+':
86
-			case 'x+':
87
-			case 'xb+':
88
-			case 'a+':
89
-			case 'ab+':
90
-			case 'w':
91
-			case 'wb':
92
-			case 'x':
93
-			case 'xb':
94
-			case 'a':
95
-			case 'ab':
96
-				$preHooks[] = 'preWrite';
97
-				$postHooks[] = 'postWrite';
98
-				$requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
99
-				break;
100
-		}
72
+    /**
73
+     * @param string $mode
74
+     * @return resource
75
+     * @throws \OCP\Files\NotPermittedException
76
+     */
77
+    public function fopen($mode) {
78
+        $preHooks = array();
79
+        $postHooks = array();
80
+        $requiredPermissions = \OCP\Constants::PERMISSION_READ;
81
+        switch ($mode) {
82
+            case 'r+':
83
+            case 'rb+':
84
+            case 'w+':
85
+            case 'wb+':
86
+            case 'x+':
87
+            case 'xb+':
88
+            case 'a+':
89
+            case 'ab+':
90
+            case 'w':
91
+            case 'wb':
92
+            case 'x':
93
+            case 'xb':
94
+            case 'a':
95
+            case 'ab':
96
+                $preHooks[] = 'preWrite';
97
+                $postHooks[] = 'postWrite';
98
+                $requiredPermissions |= \OCP\Constants::PERMISSION_UPDATE;
99
+                break;
100
+        }
101 101
 
102
-		if ($this->checkPermissions($requiredPermissions)) {
103
-			$this->sendHooks($preHooks);
104
-			$result = $this->view->fopen($this->path, $mode);
105
-			$this->sendHooks($postHooks);
106
-			return $result;
107
-		} else {
108
-			throw new NotPermittedException();
109
-		}
110
-	}
102
+        if ($this->checkPermissions($requiredPermissions)) {
103
+            $this->sendHooks($preHooks);
104
+            $result = $this->view->fopen($this->path, $mode);
105
+            $this->sendHooks($postHooks);
106
+            return $result;
107
+        } else {
108
+            throw new NotPermittedException();
109
+        }
110
+    }
111 111
 
112
-	public function delete() {
113
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
114
-			$this->sendHooks(array('preDelete'));
115
-			$fileInfo = $this->getFileInfo();
116
-			$this->view->unlink($this->path);
117
-			$nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
118
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
119
-			$this->exists = false;
120
-			$this->fileInfo = null;
121
-		} else {
122
-			throw new NotPermittedException();
123
-		}
124
-	}
112
+    public function delete() {
113
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
114
+            $this->sendHooks(array('preDelete'));
115
+            $fileInfo = $this->getFileInfo();
116
+            $this->view->unlink($this->path);
117
+            $nonExisting = new NonExistingFile($this->root, $this->view, $this->path, $fileInfo);
118
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
119
+            $this->exists = false;
120
+            $this->fileInfo = null;
121
+        } else {
122
+            throw new NotPermittedException();
123
+        }
124
+    }
125 125
 
126
-	/**
127
-	 * @param string $type
128
-	 * @param bool $raw
129
-	 * @return string
130
-	 */
131
-	public function hash($type, $raw = false) {
132
-		return $this->view->hash($type, $this->path, $raw);
133
-	}
126
+    /**
127
+     * @param string $type
128
+     * @param bool $raw
129
+     * @return string
130
+     */
131
+    public function hash($type, $raw = false) {
132
+        return $this->view->hash($type, $this->path, $raw);
133
+    }
134 134
 
135
-	/**
136
-	 * @inheritdoc
137
-	 */
138
-	public function getChecksum() {
139
-		return $this->getFileInfo()->getChecksum();
140
-	}
135
+    /**
136
+     * @inheritdoc
137
+     */
138
+    public function getChecksum() {
139
+        return $this->getFileInfo()->getChecksum();
140
+    }
141 141
 }
Please login to merge, or discard this patch.
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   +386 added lines, -386 removed lines patch added patch discarded remove patch
@@ -35,390 +35,390 @@
 block discarded – undo
35 35
 use OCP\Files\NotPermittedException;
36 36
 
37 37
 class Folder extends Node implements \OCP\Files\Folder {
38
-	/**
39
-	 * Creates a Folder that represents a non-existing path
40
-	 *
41
-	 * @param string $path path
42
-	 * @return string non-existing node class
43
-	 */
44
-	protected function createNonExistingNode($path) {
45
-		return new NonExistingFolder($this->root, $this->view, $path);
46
-	}
47
-
48
-	/**
49
-	 * @param string $path path relative to the folder
50
-	 * @return string
51
-	 * @throws \OCP\Files\NotPermittedException
52
-	 */
53
-	public function getFullPath($path) {
54
-		if (!$this->isValidPath($path)) {
55
-			throw new NotPermittedException('Invalid path');
56
-		}
57
-		return $this->path . $this->normalizePath($path);
58
-	}
59
-
60
-	/**
61
-	 * @param string $path
62
-	 * @return string
63
-	 */
64
-	public function getRelativePath($path) {
65
-		if ($this->path === '' or $this->path === '/') {
66
-			return $this->normalizePath($path);
67
-		}
68
-		if ($path === $this->path) {
69
-			return '/';
70
-		} else if (strpos($path, $this->path . '/') !== 0) {
71
-			return null;
72
-		} else {
73
-			$path = substr($path, strlen($this->path));
74
-			return $this->normalizePath($path);
75
-		}
76
-	}
77
-
78
-	/**
79
-	 * check if a node is a (grand-)child of the folder
80
-	 *
81
-	 * @param \OC\Files\Node\Node $node
82
-	 * @return bool
83
-	 */
84
-	public function isSubNode($node) {
85
-		return strpos($node->getPath(), $this->path . '/') === 0;
86
-	}
87
-
88
-	/**
89
-	 * get the content of this directory
90
-	 *
91
-	 * @throws \OCP\Files\NotFoundException
92
-	 * @return Node[]
93
-	 */
94
-	public function getDirectoryListing() {
95
-		$folderContent = $this->view->getDirectoryContent($this->path);
96
-
97
-		return array_map(function (FileInfo $info) {
98
-			if ($info->getMimetype() === 'httpd/unix-directory') {
99
-				return new Folder($this->root, $this->view, $info->getPath(), $info);
100
-			} else {
101
-				return new File($this->root, $this->view, $info->getPath(), $info);
102
-			}
103
-		}, $folderContent);
104
-	}
105
-
106
-	/**
107
-	 * @param string $path
108
-	 * @param FileInfo $info
109
-	 * @return File|Folder
110
-	 */
111
-	protected function createNode($path, FileInfo $info = null) {
112
-		if (is_null($info)) {
113
-			$isDir = $this->view->is_dir($path);
114
-		} else {
115
-			$isDir = $info->getType() === FileInfo::TYPE_FOLDER;
116
-		}
117
-		if ($isDir) {
118
-			return new Folder($this->root, $this->view, $path, $info);
119
-		} else {
120
-			return new File($this->root, $this->view, $path, $info);
121
-		}
122
-	}
123
-
124
-	/**
125
-	 * Get the node at $path
126
-	 *
127
-	 * @param string $path
128
-	 * @return \OC\Files\Node\Node
129
-	 * @throws \OCP\Files\NotFoundException
130
-	 */
131
-	public function get($path) {
132
-		return $this->root->get($this->getFullPath($path));
133
-	}
134
-
135
-	/**
136
-	 * @param string $path
137
-	 * @return bool
138
-	 */
139
-	public function nodeExists($path) {
140
-		try {
141
-			$this->get($path);
142
-			return true;
143
-		} catch (NotFoundException $e) {
144
-			return false;
145
-		}
146
-	}
147
-
148
-	/**
149
-	 * @param string $path
150
-	 * @return \OC\Files\Node\Folder
151
-	 * @throws \OCP\Files\NotPermittedException
152
-	 */
153
-	public function newFolder($path) {
154
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
155
-			$fullPath = $this->getFullPath($path);
156
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
157
-			$this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
158
-			$this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
159
-			$this->view->mkdir($fullPath);
160
-			$node = new Folder($this->root, $this->view, $fullPath);
161
-			$this->root->emit('\OC\Files', 'postWrite', array($node));
162
-			$this->root->emit('\OC\Files', 'postCreate', array($node));
163
-			return $node;
164
-		} else {
165
-			throw new NotPermittedException('No create permission for folder');
166
-		}
167
-	}
168
-
169
-	/**
170
-	 * @param string $path
171
-	 * @return \OC\Files\Node\File
172
-	 * @throws \OCP\Files\NotPermittedException
173
-	 */
174
-	public function newFile($path) {
175
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
176
-			$fullPath = $this->getFullPath($path);
177
-			$nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
178
-			$this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
179
-			$this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
180
-			$this->view->touch($fullPath);
181
-			$node = new File($this->root, $this->view, $fullPath);
182
-			$this->root->emit('\OC\Files', 'postWrite', array($node));
183
-			$this->root->emit('\OC\Files', 'postCreate', array($node));
184
-			return $node;
185
-		} else {
186
-			throw new NotPermittedException('No create permission for path');
187
-		}
188
-	}
189
-
190
-	/**
191
-	 * search for files with the name matching $query
192
-	 *
193
-	 * @param string $query
194
-	 * @return \OC\Files\Node\Node[]
195
-	 */
196
-	public function search($query) {
197
-		return $this->searchCommon('search', array('%' . $query . '%'));
198
-	}
199
-
200
-	/**
201
-	 * search for files by mimetype
202
-	 *
203
-	 * @param string $mimetype
204
-	 * @return Node[]
205
-	 */
206
-	public function searchByMime($mimetype) {
207
-		return $this->searchCommon('searchByMime', array($mimetype));
208
-	}
209
-
210
-	/**
211
-	 * search for files by tag
212
-	 *
213
-	 * @param string|int $tag name or tag id
214
-	 * @param string $userId owner of the tags
215
-	 * @return Node[]
216
-	 */
217
-	public function searchByTag($tag, $userId) {
218
-		return $this->searchCommon('searchByTag', array($tag, $userId));
219
-	}
220
-
221
-	/**
222
-	 * @param string $method cache method
223
-	 * @param array $args call args
224
-	 * @return \OC\Files\Node\Node[]
225
-	 */
226
-	private function searchCommon($method, $args) {
227
-		$files = array();
228
-		$rootLength = strlen($this->path);
229
-		$mount = $this->root->getMount($this->path);
230
-		$storage = $mount->getStorage();
231
-		$internalPath = $mount->getInternalPath($this->path);
232
-		$internalPath = rtrim($internalPath, '/');
233
-		if ($internalPath !== '') {
234
-			$internalPath = $internalPath . '/';
235
-		}
236
-		$internalRootLength = strlen($internalPath);
237
-
238
-		$cache = $storage->getCache('');
239
-
240
-		$results = call_user_func_array(array($cache, $method), $args);
241
-		foreach ($results as $result) {
242
-			if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
243
-				$result['internalPath'] = $result['path'];
244
-				$result['path'] = substr($result['path'], $internalRootLength);
245
-				$result['storage'] = $storage;
246
-				$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
247
-			}
248
-		}
249
-
250
-		$mounts = $this->root->getMountsIn($this->path);
251
-		foreach ($mounts as $mount) {
252
-			$storage = $mount->getStorage();
253
-			if ($storage) {
254
-				$cache = $storage->getCache('');
255
-
256
-				$relativeMountPoint = substr($mount->getMountPoint(), $rootLength);
257
-				$results = call_user_func_array(array($cache, $method), $args);
258
-				foreach ($results as $result) {
259
-					$result['internalPath'] = $result['path'];
260
-					$result['path'] = $relativeMountPoint . $result['path'];
261
-					$result['storage'] = $storage;
262
-					$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
263
-				}
264
-			}
265
-		}
266
-
267
-		return array_map(function (FileInfo $file) {
268
-			return $this->createNode($file->getPath(), $file);
269
-		}, $files);
270
-	}
271
-
272
-	/**
273
-	 * @param int $id
274
-	 * @return \OC\Files\Node\Node[]
275
-	 */
276
-	public function getById($id) {
277
-		$mountCache = $this->root->getUserMountCache();
278
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id);
279
-		$mounts = $this->root->getMountsIn($this->path);
280
-		$mounts[] = $this->root->getMount($this->path);
281
-		/** @var IMountPoint[] $folderMounts */
282
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
283
-			return $mountPoint->getMountPoint();
284
-		}, $mounts), $mounts);
285
-
286
-		/** @var ICachedMountInfo[] $mountsContainingFile */
287
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
288
-			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
289
-		}));
290
-
291
-		if (count($mountsContainingFile) === 0) {
292
-			return [];
293
-		}
294
-
295
-		// we only need to get the cache info once, since all mounts we found point to the same storage
296
-
297
-		$mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()];
298
-		$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
299
-		if (!$cacheEntry) {
300
-			return [];
301
-		}
302
-		// cache jails will hide the "true" internal path
303
-		$internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
304
-
305
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
306
-			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
307
-			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
308
-			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
309
-			$absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
310
-			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
311
-				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
312
-				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
313
-			));
314
-		}, $mountsContainingFile);
315
-
316
-		return array_filter($nodes, function (Node $node) {
317
-			return $this->getRelativePath($node->getPath());
318
-		});
319
-	}
320
-
321
-	public function getFreeSpace() {
322
-		return $this->view->free_space($this->path);
323
-	}
324
-
325
-	public function delete() {
326
-		if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
327
-			$this->sendHooks(array('preDelete'));
328
-			$fileInfo = $this->getFileInfo();
329
-			$this->view->rmdir($this->path);
330
-			$nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
331
-			$this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
332
-			$this->exists = false;
333
-		} else {
334
-			throw new NotPermittedException('No delete permission for path');
335
-		}
336
-	}
337
-
338
-	/**
339
-	 * Add a suffix to the name in case the file exists
340
-	 *
341
-	 * @param string $name
342
-	 * @return string
343
-	 * @throws NotPermittedException
344
-	 */
345
-	public function getNonExistingName($name) {
346
-		$uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
347
-		return trim($this->getRelativePath($uniqueName), '/');
348
-	}
349
-
350
-	/**
351
-	 * @param int $limit
352
-	 * @param int $offset
353
-	 * @return \OCP\Files\Node[]
354
-	 */
355
-	public function getRecent($limit, $offset = 0) {
356
-		$mimetypeLoader = \OC::$server->getMimeTypeLoader();
357
-		$mounts = $this->root->getMountsIn($this->path);
358
-		$mounts[] = $this->getMountPoint();
359
-
360
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
361
-			return $mount->getStorage();
362
-		});
363
-		$storageIds = array_map(function (IMountPoint $mount) {
364
-			return $mount->getStorage()->getCache()->getNumericStorageId();
365
-		}, $mounts);
366
-		/** @var IMountPoint[] $mountMap */
367
-		$mountMap = array_combine($storageIds, $mounts);
368
-		$folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
369
-
370
-		//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)
371
-
372
-		$builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
373
-		$query = $builder
374
-			->select('f.*')
375
-			->from('filecache', 'f')
376
-			->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
377
-			->andWhere($builder->expr()->orX(
378
-			// handle non empty folders separate
379
-				$builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
380
-				$builder->expr()->eq('f.size', new Literal(0))
381
-			))
382
-			->orderBy('f.mtime', 'DESC')
383
-			->setMaxResults($limit)
384
-			->setFirstResult($offset);
385
-
386
-		$result = $query->execute()->fetchAll();
387
-
388
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
389
-			$mount = $mountMap[$entry['storage']];
390
-			$entry['internalPath'] = $entry['path'];
391
-			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
392
-			$entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
393
-			$path = $this->getAbsolutePath($mount, $entry['path']);
394
-			if (is_null($path)) {
395
-				return null;
396
-			}
397
-			$fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
398
-			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
399
-		}, $result));
400
-
401
-		return array_values(array_filter($files, function (Node $node) {
402
-			$relative = $this->getRelativePath($node->getPath());
403
-			return $relative !== null && $relative !== '/';
404
-		}));
405
-	}
406
-
407
-	private function getAbsolutePath(IMountPoint $mount, $path) {
408
-		$storage = $mount->getStorage();
409
-		if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
410
-			/** @var \OC\Files\Storage\Wrapper\Jail $storage */
411
-			$jailRoot = $storage->getSourcePath('');
412
-			$rootLength = strlen($jailRoot) + 1;
413
-			if ($path === $jailRoot) {
414
-				return $mount->getMountPoint();
415
-			} else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
416
-				return $mount->getMountPoint() . substr($path, $rootLength);
417
-			} else {
418
-				return null;
419
-			}
420
-		} else {
421
-			return $mount->getMountPoint() . $path;
422
-		}
423
-	}
38
+    /**
39
+     * Creates a Folder that represents a non-existing path
40
+     *
41
+     * @param string $path path
42
+     * @return string non-existing node class
43
+     */
44
+    protected function createNonExistingNode($path) {
45
+        return new NonExistingFolder($this->root, $this->view, $path);
46
+    }
47
+
48
+    /**
49
+     * @param string $path path relative to the folder
50
+     * @return string
51
+     * @throws \OCP\Files\NotPermittedException
52
+     */
53
+    public function getFullPath($path) {
54
+        if (!$this->isValidPath($path)) {
55
+            throw new NotPermittedException('Invalid path');
56
+        }
57
+        return $this->path . $this->normalizePath($path);
58
+    }
59
+
60
+    /**
61
+     * @param string $path
62
+     * @return string
63
+     */
64
+    public function getRelativePath($path) {
65
+        if ($this->path === '' or $this->path === '/') {
66
+            return $this->normalizePath($path);
67
+        }
68
+        if ($path === $this->path) {
69
+            return '/';
70
+        } else if (strpos($path, $this->path . '/') !== 0) {
71
+            return null;
72
+        } else {
73
+            $path = substr($path, strlen($this->path));
74
+            return $this->normalizePath($path);
75
+        }
76
+    }
77
+
78
+    /**
79
+     * check if a node is a (grand-)child of the folder
80
+     *
81
+     * @param \OC\Files\Node\Node $node
82
+     * @return bool
83
+     */
84
+    public function isSubNode($node) {
85
+        return strpos($node->getPath(), $this->path . '/') === 0;
86
+    }
87
+
88
+    /**
89
+     * get the content of this directory
90
+     *
91
+     * @throws \OCP\Files\NotFoundException
92
+     * @return Node[]
93
+     */
94
+    public function getDirectoryListing() {
95
+        $folderContent = $this->view->getDirectoryContent($this->path);
96
+
97
+        return array_map(function (FileInfo $info) {
98
+            if ($info->getMimetype() === 'httpd/unix-directory') {
99
+                return new Folder($this->root, $this->view, $info->getPath(), $info);
100
+            } else {
101
+                return new File($this->root, $this->view, $info->getPath(), $info);
102
+            }
103
+        }, $folderContent);
104
+    }
105
+
106
+    /**
107
+     * @param string $path
108
+     * @param FileInfo $info
109
+     * @return File|Folder
110
+     */
111
+    protected function createNode($path, FileInfo $info = null) {
112
+        if (is_null($info)) {
113
+            $isDir = $this->view->is_dir($path);
114
+        } else {
115
+            $isDir = $info->getType() === FileInfo::TYPE_FOLDER;
116
+        }
117
+        if ($isDir) {
118
+            return new Folder($this->root, $this->view, $path, $info);
119
+        } else {
120
+            return new File($this->root, $this->view, $path, $info);
121
+        }
122
+    }
123
+
124
+    /**
125
+     * Get the node at $path
126
+     *
127
+     * @param string $path
128
+     * @return \OC\Files\Node\Node
129
+     * @throws \OCP\Files\NotFoundException
130
+     */
131
+    public function get($path) {
132
+        return $this->root->get($this->getFullPath($path));
133
+    }
134
+
135
+    /**
136
+     * @param string $path
137
+     * @return bool
138
+     */
139
+    public function nodeExists($path) {
140
+        try {
141
+            $this->get($path);
142
+            return true;
143
+        } catch (NotFoundException $e) {
144
+            return false;
145
+        }
146
+    }
147
+
148
+    /**
149
+     * @param string $path
150
+     * @return \OC\Files\Node\Folder
151
+     * @throws \OCP\Files\NotPermittedException
152
+     */
153
+    public function newFolder($path) {
154
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
155
+            $fullPath = $this->getFullPath($path);
156
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath);
157
+            $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
158
+            $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
159
+            $this->view->mkdir($fullPath);
160
+            $node = new Folder($this->root, $this->view, $fullPath);
161
+            $this->root->emit('\OC\Files', 'postWrite', array($node));
162
+            $this->root->emit('\OC\Files', 'postCreate', array($node));
163
+            return $node;
164
+        } else {
165
+            throw new NotPermittedException('No create permission for folder');
166
+        }
167
+    }
168
+
169
+    /**
170
+     * @param string $path
171
+     * @return \OC\Files\Node\File
172
+     * @throws \OCP\Files\NotPermittedException
173
+     */
174
+    public function newFile($path) {
175
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) {
176
+            $fullPath = $this->getFullPath($path);
177
+            $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath);
178
+            $this->root->emit('\OC\Files', 'preWrite', array($nonExisting));
179
+            $this->root->emit('\OC\Files', 'preCreate', array($nonExisting));
180
+            $this->view->touch($fullPath);
181
+            $node = new File($this->root, $this->view, $fullPath);
182
+            $this->root->emit('\OC\Files', 'postWrite', array($node));
183
+            $this->root->emit('\OC\Files', 'postCreate', array($node));
184
+            return $node;
185
+        } else {
186
+            throw new NotPermittedException('No create permission for path');
187
+        }
188
+    }
189
+
190
+    /**
191
+     * search for files with the name matching $query
192
+     *
193
+     * @param string $query
194
+     * @return \OC\Files\Node\Node[]
195
+     */
196
+    public function search($query) {
197
+        return $this->searchCommon('search', array('%' . $query . '%'));
198
+    }
199
+
200
+    /**
201
+     * search for files by mimetype
202
+     *
203
+     * @param string $mimetype
204
+     * @return Node[]
205
+     */
206
+    public function searchByMime($mimetype) {
207
+        return $this->searchCommon('searchByMime', array($mimetype));
208
+    }
209
+
210
+    /**
211
+     * search for files by tag
212
+     *
213
+     * @param string|int $tag name or tag id
214
+     * @param string $userId owner of the tags
215
+     * @return Node[]
216
+     */
217
+    public function searchByTag($tag, $userId) {
218
+        return $this->searchCommon('searchByTag', array($tag, $userId));
219
+    }
220
+
221
+    /**
222
+     * @param string $method cache method
223
+     * @param array $args call args
224
+     * @return \OC\Files\Node\Node[]
225
+     */
226
+    private function searchCommon($method, $args) {
227
+        $files = array();
228
+        $rootLength = strlen($this->path);
229
+        $mount = $this->root->getMount($this->path);
230
+        $storage = $mount->getStorage();
231
+        $internalPath = $mount->getInternalPath($this->path);
232
+        $internalPath = rtrim($internalPath, '/');
233
+        if ($internalPath !== '') {
234
+            $internalPath = $internalPath . '/';
235
+        }
236
+        $internalRootLength = strlen($internalPath);
237
+
238
+        $cache = $storage->getCache('');
239
+
240
+        $results = call_user_func_array(array($cache, $method), $args);
241
+        foreach ($results as $result) {
242
+            if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) {
243
+                $result['internalPath'] = $result['path'];
244
+                $result['path'] = substr($result['path'], $internalRootLength);
245
+                $result['storage'] = $storage;
246
+                $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
247
+            }
248
+        }
249
+
250
+        $mounts = $this->root->getMountsIn($this->path);
251
+        foreach ($mounts as $mount) {
252
+            $storage = $mount->getStorage();
253
+            if ($storage) {
254
+                $cache = $storage->getCache('');
255
+
256
+                $relativeMountPoint = substr($mount->getMountPoint(), $rootLength);
257
+                $results = call_user_func_array(array($cache, $method), $args);
258
+                foreach ($results as $result) {
259
+                    $result['internalPath'] = $result['path'];
260
+                    $result['path'] = $relativeMountPoint . $result['path'];
261
+                    $result['storage'] = $storage;
262
+                    $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
263
+                }
264
+            }
265
+        }
266
+
267
+        return array_map(function (FileInfo $file) {
268
+            return $this->createNode($file->getPath(), $file);
269
+        }, $files);
270
+    }
271
+
272
+    /**
273
+     * @param int $id
274
+     * @return \OC\Files\Node\Node[]
275
+     */
276
+    public function getById($id) {
277
+        $mountCache = $this->root->getUserMountCache();
278
+        $mountsContainingFile = $mountCache->getMountsForFileId((int)$id);
279
+        $mounts = $this->root->getMountsIn($this->path);
280
+        $mounts[] = $this->root->getMount($this->path);
281
+        /** @var IMountPoint[] $folderMounts */
282
+        $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
283
+            return $mountPoint->getMountPoint();
284
+        }, $mounts), $mounts);
285
+
286
+        /** @var ICachedMountInfo[] $mountsContainingFile */
287
+        $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
288
+            return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
289
+        }));
290
+
291
+        if (count($mountsContainingFile) === 0) {
292
+            return [];
293
+        }
294
+
295
+        // we only need to get the cache info once, since all mounts we found point to the same storage
296
+
297
+        $mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()];
298
+        $cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
299
+        if (!$cacheEntry) {
300
+            return [];
301
+        }
302
+        // cache jails will hide the "true" internal path
303
+        $internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
304
+
305
+        $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
306
+            $mount = $folderMounts[$cachedMountInfo->getMountPoint()];
307
+            $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
308
+            $pathRelativeToMount = ltrim($pathRelativeToMount, '/');
309
+            $absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
310
+            return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
311
+                $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
312
+                \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
313
+            ));
314
+        }, $mountsContainingFile);
315
+
316
+        return array_filter($nodes, function (Node $node) {
317
+            return $this->getRelativePath($node->getPath());
318
+        });
319
+    }
320
+
321
+    public function getFreeSpace() {
322
+        return $this->view->free_space($this->path);
323
+    }
324
+
325
+    public function delete() {
326
+        if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) {
327
+            $this->sendHooks(array('preDelete'));
328
+            $fileInfo = $this->getFileInfo();
329
+            $this->view->rmdir($this->path);
330
+            $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo);
331
+            $this->root->emit('\OC\Files', 'postDelete', array($nonExisting));
332
+            $this->exists = false;
333
+        } else {
334
+            throw new NotPermittedException('No delete permission for path');
335
+        }
336
+    }
337
+
338
+    /**
339
+     * Add a suffix to the name in case the file exists
340
+     *
341
+     * @param string $name
342
+     * @return string
343
+     * @throws NotPermittedException
344
+     */
345
+    public function getNonExistingName($name) {
346
+        $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view);
347
+        return trim($this->getRelativePath($uniqueName), '/');
348
+    }
349
+
350
+    /**
351
+     * @param int $limit
352
+     * @param int $offset
353
+     * @return \OCP\Files\Node[]
354
+     */
355
+    public function getRecent($limit, $offset = 0) {
356
+        $mimetypeLoader = \OC::$server->getMimeTypeLoader();
357
+        $mounts = $this->root->getMountsIn($this->path);
358
+        $mounts[] = $this->getMountPoint();
359
+
360
+        $mounts = array_filter($mounts, function (IMountPoint $mount) {
361
+            return $mount->getStorage();
362
+        });
363
+        $storageIds = array_map(function (IMountPoint $mount) {
364
+            return $mount->getStorage()->getCache()->getNumericStorageId();
365
+        }, $mounts);
366
+        /** @var IMountPoint[] $mountMap */
367
+        $mountMap = array_combine($storageIds, $mounts);
368
+        $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER);
369
+
370
+        //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)
371
+
372
+        $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
373
+        $query = $builder
374
+            ->select('f.*')
375
+            ->from('filecache', 'f')
376
+            ->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY)))
377
+            ->andWhere($builder->expr()->orX(
378
+            // handle non empty folders separate
379
+                $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)),
380
+                $builder->expr()->eq('f.size', new Literal(0))
381
+            ))
382
+            ->orderBy('f.mtime', 'DESC')
383
+            ->setMaxResults($limit)
384
+            ->setFirstResult($offset);
385
+
386
+        $result = $query->execute()->fetchAll();
387
+
388
+        $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
389
+            $mount = $mountMap[$entry['storage']];
390
+            $entry['internalPath'] = $entry['path'];
391
+            $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
392
+            $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']);
393
+            $path = $this->getAbsolutePath($mount, $entry['path']);
394
+            if (is_null($path)) {
395
+                return null;
396
+            }
397
+            $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount);
398
+            return $this->root->createNode($fileInfo->getPath(), $fileInfo);
399
+        }, $result));
400
+
401
+        return array_values(array_filter($files, function (Node $node) {
402
+            $relative = $this->getRelativePath($node->getPath());
403
+            return $relative !== null && $relative !== '/';
404
+        }));
405
+    }
406
+
407
+    private function getAbsolutePath(IMountPoint $mount, $path) {
408
+        $storage = $mount->getStorage();
409
+        if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) {
410
+            /** @var \OC\Files\Storage\Wrapper\Jail $storage */
411
+            $jailRoot = $storage->getSourcePath('');
412
+            $rootLength = strlen($jailRoot) + 1;
413
+            if ($path === $jailRoot) {
414
+                return $mount->getMountPoint();
415
+            } else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
416
+                return $mount->getMountPoint() . substr($path, $rootLength);
417
+            } else {
418
+                return null;
419
+            }
420
+        } else {
421
+            return $mount->getMountPoint() . $path;
422
+        }
423
+    }
424 424
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 		if (!$this->isValidPath($path)) {
55 55
 			throw new NotPermittedException('Invalid path');
56 56
 		}
57
-		return $this->path . $this->normalizePath($path);
57
+		return $this->path.$this->normalizePath($path);
58 58
 	}
59 59
 
60 60
 	/**
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 		}
68 68
 		if ($path === $this->path) {
69 69
 			return '/';
70
-		} else if (strpos($path, $this->path . '/') !== 0) {
70
+		} else if (strpos($path, $this->path.'/') !== 0) {
71 71
 			return null;
72 72
 		} else {
73 73
 			$path = substr($path, strlen($this->path));
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 	 * @return bool
83 83
 	 */
84 84
 	public function isSubNode($node) {
85
-		return strpos($node->getPath(), $this->path . '/') === 0;
85
+		return strpos($node->getPath(), $this->path.'/') === 0;
86 86
 	}
87 87
 
88 88
 	/**
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	public function getDirectoryListing() {
95 95
 		$folderContent = $this->view->getDirectoryContent($this->path);
96 96
 
97
-		return array_map(function (FileInfo $info) {
97
+		return array_map(function(FileInfo $info) {
98 98
 			if ($info->getMimetype() === 'httpd/unix-directory') {
99 99
 				return new Folder($this->root, $this->view, $info->getPath(), $info);
100 100
 			} else {
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 	 * @return \OC\Files\Node\Node[]
195 195
 	 */
196 196
 	public function search($query) {
197
-		return $this->searchCommon('search', array('%' . $query . '%'));
197
+		return $this->searchCommon('search', array('%'.$query.'%'));
198 198
 	}
199 199
 
200 200
 	/**
@@ -231,7 +231,7 @@  discard block
 block discarded – undo
231 231
 		$internalPath = $mount->getInternalPath($this->path);
232 232
 		$internalPath = rtrim($internalPath, '/');
233 233
 		if ($internalPath !== '') {
234
-			$internalPath = $internalPath . '/';
234
+			$internalPath = $internalPath.'/';
235 235
 		}
236 236
 		$internalRootLength = strlen($internalPath);
237 237
 
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
 				$result['internalPath'] = $result['path'];
244 244
 				$result['path'] = substr($result['path'], $internalRootLength);
245 245
 				$result['storage'] = $storage;
246
-				$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
246
+				$files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount);
247 247
 			}
248 248
 		}
249 249
 
@@ -257,14 +257,14 @@  discard block
 block discarded – undo
257 257
 				$results = call_user_func_array(array($cache, $method), $args);
258 258
 				foreach ($results as $result) {
259 259
 					$result['internalPath'] = $result['path'];
260
-					$result['path'] = $relativeMountPoint . $result['path'];
260
+					$result['path'] = $relativeMountPoint.$result['path'];
261 261
 					$result['storage'] = $storage;
262
-					$files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount);
262
+					$files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount);
263 263
 				}
264 264
 			}
265 265
 		}
266 266
 
267
-		return array_map(function (FileInfo $file) {
267
+		return array_map(function(FileInfo $file) {
268 268
 			return $this->createNode($file->getPath(), $file);
269 269
 		}, $files);
270 270
 	}
@@ -275,16 +275,16 @@  discard block
 block discarded – undo
275 275
 	 */
276 276
 	public function getById($id) {
277 277
 		$mountCache = $this->root->getUserMountCache();
278
-		$mountsContainingFile = $mountCache->getMountsForFileId((int)$id);
278
+		$mountsContainingFile = $mountCache->getMountsForFileId((int) $id);
279 279
 		$mounts = $this->root->getMountsIn($this->path);
280 280
 		$mounts[] = $this->root->getMount($this->path);
281 281
 		/** @var IMountPoint[] $folderMounts */
282
-		$folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) {
282
+		$folderMounts = array_combine(array_map(function(IMountPoint $mountPoint) {
283 283
 			return $mountPoint->getMountPoint();
284 284
 		}, $mounts), $mounts);
285 285
 
286 286
 		/** @var ICachedMountInfo[] $mountsContainingFile */
287
-		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
287
+		$mountsContainingFile = array_values(array_filter($mountsContainingFile, function(ICachedMountInfo $cachedMountInfo) use ($folderMounts) {
288 288
 			return isset($folderMounts[$cachedMountInfo->getMountPoint()]);
289 289
 		}));
290 290
 
@@ -295,25 +295,25 @@  discard block
 block discarded – undo
295 295
 		// we only need to get the cache info once, since all mounts we found point to the same storage
296 296
 
297 297
 		$mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()];
298
-		$cacheEntry = $mount->getStorage()->getCache()->get((int)$id);
298
+		$cacheEntry = $mount->getStorage()->getCache()->get((int) $id);
299 299
 		if (!$cacheEntry) {
300 300
 			return [];
301 301
 		}
302 302
 		// cache jails will hide the "true" internal path
303
-		$internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/');
303
+		$internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath().'/'.$cacheEntry->getPath(), '/');
304 304
 
305
-		$nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
305
+		$nodes = array_map(function(ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) {
306 306
 			$mount = $folderMounts[$cachedMountInfo->getMountPoint()];
307 307
 			$pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath()));
308 308
 			$pathRelativeToMount = ltrim($pathRelativeToMount, '/');
309
-			$absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount;
309
+			$absolutePath = $cachedMountInfo->getMountPoint().$pathRelativeToMount;
310 310
 			return $this->root->createNode($absolutePath, new \OC\Files\FileInfo(
311 311
 				$absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount,
312 312
 				\OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount))
313 313
 			));
314 314
 		}, $mountsContainingFile);
315 315
 
316
-		return array_filter($nodes, function (Node $node) {
316
+		return array_filter($nodes, function(Node $node) {
317 317
 			return $this->getRelativePath($node->getPath());
318 318
 		});
319 319
 	}
@@ -357,10 +357,10 @@  discard block
 block discarded – undo
357 357
 		$mounts = $this->root->getMountsIn($this->path);
358 358
 		$mounts[] = $this->getMountPoint();
359 359
 
360
-		$mounts = array_filter($mounts, function (IMountPoint $mount) {
360
+		$mounts = array_filter($mounts, function(IMountPoint $mount) {
361 361
 			return $mount->getStorage();
362 362
 		});
363
-		$storageIds = array_map(function (IMountPoint $mount) {
363
+		$storageIds = array_map(function(IMountPoint $mount) {
364 364
 			return $mount->getStorage()->getCache()->getNumericStorageId();
365 365
 		}, $mounts);
366 366
 		/** @var IMountPoint[] $mountMap */
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 
386 386
 		$result = $query->execute()->fetchAll();
387 387
 
388
-		$files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) {
388
+		$files = array_filter(array_map(function(array $entry) use ($mountMap, $mimetypeLoader) {
389 389
 			$mount = $mountMap[$entry['storage']];
390 390
 			$entry['internalPath'] = $entry['path'];
391 391
 			$entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']);
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 			return $this->root->createNode($fileInfo->getPath(), $fileInfo);
399 399
 		}, $result));
400 400
 
401
-		return array_values(array_filter($files, function (Node $node) {
401
+		return array_values(array_filter($files, function(Node $node) {
402 402
 			$relative = $this->getRelativePath($node->getPath());
403 403
 			return $relative !== null && $relative !== '/';
404 404
 		}));
@@ -412,13 +412,13 @@  discard block
 block discarded – undo
412 412
 			$rootLength = strlen($jailRoot) + 1;
413 413
 			if ($path === $jailRoot) {
414 414
 				return $mount->getMountPoint();
415
-			} else if (substr($path, 0, $rootLength) === $jailRoot . '/') {
416
-				return $mount->getMountPoint() . substr($path, $rootLength);
415
+			} else if (substr($path, 0, $rootLength) === $jailRoot.'/') {
416
+				return $mount->getMountPoint().substr($path, $rootLength);
417 417
 			} else {
418 418
 				return null;
419 419
 			}
420 420
 		} else {
421
-			return $mount->getMountPoint() . $path;
421
+			return $mount->getMountPoint().$path;
422 422
 		}
423 423
 	}
424 424
 }
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.
settings/Controller/UsersController.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -33,7 +33,6 @@
 block discarded – undo
33 33
 use OC\Accounts\AccountManager;
34 34
 use OC\AppFramework\Http;
35 35
 use OC\ForbiddenException;
36
-use OC\User\User;
37 36
 use OCP\App\IAppManager;
38 37
 use OCP\AppFramework\Controller;
39 38
 use OCP\AppFramework\Http\DataResponse;
Please login to merge, or discard this patch.
Indentation   +805 added lines, -805 removed lines patch added patch discarded remove patch
@@ -57,810 +57,810 @@
 block discarded – undo
57 57
  * @package OC\Settings\Controller
58 58
  */
59 59
 class UsersController extends Controller {
60
-	/** @var IL10N */
61
-	private $l10n;
62
-	/** @var IUserSession */
63
-	private $userSession;
64
-	/** @var bool */
65
-	private $isAdmin;
66
-	/** @var IUserManager */
67
-	private $userManager;
68
-	/** @var IGroupManager */
69
-	private $groupManager;
70
-	/** @var IConfig */
71
-	private $config;
72
-	/** @var ILogger */
73
-	private $log;
74
-	/** @var \OC_Defaults */
75
-	private $defaults;
76
-	/** @var IMailer */
77
-	private $mailer;
78
-	/** @var string */
79
-	private $fromMailAddress;
80
-	/** @var IURLGenerator */
81
-	private $urlGenerator;
82
-	/** @var bool contains the state of the encryption app */
83
-	private $isEncryptionAppEnabled;
84
-	/** @var bool contains the state of the admin recovery setting */
85
-	private $isRestoreEnabled = false;
86
-	/** @var IAvatarManager */
87
-	private $avatarManager;
88
-	/** @var AccountManager */
89
-	private $accountManager;
90
-	/** @var ISecureRandom */
91
-	private $secureRandom;
92
-	/** @var ITimeFactory */
93
-	private $timeFactory;
94
-	/** @var ICrypto */
95
-	private $crypto;
96
-
97
-
98
-	/**
99
-	 * @param string $appName
100
-	 * @param IRequest $request
101
-	 * @param IUserManager $userManager
102
-	 * @param IGroupManager $groupManager
103
-	 * @param IUserSession $userSession
104
-	 * @param IConfig $config
105
-	 * @param bool $isAdmin
106
-	 * @param IL10N $l10n
107
-	 * @param ILogger $log
108
-	 * @param \OC_Defaults $defaults
109
-	 * @param IMailer $mailer
110
-	 * @param string $fromMailAddress
111
-	 * @param IURLGenerator $urlGenerator
112
-	 * @param IAppManager $appManager
113
-	 * @param IAvatarManager $avatarManager
114
-	 * @param AccountManager $accountManager
115
-	 * @param ISecureRandom $secureRandom
116
-	 * @param ITimeFactory $timeFactory
117
-	 * @param ICrypto $crypto
118
-	 */
119
-	public function __construct($appName,
120
-								IRequest $request,
121
-								IUserManager $userManager,
122
-								IGroupManager $groupManager,
123
-								IUserSession $userSession,
124
-								IConfig $config,
125
-								$isAdmin,
126
-								IL10N $l10n,
127
-								ILogger $log,
128
-								\OC_Defaults $defaults,
129
-								IMailer $mailer,
130
-								$fromMailAddress,
131
-								IURLGenerator $urlGenerator,
132
-								IAppManager $appManager,
133
-								IAvatarManager $avatarManager,
134
-								AccountManager $accountManager,
135
-								ISecureRandom $secureRandom,
136
-								ITimeFactory $timeFactory,
137
-								ICrypto $crypto) {
138
-		parent::__construct($appName, $request);
139
-		$this->userManager = $userManager;
140
-		$this->groupManager = $groupManager;
141
-		$this->userSession = $userSession;
142
-		$this->config = $config;
143
-		$this->isAdmin = $isAdmin;
144
-		$this->l10n = $l10n;
145
-		$this->log = $log;
146
-		$this->defaults = $defaults;
147
-		$this->mailer = $mailer;
148
-		$this->fromMailAddress = $fromMailAddress;
149
-		$this->urlGenerator = $urlGenerator;
150
-		$this->avatarManager = $avatarManager;
151
-		$this->accountManager = $accountManager;
152
-		$this->secureRandom = $secureRandom;
153
-		$this->timeFactory = $timeFactory;
154
-		$this->crypto = $crypto;
155
-
156
-		// check for encryption state - TODO see formatUserForIndex
157
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
158
-		if($this->isEncryptionAppEnabled) {
159
-			// putting this directly in empty is possible in PHP 5.5+
160
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
161
-			$this->isRestoreEnabled = !empty($result);
162
-		}
163
-	}
164
-
165
-	/**
166
-	 * @param IUser $user
167
-	 * @param array $userGroups
168
-	 * @return array
169
-	 */
170
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
171
-
172
-		// TODO: eliminate this encryption specific code below and somehow
173
-		// hook in additional user info from other apps
174
-
175
-		// recovery isn't possible if admin or user has it disabled and encryption
176
-		// is enabled - so we eliminate the else paths in the conditional tree
177
-		// below
178
-		$restorePossible = false;
179
-
180
-		if ($this->isEncryptionAppEnabled) {
181
-			if ($this->isRestoreEnabled) {
182
-				// check for the users recovery setting
183
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
184
-				// method call inside empty is possible with PHP 5.5+
185
-				$recoveryModeEnabled = !empty($recoveryMode);
186
-				if ($recoveryModeEnabled) {
187
-					// user also has recovery mode enabled
188
-					$restorePossible = true;
189
-				}
190
-			}
191
-		} else {
192
-			// recovery is possible if encryption is disabled (plain files are
193
-			// available)
194
-			$restorePossible = true;
195
-		}
196
-
197
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
198
-		foreach($subAdminGroups as $key => $subAdminGroup) {
199
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
200
-		}
201
-
202
-		$displayName = $user->getEMailAddress();
203
-		if (is_null($displayName)) {
204
-			$displayName = '';
205
-		}
206
-
207
-		$avatarAvailable = false;
208
-		try {
209
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
210
-		} catch (\Exception $e) {
211
-			//No avatar yet
212
-		}
213
-
214
-		return [
215
-			'name' => $user->getUID(),
216
-			'displayname' => $user->getDisplayName(),
217
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
218
-			'subadmin' => $subAdminGroups,
219
-			'quota' => $user->getQuota(),
220
-			'storageLocation' => $user->getHome(),
221
-			'lastLogin' => $user->getLastLogin() * 1000,
222
-			'backend' => $user->getBackendClassName(),
223
-			'email' => $displayName,
224
-			'isRestoreDisabled' => !$restorePossible,
225
-			'isAvatarAvailable' => $avatarAvailable,
226
-		];
227
-	}
228
-
229
-	/**
230
-	 * @param array $userIDs Array with schema [$uid => $displayName]
231
-	 * @return IUser[]
232
-	 */
233
-	private function getUsersForUID(array $userIDs) {
234
-		$users = [];
235
-		foreach ($userIDs as $uid => $displayName) {
236
-			$users[$uid] = $this->userManager->get($uid);
237
-		}
238
-		return $users;
239
-	}
240
-
241
-	/**
242
-	 * @NoAdminRequired
243
-	 *
244
-	 * @param int $offset
245
-	 * @param int $limit
246
-	 * @param string $gid GID to filter for
247
-	 * @param string $pattern Pattern to search for in the username
248
-	 * @param string $backend Backend to filter for (class-name)
249
-	 * @return DataResponse
250
-	 *
251
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
252
-	 */
253
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
254
-		// FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
255
-		if($gid === '_everyone') {
256
-			$gid = '';
257
-		}
258
-
259
-		// Remove backends
260
-		if(!empty($backend)) {
261
-			$activeBackends = $this->userManager->getBackends();
262
-			$this->userManager->clearBackends();
263
-			foreach($activeBackends as $singleActiveBackend) {
264
-				if($backend === get_class($singleActiveBackend)) {
265
-					$this->userManager->registerBackend($singleActiveBackend);
266
-					break;
267
-				}
268
-			}
269
-		}
270
-
271
-		$users = [];
272
-		if ($this->isAdmin) {
273
-
274
-			if($gid !== '') {
275
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
276
-			} else {
277
-				$batch = $this->userManager->search($pattern, $limit, $offset);
278
-			}
279
-
280
-			foreach ($batch as $user) {
281
-				$users[] = $this->formatUserForIndex($user);
282
-			}
283
-
284
-		} else {
285
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
286
-			// New class returns IGroup[] so convert back
287
-			$gids = [];
288
-			foreach ($subAdminOfGroups as $group) {
289
-				$gids[] = $group->getGID();
290
-			}
291
-			$subAdminOfGroups = $gids;
292
-
293
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
294
-			if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
295
-				$gid = '';
296
-			}
297
-
298
-			// Batch all groups the user is subadmin of when a group is specified
299
-			$batch = [];
300
-			if($gid === '') {
301
-				foreach($subAdminOfGroups as $group) {
302
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
303
-
304
-					foreach($groupUsers as $uid => $displayName) {
305
-						$batch[$uid] = $displayName;
306
-					}
307
-				}
308
-			} else {
309
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
310
-			}
311
-			$batch = $this->getUsersForUID($batch);
312
-
313
-			foreach ($batch as $user) {
314
-				// Only add the groups, this user is a subadmin of
315
-				$userGroups = array_values(array_intersect(
316
-					$this->groupManager->getUserGroupIds($user),
317
-					$subAdminOfGroups
318
-				));
319
-				$users[] = $this->formatUserForIndex($user, $userGroups);
320
-			}
321
-		}
322
-
323
-		return new DataResponse($users);
324
-	}
325
-
326
-	/**
327
-	 * @NoAdminRequired
328
-	 * @PasswordConfirmationRequired
329
-	 *
330
-	 * @param string $username
331
-	 * @param string $password
332
-	 * @param array $groups
333
-	 * @param string $email
334
-	 * @return DataResponse
335
-	 */
336
-	public function create($username, $password, array $groups=array(), $email='') {
337
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
338
-			return new DataResponse(
339
-				array(
340
-					'message' => (string)$this->l10n->t('Invalid mail address')
341
-				),
342
-				Http::STATUS_UNPROCESSABLE_ENTITY
343
-			);
344
-		}
345
-
346
-		$currentUser = $this->userSession->getUser();
347
-
348
-		if (!$this->isAdmin) {
349
-			if (!empty($groups)) {
350
-				foreach ($groups as $key => $group) {
351
-					$groupObject = $this->groupManager->get($group);
352
-					if($groupObject === null) {
353
-						unset($groups[$key]);
354
-						continue;
355
-					}
356
-
357
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
358
-						unset($groups[$key]);
359
-					}
360
-				}
361
-			}
362
-
363
-			if (empty($groups)) {
364
-				return new DataResponse(
365
-					array(
366
-						'message' => $this->l10n->t('No valid group selected'),
367
-					),
368
-					Http::STATUS_FORBIDDEN
369
-				);
370
-			}
371
-		}
372
-
373
-		if ($this->userManager->userExists($username)) {
374
-			return new DataResponse(
375
-				array(
376
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
377
-				),
378
-				Http::STATUS_CONFLICT
379
-			);
380
-		}
381
-
382
-		$generatedPassword = false;
383
-		if ($password === '') {
384
-			if ($email === '') {
385
-				return new DataResponse(
386
-					array(
387
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
388
-					),
389
-					Http::STATUS_UNPROCESSABLE_ENTITY
390
-				);
391
-			}
392
-
393
-			$password = $this->secureRandom->generate(32);
394
-			$generatedPassword = true;
395
-		}
396
-
397
-		try {
398
-			$user = $this->userManager->createUser($username, $password);
399
-		} catch (\Exception $exception) {
400
-			$message = $exception->getMessage();
401
-			if (!$message) {
402
-				$message = $this->l10n->t('Unable to create user.');
403
-			}
404
-			return new DataResponse(
405
-				array(
406
-					'message' => (string) $message,
407
-				),
408
-				Http::STATUS_FORBIDDEN
409
-			);
410
-		}
411
-
412
-		if($user instanceof IUser) {
413
-			if($groups !== null) {
414
-				foreach($groups as $groupName) {
415
-					$group = $this->groupManager->get($groupName);
416
-
417
-					if(empty($group)) {
418
-						$group = $this->groupManager->createGroup($groupName);
419
-					}
420
-					$group->addUser($user);
421
-				}
422
-			}
423
-			/**
424
-			 * Send new user mail only if a mail is set
425
-			 */
426
-			if($email !== '') {
427
-				$user->setEMailAddress($email);
428
-
429
-				if ($generatedPassword) {
430
-					$token = $this->secureRandom->generate(
431
-						21,
432
-						ISecureRandom::CHAR_DIGITS .
433
-						ISecureRandom::CHAR_LOWER .
434
-						ISecureRandom::CHAR_UPPER
435
-					);
436
-					$tokenValue = $this->timeFactory->getTime() . ':' . $token;
437
-					$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
438
-					$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
439
-					$this->config->setUserValue($username, 'core', 'lostpassword', $encryptedValue);
440
-
441
-					$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $username, 'token' => $token]);
442
-				} else {
443
-					$link = $this->urlGenerator->getAbsoluteURL('/');
444
-				}
445
-
446
-				// data for the mail template
447
-				$mailData = array(
448
-					'username' => $username,
449
-					'url' => $link
450
-				);
451
-
452
-				$mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank');
453
-				$mailContent = $mail->render();
454
-
455
-				$mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank');
456
-				$plainTextMailContent = $mail->render();
457
-
458
-				$subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]);
459
-
460
-				try {
461
-					$message = $this->mailer->createMessage();
462
-					$message->setTo([$email => $username]);
463
-					$message->setSubject($subject);
464
-					$message->setHtmlBody($mailContent);
465
-					$message->setPlainBody($plainTextMailContent);
466
-					$message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
467
-					$this->mailer->send($message);
468
-				} catch(\Exception $e) {
469
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
470
-				}
471
-			}
472
-			// fetch users groups
473
-			$userGroups = $this->groupManager->getUserGroupIds($user);
474
-
475
-			return new DataResponse(
476
-				$this->formatUserForIndex($user, $userGroups),
477
-				Http::STATUS_CREATED
478
-			);
479
-		}
480
-
481
-		return new DataResponse(
482
-			array(
483
-				'message' => (string)$this->l10n->t('Unable to create user.')
484
-			),
485
-			Http::STATUS_FORBIDDEN
486
-		);
487
-
488
-	}
489
-
490
-	/**
491
-	 * @NoAdminRequired
492
-	 * @PasswordConfirmationRequired
493
-	 *
494
-	 * @param string $id
495
-	 * @return DataResponse
496
-	 */
497
-	public function destroy($id) {
498
-		$userId = $this->userSession->getUser()->getUID();
499
-		$user = $this->userManager->get($id);
500
-
501
-		if($userId === $id) {
502
-			return new DataResponse(
503
-				array(
504
-					'status' => 'error',
505
-					'data' => array(
506
-						'message' => (string)$this->l10n->t('Unable to delete user.')
507
-					)
508
-				),
509
-				Http::STATUS_FORBIDDEN
510
-			);
511
-		}
512
-
513
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
514
-			return new DataResponse(
515
-				array(
516
-					'status' => 'error',
517
-					'data' => array(
518
-						'message' => (string)$this->l10n->t('Authentication error')
519
-					)
520
-				),
521
-				Http::STATUS_FORBIDDEN
522
-			);
523
-		}
524
-
525
-		if($user) {
526
-			if($user->delete()) {
527
-				return new DataResponse(
528
-					array(
529
-						'status' => 'success',
530
-						'data' => array(
531
-							'username' => $id
532
-						)
533
-					),
534
-					Http::STATUS_NO_CONTENT
535
-				);
536
-			}
537
-		}
538
-
539
-		return new DataResponse(
540
-			array(
541
-				'status' => 'error',
542
-				'data' => array(
543
-					'message' => (string)$this->l10n->t('Unable to delete user.')
544
-				)
545
-			),
546
-			Http::STATUS_FORBIDDEN
547
-		);
548
-	}
549
-
550
-	/**
551
-	 * @NoAdminRequired
552
-	 * @NoSubadminRequired
553
-	 * @PasswordConfirmationRequired
554
-	 *
555
-	 * @param string $avatarScope
556
-	 * @param string $displayname
557
-	 * @param string $displaynameScope
558
-	 * @param string $phone
559
-	 * @param string $phoneScope
560
-	 * @param string $email
561
-	 * @param string $emailScope
562
-	 * @param string $website
563
-	 * @param string $websiteScope
564
-	 * @param string $address
565
-	 * @param string $addressScope
566
-	 * @param string $twitter
567
-	 * @param string $twitterScope
568
-	 * @return DataResponse
569
-	 */
570
-	public function setUserSettings($avatarScope,
571
-									$displayname,
572
-									$displaynameScope,
573
-									$phone,
574
-									$phoneScope,
575
-									$email,
576
-									$emailScope,
577
-									$website,
578
-									$websiteScope,
579
-									$address,
580
-									$addressScope,
581
-									$twitter,
582
-									$twitterScope
583
-	) {
584
-
585
-		if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
586
-			return new DataResponse(
587
-				array(
588
-					'status' => 'error',
589
-					'data' => array(
590
-						'message' => (string)$this->l10n->t('Invalid mail address')
591
-					)
592
-				),
593
-				Http::STATUS_UNPROCESSABLE_ENTITY
594
-			);
595
-		}
596
-
597
-		$data = [
598
-			AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
599
-			AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
600
-			AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
601
-			AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
602
-			AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
603
-			AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
604
-			AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
605
-		];
606
-
607
-		$user = $this->userSession->getUser();
608
-
609
-		try {
610
-			$this->saveUserSettings($user, $data);
611
-			return new DataResponse(
612
-				array(
613
-					'status' => 'success',
614
-					'data' => array(
615
-						'userId' => $user->getUID(),
616
-						'avatarScope' => $avatarScope,
617
-						'displayname' => $displayname,
618
-						'displaynameScope' => $displaynameScope,
619
-						'email' => $email,
620
-						'emailScope' => $emailScope,
621
-						'website' => $website,
622
-						'websiteScope' => $websiteScope,
623
-						'address' => $address,
624
-						'addressScope' => $addressScope,
625
-						'message' => (string)$this->l10n->t('Settings saved')
626
-					)
627
-				),
628
-				Http::STATUS_OK
629
-			);
630
-		} catch (ForbiddenException $e) {
631
-			return new DataResponse([
632
-				'status' => 'error',
633
-				'data' => [
634
-					'message' => $e->getMessage()
635
-				],
636
-			]);
637
-		}
638
-
639
-	}
640
-
641
-
642
-	/**
643
-	 * update account manager with new user data
644
-	 *
645
-	 * @param IUser $user
646
-	 * @param array $data
647
-	 * @throws ForbiddenException
648
-	 */
649
-	protected function saveUserSettings(IUser $user, $data) {
650
-
651
-		// keep the user back-end up-to-date with the latest display name and email
652
-		// address
653
-		$oldDisplayName = $user->getDisplayName();
654
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
655
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
656
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
657
-		) {
658
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
659
-			if ($result === false) {
660
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
661
-			}
662
-		}
663
-
664
-		$oldEmailAddress = $user->getEMailAddress();
665
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
666
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
667
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
668
-		) {
669
-			// this is the only permission a backend provides and is also used
670
-			// for the permission of setting a email address
671
-			if (!$user->canChangeDisplayName()) {
672
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
673
-			}
674
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
675
-		}
676
-
677
-		$this->accountManager->updateUser($user, $data);
678
-	}
679
-
680
-	/**
681
-	 * Count all unique users visible for the current admin/subadmin.
682
-	 *
683
-	 * @NoAdminRequired
684
-	 *
685
-	 * @return DataResponse
686
-	 */
687
-	public function stats() {
688
-		$userCount = 0;
689
-		if ($this->isAdmin) {
690
-			$countByBackend = $this->userManager->countUsers();
691
-
692
-			if (!empty($countByBackend)) {
693
-				foreach ($countByBackend as $count) {
694
-					$userCount += $count;
695
-				}
696
-			}
697
-		} else {
698
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
699
-
700
-			$uniqueUsers = [];
701
-			foreach ($groups as $group) {
702
-				foreach($group->getUsers() as $uid => $displayName) {
703
-					$uniqueUsers[$uid] = true;
704
-				}
705
-			}
706
-
707
-			$userCount = count($uniqueUsers);
708
-		}
709
-
710
-		return new DataResponse(
711
-			[
712
-				'totalUsers' => $userCount
713
-			]
714
-		);
715
-	}
716
-
717
-
718
-	/**
719
-	 * Set the displayName of a user
720
-	 *
721
-	 * @NoAdminRequired
722
-	 * @NoSubadminRequired
723
-	 * @PasswordConfirmationRequired
724
-	 * @todo merge into saveUserSettings
725
-	 *
726
-	 * @param string $username
727
-	 * @param string $displayName
728
-	 * @return DataResponse
729
-	 */
730
-	public function setDisplayName($username, $displayName) {
731
-		$currentUser = $this->userSession->getUser();
732
-		$user = $this->userManager->get($username);
733
-
734
-		if ($user === null ||
735
-			!$user->canChangeDisplayName() ||
736
-			(
737
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
738
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
739
-				$currentUser->getUID() !== $username
740
-
741
-			)
742
-		) {
743
-			return new DataResponse([
744
-				'status' => 'error',
745
-				'data' => [
746
-					'message' => $this->l10n->t('Authentication error'),
747
-				],
748
-			]);
749
-		}
750
-
751
-		$userData = $this->accountManager->getUser($user);
752
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
753
-
754
-
755
-		try {
756
-			$this->saveUserSettings($user, $userData);
757
-			return new DataResponse([
758
-				'status' => 'success',
759
-				'data' => [
760
-					'message' => $this->l10n->t('Your full name has been changed.'),
761
-					'username' => $username,
762
-					'displayName' => $displayName,
763
-				],
764
-			]);
765
-		} catch (ForbiddenException $e) {
766
-			return new DataResponse([
767
-				'status' => 'error',
768
-				'data' => [
769
-					'message' => $e->getMessage(),
770
-					'displayName' => $user->getDisplayName(),
771
-				],
772
-			]);
773
-		}
774
-	}
775
-
776
-	/**
777
-	 * Set the mail address of a user
778
-	 *
779
-	 * @NoAdminRequired
780
-	 * @NoSubadminRequired
781
-	 * @PasswordConfirmationRequired
782
-	 *
783
-	 * @param string $id
784
-	 * @param string $mailAddress
785
-	 * @return DataResponse
786
-	 */
787
-	public function setEMailAddress($id, $mailAddress) {
788
-		$user = $this->userManager->get($id);
789
-		if (!$this->isAdmin
790
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
791
-		) {
792
-			return new DataResponse(
793
-				array(
794
-					'status' => 'error',
795
-					'data' => array(
796
-						'message' => (string)$this->l10n->t('Forbidden')
797
-					)
798
-				),
799
-				Http::STATUS_FORBIDDEN
800
-			);
801
-		}
802
-
803
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
804
-			return new DataResponse(
805
-				array(
806
-					'status' => 'error',
807
-					'data' => array(
808
-						'message' => (string)$this->l10n->t('Invalid mail address')
809
-					)
810
-				),
811
-				Http::STATUS_UNPROCESSABLE_ENTITY
812
-			);
813
-		}
814
-
815
-		if (!$user) {
816
-			return new DataResponse(
817
-				array(
818
-					'status' => 'error',
819
-					'data' => array(
820
-						'message' => (string)$this->l10n->t('Invalid user')
821
-					)
822
-				),
823
-				Http::STATUS_UNPROCESSABLE_ENTITY
824
-			);
825
-		}
826
-		// this is the only permission a backend provides and is also used
827
-		// for the permission of setting a email address
828
-		if (!$user->canChangeDisplayName()) {
829
-			return new DataResponse(
830
-				array(
831
-					'status' => 'error',
832
-					'data' => array(
833
-						'message' => (string)$this->l10n->t('Unable to change mail address')
834
-					)
835
-				),
836
-				Http::STATUS_FORBIDDEN
837
-			);
838
-		}
839
-
840
-		$userData = $this->accountManager->getUser($user);
841
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
842
-
843
-		try {
844
-			$this->saveUserSettings($user, $userData);
845
-			return new DataResponse(
846
-				array(
847
-					'status' => 'success',
848
-					'data' => array(
849
-						'username' => $id,
850
-						'mailAddress' => $mailAddress,
851
-						'message' => (string)$this->l10n->t('Email saved')
852
-					)
853
-				),
854
-				Http::STATUS_OK
855
-			);
856
-		} catch (ForbiddenException $e) {
857
-			return new DataResponse([
858
-				'status' => 'error',
859
-				'data' => [
860
-					'message' => $e->getMessage()
861
-				],
862
-			]);
863
-		}
864
-	}
60
+    /** @var IL10N */
61
+    private $l10n;
62
+    /** @var IUserSession */
63
+    private $userSession;
64
+    /** @var bool */
65
+    private $isAdmin;
66
+    /** @var IUserManager */
67
+    private $userManager;
68
+    /** @var IGroupManager */
69
+    private $groupManager;
70
+    /** @var IConfig */
71
+    private $config;
72
+    /** @var ILogger */
73
+    private $log;
74
+    /** @var \OC_Defaults */
75
+    private $defaults;
76
+    /** @var IMailer */
77
+    private $mailer;
78
+    /** @var string */
79
+    private $fromMailAddress;
80
+    /** @var IURLGenerator */
81
+    private $urlGenerator;
82
+    /** @var bool contains the state of the encryption app */
83
+    private $isEncryptionAppEnabled;
84
+    /** @var bool contains the state of the admin recovery setting */
85
+    private $isRestoreEnabled = false;
86
+    /** @var IAvatarManager */
87
+    private $avatarManager;
88
+    /** @var AccountManager */
89
+    private $accountManager;
90
+    /** @var ISecureRandom */
91
+    private $secureRandom;
92
+    /** @var ITimeFactory */
93
+    private $timeFactory;
94
+    /** @var ICrypto */
95
+    private $crypto;
96
+
97
+
98
+    /**
99
+     * @param string $appName
100
+     * @param IRequest $request
101
+     * @param IUserManager $userManager
102
+     * @param IGroupManager $groupManager
103
+     * @param IUserSession $userSession
104
+     * @param IConfig $config
105
+     * @param bool $isAdmin
106
+     * @param IL10N $l10n
107
+     * @param ILogger $log
108
+     * @param \OC_Defaults $defaults
109
+     * @param IMailer $mailer
110
+     * @param string $fromMailAddress
111
+     * @param IURLGenerator $urlGenerator
112
+     * @param IAppManager $appManager
113
+     * @param IAvatarManager $avatarManager
114
+     * @param AccountManager $accountManager
115
+     * @param ISecureRandom $secureRandom
116
+     * @param ITimeFactory $timeFactory
117
+     * @param ICrypto $crypto
118
+     */
119
+    public function __construct($appName,
120
+                                IRequest $request,
121
+                                IUserManager $userManager,
122
+                                IGroupManager $groupManager,
123
+                                IUserSession $userSession,
124
+                                IConfig $config,
125
+                                $isAdmin,
126
+                                IL10N $l10n,
127
+                                ILogger $log,
128
+                                \OC_Defaults $defaults,
129
+                                IMailer $mailer,
130
+                                $fromMailAddress,
131
+                                IURLGenerator $urlGenerator,
132
+                                IAppManager $appManager,
133
+                                IAvatarManager $avatarManager,
134
+                                AccountManager $accountManager,
135
+                                ISecureRandom $secureRandom,
136
+                                ITimeFactory $timeFactory,
137
+                                ICrypto $crypto) {
138
+        parent::__construct($appName, $request);
139
+        $this->userManager = $userManager;
140
+        $this->groupManager = $groupManager;
141
+        $this->userSession = $userSession;
142
+        $this->config = $config;
143
+        $this->isAdmin = $isAdmin;
144
+        $this->l10n = $l10n;
145
+        $this->log = $log;
146
+        $this->defaults = $defaults;
147
+        $this->mailer = $mailer;
148
+        $this->fromMailAddress = $fromMailAddress;
149
+        $this->urlGenerator = $urlGenerator;
150
+        $this->avatarManager = $avatarManager;
151
+        $this->accountManager = $accountManager;
152
+        $this->secureRandom = $secureRandom;
153
+        $this->timeFactory = $timeFactory;
154
+        $this->crypto = $crypto;
155
+
156
+        // check for encryption state - TODO see formatUserForIndex
157
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
158
+        if($this->isEncryptionAppEnabled) {
159
+            // putting this directly in empty is possible in PHP 5.5+
160
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
161
+            $this->isRestoreEnabled = !empty($result);
162
+        }
163
+    }
164
+
165
+    /**
166
+     * @param IUser $user
167
+     * @param array $userGroups
168
+     * @return array
169
+     */
170
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
171
+
172
+        // TODO: eliminate this encryption specific code below and somehow
173
+        // hook in additional user info from other apps
174
+
175
+        // recovery isn't possible if admin or user has it disabled and encryption
176
+        // is enabled - so we eliminate the else paths in the conditional tree
177
+        // below
178
+        $restorePossible = false;
179
+
180
+        if ($this->isEncryptionAppEnabled) {
181
+            if ($this->isRestoreEnabled) {
182
+                // check for the users recovery setting
183
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
184
+                // method call inside empty is possible with PHP 5.5+
185
+                $recoveryModeEnabled = !empty($recoveryMode);
186
+                if ($recoveryModeEnabled) {
187
+                    // user also has recovery mode enabled
188
+                    $restorePossible = true;
189
+                }
190
+            }
191
+        } else {
192
+            // recovery is possible if encryption is disabled (plain files are
193
+            // available)
194
+            $restorePossible = true;
195
+        }
196
+
197
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
198
+        foreach($subAdminGroups as $key => $subAdminGroup) {
199
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
200
+        }
201
+
202
+        $displayName = $user->getEMailAddress();
203
+        if (is_null($displayName)) {
204
+            $displayName = '';
205
+        }
206
+
207
+        $avatarAvailable = false;
208
+        try {
209
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
210
+        } catch (\Exception $e) {
211
+            //No avatar yet
212
+        }
213
+
214
+        return [
215
+            'name' => $user->getUID(),
216
+            'displayname' => $user->getDisplayName(),
217
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
218
+            'subadmin' => $subAdminGroups,
219
+            'quota' => $user->getQuota(),
220
+            'storageLocation' => $user->getHome(),
221
+            'lastLogin' => $user->getLastLogin() * 1000,
222
+            'backend' => $user->getBackendClassName(),
223
+            'email' => $displayName,
224
+            'isRestoreDisabled' => !$restorePossible,
225
+            'isAvatarAvailable' => $avatarAvailable,
226
+        ];
227
+    }
228
+
229
+    /**
230
+     * @param array $userIDs Array with schema [$uid => $displayName]
231
+     * @return IUser[]
232
+     */
233
+    private function getUsersForUID(array $userIDs) {
234
+        $users = [];
235
+        foreach ($userIDs as $uid => $displayName) {
236
+            $users[$uid] = $this->userManager->get($uid);
237
+        }
238
+        return $users;
239
+    }
240
+
241
+    /**
242
+     * @NoAdminRequired
243
+     *
244
+     * @param int $offset
245
+     * @param int $limit
246
+     * @param string $gid GID to filter for
247
+     * @param string $pattern Pattern to search for in the username
248
+     * @param string $backend Backend to filter for (class-name)
249
+     * @return DataResponse
250
+     *
251
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
252
+     */
253
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
254
+        // FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
255
+        if($gid === '_everyone') {
256
+            $gid = '';
257
+        }
258
+
259
+        // Remove backends
260
+        if(!empty($backend)) {
261
+            $activeBackends = $this->userManager->getBackends();
262
+            $this->userManager->clearBackends();
263
+            foreach($activeBackends as $singleActiveBackend) {
264
+                if($backend === get_class($singleActiveBackend)) {
265
+                    $this->userManager->registerBackend($singleActiveBackend);
266
+                    break;
267
+                }
268
+            }
269
+        }
270
+
271
+        $users = [];
272
+        if ($this->isAdmin) {
273
+
274
+            if($gid !== '') {
275
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
276
+            } else {
277
+                $batch = $this->userManager->search($pattern, $limit, $offset);
278
+            }
279
+
280
+            foreach ($batch as $user) {
281
+                $users[] = $this->formatUserForIndex($user);
282
+            }
283
+
284
+        } else {
285
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
286
+            // New class returns IGroup[] so convert back
287
+            $gids = [];
288
+            foreach ($subAdminOfGroups as $group) {
289
+                $gids[] = $group->getGID();
290
+            }
291
+            $subAdminOfGroups = $gids;
292
+
293
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
294
+            if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
295
+                $gid = '';
296
+            }
297
+
298
+            // Batch all groups the user is subadmin of when a group is specified
299
+            $batch = [];
300
+            if($gid === '') {
301
+                foreach($subAdminOfGroups as $group) {
302
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
303
+
304
+                    foreach($groupUsers as $uid => $displayName) {
305
+                        $batch[$uid] = $displayName;
306
+                    }
307
+                }
308
+            } else {
309
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
310
+            }
311
+            $batch = $this->getUsersForUID($batch);
312
+
313
+            foreach ($batch as $user) {
314
+                // Only add the groups, this user is a subadmin of
315
+                $userGroups = array_values(array_intersect(
316
+                    $this->groupManager->getUserGroupIds($user),
317
+                    $subAdminOfGroups
318
+                ));
319
+                $users[] = $this->formatUserForIndex($user, $userGroups);
320
+            }
321
+        }
322
+
323
+        return new DataResponse($users);
324
+    }
325
+
326
+    /**
327
+     * @NoAdminRequired
328
+     * @PasswordConfirmationRequired
329
+     *
330
+     * @param string $username
331
+     * @param string $password
332
+     * @param array $groups
333
+     * @param string $email
334
+     * @return DataResponse
335
+     */
336
+    public function create($username, $password, array $groups=array(), $email='') {
337
+        if($email !== '' && !$this->mailer->validateMailAddress($email)) {
338
+            return new DataResponse(
339
+                array(
340
+                    'message' => (string)$this->l10n->t('Invalid mail address')
341
+                ),
342
+                Http::STATUS_UNPROCESSABLE_ENTITY
343
+            );
344
+        }
345
+
346
+        $currentUser = $this->userSession->getUser();
347
+
348
+        if (!$this->isAdmin) {
349
+            if (!empty($groups)) {
350
+                foreach ($groups as $key => $group) {
351
+                    $groupObject = $this->groupManager->get($group);
352
+                    if($groupObject === null) {
353
+                        unset($groups[$key]);
354
+                        continue;
355
+                    }
356
+
357
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
358
+                        unset($groups[$key]);
359
+                    }
360
+                }
361
+            }
362
+
363
+            if (empty($groups)) {
364
+                return new DataResponse(
365
+                    array(
366
+                        'message' => $this->l10n->t('No valid group selected'),
367
+                    ),
368
+                    Http::STATUS_FORBIDDEN
369
+                );
370
+            }
371
+        }
372
+
373
+        if ($this->userManager->userExists($username)) {
374
+            return new DataResponse(
375
+                array(
376
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
377
+                ),
378
+                Http::STATUS_CONFLICT
379
+            );
380
+        }
381
+
382
+        $generatedPassword = false;
383
+        if ($password === '') {
384
+            if ($email === '') {
385
+                return new DataResponse(
386
+                    array(
387
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
388
+                    ),
389
+                    Http::STATUS_UNPROCESSABLE_ENTITY
390
+                );
391
+            }
392
+
393
+            $password = $this->secureRandom->generate(32);
394
+            $generatedPassword = true;
395
+        }
396
+
397
+        try {
398
+            $user = $this->userManager->createUser($username, $password);
399
+        } catch (\Exception $exception) {
400
+            $message = $exception->getMessage();
401
+            if (!$message) {
402
+                $message = $this->l10n->t('Unable to create user.');
403
+            }
404
+            return new DataResponse(
405
+                array(
406
+                    'message' => (string) $message,
407
+                ),
408
+                Http::STATUS_FORBIDDEN
409
+            );
410
+        }
411
+
412
+        if($user instanceof IUser) {
413
+            if($groups !== null) {
414
+                foreach($groups as $groupName) {
415
+                    $group = $this->groupManager->get($groupName);
416
+
417
+                    if(empty($group)) {
418
+                        $group = $this->groupManager->createGroup($groupName);
419
+                    }
420
+                    $group->addUser($user);
421
+                }
422
+            }
423
+            /**
424
+             * Send new user mail only if a mail is set
425
+             */
426
+            if($email !== '') {
427
+                $user->setEMailAddress($email);
428
+
429
+                if ($generatedPassword) {
430
+                    $token = $this->secureRandom->generate(
431
+                        21,
432
+                        ISecureRandom::CHAR_DIGITS .
433
+                        ISecureRandom::CHAR_LOWER .
434
+                        ISecureRandom::CHAR_UPPER
435
+                    );
436
+                    $tokenValue = $this->timeFactory->getTime() . ':' . $token;
437
+                    $mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
438
+                    $encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
439
+                    $this->config->setUserValue($username, 'core', 'lostpassword', $encryptedValue);
440
+
441
+                    $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $username, 'token' => $token]);
442
+                } else {
443
+                    $link = $this->urlGenerator->getAbsoluteURL('/');
444
+                }
445
+
446
+                // data for the mail template
447
+                $mailData = array(
448
+                    'username' => $username,
449
+                    'url' => $link
450
+                );
451
+
452
+                $mail = new TemplateResponse('settings', 'email.new_user', $mailData, 'blank');
453
+                $mailContent = $mail->render();
454
+
455
+                $mail = new TemplateResponse('settings', 'email.new_user_plain_text', $mailData, 'blank');
456
+                $plainTextMailContent = $mail->render();
457
+
458
+                $subject = $this->l10n->t('Your %s account was created', [$this->defaults->getName()]);
459
+
460
+                try {
461
+                    $message = $this->mailer->createMessage();
462
+                    $message->setTo([$email => $username]);
463
+                    $message->setSubject($subject);
464
+                    $message->setHtmlBody($mailContent);
465
+                    $message->setPlainBody($plainTextMailContent);
466
+                    $message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
467
+                    $this->mailer->send($message);
468
+                } catch(\Exception $e) {
469
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
470
+                }
471
+            }
472
+            // fetch users groups
473
+            $userGroups = $this->groupManager->getUserGroupIds($user);
474
+
475
+            return new DataResponse(
476
+                $this->formatUserForIndex($user, $userGroups),
477
+                Http::STATUS_CREATED
478
+            );
479
+        }
480
+
481
+        return new DataResponse(
482
+            array(
483
+                'message' => (string)$this->l10n->t('Unable to create user.')
484
+            ),
485
+            Http::STATUS_FORBIDDEN
486
+        );
487
+
488
+    }
489
+
490
+    /**
491
+     * @NoAdminRequired
492
+     * @PasswordConfirmationRequired
493
+     *
494
+     * @param string $id
495
+     * @return DataResponse
496
+     */
497
+    public function destroy($id) {
498
+        $userId = $this->userSession->getUser()->getUID();
499
+        $user = $this->userManager->get($id);
500
+
501
+        if($userId === $id) {
502
+            return new DataResponse(
503
+                array(
504
+                    'status' => 'error',
505
+                    'data' => array(
506
+                        'message' => (string)$this->l10n->t('Unable to delete user.')
507
+                    )
508
+                ),
509
+                Http::STATUS_FORBIDDEN
510
+            );
511
+        }
512
+
513
+        if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
514
+            return new DataResponse(
515
+                array(
516
+                    'status' => 'error',
517
+                    'data' => array(
518
+                        'message' => (string)$this->l10n->t('Authentication error')
519
+                    )
520
+                ),
521
+                Http::STATUS_FORBIDDEN
522
+            );
523
+        }
524
+
525
+        if($user) {
526
+            if($user->delete()) {
527
+                return new DataResponse(
528
+                    array(
529
+                        'status' => 'success',
530
+                        'data' => array(
531
+                            'username' => $id
532
+                        )
533
+                    ),
534
+                    Http::STATUS_NO_CONTENT
535
+                );
536
+            }
537
+        }
538
+
539
+        return new DataResponse(
540
+            array(
541
+                'status' => 'error',
542
+                'data' => array(
543
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
544
+                )
545
+            ),
546
+            Http::STATUS_FORBIDDEN
547
+        );
548
+    }
549
+
550
+    /**
551
+     * @NoAdminRequired
552
+     * @NoSubadminRequired
553
+     * @PasswordConfirmationRequired
554
+     *
555
+     * @param string $avatarScope
556
+     * @param string $displayname
557
+     * @param string $displaynameScope
558
+     * @param string $phone
559
+     * @param string $phoneScope
560
+     * @param string $email
561
+     * @param string $emailScope
562
+     * @param string $website
563
+     * @param string $websiteScope
564
+     * @param string $address
565
+     * @param string $addressScope
566
+     * @param string $twitter
567
+     * @param string $twitterScope
568
+     * @return DataResponse
569
+     */
570
+    public function setUserSettings($avatarScope,
571
+                                    $displayname,
572
+                                    $displaynameScope,
573
+                                    $phone,
574
+                                    $phoneScope,
575
+                                    $email,
576
+                                    $emailScope,
577
+                                    $website,
578
+                                    $websiteScope,
579
+                                    $address,
580
+                                    $addressScope,
581
+                                    $twitter,
582
+                                    $twitterScope
583
+    ) {
584
+
585
+        if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
586
+            return new DataResponse(
587
+                array(
588
+                    'status' => 'error',
589
+                    'data' => array(
590
+                        'message' => (string)$this->l10n->t('Invalid mail address')
591
+                    )
592
+                ),
593
+                Http::STATUS_UNPROCESSABLE_ENTITY
594
+            );
595
+        }
596
+
597
+        $data = [
598
+            AccountManager::PROPERTY_AVATAR =>  ['scope' => $avatarScope],
599
+            AccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
600
+            AccountManager::PROPERTY_EMAIL=> ['value' => $email, 'scope' => $emailScope],
601
+            AccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
602
+            AccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
603
+            AccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
604
+            AccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope]
605
+        ];
606
+
607
+        $user = $this->userSession->getUser();
608
+
609
+        try {
610
+            $this->saveUserSettings($user, $data);
611
+            return new DataResponse(
612
+                array(
613
+                    'status' => 'success',
614
+                    'data' => array(
615
+                        'userId' => $user->getUID(),
616
+                        'avatarScope' => $avatarScope,
617
+                        'displayname' => $displayname,
618
+                        'displaynameScope' => $displaynameScope,
619
+                        'email' => $email,
620
+                        'emailScope' => $emailScope,
621
+                        'website' => $website,
622
+                        'websiteScope' => $websiteScope,
623
+                        'address' => $address,
624
+                        'addressScope' => $addressScope,
625
+                        'message' => (string)$this->l10n->t('Settings saved')
626
+                    )
627
+                ),
628
+                Http::STATUS_OK
629
+            );
630
+        } catch (ForbiddenException $e) {
631
+            return new DataResponse([
632
+                'status' => 'error',
633
+                'data' => [
634
+                    'message' => $e->getMessage()
635
+                ],
636
+            ]);
637
+        }
638
+
639
+    }
640
+
641
+
642
+    /**
643
+     * update account manager with new user data
644
+     *
645
+     * @param IUser $user
646
+     * @param array $data
647
+     * @throws ForbiddenException
648
+     */
649
+    protected function saveUserSettings(IUser $user, $data) {
650
+
651
+        // keep the user back-end up-to-date with the latest display name and email
652
+        // address
653
+        $oldDisplayName = $user->getDisplayName();
654
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
655
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
656
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
657
+        ) {
658
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
659
+            if ($result === false) {
660
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
661
+            }
662
+        }
663
+
664
+        $oldEmailAddress = $user->getEMailAddress();
665
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
666
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
667
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
668
+        ) {
669
+            // this is the only permission a backend provides and is also used
670
+            // for the permission of setting a email address
671
+            if (!$user->canChangeDisplayName()) {
672
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
673
+            }
674
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
675
+        }
676
+
677
+        $this->accountManager->updateUser($user, $data);
678
+    }
679
+
680
+    /**
681
+     * Count all unique users visible for the current admin/subadmin.
682
+     *
683
+     * @NoAdminRequired
684
+     *
685
+     * @return DataResponse
686
+     */
687
+    public function stats() {
688
+        $userCount = 0;
689
+        if ($this->isAdmin) {
690
+            $countByBackend = $this->userManager->countUsers();
691
+
692
+            if (!empty($countByBackend)) {
693
+                foreach ($countByBackend as $count) {
694
+                    $userCount += $count;
695
+                }
696
+            }
697
+        } else {
698
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
699
+
700
+            $uniqueUsers = [];
701
+            foreach ($groups as $group) {
702
+                foreach($group->getUsers() as $uid => $displayName) {
703
+                    $uniqueUsers[$uid] = true;
704
+                }
705
+            }
706
+
707
+            $userCount = count($uniqueUsers);
708
+        }
709
+
710
+        return new DataResponse(
711
+            [
712
+                'totalUsers' => $userCount
713
+            ]
714
+        );
715
+    }
716
+
717
+
718
+    /**
719
+     * Set the displayName of a user
720
+     *
721
+     * @NoAdminRequired
722
+     * @NoSubadminRequired
723
+     * @PasswordConfirmationRequired
724
+     * @todo merge into saveUserSettings
725
+     *
726
+     * @param string $username
727
+     * @param string $displayName
728
+     * @return DataResponse
729
+     */
730
+    public function setDisplayName($username, $displayName) {
731
+        $currentUser = $this->userSession->getUser();
732
+        $user = $this->userManager->get($username);
733
+
734
+        if ($user === null ||
735
+            !$user->canChangeDisplayName() ||
736
+            (
737
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
738
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
739
+                $currentUser->getUID() !== $username
740
+
741
+            )
742
+        ) {
743
+            return new DataResponse([
744
+                'status' => 'error',
745
+                'data' => [
746
+                    'message' => $this->l10n->t('Authentication error'),
747
+                ],
748
+            ]);
749
+        }
750
+
751
+        $userData = $this->accountManager->getUser($user);
752
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
753
+
754
+
755
+        try {
756
+            $this->saveUserSettings($user, $userData);
757
+            return new DataResponse([
758
+                'status' => 'success',
759
+                'data' => [
760
+                    'message' => $this->l10n->t('Your full name has been changed.'),
761
+                    'username' => $username,
762
+                    'displayName' => $displayName,
763
+                ],
764
+            ]);
765
+        } catch (ForbiddenException $e) {
766
+            return new DataResponse([
767
+                'status' => 'error',
768
+                'data' => [
769
+                    'message' => $e->getMessage(),
770
+                    'displayName' => $user->getDisplayName(),
771
+                ],
772
+            ]);
773
+        }
774
+    }
775
+
776
+    /**
777
+     * Set the mail address of a user
778
+     *
779
+     * @NoAdminRequired
780
+     * @NoSubadminRequired
781
+     * @PasswordConfirmationRequired
782
+     *
783
+     * @param string $id
784
+     * @param string $mailAddress
785
+     * @return DataResponse
786
+     */
787
+    public function setEMailAddress($id, $mailAddress) {
788
+        $user = $this->userManager->get($id);
789
+        if (!$this->isAdmin
790
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
791
+        ) {
792
+            return new DataResponse(
793
+                array(
794
+                    'status' => 'error',
795
+                    'data' => array(
796
+                        'message' => (string)$this->l10n->t('Forbidden')
797
+                    )
798
+                ),
799
+                Http::STATUS_FORBIDDEN
800
+            );
801
+        }
802
+
803
+        if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
804
+            return new DataResponse(
805
+                array(
806
+                    'status' => 'error',
807
+                    'data' => array(
808
+                        'message' => (string)$this->l10n->t('Invalid mail address')
809
+                    )
810
+                ),
811
+                Http::STATUS_UNPROCESSABLE_ENTITY
812
+            );
813
+        }
814
+
815
+        if (!$user) {
816
+            return new DataResponse(
817
+                array(
818
+                    'status' => 'error',
819
+                    'data' => array(
820
+                        'message' => (string)$this->l10n->t('Invalid user')
821
+                    )
822
+                ),
823
+                Http::STATUS_UNPROCESSABLE_ENTITY
824
+            );
825
+        }
826
+        // this is the only permission a backend provides and is also used
827
+        // for the permission of setting a email address
828
+        if (!$user->canChangeDisplayName()) {
829
+            return new DataResponse(
830
+                array(
831
+                    'status' => 'error',
832
+                    'data' => array(
833
+                        'message' => (string)$this->l10n->t('Unable to change mail address')
834
+                    )
835
+                ),
836
+                Http::STATUS_FORBIDDEN
837
+            );
838
+        }
839
+
840
+        $userData = $this->accountManager->getUser($user);
841
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
842
+
843
+        try {
844
+            $this->saveUserSettings($user, $userData);
845
+            return new DataResponse(
846
+                array(
847
+                    'status' => 'success',
848
+                    'data' => array(
849
+                        'username' => $id,
850
+                        'mailAddress' => $mailAddress,
851
+                        'message' => (string)$this->l10n->t('Email saved')
852
+                    )
853
+                ),
854
+                Http::STATUS_OK
855
+            );
856
+        } catch (ForbiddenException $e) {
857
+            return new DataResponse([
858
+                'status' => 'error',
859
+                'data' => [
860
+                    'message' => $e->getMessage()
861
+                ],
862
+            ]);
863
+        }
864
+    }
865 865
 
866 866
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 
156 156
 		// check for encryption state - TODO see formatUserForIndex
157 157
 		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
158
-		if($this->isEncryptionAppEnabled) {
158
+		if ($this->isEncryptionAppEnabled) {
159 159
 			// putting this directly in empty is possible in PHP 5.5+
160 160
 			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
161 161
 			$this->isRestoreEnabled = !empty($result);
@@ -195,7 +195,7 @@  discard block
 block discarded – undo
195 195
 		}
196 196
 
197 197
 		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
198
-		foreach($subAdminGroups as $key => $subAdminGroup) {
198
+		foreach ($subAdminGroups as $key => $subAdminGroup) {
199 199
 			$subAdminGroups[$key] = $subAdminGroup->getGID();
200 200
 		}
201 201
 
@@ -252,16 +252,16 @@  discard block
 block discarded – undo
252 252
 	 */
253 253
 	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
254 254
 		// FIXME: The JS sends the group '_everyone' instead of no GID for the "all users" group.
255
-		if($gid === '_everyone') {
255
+		if ($gid === '_everyone') {
256 256
 			$gid = '';
257 257
 		}
258 258
 
259 259
 		// Remove backends
260
-		if(!empty($backend)) {
260
+		if (!empty($backend)) {
261 261
 			$activeBackends = $this->userManager->getBackends();
262 262
 			$this->userManager->clearBackends();
263
-			foreach($activeBackends as $singleActiveBackend) {
264
-				if($backend === get_class($singleActiveBackend)) {
263
+			foreach ($activeBackends as $singleActiveBackend) {
264
+				if ($backend === get_class($singleActiveBackend)) {
265 265
 					$this->userManager->registerBackend($singleActiveBackend);
266 266
 					break;
267 267
 				}
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 		$users = [];
272 272
 		if ($this->isAdmin) {
273 273
 
274
-			if($gid !== '') {
274
+			if ($gid !== '') {
275 275
 				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
276 276
 			} else {
277 277
 				$batch = $this->userManager->search($pattern, $limit, $offset);
@@ -291,17 +291,17 @@  discard block
 block discarded – undo
291 291
 			$subAdminOfGroups = $gids;
292 292
 
293 293
 			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
294
-			if($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
294
+			if ($gid !== '' && !in_array($gid, $subAdminOfGroups)) {
295 295
 				$gid = '';
296 296
 			}
297 297
 
298 298
 			// Batch all groups the user is subadmin of when a group is specified
299 299
 			$batch = [];
300
-			if($gid === '') {
301
-				foreach($subAdminOfGroups as $group) {
300
+			if ($gid === '') {
301
+				foreach ($subAdminOfGroups as $group) {
302 302
 					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
303 303
 
304
-					foreach($groupUsers as $uid => $displayName) {
304
+					foreach ($groupUsers as $uid => $displayName) {
305 305
 						$batch[$uid] = $displayName;
306 306
 					}
307 307
 				}
@@ -333,11 +333,11 @@  discard block
 block discarded – undo
333 333
 	 * @param string $email
334 334
 	 * @return DataResponse
335 335
 	 */
336
-	public function create($username, $password, array $groups=array(), $email='') {
337
-		if($email !== '' && !$this->mailer->validateMailAddress($email)) {
336
+	public function create($username, $password, array $groups = array(), $email = '') {
337
+		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
338 338
 			return new DataResponse(
339 339
 				array(
340
-					'message' => (string)$this->l10n->t('Invalid mail address')
340
+					'message' => (string) $this->l10n->t('Invalid mail address')
341 341
 				),
342 342
 				Http::STATUS_UNPROCESSABLE_ENTITY
343 343
 			);
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 			if (!empty($groups)) {
350 350
 				foreach ($groups as $key => $group) {
351 351
 					$groupObject = $this->groupManager->get($group);
352
-					if($groupObject === null) {
352
+					if ($groupObject === null) {
353 353
 						unset($groups[$key]);
354 354
 						continue;
355 355
 					}
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 		if ($this->userManager->userExists($username)) {
374 374
 			return new DataResponse(
375 375
 				array(
376
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
376
+					'message' => (string) $this->l10n->t('A user with that name already exists.')
377 377
 				),
378 378
 				Http::STATUS_CONFLICT
379 379
 			);
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 			if ($email === '') {
385 385
 				return new DataResponse(
386 386
 					array(
387
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
387
+						'message' => (string) $this->l10n->t('To send a password link to the user an email address is required.')
388 388
 					),
389 389
 					Http::STATUS_UNPROCESSABLE_ENTITY
390 390
 				);
@@ -409,12 +409,12 @@  discard block
 block discarded – undo
409 409
 			);
410 410
 		}
411 411
 
412
-		if($user instanceof IUser) {
413
-			if($groups !== null) {
414
-				foreach($groups as $groupName) {
412
+		if ($user instanceof IUser) {
413
+			if ($groups !== null) {
414
+				foreach ($groups as $groupName) {
415 415
 					$group = $this->groupManager->get($groupName);
416 416
 
417
-					if(empty($group)) {
417
+					if (empty($group)) {
418 418
 						$group = $this->groupManager->createGroup($groupName);
419 419
 					}
420 420
 					$group->addUser($user);
@@ -423,19 +423,19 @@  discard block
 block discarded – undo
423 423
 			/**
424 424
 			 * Send new user mail only if a mail is set
425 425
 			 */
426
-			if($email !== '') {
426
+			if ($email !== '') {
427 427
 				$user->setEMailAddress($email);
428 428
 
429 429
 				if ($generatedPassword) {
430 430
 					$token = $this->secureRandom->generate(
431 431
 						21,
432
-						ISecureRandom::CHAR_DIGITS .
433
-						ISecureRandom::CHAR_LOWER .
432
+						ISecureRandom::CHAR_DIGITS.
433
+						ISecureRandom::CHAR_LOWER.
434 434
 						ISecureRandom::CHAR_UPPER
435 435
 					);
436
-					$tokenValue = $this->timeFactory->getTime() . ':' . $token;
436
+					$tokenValue = $this->timeFactory->getTime().':'.$token;
437 437
 					$mailAddress = !is_null($user->getEMailAddress()) ? $user->getEMailAddress() : '';
438
-					$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress . $this->config->getSystemValue('secret'));
438
+					$encryptedValue = $this->crypto->encrypt($tokenValue, $mailAddress.$this->config->getSystemValue('secret'));
439 439
 					$this->config->setUserValue($username, 'core', 'lostpassword', $encryptedValue);
440 440
 
441 441
 					$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', ['userId' => $username, 'token' => $token]);
@@ -465,8 +465,8 @@  discard block
 block discarded – undo
465 465
 					$message->setPlainBody($plainTextMailContent);
466 466
 					$message->setFrom([$this->fromMailAddress => $this->defaults->getName()]);
467 467
 					$this->mailer->send($message);
468
-				} catch(\Exception $e) {
469
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
468
+				} catch (\Exception $e) {
469
+					$this->log->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
470 470
 				}
471 471
 			}
472 472
 			// fetch users groups
@@ -480,7 +480,7 @@  discard block
 block discarded – undo
480 480
 
481 481
 		return new DataResponse(
482 482
 			array(
483
-				'message' => (string)$this->l10n->t('Unable to create user.')
483
+				'message' => (string) $this->l10n->t('Unable to create user.')
484 484
 			),
485 485
 			Http::STATUS_FORBIDDEN
486 486
 		);
@@ -498,32 +498,32 @@  discard block
 block discarded – undo
498 498
 		$userId = $this->userSession->getUser()->getUID();
499 499
 		$user = $this->userManager->get($id);
500 500
 
501
-		if($userId === $id) {
501
+		if ($userId === $id) {
502 502
 			return new DataResponse(
503 503
 				array(
504 504
 					'status' => 'error',
505 505
 					'data' => array(
506
-						'message' => (string)$this->l10n->t('Unable to delete user.')
506
+						'message' => (string) $this->l10n->t('Unable to delete user.')
507 507
 					)
508 508
 				),
509 509
 				Http::STATUS_FORBIDDEN
510 510
 			);
511 511
 		}
512 512
 
513
-		if(!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
513
+		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
514 514
 			return new DataResponse(
515 515
 				array(
516 516
 					'status' => 'error',
517 517
 					'data' => array(
518
-						'message' => (string)$this->l10n->t('Authentication error')
518
+						'message' => (string) $this->l10n->t('Authentication error')
519 519
 					)
520 520
 				),
521 521
 				Http::STATUS_FORBIDDEN
522 522
 			);
523 523
 		}
524 524
 
525
-		if($user) {
526
-			if($user->delete()) {
525
+		if ($user) {
526
+			if ($user->delete()) {
527 527
 				return new DataResponse(
528 528
 					array(
529 529
 						'status' => 'success',
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
 			array(
541 541
 				'status' => 'error',
542 542
 				'data' => array(
543
-					'message' => (string)$this->l10n->t('Unable to delete user.')
543
+					'message' => (string) $this->l10n->t('Unable to delete user.')
544 544
 				)
545 545
 			),
546 546
 			Http::STATUS_FORBIDDEN
@@ -582,12 +582,12 @@  discard block
 block discarded – undo
582 582
 									$twitterScope
583 583
 	) {
584 584
 
585
-		if(!empty($email) && !$this->mailer->validateMailAddress($email)) {
585
+		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
586 586
 			return new DataResponse(
587 587
 				array(
588 588
 					'status' => 'error',
589 589
 					'data' => array(
590
-						'message' => (string)$this->l10n->t('Invalid mail address')
590
+						'message' => (string) $this->l10n->t('Invalid mail address')
591 591
 					)
592 592
 				),
593 593
 				Http::STATUS_UNPROCESSABLE_ENTITY
@@ -622,7 +622,7 @@  discard block
 block discarded – undo
622 622
 						'websiteScope' => $websiteScope,
623 623
 						'address' => $address,
624 624
 						'addressScope' => $addressScope,
625
-						'message' => (string)$this->l10n->t('Settings saved')
625
+						'message' => (string) $this->l10n->t('Settings saved')
626 626
 					)
627 627
 				),
628 628
 				Http::STATUS_OK
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$uniqueUsers = [];
701 701
 			foreach ($groups as $group) {
702
-				foreach($group->getUsers() as $uid => $displayName) {
702
+				foreach ($group->getUsers() as $uid => $displayName) {
703 703
 					$uniqueUsers[$uid] = true;
704 704
 				}
705 705
 			}
@@ -793,19 +793,19 @@  discard block
 block discarded – undo
793 793
 				array(
794 794
 					'status' => 'error',
795 795
 					'data' => array(
796
-						'message' => (string)$this->l10n->t('Forbidden')
796
+						'message' => (string) $this->l10n->t('Forbidden')
797 797
 					)
798 798
 				),
799 799
 				Http::STATUS_FORBIDDEN
800 800
 			);
801 801
 		}
802 802
 
803
-		if($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
803
+		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
804 804
 			return new DataResponse(
805 805
 				array(
806 806
 					'status' => 'error',
807 807
 					'data' => array(
808
-						'message' => (string)$this->l10n->t('Invalid mail address')
808
+						'message' => (string) $this->l10n->t('Invalid mail address')
809 809
 					)
810 810
 				),
811 811
 				Http::STATUS_UNPROCESSABLE_ENTITY
@@ -817,7 +817,7 @@  discard block
 block discarded – undo
817 817
 				array(
818 818
 					'status' => 'error',
819 819
 					'data' => array(
820
-						'message' => (string)$this->l10n->t('Invalid user')
820
+						'message' => (string) $this->l10n->t('Invalid user')
821 821
 					)
822 822
 				),
823 823
 				Http::STATUS_UNPROCESSABLE_ENTITY
@@ -830,7 +830,7 @@  discard block
 block discarded – undo
830 830
 				array(
831 831
 					'status' => 'error',
832 832
 					'data' => array(
833
-						'message' => (string)$this->l10n->t('Unable to change mail address')
833
+						'message' => (string) $this->l10n->t('Unable to change mail address')
834 834
 					)
835 835
 				),
836 836
 				Http::STATUS_FORBIDDEN
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 					'data' => array(
849 849
 						'username' => $id,
850 850
 						'mailAddress' => $mailAddress,
851
-						'message' => (string)$this->l10n->t('Email saved')
851
+						'message' => (string) $this->l10n->t('Email saved')
852 852
 					)
853 853
 				),
854 854
 				Http::STATUS_OK
Please login to merge, or discard this patch.
apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -20,7 +20,6 @@
 block discarded – undo
20 20
  */
21 21
 namespace OCA\DAV\CalDAV\Publishing\Xml;
22 22
 
23
-use OCA\DAV\CalDAV\Publishing\PublishPlugin as Plugin;
24 23
 use Sabre\Xml\Writer;
25 24
 use Sabre\Xml\XmlSerializable;
26 25
 
Please login to merge, or discard this patch.
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -26,58 +26,58 @@
 block discarded – undo
26 26
 
27 27
 class Publisher implements XmlSerializable {
28 28
 
29
-	/**
30
-	 * @var string $publishUrl
31
-	 */
32
-	protected $publishUrl;
29
+    /**
30
+     * @var string $publishUrl
31
+     */
32
+    protected $publishUrl;
33 33
 
34
-	/**
35
-	 * @var boolean $isPublished
36
-	 */
37
-	protected $isPublished;
34
+    /**
35
+     * @var boolean $isPublished
36
+     */
37
+    protected $isPublished;
38 38
 
39
-	/**
40
-	 * @param string $publishUrl
41
-	 * @param boolean $isPublished
42
-	 */
43
-	function __construct($publishUrl, $isPublished) {
44
-		$this->publishUrl = $publishUrl;
45
-		$this->isPublished = $isPublished;
46
-	}
39
+    /**
40
+     * @param string $publishUrl
41
+     * @param boolean $isPublished
42
+     */
43
+    function __construct($publishUrl, $isPublished) {
44
+        $this->publishUrl = $publishUrl;
45
+        $this->isPublished = $isPublished;
46
+    }
47 47
 
48
-	/**
49
-	 * @return string
50
-	 */
51
-	function getValue() {
52
-		return $this->publishUrl;
53
-	}
48
+    /**
49
+     * @return string
50
+     */
51
+    function getValue() {
52
+        return $this->publishUrl;
53
+    }
54 54
 
55
-	/**
56
-	 * The xmlSerialize metod is called during xml writing.
57
-	 *
58
-	 * Use the $writer argument to write its own xml serialization.
59
-	 *
60
-	 * An important note: do _not_ create a parent element. Any element
61
-	 * implementing XmlSerializble should only ever write what's considered
62
-	 * its 'inner xml'.
63
-	 *
64
-	 * The parent of the current element is responsible for writing a
65
-	 * containing element.
66
-	 *
67
-	 * This allows serializers to be re-used for different element names.
68
-	 *
69
-	 * If you are opening new elements, you must also close them again.
70
-	 *
71
-	 * @param Writer $writer
72
-	 * @return void
73
-	 */
74
-	function xmlSerialize(Writer $writer) {
75
-		if (!$this->isPublished) {
76
-			// for pre-publish-url
77
-			$writer->write($this->publishUrl);
78
-		} else {
79
-			// for publish-url
80
-			$writer->writeElement('{DAV:}href', $this->publishUrl);
81
-		}
82
-	}
55
+    /**
56
+     * The xmlSerialize metod is called during xml writing.
57
+     *
58
+     * Use the $writer argument to write its own xml serialization.
59
+     *
60
+     * An important note: do _not_ create a parent element. Any element
61
+     * implementing XmlSerializble should only ever write what's considered
62
+     * its 'inner xml'.
63
+     *
64
+     * The parent of the current element is responsible for writing a
65
+     * containing element.
66
+     *
67
+     * This allows serializers to be re-used for different element names.
68
+     *
69
+     * If you are opening new elements, you must also close them again.
70
+     *
71
+     * @param Writer $writer
72
+     * @return void
73
+     */
74
+    function xmlSerialize(Writer $writer) {
75
+        if (!$this->isPublished) {
76
+            // for pre-publish-url
77
+            $writer->write($this->publishUrl);
78
+        } else {
79
+            // for publish-url
80
+            $writer->writeElement('{DAV:}href', $this->publishUrl);
81
+        }
82
+    }
83 83
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/FilesPlugin.php 4 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -31,7 +31,6 @@
 block discarded – undo
31 31
 namespace OCA\DAV\Connector\Sabre;
32 32
 
33 33
 use OC\Files\View;
34
-use OCA\DAV\Upload\FutureFile;
35 34
 use OCP\Files\ForbiddenException;
36 35
 use OCP\IPreview;
37 36
 use Sabre\DAV\Exception\Forbidden;
Please login to merge, or discard this patch.
Indentation   +384 added lines, -384 removed lines patch added patch discarded remove patch
@@ -51,388 +51,388 @@
 block discarded – undo
51 51
 
52 52
 class FilesPlugin extends ServerPlugin {
53 53
 
54
-	// namespace
55
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
56
-	const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
57
-	const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
58
-	const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
59
-	const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
60
-	const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
61
-	const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
62
-	const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
63
-	const GETETAG_PROPERTYNAME = '{DAV:}getetag';
64
-	const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
65
-	const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
66
-	const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
67
-	const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
68
-	const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
69
-	const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
70
-
71
-	/**
72
-	 * Reference to main server object
73
-	 *
74
-	 * @var \Sabre\DAV\Server
75
-	 */
76
-	private $server;
77
-
78
-	/**
79
-	 * @var Tree
80
-	 */
81
-	private $tree;
82
-
83
-	/**
84
-	 * Whether this is public webdav.
85
-	 * If true, some returned information will be stripped off.
86
-	 *
87
-	 * @var bool
88
-	 */
89
-	private $isPublic;
90
-
91
-	/**
92
-	 * @var View
93
-	 */
94
-	private $fileView;
95
-
96
-	/**
97
-	 * @var bool
98
-	 */
99
-	private $downloadAttachment;
100
-
101
-	/**
102
-	 * @var IConfig
103
-	 */
104
-	private $config;
105
-
106
-	/**
107
-	 * @var IRequest
108
-	 */
109
-	private $request;
110
-
111
-	/**
112
-	 * @var IPreview
113
-	 */
114
-	private $previewManager;
115
-
116
-	/**
117
-	 * @param Tree $tree
118
-	 * @param IConfig $config
119
-	 * @param IRequest $request
120
-	 * @param IPreview $previewManager
121
-	 * @param bool $isPublic
122
-	 * @param bool $downloadAttachment
123
-	 */
124
-	public function __construct(Tree $tree,
125
-								IConfig $config,
126
-								IRequest $request,
127
-								IPreview $previewManager,
128
-								$isPublic = false,
129
-								$downloadAttachment = true) {
130
-		$this->tree = $tree;
131
-		$this->config = $config;
132
-		$this->request = $request;
133
-		$this->isPublic = $isPublic;
134
-		$this->downloadAttachment = $downloadAttachment;
135
-		$this->previewManager = $previewManager;
136
-	}
137
-
138
-	/**
139
-	 * This initializes the plugin.
140
-	 *
141
-	 * This function is called by \Sabre\DAV\Server, after
142
-	 * addPlugin is called.
143
-	 *
144
-	 * This method should set up the required event subscriptions.
145
-	 *
146
-	 * @param \Sabre\DAV\Server $server
147
-	 * @return void
148
-	 */
149
-	public function initialize(\Sabre\DAV\Server $server) {
150
-
151
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
152
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
153
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
154
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
155
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
156
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
157
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
158
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
159
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
160
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
161
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
162
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
163
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
164
-
165
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
166
-		$allowedProperties = ['{DAV:}getetag'];
167
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
168
-
169
-		$this->server = $server;
170
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
171
-		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172
-		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173
-		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
175
-		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176
-		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
177
-			$body = $response->getBody();
178
-			if (is_resource($body)) {
179
-				fclose($body);
180
-			}
181
-		});
182
-		$this->server->on('beforeMove', [$this, 'checkMove']);
183
-	}
184
-
185
-	/**
186
-	 * Plugin that checks if a move can actually be performed.
187
-	 *
188
-	 * @param string $source source path
189
-	 * @param string $destination destination path
190
-	 * @throws Forbidden
191
-	 * @throws NotFound
192
-	 */
193
-	function checkMove($source, $destination) {
194
-		$sourceNode = $this->tree->getNodeForPath($source);
195
-		if (!$sourceNode instanceof Node) {
196
-			return;
197
-		}
198
-		list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
199
-		list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
200
-
201
-		if ($sourceDir !== $destinationDir) {
202
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
203
-			if (is_null($sourceNodeFileInfo)) {
204
-				throw new NotFound($source . ' does not exist');
205
-			}
206
-
207
-			if (!$sourceNodeFileInfo->isDeletable()) {
208
-				throw new Forbidden($source . " cannot be deleted");
209
-			}
210
-		}
211
-	}
212
-
213
-	/**
214
-	 * This sets a cookie to be able to recognize the start of the download
215
-	 * the content must not be longer than 32 characters and must only contain
216
-	 * alphanumeric characters
217
-	 *
218
-	 * @param RequestInterface $request
219
-	 * @param ResponseInterface $response
220
-	 */
221
-	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
222
-		$queryParams = $request->getQueryParameters();
223
-
224
-		/**
225
-		 * this sets a cookie to be able to recognize the start of the download
226
-		 * the content must not be longer than 32 characters and must only contain
227
-		 * alphanumeric characters
228
-		 */
229
-		if (isset($queryParams['downloadStartSecret'])) {
230
-			$token = $queryParams['downloadStartSecret'];
231
-			if (!isset($token[32])
232
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
233
-				// FIXME: use $response->setHeader() instead
234
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
235
-			}
236
-		}
237
-	}
238
-
239
-	/**
240
-	 * Add headers to file download
241
-	 *
242
-	 * @param RequestInterface $request
243
-	 * @param ResponseInterface $response
244
-	 */
245
-	function httpGet(RequestInterface $request, ResponseInterface $response) {
246
-		// Only handle valid files
247
-		$node = $this->tree->getNodeForPath($request->getPath());
248
-		if (!($node instanceof IFile)) return;
249
-
250
-		// adds a 'Content-Disposition: attachment' header in case no disposition
251
-		// header has been set before
252
-		if ($this->downloadAttachment &&
253
-			$response->getHeader('Content-Disposition') === null) {
254
-			$filename = $node->getName();
255
-			if ($this->request->isUserAgent(
256
-				[
257
-					\OC\AppFramework\Http\Request::USER_AGENT_IE,
258
-					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
259
-					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
260
-				])) {
261
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
262
-			} else {
263
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
264
-													 . '; filename="' . rawurlencode($filename) . '"');
265
-			}
266
-		}
267
-
268
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
269
-			//Add OC-Checksum header
270
-			/** @var $node File */
271
-			$checksum = $node->getChecksum();
272
-			if ($checksum !== null && $checksum !== '') {
273
-				$response->addHeader('OC-Checksum', $checksum);
274
-			}
275
-		}
276
-	}
277
-
278
-	/**
279
-	 * Adds all ownCloud-specific properties
280
-	 *
281
-	 * @param PropFind $propFind
282
-	 * @param \Sabre\DAV\INode $node
283
-	 * @return void
284
-	 */
285
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
286
-
287
-		$httpRequest = $this->server->httpRequest;
288
-
289
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
290
-
291
-			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
292
-				return $node->getFileId();
293
-			});
294
-
295
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
296
-				return $node->getInternalFileId();
297
-			});
298
-
299
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
300
-				$perms = $node->getDavPermissions();
301
-				if ($this->isPublic) {
302
-					// remove mount information
303
-					$perms = str_replace(['S', 'M'], '', $perms);
304
-				}
305
-				return $perms;
306
-			});
307
-
308
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
309
-				return $node->getSharePermissions(
310
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
311
-				);
312
-			});
313
-
314
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
315
-				return $node->getETag();
316
-			});
317
-
318
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
319
-				$owner = $node->getOwner();
320
-				return $owner->getUID();
321
-			});
322
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
323
-				$owner = $node->getOwner();
324
-				$displayName = $owner->getDisplayName();
325
-				return $displayName;
326
-			});
327
-
328
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
329
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
330
-			});
331
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
332
-				return $node->getSize();
333
-			});
334
-		}
335
-
336
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
337
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
338
-				return $this->config->getSystemValue('data-fingerprint', '');
339
-			});
340
-		}
341
-
342
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
343
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
344
-				/** @var $node \OCA\DAV\Connector\Sabre\File */
345
-				try {
346
-					$directDownloadUrl = $node->getDirectDownload();
347
-					if (isset($directDownloadUrl['url'])) {
348
-						return $directDownloadUrl['url'];
349
-					}
350
-				} catch (StorageNotAvailableException $e) {
351
-					return false;
352
-				} catch (ForbiddenException $e) {
353
-					return false;
354
-				}
355
-				return false;
356
-			});
357
-
358
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
359
-				$checksum = $node->getChecksum();
360
-				if ($checksum === NULL || $checksum === '') {
361
-					return null;
362
-				}
363
-
364
-				return new ChecksumList($checksum);
365
-			});
366
-
367
-		}
368
-
369
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
370
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
371
-				return $node->getSize();
372
-			});
373
-		}
374
-	}
375
-
376
-	/**
377
-	 * Update ownCloud-specific properties
378
-	 *
379
-	 * @param string $path
380
-	 * @param PropPatch $propPatch
381
-	 *
382
-	 * @return void
383
-	 */
384
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
385
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($path) {
386
-			if (empty($time)) {
387
-				return false;
388
-			}
389
-			$node = $this->tree->getNodeForPath($path);
390
-			if (is_null($node)) {
391
-				return 404;
392
-			}
393
-			$node->touch($time);
394
-			return true;
395
-		});
396
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($path) {
397
-			if (empty($etag)) {
398
-				return false;
399
-			}
400
-			$node = $this->tree->getNodeForPath($path);
401
-			if (is_null($node)) {
402
-				return 404;
403
-			}
404
-			if ($node->setEtag($etag) !== -1) {
405
-				return true;
406
-			}
407
-			return false;
408
-		});
409
-	}
410
-
411
-	/**
412
-	 * @param string $filePath
413
-	 * @param \Sabre\DAV\INode $node
414
-	 * @throws \Sabre\DAV\Exception\BadRequest
415
-	 */
416
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
417
-		// chunked upload handling
418
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
419
-			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
420
-			$info = \OC_FileChunking::decodeName($name);
421
-			if (!empty($info)) {
422
-				$filePath = $path . '/' . $info['name'];
423
-			}
424
-		}
425
-
426
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
427
-		if (!$this->server->tree->nodeExists($filePath)) {
428
-			return;
429
-		}
430
-		$node = $this->server->tree->getNodeForPath($filePath);
431
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
432
-			$fileId = $node->getFileId();
433
-			if (!is_null($fileId)) {
434
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
435
-			}
436
-		}
437
-	}
54
+    // namespace
55
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
56
+    const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
57
+    const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
58
+    const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
59
+    const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
60
+    const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
61
+    const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
62
+    const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
63
+    const GETETAG_PROPERTYNAME = '{DAV:}getetag';
64
+    const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
65
+    const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
66
+    const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
67
+    const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
68
+    const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
69
+    const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
70
+
71
+    /**
72
+     * Reference to main server object
73
+     *
74
+     * @var \Sabre\DAV\Server
75
+     */
76
+    private $server;
77
+
78
+    /**
79
+     * @var Tree
80
+     */
81
+    private $tree;
82
+
83
+    /**
84
+     * Whether this is public webdav.
85
+     * If true, some returned information will be stripped off.
86
+     *
87
+     * @var bool
88
+     */
89
+    private $isPublic;
90
+
91
+    /**
92
+     * @var View
93
+     */
94
+    private $fileView;
95
+
96
+    /**
97
+     * @var bool
98
+     */
99
+    private $downloadAttachment;
100
+
101
+    /**
102
+     * @var IConfig
103
+     */
104
+    private $config;
105
+
106
+    /**
107
+     * @var IRequest
108
+     */
109
+    private $request;
110
+
111
+    /**
112
+     * @var IPreview
113
+     */
114
+    private $previewManager;
115
+
116
+    /**
117
+     * @param Tree $tree
118
+     * @param IConfig $config
119
+     * @param IRequest $request
120
+     * @param IPreview $previewManager
121
+     * @param bool $isPublic
122
+     * @param bool $downloadAttachment
123
+     */
124
+    public function __construct(Tree $tree,
125
+                                IConfig $config,
126
+                                IRequest $request,
127
+                                IPreview $previewManager,
128
+                                $isPublic = false,
129
+                                $downloadAttachment = true) {
130
+        $this->tree = $tree;
131
+        $this->config = $config;
132
+        $this->request = $request;
133
+        $this->isPublic = $isPublic;
134
+        $this->downloadAttachment = $downloadAttachment;
135
+        $this->previewManager = $previewManager;
136
+    }
137
+
138
+    /**
139
+     * This initializes the plugin.
140
+     *
141
+     * This function is called by \Sabre\DAV\Server, after
142
+     * addPlugin is called.
143
+     *
144
+     * This method should set up the required event subscriptions.
145
+     *
146
+     * @param \Sabre\DAV\Server $server
147
+     * @return void
148
+     */
149
+    public function initialize(\Sabre\DAV\Server $server) {
150
+
151
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
152
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
153
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
154
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
155
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
156
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
157
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
158
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
159
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
160
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
161
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
162
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
163
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
164
+
165
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
166
+        $allowedProperties = ['{DAV:}getetag'];
167
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
168
+
169
+        $this->server = $server;
170
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
171
+        $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172
+        $this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173
+        $this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
175
+        $this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176
+        $this->server->on('afterResponse', function($request, ResponseInterface $response) {
177
+            $body = $response->getBody();
178
+            if (is_resource($body)) {
179
+                fclose($body);
180
+            }
181
+        });
182
+        $this->server->on('beforeMove', [$this, 'checkMove']);
183
+    }
184
+
185
+    /**
186
+     * Plugin that checks if a move can actually be performed.
187
+     *
188
+     * @param string $source source path
189
+     * @param string $destination destination path
190
+     * @throws Forbidden
191
+     * @throws NotFound
192
+     */
193
+    function checkMove($source, $destination) {
194
+        $sourceNode = $this->tree->getNodeForPath($source);
195
+        if (!$sourceNode instanceof Node) {
196
+            return;
197
+        }
198
+        list($sourceDir,) = \Sabre\HTTP\URLUtil::splitPath($source);
199
+        list($destinationDir,) = \Sabre\HTTP\URLUtil::splitPath($destination);
200
+
201
+        if ($sourceDir !== $destinationDir) {
202
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
203
+            if (is_null($sourceNodeFileInfo)) {
204
+                throw new NotFound($source . ' does not exist');
205
+            }
206
+
207
+            if (!$sourceNodeFileInfo->isDeletable()) {
208
+                throw new Forbidden($source . " cannot be deleted");
209
+            }
210
+        }
211
+    }
212
+
213
+    /**
214
+     * This sets a cookie to be able to recognize the start of the download
215
+     * the content must not be longer than 32 characters and must only contain
216
+     * alphanumeric characters
217
+     *
218
+     * @param RequestInterface $request
219
+     * @param ResponseInterface $response
220
+     */
221
+    function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
222
+        $queryParams = $request->getQueryParameters();
223
+
224
+        /**
225
+         * this sets a cookie to be able to recognize the start of the download
226
+         * the content must not be longer than 32 characters and must only contain
227
+         * alphanumeric characters
228
+         */
229
+        if (isset($queryParams['downloadStartSecret'])) {
230
+            $token = $queryParams['downloadStartSecret'];
231
+            if (!isset($token[32])
232
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
233
+                // FIXME: use $response->setHeader() instead
234
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
235
+            }
236
+        }
237
+    }
238
+
239
+    /**
240
+     * Add headers to file download
241
+     *
242
+     * @param RequestInterface $request
243
+     * @param ResponseInterface $response
244
+     */
245
+    function httpGet(RequestInterface $request, ResponseInterface $response) {
246
+        // Only handle valid files
247
+        $node = $this->tree->getNodeForPath($request->getPath());
248
+        if (!($node instanceof IFile)) return;
249
+
250
+        // adds a 'Content-Disposition: attachment' header in case no disposition
251
+        // header has been set before
252
+        if ($this->downloadAttachment &&
253
+            $response->getHeader('Content-Disposition') === null) {
254
+            $filename = $node->getName();
255
+            if ($this->request->isUserAgent(
256
+                [
257
+                    \OC\AppFramework\Http\Request::USER_AGENT_IE,
258
+                    \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
259
+                    \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
260
+                ])) {
261
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
262
+            } else {
263
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
264
+                                                        . '; filename="' . rawurlencode($filename) . '"');
265
+            }
266
+        }
267
+
268
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
269
+            //Add OC-Checksum header
270
+            /** @var $node File */
271
+            $checksum = $node->getChecksum();
272
+            if ($checksum !== null && $checksum !== '') {
273
+                $response->addHeader('OC-Checksum', $checksum);
274
+            }
275
+        }
276
+    }
277
+
278
+    /**
279
+     * Adds all ownCloud-specific properties
280
+     *
281
+     * @param PropFind $propFind
282
+     * @param \Sabre\DAV\INode $node
283
+     * @return void
284
+     */
285
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
286
+
287
+        $httpRequest = $this->server->httpRequest;
288
+
289
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
290
+
291
+            $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
292
+                return $node->getFileId();
293
+            });
294
+
295
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
296
+                return $node->getInternalFileId();
297
+            });
298
+
299
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
300
+                $perms = $node->getDavPermissions();
301
+                if ($this->isPublic) {
302
+                    // remove mount information
303
+                    $perms = str_replace(['S', 'M'], '', $perms);
304
+                }
305
+                return $perms;
306
+            });
307
+
308
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
309
+                return $node->getSharePermissions(
310
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
311
+                );
312
+            });
313
+
314
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
315
+                return $node->getETag();
316
+            });
317
+
318
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
319
+                $owner = $node->getOwner();
320
+                return $owner->getUID();
321
+            });
322
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
323
+                $owner = $node->getOwner();
324
+                $displayName = $owner->getDisplayName();
325
+                return $displayName;
326
+            });
327
+
328
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
329
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
330
+            });
331
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
332
+                return $node->getSize();
333
+            });
334
+        }
335
+
336
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
337
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
338
+                return $this->config->getSystemValue('data-fingerprint', '');
339
+            });
340
+        }
341
+
342
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
343
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
344
+                /** @var $node \OCA\DAV\Connector\Sabre\File */
345
+                try {
346
+                    $directDownloadUrl = $node->getDirectDownload();
347
+                    if (isset($directDownloadUrl['url'])) {
348
+                        return $directDownloadUrl['url'];
349
+                    }
350
+                } catch (StorageNotAvailableException $e) {
351
+                    return false;
352
+                } catch (ForbiddenException $e) {
353
+                    return false;
354
+                }
355
+                return false;
356
+            });
357
+
358
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
359
+                $checksum = $node->getChecksum();
360
+                if ($checksum === NULL || $checksum === '') {
361
+                    return null;
362
+                }
363
+
364
+                return new ChecksumList($checksum);
365
+            });
366
+
367
+        }
368
+
369
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
370
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
371
+                return $node->getSize();
372
+            });
373
+        }
374
+    }
375
+
376
+    /**
377
+     * Update ownCloud-specific properties
378
+     *
379
+     * @param string $path
380
+     * @param PropPatch $propPatch
381
+     *
382
+     * @return void
383
+     */
384
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
385
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($path) {
386
+            if (empty($time)) {
387
+                return false;
388
+            }
389
+            $node = $this->tree->getNodeForPath($path);
390
+            if (is_null($node)) {
391
+                return 404;
392
+            }
393
+            $node->touch($time);
394
+            return true;
395
+        });
396
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($path) {
397
+            if (empty($etag)) {
398
+                return false;
399
+            }
400
+            $node = $this->tree->getNodeForPath($path);
401
+            if (is_null($node)) {
402
+                return 404;
403
+            }
404
+            if ($node->setEtag($etag) !== -1) {
405
+                return true;
406
+            }
407
+            return false;
408
+        });
409
+    }
410
+
411
+    /**
412
+     * @param string $filePath
413
+     * @param \Sabre\DAV\INode $node
414
+     * @throws \Sabre\DAV\Exception\BadRequest
415
+     */
416
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
417
+        // chunked upload handling
418
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
419
+            list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
420
+            $info = \OC_FileChunking::decodeName($name);
421
+            if (!empty($info)) {
422
+                $filePath = $path . '/' . $info['name'];
423
+            }
424
+        }
425
+
426
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
427
+        if (!$this->server->tree->nodeExists($filePath)) {
428
+            return;
429
+        }
430
+        $node = $this->server->tree->getNodeForPath($filePath);
431
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
432
+            $fileId = $node->getFileId();
433
+            if (!is_null($fileId)) {
434
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
435
+            }
436
+        }
437
+    }
438 438
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
172 172
 		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
173 173
 		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
174
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
174
+		$this->server->on('afterMethod:GET', [$this, 'httpGet']);
175 175
 		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
176 176
 		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
177 177
 			$body = $response->getBody();
@@ -201,11 +201,11 @@  discard block
 block discarded – undo
201 201
 		if ($sourceDir !== $destinationDir) {
202 202
 			$sourceNodeFileInfo = $sourceNode->getFileInfo();
203 203
 			if (is_null($sourceNodeFileInfo)) {
204
-				throw new NotFound($source . ' does not exist');
204
+				throw new NotFound($source.' does not exist');
205 205
 			}
206 206
 
207 207
 			if (!$sourceNodeFileInfo->isDeletable()) {
208
-				throw new Forbidden($source . " cannot be deleted");
208
+				throw new Forbidden($source." cannot be deleted");
209 209
 			}
210 210
 		}
211 211
 	}
@@ -258,10 +258,10 @@  discard block
 block discarded – undo
258 258
 					\OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
259 259
 					\OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
260 260
 				])) {
261
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
261
+				$response->addHeader('Content-Disposition', 'attachment; filename="'.rawurlencode($filename).'"');
262 262
 			} else {
263
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
264
-													 . '; filename="' . rawurlencode($filename) . '"');
263
+				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\''.rawurlencode($filename)
264
+													 . '; filename="'.rawurlencode($filename).'"');
265 265
 			}
266 266
 		}
267 267
 
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 				return $displayName;
326 326
 			});
327 327
 
328
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
328
+			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function() use ($node) {
329 329
 				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
330 330
 			});
331 331
 			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
@@ -419,7 +419,7 @@  discard block
 block discarded – undo
419 419
 			list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($filePath);
420 420
 			$info = \OC_FileChunking::decodeName($name);
421 421
 			if (!empty($info)) {
422
-				$filePath = $path . '/' . $info['name'];
422
+				$filePath = $path.'/'.$info['name'];
423 423
 			}
424 424
 		}
425 425
 
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -245,7 +245,9 @@
 block discarded – undo
245 245
 	function httpGet(RequestInterface $request, ResponseInterface $response) {
246 246
 		// Only handle valid files
247 247
 		$node = $this->tree->getNodeForPath($request->getPath());
248
-		if (!($node instanceof IFile)) return;
248
+		if (!($node instanceof IFile)) {
249
+		    return;
250
+		}
249 251
 
250 252
 		// adds a 'Content-Disposition: attachment' header in case no disposition
251 253
 		// header has been set before
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.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -37,122 +37,122 @@
 block discarded – undo
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39 39
 class FTP extends StreamWrapper{
40
-	private $password;
41
-	private $user;
42
-	private $host;
43
-	private $secure;
44
-	private $root;
40
+    private $password;
41
+    private $user;
42
+    private $host;
43
+    private $secure;
44
+    private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+    private static $tempFiles=array();
47 47
 
48
-	public function __construct($params) {
49
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
53
-			if (isset($params['secure'])) {
54
-				$this->secure = $params['secure'];
55
-			} else {
56
-				$this->secure = false;
57
-			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!='/') {
60
-				$this->root='/'.$this->root;
61
-			}
62
-			if (substr($this->root, -1) !== '/') {
63
-				$this->root .= '/';
64
-			}
65
-		} else {
66
-			throw new \Exception('Creating FTP storage failed');
67
-		}
48
+    public function __construct($params) {
49
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
+            $this->host=$params['host'];
51
+            $this->user=$params['user'];
52
+            $this->password=$params['password'];
53
+            if (isset($params['secure'])) {
54
+                $this->secure = $params['secure'];
55
+            } else {
56
+                $this->secure = false;
57
+            }
58
+            $this->root=isset($params['root'])?$params['root']:'/';
59
+            if ( ! $this->root || $this->root[0]!='/') {
60
+                $this->root='/'.$this->root;
61
+            }
62
+            if (substr($this->root, -1) !== '/') {
63
+                $this->root .= '/';
64
+            }
65
+        } else {
66
+            throw new \Exception('Creating FTP storage failed');
67
+        }
68 68
 		
69
-	}
69
+    }
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
73
-	}
71
+    public function getId(){
72
+        return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
73
+    }
74 74
 
75
-	/**
76
-	 * construct the ftp url
77
-	 * @param string $path
78
-	 * @return string
79
-	 */
80
-	public function constructUrl($path) {
81
-		$url='ftp';
82
-		if ($this->secure) {
83
-			$url.='s';
84
-		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
-		return $url;
87
-	}
75
+    /**
76
+     * construct the ftp url
77
+     * @param string $path
78
+     * @return string
79
+     */
80
+    public function constructUrl($path) {
81
+        $url='ftp';
82
+        if ($this->secure) {
83
+            $url.='s';
84
+        }
85
+        $url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
+        return $url;
87
+    }
88 88
 
89
-	/**
90
-	 * Unlinks file or directory
91
-	 * @param string $path
92
-	 */
93
-	public function unlink($path) {
94
-		if ($this->is_dir($path)) {
95
-			return $this->rmdir($path);
96
-		}
97
-		else {
98
-			$url = $this->constructUrl($path);
99
-			$result = unlink($url);
100
-			clearstatcache(true, $url);
101
-			return $result;
102
-		}
103
-	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
106
-			case 'r':
107
-			case 'rb':
108
-			case 'w':
109
-			case 'wb':
110
-			case 'a':
111
-			case 'ab':
112
-				//these are supported by the wrapper
113
-				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
114
-				$handle = fopen($this->constructUrl($path), $mode, false, $context);
115
-				return RetryWrapper::wrap($handle);
116
-			case 'r+':
117
-			case 'w+':
118
-			case 'wb+':
119
-			case 'a+':
120
-			case 'x':
121
-			case 'x+':
122
-			case 'c':
123
-			case 'c+':
124
-				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
127
-				} else {
128
-					$ext='';
129
-				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
131
-				if ($this->file_exists($path)) {
132
-					$this->getFile($path, $tmpFile);
133
-				}
134
-				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
-					$this->writeBack($tmpFile, $path);
137
-				});
138
-		}
139
-		return false;
140
-	}
89
+    /**
90
+     * Unlinks file or directory
91
+     * @param string $path
92
+     */
93
+    public function unlink($path) {
94
+        if ($this->is_dir($path)) {
95
+            return $this->rmdir($path);
96
+        }
97
+        else {
98
+            $url = $this->constructUrl($path);
99
+            $result = unlink($url);
100
+            clearstatcache(true, $url);
101
+            return $result;
102
+        }
103
+    }
104
+    public function fopen($path,$mode) {
105
+        switch($mode) {
106
+            case 'r':
107
+            case 'rb':
108
+            case 'w':
109
+            case 'wb':
110
+            case 'a':
111
+            case 'ab':
112
+                //these are supported by the wrapper
113
+                $context = stream_context_create(array('ftp' => array('overwrite' => true)));
114
+                $handle = fopen($this->constructUrl($path), $mode, false, $context);
115
+                return RetryWrapper::wrap($handle);
116
+            case 'r+':
117
+            case 'w+':
118
+            case 'wb+':
119
+            case 'a+':
120
+            case 'x':
121
+            case 'x+':
122
+            case 'c':
123
+            case 'c+':
124
+                //emulate these
125
+                if (strrpos($path, '.')!==false) {
126
+                    $ext=substr($path, strrpos($path, '.'));
127
+                } else {
128
+                    $ext='';
129
+                }
130
+                $tmpFile=\OCP\Files::tmpFile($ext);
131
+                if ($this->file_exists($path)) {
132
+                    $this->getFile($path, $tmpFile);
133
+                }
134
+                $handle = fopen($tmpFile, $mode);
135
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
+                    $this->writeBack($tmpFile, $path);
137
+                });
138
+        }
139
+        return false;
140
+    }
141 141
 
142
-	public function writeBack($tmpFile, $path) {
143
-		$this->uploadFile($tmpFile, $path);
144
-		unlink($tmpFile);
145
-	}
142
+    public function writeBack($tmpFile, $path) {
143
+        $this->uploadFile($tmpFile, $path);
144
+        unlink($tmpFile);
145
+    }
146 146
 
147
-	/**
148
-	 * check if php-ftp is installed
149
-	 */
150
-	public static function checkDependencies() {
151
-		if (function_exists('ftp_login')) {
152
-			return(true);
153
-		} else {
154
-			return array('ftp');
155
-		}
156
-	}
147
+    /**
148
+     * check if php-ftp is installed
149
+     */
150
+    public static function checkDependencies() {
151
+        if (function_exists('ftp_login')) {
152
+            return(true);
153
+        } else {
154
+            return array('ftp');
155
+        }
156
+    }
157 157
 
158 158
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -36,28 +36,28 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\CallbackWrapper;
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39
-class FTP extends StreamWrapper{
39
+class FTP extends StreamWrapper {
40 40
 	private $password;
41 41
 	private $user;
42 42
 	private $host;
43 43
 	private $secure;
44 44
 	private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+	private static $tempFiles = array();
47 47
 
48 48
 	public function __construct($params) {
49 49
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
50
+			$this->host = $params['host'];
51
+			$this->user = $params['user'];
52
+			$this->password = $params['password'];
53 53
 			if (isset($params['secure'])) {
54 54
 				$this->secure = $params['secure'];
55 55
 			} else {
56 56
 				$this->secure = false;
57 57
 			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!='/') {
60
-				$this->root='/'.$this->root;
58
+			$this->root = isset($params['root']) ? $params['root'] : '/';
59
+			if (!$this->root || $this->root[0] != '/') {
60
+				$this->root = '/'.$this->root;
61 61
 			}
62 62
 			if (substr($this->root, -1) !== '/') {
63 63
 				$this->root .= '/';
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 		
69 69
 	}
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
71
+	public function getId() {
72
+		return 'ftp::'.$this->user.'@'.$this->host.'/'.$this->root;
73 73
 	}
74 74
 
75 75
 	/**
@@ -78,11 +78,11 @@  discard block
 block discarded – undo
78 78
 	 * @return string
79 79
 	 */
80 80
 	public function constructUrl($path) {
81
-		$url='ftp';
81
+		$url = 'ftp';
82 82
 		if ($this->secure) {
83
-			$url.='s';
83
+			$url .= 's';
84 84
 		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
85
+		$url .= '://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86 86
 		return $url;
87 87
 	}
88 88
 
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
 			return $result;
102 102
 		}
103 103
 	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
104
+	public function fopen($path, $mode) {
105
+		switch ($mode) {
106 106
 			case 'r':
107 107
 			case 'rb':
108 108
 			case 'w':
@@ -122,17 +122,17 @@  discard block
 block discarded – undo
122 122
 			case 'c':
123 123
 			case 'c+':
124 124
 				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
125
+				if (strrpos($path, '.') !== false) {
126
+					$ext = substr($path, strrpos($path, '.'));
127 127
 				} else {
128
-					$ext='';
128
+					$ext = '';
129 129
 				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
130
+				$tmpFile = \OCP\Files::tmpFile($ext);
131 131
 				if ($this->file_exists($path)) {
132 132
 					$this->getFile($path, $tmpFile);
133 133
 				}
134 134
 				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
135
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
136 136
 					$this->writeBack($tmpFile, $path);
137 137
 				});
138 138
 		}
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.
apps/files_external/lib/Lib/Storage/Swift.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -616,6 +616,9 @@
 block discarded – undo
616 616
 		return $this->container;
617 617
 	}
618 618
 
619
+	/**
620
+	 * @param string $path
621
+	 */
619 622
 	public function writeBack($tmpFile, $path) {
620 623
 		$fileData = fopen($tmpFile, 'r');
621 624
 		$this->getContainer()->uploadObject($path, $fileData);
Please login to merge, or discard this patch.
Indentation   +604 added lines, -604 removed lines patch added patch discarded remove patch
@@ -48,609 +48,609 @@
 block discarded – undo
48 48
 
49 49
 class Swift extends \OC\Files\Storage\Common {
50 50
 
51
-	/**
52
-	 * @var \OpenCloud\ObjectStore\Service
53
-	 */
54
-	private $connection;
55
-	/**
56
-	 * @var \OpenCloud\ObjectStore\Resource\Container
57
-	 */
58
-	private $container;
59
-	/**
60
-	 * @var \OpenCloud\OpenStack
61
-	 */
62
-	private $anchor;
63
-	/**
64
-	 * @var string
65
-	 */
66
-	private $bucket;
67
-	/**
68
-	 * Connection parameters
69
-	 *
70
-	 * @var array
71
-	 */
72
-	private $params;
73
-
74
-	/** @var string  */
75
-	private $id;
76
-
77
-	/**
78
-	 * @var array
79
-	 */
80
-	private static $tmpFiles = array();
81
-
82
-	/**
83
-	 * Key value cache mapping path to data object. Maps path to
84
-	 * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
-	 * paths and path to false for not existing paths.
86
-	 * @var \OCP\ICache
87
-	 */
88
-	private $objectCache;
89
-
90
-	/**
91
-	 * @param string $path
92
-	 */
93
-	private function normalizePath($path) {
94
-		$path = trim($path, '/');
95
-
96
-		if (!$path) {
97
-			$path = '.';
98
-		}
99
-
100
-		$path = str_replace('#', '%23', $path);
101
-
102
-		return $path;
103
-	}
104
-
105
-	const SUBCONTAINER_FILE = '.subcontainers';
106
-
107
-	/**
108
-	 * translate directory path to container name
109
-	 *
110
-	 * @param string $path
111
-	 * @return string
112
-	 */
113
-
114
-	/**
115
-	 * Fetches an object from the API.
116
-	 * If the object is cached already or a
117
-	 * failed "doesn't exist" response was cached,
118
-	 * that one will be returned.
119
-	 *
120
-	 * @param string $path
121
-	 * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
-	 * or false if the object did not exist
123
-	 */
124
-	private function fetchObject($path) {
125
-		if ($this->objectCache->hasKey($path)) {
126
-			// might be "false" if object did not exist from last check
127
-			return $this->objectCache->get($path);
128
-		}
129
-		try {
130
-			$object = $this->getContainer()->getPartialObject($path);
131
-			$this->objectCache->set($path, $object);
132
-			return $object;
133
-		} catch (ClientErrorResponseException $e) {
134
-			// this exception happens when the object does not exist, which
135
-			// is expected in most cases
136
-			$this->objectCache->set($path, false);
137
-			return false;
138
-		} catch (ClientErrorResponseException $e) {
139
-			// Expected response is "404 Not Found", so only log if it isn't
140
-			if ($e->getResponse()->getStatusCode() !== 404) {
141
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
-			}
143
-			return false;
144
-		}
145
-	}
146
-
147
-	/**
148
-	 * Returns whether the given path exists.
149
-	 *
150
-	 * @param string $path
151
-	 *
152
-	 * @return bool true if the object exist, false otherwise
153
-	 */
154
-	private function doesObjectExist($path) {
155
-		return $this->fetchObject($path) !== false;
156
-	}
157
-
158
-	public function __construct($params) {
159
-		if ((empty($params['key']) and empty($params['password']))
160
-			or empty($params['user']) or empty($params['bucket'])
161
-			or empty($params['region'])
162
-		) {
163
-			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
-		}
165
-
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
-
168
-		$bucketUrl = Url::factory($params['bucket']);
169
-		if ($bucketUrl->isAbsolute()) {
170
-			$this->bucket = end(($bucketUrl->getPathSegments()));
171
-			$params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
-		} else {
173
-			$this->bucket = $params['bucket'];
174
-		}
175
-
176
-		if (empty($params['url'])) {
177
-			$params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
-		}
179
-
180
-		if (empty($params['service_name'])) {
181
-			$params['service_name'] = 'cloudFiles';
182
-		}
183
-
184
-		$this->params = $params;
185
-		// FIXME: private class...
186
-		$this->objectCache = new \OC\Cache\CappedMemoryCache();
187
-	}
188
-
189
-	public function mkdir($path) {
190
-		$path = $this->normalizePath($path);
191
-
192
-		if ($this->is_dir($path)) {
193
-			return false;
194
-		}
195
-
196
-		if ($path !== '.') {
197
-			$path .= '/';
198
-		}
199
-
200
-		try {
201
-			$customHeaders = array('content-type' => 'httpd/unix-directory');
202
-			$metadataHeaders = DataObject::stockHeaders(array());
203
-			$allHeaders = $customHeaders + $metadataHeaders;
204
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
205
-			// invalidate so that the next access gets the real object
206
-			// with all properties
207
-			$this->objectCache->remove($path);
208
-		} catch (Exceptions\CreateUpdateError $e) {
209
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
-			return false;
211
-		}
212
-
213
-		return true;
214
-	}
215
-
216
-	public function file_exists($path) {
217
-		$path = $this->normalizePath($path);
218
-
219
-		if ($path !== '.' && $this->is_dir($path)) {
220
-			$path .= '/';
221
-		}
222
-
223
-		return $this->doesObjectExist($path);
224
-	}
225
-
226
-	public function rmdir($path) {
227
-		$path = $this->normalizePath($path);
228
-
229
-		if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
-			return false;
231
-		}
232
-
233
-		$dh = $this->opendir($path);
234
-		while ($file = readdir($dh)) {
235
-			if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
-				continue;
237
-			}
238
-
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
241
-			} else {
242
-				$this->unlink($path . '/' . $file);
243
-			}
244
-		}
245
-
246
-		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
249
-		} catch (Exceptions\DeleteError $e) {
250
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
-			return false;
252
-		}
253
-
254
-		return true;
255
-	}
256
-
257
-	public function opendir($path) {
258
-		$path = $this->normalizePath($path);
259
-
260
-		if ($path === '.') {
261
-			$path = '';
262
-		} else {
263
-			$path .= '/';
264
-		}
265
-
266
-		$path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
-
268
-		try {
269
-			$files = array();
270
-			/** @var OpenCloud\Common\Collection $objects */
271
-			$objects = $this->getContainer()->objectList(array(
272
-				'prefix' => $path,
273
-				'delimiter' => '/'
274
-			));
275
-
276
-			/** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
-			foreach ($objects as $object) {
278
-				$file = basename($object->getName());
279
-				if ($file !== basename($path)) {
280
-					$files[] = $file;
281
-				}
282
-			}
283
-
284
-			return IteratorDirectory::wrap($files);
285
-		} catch (\Exception $e) {
286
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
-			return false;
288
-		}
289
-
290
-	}
291
-
292
-	public function stat($path) {
293
-		$path = $this->normalizePath($path);
294
-
295
-		if ($path === '.') {
296
-			$path = '';
297
-		} else if ($this->is_dir($path)) {
298
-			$path .= '/';
299
-		}
300
-
301
-		try {
302
-			/** @var DataObject $object */
303
-			$object = $this->fetchObject($path);
304
-			if (!$object) {
305
-				return false;
306
-			}
307
-		} catch (ClientErrorResponseException $e) {
308
-			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
-			return false;
310
-		}
311
-
312
-		$dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
-		if ($dateTime !== false) {
314
-			$mtime = $dateTime->getTimestamp();
315
-		} else {
316
-			$mtime = null;
317
-		}
318
-		$objectMetadata = $object->getMetadata();
319
-		$metaTimestamp = $objectMetadata->getProperty('timestamp');
320
-		if (isset($metaTimestamp)) {
321
-			$mtime = $metaTimestamp;
322
-		}
323
-
324
-		if (!empty($mtime)) {
325
-			$mtime = floor($mtime);
326
-		}
327
-
328
-		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
330
-		$stat['mtime'] = $mtime;
331
-		$stat['atime'] = time();
332
-		return $stat;
333
-	}
334
-
335
-	public function filetype($path) {
336
-		$path = $this->normalizePath($path);
337
-
338
-		if ($path !== '.' && $this->doesObjectExist($path)) {
339
-			return 'file';
340
-		}
341
-
342
-		if ($path !== '.') {
343
-			$path .= '/';
344
-		}
345
-
346
-		if ($this->doesObjectExist($path)) {
347
-			return 'dir';
348
-		}
349
-	}
350
-
351
-	public function unlink($path) {
352
-		$path = $this->normalizePath($path);
353
-
354
-		if ($this->is_dir($path)) {
355
-			return $this->rmdir($path);
356
-		}
357
-
358
-		try {
359
-			$this->getContainer()->dataObject()->setName($path)->delete();
360
-			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
362
-		} catch (ClientErrorResponseException $e) {
363
-			if ($e->getResponse()->getStatusCode() !== 404) {
364
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
-			}
366
-			return false;
367
-		}
368
-
369
-		return true;
370
-	}
371
-
372
-	public function fopen($path, $mode) {
373
-		$path = $this->normalizePath($path);
374
-
375
-		switch ($mode) {
376
-			case 'r':
377
-			case 'rb':
378
-				try {
379
-					$c = $this->getContainer();
380
-					$streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
381
-					$streamInterface = $streamFactory->fromRequest(
382
-						$c->getClient()
383
-							->get($c->getUrl($path)));
384
-					$streamInterface->rewind();
385
-					$stream = $streamInterface->getStream();
386
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
387
-					if(!strrpos($streamInterface
388
-						->getMetaData('wrapper_data')[0], '404 Not Found')) {
389
-						return $stream;
390
-					}
391
-					return false;
392
-				} catch (\Guzzle\Http\Exception\BadResponseException $e) {
393
-					\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
394
-					return false;
395
-				}
396
-			case 'w':
397
-			case 'wb':
398
-			case 'a':
399
-			case 'ab':
400
-			case 'r+':
401
-			case 'w+':
402
-			case 'wb+':
403
-			case 'a+':
404
-			case 'x':
405
-			case 'x+':
406
-			case 'c':
407
-			case 'c+':
408
-				if (strrpos($path, '.') !== false) {
409
-					$ext = substr($path, strrpos($path, '.'));
410
-				} else {
411
-					$ext = '';
412
-				}
413
-				$tmpFile = \OCP\Files::tmpFile($ext);
414
-				// Fetch existing file if required
415
-				if ($mode[0] !== 'w' && $this->file_exists($path)) {
416
-					if ($mode[0] === 'x') {
417
-						// File cannot already exist
418
-						return false;
419
-					}
420
-					$source = $this->fopen($path, 'r');
421
-					file_put_contents($tmpFile, $source);
422
-					// Seek to end if required
423
-					if ($mode[0] === 'a') {
424
-						fseek($tmpFile, 0, SEEK_END);
425
-					}
426
-				}
427
-				$handle = fopen($tmpFile, $mode);
428
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
429
-					$this->writeBack($tmpFile, $path);
430
-				});
431
-		}
432
-	}
433
-
434
-	public function touch($path, $mtime = null) {
435
-		$path = $this->normalizePath($path);
436
-		if (is_null($mtime)) {
437
-			$mtime = time();
438
-		}
439
-		$metadata = array('timestamp' => $mtime);
440
-		if ($this->file_exists($path)) {
441
-			if ($this->is_dir($path) && $path != '.') {
442
-				$path .= '/';
443
-			}
444
-
445
-			$object = $this->fetchObject($path);
446
-			if ($object->saveMetadata($metadata)) {
447
-				// invalidate target object to force repopulation on fetch
448
-				$this->objectCache->remove($path);
449
-			}
450
-			return true;
451
-		} else {
452
-			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
453
-			$customHeaders = array('content-type' => $mimeType);
454
-			$metadataHeaders = DataObject::stockHeaders($metadata);
455
-			$allHeaders = $customHeaders + $metadataHeaders;
456
-			$this->getContainer()->uploadObject($path, '', $allHeaders);
457
-			// invalidate target object to force repopulation on fetch
458
-			$this->objectCache->remove($path);
459
-			return true;
460
-		}
461
-	}
462
-
463
-	public function copy($path1, $path2) {
464
-		$path1 = $this->normalizePath($path1);
465
-		$path2 = $this->normalizePath($path2);
466
-
467
-		$fileType = $this->filetype($path1);
468
-		if ($fileType === 'file') {
469
-
470
-			// make way
471
-			$this->unlink($path2);
472
-
473
-			try {
474
-				$source = $this->fetchObject($path1);
475
-				$source->copy($this->bucket . '/' . $path2);
476
-				// invalidate target object to force repopulation on fetch
477
-				$this->objectCache->remove($path2);
478
-				$this->objectCache->remove($path2 . '/');
479
-			} catch (ClientErrorResponseException $e) {
480
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481
-				return false;
482
-			}
483
-
484
-		} else if ($fileType === 'dir') {
485
-
486
-			// make way
487
-			$this->unlink($path2);
488
-
489
-			try {
490
-				$source = $this->fetchObject($path1 . '/');
491
-				$source->copy($this->bucket . '/' . $path2 . '/');
492
-				// invalidate target object to force repopulation on fetch
493
-				$this->objectCache->remove($path2);
494
-				$this->objectCache->remove($path2 . '/');
495
-			} catch (ClientErrorResponseException $e) {
496
-				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497
-				return false;
498
-			}
499
-
500
-			$dh = $this->opendir($path1);
501
-			while ($file = readdir($dh)) {
502
-				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
503
-					continue;
504
-				}
505
-
506
-				$source = $path1 . '/' . $file;
507
-				$target = $path2 . '/' . $file;
508
-				$this->copy($source, $target);
509
-			}
510
-
511
-		} else {
512
-			//file does not exist
513
-			return false;
514
-		}
515
-
516
-		return true;
517
-	}
518
-
519
-	public function rename($path1, $path2) {
520
-		$path1 = $this->normalizePath($path1);
521
-		$path2 = $this->normalizePath($path2);
522
-
523
-		$fileType = $this->filetype($path1);
524
-
525
-		if ($fileType === 'dir' || $fileType === 'file') {
526
-			// copy
527
-			if ($this->copy($path1, $path2) === false) {
528
-				return false;
529
-			}
530
-
531
-			// cleanup
532
-			if ($this->unlink($path1) === false) {
533
-				$this->unlink($path2);
534
-				return false;
535
-			}
536
-
537
-			return true;
538
-		}
539
-
540
-		return false;
541
-	}
542
-
543
-	public function getId() {
544
-		return $this->id;
545
-	}
546
-
547
-	/**
548
-	 * Returns the connection
549
-	 *
550
-	 * @return OpenCloud\ObjectStore\Service connected client
551
-	 * @throws \Exception if connection could not be made
552
-	 */
553
-	public function getConnection() {
554
-		if (!is_null($this->connection)) {
555
-			return $this->connection;
556
-		}
557
-
558
-		$settings = array(
559
-			'username' => $this->params['user'],
560
-		);
561
-
562
-		if (!empty($this->params['password'])) {
563
-			$settings['password'] = $this->params['password'];
564
-		} else if (!empty($this->params['key'])) {
565
-			$settings['apiKey'] = $this->params['key'];
566
-		}
567
-
568
-		if (!empty($this->params['tenant'])) {
569
-			$settings['tenantName'] = $this->params['tenant'];
570
-		}
571
-
572
-		if (!empty($this->params['timeout'])) {
573
-			$settings['timeout'] = $this->params['timeout'];
574
-		}
575
-
576
-		if (isset($settings['apiKey'])) {
577
-			$this->anchor = new Rackspace($this->params['url'], $settings);
578
-		} else {
579
-			$this->anchor = new OpenStack($this->params['url'], $settings);
580
-		}
581
-
582
-		$connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
583
-
584
-		if (!empty($this->params['endpoint_url'])) {
585
-			$endpoint = $connection->getEndpoint();
586
-			$endpoint->setPublicUrl($this->params['endpoint_url']);
587
-			$endpoint->setPrivateUrl($this->params['endpoint_url']);
588
-			$connection->setEndpoint($endpoint);
589
-		}
590
-
591
-		$this->connection = $connection;
592
-
593
-		return $this->connection;
594
-	}
595
-
596
-	/**
597
-	 * Returns the initialized object store container.
598
-	 *
599
-	 * @return OpenCloud\ObjectStore\Resource\Container
600
-	 */
601
-	public function getContainer() {
602
-		if (!is_null($this->container)) {
603
-			return $this->container;
604
-		}
605
-
606
-		try {
607
-			$this->container = $this->getConnection()->getContainer($this->bucket);
608
-		} catch (ClientErrorResponseException $e) {
609
-			$this->container = $this->getConnection()->createContainer($this->bucket);
610
-		}
611
-
612
-		if (!$this->file_exists('.')) {
613
-			$this->mkdir('.');
614
-		}
615
-
616
-		return $this->container;
617
-	}
618
-
619
-	public function writeBack($tmpFile, $path) {
620
-		$fileData = fopen($tmpFile, 'r');
621
-		$this->getContainer()->uploadObject($path, $fileData);
622
-		// invalidate target object to force repopulation on fetch
623
-		$this->objectCache->remove(self::$tmpFiles[$tmpFile]);
624
-		unlink($tmpFile);
625
-	}
626
-
627
-	public function hasUpdated($path, $time) {
628
-		if ($this->is_file($path)) {
629
-			return parent::hasUpdated($path, $time);
630
-		}
631
-		$path = $this->normalizePath($path);
632
-		$dh = $this->opendir($path);
633
-		$content = array();
634
-		while (($file = readdir($dh)) !== false) {
635
-			$content[] = $file;
636
-		}
637
-		if ($path === '.') {
638
-			$path = '';
639
-		}
640
-		$cachedContent = $this->getCache()->getFolderContents($path);
641
-		$cachedNames = array_map(function ($content) {
642
-			return $content['name'];
643
-		}, $cachedContent);
644
-		sort($cachedNames);
645
-		sort($content);
646
-		return $cachedNames != $content;
647
-	}
648
-
649
-	/**
650
-	 * check if curl is installed
651
-	 */
652
-	public static function checkDependencies() {
653
-		return true;
654
-	}
51
+    /**
52
+     * @var \OpenCloud\ObjectStore\Service
53
+     */
54
+    private $connection;
55
+    /**
56
+     * @var \OpenCloud\ObjectStore\Resource\Container
57
+     */
58
+    private $container;
59
+    /**
60
+     * @var \OpenCloud\OpenStack
61
+     */
62
+    private $anchor;
63
+    /**
64
+     * @var string
65
+     */
66
+    private $bucket;
67
+    /**
68
+     * Connection parameters
69
+     *
70
+     * @var array
71
+     */
72
+    private $params;
73
+
74
+    /** @var string  */
75
+    private $id;
76
+
77
+    /**
78
+     * @var array
79
+     */
80
+    private static $tmpFiles = array();
81
+
82
+    /**
83
+     * Key value cache mapping path to data object. Maps path to
84
+     * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
85
+     * paths and path to false for not existing paths.
86
+     * @var \OCP\ICache
87
+     */
88
+    private $objectCache;
89
+
90
+    /**
91
+     * @param string $path
92
+     */
93
+    private function normalizePath($path) {
94
+        $path = trim($path, '/');
95
+
96
+        if (!$path) {
97
+            $path = '.';
98
+        }
99
+
100
+        $path = str_replace('#', '%23', $path);
101
+
102
+        return $path;
103
+    }
104
+
105
+    const SUBCONTAINER_FILE = '.subcontainers';
106
+
107
+    /**
108
+     * translate directory path to container name
109
+     *
110
+     * @param string $path
111
+     * @return string
112
+     */
113
+
114
+    /**
115
+     * Fetches an object from the API.
116
+     * If the object is cached already or a
117
+     * failed "doesn't exist" response was cached,
118
+     * that one will be returned.
119
+     *
120
+     * @param string $path
121
+     * @return \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject|bool object
122
+     * or false if the object did not exist
123
+     */
124
+    private function fetchObject($path) {
125
+        if ($this->objectCache->hasKey($path)) {
126
+            // might be "false" if object did not exist from last check
127
+            return $this->objectCache->get($path);
128
+        }
129
+        try {
130
+            $object = $this->getContainer()->getPartialObject($path);
131
+            $this->objectCache->set($path, $object);
132
+            return $object;
133
+        } catch (ClientErrorResponseException $e) {
134
+            // this exception happens when the object does not exist, which
135
+            // is expected in most cases
136
+            $this->objectCache->set($path, false);
137
+            return false;
138
+        } catch (ClientErrorResponseException $e) {
139
+            // Expected response is "404 Not Found", so only log if it isn't
140
+            if ($e->getResponse()->getStatusCode() !== 404) {
141
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
142
+            }
143
+            return false;
144
+        }
145
+    }
146
+
147
+    /**
148
+     * Returns whether the given path exists.
149
+     *
150
+     * @param string $path
151
+     *
152
+     * @return bool true if the object exist, false otherwise
153
+     */
154
+    private function doesObjectExist($path) {
155
+        return $this->fetchObject($path) !== false;
156
+    }
157
+
158
+    public function __construct($params) {
159
+        if ((empty($params['key']) and empty($params['password']))
160
+            or empty($params['user']) or empty($params['bucket'])
161
+            or empty($params['region'])
162
+        ) {
163
+            throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164
+        }
165
+
166
+        $this->id = 'swift::' . $params['user'] . md5($params['bucket']);
167
+
168
+        $bucketUrl = Url::factory($params['bucket']);
169
+        if ($bucketUrl->isAbsolute()) {
170
+            $this->bucket = end(($bucketUrl->getPathSegments()));
171
+            $params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
172
+        } else {
173
+            $this->bucket = $params['bucket'];
174
+        }
175
+
176
+        if (empty($params['url'])) {
177
+            $params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
178
+        }
179
+
180
+        if (empty($params['service_name'])) {
181
+            $params['service_name'] = 'cloudFiles';
182
+        }
183
+
184
+        $this->params = $params;
185
+        // FIXME: private class...
186
+        $this->objectCache = new \OC\Cache\CappedMemoryCache();
187
+    }
188
+
189
+    public function mkdir($path) {
190
+        $path = $this->normalizePath($path);
191
+
192
+        if ($this->is_dir($path)) {
193
+            return false;
194
+        }
195
+
196
+        if ($path !== '.') {
197
+            $path .= '/';
198
+        }
199
+
200
+        try {
201
+            $customHeaders = array('content-type' => 'httpd/unix-directory');
202
+            $metadataHeaders = DataObject::stockHeaders(array());
203
+            $allHeaders = $customHeaders + $metadataHeaders;
204
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
205
+            // invalidate so that the next access gets the real object
206
+            // with all properties
207
+            $this->objectCache->remove($path);
208
+        } catch (Exceptions\CreateUpdateError $e) {
209
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
210
+            return false;
211
+        }
212
+
213
+        return true;
214
+    }
215
+
216
+    public function file_exists($path) {
217
+        $path = $this->normalizePath($path);
218
+
219
+        if ($path !== '.' && $this->is_dir($path)) {
220
+            $path .= '/';
221
+        }
222
+
223
+        return $this->doesObjectExist($path);
224
+    }
225
+
226
+    public function rmdir($path) {
227
+        $path = $this->normalizePath($path);
228
+
229
+        if (!$this->is_dir($path) || !$this->isDeletable($path)) {
230
+            return false;
231
+        }
232
+
233
+        $dh = $this->opendir($path);
234
+        while ($file = readdir($dh)) {
235
+            if (\OC\Files\Filesystem::isIgnoredDir($file)) {
236
+                continue;
237
+            }
238
+
239
+            if ($this->is_dir($path . '/' . $file)) {
240
+                $this->rmdir($path . '/' . $file);
241
+            } else {
242
+                $this->unlink($path . '/' . $file);
243
+            }
244
+        }
245
+
246
+        try {
247
+            $this->getContainer()->dataObject()->setName($path . '/')->delete();
248
+            $this->objectCache->remove($path . '/');
249
+        } catch (Exceptions\DeleteError $e) {
250
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251
+            return false;
252
+        }
253
+
254
+        return true;
255
+    }
256
+
257
+    public function opendir($path) {
258
+        $path = $this->normalizePath($path);
259
+
260
+        if ($path === '.') {
261
+            $path = '';
262
+        } else {
263
+            $path .= '/';
264
+        }
265
+
266
+        $path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #
267
+
268
+        try {
269
+            $files = array();
270
+            /** @var OpenCloud\Common\Collection $objects */
271
+            $objects = $this->getContainer()->objectList(array(
272
+                'prefix' => $path,
273
+                'delimiter' => '/'
274
+            ));
275
+
276
+            /** @var OpenCloud\ObjectStore\Resource\DataObject $object */
277
+            foreach ($objects as $object) {
278
+                $file = basename($object->getName());
279
+                if ($file !== basename($path)) {
280
+                    $files[] = $file;
281
+                }
282
+            }
283
+
284
+            return IteratorDirectory::wrap($files);
285
+        } catch (\Exception $e) {
286
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
287
+            return false;
288
+        }
289
+
290
+    }
291
+
292
+    public function stat($path) {
293
+        $path = $this->normalizePath($path);
294
+
295
+        if ($path === '.') {
296
+            $path = '';
297
+        } else if ($this->is_dir($path)) {
298
+            $path .= '/';
299
+        }
300
+
301
+        try {
302
+            /** @var DataObject $object */
303
+            $object = $this->fetchObject($path);
304
+            if (!$object) {
305
+                return false;
306
+            }
307
+        } catch (ClientErrorResponseException $e) {
308
+            \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
309
+            return false;
310
+        }
311
+
312
+        $dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
313
+        if ($dateTime !== false) {
314
+            $mtime = $dateTime->getTimestamp();
315
+        } else {
316
+            $mtime = null;
317
+        }
318
+        $objectMetadata = $object->getMetadata();
319
+        $metaTimestamp = $objectMetadata->getProperty('timestamp');
320
+        if (isset($metaTimestamp)) {
321
+            $mtime = $metaTimestamp;
322
+        }
323
+
324
+        if (!empty($mtime)) {
325
+            $mtime = floor($mtime);
326
+        }
327
+
328
+        $stat = array();
329
+        $stat['size'] = (int)$object->getContentLength();
330
+        $stat['mtime'] = $mtime;
331
+        $stat['atime'] = time();
332
+        return $stat;
333
+    }
334
+
335
+    public function filetype($path) {
336
+        $path = $this->normalizePath($path);
337
+
338
+        if ($path !== '.' && $this->doesObjectExist($path)) {
339
+            return 'file';
340
+        }
341
+
342
+        if ($path !== '.') {
343
+            $path .= '/';
344
+        }
345
+
346
+        if ($this->doesObjectExist($path)) {
347
+            return 'dir';
348
+        }
349
+    }
350
+
351
+    public function unlink($path) {
352
+        $path = $this->normalizePath($path);
353
+
354
+        if ($this->is_dir($path)) {
355
+            return $this->rmdir($path);
356
+        }
357
+
358
+        try {
359
+            $this->getContainer()->dataObject()->setName($path)->delete();
360
+            $this->objectCache->remove($path);
361
+            $this->objectCache->remove($path . '/');
362
+        } catch (ClientErrorResponseException $e) {
363
+            if ($e->getResponse()->getStatusCode() !== 404) {
364
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
365
+            }
366
+            return false;
367
+        }
368
+
369
+        return true;
370
+    }
371
+
372
+    public function fopen($path, $mode) {
373
+        $path = $this->normalizePath($path);
374
+
375
+        switch ($mode) {
376
+            case 'r':
377
+            case 'rb':
378
+                try {
379
+                    $c = $this->getContainer();
380
+                    $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
381
+                    $streamInterface = $streamFactory->fromRequest(
382
+                        $c->getClient()
383
+                            ->get($c->getUrl($path)));
384
+                    $streamInterface->rewind();
385
+                    $stream = $streamInterface->getStream();
386
+                    stream_context_set_option($stream, 'swift','content', $streamInterface);
387
+                    if(!strrpos($streamInterface
388
+                        ->getMetaData('wrapper_data')[0], '404 Not Found')) {
389
+                        return $stream;
390
+                    }
391
+                    return false;
392
+                } catch (\Guzzle\Http\Exception\BadResponseException $e) {
393
+                    \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
394
+                    return false;
395
+                }
396
+            case 'w':
397
+            case 'wb':
398
+            case 'a':
399
+            case 'ab':
400
+            case 'r+':
401
+            case 'w+':
402
+            case 'wb+':
403
+            case 'a+':
404
+            case 'x':
405
+            case 'x+':
406
+            case 'c':
407
+            case 'c+':
408
+                if (strrpos($path, '.') !== false) {
409
+                    $ext = substr($path, strrpos($path, '.'));
410
+                } else {
411
+                    $ext = '';
412
+                }
413
+                $tmpFile = \OCP\Files::tmpFile($ext);
414
+                // Fetch existing file if required
415
+                if ($mode[0] !== 'w' && $this->file_exists($path)) {
416
+                    if ($mode[0] === 'x') {
417
+                        // File cannot already exist
418
+                        return false;
419
+                    }
420
+                    $source = $this->fopen($path, 'r');
421
+                    file_put_contents($tmpFile, $source);
422
+                    // Seek to end if required
423
+                    if ($mode[0] === 'a') {
424
+                        fseek($tmpFile, 0, SEEK_END);
425
+                    }
426
+                }
427
+                $handle = fopen($tmpFile, $mode);
428
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
429
+                    $this->writeBack($tmpFile, $path);
430
+                });
431
+        }
432
+    }
433
+
434
+    public function touch($path, $mtime = null) {
435
+        $path = $this->normalizePath($path);
436
+        if (is_null($mtime)) {
437
+            $mtime = time();
438
+        }
439
+        $metadata = array('timestamp' => $mtime);
440
+        if ($this->file_exists($path)) {
441
+            if ($this->is_dir($path) && $path != '.') {
442
+                $path .= '/';
443
+            }
444
+
445
+            $object = $this->fetchObject($path);
446
+            if ($object->saveMetadata($metadata)) {
447
+                // invalidate target object to force repopulation on fetch
448
+                $this->objectCache->remove($path);
449
+            }
450
+            return true;
451
+        } else {
452
+            $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
453
+            $customHeaders = array('content-type' => $mimeType);
454
+            $metadataHeaders = DataObject::stockHeaders($metadata);
455
+            $allHeaders = $customHeaders + $metadataHeaders;
456
+            $this->getContainer()->uploadObject($path, '', $allHeaders);
457
+            // invalidate target object to force repopulation on fetch
458
+            $this->objectCache->remove($path);
459
+            return true;
460
+        }
461
+    }
462
+
463
+    public function copy($path1, $path2) {
464
+        $path1 = $this->normalizePath($path1);
465
+        $path2 = $this->normalizePath($path2);
466
+
467
+        $fileType = $this->filetype($path1);
468
+        if ($fileType === 'file') {
469
+
470
+            // make way
471
+            $this->unlink($path2);
472
+
473
+            try {
474
+                $source = $this->fetchObject($path1);
475
+                $source->copy($this->bucket . '/' . $path2);
476
+                // invalidate target object to force repopulation on fetch
477
+                $this->objectCache->remove($path2);
478
+                $this->objectCache->remove($path2 . '/');
479
+            } catch (ClientErrorResponseException $e) {
480
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481
+                return false;
482
+            }
483
+
484
+        } else if ($fileType === 'dir') {
485
+
486
+            // make way
487
+            $this->unlink($path2);
488
+
489
+            try {
490
+                $source = $this->fetchObject($path1 . '/');
491
+                $source->copy($this->bucket . '/' . $path2 . '/');
492
+                // invalidate target object to force repopulation on fetch
493
+                $this->objectCache->remove($path2);
494
+                $this->objectCache->remove($path2 . '/');
495
+            } catch (ClientErrorResponseException $e) {
496
+                \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497
+                return false;
498
+            }
499
+
500
+            $dh = $this->opendir($path1);
501
+            while ($file = readdir($dh)) {
502
+                if (\OC\Files\Filesystem::isIgnoredDir($file)) {
503
+                    continue;
504
+                }
505
+
506
+                $source = $path1 . '/' . $file;
507
+                $target = $path2 . '/' . $file;
508
+                $this->copy($source, $target);
509
+            }
510
+
511
+        } else {
512
+            //file does not exist
513
+            return false;
514
+        }
515
+
516
+        return true;
517
+    }
518
+
519
+    public function rename($path1, $path2) {
520
+        $path1 = $this->normalizePath($path1);
521
+        $path2 = $this->normalizePath($path2);
522
+
523
+        $fileType = $this->filetype($path1);
524
+
525
+        if ($fileType === 'dir' || $fileType === 'file') {
526
+            // copy
527
+            if ($this->copy($path1, $path2) === false) {
528
+                return false;
529
+            }
530
+
531
+            // cleanup
532
+            if ($this->unlink($path1) === false) {
533
+                $this->unlink($path2);
534
+                return false;
535
+            }
536
+
537
+            return true;
538
+        }
539
+
540
+        return false;
541
+    }
542
+
543
+    public function getId() {
544
+        return $this->id;
545
+    }
546
+
547
+    /**
548
+     * Returns the connection
549
+     *
550
+     * @return OpenCloud\ObjectStore\Service connected client
551
+     * @throws \Exception if connection could not be made
552
+     */
553
+    public function getConnection() {
554
+        if (!is_null($this->connection)) {
555
+            return $this->connection;
556
+        }
557
+
558
+        $settings = array(
559
+            'username' => $this->params['user'],
560
+        );
561
+
562
+        if (!empty($this->params['password'])) {
563
+            $settings['password'] = $this->params['password'];
564
+        } else if (!empty($this->params['key'])) {
565
+            $settings['apiKey'] = $this->params['key'];
566
+        }
567
+
568
+        if (!empty($this->params['tenant'])) {
569
+            $settings['tenantName'] = $this->params['tenant'];
570
+        }
571
+
572
+        if (!empty($this->params['timeout'])) {
573
+            $settings['timeout'] = $this->params['timeout'];
574
+        }
575
+
576
+        if (isset($settings['apiKey'])) {
577
+            $this->anchor = new Rackspace($this->params['url'], $settings);
578
+        } else {
579
+            $this->anchor = new OpenStack($this->params['url'], $settings);
580
+        }
581
+
582
+        $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);
583
+
584
+        if (!empty($this->params['endpoint_url'])) {
585
+            $endpoint = $connection->getEndpoint();
586
+            $endpoint->setPublicUrl($this->params['endpoint_url']);
587
+            $endpoint->setPrivateUrl($this->params['endpoint_url']);
588
+            $connection->setEndpoint($endpoint);
589
+        }
590
+
591
+        $this->connection = $connection;
592
+
593
+        return $this->connection;
594
+    }
595
+
596
+    /**
597
+     * Returns the initialized object store container.
598
+     *
599
+     * @return OpenCloud\ObjectStore\Resource\Container
600
+     */
601
+    public function getContainer() {
602
+        if (!is_null($this->container)) {
603
+            return $this->container;
604
+        }
605
+
606
+        try {
607
+            $this->container = $this->getConnection()->getContainer($this->bucket);
608
+        } catch (ClientErrorResponseException $e) {
609
+            $this->container = $this->getConnection()->createContainer($this->bucket);
610
+        }
611
+
612
+        if (!$this->file_exists('.')) {
613
+            $this->mkdir('.');
614
+        }
615
+
616
+        return $this->container;
617
+    }
618
+
619
+    public function writeBack($tmpFile, $path) {
620
+        $fileData = fopen($tmpFile, 'r');
621
+        $this->getContainer()->uploadObject($path, $fileData);
622
+        // invalidate target object to force repopulation on fetch
623
+        $this->objectCache->remove(self::$tmpFiles[$tmpFile]);
624
+        unlink($tmpFile);
625
+    }
626
+
627
+    public function hasUpdated($path, $time) {
628
+        if ($this->is_file($path)) {
629
+            return parent::hasUpdated($path, $time);
630
+        }
631
+        $path = $this->normalizePath($path);
632
+        $dh = $this->opendir($path);
633
+        $content = array();
634
+        while (($file = readdir($dh)) !== false) {
635
+            $content[] = $file;
636
+        }
637
+        if ($path === '.') {
638
+            $path = '';
639
+        }
640
+        $cachedContent = $this->getCache()->getFolderContents($path);
641
+        $cachedNames = array_map(function ($content) {
642
+            return $content['name'];
643
+        }, $cachedContent);
644
+        sort($cachedNames);
645
+        sort($content);
646
+        return $cachedNames != $content;
647
+    }
648
+
649
+    /**
650
+     * check if curl is installed
651
+     */
652
+    public static function checkDependencies() {
653
+        return true;
654
+    }
655 655
 
656 656
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164 164
 		}
165 165
 
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
166
+		$this->id = 'swift::'.$params['user'].md5($params['bucket']);
167 167
 
168 168
 		$bucketUrl = Url::factory($params['bucket']);
169 169
 		if ($bucketUrl->isAbsolute()) {
@@ -236,16 +236,16 @@  discard block
 block discarded – undo
236 236
 				continue;
237 237
 			}
238 238
 
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
239
+			if ($this->is_dir($path.'/'.$file)) {
240
+				$this->rmdir($path.'/'.$file);
241 241
 			} else {
242
-				$this->unlink($path . '/' . $file);
242
+				$this->unlink($path.'/'.$file);
243 243
 			}
244 244
 		}
245 245
 
246 246
 		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
247
+			$this->getContainer()->dataObject()->setName($path.'/')->delete();
248
+			$this->objectCache->remove($path.'/');
249 249
 		} catch (Exceptions\DeleteError $e) {
250 250
 			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251 251
 			return false;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		}
327 327
 
328 328
 		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
329
+		$stat['size'] = (int) $object->getContentLength();
330 330
 		$stat['mtime'] = $mtime;
331 331
 		$stat['atime'] = time();
332 332
 		return $stat;
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 		try {
359 359
 			$this->getContainer()->dataObject()->setName($path)->delete();
360 360
 			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
361
+			$this->objectCache->remove($path.'/');
362 362
 		} catch (ClientErrorResponseException $e) {
363 363
 			if ($e->getResponse()->getStatusCode() !== 404) {
364 364
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
@@ -383,8 +383,8 @@  discard block
 block discarded – undo
383 383
 							->get($c->getUrl($path)));
384 384
 					$streamInterface->rewind();
385 385
 					$stream = $streamInterface->getStream();
386
-					stream_context_set_option($stream, 'swift','content', $streamInterface);
387
-					if(!strrpos($streamInterface
386
+					stream_context_set_option($stream, 'swift', 'content', $streamInterface);
387
+					if (!strrpos($streamInterface
388 388
 						->getMetaData('wrapper_data')[0], '404 Not Found')) {
389 389
 						return $stream;
390 390
 					}
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
 					}
426 426
 				}
427 427
 				$handle = fopen($tmpFile, $mode);
428
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
428
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
429 429
 					$this->writeBack($tmpFile, $path);
430 430
 				});
431 431
 		}
@@ -472,10 +472,10 @@  discard block
 block discarded – undo
472 472
 
473 473
 			try {
474 474
 				$source = $this->fetchObject($path1);
475
-				$source->copy($this->bucket . '/' . $path2);
475
+				$source->copy($this->bucket.'/'.$path2);
476 476
 				// invalidate target object to force repopulation on fetch
477 477
 				$this->objectCache->remove($path2);
478
-				$this->objectCache->remove($path2 . '/');
478
+				$this->objectCache->remove($path2.'/');
479 479
 			} catch (ClientErrorResponseException $e) {
480 480
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
481 481
 				return false;
@@ -487,11 +487,11 @@  discard block
 block discarded – undo
487 487
 			$this->unlink($path2);
488 488
 
489 489
 			try {
490
-				$source = $this->fetchObject($path1 . '/');
491
-				$source->copy($this->bucket . '/' . $path2 . '/');
490
+				$source = $this->fetchObject($path1.'/');
491
+				$source->copy($this->bucket.'/'.$path2.'/');
492 492
 				// invalidate target object to force repopulation on fetch
493 493
 				$this->objectCache->remove($path2);
494
-				$this->objectCache->remove($path2 . '/');
494
+				$this->objectCache->remove($path2.'/');
495 495
 			} catch (ClientErrorResponseException $e) {
496 496
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
497 497
 				return false;
@@ -503,8 +503,8 @@  discard block
 block discarded – undo
503 503
 					continue;
504 504
 				}
505 505
 
506
-				$source = $path1 . '/' . $file;
507
-				$target = $path2 . '/' . $file;
506
+				$source = $path1.'/'.$file;
507
+				$target = $path2.'/'.$file;
508 508
 				$this->copy($source, $target);
509 509
 			}
510 510
 
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 			$path = '';
639 639
 		}
640 640
 		$cachedContent = $this->getCache()->getFolderContents($path);
641
-		$cachedNames = array_map(function ($content) {
641
+		$cachedNames = array_map(function($content) {
642 642
 			return $content['name'];
643 643
 		}, $cachedContent);
644 644
 		sort($cachedNames);
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -64,558 +64,558 @@
 block discarded – undo
64 64
  */
65 65
 class ShareController extends Controller {
66 66
 
67
-	/** @var IConfig */
68
-	protected $config;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IUserManager */
72
-	protected $userManager;
73
-	/** @var ILogger */
74
-	protected $logger;
75
-	/** @var \OCP\Activity\IManager */
76
-	protected $activityManager;
77
-	/** @var \OCP\Share\IManager */
78
-	protected $shareManager;
79
-	/** @var ISession */
80
-	protected $session;
81
-	/** @var IPreview */
82
-	protected $previewManager;
83
-	/** @var IRootFolder */
84
-	protected $rootFolder;
85
-	/** @var FederatedShareProvider */
86
-	protected $federatedShareProvider;
87
-	/** @var EventDispatcherInterface */
88
-	protected $eventDispatcher;
89
-	/** @var IL10N */
90
-	protected $l10n;
91
-	/** @var Defaults */
92
-	protected $defaults;
93
-
94
-	/**
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param IConfig $config
98
-	 * @param IURLGenerator $urlGenerator
99
-	 * @param IUserManager $userManager
100
-	 * @param ILogger $logger
101
-	 * @param \OCP\Activity\IManager $activityManager
102
-	 * @param \OCP\Share\IManager $shareManager
103
-	 * @param ISession $session
104
-	 * @param IPreview $previewManager
105
-	 * @param IRootFolder $rootFolder
106
-	 * @param FederatedShareProvider $federatedShareProvider
107
-	 * @param EventDispatcherInterface $eventDispatcher
108
-	 * @param IL10N $l10n
109
-	 * @param \OC_Defaults $defaults
110
-	 */
111
-	public function __construct($appName,
112
-								IRequest $request,
113
-								IConfig $config,
114
-								IURLGenerator $urlGenerator,
115
-								IUserManager $userManager,
116
-								ILogger $logger,
117
-								\OCP\Activity\IManager $activityManager,
118
-								\OCP\Share\IManager $shareManager,
119
-								ISession $session,
120
-								IPreview $previewManager,
121
-								IRootFolder $rootFolder,
122
-								FederatedShareProvider $federatedShareProvider,
123
-								EventDispatcherInterface $eventDispatcher,
124
-								IL10N $l10n,
125
-								\OC_Defaults $defaults) {
126
-		parent::__construct($appName, $request);
127
-
128
-		$this->config = $config;
129
-		$this->urlGenerator = $urlGenerator;
130
-		$this->userManager = $userManager;
131
-		$this->logger = $logger;
132
-		$this->activityManager = $activityManager;
133
-		$this->shareManager = $shareManager;
134
-		$this->session = $session;
135
-		$this->previewManager = $previewManager;
136
-		$this->rootFolder = $rootFolder;
137
-		$this->federatedShareProvider = $federatedShareProvider;
138
-		$this->eventDispatcher = $eventDispatcher;
139
-		$this->l10n = $l10n;
140
-		$this->defaults = $defaults;
141
-	}
142
-
143
-	/**
144
-	 * @PublicPage
145
-	 * @NoCSRFRequired
146
-	 *
147
-	 * @param string $token
148
-	 * @return TemplateResponse|RedirectResponse
149
-	 */
150
-	public function showAuthenticate($token) {
151
-		$share = $this->shareManager->getShareByToken($token);
152
-
153
-		if($this->linkShareAuth($share)) {
154
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
-		}
156
-
157
-		return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
-	}
159
-
160
-	/**
161
-	 * @PublicPage
162
-	 * @UseSession
163
-	 * @BruteForceProtection publicLinkAuth
164
-	 *
165
-	 * Authenticates against password-protected shares
166
-	 * @param string $token
167
-	 * @param string $password
168
-	 * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
-	 */
170
-	public function authenticate($token, $password = '') {
171
-
172
-		// Check whether share exists
173
-		try {
174
-			$share = $this->shareManager->getShareByToken($token);
175
-		} catch (ShareNotFound $e) {
176
-			return new NotFoundResponse();
177
-		}
178
-
179
-		$authenticate = $this->linkShareAuth($share, $password);
180
-
181
-		if($authenticate === true) {
182
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
-		}
184
-
185
-		return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
-	}
187
-
188
-	/**
189
-	 * Authenticate a link item with the given password.
190
-	 * Or use the session if no password is provided.
191
-	 *
192
-	 * This is a modified version of Helper::authenticate
193
-	 * TODO: Try to merge back eventually with Helper::authenticate
194
-	 *
195
-	 * @param \OCP\Share\IShare $share
196
-	 * @param string|null $password
197
-	 * @return bool
198
-	 */
199
-	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200
-		if ($password !== null) {
201
-			if ($this->shareManager->checkPassword($share, $password)) {
202
-				$this->session->set('public_link_authenticated', (string)$share->getId());
203
-			} else {
204
-				$this->emitAccessShareHook($share, 403, 'Wrong password');
205
-				return false;
206
-			}
207
-		} else {
208
-			// not authenticated ?
209
-			if ( ! $this->session->exists('public_link_authenticated')
210
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
211
-				return false;
212
-			}
213
-		}
214
-		return true;
215
-	}
216
-
217
-	/**
218
-	 * throws hooks when a share is attempted to be accessed
219
-	 *
220
-	 * @param \OCP\Share\IShare|string $share the Share instance if available,
221
-	 * otherwise token
222
-	 * @param int $errorCode
223
-	 * @param string $errorMessage
224
-	 * @throws \OC\HintException
225
-	 * @throws \OC\ServerNotAvailableException
226
-	 */
227
-	protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
228
-		$itemType = $itemSource = $uidOwner = '';
229
-		$token = $share;
230
-		$exception = null;
231
-		if($share instanceof \OCP\Share\IShare) {
232
-			try {
233
-				$token = $share->getToken();
234
-				$uidOwner = $share->getSharedBy();
235
-				$itemType = $share->getNodeType();
236
-				$itemSource = $share->getNodeId();
237
-			} catch (\Exception $e) {
238
-				// we log what we know and pass on the exception afterwards
239
-				$exception = $e;
240
-			}
241
-		}
242
-		\OC_Hook::emit('OCP\Share', 'share_link_access', [
243
-			'itemType' => $itemType,
244
-			'itemSource' => $itemSource,
245
-			'uidOwner' => $uidOwner,
246
-			'token' => $token,
247
-			'errorCode' => $errorCode,
248
-			'errorMessage' => $errorMessage,
249
-		]);
250
-		if(!is_null($exception)) {
251
-			throw $exception;
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * Validate the permissions of the share
257
-	 *
258
-	 * @param Share\IShare $share
259
-	 * @return bool
260
-	 */
261
-	private function validateShare(\OCP\Share\IShare $share) {
262
-		return $share->getNode()->isReadable() && $share->getNode()->isShareable();
263
-	}
264
-
265
-	/**
266
-	 * @PublicPage
267
-	 * @NoCSRFRequired
268
-	 *
269
-	 * @param string $token
270
-	 * @param string $path
271
-	 * @return TemplateResponse|RedirectResponse|NotFoundResponse
272
-	 * @throws NotFoundException
273
-	 * @throws \Exception
274
-	 */
275
-	public function showShare($token, $path = '') {
276
-		\OC_User::setIncognitoMode(true);
277
-
278
-		// Check whether share exists
279
-		try {
280
-			$share = $this->shareManager->getShareByToken($token);
281
-		} catch (ShareNotFound $e) {
282
-			$this->emitAccessShareHook($token, 404, 'Share not found');
283
-			return new NotFoundResponse();
284
-		}
285
-
286
-		// Share is password protected - check whether the user is permitted to access the share
287
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
288
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
289
-				array('token' => $token)));
290
-		}
291
-
292
-		if (!$this->validateShare($share)) {
293
-			throw new NotFoundException();
294
-		}
295
-		// We can't get the path of a file share
296
-		try {
297
-			if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
298
-				$this->emitAccessShareHook($share, 404, 'Share not found');
299
-				throw new NotFoundException();
300
-			}
301
-		} catch (\Exception $e) {
302
-			$this->emitAccessShareHook($share, 404, 'Share not found');
303
-			throw $e;
304
-		}
305
-
306
-		$shareTmpl = [];
307
-		$shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
308
-		$shareTmpl['owner'] = $share->getShareOwner();
309
-		$shareTmpl['filename'] = $share->getNode()->getName();
310
-		$shareTmpl['directory_path'] = $share->getTarget();
311
-		$shareTmpl['mimetype'] = $share->getNode()->getMimetype();
312
-		$shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
313
-		$shareTmpl['dirToken'] = $token;
314
-		$shareTmpl['sharingToken'] = $token;
315
-		$shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
316
-		$shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
317
-		$shareTmpl['dir'] = '';
318
-		$shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
319
-		$shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
320
-
321
-		// Show file list
322
-		$hideFileList = false;
323
-		if ($share->getNode() instanceof \OCP\Files\Folder) {
324
-			/** @var \OCP\Files\Folder $rootFolder */
325
-			$rootFolder = $share->getNode();
326
-
327
-			try {
328
-				$folderNode = $rootFolder->get($path);
329
-			} catch (\OCP\Files\NotFoundException $e) {
330
-				$this->emitAccessShareHook($share, 404, 'Share not found');
331
-				throw new NotFoundException();
332
-			}
333
-
334
-			$shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
335
-
336
-			/*
67
+    /** @var IConfig */
68
+    protected $config;
69
+    /** @var IURLGenerator */
70
+    protected $urlGenerator;
71
+    /** @var IUserManager */
72
+    protected $userManager;
73
+    /** @var ILogger */
74
+    protected $logger;
75
+    /** @var \OCP\Activity\IManager */
76
+    protected $activityManager;
77
+    /** @var \OCP\Share\IManager */
78
+    protected $shareManager;
79
+    /** @var ISession */
80
+    protected $session;
81
+    /** @var IPreview */
82
+    protected $previewManager;
83
+    /** @var IRootFolder */
84
+    protected $rootFolder;
85
+    /** @var FederatedShareProvider */
86
+    protected $federatedShareProvider;
87
+    /** @var EventDispatcherInterface */
88
+    protected $eventDispatcher;
89
+    /** @var IL10N */
90
+    protected $l10n;
91
+    /** @var Defaults */
92
+    protected $defaults;
93
+
94
+    /**
95
+     * @param string $appName
96
+     * @param IRequest $request
97
+     * @param IConfig $config
98
+     * @param IURLGenerator $urlGenerator
99
+     * @param IUserManager $userManager
100
+     * @param ILogger $logger
101
+     * @param \OCP\Activity\IManager $activityManager
102
+     * @param \OCP\Share\IManager $shareManager
103
+     * @param ISession $session
104
+     * @param IPreview $previewManager
105
+     * @param IRootFolder $rootFolder
106
+     * @param FederatedShareProvider $federatedShareProvider
107
+     * @param EventDispatcherInterface $eventDispatcher
108
+     * @param IL10N $l10n
109
+     * @param \OC_Defaults $defaults
110
+     */
111
+    public function __construct($appName,
112
+                                IRequest $request,
113
+                                IConfig $config,
114
+                                IURLGenerator $urlGenerator,
115
+                                IUserManager $userManager,
116
+                                ILogger $logger,
117
+                                \OCP\Activity\IManager $activityManager,
118
+                                \OCP\Share\IManager $shareManager,
119
+                                ISession $session,
120
+                                IPreview $previewManager,
121
+                                IRootFolder $rootFolder,
122
+                                FederatedShareProvider $federatedShareProvider,
123
+                                EventDispatcherInterface $eventDispatcher,
124
+                                IL10N $l10n,
125
+                                \OC_Defaults $defaults) {
126
+        parent::__construct($appName, $request);
127
+
128
+        $this->config = $config;
129
+        $this->urlGenerator = $urlGenerator;
130
+        $this->userManager = $userManager;
131
+        $this->logger = $logger;
132
+        $this->activityManager = $activityManager;
133
+        $this->shareManager = $shareManager;
134
+        $this->session = $session;
135
+        $this->previewManager = $previewManager;
136
+        $this->rootFolder = $rootFolder;
137
+        $this->federatedShareProvider = $federatedShareProvider;
138
+        $this->eventDispatcher = $eventDispatcher;
139
+        $this->l10n = $l10n;
140
+        $this->defaults = $defaults;
141
+    }
142
+
143
+    /**
144
+     * @PublicPage
145
+     * @NoCSRFRequired
146
+     *
147
+     * @param string $token
148
+     * @return TemplateResponse|RedirectResponse
149
+     */
150
+    public function showAuthenticate($token) {
151
+        $share = $this->shareManager->getShareByToken($token);
152
+
153
+        if($this->linkShareAuth($share)) {
154
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155
+        }
156
+
157
+        return new TemplateResponse($this->appName, 'authenticate', array(), 'guest');
158
+    }
159
+
160
+    /**
161
+     * @PublicPage
162
+     * @UseSession
163
+     * @BruteForceProtection publicLinkAuth
164
+     *
165
+     * Authenticates against password-protected shares
166
+     * @param string $token
167
+     * @param string $password
168
+     * @return RedirectResponse|TemplateResponse|NotFoundResponse
169
+     */
170
+    public function authenticate($token, $password = '') {
171
+
172
+        // Check whether share exists
173
+        try {
174
+            $share = $this->shareManager->getShareByToken($token);
175
+        } catch (ShareNotFound $e) {
176
+            return new NotFoundResponse();
177
+        }
178
+
179
+        $authenticate = $this->linkShareAuth($share, $password);
180
+
181
+        if($authenticate === true) {
182
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183
+        }
184
+
185
+        return new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest');
186
+    }
187
+
188
+    /**
189
+     * Authenticate a link item with the given password.
190
+     * Or use the session if no password is provided.
191
+     *
192
+     * This is a modified version of Helper::authenticate
193
+     * TODO: Try to merge back eventually with Helper::authenticate
194
+     *
195
+     * @param \OCP\Share\IShare $share
196
+     * @param string|null $password
197
+     * @return bool
198
+     */
199
+    private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200
+        if ($password !== null) {
201
+            if ($this->shareManager->checkPassword($share, $password)) {
202
+                $this->session->set('public_link_authenticated', (string)$share->getId());
203
+            } else {
204
+                $this->emitAccessShareHook($share, 403, 'Wrong password');
205
+                return false;
206
+            }
207
+        } else {
208
+            // not authenticated ?
209
+            if ( ! $this->session->exists('public_link_authenticated')
210
+                || $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
211
+                return false;
212
+            }
213
+        }
214
+        return true;
215
+    }
216
+
217
+    /**
218
+     * throws hooks when a share is attempted to be accessed
219
+     *
220
+     * @param \OCP\Share\IShare|string $share the Share instance if available,
221
+     * otherwise token
222
+     * @param int $errorCode
223
+     * @param string $errorMessage
224
+     * @throws \OC\HintException
225
+     * @throws \OC\ServerNotAvailableException
226
+     */
227
+    protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') {
228
+        $itemType = $itemSource = $uidOwner = '';
229
+        $token = $share;
230
+        $exception = null;
231
+        if($share instanceof \OCP\Share\IShare) {
232
+            try {
233
+                $token = $share->getToken();
234
+                $uidOwner = $share->getSharedBy();
235
+                $itemType = $share->getNodeType();
236
+                $itemSource = $share->getNodeId();
237
+            } catch (\Exception $e) {
238
+                // we log what we know and pass on the exception afterwards
239
+                $exception = $e;
240
+            }
241
+        }
242
+        \OC_Hook::emit('OCP\Share', 'share_link_access', [
243
+            'itemType' => $itemType,
244
+            'itemSource' => $itemSource,
245
+            'uidOwner' => $uidOwner,
246
+            'token' => $token,
247
+            'errorCode' => $errorCode,
248
+            'errorMessage' => $errorMessage,
249
+        ]);
250
+        if(!is_null($exception)) {
251
+            throw $exception;
252
+        }
253
+    }
254
+
255
+    /**
256
+     * Validate the permissions of the share
257
+     *
258
+     * @param Share\IShare $share
259
+     * @return bool
260
+     */
261
+    private function validateShare(\OCP\Share\IShare $share) {
262
+        return $share->getNode()->isReadable() && $share->getNode()->isShareable();
263
+    }
264
+
265
+    /**
266
+     * @PublicPage
267
+     * @NoCSRFRequired
268
+     *
269
+     * @param string $token
270
+     * @param string $path
271
+     * @return TemplateResponse|RedirectResponse|NotFoundResponse
272
+     * @throws NotFoundException
273
+     * @throws \Exception
274
+     */
275
+    public function showShare($token, $path = '') {
276
+        \OC_User::setIncognitoMode(true);
277
+
278
+        // Check whether share exists
279
+        try {
280
+            $share = $this->shareManager->getShareByToken($token);
281
+        } catch (ShareNotFound $e) {
282
+            $this->emitAccessShareHook($token, 404, 'Share not found');
283
+            return new NotFoundResponse();
284
+        }
285
+
286
+        // Share is password protected - check whether the user is permitted to access the share
287
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
288
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
289
+                array('token' => $token)));
290
+        }
291
+
292
+        if (!$this->validateShare($share)) {
293
+            throw new NotFoundException();
294
+        }
295
+        // We can't get the path of a file share
296
+        try {
297
+            if ($share->getNode() instanceof \OCP\Files\File && $path !== '') {
298
+                $this->emitAccessShareHook($share, 404, 'Share not found');
299
+                throw new NotFoundException();
300
+            }
301
+        } catch (\Exception $e) {
302
+            $this->emitAccessShareHook($share, 404, 'Share not found');
303
+            throw $e;
304
+        }
305
+
306
+        $shareTmpl = [];
307
+        $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
308
+        $shareTmpl['owner'] = $share->getShareOwner();
309
+        $shareTmpl['filename'] = $share->getNode()->getName();
310
+        $shareTmpl['directory_path'] = $share->getTarget();
311
+        $shareTmpl['mimetype'] = $share->getNode()->getMimetype();
312
+        $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype());
313
+        $shareTmpl['dirToken'] = $token;
314
+        $shareTmpl['sharingToken'] = $token;
315
+        $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
316
+        $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false';
317
+        $shareTmpl['dir'] = '';
318
+        $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize();
319
+        $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize());
320
+
321
+        // Show file list
322
+        $hideFileList = false;
323
+        if ($share->getNode() instanceof \OCP\Files\Folder) {
324
+            /** @var \OCP\Files\Folder $rootFolder */
325
+            $rootFolder = $share->getNode();
326
+
327
+            try {
328
+                $folderNode = $rootFolder->get($path);
329
+            } catch (\OCP\Files\NotFoundException $e) {
330
+                $this->emitAccessShareHook($share, 404, 'Share not found');
331
+                throw new NotFoundException();
332
+            }
333
+
334
+            $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath());
335
+
336
+            /*
337 337
 			 * The OC_Util methods require a view. This just uses the node API
338 338
 			 */
339
-			$freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
340
-			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341
-				$freeSpace = max($freeSpace, 0);
342
-			} else {
343
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344
-			}
345
-
346
-			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
347
-			$maxUploadFilesize = $freeSpace;
348
-
349
-			$folder = new Template('files', 'list', '');
350
-			$folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
351
-			$folder->assign('dirToken', $token);
352
-			$folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
353
-			$folder->assign('isPublic', true);
354
-			$folder->assign('hideFileList', $hideFileList);
355
-			$folder->assign('publicUploadEnabled', 'no');
356
-			$folder->assign('uploadMaxFilesize', $maxUploadFilesize);
357
-			$folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
358
-			$folder->assign('freeSpace', $freeSpace);
359
-			$folder->assign('usedSpacePercent', 0);
360
-			$folder->assign('trash', false);
361
-			$shareTmpl['folder'] = $folder->fetchPage();
362
-		}
363
-
364
-		$shareTmpl['hideFileList'] = $hideFileList;
365
-		$shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
366
-		$shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
367
-		$shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
368
-		$shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
369
-		$shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
370
-		$shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
371
-		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372
-		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373
-		if ($shareTmpl['previewSupported']) {
374
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
375
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376
-		} else {
377
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
378
-		}
379
-
380
-		// Load files we need
381
-		\OCP\Util::addScript('files', 'file-upload');
382
-		\OCP\Util::addStyle('files_sharing', 'public');
383
-		\OCP\Util::addStyle('files_sharing', 'mobile');
384
-		\OCP\Util::addScript('files_sharing', 'public');
385
-		\OCP\Util::addScript('files', 'fileactions');
386
-		\OCP\Util::addScript('files', 'fileactionsmenu');
387
-		\OCP\Util::addScript('files', 'jquery.fileupload');
388
-		\OCP\Util::addScript('files_sharing', 'files_drop');
389
-
390
-		if (isset($shareTmpl['folder'])) {
391
-			// JS required for folders
392
-			\OCP\Util::addStyle('files', 'files');
393
-			\OCP\Util::addStyle('files', 'upload');
394
-			\OCP\Util::addScript('files', 'filesummary');
395
-			\OCP\Util::addScript('files', 'breadcrumb');
396
-			\OCP\Util::addScript('files', 'fileinfomodel');
397
-			\OCP\Util::addScript('files', 'newfilemenu');
398
-			\OCP\Util::addScript('files', 'files');
399
-			\OCP\Util::addScript('files', 'filelist');
400
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
401
-		}
402
-
403
-		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
-
411
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
-
413
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
-		$csp->addAllowedFrameDomain('\'self\'');
415
-		$response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
-		$response->setContentSecurityPolicy($csp);
417
-
418
-		$this->emitAccessShareHook($share);
419
-
420
-		return $response;
421
-	}
422
-
423
-	/**
424
-	 * @PublicPage
425
-	 * @NoCSRFRequired
426
-	 *
427
-	 * @param string $token
428
-	 * @param string $files
429
-	 * @param string $path
430
-	 * @param string $downloadStartSecret
431
-	 * @return void|\OCP\AppFramework\Http\Response
432
-	 * @throws NotFoundException
433
-	 */
434
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
-		\OC_User::setIncognitoMode(true);
436
-
437
-		$share = $this->shareManager->getShareByToken($token);
438
-
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
-		}
442
-
443
-		// Share is password protected - check whether the user is permitted to access the share
444
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
-				['token' => $token]));
447
-		}
448
-
449
-		$files_list = null;
450
-		if (!is_null($files)) { // download selected files
451
-			$files_list = json_decode($files);
452
-			// in case we get only a single file
453
-			if ($files_list === null) {
454
-				$files_list = [$files];
455
-			}
456
-		}
457
-
458
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
-
461
-		if (!$this->validateShare($share)) {
462
-			throw new NotFoundException();
463
-		}
464
-
465
-		// Single file share
466
-		if ($share->getNode() instanceof \OCP\Files\File) {
467
-			// Single file download
468
-			$this->singleFileDownloaded($share, $share->getNode());
469
-		}
470
-		// Directory share
471
-		else {
472
-			/** @var \OCP\Files\Folder $node */
473
-			$node = $share->getNode();
474
-
475
-			// Try to get the path
476
-			if ($path !== '') {
477
-				try {
478
-					$node = $node->get($path);
479
-				} catch (NotFoundException $e) {
480
-					$this->emitAccessShareHook($share, 404, 'Share not found');
481
-					return new NotFoundResponse();
482
-				}
483
-			}
484
-
485
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
486
-
487
-			if ($node instanceof \OCP\Files\File) {
488
-				// Single file download
489
-				$this->singleFileDownloaded($share, $share->getNode());
490
-			} else if (!empty($files_list)) {
491
-				$this->fileListDownloaded($share, $files_list, $node);
492
-			} else {
493
-				// The folder is downloaded
494
-				$this->singleFileDownloaded($share, $share->getNode());
495
-			}
496
-		}
497
-
498
-		/* FIXME: We should do this all nicely in OCP */
499
-		OC_Util::tearDownFS();
500
-		OC_Util::setupFS($share->getShareOwner());
501
-
502
-		/**
503
-		 * this sets a cookie to be able to recognize the start of the download
504
-		 * the content must not be longer than 32 characters and must only contain
505
-		 * alphanumeric characters
506
-		 */
507
-		if (!empty($downloadStartSecret)
508
-			&& !isset($downloadStartSecret[32])
509
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
-
511
-			// FIXME: set on the response once we use an actual app framework response
512
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
-		}
514
-
515
-		$this->emitAccessShareHook($share);
516
-
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
-
519
-		/**
520
-		 * Http range requests support
521
-		 */
522
-		if (isset($_SERVER['HTTP_RANGE'])) {
523
-			$server_params['range'] = $this->request->getHeader('Range');
524
-		}
525
-
526
-		// download selected files
527
-		if (!is_null($files) && $files !== '') {
528
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
-			// after dispatching the request which results in a "Cannot modify header information" notice.
530
-			OC_Files::get($originalSharePath, $files_list, $server_params);
531
-			exit();
532
-		} else {
533
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
-			// after dispatching the request which results in a "Cannot modify header information" notice.
535
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
-			exit();
537
-		}
538
-	}
539
-
540
-	/**
541
-	 * create activity for every downloaded file
542
-	 *
543
-	 * @param Share\IShare $share
544
-	 * @param array $files_list
545
-	 * @param \OCP\Files\Folder $node
546
-	 */
547
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
-		foreach ($files_list as $file) {
549
-			$subNode = $node->get($file);
550
-			$this->singleFileDownloaded($share, $subNode);
551
-		}
552
-
553
-	}
554
-
555
-	/**
556
-	 * create activity if a single file was downloaded from a link share
557
-	 *
558
-	 * @param Share\IShare $share
559
-	 */
560
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
-
562
-		$fileId = $node->getId();
563
-
564
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
-		$userNodeList = $userFolder->getById($fileId);
566
-		$userNode = $userNodeList[0];
567
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
569
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
-
571
-		$parameters = [$userPath];
572
-
573
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
-			if ($node instanceof \OCP\Files\File) {
575
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
-			} else {
577
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
-			}
579
-			$parameters[] = $share->getSharedWith();
580
-		} else {
581
-			if ($node instanceof \OCP\Files\File) {
582
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
-			} else {
584
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
-			}
586
-		}
587
-
588
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
-
590
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
591
-			$parameters[0] = $ownerPath;
592
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
-		}
594
-	}
595
-
596
-	/**
597
-	 * publish activity
598
-	 *
599
-	 * @param string $subject
600
-	 * @param array $parameters
601
-	 * @param string $affectedUser
602
-	 * @param int $fileId
603
-	 * @param string $filePath
604
-	 */
605
-	protected function publishActivity($subject,
606
-										array $parameters,
607
-										$affectedUser,
608
-										$fileId,
609
-										$filePath) {
610
-
611
-		$event = $this->activityManager->generateEvent();
612
-		$event->setApp('files_sharing')
613
-			->setType('public_links')
614
-			->setSubject($subject, $parameters)
615
-			->setAffectedUser($affectedUser)
616
-			->setObject('files', $fileId, $filePath);
617
-		$this->activityManager->publish($event);
618
-	}
339
+            $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath());
340
+            if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341
+                $freeSpace = max($freeSpace, 0);
342
+            } else {
343
+                $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344
+            }
345
+
346
+            $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
347
+            $maxUploadFilesize = $freeSpace;
348
+
349
+            $folder = new Template('files', 'list', '');
350
+            $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath()));
351
+            $folder->assign('dirToken', $token);
352
+            $folder->assign('permissions', \OCP\Constants::PERMISSION_READ);
353
+            $folder->assign('isPublic', true);
354
+            $folder->assign('hideFileList', $hideFileList);
355
+            $folder->assign('publicUploadEnabled', 'no');
356
+            $folder->assign('uploadMaxFilesize', $maxUploadFilesize);
357
+            $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize));
358
+            $folder->assign('freeSpace', $freeSpace);
359
+            $folder->assign('usedSpacePercent', 0);
360
+            $folder->assign('trash', false);
361
+            $shareTmpl['folder'] = $folder->fetchPage();
362
+        }
363
+
364
+        $shareTmpl['hideFileList'] = $hideFileList;
365
+        $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName();
366
+        $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]);
367
+        $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
368
+        $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10);
369
+        $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true);
370
+        $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024);
371
+        $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372
+        $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373
+        if ($shareTmpl['previewSupported']) {
374
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
375
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376
+        } else {
377
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
378
+        }
379
+
380
+        // Load files we need
381
+        \OCP\Util::addScript('files', 'file-upload');
382
+        \OCP\Util::addStyle('files_sharing', 'public');
383
+        \OCP\Util::addStyle('files_sharing', 'mobile');
384
+        \OCP\Util::addScript('files_sharing', 'public');
385
+        \OCP\Util::addScript('files', 'fileactions');
386
+        \OCP\Util::addScript('files', 'fileactionsmenu');
387
+        \OCP\Util::addScript('files', 'jquery.fileupload');
388
+        \OCP\Util::addScript('files_sharing', 'files_drop');
389
+
390
+        if (isset($shareTmpl['folder'])) {
391
+            // JS required for folders
392
+            \OCP\Util::addStyle('files', 'files');
393
+            \OCP\Util::addStyle('files', 'upload');
394
+            \OCP\Util::addScript('files', 'filesummary');
395
+            \OCP\Util::addScript('files', 'breadcrumb');
396
+            \OCP\Util::addScript('files', 'fileinfomodel');
397
+            \OCP\Util::addScript('files', 'newfilemenu');
398
+            \OCP\Util::addScript('files', 'files');
399
+            \OCP\Util::addScript('files', 'filelist');
400
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
401
+        }
402
+
403
+        // OpenGraph Support: http://ogp.me/
404
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
405
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
408
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
409
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $shareTmpl['previewImage']]);
410
+
411
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
412
+
413
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
414
+        $csp->addAllowedFrameDomain('\'self\'');
415
+        $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
416
+        $response->setContentSecurityPolicy($csp);
417
+
418
+        $this->emitAccessShareHook($share);
419
+
420
+        return $response;
421
+    }
422
+
423
+    /**
424
+     * @PublicPage
425
+     * @NoCSRFRequired
426
+     *
427
+     * @param string $token
428
+     * @param string $files
429
+     * @param string $path
430
+     * @param string $downloadStartSecret
431
+     * @return void|\OCP\AppFramework\Http\Response
432
+     * @throws NotFoundException
433
+     */
434
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
435
+        \OC_User::setIncognitoMode(true);
436
+
437
+        $share = $this->shareManager->getShareByToken($token);
438
+
439
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441
+        }
442
+
443
+        // Share is password protected - check whether the user is permitted to access the share
444
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
445
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
446
+                ['token' => $token]));
447
+        }
448
+
449
+        $files_list = null;
450
+        if (!is_null($files)) { // download selected files
451
+            $files_list = json_decode($files);
452
+            // in case we get only a single file
453
+            if ($files_list === null) {
454
+                $files_list = [$files];
455
+            }
456
+        }
457
+
458
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
459
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
460
+
461
+        if (!$this->validateShare($share)) {
462
+            throw new NotFoundException();
463
+        }
464
+
465
+        // Single file share
466
+        if ($share->getNode() instanceof \OCP\Files\File) {
467
+            // Single file download
468
+            $this->singleFileDownloaded($share, $share->getNode());
469
+        }
470
+        // Directory share
471
+        else {
472
+            /** @var \OCP\Files\Folder $node */
473
+            $node = $share->getNode();
474
+
475
+            // Try to get the path
476
+            if ($path !== '') {
477
+                try {
478
+                    $node = $node->get($path);
479
+                } catch (NotFoundException $e) {
480
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
481
+                    return new NotFoundResponse();
482
+                }
483
+            }
484
+
485
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
486
+
487
+            if ($node instanceof \OCP\Files\File) {
488
+                // Single file download
489
+                $this->singleFileDownloaded($share, $share->getNode());
490
+            } else if (!empty($files_list)) {
491
+                $this->fileListDownloaded($share, $files_list, $node);
492
+            } else {
493
+                // The folder is downloaded
494
+                $this->singleFileDownloaded($share, $share->getNode());
495
+            }
496
+        }
497
+
498
+        /* FIXME: We should do this all nicely in OCP */
499
+        OC_Util::tearDownFS();
500
+        OC_Util::setupFS($share->getShareOwner());
501
+
502
+        /**
503
+         * this sets a cookie to be able to recognize the start of the download
504
+         * the content must not be longer than 32 characters and must only contain
505
+         * alphanumeric characters
506
+         */
507
+        if (!empty($downloadStartSecret)
508
+            && !isset($downloadStartSecret[32])
509
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
510
+
511
+            // FIXME: set on the response once we use an actual app framework response
512
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
513
+        }
514
+
515
+        $this->emitAccessShareHook($share);
516
+
517
+        $server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
518
+
519
+        /**
520
+         * Http range requests support
521
+         */
522
+        if (isset($_SERVER['HTTP_RANGE'])) {
523
+            $server_params['range'] = $this->request->getHeader('Range');
524
+        }
525
+
526
+        // download selected files
527
+        if (!is_null($files) && $files !== '') {
528
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
529
+            // after dispatching the request which results in a "Cannot modify header information" notice.
530
+            OC_Files::get($originalSharePath, $files_list, $server_params);
531
+            exit();
532
+        } else {
533
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
534
+            // after dispatching the request which results in a "Cannot modify header information" notice.
535
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
536
+            exit();
537
+        }
538
+    }
539
+
540
+    /**
541
+     * create activity for every downloaded file
542
+     *
543
+     * @param Share\IShare $share
544
+     * @param array $files_list
545
+     * @param \OCP\Files\Folder $node
546
+     */
547
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
548
+        foreach ($files_list as $file) {
549
+            $subNode = $node->get($file);
550
+            $this->singleFileDownloaded($share, $subNode);
551
+        }
552
+
553
+    }
554
+
555
+    /**
556
+     * create activity if a single file was downloaded from a link share
557
+     *
558
+     * @param Share\IShare $share
559
+     */
560
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
561
+
562
+        $fileId = $node->getId();
563
+
564
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
565
+        $userNodeList = $userFolder->getById($fileId);
566
+        $userNode = $userNodeList[0];
567
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
568
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
569
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
570
+
571
+        $parameters = [$userPath];
572
+
573
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
574
+            if ($node instanceof \OCP\Files\File) {
575
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
576
+            } else {
577
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
578
+            }
579
+            $parameters[] = $share->getSharedWith();
580
+        } else {
581
+            if ($node instanceof \OCP\Files\File) {
582
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
583
+            } else {
584
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
585
+            }
586
+        }
587
+
588
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
589
+
590
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
591
+            $parameters[0] = $ownerPath;
592
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
593
+        }
594
+    }
595
+
596
+    /**
597
+     * publish activity
598
+     *
599
+     * @param string $subject
600
+     * @param array $parameters
601
+     * @param string $affectedUser
602
+     * @param int $fileId
603
+     * @param string $filePath
604
+     */
605
+    protected function publishActivity($subject,
606
+                                        array $parameters,
607
+                                        $affectedUser,
608
+                                        $fileId,
609
+                                        $filePath) {
610
+
611
+        $event = $this->activityManager->generateEvent();
612
+        $event->setApp('files_sharing')
613
+            ->setType('public_links')
614
+            ->setSubject($subject, $parameters)
615
+            ->setAffectedUser($affectedUser)
616
+            ->setObject('files', $fileId, $filePath);
617
+        $this->activityManager->publish($event);
618
+    }
619 619
 
620 620
 
621 621
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function showAuthenticate($token) {
151 151
 		$share = $this->shareManager->getShareByToken($token);
152 152
 
153
-		if($this->linkShareAuth($share)) {
153
+		if ($this->linkShareAuth($share)) {
154 154
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155 155
 		}
156 156
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 
179 179
 		$authenticate = $this->linkShareAuth($share, $password);
180 180
 
181
-		if($authenticate === true) {
181
+		if ($authenticate === true) {
182 182
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183 183
 		}
184 184
 
@@ -199,15 +199,15 @@  discard block
 block discarded – undo
199 199
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
200 200
 		if ($password !== null) {
201 201
 			if ($this->shareManager->checkPassword($share, $password)) {
202
-				$this->session->set('public_link_authenticated', (string)$share->getId());
202
+				$this->session->set('public_link_authenticated', (string) $share->getId());
203 203
 			} else {
204 204
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
205 205
 				return false;
206 206
 			}
207 207
 		} else {
208 208
 			// not authenticated ?
209
-			if ( ! $this->session->exists('public_link_authenticated')
210
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
209
+			if (!$this->session->exists('public_link_authenticated')
210
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
211 211
 				return false;
212 212
 			}
213 213
 		}
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 		$itemType = $itemSource = $uidOwner = '';
229 229
 		$token = $share;
230 230
 		$exception = null;
231
-		if($share instanceof \OCP\Share\IShare) {
231
+		if ($share instanceof \OCP\Share\IShare) {
232 232
 			try {
233 233
 				$token = $share->getToken();
234 234
 				$uidOwner = $share->getSharedBy();
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
 			'errorCode' => $errorCode,
248 248
 			'errorMessage' => $errorMessage,
249 249
 		]);
250
-		if(!is_null($exception)) {
250
+		if (!is_null($exception)) {
251 251
 			throw $exception;
252 252
 		}
253 253
 	}
@@ -340,7 +340,7 @@  discard block
 block discarded – undo
340 340
 			if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) {
341 341
 				$freeSpace = max($freeSpace, 0);
342 342
 			} else {
343
-				$freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
343
+				$freeSpace = (INF > 0) ? INF : PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188
344 344
 			}
345 345
 
346 346
 			$hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true;
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
 		$shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024);
372 372
 		$shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null);
373 373
 		if ($shareTmpl['previewSupported']) {
374
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
374
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
375 375
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
376 376
 		} else {
377 377
 			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 		}
402 402
 
403 403
 		// OpenGraph Support: http://ogp.me/
404
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName() . ' - ' . $this->defaults->getSlogan()]);
404
+		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $this->defaults->getName().' - '.$this->defaults->getSlogan()]);
405 405
 		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->l10n->t('%s is publicly shared', [$shareTmpl['filename']])]);
406 406
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
407 407
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
@@ -436,7 +436,7 @@  discard block
 block discarded – undo
436 436
 
437 437
 		$share = $this->shareManager->getShareByToken($token);
438 438
 
439
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
439
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
440 440
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
441 441
 		}
442 442
 
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
 
515 515
 		$this->emitAccessShareHook($share);
516 516
 
517
-		$server_params = array( 'head' => $this->request->getMethod() == 'HEAD' );
517
+		$server_params = array('head' => $this->request->getMethod() == 'HEAD');
518 518
 
519 519
 		/**
520 520
 		 * Http range requests support
Please login to merge, or discard this patch.