@@ -31,7 +31,7 @@ |
||
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); |
@@ -29,113 +29,113 @@ |
||
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 | } |
@@ -37,7 +37,7 @@ |
||
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); |
@@ -36,399 +36,399 @@ |
||
36 | 36 | use OCP\Files\Search\ISearchOperator; |
37 | 37 | |
38 | 38 | class Folder extends Node implements \OCP\Files\Folder { |
39 | - /** |
|
40 | - * Creates a Folder that represents a non-existing path |
|
41 | - * |
|
42 | - * @param string $path path |
|
43 | - * @return string non-existing node class |
|
44 | - */ |
|
45 | - protected function createNonExistingNode($path) { |
|
46 | - return new NonExistingFolder($this->root, $this->view, $path); |
|
47 | - } |
|
48 | - |
|
49 | - /** |
|
50 | - * @param string $path path relative to the folder |
|
51 | - * @return string |
|
52 | - * @throws \OCP\Files\NotPermittedException |
|
53 | - */ |
|
54 | - public function getFullPath($path) { |
|
55 | - if (!$this->isValidPath($path)) { |
|
56 | - throw new NotPermittedException('Invalid path'); |
|
57 | - } |
|
58 | - return $this->path . $this->normalizePath($path); |
|
59 | - } |
|
60 | - |
|
61 | - /** |
|
62 | - * @param string $path |
|
63 | - * @return string |
|
64 | - */ |
|
65 | - public function getRelativePath($path) { |
|
66 | - if ($this->path === '' or $this->path === '/') { |
|
67 | - return $this->normalizePath($path); |
|
68 | - } |
|
69 | - if ($path === $this->path) { |
|
70 | - return '/'; |
|
71 | - } else if (strpos($path, $this->path . '/') !== 0) { |
|
72 | - return null; |
|
73 | - } else { |
|
74 | - $path = substr($path, strlen($this->path)); |
|
75 | - return $this->normalizePath($path); |
|
76 | - } |
|
77 | - } |
|
78 | - |
|
79 | - /** |
|
80 | - * check if a node is a (grand-)child of the folder |
|
81 | - * |
|
82 | - * @param \OC\Files\Node\Node $node |
|
83 | - * @return bool |
|
84 | - */ |
|
85 | - public function isSubNode($node) { |
|
86 | - return strpos($node->getPath(), $this->path . '/') === 0; |
|
87 | - } |
|
88 | - |
|
89 | - /** |
|
90 | - * get the content of this directory |
|
91 | - * |
|
92 | - * @throws \OCP\Files\NotFoundException |
|
93 | - * @return Node[] |
|
94 | - */ |
|
95 | - public function getDirectoryListing() { |
|
96 | - $folderContent = $this->view->getDirectoryContent($this->path); |
|
97 | - |
|
98 | - return array_map(function (FileInfo $info) { |
|
99 | - if ($info->getMimetype() === 'httpd/unix-directory') { |
|
100 | - return new Folder($this->root, $this->view, $info->getPath(), $info); |
|
101 | - } else { |
|
102 | - return new File($this->root, $this->view, $info->getPath(), $info); |
|
103 | - } |
|
104 | - }, $folderContent); |
|
105 | - } |
|
106 | - |
|
107 | - /** |
|
108 | - * @param string $path |
|
109 | - * @param FileInfo $info |
|
110 | - * @return File|Folder |
|
111 | - */ |
|
112 | - protected function createNode($path, FileInfo $info = null) { |
|
113 | - if (is_null($info)) { |
|
114 | - $isDir = $this->view->is_dir($path); |
|
115 | - } else { |
|
116 | - $isDir = $info->getType() === FileInfo::TYPE_FOLDER; |
|
117 | - } |
|
118 | - if ($isDir) { |
|
119 | - return new Folder($this->root, $this->view, $path, $info); |
|
120 | - } else { |
|
121 | - return new File($this->root, $this->view, $path, $info); |
|
122 | - } |
|
123 | - } |
|
124 | - |
|
125 | - /** |
|
126 | - * Get the node at $path |
|
127 | - * |
|
128 | - * @param string $path |
|
129 | - * @return \OC\Files\Node\Node |
|
130 | - * @throws \OCP\Files\NotFoundException |
|
131 | - */ |
|
132 | - public function get($path) { |
|
133 | - return $this->root->get($this->getFullPath($path)); |
|
134 | - } |
|
135 | - |
|
136 | - /** |
|
137 | - * @param string $path |
|
138 | - * @return bool |
|
139 | - */ |
|
140 | - public function nodeExists($path) { |
|
141 | - try { |
|
142 | - $this->get($path); |
|
143 | - return true; |
|
144 | - } catch (NotFoundException $e) { |
|
145 | - return false; |
|
146 | - } |
|
147 | - } |
|
148 | - |
|
149 | - /** |
|
150 | - * @param string $path |
|
151 | - * @return \OC\Files\Node\Folder |
|
152 | - * @throws \OCP\Files\NotPermittedException |
|
153 | - */ |
|
154 | - public function newFolder($path) { |
|
155 | - if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) { |
|
156 | - $fullPath = $this->getFullPath($path); |
|
157 | - $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath); |
|
158 | - $this->root->emit('\OC\Files', 'preWrite', array($nonExisting)); |
|
159 | - $this->root->emit('\OC\Files', 'preCreate', array($nonExisting)); |
|
160 | - $this->view->mkdir($fullPath); |
|
161 | - $node = new Folder($this->root, $this->view, $fullPath); |
|
162 | - $this->root->emit('\OC\Files', 'postWrite', array($node)); |
|
163 | - $this->root->emit('\OC\Files', 'postCreate', array($node)); |
|
164 | - return $node; |
|
165 | - } else { |
|
166 | - throw new NotPermittedException('No create permission for folder'); |
|
167 | - } |
|
168 | - } |
|
169 | - |
|
170 | - /** |
|
171 | - * @param string $path |
|
172 | - * @return \OC\Files\Node\File |
|
173 | - * @throws \OCP\Files\NotPermittedException |
|
174 | - */ |
|
175 | - public function newFile($path) { |
|
176 | - if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) { |
|
177 | - $fullPath = $this->getFullPath($path); |
|
178 | - $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath); |
|
179 | - $this->root->emit('\OC\Files', 'preWrite', array($nonExisting)); |
|
180 | - $this->root->emit('\OC\Files', 'preCreate', array($nonExisting)); |
|
181 | - $this->view->touch($fullPath); |
|
182 | - $node = new File($this->root, $this->view, $fullPath); |
|
183 | - $this->root->emit('\OC\Files', 'postWrite', array($node)); |
|
184 | - $this->root->emit('\OC\Files', 'postCreate', array($node)); |
|
185 | - return $node; |
|
186 | - } else { |
|
187 | - throw new NotPermittedException('No create permission for path'); |
|
188 | - } |
|
189 | - } |
|
190 | - |
|
191 | - /** |
|
192 | - * search for files with the name matching $query |
|
193 | - * |
|
194 | - * @param string|ISearchOperator $query |
|
195 | - * @return \OC\Files\Node\Node[] |
|
196 | - */ |
|
197 | - public function search($query) { |
|
198 | - if (is_string($query)) { |
|
199 | - return $this->searchCommon('search', array('%' . $query . '%')); |
|
200 | - } else { |
|
201 | - return $this->searchCommon('searchQuery', array($query)); |
|
202 | - } |
|
203 | - } |
|
204 | - |
|
205 | - /** |
|
206 | - * search for files by mimetype |
|
207 | - * |
|
208 | - * @param string $mimetype |
|
209 | - * @return Node[] |
|
210 | - */ |
|
211 | - public function searchByMime($mimetype) { |
|
212 | - return $this->searchCommon('searchByMime', array($mimetype)); |
|
213 | - } |
|
214 | - |
|
215 | - /** |
|
216 | - * search for files by tag |
|
217 | - * |
|
218 | - * @param string|int $tag name or tag id |
|
219 | - * @param string $userId owner of the tags |
|
220 | - * @return Node[] |
|
221 | - */ |
|
222 | - public function searchByTag($tag, $userId) { |
|
223 | - return $this->searchCommon('searchByTag', array($tag, $userId)); |
|
224 | - } |
|
225 | - |
|
226 | - /** |
|
227 | - * @param string $method cache method |
|
228 | - * @param array $args call args |
|
229 | - * @return \OC\Files\Node\Node[] |
|
230 | - */ |
|
231 | - private function searchCommon($method, $args) { |
|
232 | - $files = array(); |
|
233 | - $rootLength = strlen($this->path); |
|
234 | - $mount = $this->root->getMount($this->path); |
|
235 | - $storage = $mount->getStorage(); |
|
236 | - $internalPath = $mount->getInternalPath($this->path); |
|
237 | - $internalPath = rtrim($internalPath, '/'); |
|
238 | - if ($internalPath !== '') { |
|
239 | - $internalPath = $internalPath . '/'; |
|
240 | - } |
|
241 | - $internalRootLength = strlen($internalPath); |
|
242 | - |
|
243 | - $cache = $storage->getCache(''); |
|
244 | - |
|
245 | - $results = call_user_func_array(array($cache, $method), $args); |
|
246 | - foreach ($results as $result) { |
|
247 | - if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) { |
|
248 | - $result['internalPath'] = $result['path']; |
|
249 | - $result['path'] = substr($result['path'], $internalRootLength); |
|
250 | - $result['storage'] = $storage; |
|
251 | - $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount); |
|
252 | - } |
|
253 | - } |
|
254 | - |
|
255 | - $mounts = $this->root->getMountsIn($this->path); |
|
256 | - foreach ($mounts as $mount) { |
|
257 | - $storage = $mount->getStorage(); |
|
258 | - if ($storage) { |
|
259 | - $cache = $storage->getCache(''); |
|
260 | - |
|
261 | - $relativeMountPoint = substr($mount->getMountPoint(), $rootLength); |
|
262 | - $results = call_user_func_array(array($cache, $method), $args); |
|
263 | - foreach ($results as $result) { |
|
264 | - $result['internalPath'] = $result['path']; |
|
265 | - $result['path'] = $relativeMountPoint . $result['path']; |
|
266 | - $result['storage'] = $storage; |
|
267 | - $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount); |
|
268 | - } |
|
269 | - } |
|
270 | - } |
|
271 | - |
|
272 | - return array_map(function (FileInfo $file) { |
|
273 | - return $this->createNode($file->getPath(), $file); |
|
274 | - }, $files); |
|
275 | - } |
|
276 | - |
|
277 | - /** |
|
278 | - * @param int $id |
|
279 | - * @return \OC\Files\Node\Node[] |
|
280 | - */ |
|
281 | - public function getById($id) { |
|
282 | - $mountCache = $this->root->getUserMountCache(); |
|
283 | - if (strpos($this->getPath(), '/', 1) > 0) { |
|
284 | - list(, $user) = explode('/', $this->getPath()); |
|
285 | - } else { |
|
286 | - $user = null; |
|
287 | - } |
|
288 | - $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user); |
|
289 | - $mounts = $this->root->getMountsIn($this->path); |
|
290 | - $mounts[] = $this->root->getMount($this->path); |
|
291 | - /** @var IMountPoint[] $folderMounts */ |
|
292 | - $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) { |
|
293 | - return $mountPoint->getMountPoint(); |
|
294 | - }, $mounts), $mounts); |
|
295 | - |
|
296 | - /** @var ICachedMountInfo[] $mountsContainingFile */ |
|
297 | - $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) { |
|
298 | - return isset($folderMounts[$cachedMountInfo->getMountPoint()]); |
|
299 | - })); |
|
300 | - |
|
301 | - if (count($mountsContainingFile) === 0) { |
|
302 | - return []; |
|
303 | - } |
|
304 | - |
|
305 | - // we only need to get the cache info once, since all mounts we found point to the same storage |
|
306 | - |
|
307 | - $mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()]; |
|
308 | - $cacheEntry = $mount->getStorage()->getCache()->get((int)$id); |
|
309 | - if (!$cacheEntry) { |
|
310 | - return []; |
|
311 | - } |
|
312 | - // cache jails will hide the "true" internal path |
|
313 | - $internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/'); |
|
314 | - |
|
315 | - $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) { |
|
316 | - $mount = $folderMounts[$cachedMountInfo->getMountPoint()]; |
|
317 | - $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath())); |
|
318 | - $pathRelativeToMount = ltrim($pathRelativeToMount, '/'); |
|
319 | - $absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount; |
|
320 | - return $this->root->createNode($absolutePath, new \OC\Files\FileInfo( |
|
321 | - $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount, |
|
322 | - \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount)) |
|
323 | - )); |
|
324 | - }, $mountsContainingFile); |
|
325 | - |
|
326 | - return array_filter($nodes, function (Node $node) { |
|
327 | - return $this->getRelativePath($node->getPath()); |
|
328 | - }); |
|
329 | - } |
|
330 | - |
|
331 | - public function getFreeSpace() { |
|
332 | - return $this->view->free_space($this->path); |
|
333 | - } |
|
334 | - |
|
335 | - public function delete() { |
|
336 | - if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) { |
|
337 | - $this->sendHooks(array('preDelete')); |
|
338 | - $fileInfo = $this->getFileInfo(); |
|
339 | - $this->view->rmdir($this->path); |
|
340 | - $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo); |
|
341 | - $this->root->emit('\OC\Files', 'postDelete', array($nonExisting)); |
|
342 | - $this->exists = false; |
|
343 | - } else { |
|
344 | - throw new NotPermittedException('No delete permission for path'); |
|
345 | - } |
|
346 | - } |
|
347 | - |
|
348 | - /** |
|
349 | - * Add a suffix to the name in case the file exists |
|
350 | - * |
|
351 | - * @param string $name |
|
352 | - * @return string |
|
353 | - * @throws NotPermittedException |
|
354 | - */ |
|
355 | - public function getNonExistingName($name) { |
|
356 | - $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view); |
|
357 | - return trim($this->getRelativePath($uniqueName), '/'); |
|
358 | - } |
|
359 | - |
|
360 | - /** |
|
361 | - * @param int $limit |
|
362 | - * @param int $offset |
|
363 | - * @return \OCP\Files\Node[] |
|
364 | - */ |
|
365 | - public function getRecent($limit, $offset = 0) { |
|
366 | - $mimetypeLoader = \OC::$server->getMimeTypeLoader(); |
|
367 | - $mounts = $this->root->getMountsIn($this->path); |
|
368 | - $mounts[] = $this->getMountPoint(); |
|
369 | - |
|
370 | - $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
371 | - return $mount->getStorage(); |
|
372 | - }); |
|
373 | - $storageIds = array_map(function (IMountPoint $mount) { |
|
374 | - return $mount->getStorage()->getCache()->getNumericStorageId(); |
|
375 | - }, $mounts); |
|
376 | - /** @var IMountPoint[] $mountMap */ |
|
377 | - $mountMap = array_combine($storageIds, $mounts); |
|
378 | - $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER); |
|
379 | - |
|
380 | - //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) |
|
381 | - |
|
382 | - $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
383 | - $query = $builder |
|
384 | - ->select('f.*') |
|
385 | - ->from('filecache', 'f') |
|
386 | - ->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY))) |
|
387 | - ->andWhere($builder->expr()->orX( |
|
388 | - // handle non empty folders separate |
|
389 | - $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)), |
|
390 | - $builder->expr()->eq('f.size', new Literal(0)) |
|
391 | - )) |
|
392 | - ->orderBy('f.mtime', 'DESC') |
|
393 | - ->setMaxResults($limit) |
|
394 | - ->setFirstResult($offset); |
|
395 | - |
|
396 | - $result = $query->execute()->fetchAll(); |
|
397 | - |
|
398 | - $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) { |
|
399 | - $mount = $mountMap[$entry['storage']]; |
|
400 | - $entry['internalPath'] = $entry['path']; |
|
401 | - $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']); |
|
402 | - $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']); |
|
403 | - $path = $this->getAbsolutePath($mount, $entry['path']); |
|
404 | - if (is_null($path)) { |
|
405 | - return null; |
|
406 | - } |
|
407 | - $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount); |
|
408 | - return $this->root->createNode($fileInfo->getPath(), $fileInfo); |
|
409 | - }, $result)); |
|
410 | - |
|
411 | - return array_values(array_filter($files, function (Node $node) { |
|
412 | - $relative = $this->getRelativePath($node->getPath()); |
|
413 | - return $relative !== null && $relative !== '/'; |
|
414 | - })); |
|
415 | - } |
|
416 | - |
|
417 | - private function getAbsolutePath(IMountPoint $mount, $path) { |
|
418 | - $storage = $mount->getStorage(); |
|
419 | - if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) { |
|
420 | - /** @var \OC\Files\Storage\Wrapper\Jail $storage */ |
|
421 | - $jailRoot = $storage->getUnjailedPath(''); |
|
422 | - $rootLength = strlen($jailRoot) + 1; |
|
423 | - if ($path === $jailRoot) { |
|
424 | - return $mount->getMountPoint(); |
|
425 | - } else if (substr($path, 0, $rootLength) === $jailRoot . '/') { |
|
426 | - return $mount->getMountPoint() . substr($path, $rootLength); |
|
427 | - } else { |
|
428 | - return null; |
|
429 | - } |
|
430 | - } else { |
|
431 | - return $mount->getMountPoint() . $path; |
|
432 | - } |
|
433 | - } |
|
39 | + /** |
|
40 | + * Creates a Folder that represents a non-existing path |
|
41 | + * |
|
42 | + * @param string $path path |
|
43 | + * @return string non-existing node class |
|
44 | + */ |
|
45 | + protected function createNonExistingNode($path) { |
|
46 | + return new NonExistingFolder($this->root, $this->view, $path); |
|
47 | + } |
|
48 | + |
|
49 | + /** |
|
50 | + * @param string $path path relative to the folder |
|
51 | + * @return string |
|
52 | + * @throws \OCP\Files\NotPermittedException |
|
53 | + */ |
|
54 | + public function getFullPath($path) { |
|
55 | + if (!$this->isValidPath($path)) { |
|
56 | + throw new NotPermittedException('Invalid path'); |
|
57 | + } |
|
58 | + return $this->path . $this->normalizePath($path); |
|
59 | + } |
|
60 | + |
|
61 | + /** |
|
62 | + * @param string $path |
|
63 | + * @return string |
|
64 | + */ |
|
65 | + public function getRelativePath($path) { |
|
66 | + if ($this->path === '' or $this->path === '/') { |
|
67 | + return $this->normalizePath($path); |
|
68 | + } |
|
69 | + if ($path === $this->path) { |
|
70 | + return '/'; |
|
71 | + } else if (strpos($path, $this->path . '/') !== 0) { |
|
72 | + return null; |
|
73 | + } else { |
|
74 | + $path = substr($path, strlen($this->path)); |
|
75 | + return $this->normalizePath($path); |
|
76 | + } |
|
77 | + } |
|
78 | + |
|
79 | + /** |
|
80 | + * check if a node is a (grand-)child of the folder |
|
81 | + * |
|
82 | + * @param \OC\Files\Node\Node $node |
|
83 | + * @return bool |
|
84 | + */ |
|
85 | + public function isSubNode($node) { |
|
86 | + return strpos($node->getPath(), $this->path . '/') === 0; |
|
87 | + } |
|
88 | + |
|
89 | + /** |
|
90 | + * get the content of this directory |
|
91 | + * |
|
92 | + * @throws \OCP\Files\NotFoundException |
|
93 | + * @return Node[] |
|
94 | + */ |
|
95 | + public function getDirectoryListing() { |
|
96 | + $folderContent = $this->view->getDirectoryContent($this->path); |
|
97 | + |
|
98 | + return array_map(function (FileInfo $info) { |
|
99 | + if ($info->getMimetype() === 'httpd/unix-directory') { |
|
100 | + return new Folder($this->root, $this->view, $info->getPath(), $info); |
|
101 | + } else { |
|
102 | + return new File($this->root, $this->view, $info->getPath(), $info); |
|
103 | + } |
|
104 | + }, $folderContent); |
|
105 | + } |
|
106 | + |
|
107 | + /** |
|
108 | + * @param string $path |
|
109 | + * @param FileInfo $info |
|
110 | + * @return File|Folder |
|
111 | + */ |
|
112 | + protected function createNode($path, FileInfo $info = null) { |
|
113 | + if (is_null($info)) { |
|
114 | + $isDir = $this->view->is_dir($path); |
|
115 | + } else { |
|
116 | + $isDir = $info->getType() === FileInfo::TYPE_FOLDER; |
|
117 | + } |
|
118 | + if ($isDir) { |
|
119 | + return new Folder($this->root, $this->view, $path, $info); |
|
120 | + } else { |
|
121 | + return new File($this->root, $this->view, $path, $info); |
|
122 | + } |
|
123 | + } |
|
124 | + |
|
125 | + /** |
|
126 | + * Get the node at $path |
|
127 | + * |
|
128 | + * @param string $path |
|
129 | + * @return \OC\Files\Node\Node |
|
130 | + * @throws \OCP\Files\NotFoundException |
|
131 | + */ |
|
132 | + public function get($path) { |
|
133 | + return $this->root->get($this->getFullPath($path)); |
|
134 | + } |
|
135 | + |
|
136 | + /** |
|
137 | + * @param string $path |
|
138 | + * @return bool |
|
139 | + */ |
|
140 | + public function nodeExists($path) { |
|
141 | + try { |
|
142 | + $this->get($path); |
|
143 | + return true; |
|
144 | + } catch (NotFoundException $e) { |
|
145 | + return false; |
|
146 | + } |
|
147 | + } |
|
148 | + |
|
149 | + /** |
|
150 | + * @param string $path |
|
151 | + * @return \OC\Files\Node\Folder |
|
152 | + * @throws \OCP\Files\NotPermittedException |
|
153 | + */ |
|
154 | + public function newFolder($path) { |
|
155 | + if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) { |
|
156 | + $fullPath = $this->getFullPath($path); |
|
157 | + $nonExisting = new NonExistingFolder($this->root, $this->view, $fullPath); |
|
158 | + $this->root->emit('\OC\Files', 'preWrite', array($nonExisting)); |
|
159 | + $this->root->emit('\OC\Files', 'preCreate', array($nonExisting)); |
|
160 | + $this->view->mkdir($fullPath); |
|
161 | + $node = new Folder($this->root, $this->view, $fullPath); |
|
162 | + $this->root->emit('\OC\Files', 'postWrite', array($node)); |
|
163 | + $this->root->emit('\OC\Files', 'postCreate', array($node)); |
|
164 | + return $node; |
|
165 | + } else { |
|
166 | + throw new NotPermittedException('No create permission for folder'); |
|
167 | + } |
|
168 | + } |
|
169 | + |
|
170 | + /** |
|
171 | + * @param string $path |
|
172 | + * @return \OC\Files\Node\File |
|
173 | + * @throws \OCP\Files\NotPermittedException |
|
174 | + */ |
|
175 | + public function newFile($path) { |
|
176 | + if ($this->checkPermissions(\OCP\Constants::PERMISSION_CREATE)) { |
|
177 | + $fullPath = $this->getFullPath($path); |
|
178 | + $nonExisting = new NonExistingFile($this->root, $this->view, $fullPath); |
|
179 | + $this->root->emit('\OC\Files', 'preWrite', array($nonExisting)); |
|
180 | + $this->root->emit('\OC\Files', 'preCreate', array($nonExisting)); |
|
181 | + $this->view->touch($fullPath); |
|
182 | + $node = new File($this->root, $this->view, $fullPath); |
|
183 | + $this->root->emit('\OC\Files', 'postWrite', array($node)); |
|
184 | + $this->root->emit('\OC\Files', 'postCreate', array($node)); |
|
185 | + return $node; |
|
186 | + } else { |
|
187 | + throw new NotPermittedException('No create permission for path'); |
|
188 | + } |
|
189 | + } |
|
190 | + |
|
191 | + /** |
|
192 | + * search for files with the name matching $query |
|
193 | + * |
|
194 | + * @param string|ISearchOperator $query |
|
195 | + * @return \OC\Files\Node\Node[] |
|
196 | + */ |
|
197 | + public function search($query) { |
|
198 | + if (is_string($query)) { |
|
199 | + return $this->searchCommon('search', array('%' . $query . '%')); |
|
200 | + } else { |
|
201 | + return $this->searchCommon('searchQuery', array($query)); |
|
202 | + } |
|
203 | + } |
|
204 | + |
|
205 | + /** |
|
206 | + * search for files by mimetype |
|
207 | + * |
|
208 | + * @param string $mimetype |
|
209 | + * @return Node[] |
|
210 | + */ |
|
211 | + public function searchByMime($mimetype) { |
|
212 | + return $this->searchCommon('searchByMime', array($mimetype)); |
|
213 | + } |
|
214 | + |
|
215 | + /** |
|
216 | + * search for files by tag |
|
217 | + * |
|
218 | + * @param string|int $tag name or tag id |
|
219 | + * @param string $userId owner of the tags |
|
220 | + * @return Node[] |
|
221 | + */ |
|
222 | + public function searchByTag($tag, $userId) { |
|
223 | + return $this->searchCommon('searchByTag', array($tag, $userId)); |
|
224 | + } |
|
225 | + |
|
226 | + /** |
|
227 | + * @param string $method cache method |
|
228 | + * @param array $args call args |
|
229 | + * @return \OC\Files\Node\Node[] |
|
230 | + */ |
|
231 | + private function searchCommon($method, $args) { |
|
232 | + $files = array(); |
|
233 | + $rootLength = strlen($this->path); |
|
234 | + $mount = $this->root->getMount($this->path); |
|
235 | + $storage = $mount->getStorage(); |
|
236 | + $internalPath = $mount->getInternalPath($this->path); |
|
237 | + $internalPath = rtrim($internalPath, '/'); |
|
238 | + if ($internalPath !== '') { |
|
239 | + $internalPath = $internalPath . '/'; |
|
240 | + } |
|
241 | + $internalRootLength = strlen($internalPath); |
|
242 | + |
|
243 | + $cache = $storage->getCache(''); |
|
244 | + |
|
245 | + $results = call_user_func_array(array($cache, $method), $args); |
|
246 | + foreach ($results as $result) { |
|
247 | + if ($internalRootLength === 0 or substr($result['path'], 0, $internalRootLength) === $internalPath) { |
|
248 | + $result['internalPath'] = $result['path']; |
|
249 | + $result['path'] = substr($result['path'], $internalRootLength); |
|
250 | + $result['storage'] = $storage; |
|
251 | + $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount); |
|
252 | + } |
|
253 | + } |
|
254 | + |
|
255 | + $mounts = $this->root->getMountsIn($this->path); |
|
256 | + foreach ($mounts as $mount) { |
|
257 | + $storage = $mount->getStorage(); |
|
258 | + if ($storage) { |
|
259 | + $cache = $storage->getCache(''); |
|
260 | + |
|
261 | + $relativeMountPoint = substr($mount->getMountPoint(), $rootLength); |
|
262 | + $results = call_user_func_array(array($cache, $method), $args); |
|
263 | + foreach ($results as $result) { |
|
264 | + $result['internalPath'] = $result['path']; |
|
265 | + $result['path'] = $relativeMountPoint . $result['path']; |
|
266 | + $result['storage'] = $storage; |
|
267 | + $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount); |
|
268 | + } |
|
269 | + } |
|
270 | + } |
|
271 | + |
|
272 | + return array_map(function (FileInfo $file) { |
|
273 | + return $this->createNode($file->getPath(), $file); |
|
274 | + }, $files); |
|
275 | + } |
|
276 | + |
|
277 | + /** |
|
278 | + * @param int $id |
|
279 | + * @return \OC\Files\Node\Node[] |
|
280 | + */ |
|
281 | + public function getById($id) { |
|
282 | + $mountCache = $this->root->getUserMountCache(); |
|
283 | + if (strpos($this->getPath(), '/', 1) > 0) { |
|
284 | + list(, $user) = explode('/', $this->getPath()); |
|
285 | + } else { |
|
286 | + $user = null; |
|
287 | + } |
|
288 | + $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user); |
|
289 | + $mounts = $this->root->getMountsIn($this->path); |
|
290 | + $mounts[] = $this->root->getMount($this->path); |
|
291 | + /** @var IMountPoint[] $folderMounts */ |
|
292 | + $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) { |
|
293 | + return $mountPoint->getMountPoint(); |
|
294 | + }, $mounts), $mounts); |
|
295 | + |
|
296 | + /** @var ICachedMountInfo[] $mountsContainingFile */ |
|
297 | + $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) { |
|
298 | + return isset($folderMounts[$cachedMountInfo->getMountPoint()]); |
|
299 | + })); |
|
300 | + |
|
301 | + if (count($mountsContainingFile) === 0) { |
|
302 | + return []; |
|
303 | + } |
|
304 | + |
|
305 | + // we only need to get the cache info once, since all mounts we found point to the same storage |
|
306 | + |
|
307 | + $mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()]; |
|
308 | + $cacheEntry = $mount->getStorage()->getCache()->get((int)$id); |
|
309 | + if (!$cacheEntry) { |
|
310 | + return []; |
|
311 | + } |
|
312 | + // cache jails will hide the "true" internal path |
|
313 | + $internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/'); |
|
314 | + |
|
315 | + $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) { |
|
316 | + $mount = $folderMounts[$cachedMountInfo->getMountPoint()]; |
|
317 | + $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath())); |
|
318 | + $pathRelativeToMount = ltrim($pathRelativeToMount, '/'); |
|
319 | + $absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount; |
|
320 | + return $this->root->createNode($absolutePath, new \OC\Files\FileInfo( |
|
321 | + $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount, |
|
322 | + \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount)) |
|
323 | + )); |
|
324 | + }, $mountsContainingFile); |
|
325 | + |
|
326 | + return array_filter($nodes, function (Node $node) { |
|
327 | + return $this->getRelativePath($node->getPath()); |
|
328 | + }); |
|
329 | + } |
|
330 | + |
|
331 | + public function getFreeSpace() { |
|
332 | + return $this->view->free_space($this->path); |
|
333 | + } |
|
334 | + |
|
335 | + public function delete() { |
|
336 | + if ($this->checkPermissions(\OCP\Constants::PERMISSION_DELETE)) { |
|
337 | + $this->sendHooks(array('preDelete')); |
|
338 | + $fileInfo = $this->getFileInfo(); |
|
339 | + $this->view->rmdir($this->path); |
|
340 | + $nonExisting = new NonExistingFolder($this->root, $this->view, $this->path, $fileInfo); |
|
341 | + $this->root->emit('\OC\Files', 'postDelete', array($nonExisting)); |
|
342 | + $this->exists = false; |
|
343 | + } else { |
|
344 | + throw new NotPermittedException('No delete permission for path'); |
|
345 | + } |
|
346 | + } |
|
347 | + |
|
348 | + /** |
|
349 | + * Add a suffix to the name in case the file exists |
|
350 | + * |
|
351 | + * @param string $name |
|
352 | + * @return string |
|
353 | + * @throws NotPermittedException |
|
354 | + */ |
|
355 | + public function getNonExistingName($name) { |
|
356 | + $uniqueName = \OC_Helper::buildNotExistingFileNameForView($this->getPath(), $name, $this->view); |
|
357 | + return trim($this->getRelativePath($uniqueName), '/'); |
|
358 | + } |
|
359 | + |
|
360 | + /** |
|
361 | + * @param int $limit |
|
362 | + * @param int $offset |
|
363 | + * @return \OCP\Files\Node[] |
|
364 | + */ |
|
365 | + public function getRecent($limit, $offset = 0) { |
|
366 | + $mimetypeLoader = \OC::$server->getMimeTypeLoader(); |
|
367 | + $mounts = $this->root->getMountsIn($this->path); |
|
368 | + $mounts[] = $this->getMountPoint(); |
|
369 | + |
|
370 | + $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
371 | + return $mount->getStorage(); |
|
372 | + }); |
|
373 | + $storageIds = array_map(function (IMountPoint $mount) { |
|
374 | + return $mount->getStorage()->getCache()->getNumericStorageId(); |
|
375 | + }, $mounts); |
|
376 | + /** @var IMountPoint[] $mountMap */ |
|
377 | + $mountMap = array_combine($storageIds, $mounts); |
|
378 | + $folderMimetype = $mimetypeLoader->getId(FileInfo::MIMETYPE_FOLDER); |
|
379 | + |
|
380 | + //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) |
|
381 | + |
|
382 | + $builder = \OC::$server->getDatabaseConnection()->getQueryBuilder(); |
|
383 | + $query = $builder |
|
384 | + ->select('f.*') |
|
385 | + ->from('filecache', 'f') |
|
386 | + ->andWhere($builder->expr()->in('f.storage', $builder->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY))) |
|
387 | + ->andWhere($builder->expr()->orX( |
|
388 | + // handle non empty folders separate |
|
389 | + $builder->expr()->neq('f.mimetype', $builder->createNamedParameter($folderMimetype, IQueryBuilder::PARAM_INT)), |
|
390 | + $builder->expr()->eq('f.size', new Literal(0)) |
|
391 | + )) |
|
392 | + ->orderBy('f.mtime', 'DESC') |
|
393 | + ->setMaxResults($limit) |
|
394 | + ->setFirstResult($offset); |
|
395 | + |
|
396 | + $result = $query->execute()->fetchAll(); |
|
397 | + |
|
398 | + $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) { |
|
399 | + $mount = $mountMap[$entry['storage']]; |
|
400 | + $entry['internalPath'] = $entry['path']; |
|
401 | + $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']); |
|
402 | + $entry['mimepart'] = $mimetypeLoader->getMimetypeById($entry['mimepart']); |
|
403 | + $path = $this->getAbsolutePath($mount, $entry['path']); |
|
404 | + if (is_null($path)) { |
|
405 | + return null; |
|
406 | + } |
|
407 | + $fileInfo = new \OC\Files\FileInfo($path, $mount->getStorage(), $entry['internalPath'], $entry, $mount); |
|
408 | + return $this->root->createNode($fileInfo->getPath(), $fileInfo); |
|
409 | + }, $result)); |
|
410 | + |
|
411 | + return array_values(array_filter($files, function (Node $node) { |
|
412 | + $relative = $this->getRelativePath($node->getPath()); |
|
413 | + return $relative !== null && $relative !== '/'; |
|
414 | + })); |
|
415 | + } |
|
416 | + |
|
417 | + private function getAbsolutePath(IMountPoint $mount, $path) { |
|
418 | + $storage = $mount->getStorage(); |
|
419 | + if ($storage->instanceOfStorage('\OC\Files\Storage\Wrapper\Jail')) { |
|
420 | + /** @var \OC\Files\Storage\Wrapper\Jail $storage */ |
|
421 | + $jailRoot = $storage->getUnjailedPath(''); |
|
422 | + $rootLength = strlen($jailRoot) + 1; |
|
423 | + if ($path === $jailRoot) { |
|
424 | + return $mount->getMountPoint(); |
|
425 | + } else if (substr($path, 0, $rootLength) === $jailRoot . '/') { |
|
426 | + return $mount->getMountPoint() . substr($path, $rootLength); |
|
427 | + } else { |
|
428 | + return null; |
|
429 | + } |
|
430 | + } else { |
|
431 | + return $mount->getMountPoint() . $path; |
|
432 | + } |
|
433 | + } |
|
434 | 434 | } |
@@ -55,7 +55,7 @@ discard block |
||
55 | 55 | if (!$this->isValidPath($path)) { |
56 | 56 | throw new NotPermittedException('Invalid path'); |
57 | 57 | } |
58 | - return $this->path . $this->normalizePath($path); |
|
58 | + return $this->path.$this->normalizePath($path); |
|
59 | 59 | } |
60 | 60 | |
61 | 61 | /** |
@@ -68,7 +68,7 @@ discard block |
||
68 | 68 | } |
69 | 69 | if ($path === $this->path) { |
70 | 70 | return '/'; |
71 | - } else if (strpos($path, $this->path . '/') !== 0) { |
|
71 | + } else if (strpos($path, $this->path.'/') !== 0) { |
|
72 | 72 | return null; |
73 | 73 | } else { |
74 | 74 | $path = substr($path, strlen($this->path)); |
@@ -83,7 +83,7 @@ discard block |
||
83 | 83 | * @return bool |
84 | 84 | */ |
85 | 85 | public function isSubNode($node) { |
86 | - return strpos($node->getPath(), $this->path . '/') === 0; |
|
86 | + return strpos($node->getPath(), $this->path.'/') === 0; |
|
87 | 87 | } |
88 | 88 | |
89 | 89 | /** |
@@ -95,7 +95,7 @@ discard block |
||
95 | 95 | public function getDirectoryListing() { |
96 | 96 | $folderContent = $this->view->getDirectoryContent($this->path); |
97 | 97 | |
98 | - return array_map(function (FileInfo $info) { |
|
98 | + return array_map(function(FileInfo $info) { |
|
99 | 99 | if ($info->getMimetype() === 'httpd/unix-directory') { |
100 | 100 | return new Folder($this->root, $this->view, $info->getPath(), $info); |
101 | 101 | } else { |
@@ -196,7 +196,7 @@ discard block |
||
196 | 196 | */ |
197 | 197 | public function search($query) { |
198 | 198 | if (is_string($query)) { |
199 | - return $this->searchCommon('search', array('%' . $query . '%')); |
|
199 | + return $this->searchCommon('search', array('%'.$query.'%')); |
|
200 | 200 | } else { |
201 | 201 | return $this->searchCommon('searchQuery', array($query)); |
202 | 202 | } |
@@ -236,7 +236,7 @@ discard block |
||
236 | 236 | $internalPath = $mount->getInternalPath($this->path); |
237 | 237 | $internalPath = rtrim($internalPath, '/'); |
238 | 238 | if ($internalPath !== '') { |
239 | - $internalPath = $internalPath . '/'; |
|
239 | + $internalPath = $internalPath.'/'; |
|
240 | 240 | } |
241 | 241 | $internalRootLength = strlen($internalPath); |
242 | 242 | |
@@ -248,7 +248,7 @@ discard block |
||
248 | 248 | $result['internalPath'] = $result['path']; |
249 | 249 | $result['path'] = substr($result['path'], $internalRootLength); |
250 | 250 | $result['storage'] = $storage; |
251 | - $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount); |
|
251 | + $files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount); |
|
252 | 252 | } |
253 | 253 | } |
254 | 254 | |
@@ -262,14 +262,14 @@ discard block |
||
262 | 262 | $results = call_user_func_array(array($cache, $method), $args); |
263 | 263 | foreach ($results as $result) { |
264 | 264 | $result['internalPath'] = $result['path']; |
265 | - $result['path'] = $relativeMountPoint . $result['path']; |
|
265 | + $result['path'] = $relativeMountPoint.$result['path']; |
|
266 | 266 | $result['storage'] = $storage; |
267 | - $files[] = new \OC\Files\FileInfo($this->path . '/' . $result['path'], $storage, $result['internalPath'], $result, $mount); |
|
267 | + $files[] = new \OC\Files\FileInfo($this->path.'/'.$result['path'], $storage, $result['internalPath'], $result, $mount); |
|
268 | 268 | } |
269 | 269 | } |
270 | 270 | } |
271 | 271 | |
272 | - return array_map(function (FileInfo $file) { |
|
272 | + return array_map(function(FileInfo $file) { |
|
273 | 273 | return $this->createNode($file->getPath(), $file); |
274 | 274 | }, $files); |
275 | 275 | } |
@@ -285,16 +285,16 @@ discard block |
||
285 | 285 | } else { |
286 | 286 | $user = null; |
287 | 287 | } |
288 | - $mountsContainingFile = $mountCache->getMountsForFileId((int)$id, $user); |
|
288 | + $mountsContainingFile = $mountCache->getMountsForFileId((int) $id, $user); |
|
289 | 289 | $mounts = $this->root->getMountsIn($this->path); |
290 | 290 | $mounts[] = $this->root->getMount($this->path); |
291 | 291 | /** @var IMountPoint[] $folderMounts */ |
292 | - $folderMounts = array_combine(array_map(function (IMountPoint $mountPoint) { |
|
292 | + $folderMounts = array_combine(array_map(function(IMountPoint $mountPoint) { |
|
293 | 293 | return $mountPoint->getMountPoint(); |
294 | 294 | }, $mounts), $mounts); |
295 | 295 | |
296 | 296 | /** @var ICachedMountInfo[] $mountsContainingFile */ |
297 | - $mountsContainingFile = array_values(array_filter($mountsContainingFile, function (ICachedMountInfo $cachedMountInfo) use ($folderMounts) { |
|
297 | + $mountsContainingFile = array_values(array_filter($mountsContainingFile, function(ICachedMountInfo $cachedMountInfo) use ($folderMounts) { |
|
298 | 298 | return isset($folderMounts[$cachedMountInfo->getMountPoint()]); |
299 | 299 | })); |
300 | 300 | |
@@ -305,25 +305,25 @@ discard block |
||
305 | 305 | // we only need to get the cache info once, since all mounts we found point to the same storage |
306 | 306 | |
307 | 307 | $mount = $folderMounts[$mountsContainingFile[0]->getMountPoint()]; |
308 | - $cacheEntry = $mount->getStorage()->getCache()->get((int)$id); |
|
308 | + $cacheEntry = $mount->getStorage()->getCache()->get((int) $id); |
|
309 | 309 | if (!$cacheEntry) { |
310 | 310 | return []; |
311 | 311 | } |
312 | 312 | // cache jails will hide the "true" internal path |
313 | - $internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath() . '/' . $cacheEntry->getPath(), '/'); |
|
313 | + $internalPath = ltrim($mountsContainingFile[0]->getRootInternalPath().'/'.$cacheEntry->getPath(), '/'); |
|
314 | 314 | |
315 | - $nodes = array_map(function (ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) { |
|
315 | + $nodes = array_map(function(ICachedMountInfo $cachedMountInfo) use ($cacheEntry, $folderMounts, $internalPath) { |
|
316 | 316 | $mount = $folderMounts[$cachedMountInfo->getMountPoint()]; |
317 | 317 | $pathRelativeToMount = substr($internalPath, strlen($cachedMountInfo->getRootInternalPath())); |
318 | 318 | $pathRelativeToMount = ltrim($pathRelativeToMount, '/'); |
319 | - $absolutePath = $cachedMountInfo->getMountPoint() . $pathRelativeToMount; |
|
319 | + $absolutePath = $cachedMountInfo->getMountPoint().$pathRelativeToMount; |
|
320 | 320 | return $this->root->createNode($absolutePath, new \OC\Files\FileInfo( |
321 | 321 | $absolutePath, $mount->getStorage(), $cacheEntry->getPath(), $cacheEntry, $mount, |
322 | 322 | \OC::$server->getUserManager()->get($mount->getStorage()->getOwner($pathRelativeToMount)) |
323 | 323 | )); |
324 | 324 | }, $mountsContainingFile); |
325 | 325 | |
326 | - return array_filter($nodes, function (Node $node) { |
|
326 | + return array_filter($nodes, function(Node $node) { |
|
327 | 327 | return $this->getRelativePath($node->getPath()); |
328 | 328 | }); |
329 | 329 | } |
@@ -367,10 +367,10 @@ discard block |
||
367 | 367 | $mounts = $this->root->getMountsIn($this->path); |
368 | 368 | $mounts[] = $this->getMountPoint(); |
369 | 369 | |
370 | - $mounts = array_filter($mounts, function (IMountPoint $mount) { |
|
370 | + $mounts = array_filter($mounts, function(IMountPoint $mount) { |
|
371 | 371 | return $mount->getStorage(); |
372 | 372 | }); |
373 | - $storageIds = array_map(function (IMountPoint $mount) { |
|
373 | + $storageIds = array_map(function(IMountPoint $mount) { |
|
374 | 374 | return $mount->getStorage()->getCache()->getNumericStorageId(); |
375 | 375 | }, $mounts); |
376 | 376 | /** @var IMountPoint[] $mountMap */ |
@@ -395,7 +395,7 @@ discard block |
||
395 | 395 | |
396 | 396 | $result = $query->execute()->fetchAll(); |
397 | 397 | |
398 | - $files = array_filter(array_map(function (array $entry) use ($mountMap, $mimetypeLoader) { |
|
398 | + $files = array_filter(array_map(function(array $entry) use ($mountMap, $mimetypeLoader) { |
|
399 | 399 | $mount = $mountMap[$entry['storage']]; |
400 | 400 | $entry['internalPath'] = $entry['path']; |
401 | 401 | $entry['mimetype'] = $mimetypeLoader->getMimetypeById($entry['mimetype']); |
@@ -408,7 +408,7 @@ discard block |
||
408 | 408 | return $this->root->createNode($fileInfo->getPath(), $fileInfo); |
409 | 409 | }, $result)); |
410 | 410 | |
411 | - return array_values(array_filter($files, function (Node $node) { |
|
411 | + return array_values(array_filter($files, function(Node $node) { |
|
412 | 412 | $relative = $this->getRelativePath($node->getPath()); |
413 | 413 | return $relative !== null && $relative !== '/'; |
414 | 414 | })); |
@@ -422,13 +422,13 @@ discard block |
||
422 | 422 | $rootLength = strlen($jailRoot) + 1; |
423 | 423 | if ($path === $jailRoot) { |
424 | 424 | return $mount->getMountPoint(); |
425 | - } else if (substr($path, 0, $rootLength) === $jailRoot . '/') { |
|
426 | - return $mount->getMountPoint() . substr($path, $rootLength); |
|
425 | + } else if (substr($path, 0, $rootLength) === $jailRoot.'/') { |
|
426 | + return $mount->getMountPoint().substr($path, $rootLength); |
|
427 | 427 | } else { |
428 | 428 | return null; |
429 | 429 | } |
430 | 430 | } else { |
431 | - return $mount->getMountPoint() . $path; |
|
431 | + return $mount->getMountPoint().$path; |
|
432 | 432 | } |
433 | 433 | } |
434 | 434 | } |
@@ -33,6 +33,7 @@ |
||
33 | 33 | * |
34 | 34 | * @returns string |
35 | 35 | * @since 12 |
36 | + * @return string |
|
36 | 37 | */ |
37 | 38 | public function getIcon(); |
38 | 39 | } |
@@ -27,12 +27,12 @@ |
||
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 | } |
@@ -139,6 +139,9 @@ |
||
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); |
@@ -37,122 +37,122 @@ |
||
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 | } |
@@ -36,28 +36,28 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 | } |
@@ -93,8 +93,7 @@ |
||
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); |
@@ -616,6 +616,9 @@ |
||
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); |
@@ -48,606 +48,606 @@ |
||
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 'a': |
|
377 | - case 'ab': |
|
378 | - case 'a+': |
|
379 | - return false; |
|
380 | - case 'r': |
|
381 | - case 'rb': |
|
382 | - try { |
|
383 | - $c = $this->getContainer(); |
|
384 | - $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory(); |
|
385 | - $streamInterface = $streamFactory->fromRequest( |
|
386 | - $c->getClient() |
|
387 | - ->get($c->getUrl($path))); |
|
388 | - $streamInterface->rewind(); |
|
389 | - $stream = $streamInterface->getStream(); |
|
390 | - stream_context_set_option($stream, 'swift','content', $streamInterface); |
|
391 | - if(!strrpos($streamInterface |
|
392 | - ->getMetaData('wrapper_data')[0], '404 Not Found')) { |
|
393 | - return $stream; |
|
394 | - } |
|
395 | - return false; |
|
396 | - } catch (\Guzzle\Http\Exception\BadResponseException $e) { |
|
397 | - \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
|
398 | - return false; |
|
399 | - } |
|
400 | - case 'w': |
|
401 | - case 'wb': |
|
402 | - case 'r+': |
|
403 | - case 'w+': |
|
404 | - case 'wb+': |
|
405 | - case 'x': |
|
406 | - case 'x+': |
|
407 | - case 'c': |
|
408 | - case 'c+': |
|
409 | - if (strrpos($path, '.') !== false) { |
|
410 | - $ext = substr($path, strrpos($path, '.')); |
|
411 | - } else { |
|
412 | - $ext = ''; |
|
413 | - } |
|
414 | - $tmpFile = \OCP\Files::tmpFile($ext); |
|
415 | - // Fetch existing file if required |
|
416 | - if ($mode[0] !== 'w' && $this->file_exists($path)) { |
|
417 | - if ($mode[0] === 'x') { |
|
418 | - // File cannot already exist |
|
419 | - return false; |
|
420 | - } |
|
421 | - $source = $this->fopen($path, 'r'); |
|
422 | - file_put_contents($tmpFile, $source); |
|
423 | - } |
|
424 | - $handle = fopen($tmpFile, $mode); |
|
425 | - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { |
|
426 | - $this->writeBack($tmpFile, $path); |
|
427 | - }); |
|
428 | - } |
|
429 | - } |
|
430 | - |
|
431 | - public function touch($path, $mtime = null) { |
|
432 | - $path = $this->normalizePath($path); |
|
433 | - if (is_null($mtime)) { |
|
434 | - $mtime = time(); |
|
435 | - } |
|
436 | - $metadata = array('timestamp' => $mtime); |
|
437 | - if ($this->file_exists($path)) { |
|
438 | - if ($this->is_dir($path) && $path != '.') { |
|
439 | - $path .= '/'; |
|
440 | - } |
|
441 | - |
|
442 | - $object = $this->fetchObject($path); |
|
443 | - if ($object->saveMetadata($metadata)) { |
|
444 | - // invalidate target object to force repopulation on fetch |
|
445 | - $this->objectCache->remove($path); |
|
446 | - } |
|
447 | - return true; |
|
448 | - } else { |
|
449 | - $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path); |
|
450 | - $customHeaders = array('content-type' => $mimeType); |
|
451 | - $metadataHeaders = DataObject::stockHeaders($metadata); |
|
452 | - $allHeaders = $customHeaders + $metadataHeaders; |
|
453 | - $this->getContainer()->uploadObject($path, '', $allHeaders); |
|
454 | - // invalidate target object to force repopulation on fetch |
|
455 | - $this->objectCache->remove($path); |
|
456 | - return true; |
|
457 | - } |
|
458 | - } |
|
459 | - |
|
460 | - public function copy($path1, $path2) { |
|
461 | - $path1 = $this->normalizePath($path1); |
|
462 | - $path2 = $this->normalizePath($path2); |
|
463 | - |
|
464 | - $fileType = $this->filetype($path1); |
|
465 | - if ($fileType === 'file') { |
|
466 | - |
|
467 | - // make way |
|
468 | - $this->unlink($path2); |
|
469 | - |
|
470 | - try { |
|
471 | - $source = $this->fetchObject($path1); |
|
472 | - $source->copy($this->bucket . '/' . $path2); |
|
473 | - // invalidate target object to force repopulation on fetch |
|
474 | - $this->objectCache->remove($path2); |
|
475 | - $this->objectCache->remove($path2 . '/'); |
|
476 | - } catch (ClientErrorResponseException $e) { |
|
477 | - \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
|
478 | - return false; |
|
479 | - } |
|
480 | - |
|
481 | - } else if ($fileType === 'dir') { |
|
482 | - |
|
483 | - // make way |
|
484 | - $this->unlink($path2); |
|
485 | - |
|
486 | - try { |
|
487 | - $source = $this->fetchObject($path1 . '/'); |
|
488 | - $source->copy($this->bucket . '/' . $path2 . '/'); |
|
489 | - // invalidate target object to force repopulation on fetch |
|
490 | - $this->objectCache->remove($path2); |
|
491 | - $this->objectCache->remove($path2 . '/'); |
|
492 | - } catch (ClientErrorResponseException $e) { |
|
493 | - \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
|
494 | - return false; |
|
495 | - } |
|
496 | - |
|
497 | - $dh = $this->opendir($path1); |
|
498 | - while ($file = readdir($dh)) { |
|
499 | - if (\OC\Files\Filesystem::isIgnoredDir($file)) { |
|
500 | - continue; |
|
501 | - } |
|
502 | - |
|
503 | - $source = $path1 . '/' . $file; |
|
504 | - $target = $path2 . '/' . $file; |
|
505 | - $this->copy($source, $target); |
|
506 | - } |
|
507 | - |
|
508 | - } else { |
|
509 | - //file does not exist |
|
510 | - return false; |
|
511 | - } |
|
512 | - |
|
513 | - return true; |
|
514 | - } |
|
515 | - |
|
516 | - public function rename($path1, $path2) { |
|
517 | - $path1 = $this->normalizePath($path1); |
|
518 | - $path2 = $this->normalizePath($path2); |
|
519 | - |
|
520 | - $fileType = $this->filetype($path1); |
|
521 | - |
|
522 | - if ($fileType === 'dir' || $fileType === 'file') { |
|
523 | - // copy |
|
524 | - if ($this->copy($path1, $path2) === false) { |
|
525 | - return false; |
|
526 | - } |
|
527 | - |
|
528 | - // cleanup |
|
529 | - if ($this->unlink($path1) === false) { |
|
530 | - $this->unlink($path2); |
|
531 | - return false; |
|
532 | - } |
|
533 | - |
|
534 | - return true; |
|
535 | - } |
|
536 | - |
|
537 | - return false; |
|
538 | - } |
|
539 | - |
|
540 | - public function getId() { |
|
541 | - return $this->id; |
|
542 | - } |
|
543 | - |
|
544 | - /** |
|
545 | - * Returns the connection |
|
546 | - * |
|
547 | - * @return OpenCloud\ObjectStore\Service connected client |
|
548 | - * @throws \Exception if connection could not be made |
|
549 | - */ |
|
550 | - public function getConnection() { |
|
551 | - if (!is_null($this->connection)) { |
|
552 | - return $this->connection; |
|
553 | - } |
|
554 | - |
|
555 | - $settings = array( |
|
556 | - 'username' => $this->params['user'], |
|
557 | - ); |
|
558 | - |
|
559 | - if (!empty($this->params['password'])) { |
|
560 | - $settings['password'] = $this->params['password']; |
|
561 | - } else if (!empty($this->params['key'])) { |
|
562 | - $settings['apiKey'] = $this->params['key']; |
|
563 | - } |
|
564 | - |
|
565 | - if (!empty($this->params['tenant'])) { |
|
566 | - $settings['tenantName'] = $this->params['tenant']; |
|
567 | - } |
|
568 | - |
|
569 | - if (!empty($this->params['timeout'])) { |
|
570 | - $settings['timeout'] = $this->params['timeout']; |
|
571 | - } |
|
572 | - |
|
573 | - if (isset($settings['apiKey'])) { |
|
574 | - $this->anchor = new Rackspace($this->params['url'], $settings); |
|
575 | - } else { |
|
576 | - $this->anchor = new OpenStack($this->params['url'], $settings); |
|
577 | - } |
|
578 | - |
|
579 | - $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']); |
|
580 | - |
|
581 | - if (!empty($this->params['endpoint_url'])) { |
|
582 | - $endpoint = $connection->getEndpoint(); |
|
583 | - $endpoint->setPublicUrl($this->params['endpoint_url']); |
|
584 | - $endpoint->setPrivateUrl($this->params['endpoint_url']); |
|
585 | - $connection->setEndpoint($endpoint); |
|
586 | - } |
|
587 | - |
|
588 | - $this->connection = $connection; |
|
589 | - |
|
590 | - return $this->connection; |
|
591 | - } |
|
592 | - |
|
593 | - /** |
|
594 | - * Returns the initialized object store container. |
|
595 | - * |
|
596 | - * @return OpenCloud\ObjectStore\Resource\Container |
|
597 | - */ |
|
598 | - public function getContainer() { |
|
599 | - if (!is_null($this->container)) { |
|
600 | - return $this->container; |
|
601 | - } |
|
602 | - |
|
603 | - try { |
|
604 | - $this->container = $this->getConnection()->getContainer($this->bucket); |
|
605 | - } catch (ClientErrorResponseException $e) { |
|
606 | - $this->container = $this->getConnection()->createContainer($this->bucket); |
|
607 | - } |
|
608 | - |
|
609 | - if (!$this->file_exists('.')) { |
|
610 | - $this->mkdir('.'); |
|
611 | - } |
|
612 | - |
|
613 | - return $this->container; |
|
614 | - } |
|
615 | - |
|
616 | - public function writeBack($tmpFile, $path) { |
|
617 | - $fileData = fopen($tmpFile, 'r'); |
|
618 | - $this->getContainer()->uploadObject($path, $fileData); |
|
619 | - // invalidate target object to force repopulation on fetch |
|
620 | - $this->objectCache->remove(self::$tmpFiles[$tmpFile]); |
|
621 | - unlink($tmpFile); |
|
622 | - } |
|
623 | - |
|
624 | - public function hasUpdated($path, $time) { |
|
625 | - if ($this->is_file($path)) { |
|
626 | - return parent::hasUpdated($path, $time); |
|
627 | - } |
|
628 | - $path = $this->normalizePath($path); |
|
629 | - $dh = $this->opendir($path); |
|
630 | - $content = array(); |
|
631 | - while (($file = readdir($dh)) !== false) { |
|
632 | - $content[] = $file; |
|
633 | - } |
|
634 | - if ($path === '.') { |
|
635 | - $path = ''; |
|
636 | - } |
|
637 | - $cachedContent = $this->getCache()->getFolderContents($path); |
|
638 | - $cachedNames = array_map(function ($content) { |
|
639 | - return $content['name']; |
|
640 | - }, $cachedContent); |
|
641 | - sort($cachedNames); |
|
642 | - sort($content); |
|
643 | - return $cachedNames != $content; |
|
644 | - } |
|
645 | - |
|
646 | - /** |
|
647 | - * check if curl is installed |
|
648 | - */ |
|
649 | - public static function checkDependencies() { |
|
650 | - return true; |
|
651 | - } |
|
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 'a': |
|
377 | + case 'ab': |
|
378 | + case 'a+': |
|
379 | + return false; |
|
380 | + case 'r': |
|
381 | + case 'rb': |
|
382 | + try { |
|
383 | + $c = $this->getContainer(); |
|
384 | + $streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory(); |
|
385 | + $streamInterface = $streamFactory->fromRequest( |
|
386 | + $c->getClient() |
|
387 | + ->get($c->getUrl($path))); |
|
388 | + $streamInterface->rewind(); |
|
389 | + $stream = $streamInterface->getStream(); |
|
390 | + stream_context_set_option($stream, 'swift','content', $streamInterface); |
|
391 | + if(!strrpos($streamInterface |
|
392 | + ->getMetaData('wrapper_data')[0], '404 Not Found')) { |
|
393 | + return $stream; |
|
394 | + } |
|
395 | + return false; |
|
396 | + } catch (\Guzzle\Http\Exception\BadResponseException $e) { |
|
397 | + \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
|
398 | + return false; |
|
399 | + } |
|
400 | + case 'w': |
|
401 | + case 'wb': |
|
402 | + case 'r+': |
|
403 | + case 'w+': |
|
404 | + case 'wb+': |
|
405 | + case 'x': |
|
406 | + case 'x+': |
|
407 | + case 'c': |
|
408 | + case 'c+': |
|
409 | + if (strrpos($path, '.') !== false) { |
|
410 | + $ext = substr($path, strrpos($path, '.')); |
|
411 | + } else { |
|
412 | + $ext = ''; |
|
413 | + } |
|
414 | + $tmpFile = \OCP\Files::tmpFile($ext); |
|
415 | + // Fetch existing file if required |
|
416 | + if ($mode[0] !== 'w' && $this->file_exists($path)) { |
|
417 | + if ($mode[0] === 'x') { |
|
418 | + // File cannot already exist |
|
419 | + return false; |
|
420 | + } |
|
421 | + $source = $this->fopen($path, 'r'); |
|
422 | + file_put_contents($tmpFile, $source); |
|
423 | + } |
|
424 | + $handle = fopen($tmpFile, $mode); |
|
425 | + return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { |
|
426 | + $this->writeBack($tmpFile, $path); |
|
427 | + }); |
|
428 | + } |
|
429 | + } |
|
430 | + |
|
431 | + public function touch($path, $mtime = null) { |
|
432 | + $path = $this->normalizePath($path); |
|
433 | + if (is_null($mtime)) { |
|
434 | + $mtime = time(); |
|
435 | + } |
|
436 | + $metadata = array('timestamp' => $mtime); |
|
437 | + if ($this->file_exists($path)) { |
|
438 | + if ($this->is_dir($path) && $path != '.') { |
|
439 | + $path .= '/'; |
|
440 | + } |
|
441 | + |
|
442 | + $object = $this->fetchObject($path); |
|
443 | + if ($object->saveMetadata($metadata)) { |
|
444 | + // invalidate target object to force repopulation on fetch |
|
445 | + $this->objectCache->remove($path); |
|
446 | + } |
|
447 | + return true; |
|
448 | + } else { |
|
449 | + $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path); |
|
450 | + $customHeaders = array('content-type' => $mimeType); |
|
451 | + $metadataHeaders = DataObject::stockHeaders($metadata); |
|
452 | + $allHeaders = $customHeaders + $metadataHeaders; |
|
453 | + $this->getContainer()->uploadObject($path, '', $allHeaders); |
|
454 | + // invalidate target object to force repopulation on fetch |
|
455 | + $this->objectCache->remove($path); |
|
456 | + return true; |
|
457 | + } |
|
458 | + } |
|
459 | + |
|
460 | + public function copy($path1, $path2) { |
|
461 | + $path1 = $this->normalizePath($path1); |
|
462 | + $path2 = $this->normalizePath($path2); |
|
463 | + |
|
464 | + $fileType = $this->filetype($path1); |
|
465 | + if ($fileType === 'file') { |
|
466 | + |
|
467 | + // make way |
|
468 | + $this->unlink($path2); |
|
469 | + |
|
470 | + try { |
|
471 | + $source = $this->fetchObject($path1); |
|
472 | + $source->copy($this->bucket . '/' . $path2); |
|
473 | + // invalidate target object to force repopulation on fetch |
|
474 | + $this->objectCache->remove($path2); |
|
475 | + $this->objectCache->remove($path2 . '/'); |
|
476 | + } catch (ClientErrorResponseException $e) { |
|
477 | + \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
|
478 | + return false; |
|
479 | + } |
|
480 | + |
|
481 | + } else if ($fileType === 'dir') { |
|
482 | + |
|
483 | + // make way |
|
484 | + $this->unlink($path2); |
|
485 | + |
|
486 | + try { |
|
487 | + $source = $this->fetchObject($path1 . '/'); |
|
488 | + $source->copy($this->bucket . '/' . $path2 . '/'); |
|
489 | + // invalidate target object to force repopulation on fetch |
|
490 | + $this->objectCache->remove($path2); |
|
491 | + $this->objectCache->remove($path2 . '/'); |
|
492 | + } catch (ClientErrorResponseException $e) { |
|
493 | + \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
|
494 | + return false; |
|
495 | + } |
|
496 | + |
|
497 | + $dh = $this->opendir($path1); |
|
498 | + while ($file = readdir($dh)) { |
|
499 | + if (\OC\Files\Filesystem::isIgnoredDir($file)) { |
|
500 | + continue; |
|
501 | + } |
|
502 | + |
|
503 | + $source = $path1 . '/' . $file; |
|
504 | + $target = $path2 . '/' . $file; |
|
505 | + $this->copy($source, $target); |
|
506 | + } |
|
507 | + |
|
508 | + } else { |
|
509 | + //file does not exist |
|
510 | + return false; |
|
511 | + } |
|
512 | + |
|
513 | + return true; |
|
514 | + } |
|
515 | + |
|
516 | + public function rename($path1, $path2) { |
|
517 | + $path1 = $this->normalizePath($path1); |
|
518 | + $path2 = $this->normalizePath($path2); |
|
519 | + |
|
520 | + $fileType = $this->filetype($path1); |
|
521 | + |
|
522 | + if ($fileType === 'dir' || $fileType === 'file') { |
|
523 | + // copy |
|
524 | + if ($this->copy($path1, $path2) === false) { |
|
525 | + return false; |
|
526 | + } |
|
527 | + |
|
528 | + // cleanup |
|
529 | + if ($this->unlink($path1) === false) { |
|
530 | + $this->unlink($path2); |
|
531 | + return false; |
|
532 | + } |
|
533 | + |
|
534 | + return true; |
|
535 | + } |
|
536 | + |
|
537 | + return false; |
|
538 | + } |
|
539 | + |
|
540 | + public function getId() { |
|
541 | + return $this->id; |
|
542 | + } |
|
543 | + |
|
544 | + /** |
|
545 | + * Returns the connection |
|
546 | + * |
|
547 | + * @return OpenCloud\ObjectStore\Service connected client |
|
548 | + * @throws \Exception if connection could not be made |
|
549 | + */ |
|
550 | + public function getConnection() { |
|
551 | + if (!is_null($this->connection)) { |
|
552 | + return $this->connection; |
|
553 | + } |
|
554 | + |
|
555 | + $settings = array( |
|
556 | + 'username' => $this->params['user'], |
|
557 | + ); |
|
558 | + |
|
559 | + if (!empty($this->params['password'])) { |
|
560 | + $settings['password'] = $this->params['password']; |
|
561 | + } else if (!empty($this->params['key'])) { |
|
562 | + $settings['apiKey'] = $this->params['key']; |
|
563 | + } |
|
564 | + |
|
565 | + if (!empty($this->params['tenant'])) { |
|
566 | + $settings['tenantName'] = $this->params['tenant']; |
|
567 | + } |
|
568 | + |
|
569 | + if (!empty($this->params['timeout'])) { |
|
570 | + $settings['timeout'] = $this->params['timeout']; |
|
571 | + } |
|
572 | + |
|
573 | + if (isset($settings['apiKey'])) { |
|
574 | + $this->anchor = new Rackspace($this->params['url'], $settings); |
|
575 | + } else { |
|
576 | + $this->anchor = new OpenStack($this->params['url'], $settings); |
|
577 | + } |
|
578 | + |
|
579 | + $connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']); |
|
580 | + |
|
581 | + if (!empty($this->params['endpoint_url'])) { |
|
582 | + $endpoint = $connection->getEndpoint(); |
|
583 | + $endpoint->setPublicUrl($this->params['endpoint_url']); |
|
584 | + $endpoint->setPrivateUrl($this->params['endpoint_url']); |
|
585 | + $connection->setEndpoint($endpoint); |
|
586 | + } |
|
587 | + |
|
588 | + $this->connection = $connection; |
|
589 | + |
|
590 | + return $this->connection; |
|
591 | + } |
|
592 | + |
|
593 | + /** |
|
594 | + * Returns the initialized object store container. |
|
595 | + * |
|
596 | + * @return OpenCloud\ObjectStore\Resource\Container |
|
597 | + */ |
|
598 | + public function getContainer() { |
|
599 | + if (!is_null($this->container)) { |
|
600 | + return $this->container; |
|
601 | + } |
|
602 | + |
|
603 | + try { |
|
604 | + $this->container = $this->getConnection()->getContainer($this->bucket); |
|
605 | + } catch (ClientErrorResponseException $e) { |
|
606 | + $this->container = $this->getConnection()->createContainer($this->bucket); |
|
607 | + } |
|
608 | + |
|
609 | + if (!$this->file_exists('.')) { |
|
610 | + $this->mkdir('.'); |
|
611 | + } |
|
612 | + |
|
613 | + return $this->container; |
|
614 | + } |
|
615 | + |
|
616 | + public function writeBack($tmpFile, $path) { |
|
617 | + $fileData = fopen($tmpFile, 'r'); |
|
618 | + $this->getContainer()->uploadObject($path, $fileData); |
|
619 | + // invalidate target object to force repopulation on fetch |
|
620 | + $this->objectCache->remove(self::$tmpFiles[$tmpFile]); |
|
621 | + unlink($tmpFile); |
|
622 | + } |
|
623 | + |
|
624 | + public function hasUpdated($path, $time) { |
|
625 | + if ($this->is_file($path)) { |
|
626 | + return parent::hasUpdated($path, $time); |
|
627 | + } |
|
628 | + $path = $this->normalizePath($path); |
|
629 | + $dh = $this->opendir($path); |
|
630 | + $content = array(); |
|
631 | + while (($file = readdir($dh)) !== false) { |
|
632 | + $content[] = $file; |
|
633 | + } |
|
634 | + if ($path === '.') { |
|
635 | + $path = ''; |
|
636 | + } |
|
637 | + $cachedContent = $this->getCache()->getFolderContents($path); |
|
638 | + $cachedNames = array_map(function ($content) { |
|
639 | + return $content['name']; |
|
640 | + }, $cachedContent); |
|
641 | + sort($cachedNames); |
|
642 | + sort($content); |
|
643 | + return $cachedNames != $content; |
|
644 | + } |
|
645 | + |
|
646 | + /** |
|
647 | + * check if curl is installed |
|
648 | + */ |
|
649 | + public static function checkDependencies() { |
|
650 | + return true; |
|
651 | + } |
|
652 | 652 | |
653 | 653 | } |
@@ -163,7 +163,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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); |
@@ -387,8 +387,8 @@ discard block |
||
387 | 387 | ->get($c->getUrl($path))); |
388 | 388 | $streamInterface->rewind(); |
389 | 389 | $stream = $streamInterface->getStream(); |
390 | - stream_context_set_option($stream, 'swift','content', $streamInterface); |
|
391 | - if(!strrpos($streamInterface |
|
390 | + stream_context_set_option($stream, 'swift', 'content', $streamInterface); |
|
391 | + if (!strrpos($streamInterface |
|
392 | 392 | ->getMetaData('wrapper_data')[0], '404 Not Found')) { |
393 | 393 | return $stream; |
394 | 394 | } |
@@ -422,7 +422,7 @@ discard block |
||
422 | 422 | file_put_contents($tmpFile, $source); |
423 | 423 | } |
424 | 424 | $handle = fopen($tmpFile, $mode); |
425 | - return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) { |
|
425 | + return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) { |
|
426 | 426 | $this->writeBack($tmpFile, $path); |
427 | 427 | }); |
428 | 428 | } |
@@ -469,10 +469,10 @@ discard block |
||
469 | 469 | |
470 | 470 | try { |
471 | 471 | $source = $this->fetchObject($path1); |
472 | - $source->copy($this->bucket . '/' . $path2); |
|
472 | + $source->copy($this->bucket.'/'.$path2); |
|
473 | 473 | // invalidate target object to force repopulation on fetch |
474 | 474 | $this->objectCache->remove($path2); |
475 | - $this->objectCache->remove($path2 . '/'); |
|
475 | + $this->objectCache->remove($path2.'/'); |
|
476 | 476 | } catch (ClientErrorResponseException $e) { |
477 | 477 | \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
478 | 478 | return false; |
@@ -484,11 +484,11 @@ discard block |
||
484 | 484 | $this->unlink($path2); |
485 | 485 | |
486 | 486 | try { |
487 | - $source = $this->fetchObject($path1 . '/'); |
|
488 | - $source->copy($this->bucket . '/' . $path2 . '/'); |
|
487 | + $source = $this->fetchObject($path1.'/'); |
|
488 | + $source->copy($this->bucket.'/'.$path2.'/'); |
|
489 | 489 | // invalidate target object to force repopulation on fetch |
490 | 490 | $this->objectCache->remove($path2); |
491 | - $this->objectCache->remove($path2 . '/'); |
|
491 | + $this->objectCache->remove($path2.'/'); |
|
492 | 492 | } catch (ClientErrorResponseException $e) { |
493 | 493 | \OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR); |
494 | 494 | return false; |
@@ -500,8 +500,8 @@ discard block |
||
500 | 500 | continue; |
501 | 501 | } |
502 | 502 | |
503 | - $source = $path1 . '/' . $file; |
|
504 | - $target = $path2 . '/' . $file; |
|
503 | + $source = $path1.'/'.$file; |
|
504 | + $target = $path2.'/'.$file; |
|
505 | 505 | $this->copy($source, $target); |
506 | 506 | } |
507 | 507 | |
@@ -635,7 +635,7 @@ discard block |
||
635 | 635 | $path = ''; |
636 | 636 | } |
637 | 637 | $cachedContent = $this->getCache()->getFolderContents($path); |
638 | - $cachedNames = array_map(function ($content) { |
|
638 | + $cachedNames = array_map(function($content) { |
|
639 | 639 | return $content['name']; |
640 | 640 | }, $cachedContent); |
641 | 641 | sort($cachedNames); |
@@ -597,7 +597,7 @@ |
||
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 |
@@ -150,7 +150,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
@@ -64,558 +64,558 @@ |
||
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 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 | - 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(action=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 | - $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest'); |
|
186 | - $response->throttle(); |
|
187 | - return $response; |
|
188 | - } |
|
189 | - |
|
190 | - /** |
|
191 | - * Authenticate a link item with the given password. |
|
192 | - * Or use the session if no password is provided. |
|
193 | - * |
|
194 | - * This is a modified version of Helper::authenticate |
|
195 | - * TODO: Try to merge back eventually with Helper::authenticate |
|
196 | - * |
|
197 | - * @param \OCP\Share\IShare $share |
|
198 | - * @param string|null $password |
|
199 | - * @return bool |
|
200 | - */ |
|
201 | - private function linkShareAuth(\OCP\Share\IShare $share, $password = null) { |
|
202 | - if ($password !== null) { |
|
203 | - if ($this->shareManager->checkPassword($share, $password)) { |
|
204 | - $this->session->set('public_link_authenticated', (string)$share->getId()); |
|
205 | - } else { |
|
206 | - $this->emitAccessShareHook($share, 403, 'Wrong password'); |
|
207 | - return false; |
|
208 | - } |
|
209 | - } else { |
|
210 | - // not authenticated ? |
|
211 | - if ( ! $this->session->exists('public_link_authenticated') |
|
212 | - || $this->session->get('public_link_authenticated') !== (string)$share->getId()) { |
|
213 | - return false; |
|
214 | - } |
|
215 | - } |
|
216 | - return true; |
|
217 | - } |
|
218 | - |
|
219 | - /** |
|
220 | - * throws hooks when a share is attempted to be accessed |
|
221 | - * |
|
222 | - * @param \OCP\Share\IShare|string $share the Share instance if available, |
|
223 | - * otherwise token |
|
224 | - * @param int $errorCode |
|
225 | - * @param string $errorMessage |
|
226 | - * @throws \OC\HintException |
|
227 | - * @throws \OC\ServerNotAvailableException |
|
228 | - */ |
|
229 | - protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') { |
|
230 | - $itemType = $itemSource = $uidOwner = ''; |
|
231 | - $token = $share; |
|
232 | - $exception = null; |
|
233 | - if($share instanceof \OCP\Share\IShare) { |
|
234 | - try { |
|
235 | - $token = $share->getToken(); |
|
236 | - $uidOwner = $share->getSharedBy(); |
|
237 | - $itemType = $share->getNodeType(); |
|
238 | - $itemSource = $share->getNodeId(); |
|
239 | - } catch (\Exception $e) { |
|
240 | - // we log what we know and pass on the exception afterwards |
|
241 | - $exception = $e; |
|
242 | - } |
|
243 | - } |
|
244 | - \OC_Hook::emit('OCP\Share', 'share_link_access', [ |
|
245 | - 'itemType' => $itemType, |
|
246 | - 'itemSource' => $itemSource, |
|
247 | - 'uidOwner' => $uidOwner, |
|
248 | - 'token' => $token, |
|
249 | - 'errorCode' => $errorCode, |
|
250 | - 'errorMessage' => $errorMessage, |
|
251 | - ]); |
|
252 | - if(!is_null($exception)) { |
|
253 | - throw $exception; |
|
254 | - } |
|
255 | - } |
|
256 | - |
|
257 | - /** |
|
258 | - * Validate the permissions of the share |
|
259 | - * |
|
260 | - * @param Share\IShare $share |
|
261 | - * @return bool |
|
262 | - */ |
|
263 | - private function validateShare(\OCP\Share\IShare $share) { |
|
264 | - return $share->getNode()->isReadable() && $share->getNode()->isShareable(); |
|
265 | - } |
|
266 | - |
|
267 | - /** |
|
268 | - * @PublicPage |
|
269 | - * @NoCSRFRequired |
|
270 | - * |
|
271 | - * @param string $token |
|
272 | - * @param string $path |
|
273 | - * @return TemplateResponse|RedirectResponse|NotFoundResponse |
|
274 | - * @throws NotFoundException |
|
275 | - * @throws \Exception |
|
276 | - */ |
|
277 | - public function showShare($token, $path = '') { |
|
278 | - \OC_User::setIncognitoMode(true); |
|
279 | - |
|
280 | - // Check whether share exists |
|
281 | - try { |
|
282 | - $share = $this->shareManager->getShareByToken($token); |
|
283 | - } catch (ShareNotFound $e) { |
|
284 | - $this->emitAccessShareHook($token, 404, 'Share not found'); |
|
285 | - return new NotFoundResponse(); |
|
286 | - } |
|
287 | - |
|
288 | - // Share is password protected - check whether the user is permitted to access the share |
|
289 | - if ($share->getPassword() !== null && !$this->linkShareAuth($share)) { |
|
290 | - return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', |
|
291 | - array('token' => $token))); |
|
292 | - } |
|
293 | - |
|
294 | - if (!$this->validateShare($share)) { |
|
295 | - throw new NotFoundException(); |
|
296 | - } |
|
297 | - // We can't get the path of a file share |
|
298 | - try { |
|
299 | - if ($share->getNode() instanceof \OCP\Files\File && $path !== '') { |
|
300 | - $this->emitAccessShareHook($share, 404, 'Share not found'); |
|
301 | - throw new NotFoundException(); |
|
302 | - } |
|
303 | - } catch (\Exception $e) { |
|
304 | - $this->emitAccessShareHook($share, 404, 'Share not found'); |
|
305 | - throw $e; |
|
306 | - } |
|
307 | - |
|
308 | - $shareTmpl = []; |
|
309 | - $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName(); |
|
310 | - $shareTmpl['owner'] = $share->getShareOwner(); |
|
311 | - $shareTmpl['filename'] = $share->getNode()->getName(); |
|
312 | - $shareTmpl['directory_path'] = $share->getTarget(); |
|
313 | - $shareTmpl['mimetype'] = $share->getNode()->getMimetype(); |
|
314 | - $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype()); |
|
315 | - $shareTmpl['dirToken'] = $token; |
|
316 | - $shareTmpl['sharingToken'] = $token; |
|
317 | - $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled(); |
|
318 | - $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false'; |
|
319 | - $shareTmpl['dir'] = ''; |
|
320 | - $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize(); |
|
321 | - $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize()); |
|
322 | - |
|
323 | - // Show file list |
|
324 | - $hideFileList = false; |
|
325 | - if ($share->getNode() instanceof \OCP\Files\Folder) { |
|
326 | - /** @var \OCP\Files\Folder $rootFolder */ |
|
327 | - $rootFolder = $share->getNode(); |
|
328 | - |
|
329 | - try { |
|
330 | - $folderNode = $rootFolder->get($path); |
|
331 | - } catch (\OCP\Files\NotFoundException $e) { |
|
332 | - $this->emitAccessShareHook($share, 404, 'Share not found'); |
|
333 | - throw new NotFoundException(); |
|
334 | - } |
|
335 | - |
|
336 | - $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath()); |
|
337 | - |
|
338 | - /* |
|
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 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 | + 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(action=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 | + $response = new TemplateResponse($this->appName, 'authenticate', array('wrongpw' => true), 'guest'); |
|
186 | + $response->throttle(); |
|
187 | + return $response; |
|
188 | + } |
|
189 | + |
|
190 | + /** |
|
191 | + * Authenticate a link item with the given password. |
|
192 | + * Or use the session if no password is provided. |
|
193 | + * |
|
194 | + * This is a modified version of Helper::authenticate |
|
195 | + * TODO: Try to merge back eventually with Helper::authenticate |
|
196 | + * |
|
197 | + * @param \OCP\Share\IShare $share |
|
198 | + * @param string|null $password |
|
199 | + * @return bool |
|
200 | + */ |
|
201 | + private function linkShareAuth(\OCP\Share\IShare $share, $password = null) { |
|
202 | + if ($password !== null) { |
|
203 | + if ($this->shareManager->checkPassword($share, $password)) { |
|
204 | + $this->session->set('public_link_authenticated', (string)$share->getId()); |
|
205 | + } else { |
|
206 | + $this->emitAccessShareHook($share, 403, 'Wrong password'); |
|
207 | + return false; |
|
208 | + } |
|
209 | + } else { |
|
210 | + // not authenticated ? |
|
211 | + if ( ! $this->session->exists('public_link_authenticated') |
|
212 | + || $this->session->get('public_link_authenticated') !== (string)$share->getId()) { |
|
213 | + return false; |
|
214 | + } |
|
215 | + } |
|
216 | + return true; |
|
217 | + } |
|
218 | + |
|
219 | + /** |
|
220 | + * throws hooks when a share is attempted to be accessed |
|
221 | + * |
|
222 | + * @param \OCP\Share\IShare|string $share the Share instance if available, |
|
223 | + * otherwise token |
|
224 | + * @param int $errorCode |
|
225 | + * @param string $errorMessage |
|
226 | + * @throws \OC\HintException |
|
227 | + * @throws \OC\ServerNotAvailableException |
|
228 | + */ |
|
229 | + protected function emitAccessShareHook($share, $errorCode = 200, $errorMessage = '') { |
|
230 | + $itemType = $itemSource = $uidOwner = ''; |
|
231 | + $token = $share; |
|
232 | + $exception = null; |
|
233 | + if($share instanceof \OCP\Share\IShare) { |
|
234 | + try { |
|
235 | + $token = $share->getToken(); |
|
236 | + $uidOwner = $share->getSharedBy(); |
|
237 | + $itemType = $share->getNodeType(); |
|
238 | + $itemSource = $share->getNodeId(); |
|
239 | + } catch (\Exception $e) { |
|
240 | + // we log what we know and pass on the exception afterwards |
|
241 | + $exception = $e; |
|
242 | + } |
|
243 | + } |
|
244 | + \OC_Hook::emit('OCP\Share', 'share_link_access', [ |
|
245 | + 'itemType' => $itemType, |
|
246 | + 'itemSource' => $itemSource, |
|
247 | + 'uidOwner' => $uidOwner, |
|
248 | + 'token' => $token, |
|
249 | + 'errorCode' => $errorCode, |
|
250 | + 'errorMessage' => $errorMessage, |
|
251 | + ]); |
|
252 | + if(!is_null($exception)) { |
|
253 | + throw $exception; |
|
254 | + } |
|
255 | + } |
|
256 | + |
|
257 | + /** |
|
258 | + * Validate the permissions of the share |
|
259 | + * |
|
260 | + * @param Share\IShare $share |
|
261 | + * @return bool |
|
262 | + */ |
|
263 | + private function validateShare(\OCP\Share\IShare $share) { |
|
264 | + return $share->getNode()->isReadable() && $share->getNode()->isShareable(); |
|
265 | + } |
|
266 | + |
|
267 | + /** |
|
268 | + * @PublicPage |
|
269 | + * @NoCSRFRequired |
|
270 | + * |
|
271 | + * @param string $token |
|
272 | + * @param string $path |
|
273 | + * @return TemplateResponse|RedirectResponse|NotFoundResponse |
|
274 | + * @throws NotFoundException |
|
275 | + * @throws \Exception |
|
276 | + */ |
|
277 | + public function showShare($token, $path = '') { |
|
278 | + \OC_User::setIncognitoMode(true); |
|
279 | + |
|
280 | + // Check whether share exists |
|
281 | + try { |
|
282 | + $share = $this->shareManager->getShareByToken($token); |
|
283 | + } catch (ShareNotFound $e) { |
|
284 | + $this->emitAccessShareHook($token, 404, 'Share not found'); |
|
285 | + return new NotFoundResponse(); |
|
286 | + } |
|
287 | + |
|
288 | + // Share is password protected - check whether the user is permitted to access the share |
|
289 | + if ($share->getPassword() !== null && !$this->linkShareAuth($share)) { |
|
290 | + return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', |
|
291 | + array('token' => $token))); |
|
292 | + } |
|
293 | + |
|
294 | + if (!$this->validateShare($share)) { |
|
295 | + throw new NotFoundException(); |
|
296 | + } |
|
297 | + // We can't get the path of a file share |
|
298 | + try { |
|
299 | + if ($share->getNode() instanceof \OCP\Files\File && $path !== '') { |
|
300 | + $this->emitAccessShareHook($share, 404, 'Share not found'); |
|
301 | + throw new NotFoundException(); |
|
302 | + } |
|
303 | + } catch (\Exception $e) { |
|
304 | + $this->emitAccessShareHook($share, 404, 'Share not found'); |
|
305 | + throw $e; |
|
306 | + } |
|
307 | + |
|
308 | + $shareTmpl = []; |
|
309 | + $shareTmpl['displayName'] = $this->userManager->get($share->getShareOwner())->getDisplayName(); |
|
310 | + $shareTmpl['owner'] = $share->getShareOwner(); |
|
311 | + $shareTmpl['filename'] = $share->getNode()->getName(); |
|
312 | + $shareTmpl['directory_path'] = $share->getTarget(); |
|
313 | + $shareTmpl['mimetype'] = $share->getNode()->getMimetype(); |
|
314 | + $shareTmpl['previewSupported'] = $this->previewManager->isMimeSupported($share->getNode()->getMimetype()); |
|
315 | + $shareTmpl['dirToken'] = $token; |
|
316 | + $shareTmpl['sharingToken'] = $token; |
|
317 | + $shareTmpl['server2serversharing'] = $this->federatedShareProvider->isOutgoingServer2serverShareEnabled(); |
|
318 | + $shareTmpl['protected'] = $share->getPassword() !== null ? 'true' : 'false'; |
|
319 | + $shareTmpl['dir'] = ''; |
|
320 | + $shareTmpl['nonHumanFileSize'] = $share->getNode()->getSize(); |
|
321 | + $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($share->getNode()->getSize()); |
|
322 | + |
|
323 | + // Show file list |
|
324 | + $hideFileList = false; |
|
325 | + if ($share->getNode() instanceof \OCP\Files\Folder) { |
|
326 | + /** @var \OCP\Files\Folder $rootFolder */ |
|
327 | + $rootFolder = $share->getNode(); |
|
328 | + |
|
329 | + try { |
|
330 | + $folderNode = $rootFolder->get($path); |
|
331 | + } catch (\OCP\Files\NotFoundException $e) { |
|
332 | + $this->emitAccessShareHook($share, 404, 'Share not found'); |
|
333 | + throw new NotFoundException(); |
|
334 | + } |
|
335 | + |
|
336 | + $shareTmpl['dir'] = $rootFolder->getRelativePath($folderNode->getPath()); |
|
337 | + |
|
338 | + /* |
|
339 | 339 | * The OC_Util methods require a view. This just uses the node API |
340 | 340 | */ |
341 | - $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath()); |
|
342 | - if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) { |
|
343 | - $freeSpace = max($freeSpace, 0); |
|
344 | - } else { |
|
345 | - $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188 |
|
346 | - } |
|
347 | - |
|
348 | - $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true; |
|
349 | - $maxUploadFilesize = $freeSpace; |
|
350 | - |
|
351 | - $folder = new Template('files', 'list', ''); |
|
352 | - $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath())); |
|
353 | - $folder->assign('dirToken', $token); |
|
354 | - $folder->assign('permissions', \OCP\Constants::PERMISSION_READ); |
|
355 | - $folder->assign('isPublic', true); |
|
356 | - $folder->assign('hideFileList', $hideFileList); |
|
357 | - $folder->assign('publicUploadEnabled', 'no'); |
|
358 | - $folder->assign('uploadMaxFilesize', $maxUploadFilesize); |
|
359 | - $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize)); |
|
360 | - $folder->assign('freeSpace', $freeSpace); |
|
361 | - $folder->assign('usedSpacePercent', 0); |
|
362 | - $folder->assign('trash', false); |
|
363 | - $shareTmpl['folder'] = $folder->fetchPage(); |
|
364 | - } |
|
365 | - |
|
366 | - $shareTmpl['hideFileList'] = $hideFileList; |
|
367 | - $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName(); |
|
368 | - $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]); |
|
369 | - $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]); |
|
370 | - $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10); |
|
371 | - $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true); |
|
372 | - $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024); |
|
373 | - $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024); |
|
374 | - $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null); |
|
375 | - if ($shareTmpl['previewSupported']) { |
|
376 | - $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview', |
|
377 | - ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]); |
|
378 | - } else { |
|
379 | - $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png')); |
|
380 | - } |
|
381 | - |
|
382 | - // Load files we need |
|
383 | - \OCP\Util::addScript('files', 'file-upload'); |
|
384 | - \OCP\Util::addStyle('files_sharing', 'publicView'); |
|
385 | - \OCP\Util::addScript('files_sharing', 'public'); |
|
386 | - \OCP\Util::addScript('files', 'fileactions'); |
|
387 | - \OCP\Util::addScript('files', 'fileactionsmenu'); |
|
388 | - \OCP\Util::addScript('files', 'jquery.fileupload'); |
|
389 | - \OCP\Util::addScript('files_sharing', 'files_drop'); |
|
390 | - |
|
391 | - if (isset($shareTmpl['folder'])) { |
|
392 | - // JS required for folders |
|
393 | - \OCP\Util::addStyle('files', 'merged'); |
|
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 | - } |
|
341 | + $freeSpace = $share->getNode()->getStorage()->free_space($share->getNode()->getInternalPath()); |
|
342 | + if ($freeSpace < \OCP\Files\FileInfo::SPACE_UNLIMITED) { |
|
343 | + $freeSpace = max($freeSpace, 0); |
|
344 | + } else { |
|
345 | + $freeSpace = (INF > 0) ? INF: PHP_INT_MAX; // work around https://bugs.php.net/bug.php?id=69188 |
|
346 | + } |
|
347 | + |
|
348 | + $hideFileList = $share->getPermissions() & \OCP\Constants::PERMISSION_READ ? false : true; |
|
349 | + $maxUploadFilesize = $freeSpace; |
|
350 | + |
|
351 | + $folder = new Template('files', 'list', ''); |
|
352 | + $folder->assign('dir', $rootFolder->getRelativePath($folderNode->getPath())); |
|
353 | + $folder->assign('dirToken', $token); |
|
354 | + $folder->assign('permissions', \OCP\Constants::PERMISSION_READ); |
|
355 | + $folder->assign('isPublic', true); |
|
356 | + $folder->assign('hideFileList', $hideFileList); |
|
357 | + $folder->assign('publicUploadEnabled', 'no'); |
|
358 | + $folder->assign('uploadMaxFilesize', $maxUploadFilesize); |
|
359 | + $folder->assign('uploadMaxHumanFilesize', \OCP\Util::humanFileSize($maxUploadFilesize)); |
|
360 | + $folder->assign('freeSpace', $freeSpace); |
|
361 | + $folder->assign('usedSpacePercent', 0); |
|
362 | + $folder->assign('trash', false); |
|
363 | + $shareTmpl['folder'] = $folder->fetchPage(); |
|
364 | + } |
|
365 | + |
|
366 | + $shareTmpl['hideFileList'] = $hideFileList; |
|
367 | + $shareTmpl['shareOwner'] = $this->userManager->get($share->getShareOwner())->getDisplayName(); |
|
368 | + $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', ['token' => $token]); |
|
369 | + $shareTmpl['shareUrl'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]); |
|
370 | + $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10); |
|
371 | + $shareTmpl['previewEnabled'] = $this->config->getSystemValue('enable_previews', true); |
|
372 | + $shareTmpl['previewMaxX'] = $this->config->getSystemValue('preview_max_x', 1024); |
|
373 | + $shareTmpl['previewMaxY'] = $this->config->getSystemValue('preview_max_y', 1024); |
|
374 | + $shareTmpl['disclaimer'] = $this->config->getAppValue('core', 'shareapi_public_link_disclaimertext', null); |
|
375 | + if ($shareTmpl['previewSupported']) { |
|
376 | + $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview', |
|
377 | + ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]); |
|
378 | + } else { |
|
379 | + $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png')); |
|
380 | + } |
|
381 | + |
|
382 | + // Load files we need |
|
383 | + \OCP\Util::addScript('files', 'file-upload'); |
|
384 | + \OCP\Util::addStyle('files_sharing', 'publicView'); |
|
385 | + \OCP\Util::addScript('files_sharing', 'public'); |
|
386 | + \OCP\Util::addScript('files', 'fileactions'); |
|
387 | + \OCP\Util::addScript('files', 'fileactionsmenu'); |
|
388 | + \OCP\Util::addScript('files', 'jquery.fileupload'); |
|
389 | + \OCP\Util::addScript('files_sharing', 'files_drop'); |
|
390 | + |
|
391 | + if (isset($shareTmpl['folder'])) { |
|
392 | + // JS required for folders |
|
393 | + \OCP\Util::addStyle('files', 'merged'); |
|
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 | } |
@@ -358,7 +358,7 @@ discard block |
||
358 | 358 | * split user and remote from federated cloud id |
359 | 359 | * |
360 | 360 | * @param string $address federated share address |
361 | - * @return array [user, remoteURL] |
|
361 | + * @return string[] [user, remoteURL] |
|
362 | 362 | * @throws \Exception |
363 | 363 | */ |
364 | 364 | public function splitUserRemote($address) { |
@@ -633,6 +633,9 @@ discard block |
||
633 | 633 | return $result; |
634 | 634 | } |
635 | 635 | |
636 | + /** |
|
637 | + * @param string $search |
|
638 | + */ |
|
636 | 639 | protected function getLookup($search) { |
637 | 640 | $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no'); |
638 | 641 | $result = []; |
@@ -234,17 +234,17 @@ discard block |
||
234 | 234 | $this->result['groups'] = $this->result['exact']['groups'] = []; |
235 | 235 | |
236 | 236 | $groups = $this->groupManager->search($search, $this->limit, $this->offset); |
237 | - $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); |
|
237 | + $groupIds = array_map(function(IGroup $group) { return $group->getGID(); }, $groups); |
|
238 | 238 | |
239 | 239 | if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) { |
240 | 240 | $this->reachedEndFor[] = 'groups'; |
241 | 241 | } |
242 | 242 | |
243 | - $userGroups = []; |
|
243 | + $userGroups = []; |
|
244 | 244 | if (!empty($groups) && $this->shareWithGroupOnly) { |
245 | 245 | // Intersect all the groups that match with the groups this user is a member of |
246 | 246 | $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser()); |
247 | - $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups); |
|
247 | + $userGroups = array_map(function(IGroup $group) { return $group->getGID(); }, $userGroups); |
|
248 | 248 | $groupIds = array_intersect($groupIds, $userGroups); |
249 | 249 | } |
250 | 250 | |
@@ -322,7 +322,7 @@ discard block |
||
322 | 322 | $result['exactIdMatch'] = true; |
323 | 323 | } |
324 | 324 | $result['exact'][] = [ |
325 | - 'label' => $contact['FN'] . " ($cloudId)", |
|
325 | + 'label' => $contact['FN']." ($cloudId)", |
|
326 | 326 | 'value' => [ |
327 | 327 | 'shareType' => Share::SHARE_TYPE_REMOTE, |
328 | 328 | 'shareWith' => $cloudId, |
@@ -331,7 +331,7 @@ discard block |
||
331 | 331 | ]; |
332 | 332 | } else { |
333 | 333 | $result['results'][] = [ |
334 | - 'label' => $contact['FN'] . " ($cloudId)", |
|
334 | + 'label' => $contact['FN']." ($cloudId)", |
|
335 | 335 | 'value' => [ |
336 | 336 | 'shareType' => Share::SHARE_TYPE_REMOTE, |
337 | 337 | 'shareWith' => $cloudId, |
@@ -415,13 +415,13 @@ discard block |
||
415 | 415 | public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) { |
416 | 416 | |
417 | 417 | // only search for string larger than a given threshold |
418 | - $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0); |
|
418 | + $threshold = (int) $this->config->getSystemValue('sharing.minSearchStringLength', 0); |
|
419 | 419 | if (strlen($search) < $threshold) { |
420 | 420 | return new DataResponse($this->result); |
421 | 421 | } |
422 | 422 | |
423 | 423 | // never return more than the max. number of results configured in the config.php |
424 | - $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0); |
|
424 | + $maxResults = (int) $this->config->getSystemValue('sharing.maxAutocompleteResults', 0); |
|
425 | 425 | if ($maxResults > 0) { |
426 | 426 | $perPage = min($perPage, $maxResults); |
427 | 427 | } |
@@ -585,7 +585,7 @@ discard block |
||
585 | 585 | $result['exactIdMatch'] = true; |
586 | 586 | } |
587 | 587 | $result['exact'][] = [ |
588 | - 'label' => $contact['FN'] . " ($emailAddress)", |
|
588 | + 'label' => $contact['FN']." ($emailAddress)", |
|
589 | 589 | 'value' => [ |
590 | 590 | 'shareType' => Share::SHARE_TYPE_EMAIL, |
591 | 591 | 'shareWith' => $emailAddress, |
@@ -593,7 +593,7 @@ discard block |
||
593 | 593 | ]; |
594 | 594 | } else { |
595 | 595 | $result['results'][] = [ |
596 | - 'label' => $contact['FN'] . " ($emailAddress)", |
|
596 | + 'label' => $contact['FN']." ($emailAddress)", |
|
597 | 597 | 'value' => [ |
598 | 598 | 'shareType' => Share::SHARE_TYPE_EMAIL, |
599 | 599 | 'shareWith' => $emailAddress, |
@@ -627,11 +627,11 @@ discard block |
||
627 | 627 | $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no'); |
628 | 628 | $result = []; |
629 | 629 | |
630 | - if($isEnabled === 'yes') { |
|
630 | + if ($isEnabled === 'yes') { |
|
631 | 631 | try { |
632 | 632 | $client = $this->clientService->newClient(); |
633 | 633 | $response = $client->get( |
634 | - 'https://lookup.nextcloud.com/users?search=' . urlencode($search), |
|
634 | + 'https://lookup.nextcloud.com/users?search='.urlencode($search), |
|
635 | 635 | [ |
636 | 636 | 'timeout' => 10, |
637 | 637 | 'connect_timeout' => 3, |
@@ -666,12 +666,12 @@ discard block |
||
666 | 666 | */ |
667 | 667 | protected function getPaginationLink($page, array $params) { |
668 | 668 | if ($this->isV2()) { |
669 | - $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?'; |
|
669 | + $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees').'?'; |
|
670 | 670 | } else { |
671 | - $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?'; |
|
671 | + $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees').'?'; |
|
672 | 672 | } |
673 | 673 | $params['page'] = $page + 1; |
674 | - $link = '<' . $url . http_build_query($params) . '>; rel="next"'; |
|
674 | + $link = '<'.$url.http_build_query($params).'>; rel="next"'; |
|
675 | 675 | |
676 | 676 | return $link; |
677 | 677 | } |
@@ -43,672 +43,672 @@ |
||
43 | 43 | |
44 | 44 | class ShareesAPIController extends OCSController { |
45 | 45 | |
46 | - /** @var IGroupManager */ |
|
47 | - protected $groupManager; |
|
48 | - |
|
49 | - /** @var IUserManager */ |
|
50 | - protected $userManager; |
|
51 | - |
|
52 | - /** @var IManager */ |
|
53 | - protected $contactsManager; |
|
54 | - |
|
55 | - /** @var IConfig */ |
|
56 | - protected $config; |
|
57 | - |
|
58 | - /** @var IUserSession */ |
|
59 | - protected $userSession; |
|
60 | - |
|
61 | - /** @var IURLGenerator */ |
|
62 | - protected $urlGenerator; |
|
63 | - |
|
64 | - /** @var ILogger */ |
|
65 | - protected $logger; |
|
66 | - |
|
67 | - /** @var \OCP\Share\IManager */ |
|
68 | - protected $shareManager; |
|
69 | - |
|
70 | - /** @var IClientService */ |
|
71 | - protected $clientService; |
|
72 | - |
|
73 | - /** @var ICloudIdManager */ |
|
74 | - protected $cloudIdManager; |
|
75 | - |
|
76 | - /** @var bool */ |
|
77 | - protected $shareWithGroupOnly = false; |
|
78 | - |
|
79 | - /** @var bool */ |
|
80 | - protected $shareeEnumeration = true; |
|
81 | - |
|
82 | - /** @var int */ |
|
83 | - protected $offset = 0; |
|
84 | - |
|
85 | - /** @var int */ |
|
86 | - protected $limit = 10; |
|
87 | - |
|
88 | - /** @var array */ |
|
89 | - protected $result = [ |
|
90 | - 'exact' => [ |
|
91 | - 'users' => [], |
|
92 | - 'groups' => [], |
|
93 | - 'remotes' => [], |
|
94 | - 'emails' => [], |
|
95 | - 'circles' => [], |
|
96 | - ], |
|
97 | - 'users' => [], |
|
98 | - 'groups' => [], |
|
99 | - 'remotes' => [], |
|
100 | - 'emails' => [], |
|
101 | - 'lookup' => [], |
|
102 | - 'circles' => [], |
|
103 | - ]; |
|
104 | - |
|
105 | - protected $reachedEndFor = []; |
|
106 | - |
|
107 | - /** |
|
108 | - * @param string $appName |
|
109 | - * @param IRequest $request |
|
110 | - * @param IGroupManager $groupManager |
|
111 | - * @param IUserManager $userManager |
|
112 | - * @param IManager $contactsManager |
|
113 | - * @param IConfig $config |
|
114 | - * @param IUserSession $userSession |
|
115 | - * @param IURLGenerator $urlGenerator |
|
116 | - * @param ILogger $logger |
|
117 | - * @param \OCP\Share\IManager $shareManager |
|
118 | - * @param IClientService $clientService |
|
119 | - * @param ICloudIdManager $cloudIdManager |
|
120 | - */ |
|
121 | - public function __construct($appName, |
|
122 | - IRequest $request, |
|
123 | - IGroupManager $groupManager, |
|
124 | - IUserManager $userManager, |
|
125 | - IManager $contactsManager, |
|
126 | - IConfig $config, |
|
127 | - IUserSession $userSession, |
|
128 | - IURLGenerator $urlGenerator, |
|
129 | - ILogger $logger, |
|
130 | - \OCP\Share\IManager $shareManager, |
|
131 | - IClientService $clientService, |
|
132 | - ICloudIdManager $cloudIdManager |
|
133 | - ) { |
|
134 | - parent::__construct($appName, $request); |
|
135 | - |
|
136 | - $this->groupManager = $groupManager; |
|
137 | - $this->userManager = $userManager; |
|
138 | - $this->contactsManager = $contactsManager; |
|
139 | - $this->config = $config; |
|
140 | - $this->userSession = $userSession; |
|
141 | - $this->urlGenerator = $urlGenerator; |
|
142 | - $this->logger = $logger; |
|
143 | - $this->shareManager = $shareManager; |
|
144 | - $this->clientService = $clientService; |
|
145 | - $this->cloudIdManager = $cloudIdManager; |
|
146 | - } |
|
147 | - |
|
148 | - /** |
|
149 | - * @param string $search |
|
150 | - */ |
|
151 | - protected function getUsers($search) { |
|
152 | - $this->result['users'] = $this->result['exact']['users'] = $users = []; |
|
153 | - |
|
154 | - $userGroups = []; |
|
155 | - if ($this->shareWithGroupOnly) { |
|
156 | - // Search in all the groups this user is part of |
|
157 | - $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser()); |
|
158 | - foreach ($userGroups as $userGroup) { |
|
159 | - $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset); |
|
160 | - foreach ($usersTmp as $uid => $userDisplayName) { |
|
161 | - $users[$uid] = $userDisplayName; |
|
162 | - } |
|
163 | - } |
|
164 | - } else { |
|
165 | - // Search in all users |
|
166 | - $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset); |
|
167 | - |
|
168 | - foreach ($usersTmp as $user) { |
|
169 | - $users[$user->getUID()] = $user->getDisplayName(); |
|
170 | - } |
|
171 | - } |
|
172 | - |
|
173 | - if (!$this->shareeEnumeration || sizeof($users) < $this->limit) { |
|
174 | - $this->reachedEndFor[] = 'users'; |
|
175 | - } |
|
176 | - |
|
177 | - $foundUserById = false; |
|
178 | - $lowerSearch = strtolower($search); |
|
179 | - foreach ($users as $uid => $userDisplayName) { |
|
180 | - if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) { |
|
181 | - if (strtolower($uid) === $lowerSearch) { |
|
182 | - $foundUserById = true; |
|
183 | - } |
|
184 | - $this->result['exact']['users'][] = [ |
|
185 | - 'label' => $userDisplayName, |
|
186 | - 'value' => [ |
|
187 | - 'shareType' => Share::SHARE_TYPE_USER, |
|
188 | - 'shareWith' => $uid, |
|
189 | - ], |
|
190 | - ]; |
|
191 | - } else { |
|
192 | - $this->result['users'][] = [ |
|
193 | - 'label' => $userDisplayName, |
|
194 | - 'value' => [ |
|
195 | - 'shareType' => Share::SHARE_TYPE_USER, |
|
196 | - 'shareWith' => $uid, |
|
197 | - ], |
|
198 | - ]; |
|
199 | - } |
|
200 | - } |
|
201 | - |
|
202 | - if ($this->offset === 0 && !$foundUserById) { |
|
203 | - // On page one we try if the search result has a direct hit on the |
|
204 | - // user id and if so, we add that to the exact match list |
|
205 | - $user = $this->userManager->get($search); |
|
206 | - if ($user instanceof IUser) { |
|
207 | - $addUser = true; |
|
208 | - |
|
209 | - if ($this->shareWithGroupOnly) { |
|
210 | - // Only add, if we have a common group |
|
211 | - $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user)); |
|
212 | - $addUser = !empty($commonGroups); |
|
213 | - } |
|
214 | - |
|
215 | - if ($addUser) { |
|
216 | - array_push($this->result['exact']['users'], [ |
|
217 | - 'label' => $user->getDisplayName(), |
|
218 | - 'value' => [ |
|
219 | - 'shareType' => Share::SHARE_TYPE_USER, |
|
220 | - 'shareWith' => $user->getUID(), |
|
221 | - ], |
|
222 | - ]); |
|
223 | - } |
|
224 | - } |
|
225 | - } |
|
226 | - |
|
227 | - if (!$this->shareeEnumeration) { |
|
228 | - $this->result['users'] = []; |
|
229 | - } |
|
230 | - } |
|
231 | - |
|
232 | - /** |
|
233 | - * @param string $search |
|
234 | - */ |
|
235 | - protected function getGroups($search) { |
|
236 | - $this->result['groups'] = $this->result['exact']['groups'] = []; |
|
237 | - |
|
238 | - $groups = $this->groupManager->search($search, $this->limit, $this->offset); |
|
239 | - $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); |
|
240 | - |
|
241 | - if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) { |
|
242 | - $this->reachedEndFor[] = 'groups'; |
|
243 | - } |
|
244 | - |
|
245 | - $userGroups = []; |
|
246 | - if (!empty($groups) && $this->shareWithGroupOnly) { |
|
247 | - // Intersect all the groups that match with the groups this user is a member of |
|
248 | - $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser()); |
|
249 | - $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups); |
|
250 | - $groupIds = array_intersect($groupIds, $userGroups); |
|
251 | - } |
|
252 | - |
|
253 | - $lowerSearch = strtolower($search); |
|
254 | - foreach ($groups as $group) { |
|
255 | - // FIXME: use a more efficient approach |
|
256 | - $gid = $group->getGID(); |
|
257 | - if (!in_array($gid, $groupIds)) { |
|
258 | - continue; |
|
259 | - } |
|
260 | - if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) { |
|
261 | - $this->result['exact']['groups'][] = [ |
|
262 | - 'label' => $group->getDisplayName(), |
|
263 | - 'value' => [ |
|
264 | - 'shareType' => Share::SHARE_TYPE_GROUP, |
|
265 | - 'shareWith' => $gid, |
|
266 | - ], |
|
267 | - ]; |
|
268 | - } else { |
|
269 | - $this->result['groups'][] = [ |
|
270 | - 'label' => $group->getDisplayName(), |
|
271 | - 'value' => [ |
|
272 | - 'shareType' => Share::SHARE_TYPE_GROUP, |
|
273 | - 'shareWith' => $gid, |
|
274 | - ], |
|
275 | - ]; |
|
276 | - } |
|
277 | - } |
|
278 | - |
|
279 | - if ($this->offset === 0 && empty($this->result['exact']['groups'])) { |
|
280 | - // On page one we try if the search result has a direct hit on the |
|
281 | - // user id and if so, we add that to the exact match list |
|
282 | - $group = $this->groupManager->get($search); |
|
283 | - if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) { |
|
284 | - array_push($this->result['exact']['groups'], [ |
|
285 | - 'label' => $group->getDisplayName(), |
|
286 | - 'value' => [ |
|
287 | - 'shareType' => Share::SHARE_TYPE_GROUP, |
|
288 | - 'shareWith' => $group->getGID(), |
|
289 | - ], |
|
290 | - ]); |
|
291 | - } |
|
292 | - } |
|
293 | - |
|
294 | - if (!$this->shareeEnumeration) { |
|
295 | - $this->result['groups'] = []; |
|
296 | - } |
|
297 | - } |
|
298 | - |
|
299 | - |
|
300 | - /** |
|
301 | - * @param string $search |
|
302 | - */ |
|
303 | - protected function getCircles($search) { |
|
304 | - $this->result['circles'] = $this->result['exact']['circles'] = []; |
|
305 | - |
|
306 | - $result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset); |
|
307 | - if (array_key_exists('circles', $result['exact'])) { |
|
308 | - $this->result['exact']['circles'] = $result['exact']['circles']; |
|
309 | - } |
|
310 | - if (array_key_exists('circles', $result)) { |
|
311 | - $this->result['circles'] = $result['circles']; |
|
312 | - } |
|
313 | - } |
|
314 | - |
|
315 | - |
|
316 | - /** |
|
317 | - * @param string $search |
|
318 | - * @return array |
|
319 | - */ |
|
320 | - protected function getRemote($search) { |
|
321 | - $result = ['results' => [], 'exact' => []]; |
|
322 | - |
|
323 | - // Search in contacts |
|
324 | - //@todo Pagination missing |
|
325 | - $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']); |
|
326 | - $result['exactIdMatch'] = false; |
|
327 | - foreach ($addressBookContacts as $contact) { |
|
328 | - if (isset($contact['isLocalSystemBook'])) { |
|
329 | - continue; |
|
330 | - } |
|
331 | - if (isset($contact['CLOUD'])) { |
|
332 | - $cloudIds = $contact['CLOUD']; |
|
333 | - if (!is_array($cloudIds)) { |
|
334 | - $cloudIds = [$cloudIds]; |
|
335 | - } |
|
336 | - $lowerSearch = strtolower($search); |
|
337 | - foreach ($cloudIds as $cloudId) { |
|
338 | - list(, $serverUrl) = $this->splitUserRemote($cloudId); |
|
339 | - if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) { |
|
340 | - if (strtolower($cloudId) === $lowerSearch) { |
|
341 | - $result['exactIdMatch'] = true; |
|
342 | - } |
|
343 | - $result['exact'][] = [ |
|
344 | - 'label' => $contact['FN'] . " ($cloudId)", |
|
345 | - 'value' => [ |
|
346 | - 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
347 | - 'shareWith' => $cloudId, |
|
348 | - 'server' => $serverUrl, |
|
349 | - ], |
|
350 | - ]; |
|
351 | - } else { |
|
352 | - $result['results'][] = [ |
|
353 | - 'label' => $contact['FN'] . " ($cloudId)", |
|
354 | - 'value' => [ |
|
355 | - 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
356 | - 'shareWith' => $cloudId, |
|
357 | - 'server' => $serverUrl, |
|
358 | - ], |
|
359 | - ]; |
|
360 | - } |
|
361 | - } |
|
362 | - } |
|
363 | - } |
|
364 | - |
|
365 | - if (!$this->shareeEnumeration) { |
|
366 | - $result['results'] = []; |
|
367 | - } |
|
368 | - |
|
369 | - if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) { |
|
370 | - $result['exact'][] = [ |
|
371 | - 'label' => $search, |
|
372 | - 'value' => [ |
|
373 | - 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
374 | - 'shareWith' => $search, |
|
375 | - ], |
|
376 | - ]; |
|
377 | - } |
|
378 | - |
|
379 | - $this->reachedEndFor[] = 'remotes'; |
|
380 | - |
|
381 | - return $result; |
|
382 | - } |
|
383 | - |
|
384 | - /** |
|
385 | - * split user and remote from federated cloud id |
|
386 | - * |
|
387 | - * @param string $address federated share address |
|
388 | - * @return array [user, remoteURL] |
|
389 | - * @throws \Exception |
|
390 | - */ |
|
391 | - public function splitUserRemote($address) { |
|
392 | - try { |
|
393 | - $cloudId = $this->cloudIdManager->resolveCloudId($address); |
|
394 | - return [$cloudId->getUser(), $cloudId->getRemote()]; |
|
395 | - } catch (\InvalidArgumentException $e) { |
|
396 | - throw new \Exception('Invalid Federated Cloud ID', 0, $e); |
|
397 | - } |
|
398 | - } |
|
399 | - |
|
400 | - /** |
|
401 | - * Strips away a potential file names and trailing slashes: |
|
402 | - * - http://localhost |
|
403 | - * - http://localhost/ |
|
404 | - * - http://localhost/index.php |
|
405 | - * - http://localhost/index.php/s/{shareToken} |
|
406 | - * |
|
407 | - * all return: http://localhost |
|
408 | - * |
|
409 | - * @param string $remote |
|
410 | - * @return string |
|
411 | - */ |
|
412 | - protected function fixRemoteURL($remote) { |
|
413 | - $remote = str_replace('\\', '/', $remote); |
|
414 | - if ($fileNamePosition = strpos($remote, '/index.php')) { |
|
415 | - $remote = substr($remote, 0, $fileNamePosition); |
|
416 | - } |
|
417 | - $remote = rtrim($remote, '/'); |
|
418 | - |
|
419 | - return $remote; |
|
420 | - } |
|
421 | - |
|
422 | - /** |
|
423 | - * @NoAdminRequired |
|
424 | - * |
|
425 | - * @param string $search |
|
426 | - * @param string $itemType |
|
427 | - * @param int $page |
|
428 | - * @param int $perPage |
|
429 | - * @param int|int[] $shareType |
|
430 | - * @param bool $lookup |
|
431 | - * @return DataResponse |
|
432 | - * @throws OCSBadRequestException |
|
433 | - */ |
|
434 | - public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) { |
|
435 | - |
|
436 | - // only search for string larger than a given threshold |
|
437 | - $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0); |
|
438 | - if (strlen($search) < $threshold) { |
|
439 | - return new DataResponse($this->result); |
|
440 | - } |
|
441 | - |
|
442 | - // never return more than the max. number of results configured in the config.php |
|
443 | - $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0); |
|
444 | - if ($maxResults > 0) { |
|
445 | - $perPage = min($perPage, $maxResults); |
|
446 | - } |
|
447 | - if ($perPage <= 0) { |
|
448 | - throw new OCSBadRequestException('Invalid perPage argument'); |
|
449 | - } |
|
450 | - if ($page <= 0) { |
|
451 | - throw new OCSBadRequestException('Invalid page'); |
|
452 | - } |
|
453 | - |
|
454 | - $shareTypes = [ |
|
455 | - Share::SHARE_TYPE_USER, |
|
456 | - ]; |
|
457 | - |
|
458 | - if ($itemType === 'file' || $itemType === 'folder') { |
|
459 | - if ($this->shareManager->allowGroupSharing()) { |
|
460 | - $shareTypes[] = Share::SHARE_TYPE_GROUP; |
|
461 | - } |
|
462 | - |
|
463 | - if ($this->isRemoteSharingAllowed($itemType)) { |
|
464 | - $shareTypes[] = Share::SHARE_TYPE_REMOTE; |
|
465 | - } |
|
466 | - |
|
467 | - if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) { |
|
468 | - $shareTypes[] = Share::SHARE_TYPE_EMAIL; |
|
469 | - } |
|
470 | - } else { |
|
471 | - $shareTypes[] = Share::SHARE_TYPE_GROUP; |
|
472 | - $shareTypes[] = Share::SHARE_TYPE_EMAIL; |
|
473 | - } |
|
474 | - |
|
475 | - if (\OCP\App::isEnabled('circles')) { |
|
476 | - $shareTypes[] = Share::SHARE_TYPE_CIRCLE; |
|
477 | - } |
|
478 | - |
|
479 | - if (isset($_GET['shareType']) && is_array($_GET['shareType'])) { |
|
480 | - $shareTypes = array_intersect($shareTypes, $_GET['shareType']); |
|
481 | - sort($shareTypes); |
|
482 | - } else if (is_numeric($shareType)) { |
|
483 | - $shareTypes = array_intersect($shareTypes, [(int) $shareType]); |
|
484 | - sort($shareTypes); |
|
485 | - } |
|
486 | - |
|
487 | - $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; |
|
488 | - $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; |
|
489 | - $this->limit = (int) $perPage; |
|
490 | - $this->offset = $perPage * ($page - 1); |
|
491 | - |
|
492 | - return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup); |
|
493 | - } |
|
494 | - |
|
495 | - /** |
|
496 | - * Method to get out the static call for better testing |
|
497 | - * |
|
498 | - * @param string $itemType |
|
499 | - * @return bool |
|
500 | - */ |
|
501 | - protected function isRemoteSharingAllowed($itemType) { |
|
502 | - try { |
|
503 | - $backend = Share::getBackend($itemType); |
|
504 | - return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE); |
|
505 | - } catch (\Exception $e) { |
|
506 | - return false; |
|
507 | - } |
|
508 | - } |
|
509 | - |
|
510 | - /** |
|
511 | - * Testable search function that does not need globals |
|
512 | - * |
|
513 | - * @param string $search |
|
514 | - * @param string $itemType |
|
515 | - * @param array $shareTypes |
|
516 | - * @param int $page |
|
517 | - * @param int $perPage |
|
518 | - * @param bool $lookup |
|
519 | - * @return DataResponse |
|
520 | - * @throws OCSBadRequestException |
|
521 | - */ |
|
522 | - protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) { |
|
523 | - // Verify arguments |
|
524 | - if ($itemType === null) { |
|
525 | - throw new OCSBadRequestException('Missing itemType'); |
|
526 | - } |
|
527 | - |
|
528 | - // Get users |
|
529 | - if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) { |
|
530 | - $this->getUsers($search); |
|
531 | - } |
|
532 | - |
|
533 | - // Get groups |
|
534 | - if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) { |
|
535 | - $this->getGroups($search); |
|
536 | - } |
|
537 | - |
|
538 | - // Get circles |
|
539 | - if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) { |
|
540 | - $this->getCircles($search); |
|
541 | - } |
|
542 | - |
|
543 | - |
|
544 | - // Get remote |
|
545 | - $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false]; |
|
546 | - if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) { |
|
547 | - $remoteResults = $this->getRemote($search); |
|
548 | - } |
|
549 | - |
|
550 | - // Get emails |
|
551 | - $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false]; |
|
552 | - if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) { |
|
553 | - $mailResults = $this->getEmail($search); |
|
554 | - } |
|
555 | - |
|
556 | - // Get from lookup server |
|
557 | - if ($lookup) { |
|
558 | - $this->getLookup($search); |
|
559 | - } |
|
560 | - |
|
561 | - // if we have a exact match, either for the federated cloud id or for the |
|
562 | - // email address we only return the exact match. It is highly unlikely |
|
563 | - // that the exact same email address and federated cloud id exists |
|
564 | - if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) { |
|
565 | - $this->result['emails'] = $mailResults['results']; |
|
566 | - $this->result['exact']['emails'] = $mailResults['exact']; |
|
567 | - } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) { |
|
568 | - $this->result['remotes'] = $remoteResults['results']; |
|
569 | - $this->result['exact']['remotes'] = $remoteResults['exact']; |
|
570 | - } else { |
|
571 | - $this->result['remotes'] = $remoteResults['results']; |
|
572 | - $this->result['exact']['remotes'] = $remoteResults['exact']; |
|
573 | - $this->result['emails'] = $mailResults['results']; |
|
574 | - $this->result['exact']['emails'] = $mailResults['exact']; |
|
575 | - } |
|
576 | - |
|
577 | - $response = new DataResponse($this->result); |
|
578 | - |
|
579 | - if (sizeof($this->reachedEndFor) < 3) { |
|
580 | - $response->addHeader('Link', $this->getPaginationLink($page, [ |
|
581 | - 'search' => $search, |
|
582 | - 'itemType' => $itemType, |
|
583 | - 'shareType' => $shareTypes, |
|
584 | - 'perPage' => $perPage, |
|
585 | - ])); |
|
586 | - } |
|
587 | - |
|
588 | - return $response; |
|
589 | - } |
|
590 | - |
|
591 | - /** |
|
592 | - * @param string $search |
|
593 | - * @return array |
|
594 | - */ |
|
595 | - protected function getEmail($search) { |
|
596 | - $result = ['results' => [], 'exact' => []]; |
|
597 | - |
|
598 | - // Search in contacts |
|
599 | - //@todo Pagination missing |
|
600 | - $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']); |
|
601 | - $result['exactIdMatch'] = false; |
|
602 | - foreach ($addressBookContacts as $contact) { |
|
603 | - if (isset($contact['isLocalSystemBook'])) { |
|
604 | - continue; |
|
605 | - } |
|
606 | - if (isset($contact['EMAIL'])) { |
|
607 | - $emailAddresses = $contact['EMAIL']; |
|
608 | - if (!is_array($emailAddresses)) { |
|
609 | - $emailAddresses = [$emailAddresses]; |
|
610 | - } |
|
611 | - foreach ($emailAddresses as $emailAddress) { |
|
612 | - if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) { |
|
613 | - if (strtolower($emailAddress) === strtolower($search)) { |
|
614 | - $result['exactIdMatch'] = true; |
|
615 | - } |
|
616 | - $result['exact'][] = [ |
|
617 | - 'label' => $contact['FN'] . " ($emailAddress)", |
|
618 | - 'value' => [ |
|
619 | - 'shareType' => Share::SHARE_TYPE_EMAIL, |
|
620 | - 'shareWith' => $emailAddress, |
|
621 | - ], |
|
622 | - ]; |
|
623 | - } else { |
|
624 | - $result['results'][] = [ |
|
625 | - 'label' => $contact['FN'] . " ($emailAddress)", |
|
626 | - 'value' => [ |
|
627 | - 'shareType' => Share::SHARE_TYPE_EMAIL, |
|
628 | - 'shareWith' => $emailAddress, |
|
629 | - ], |
|
630 | - ]; |
|
631 | - } |
|
632 | - } |
|
633 | - } |
|
634 | - } |
|
635 | - |
|
636 | - if (!$this->shareeEnumeration) { |
|
637 | - $result['results'] = []; |
|
638 | - } |
|
639 | - |
|
640 | - if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) { |
|
641 | - $result['exact'][] = [ |
|
642 | - 'label' => $search, |
|
643 | - 'value' => [ |
|
644 | - 'shareType' => Share::SHARE_TYPE_EMAIL, |
|
645 | - 'shareWith' => $search, |
|
646 | - ], |
|
647 | - ]; |
|
648 | - } |
|
649 | - |
|
650 | - $this->reachedEndFor[] = 'emails'; |
|
651 | - |
|
652 | - return $result; |
|
653 | - } |
|
654 | - |
|
655 | - protected function getLookup($search) { |
|
656 | - $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no'); |
|
657 | - $result = []; |
|
658 | - |
|
659 | - if($isEnabled === 'yes') { |
|
660 | - try { |
|
661 | - $client = $this->clientService->newClient(); |
|
662 | - $response = $client->get( |
|
663 | - 'https://lookup.nextcloud.com/users?search=' . urlencode($search), |
|
664 | - [ |
|
665 | - 'timeout' => 10, |
|
666 | - 'connect_timeout' => 3, |
|
667 | - ] |
|
668 | - ); |
|
669 | - |
|
670 | - $body = json_decode($response->getBody(), true); |
|
671 | - |
|
672 | - $result = []; |
|
673 | - foreach ($body as $lookup) { |
|
674 | - $result[] = [ |
|
675 | - 'label' => $lookup['federationId'], |
|
676 | - 'value' => [ |
|
677 | - 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
678 | - 'shareWith' => $lookup['federationId'], |
|
679 | - ], |
|
680 | - 'extra' => $lookup, |
|
681 | - ]; |
|
682 | - } |
|
683 | - } catch (\Exception $e) {} |
|
684 | - } |
|
685 | - |
|
686 | - $this->result['lookup'] = $result; |
|
687 | - } |
|
688 | - |
|
689 | - /** |
|
690 | - * Generates a bunch of pagination links for the current page |
|
691 | - * |
|
692 | - * @param int $page Current page |
|
693 | - * @param array $params Parameters for the URL |
|
694 | - * @return string |
|
695 | - */ |
|
696 | - protected function getPaginationLink($page, array $params) { |
|
697 | - if ($this->isV2()) { |
|
698 | - $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?'; |
|
699 | - } else { |
|
700 | - $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?'; |
|
701 | - } |
|
702 | - $params['page'] = $page + 1; |
|
703 | - $link = '<' . $url . http_build_query($params) . '>; rel="next"'; |
|
704 | - |
|
705 | - return $link; |
|
706 | - } |
|
707 | - |
|
708 | - /** |
|
709 | - * @return bool |
|
710 | - */ |
|
711 | - protected function isV2() { |
|
712 | - return $this->request->getScriptName() === '/ocs/v2.php'; |
|
713 | - } |
|
46 | + /** @var IGroupManager */ |
|
47 | + protected $groupManager; |
|
48 | + |
|
49 | + /** @var IUserManager */ |
|
50 | + protected $userManager; |
|
51 | + |
|
52 | + /** @var IManager */ |
|
53 | + protected $contactsManager; |
|
54 | + |
|
55 | + /** @var IConfig */ |
|
56 | + protected $config; |
|
57 | + |
|
58 | + /** @var IUserSession */ |
|
59 | + protected $userSession; |
|
60 | + |
|
61 | + /** @var IURLGenerator */ |
|
62 | + protected $urlGenerator; |
|
63 | + |
|
64 | + /** @var ILogger */ |
|
65 | + protected $logger; |
|
66 | + |
|
67 | + /** @var \OCP\Share\IManager */ |
|
68 | + protected $shareManager; |
|
69 | + |
|
70 | + /** @var IClientService */ |
|
71 | + protected $clientService; |
|
72 | + |
|
73 | + /** @var ICloudIdManager */ |
|
74 | + protected $cloudIdManager; |
|
75 | + |
|
76 | + /** @var bool */ |
|
77 | + protected $shareWithGroupOnly = false; |
|
78 | + |
|
79 | + /** @var bool */ |
|
80 | + protected $shareeEnumeration = true; |
|
81 | + |
|
82 | + /** @var int */ |
|
83 | + protected $offset = 0; |
|
84 | + |
|
85 | + /** @var int */ |
|
86 | + protected $limit = 10; |
|
87 | + |
|
88 | + /** @var array */ |
|
89 | + protected $result = [ |
|
90 | + 'exact' => [ |
|
91 | + 'users' => [], |
|
92 | + 'groups' => [], |
|
93 | + 'remotes' => [], |
|
94 | + 'emails' => [], |
|
95 | + 'circles' => [], |
|
96 | + ], |
|
97 | + 'users' => [], |
|
98 | + 'groups' => [], |
|
99 | + 'remotes' => [], |
|
100 | + 'emails' => [], |
|
101 | + 'lookup' => [], |
|
102 | + 'circles' => [], |
|
103 | + ]; |
|
104 | + |
|
105 | + protected $reachedEndFor = []; |
|
106 | + |
|
107 | + /** |
|
108 | + * @param string $appName |
|
109 | + * @param IRequest $request |
|
110 | + * @param IGroupManager $groupManager |
|
111 | + * @param IUserManager $userManager |
|
112 | + * @param IManager $contactsManager |
|
113 | + * @param IConfig $config |
|
114 | + * @param IUserSession $userSession |
|
115 | + * @param IURLGenerator $urlGenerator |
|
116 | + * @param ILogger $logger |
|
117 | + * @param \OCP\Share\IManager $shareManager |
|
118 | + * @param IClientService $clientService |
|
119 | + * @param ICloudIdManager $cloudIdManager |
|
120 | + */ |
|
121 | + public function __construct($appName, |
|
122 | + IRequest $request, |
|
123 | + IGroupManager $groupManager, |
|
124 | + IUserManager $userManager, |
|
125 | + IManager $contactsManager, |
|
126 | + IConfig $config, |
|
127 | + IUserSession $userSession, |
|
128 | + IURLGenerator $urlGenerator, |
|
129 | + ILogger $logger, |
|
130 | + \OCP\Share\IManager $shareManager, |
|
131 | + IClientService $clientService, |
|
132 | + ICloudIdManager $cloudIdManager |
|
133 | + ) { |
|
134 | + parent::__construct($appName, $request); |
|
135 | + |
|
136 | + $this->groupManager = $groupManager; |
|
137 | + $this->userManager = $userManager; |
|
138 | + $this->contactsManager = $contactsManager; |
|
139 | + $this->config = $config; |
|
140 | + $this->userSession = $userSession; |
|
141 | + $this->urlGenerator = $urlGenerator; |
|
142 | + $this->logger = $logger; |
|
143 | + $this->shareManager = $shareManager; |
|
144 | + $this->clientService = $clientService; |
|
145 | + $this->cloudIdManager = $cloudIdManager; |
|
146 | + } |
|
147 | + |
|
148 | + /** |
|
149 | + * @param string $search |
|
150 | + */ |
|
151 | + protected function getUsers($search) { |
|
152 | + $this->result['users'] = $this->result['exact']['users'] = $users = []; |
|
153 | + |
|
154 | + $userGroups = []; |
|
155 | + if ($this->shareWithGroupOnly) { |
|
156 | + // Search in all the groups this user is part of |
|
157 | + $userGroups = $this->groupManager->getUserGroupIds($this->userSession->getUser()); |
|
158 | + foreach ($userGroups as $userGroup) { |
|
159 | + $usersTmp = $this->groupManager->displayNamesInGroup($userGroup, $search, $this->limit, $this->offset); |
|
160 | + foreach ($usersTmp as $uid => $userDisplayName) { |
|
161 | + $users[$uid] = $userDisplayName; |
|
162 | + } |
|
163 | + } |
|
164 | + } else { |
|
165 | + // Search in all users |
|
166 | + $usersTmp = $this->userManager->searchDisplayName($search, $this->limit, $this->offset); |
|
167 | + |
|
168 | + foreach ($usersTmp as $user) { |
|
169 | + $users[$user->getUID()] = $user->getDisplayName(); |
|
170 | + } |
|
171 | + } |
|
172 | + |
|
173 | + if (!$this->shareeEnumeration || sizeof($users) < $this->limit) { |
|
174 | + $this->reachedEndFor[] = 'users'; |
|
175 | + } |
|
176 | + |
|
177 | + $foundUserById = false; |
|
178 | + $lowerSearch = strtolower($search); |
|
179 | + foreach ($users as $uid => $userDisplayName) { |
|
180 | + if (strtolower($uid) === $lowerSearch || strtolower($userDisplayName) === $lowerSearch) { |
|
181 | + if (strtolower($uid) === $lowerSearch) { |
|
182 | + $foundUserById = true; |
|
183 | + } |
|
184 | + $this->result['exact']['users'][] = [ |
|
185 | + 'label' => $userDisplayName, |
|
186 | + 'value' => [ |
|
187 | + 'shareType' => Share::SHARE_TYPE_USER, |
|
188 | + 'shareWith' => $uid, |
|
189 | + ], |
|
190 | + ]; |
|
191 | + } else { |
|
192 | + $this->result['users'][] = [ |
|
193 | + 'label' => $userDisplayName, |
|
194 | + 'value' => [ |
|
195 | + 'shareType' => Share::SHARE_TYPE_USER, |
|
196 | + 'shareWith' => $uid, |
|
197 | + ], |
|
198 | + ]; |
|
199 | + } |
|
200 | + } |
|
201 | + |
|
202 | + if ($this->offset === 0 && !$foundUserById) { |
|
203 | + // On page one we try if the search result has a direct hit on the |
|
204 | + // user id and if so, we add that to the exact match list |
|
205 | + $user = $this->userManager->get($search); |
|
206 | + if ($user instanceof IUser) { |
|
207 | + $addUser = true; |
|
208 | + |
|
209 | + if ($this->shareWithGroupOnly) { |
|
210 | + // Only add, if we have a common group |
|
211 | + $commonGroups = array_intersect($userGroups, $this->groupManager->getUserGroupIds($user)); |
|
212 | + $addUser = !empty($commonGroups); |
|
213 | + } |
|
214 | + |
|
215 | + if ($addUser) { |
|
216 | + array_push($this->result['exact']['users'], [ |
|
217 | + 'label' => $user->getDisplayName(), |
|
218 | + 'value' => [ |
|
219 | + 'shareType' => Share::SHARE_TYPE_USER, |
|
220 | + 'shareWith' => $user->getUID(), |
|
221 | + ], |
|
222 | + ]); |
|
223 | + } |
|
224 | + } |
|
225 | + } |
|
226 | + |
|
227 | + if (!$this->shareeEnumeration) { |
|
228 | + $this->result['users'] = []; |
|
229 | + } |
|
230 | + } |
|
231 | + |
|
232 | + /** |
|
233 | + * @param string $search |
|
234 | + */ |
|
235 | + protected function getGroups($search) { |
|
236 | + $this->result['groups'] = $this->result['exact']['groups'] = []; |
|
237 | + |
|
238 | + $groups = $this->groupManager->search($search, $this->limit, $this->offset); |
|
239 | + $groupIds = array_map(function (IGroup $group) { return $group->getGID(); }, $groups); |
|
240 | + |
|
241 | + if (!$this->shareeEnumeration || sizeof($groups) < $this->limit) { |
|
242 | + $this->reachedEndFor[] = 'groups'; |
|
243 | + } |
|
244 | + |
|
245 | + $userGroups = []; |
|
246 | + if (!empty($groups) && $this->shareWithGroupOnly) { |
|
247 | + // Intersect all the groups that match with the groups this user is a member of |
|
248 | + $userGroups = $this->groupManager->getUserGroups($this->userSession->getUser()); |
|
249 | + $userGroups = array_map(function (IGroup $group) { return $group->getGID(); }, $userGroups); |
|
250 | + $groupIds = array_intersect($groupIds, $userGroups); |
|
251 | + } |
|
252 | + |
|
253 | + $lowerSearch = strtolower($search); |
|
254 | + foreach ($groups as $group) { |
|
255 | + // FIXME: use a more efficient approach |
|
256 | + $gid = $group->getGID(); |
|
257 | + if (!in_array($gid, $groupIds)) { |
|
258 | + continue; |
|
259 | + } |
|
260 | + if (strtolower($gid) === $lowerSearch || strtolower($group->getDisplayName()) === $lowerSearch) { |
|
261 | + $this->result['exact']['groups'][] = [ |
|
262 | + 'label' => $group->getDisplayName(), |
|
263 | + 'value' => [ |
|
264 | + 'shareType' => Share::SHARE_TYPE_GROUP, |
|
265 | + 'shareWith' => $gid, |
|
266 | + ], |
|
267 | + ]; |
|
268 | + } else { |
|
269 | + $this->result['groups'][] = [ |
|
270 | + 'label' => $group->getDisplayName(), |
|
271 | + 'value' => [ |
|
272 | + 'shareType' => Share::SHARE_TYPE_GROUP, |
|
273 | + 'shareWith' => $gid, |
|
274 | + ], |
|
275 | + ]; |
|
276 | + } |
|
277 | + } |
|
278 | + |
|
279 | + if ($this->offset === 0 && empty($this->result['exact']['groups'])) { |
|
280 | + // On page one we try if the search result has a direct hit on the |
|
281 | + // user id and if so, we add that to the exact match list |
|
282 | + $group = $this->groupManager->get($search); |
|
283 | + if ($group instanceof IGroup && (!$this->shareWithGroupOnly || in_array($group->getGID(), $userGroups))) { |
|
284 | + array_push($this->result['exact']['groups'], [ |
|
285 | + 'label' => $group->getDisplayName(), |
|
286 | + 'value' => [ |
|
287 | + 'shareType' => Share::SHARE_TYPE_GROUP, |
|
288 | + 'shareWith' => $group->getGID(), |
|
289 | + ], |
|
290 | + ]); |
|
291 | + } |
|
292 | + } |
|
293 | + |
|
294 | + if (!$this->shareeEnumeration) { |
|
295 | + $this->result['groups'] = []; |
|
296 | + } |
|
297 | + } |
|
298 | + |
|
299 | + |
|
300 | + /** |
|
301 | + * @param string $search |
|
302 | + */ |
|
303 | + protected function getCircles($search) { |
|
304 | + $this->result['circles'] = $this->result['exact']['circles'] = []; |
|
305 | + |
|
306 | + $result = \OCA\Circles\Api\Sharees::search($search, $this->limit, $this->offset); |
|
307 | + if (array_key_exists('circles', $result['exact'])) { |
|
308 | + $this->result['exact']['circles'] = $result['exact']['circles']; |
|
309 | + } |
|
310 | + if (array_key_exists('circles', $result)) { |
|
311 | + $this->result['circles'] = $result['circles']; |
|
312 | + } |
|
313 | + } |
|
314 | + |
|
315 | + |
|
316 | + /** |
|
317 | + * @param string $search |
|
318 | + * @return array |
|
319 | + */ |
|
320 | + protected function getRemote($search) { |
|
321 | + $result = ['results' => [], 'exact' => []]; |
|
322 | + |
|
323 | + // Search in contacts |
|
324 | + //@todo Pagination missing |
|
325 | + $addressBookContacts = $this->contactsManager->search($search, ['CLOUD', 'FN']); |
|
326 | + $result['exactIdMatch'] = false; |
|
327 | + foreach ($addressBookContacts as $contact) { |
|
328 | + if (isset($contact['isLocalSystemBook'])) { |
|
329 | + continue; |
|
330 | + } |
|
331 | + if (isset($contact['CLOUD'])) { |
|
332 | + $cloudIds = $contact['CLOUD']; |
|
333 | + if (!is_array($cloudIds)) { |
|
334 | + $cloudIds = [$cloudIds]; |
|
335 | + } |
|
336 | + $lowerSearch = strtolower($search); |
|
337 | + foreach ($cloudIds as $cloudId) { |
|
338 | + list(, $serverUrl) = $this->splitUserRemote($cloudId); |
|
339 | + if (strtolower($contact['FN']) === $lowerSearch || strtolower($cloudId) === $lowerSearch) { |
|
340 | + if (strtolower($cloudId) === $lowerSearch) { |
|
341 | + $result['exactIdMatch'] = true; |
|
342 | + } |
|
343 | + $result['exact'][] = [ |
|
344 | + 'label' => $contact['FN'] . " ($cloudId)", |
|
345 | + 'value' => [ |
|
346 | + 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
347 | + 'shareWith' => $cloudId, |
|
348 | + 'server' => $serverUrl, |
|
349 | + ], |
|
350 | + ]; |
|
351 | + } else { |
|
352 | + $result['results'][] = [ |
|
353 | + 'label' => $contact['FN'] . " ($cloudId)", |
|
354 | + 'value' => [ |
|
355 | + 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
356 | + 'shareWith' => $cloudId, |
|
357 | + 'server' => $serverUrl, |
|
358 | + ], |
|
359 | + ]; |
|
360 | + } |
|
361 | + } |
|
362 | + } |
|
363 | + } |
|
364 | + |
|
365 | + if (!$this->shareeEnumeration) { |
|
366 | + $result['results'] = []; |
|
367 | + } |
|
368 | + |
|
369 | + if (!$result['exactIdMatch'] && $this->cloudIdManager->isValidCloudId($search) && $this->offset === 0) { |
|
370 | + $result['exact'][] = [ |
|
371 | + 'label' => $search, |
|
372 | + 'value' => [ |
|
373 | + 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
374 | + 'shareWith' => $search, |
|
375 | + ], |
|
376 | + ]; |
|
377 | + } |
|
378 | + |
|
379 | + $this->reachedEndFor[] = 'remotes'; |
|
380 | + |
|
381 | + return $result; |
|
382 | + } |
|
383 | + |
|
384 | + /** |
|
385 | + * split user and remote from federated cloud id |
|
386 | + * |
|
387 | + * @param string $address federated share address |
|
388 | + * @return array [user, remoteURL] |
|
389 | + * @throws \Exception |
|
390 | + */ |
|
391 | + public function splitUserRemote($address) { |
|
392 | + try { |
|
393 | + $cloudId = $this->cloudIdManager->resolveCloudId($address); |
|
394 | + return [$cloudId->getUser(), $cloudId->getRemote()]; |
|
395 | + } catch (\InvalidArgumentException $e) { |
|
396 | + throw new \Exception('Invalid Federated Cloud ID', 0, $e); |
|
397 | + } |
|
398 | + } |
|
399 | + |
|
400 | + /** |
|
401 | + * Strips away a potential file names and trailing slashes: |
|
402 | + * - http://localhost |
|
403 | + * - http://localhost/ |
|
404 | + * - http://localhost/index.php |
|
405 | + * - http://localhost/index.php/s/{shareToken} |
|
406 | + * |
|
407 | + * all return: http://localhost |
|
408 | + * |
|
409 | + * @param string $remote |
|
410 | + * @return string |
|
411 | + */ |
|
412 | + protected function fixRemoteURL($remote) { |
|
413 | + $remote = str_replace('\\', '/', $remote); |
|
414 | + if ($fileNamePosition = strpos($remote, '/index.php')) { |
|
415 | + $remote = substr($remote, 0, $fileNamePosition); |
|
416 | + } |
|
417 | + $remote = rtrim($remote, '/'); |
|
418 | + |
|
419 | + return $remote; |
|
420 | + } |
|
421 | + |
|
422 | + /** |
|
423 | + * @NoAdminRequired |
|
424 | + * |
|
425 | + * @param string $search |
|
426 | + * @param string $itemType |
|
427 | + * @param int $page |
|
428 | + * @param int $perPage |
|
429 | + * @param int|int[] $shareType |
|
430 | + * @param bool $lookup |
|
431 | + * @return DataResponse |
|
432 | + * @throws OCSBadRequestException |
|
433 | + */ |
|
434 | + public function search($search = '', $itemType = null, $page = 1, $perPage = 200, $shareType = null, $lookup = true) { |
|
435 | + |
|
436 | + // only search for string larger than a given threshold |
|
437 | + $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0); |
|
438 | + if (strlen($search) < $threshold) { |
|
439 | + return new DataResponse($this->result); |
|
440 | + } |
|
441 | + |
|
442 | + // never return more than the max. number of results configured in the config.php |
|
443 | + $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0); |
|
444 | + if ($maxResults > 0) { |
|
445 | + $perPage = min($perPage, $maxResults); |
|
446 | + } |
|
447 | + if ($perPage <= 0) { |
|
448 | + throw new OCSBadRequestException('Invalid perPage argument'); |
|
449 | + } |
|
450 | + if ($page <= 0) { |
|
451 | + throw new OCSBadRequestException('Invalid page'); |
|
452 | + } |
|
453 | + |
|
454 | + $shareTypes = [ |
|
455 | + Share::SHARE_TYPE_USER, |
|
456 | + ]; |
|
457 | + |
|
458 | + if ($itemType === 'file' || $itemType === 'folder') { |
|
459 | + if ($this->shareManager->allowGroupSharing()) { |
|
460 | + $shareTypes[] = Share::SHARE_TYPE_GROUP; |
|
461 | + } |
|
462 | + |
|
463 | + if ($this->isRemoteSharingAllowed($itemType)) { |
|
464 | + $shareTypes[] = Share::SHARE_TYPE_REMOTE; |
|
465 | + } |
|
466 | + |
|
467 | + if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) { |
|
468 | + $shareTypes[] = Share::SHARE_TYPE_EMAIL; |
|
469 | + } |
|
470 | + } else { |
|
471 | + $shareTypes[] = Share::SHARE_TYPE_GROUP; |
|
472 | + $shareTypes[] = Share::SHARE_TYPE_EMAIL; |
|
473 | + } |
|
474 | + |
|
475 | + if (\OCP\App::isEnabled('circles')) { |
|
476 | + $shareTypes[] = Share::SHARE_TYPE_CIRCLE; |
|
477 | + } |
|
478 | + |
|
479 | + if (isset($_GET['shareType']) && is_array($_GET['shareType'])) { |
|
480 | + $shareTypes = array_intersect($shareTypes, $_GET['shareType']); |
|
481 | + sort($shareTypes); |
|
482 | + } else if (is_numeric($shareType)) { |
|
483 | + $shareTypes = array_intersect($shareTypes, [(int) $shareType]); |
|
484 | + sort($shareTypes); |
|
485 | + } |
|
486 | + |
|
487 | + $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes'; |
|
488 | + $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; |
|
489 | + $this->limit = (int) $perPage; |
|
490 | + $this->offset = $perPage * ($page - 1); |
|
491 | + |
|
492 | + return $this->searchSharees($search, $itemType, $shareTypes, $page, $perPage, $lookup); |
|
493 | + } |
|
494 | + |
|
495 | + /** |
|
496 | + * Method to get out the static call for better testing |
|
497 | + * |
|
498 | + * @param string $itemType |
|
499 | + * @return bool |
|
500 | + */ |
|
501 | + protected function isRemoteSharingAllowed($itemType) { |
|
502 | + try { |
|
503 | + $backend = Share::getBackend($itemType); |
|
504 | + return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE); |
|
505 | + } catch (\Exception $e) { |
|
506 | + return false; |
|
507 | + } |
|
508 | + } |
|
509 | + |
|
510 | + /** |
|
511 | + * Testable search function that does not need globals |
|
512 | + * |
|
513 | + * @param string $search |
|
514 | + * @param string $itemType |
|
515 | + * @param array $shareTypes |
|
516 | + * @param int $page |
|
517 | + * @param int $perPage |
|
518 | + * @param bool $lookup |
|
519 | + * @return DataResponse |
|
520 | + * @throws OCSBadRequestException |
|
521 | + */ |
|
522 | + protected function searchSharees($search, $itemType, array $shareTypes, $page, $perPage, $lookup) { |
|
523 | + // Verify arguments |
|
524 | + if ($itemType === null) { |
|
525 | + throw new OCSBadRequestException('Missing itemType'); |
|
526 | + } |
|
527 | + |
|
528 | + // Get users |
|
529 | + if (in_array(Share::SHARE_TYPE_USER, $shareTypes)) { |
|
530 | + $this->getUsers($search); |
|
531 | + } |
|
532 | + |
|
533 | + // Get groups |
|
534 | + if (in_array(Share::SHARE_TYPE_GROUP, $shareTypes)) { |
|
535 | + $this->getGroups($search); |
|
536 | + } |
|
537 | + |
|
538 | + // Get circles |
|
539 | + if (in_array(Share::SHARE_TYPE_CIRCLE, $shareTypes)) { |
|
540 | + $this->getCircles($search); |
|
541 | + } |
|
542 | + |
|
543 | + |
|
544 | + // Get remote |
|
545 | + $remoteResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false]; |
|
546 | + if (in_array(Share::SHARE_TYPE_REMOTE, $shareTypes)) { |
|
547 | + $remoteResults = $this->getRemote($search); |
|
548 | + } |
|
549 | + |
|
550 | + // Get emails |
|
551 | + $mailResults = ['results' => [], 'exact' => [], 'exactIdMatch' => false]; |
|
552 | + if (in_array(Share::SHARE_TYPE_EMAIL, $shareTypes)) { |
|
553 | + $mailResults = $this->getEmail($search); |
|
554 | + } |
|
555 | + |
|
556 | + // Get from lookup server |
|
557 | + if ($lookup) { |
|
558 | + $this->getLookup($search); |
|
559 | + } |
|
560 | + |
|
561 | + // if we have a exact match, either for the federated cloud id or for the |
|
562 | + // email address we only return the exact match. It is highly unlikely |
|
563 | + // that the exact same email address and federated cloud id exists |
|
564 | + if ($mailResults['exactIdMatch'] && !$remoteResults['exactIdMatch']) { |
|
565 | + $this->result['emails'] = $mailResults['results']; |
|
566 | + $this->result['exact']['emails'] = $mailResults['exact']; |
|
567 | + } else if (!$mailResults['exactIdMatch'] && $remoteResults['exactIdMatch']) { |
|
568 | + $this->result['remotes'] = $remoteResults['results']; |
|
569 | + $this->result['exact']['remotes'] = $remoteResults['exact']; |
|
570 | + } else { |
|
571 | + $this->result['remotes'] = $remoteResults['results']; |
|
572 | + $this->result['exact']['remotes'] = $remoteResults['exact']; |
|
573 | + $this->result['emails'] = $mailResults['results']; |
|
574 | + $this->result['exact']['emails'] = $mailResults['exact']; |
|
575 | + } |
|
576 | + |
|
577 | + $response = new DataResponse($this->result); |
|
578 | + |
|
579 | + if (sizeof($this->reachedEndFor) < 3) { |
|
580 | + $response->addHeader('Link', $this->getPaginationLink($page, [ |
|
581 | + 'search' => $search, |
|
582 | + 'itemType' => $itemType, |
|
583 | + 'shareType' => $shareTypes, |
|
584 | + 'perPage' => $perPage, |
|
585 | + ])); |
|
586 | + } |
|
587 | + |
|
588 | + return $response; |
|
589 | + } |
|
590 | + |
|
591 | + /** |
|
592 | + * @param string $search |
|
593 | + * @return array |
|
594 | + */ |
|
595 | + protected function getEmail($search) { |
|
596 | + $result = ['results' => [], 'exact' => []]; |
|
597 | + |
|
598 | + // Search in contacts |
|
599 | + //@todo Pagination missing |
|
600 | + $addressBookContacts = $this->contactsManager->search($search, ['EMAIL', 'FN']); |
|
601 | + $result['exactIdMatch'] = false; |
|
602 | + foreach ($addressBookContacts as $contact) { |
|
603 | + if (isset($contact['isLocalSystemBook'])) { |
|
604 | + continue; |
|
605 | + } |
|
606 | + if (isset($contact['EMAIL'])) { |
|
607 | + $emailAddresses = $contact['EMAIL']; |
|
608 | + if (!is_array($emailAddresses)) { |
|
609 | + $emailAddresses = [$emailAddresses]; |
|
610 | + } |
|
611 | + foreach ($emailAddresses as $emailAddress) { |
|
612 | + if (strtolower($contact['FN']) === strtolower($search) || strtolower($emailAddress) === strtolower($search)) { |
|
613 | + if (strtolower($emailAddress) === strtolower($search)) { |
|
614 | + $result['exactIdMatch'] = true; |
|
615 | + } |
|
616 | + $result['exact'][] = [ |
|
617 | + 'label' => $contact['FN'] . " ($emailAddress)", |
|
618 | + 'value' => [ |
|
619 | + 'shareType' => Share::SHARE_TYPE_EMAIL, |
|
620 | + 'shareWith' => $emailAddress, |
|
621 | + ], |
|
622 | + ]; |
|
623 | + } else { |
|
624 | + $result['results'][] = [ |
|
625 | + 'label' => $contact['FN'] . " ($emailAddress)", |
|
626 | + 'value' => [ |
|
627 | + 'shareType' => Share::SHARE_TYPE_EMAIL, |
|
628 | + 'shareWith' => $emailAddress, |
|
629 | + ], |
|
630 | + ]; |
|
631 | + } |
|
632 | + } |
|
633 | + } |
|
634 | + } |
|
635 | + |
|
636 | + if (!$this->shareeEnumeration) { |
|
637 | + $result['results'] = []; |
|
638 | + } |
|
639 | + |
|
640 | + if (!$result['exactIdMatch'] && filter_var($search, FILTER_VALIDATE_EMAIL)) { |
|
641 | + $result['exact'][] = [ |
|
642 | + 'label' => $search, |
|
643 | + 'value' => [ |
|
644 | + 'shareType' => Share::SHARE_TYPE_EMAIL, |
|
645 | + 'shareWith' => $search, |
|
646 | + ], |
|
647 | + ]; |
|
648 | + } |
|
649 | + |
|
650 | + $this->reachedEndFor[] = 'emails'; |
|
651 | + |
|
652 | + return $result; |
|
653 | + } |
|
654 | + |
|
655 | + protected function getLookup($search) { |
|
656 | + $isEnabled = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no'); |
|
657 | + $result = []; |
|
658 | + |
|
659 | + if($isEnabled === 'yes') { |
|
660 | + try { |
|
661 | + $client = $this->clientService->newClient(); |
|
662 | + $response = $client->get( |
|
663 | + 'https://lookup.nextcloud.com/users?search=' . urlencode($search), |
|
664 | + [ |
|
665 | + 'timeout' => 10, |
|
666 | + 'connect_timeout' => 3, |
|
667 | + ] |
|
668 | + ); |
|
669 | + |
|
670 | + $body = json_decode($response->getBody(), true); |
|
671 | + |
|
672 | + $result = []; |
|
673 | + foreach ($body as $lookup) { |
|
674 | + $result[] = [ |
|
675 | + 'label' => $lookup['federationId'], |
|
676 | + 'value' => [ |
|
677 | + 'shareType' => Share::SHARE_TYPE_REMOTE, |
|
678 | + 'shareWith' => $lookup['federationId'], |
|
679 | + ], |
|
680 | + 'extra' => $lookup, |
|
681 | + ]; |
|
682 | + } |
|
683 | + } catch (\Exception $e) {} |
|
684 | + } |
|
685 | + |
|
686 | + $this->result['lookup'] = $result; |
|
687 | + } |
|
688 | + |
|
689 | + /** |
|
690 | + * Generates a bunch of pagination links for the current page |
|
691 | + * |
|
692 | + * @param int $page Current page |
|
693 | + * @param array $params Parameters for the URL |
|
694 | + * @return string |
|
695 | + */ |
|
696 | + protected function getPaginationLink($page, array $params) { |
|
697 | + if ($this->isV2()) { |
|
698 | + $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?'; |
|
699 | + } else { |
|
700 | + $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?'; |
|
701 | + } |
|
702 | + $params['page'] = $page + 1; |
|
703 | + $link = '<' . $url . http_build_query($params) . '>; rel="next"'; |
|
704 | + |
|
705 | + return $link; |
|
706 | + } |
|
707 | + |
|
708 | + /** |
|
709 | + * @return bool |
|
710 | + */ |
|
711 | + protected function isV2() { |
|
712 | + return $this->request->getScriptName() === '/ocs/v2.php'; |
|
713 | + } |
|
714 | 714 | } |
@@ -225,7 +225,7 @@ |
||
225 | 225 | /** |
226 | 226 | * creates a array with all user data |
227 | 227 | * |
228 | - * @param $userId |
|
228 | + * @param string $userId |
|
229 | 229 | * @return array |
230 | 230 | * @throws OCSException |
231 | 231 | */ |
@@ -335,7 +335,7 @@ |
||
335 | 335 | } |
336 | 336 | if($quota === 0) { |
337 | 337 | $quota = 'default'; |
338 | - }else if($quota === -1) { |
|
338 | + } else if($quota === -1) { |
|
339 | 339 | $quota = 'none'; |
340 | 340 | } else { |
341 | 341 | $quota = \OCP\Util::humanFileSize($quota); |
@@ -48,757 +48,757 @@ |
||
48 | 48 | |
49 | 49 | class UsersController extends OCSController { |
50 | 50 | |
51 | - /** @var IUserManager */ |
|
52 | - private $userManager; |
|
53 | - /** @var IConfig */ |
|
54 | - private $config; |
|
55 | - /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface |
|
56 | - private $groupManager; |
|
57 | - /** @var IUserSession */ |
|
58 | - private $userSession; |
|
59 | - /** @var AccountManager */ |
|
60 | - private $accountManager; |
|
61 | - /** @var ILogger */ |
|
62 | - private $logger; |
|
63 | - /** @var IFactory */ |
|
64 | - private $l10nFactory; |
|
65 | - /** @var NewUserMailHelper */ |
|
66 | - private $newUserMailHelper; |
|
67 | - |
|
68 | - /** |
|
69 | - * @param string $appName |
|
70 | - * @param IRequest $request |
|
71 | - * @param IUserManager $userManager |
|
72 | - * @param IConfig $config |
|
73 | - * @param IGroupManager $groupManager |
|
74 | - * @param IUserSession $userSession |
|
75 | - * @param AccountManager $accountManager |
|
76 | - * @param ILogger $logger |
|
77 | - * @param IFactory $l10nFactory |
|
78 | - * @param NewUserMailHelper $newUserMailHelper |
|
79 | - */ |
|
80 | - public function __construct($appName, |
|
81 | - IRequest $request, |
|
82 | - IUserManager $userManager, |
|
83 | - IConfig $config, |
|
84 | - IGroupManager $groupManager, |
|
85 | - IUserSession $userSession, |
|
86 | - AccountManager $accountManager, |
|
87 | - ILogger $logger, |
|
88 | - IFactory $l10nFactory, |
|
89 | - NewUserMailHelper $newUserMailHelper) { |
|
90 | - parent::__construct($appName, $request); |
|
91 | - |
|
92 | - $this->userManager = $userManager; |
|
93 | - $this->config = $config; |
|
94 | - $this->groupManager = $groupManager; |
|
95 | - $this->userSession = $userSession; |
|
96 | - $this->accountManager = $accountManager; |
|
97 | - $this->logger = $logger; |
|
98 | - $this->l10nFactory = $l10nFactory; |
|
99 | - $this->newUserMailHelper = $newUserMailHelper; |
|
100 | - } |
|
101 | - |
|
102 | - /** |
|
103 | - * @NoAdminRequired |
|
104 | - * |
|
105 | - * returns a list of users |
|
106 | - * |
|
107 | - * @param string $search |
|
108 | - * @param int $limit |
|
109 | - * @param int $offset |
|
110 | - * @return DataResponse |
|
111 | - */ |
|
112 | - public function getUsers($search = '', $limit = null, $offset = null) { |
|
113 | - $user = $this->userSession->getUser(); |
|
114 | - $users = []; |
|
115 | - |
|
116 | - // Admin? Or SubAdmin? |
|
117 | - $uid = $user->getUID(); |
|
118 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
119 | - if($this->groupManager->isAdmin($uid)){ |
|
120 | - $users = $this->userManager->search($search, $limit, $offset); |
|
121 | - } else if ($subAdminManager->isSubAdmin($user)) { |
|
122 | - $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user); |
|
123 | - foreach ($subAdminOfGroups as $key => $group) { |
|
124 | - $subAdminOfGroups[$key] = $group->getGID(); |
|
125 | - } |
|
126 | - |
|
127 | - if($offset === null) { |
|
128 | - $offset = 0; |
|
129 | - } |
|
130 | - |
|
131 | - $users = []; |
|
132 | - foreach ($subAdminOfGroups as $group) { |
|
133 | - $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search)); |
|
134 | - } |
|
135 | - |
|
136 | - $users = array_slice($users, $offset, $limit); |
|
137 | - } |
|
138 | - |
|
139 | - $users = array_keys($users); |
|
140 | - |
|
141 | - return new DataResponse([ |
|
142 | - 'users' => $users |
|
143 | - ]); |
|
144 | - } |
|
145 | - |
|
146 | - /** |
|
147 | - * @PasswordConfirmationRequired |
|
148 | - * @NoAdminRequired |
|
149 | - * |
|
150 | - * @param string $userid |
|
151 | - * @param string $password |
|
152 | - * @param array $groups |
|
153 | - * @return DataResponse |
|
154 | - * @throws OCSException |
|
155 | - */ |
|
156 | - public function addUser($userid, $password, $groups = null) { |
|
157 | - $user = $this->userSession->getUser(); |
|
158 | - $isAdmin = $this->groupManager->isAdmin($user->getUID()); |
|
159 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
160 | - |
|
161 | - if($this->userManager->userExists($userid)) { |
|
162 | - $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); |
|
163 | - throw new OCSException('User already exists', 102); |
|
164 | - } |
|
165 | - |
|
166 | - if(is_array($groups)) { |
|
167 | - foreach ($groups as $group) { |
|
168 | - if(!$this->groupManager->groupExists($group)) { |
|
169 | - throw new OCSException('group '.$group.' does not exist', 104); |
|
170 | - } |
|
171 | - if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) { |
|
172 | - throw new OCSException('insufficient privileges for group '. $group, 105); |
|
173 | - } |
|
174 | - } |
|
175 | - } else { |
|
176 | - if(!$isAdmin) { |
|
177 | - throw new OCSException('no group specified (required for subadmins)', 106); |
|
178 | - } |
|
179 | - } |
|
180 | - |
|
181 | - try { |
|
182 | - $newUser = $this->userManager->createUser($userid, $password); |
|
183 | - $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']); |
|
184 | - |
|
185 | - if (is_array($groups)) { |
|
186 | - foreach ($groups as $group) { |
|
187 | - $this->groupManager->get($group)->addUser($newUser); |
|
188 | - $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']); |
|
189 | - } |
|
190 | - } |
|
191 | - return new DataResponse(); |
|
192 | - } catch (\Exception $e) { |
|
193 | - $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']); |
|
194 | - throw new OCSException('Bad request', 101); |
|
195 | - } |
|
196 | - } |
|
197 | - |
|
198 | - /** |
|
199 | - * @NoAdminRequired |
|
200 | - * @NoSubAdminRequired |
|
201 | - * |
|
202 | - * gets user info |
|
203 | - * |
|
204 | - * @param string $userId |
|
205 | - * @return DataResponse |
|
206 | - * @throws OCSException |
|
207 | - */ |
|
208 | - public function getUser($userId) { |
|
209 | - $data = $this->getUserData($userId); |
|
210 | - return new DataResponse($data); |
|
211 | - } |
|
212 | - |
|
213 | - /** |
|
214 | - * @NoAdminRequired |
|
215 | - * @NoSubAdminRequired |
|
216 | - * |
|
217 | - * gets user info from the currently logged in user |
|
218 | - * |
|
219 | - * @return DataResponse |
|
220 | - * @throws OCSException |
|
221 | - */ |
|
222 | - public function getCurrentUser() { |
|
223 | - $user = $this->userSession->getUser(); |
|
224 | - if ($user) { |
|
225 | - $data = $this->getUserData($user->getUID()); |
|
226 | - // rename "displayname" to "display-name" only for this call to keep |
|
227 | - // the API stable. |
|
228 | - $data['display-name'] = $data['displayname']; |
|
229 | - unset($data['displayname']); |
|
230 | - return new DataResponse($data); |
|
231 | - |
|
232 | - } |
|
233 | - |
|
234 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
235 | - } |
|
236 | - |
|
237 | - /** |
|
238 | - * creates a array with all user data |
|
239 | - * |
|
240 | - * @param $userId |
|
241 | - * @return array |
|
242 | - * @throws OCSException |
|
243 | - */ |
|
244 | - protected function getUserData($userId) { |
|
245 | - $currentLoggedInUser = $this->userSession->getUser(); |
|
246 | - |
|
247 | - $data = []; |
|
248 | - |
|
249 | - // Check if the target user exists |
|
250 | - $targetUserObject = $this->userManager->get($userId); |
|
251 | - if($targetUserObject === null) { |
|
252 | - throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND); |
|
253 | - } |
|
254 | - |
|
255 | - // Admin? Or SubAdmin? |
|
256 | - if($this->groupManager->isAdmin($currentLoggedInUser->getUID()) |
|
257 | - || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) { |
|
258 | - $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true'); |
|
259 | - } else { |
|
260 | - // Check they are looking up themselves |
|
261 | - if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) { |
|
262 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
263 | - } |
|
264 | - } |
|
265 | - |
|
266 | - $userAccount = $this->accountManager->getUser($targetUserObject); |
|
267 | - $groups = $this->groupManager->getUserGroups($targetUserObject); |
|
268 | - $gids = []; |
|
269 | - foreach ($groups as $group) { |
|
270 | - $gids[] = $group->getDisplayName(); |
|
271 | - } |
|
272 | - |
|
273 | - // Find the data |
|
274 | - $data['id'] = $targetUserObject->getUID(); |
|
275 | - $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID()); |
|
276 | - $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress(); |
|
277 | - $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName(); |
|
278 | - $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value']; |
|
279 | - $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value']; |
|
280 | - $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value']; |
|
281 | - $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value']; |
|
282 | - $data['groups'] = $gids; |
|
283 | - |
|
284 | - return $data; |
|
285 | - } |
|
286 | - |
|
287 | - /** |
|
288 | - * @NoAdminRequired |
|
289 | - * @NoSubAdminRequired |
|
290 | - * @PasswordConfirmationRequired |
|
291 | - * |
|
292 | - * edit users |
|
293 | - * |
|
294 | - * @param string $userId |
|
295 | - * @param string $key |
|
296 | - * @param string $value |
|
297 | - * @return DataResponse |
|
298 | - * @throws OCSException |
|
299 | - * @throws OCSForbiddenException |
|
300 | - */ |
|
301 | - public function editUser($userId, $key, $value) { |
|
302 | - $currentLoggedInUser = $this->userSession->getUser(); |
|
303 | - |
|
304 | - $targetUser = $this->userManager->get($userId); |
|
305 | - if($targetUser === null) { |
|
306 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
307 | - } |
|
308 | - |
|
309 | - $permittedFields = []; |
|
310 | - if($targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
311 | - // Editing self (display, email) |
|
312 | - $permittedFields[] = 'display'; |
|
313 | - $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME; |
|
314 | - $permittedFields[] = AccountManager::PROPERTY_EMAIL; |
|
315 | - $permittedFields[] = 'password'; |
|
316 | - $permittedFields[] = AccountManager::PROPERTY_PHONE; |
|
317 | - $permittedFields[] = AccountManager::PROPERTY_ADDRESS; |
|
318 | - $permittedFields[] = AccountManager::PROPERTY_WEBSITE; |
|
319 | - $permittedFields[] = AccountManager::PROPERTY_TWITTER; |
|
320 | - // If admin they can edit their own quota |
|
321 | - if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
322 | - $permittedFields[] = 'quota'; |
|
323 | - } |
|
324 | - } else { |
|
325 | - // Check if admin / subadmin |
|
326 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
327 | - if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
328 | - || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
329 | - // They have permissions over the user |
|
330 | - $permittedFields[] = 'display'; |
|
331 | - $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME; |
|
332 | - $permittedFields[] = AccountManager::PROPERTY_EMAIL; |
|
333 | - $permittedFields[] = 'password'; |
|
334 | - $permittedFields[] = AccountManager::PROPERTY_PHONE; |
|
335 | - $permittedFields[] = AccountManager::PROPERTY_ADDRESS; |
|
336 | - $permittedFields[] = AccountManager::PROPERTY_WEBSITE; |
|
337 | - $permittedFields[] = AccountManager::PROPERTY_TWITTER; |
|
338 | - $permittedFields[] = 'quota'; |
|
339 | - } else { |
|
340 | - // No rights |
|
341 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
342 | - } |
|
343 | - } |
|
344 | - // Check if permitted to edit this field |
|
345 | - if(!in_array($key, $permittedFields)) { |
|
346 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
347 | - } |
|
348 | - // Process the edit |
|
349 | - switch($key) { |
|
350 | - case 'display': |
|
351 | - case AccountManager::PROPERTY_DISPLAYNAME: |
|
352 | - $targetUser->setDisplayName($value); |
|
353 | - break; |
|
354 | - case 'quota': |
|
355 | - $quota = $value; |
|
356 | - if($quota !== 'none' && $quota !== 'default') { |
|
357 | - if (is_numeric($quota)) { |
|
358 | - $quota = (float) $quota; |
|
359 | - } else { |
|
360 | - $quota = \OCP\Util::computerFileSize($quota); |
|
361 | - } |
|
362 | - if ($quota === false) { |
|
363 | - throw new OCSException('Invalid quota value '.$value, 103); |
|
364 | - } |
|
365 | - if($quota === 0) { |
|
366 | - $quota = 'default'; |
|
367 | - }else if($quota === -1) { |
|
368 | - $quota = 'none'; |
|
369 | - } else { |
|
370 | - $quota = \OCP\Util::humanFileSize($quota); |
|
371 | - } |
|
372 | - } |
|
373 | - $targetUser->setQuota($quota); |
|
374 | - break; |
|
375 | - case 'password': |
|
376 | - $targetUser->setPassword($value); |
|
377 | - break; |
|
378 | - case AccountManager::PROPERTY_EMAIL: |
|
379 | - if(filter_var($value, FILTER_VALIDATE_EMAIL)) { |
|
380 | - $targetUser->setEMailAddress($value); |
|
381 | - } else { |
|
382 | - throw new OCSException('', 102); |
|
383 | - } |
|
384 | - break; |
|
385 | - case AccountManager::PROPERTY_PHONE: |
|
386 | - case AccountManager::PROPERTY_ADDRESS: |
|
387 | - case AccountManager::PROPERTY_WEBSITE: |
|
388 | - case AccountManager::PROPERTY_TWITTER: |
|
389 | - $userAccount = $this->accountManager->getUser($targetUser); |
|
390 | - if ($userAccount[$key]['value'] !== $value) { |
|
391 | - $userAccount[$key]['value'] = $value; |
|
392 | - $this->accountManager->updateUser($targetUser, $userAccount); |
|
393 | - } |
|
394 | - break; |
|
395 | - default: |
|
396 | - throw new OCSException('', 103); |
|
397 | - } |
|
398 | - return new DataResponse(); |
|
399 | - } |
|
400 | - |
|
401 | - /** |
|
402 | - * @PasswordConfirmationRequired |
|
403 | - * @NoAdminRequired |
|
404 | - * |
|
405 | - * @param string $userId |
|
406 | - * @return DataResponse |
|
407 | - * @throws OCSException |
|
408 | - * @throws OCSForbiddenException |
|
409 | - */ |
|
410 | - public function deleteUser($userId) { |
|
411 | - $currentLoggedInUser = $this->userSession->getUser(); |
|
412 | - |
|
413 | - $targetUser = $this->userManager->get($userId); |
|
414 | - |
|
415 | - if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
416 | - throw new OCSException('', 101); |
|
417 | - } |
|
418 | - |
|
419 | - // If not permitted |
|
420 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
421 | - if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
422 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
423 | - } |
|
424 | - |
|
425 | - // Go ahead with the delete |
|
426 | - if($targetUser->delete()) { |
|
427 | - return new DataResponse(); |
|
428 | - } else { |
|
429 | - throw new OCSException('', 101); |
|
430 | - } |
|
431 | - } |
|
432 | - |
|
433 | - /** |
|
434 | - * @PasswordConfirmationRequired |
|
435 | - * @NoAdminRequired |
|
436 | - * |
|
437 | - * @param string $userId |
|
438 | - * @return DataResponse |
|
439 | - * @throws OCSException |
|
440 | - * @throws OCSForbiddenException |
|
441 | - */ |
|
442 | - public function disableUser($userId) { |
|
443 | - return $this->setEnabled($userId, false); |
|
444 | - } |
|
445 | - |
|
446 | - /** |
|
447 | - * @PasswordConfirmationRequired |
|
448 | - * @NoAdminRequired |
|
449 | - * |
|
450 | - * @param string $userId |
|
451 | - * @return DataResponse |
|
452 | - * @throws OCSException |
|
453 | - * @throws OCSForbiddenException |
|
454 | - */ |
|
455 | - public function enableUser($userId) { |
|
456 | - return $this->setEnabled($userId, true); |
|
457 | - } |
|
458 | - |
|
459 | - /** |
|
460 | - * @param string $userId |
|
461 | - * @param bool $value |
|
462 | - * @return DataResponse |
|
463 | - * @throws OCSException |
|
464 | - * @throws OCSForbiddenException |
|
465 | - */ |
|
466 | - private function setEnabled($userId, $value) { |
|
467 | - $currentLoggedInUser = $this->userSession->getUser(); |
|
468 | - |
|
469 | - $targetUser = $this->userManager->get($userId); |
|
470 | - if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
471 | - throw new OCSException('', 101); |
|
472 | - } |
|
473 | - |
|
474 | - // If not permitted |
|
475 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
476 | - if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
477 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
478 | - } |
|
479 | - |
|
480 | - // enable/disable the user now |
|
481 | - $targetUser->setEnabled($value); |
|
482 | - return new DataResponse(); |
|
483 | - } |
|
484 | - |
|
485 | - /** |
|
486 | - * @NoAdminRequired |
|
487 | - * @NoSubAdminRequired |
|
488 | - * |
|
489 | - * @param string $userId |
|
490 | - * @return DataResponse |
|
491 | - * @throws OCSException |
|
492 | - */ |
|
493 | - public function getUsersGroups($userId) { |
|
494 | - $loggedInUser = $this->userSession->getUser(); |
|
495 | - |
|
496 | - $targetUser = $this->userManager->get($userId); |
|
497 | - if($targetUser === null) { |
|
498 | - throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND); |
|
499 | - } |
|
500 | - |
|
501 | - if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
502 | - // Self lookup or admin lookup |
|
503 | - return new DataResponse([ |
|
504 | - 'groups' => $this->groupManager->getUserGroupIds($targetUser) |
|
505 | - ]); |
|
506 | - } else { |
|
507 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
508 | - |
|
509 | - // Looking up someone else |
|
510 | - if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) { |
|
511 | - // Return the group that the method caller is subadmin of for the user in question |
|
512 | - /** @var IGroup[] $getSubAdminsGroups */ |
|
513 | - $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); |
|
514 | - foreach ($getSubAdminsGroups as $key => $group) { |
|
515 | - $getSubAdminsGroups[$key] = $group->getGID(); |
|
516 | - } |
|
517 | - $groups = array_intersect( |
|
518 | - $getSubAdminsGroups, |
|
519 | - $this->groupManager->getUserGroupIds($targetUser) |
|
520 | - ); |
|
521 | - return new DataResponse(['groups' => $groups]); |
|
522 | - } else { |
|
523 | - // Not permitted |
|
524 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
525 | - } |
|
526 | - } |
|
527 | - |
|
528 | - } |
|
529 | - |
|
530 | - /** |
|
531 | - * @PasswordConfirmationRequired |
|
532 | - * @NoAdminRequired |
|
533 | - * |
|
534 | - * @param string $userId |
|
535 | - * @param string $groupid |
|
536 | - * @return DataResponse |
|
537 | - * @throws OCSException |
|
538 | - */ |
|
539 | - public function addToGroup($userId, $groupid = '') { |
|
540 | - if($groupid === '') { |
|
541 | - throw new OCSException('', 101); |
|
542 | - } |
|
543 | - |
|
544 | - $group = $this->groupManager->get($groupid); |
|
545 | - $targetUser = $this->userManager->get($userId); |
|
546 | - if($group === null) { |
|
547 | - throw new OCSException('', 102); |
|
548 | - } |
|
549 | - if($targetUser === null) { |
|
550 | - throw new OCSException('', 103); |
|
551 | - } |
|
552 | - |
|
553 | - // If they're not an admin, check they are a subadmin of the group in question |
|
554 | - $loggedInUser = $this->userSession->getUser(); |
|
555 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
556 | - if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { |
|
557 | - throw new OCSException('', 104); |
|
558 | - } |
|
559 | - |
|
560 | - // Add user to group |
|
561 | - $group->addUser($targetUser); |
|
562 | - return new DataResponse(); |
|
563 | - } |
|
564 | - |
|
565 | - /** |
|
566 | - * @PasswordConfirmationRequired |
|
567 | - * @NoAdminRequired |
|
568 | - * |
|
569 | - * @param string $userId |
|
570 | - * @param string $groupid |
|
571 | - * @return DataResponse |
|
572 | - * @throws OCSException |
|
573 | - */ |
|
574 | - public function removeFromGroup($userId, $groupid) { |
|
575 | - $loggedInUser = $this->userSession->getUser(); |
|
576 | - |
|
577 | - if($groupid === null) { |
|
578 | - throw new OCSException('', 101); |
|
579 | - } |
|
580 | - |
|
581 | - $group = $this->groupManager->get($groupid); |
|
582 | - if($group === null) { |
|
583 | - throw new OCSException('', 102); |
|
584 | - } |
|
585 | - |
|
586 | - $targetUser = $this->userManager->get($userId); |
|
587 | - if($targetUser === null) { |
|
588 | - throw new OCSException('', 103); |
|
589 | - } |
|
590 | - |
|
591 | - // If they're not an admin, check they are a subadmin of the group in question |
|
592 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
593 | - if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { |
|
594 | - throw new OCSException('', 104); |
|
595 | - } |
|
596 | - |
|
597 | - // Check they aren't removing themselves from 'admin' or their 'subadmin; group |
|
598 | - if ($targetUser->getUID() === $loggedInUser->getUID()) { |
|
599 | - if ($this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
600 | - if ($group->getGID() === 'admin') { |
|
601 | - throw new OCSException('Cannot remove yourself from the admin group', 105); |
|
602 | - } |
|
603 | - } else { |
|
604 | - // Not an admin, so the user must be a subadmin of this group, but that is not allowed. |
|
605 | - throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105); |
|
606 | - } |
|
607 | - |
|
608 | - } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
609 | - /** @var IGroup[] $subAdminGroups */ |
|
610 | - $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); |
|
611 | - $subAdminGroups = array_map(function (IGroup $subAdminGroup) { |
|
612 | - return $subAdminGroup->getGID(); |
|
613 | - }, $subAdminGroups); |
|
614 | - $userGroups = $this->groupManager->getUserGroupIds($targetUser); |
|
615 | - $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups); |
|
616 | - |
|
617 | - if (count($userSubAdminGroups) <= 1) { |
|
618 | - // Subadmin must not be able to remove a user from all their subadmin groups. |
|
619 | - throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105); |
|
620 | - } |
|
621 | - } |
|
622 | - |
|
623 | - // Remove user from group |
|
624 | - $group->removeUser($targetUser); |
|
625 | - return new DataResponse(); |
|
626 | - } |
|
627 | - |
|
628 | - /** |
|
629 | - * Creates a subadmin |
|
630 | - * |
|
631 | - * @PasswordConfirmationRequired |
|
632 | - * |
|
633 | - * @param string $userId |
|
634 | - * @param string $groupid |
|
635 | - * @return DataResponse |
|
636 | - * @throws OCSException |
|
637 | - */ |
|
638 | - public function addSubAdmin($userId, $groupid) { |
|
639 | - $group = $this->groupManager->get($groupid); |
|
640 | - $user = $this->userManager->get($userId); |
|
641 | - |
|
642 | - // Check if the user exists |
|
643 | - if($user === null) { |
|
644 | - throw new OCSException('User does not exist', 101); |
|
645 | - } |
|
646 | - // Check if group exists |
|
647 | - if($group === null) { |
|
648 | - throw new OCSException('Group does not exist', 102); |
|
649 | - } |
|
650 | - // Check if trying to make subadmin of admin group |
|
651 | - if($group->getGID() === 'admin') { |
|
652 | - throw new OCSException('Cannot create subadmins for admin group', 103); |
|
653 | - } |
|
654 | - |
|
655 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
656 | - |
|
657 | - // We cannot be subadmin twice |
|
658 | - if ($subAdminManager->isSubAdminofGroup($user, $group)) { |
|
659 | - return new DataResponse(); |
|
660 | - } |
|
661 | - // Go |
|
662 | - if($subAdminManager->createSubAdmin($user, $group)) { |
|
663 | - return new DataResponse(); |
|
664 | - } else { |
|
665 | - throw new OCSException('Unknown error occurred', 103); |
|
666 | - } |
|
667 | - } |
|
668 | - |
|
669 | - /** |
|
670 | - * Removes a subadmin from a group |
|
671 | - * |
|
672 | - * @PasswordConfirmationRequired |
|
673 | - * |
|
674 | - * @param string $userId |
|
675 | - * @param string $groupid |
|
676 | - * @return DataResponse |
|
677 | - * @throws OCSException |
|
678 | - */ |
|
679 | - public function removeSubAdmin($userId, $groupid) { |
|
680 | - $group = $this->groupManager->get($groupid); |
|
681 | - $user = $this->userManager->get($userId); |
|
682 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
683 | - |
|
684 | - // Check if the user exists |
|
685 | - if($user === null) { |
|
686 | - throw new OCSException('User does not exist', 101); |
|
687 | - } |
|
688 | - // Check if the group exists |
|
689 | - if($group === null) { |
|
690 | - throw new OCSException('Group does not exist', 101); |
|
691 | - } |
|
692 | - // Check if they are a subadmin of this said group |
|
693 | - if(!$subAdminManager->isSubAdminOfGroup($user, $group)) { |
|
694 | - throw new OCSException('User is not a subadmin of this group', 102); |
|
695 | - } |
|
696 | - |
|
697 | - // Go |
|
698 | - if($subAdminManager->deleteSubAdmin($user, $group)) { |
|
699 | - return new DataResponse(); |
|
700 | - } else { |
|
701 | - throw new OCSException('Unknown error occurred', 103); |
|
702 | - } |
|
703 | - } |
|
704 | - |
|
705 | - /** |
|
706 | - * Get the groups a user is a subadmin of |
|
707 | - * |
|
708 | - * @param string $userId |
|
709 | - * @return DataResponse |
|
710 | - * @throws OCSException |
|
711 | - */ |
|
712 | - public function getUserSubAdminGroups($userId) { |
|
713 | - $user = $this->userManager->get($userId); |
|
714 | - // Check if the user exists |
|
715 | - if($user === null) { |
|
716 | - throw new OCSException('User does not exist', 101); |
|
717 | - } |
|
718 | - |
|
719 | - // Get the subadmin groups |
|
720 | - $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user); |
|
721 | - foreach ($groups as $key => $group) { |
|
722 | - $groups[$key] = $group->getGID(); |
|
723 | - } |
|
724 | - |
|
725 | - if(!$groups) { |
|
726 | - throw new OCSException('Unknown error occurred', 102); |
|
727 | - } else { |
|
728 | - return new DataResponse($groups); |
|
729 | - } |
|
730 | - } |
|
731 | - |
|
732 | - /** |
|
733 | - * @param string $userId |
|
734 | - * @return array |
|
735 | - * @throws \OCP\Files\NotFoundException |
|
736 | - */ |
|
737 | - protected function fillStorageInfo($userId) { |
|
738 | - try { |
|
739 | - \OC_Util::tearDownFS(); |
|
740 | - \OC_Util::setupFS($userId); |
|
741 | - $storage = OC_Helper::getStorageInfo('/'); |
|
742 | - $data = [ |
|
743 | - 'free' => $storage['free'], |
|
744 | - 'used' => $storage['used'], |
|
745 | - 'total' => $storage['total'], |
|
746 | - 'relative' => $storage['relative'], |
|
747 | - 'quota' => $storage['quota'], |
|
748 | - ]; |
|
749 | - } catch (NotFoundException $ex) { |
|
750 | - $data = []; |
|
751 | - } |
|
752 | - return $data; |
|
753 | - } |
|
754 | - |
|
755 | - /** |
|
756 | - * @NoAdminRequired |
|
757 | - * @PasswordConfirmationRequired |
|
758 | - * |
|
759 | - * resend welcome message |
|
760 | - * |
|
761 | - * @param string $userId |
|
762 | - * @return DataResponse |
|
763 | - * @throws OCSException |
|
764 | - */ |
|
765 | - public function resendWelcomeMessage($userId) { |
|
766 | - $currentLoggedInUser = $this->userSession->getUser(); |
|
767 | - |
|
768 | - $targetUser = $this->userManager->get($userId); |
|
769 | - if($targetUser === null) { |
|
770 | - throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND); |
|
771 | - } |
|
772 | - |
|
773 | - // Check if admin / subadmin |
|
774 | - $subAdminManager = $this->groupManager->getSubAdmin(); |
|
775 | - if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
776 | - && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
777 | - // No rights |
|
778 | - throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
779 | - } |
|
780 | - |
|
781 | - $email = $targetUser->getEMailAddress(); |
|
782 | - if ($email === '' || $email === null) { |
|
783 | - throw new OCSException('Email address not available', 101); |
|
784 | - } |
|
785 | - $username = $targetUser->getUID(); |
|
786 | - $lang = $this->config->getUserValue($username, 'core', 'lang', 'en'); |
|
787 | - if (!$this->l10nFactory->languageExists('settings', $lang)) { |
|
788 | - $lang = 'en'; |
|
789 | - } |
|
790 | - |
|
791 | - $l10n = $this->l10nFactory->get('settings', $lang); |
|
792 | - |
|
793 | - try { |
|
794 | - $this->newUserMailHelper->setL10N($l10n); |
|
795 | - $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false); |
|
796 | - $this->newUserMailHelper->sendMail($targetUser, $emailTemplate); |
|
797 | - } catch(\Exception $e) { |
|
798 | - $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings')); |
|
799 | - throw new OCSException('Sending email failed', 102); |
|
800 | - } |
|
801 | - |
|
802 | - return new DataResponse(); |
|
803 | - } |
|
51 | + /** @var IUserManager */ |
|
52 | + private $userManager; |
|
53 | + /** @var IConfig */ |
|
54 | + private $config; |
|
55 | + /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface |
|
56 | + private $groupManager; |
|
57 | + /** @var IUserSession */ |
|
58 | + private $userSession; |
|
59 | + /** @var AccountManager */ |
|
60 | + private $accountManager; |
|
61 | + /** @var ILogger */ |
|
62 | + private $logger; |
|
63 | + /** @var IFactory */ |
|
64 | + private $l10nFactory; |
|
65 | + /** @var NewUserMailHelper */ |
|
66 | + private $newUserMailHelper; |
|
67 | + |
|
68 | + /** |
|
69 | + * @param string $appName |
|
70 | + * @param IRequest $request |
|
71 | + * @param IUserManager $userManager |
|
72 | + * @param IConfig $config |
|
73 | + * @param IGroupManager $groupManager |
|
74 | + * @param IUserSession $userSession |
|
75 | + * @param AccountManager $accountManager |
|
76 | + * @param ILogger $logger |
|
77 | + * @param IFactory $l10nFactory |
|
78 | + * @param NewUserMailHelper $newUserMailHelper |
|
79 | + */ |
|
80 | + public function __construct($appName, |
|
81 | + IRequest $request, |
|
82 | + IUserManager $userManager, |
|
83 | + IConfig $config, |
|
84 | + IGroupManager $groupManager, |
|
85 | + IUserSession $userSession, |
|
86 | + AccountManager $accountManager, |
|
87 | + ILogger $logger, |
|
88 | + IFactory $l10nFactory, |
|
89 | + NewUserMailHelper $newUserMailHelper) { |
|
90 | + parent::__construct($appName, $request); |
|
91 | + |
|
92 | + $this->userManager = $userManager; |
|
93 | + $this->config = $config; |
|
94 | + $this->groupManager = $groupManager; |
|
95 | + $this->userSession = $userSession; |
|
96 | + $this->accountManager = $accountManager; |
|
97 | + $this->logger = $logger; |
|
98 | + $this->l10nFactory = $l10nFactory; |
|
99 | + $this->newUserMailHelper = $newUserMailHelper; |
|
100 | + } |
|
101 | + |
|
102 | + /** |
|
103 | + * @NoAdminRequired |
|
104 | + * |
|
105 | + * returns a list of users |
|
106 | + * |
|
107 | + * @param string $search |
|
108 | + * @param int $limit |
|
109 | + * @param int $offset |
|
110 | + * @return DataResponse |
|
111 | + */ |
|
112 | + public function getUsers($search = '', $limit = null, $offset = null) { |
|
113 | + $user = $this->userSession->getUser(); |
|
114 | + $users = []; |
|
115 | + |
|
116 | + // Admin? Or SubAdmin? |
|
117 | + $uid = $user->getUID(); |
|
118 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
119 | + if($this->groupManager->isAdmin($uid)){ |
|
120 | + $users = $this->userManager->search($search, $limit, $offset); |
|
121 | + } else if ($subAdminManager->isSubAdmin($user)) { |
|
122 | + $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user); |
|
123 | + foreach ($subAdminOfGroups as $key => $group) { |
|
124 | + $subAdminOfGroups[$key] = $group->getGID(); |
|
125 | + } |
|
126 | + |
|
127 | + if($offset === null) { |
|
128 | + $offset = 0; |
|
129 | + } |
|
130 | + |
|
131 | + $users = []; |
|
132 | + foreach ($subAdminOfGroups as $group) { |
|
133 | + $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search)); |
|
134 | + } |
|
135 | + |
|
136 | + $users = array_slice($users, $offset, $limit); |
|
137 | + } |
|
138 | + |
|
139 | + $users = array_keys($users); |
|
140 | + |
|
141 | + return new DataResponse([ |
|
142 | + 'users' => $users |
|
143 | + ]); |
|
144 | + } |
|
145 | + |
|
146 | + /** |
|
147 | + * @PasswordConfirmationRequired |
|
148 | + * @NoAdminRequired |
|
149 | + * |
|
150 | + * @param string $userid |
|
151 | + * @param string $password |
|
152 | + * @param array $groups |
|
153 | + * @return DataResponse |
|
154 | + * @throws OCSException |
|
155 | + */ |
|
156 | + public function addUser($userid, $password, $groups = null) { |
|
157 | + $user = $this->userSession->getUser(); |
|
158 | + $isAdmin = $this->groupManager->isAdmin($user->getUID()); |
|
159 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
160 | + |
|
161 | + if($this->userManager->userExists($userid)) { |
|
162 | + $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); |
|
163 | + throw new OCSException('User already exists', 102); |
|
164 | + } |
|
165 | + |
|
166 | + if(is_array($groups)) { |
|
167 | + foreach ($groups as $group) { |
|
168 | + if(!$this->groupManager->groupExists($group)) { |
|
169 | + throw new OCSException('group '.$group.' does not exist', 104); |
|
170 | + } |
|
171 | + if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) { |
|
172 | + throw new OCSException('insufficient privileges for group '. $group, 105); |
|
173 | + } |
|
174 | + } |
|
175 | + } else { |
|
176 | + if(!$isAdmin) { |
|
177 | + throw new OCSException('no group specified (required for subadmins)', 106); |
|
178 | + } |
|
179 | + } |
|
180 | + |
|
181 | + try { |
|
182 | + $newUser = $this->userManager->createUser($userid, $password); |
|
183 | + $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']); |
|
184 | + |
|
185 | + if (is_array($groups)) { |
|
186 | + foreach ($groups as $group) { |
|
187 | + $this->groupManager->get($group)->addUser($newUser); |
|
188 | + $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']); |
|
189 | + } |
|
190 | + } |
|
191 | + return new DataResponse(); |
|
192 | + } catch (\Exception $e) { |
|
193 | + $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']); |
|
194 | + throw new OCSException('Bad request', 101); |
|
195 | + } |
|
196 | + } |
|
197 | + |
|
198 | + /** |
|
199 | + * @NoAdminRequired |
|
200 | + * @NoSubAdminRequired |
|
201 | + * |
|
202 | + * gets user info |
|
203 | + * |
|
204 | + * @param string $userId |
|
205 | + * @return DataResponse |
|
206 | + * @throws OCSException |
|
207 | + */ |
|
208 | + public function getUser($userId) { |
|
209 | + $data = $this->getUserData($userId); |
|
210 | + return new DataResponse($data); |
|
211 | + } |
|
212 | + |
|
213 | + /** |
|
214 | + * @NoAdminRequired |
|
215 | + * @NoSubAdminRequired |
|
216 | + * |
|
217 | + * gets user info from the currently logged in user |
|
218 | + * |
|
219 | + * @return DataResponse |
|
220 | + * @throws OCSException |
|
221 | + */ |
|
222 | + public function getCurrentUser() { |
|
223 | + $user = $this->userSession->getUser(); |
|
224 | + if ($user) { |
|
225 | + $data = $this->getUserData($user->getUID()); |
|
226 | + // rename "displayname" to "display-name" only for this call to keep |
|
227 | + // the API stable. |
|
228 | + $data['display-name'] = $data['displayname']; |
|
229 | + unset($data['displayname']); |
|
230 | + return new DataResponse($data); |
|
231 | + |
|
232 | + } |
|
233 | + |
|
234 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
235 | + } |
|
236 | + |
|
237 | + /** |
|
238 | + * creates a array with all user data |
|
239 | + * |
|
240 | + * @param $userId |
|
241 | + * @return array |
|
242 | + * @throws OCSException |
|
243 | + */ |
|
244 | + protected function getUserData($userId) { |
|
245 | + $currentLoggedInUser = $this->userSession->getUser(); |
|
246 | + |
|
247 | + $data = []; |
|
248 | + |
|
249 | + // Check if the target user exists |
|
250 | + $targetUserObject = $this->userManager->get($userId); |
|
251 | + if($targetUserObject === null) { |
|
252 | + throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND); |
|
253 | + } |
|
254 | + |
|
255 | + // Admin? Or SubAdmin? |
|
256 | + if($this->groupManager->isAdmin($currentLoggedInUser->getUID()) |
|
257 | + || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) { |
|
258 | + $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true'); |
|
259 | + } else { |
|
260 | + // Check they are looking up themselves |
|
261 | + if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) { |
|
262 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
263 | + } |
|
264 | + } |
|
265 | + |
|
266 | + $userAccount = $this->accountManager->getUser($targetUserObject); |
|
267 | + $groups = $this->groupManager->getUserGroups($targetUserObject); |
|
268 | + $gids = []; |
|
269 | + foreach ($groups as $group) { |
|
270 | + $gids[] = $group->getDisplayName(); |
|
271 | + } |
|
272 | + |
|
273 | + // Find the data |
|
274 | + $data['id'] = $targetUserObject->getUID(); |
|
275 | + $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID()); |
|
276 | + $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress(); |
|
277 | + $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName(); |
|
278 | + $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value']; |
|
279 | + $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value']; |
|
280 | + $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value']; |
|
281 | + $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value']; |
|
282 | + $data['groups'] = $gids; |
|
283 | + |
|
284 | + return $data; |
|
285 | + } |
|
286 | + |
|
287 | + /** |
|
288 | + * @NoAdminRequired |
|
289 | + * @NoSubAdminRequired |
|
290 | + * @PasswordConfirmationRequired |
|
291 | + * |
|
292 | + * edit users |
|
293 | + * |
|
294 | + * @param string $userId |
|
295 | + * @param string $key |
|
296 | + * @param string $value |
|
297 | + * @return DataResponse |
|
298 | + * @throws OCSException |
|
299 | + * @throws OCSForbiddenException |
|
300 | + */ |
|
301 | + public function editUser($userId, $key, $value) { |
|
302 | + $currentLoggedInUser = $this->userSession->getUser(); |
|
303 | + |
|
304 | + $targetUser = $this->userManager->get($userId); |
|
305 | + if($targetUser === null) { |
|
306 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
307 | + } |
|
308 | + |
|
309 | + $permittedFields = []; |
|
310 | + if($targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
311 | + // Editing self (display, email) |
|
312 | + $permittedFields[] = 'display'; |
|
313 | + $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME; |
|
314 | + $permittedFields[] = AccountManager::PROPERTY_EMAIL; |
|
315 | + $permittedFields[] = 'password'; |
|
316 | + $permittedFields[] = AccountManager::PROPERTY_PHONE; |
|
317 | + $permittedFields[] = AccountManager::PROPERTY_ADDRESS; |
|
318 | + $permittedFields[] = AccountManager::PROPERTY_WEBSITE; |
|
319 | + $permittedFields[] = AccountManager::PROPERTY_TWITTER; |
|
320 | + // If admin they can edit their own quota |
|
321 | + if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
322 | + $permittedFields[] = 'quota'; |
|
323 | + } |
|
324 | + } else { |
|
325 | + // Check if admin / subadmin |
|
326 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
327 | + if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
328 | + || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
329 | + // They have permissions over the user |
|
330 | + $permittedFields[] = 'display'; |
|
331 | + $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME; |
|
332 | + $permittedFields[] = AccountManager::PROPERTY_EMAIL; |
|
333 | + $permittedFields[] = 'password'; |
|
334 | + $permittedFields[] = AccountManager::PROPERTY_PHONE; |
|
335 | + $permittedFields[] = AccountManager::PROPERTY_ADDRESS; |
|
336 | + $permittedFields[] = AccountManager::PROPERTY_WEBSITE; |
|
337 | + $permittedFields[] = AccountManager::PROPERTY_TWITTER; |
|
338 | + $permittedFields[] = 'quota'; |
|
339 | + } else { |
|
340 | + // No rights |
|
341 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
342 | + } |
|
343 | + } |
|
344 | + // Check if permitted to edit this field |
|
345 | + if(!in_array($key, $permittedFields)) { |
|
346 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
347 | + } |
|
348 | + // Process the edit |
|
349 | + switch($key) { |
|
350 | + case 'display': |
|
351 | + case AccountManager::PROPERTY_DISPLAYNAME: |
|
352 | + $targetUser->setDisplayName($value); |
|
353 | + break; |
|
354 | + case 'quota': |
|
355 | + $quota = $value; |
|
356 | + if($quota !== 'none' && $quota !== 'default') { |
|
357 | + if (is_numeric($quota)) { |
|
358 | + $quota = (float) $quota; |
|
359 | + } else { |
|
360 | + $quota = \OCP\Util::computerFileSize($quota); |
|
361 | + } |
|
362 | + if ($quota === false) { |
|
363 | + throw new OCSException('Invalid quota value '.$value, 103); |
|
364 | + } |
|
365 | + if($quota === 0) { |
|
366 | + $quota = 'default'; |
|
367 | + }else if($quota === -1) { |
|
368 | + $quota = 'none'; |
|
369 | + } else { |
|
370 | + $quota = \OCP\Util::humanFileSize($quota); |
|
371 | + } |
|
372 | + } |
|
373 | + $targetUser->setQuota($quota); |
|
374 | + break; |
|
375 | + case 'password': |
|
376 | + $targetUser->setPassword($value); |
|
377 | + break; |
|
378 | + case AccountManager::PROPERTY_EMAIL: |
|
379 | + if(filter_var($value, FILTER_VALIDATE_EMAIL)) { |
|
380 | + $targetUser->setEMailAddress($value); |
|
381 | + } else { |
|
382 | + throw new OCSException('', 102); |
|
383 | + } |
|
384 | + break; |
|
385 | + case AccountManager::PROPERTY_PHONE: |
|
386 | + case AccountManager::PROPERTY_ADDRESS: |
|
387 | + case AccountManager::PROPERTY_WEBSITE: |
|
388 | + case AccountManager::PROPERTY_TWITTER: |
|
389 | + $userAccount = $this->accountManager->getUser($targetUser); |
|
390 | + if ($userAccount[$key]['value'] !== $value) { |
|
391 | + $userAccount[$key]['value'] = $value; |
|
392 | + $this->accountManager->updateUser($targetUser, $userAccount); |
|
393 | + } |
|
394 | + break; |
|
395 | + default: |
|
396 | + throw new OCSException('', 103); |
|
397 | + } |
|
398 | + return new DataResponse(); |
|
399 | + } |
|
400 | + |
|
401 | + /** |
|
402 | + * @PasswordConfirmationRequired |
|
403 | + * @NoAdminRequired |
|
404 | + * |
|
405 | + * @param string $userId |
|
406 | + * @return DataResponse |
|
407 | + * @throws OCSException |
|
408 | + * @throws OCSForbiddenException |
|
409 | + */ |
|
410 | + public function deleteUser($userId) { |
|
411 | + $currentLoggedInUser = $this->userSession->getUser(); |
|
412 | + |
|
413 | + $targetUser = $this->userManager->get($userId); |
|
414 | + |
|
415 | + if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
416 | + throw new OCSException('', 101); |
|
417 | + } |
|
418 | + |
|
419 | + // If not permitted |
|
420 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
421 | + if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
422 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
423 | + } |
|
424 | + |
|
425 | + // Go ahead with the delete |
|
426 | + if($targetUser->delete()) { |
|
427 | + return new DataResponse(); |
|
428 | + } else { |
|
429 | + throw new OCSException('', 101); |
|
430 | + } |
|
431 | + } |
|
432 | + |
|
433 | + /** |
|
434 | + * @PasswordConfirmationRequired |
|
435 | + * @NoAdminRequired |
|
436 | + * |
|
437 | + * @param string $userId |
|
438 | + * @return DataResponse |
|
439 | + * @throws OCSException |
|
440 | + * @throws OCSForbiddenException |
|
441 | + */ |
|
442 | + public function disableUser($userId) { |
|
443 | + return $this->setEnabled($userId, false); |
|
444 | + } |
|
445 | + |
|
446 | + /** |
|
447 | + * @PasswordConfirmationRequired |
|
448 | + * @NoAdminRequired |
|
449 | + * |
|
450 | + * @param string $userId |
|
451 | + * @return DataResponse |
|
452 | + * @throws OCSException |
|
453 | + * @throws OCSForbiddenException |
|
454 | + */ |
|
455 | + public function enableUser($userId) { |
|
456 | + return $this->setEnabled($userId, true); |
|
457 | + } |
|
458 | + |
|
459 | + /** |
|
460 | + * @param string $userId |
|
461 | + * @param bool $value |
|
462 | + * @return DataResponse |
|
463 | + * @throws OCSException |
|
464 | + * @throws OCSForbiddenException |
|
465 | + */ |
|
466 | + private function setEnabled($userId, $value) { |
|
467 | + $currentLoggedInUser = $this->userSession->getUser(); |
|
468 | + |
|
469 | + $targetUser = $this->userManager->get($userId); |
|
470 | + if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
471 | + throw new OCSException('', 101); |
|
472 | + } |
|
473 | + |
|
474 | + // If not permitted |
|
475 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
476 | + if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
477 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
478 | + } |
|
479 | + |
|
480 | + // enable/disable the user now |
|
481 | + $targetUser->setEnabled($value); |
|
482 | + return new DataResponse(); |
|
483 | + } |
|
484 | + |
|
485 | + /** |
|
486 | + * @NoAdminRequired |
|
487 | + * @NoSubAdminRequired |
|
488 | + * |
|
489 | + * @param string $userId |
|
490 | + * @return DataResponse |
|
491 | + * @throws OCSException |
|
492 | + */ |
|
493 | + public function getUsersGroups($userId) { |
|
494 | + $loggedInUser = $this->userSession->getUser(); |
|
495 | + |
|
496 | + $targetUser = $this->userManager->get($userId); |
|
497 | + if($targetUser === null) { |
|
498 | + throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND); |
|
499 | + } |
|
500 | + |
|
501 | + if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
502 | + // Self lookup or admin lookup |
|
503 | + return new DataResponse([ |
|
504 | + 'groups' => $this->groupManager->getUserGroupIds($targetUser) |
|
505 | + ]); |
|
506 | + } else { |
|
507 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
508 | + |
|
509 | + // Looking up someone else |
|
510 | + if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) { |
|
511 | + // Return the group that the method caller is subadmin of for the user in question |
|
512 | + /** @var IGroup[] $getSubAdminsGroups */ |
|
513 | + $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); |
|
514 | + foreach ($getSubAdminsGroups as $key => $group) { |
|
515 | + $getSubAdminsGroups[$key] = $group->getGID(); |
|
516 | + } |
|
517 | + $groups = array_intersect( |
|
518 | + $getSubAdminsGroups, |
|
519 | + $this->groupManager->getUserGroupIds($targetUser) |
|
520 | + ); |
|
521 | + return new DataResponse(['groups' => $groups]); |
|
522 | + } else { |
|
523 | + // Not permitted |
|
524 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
525 | + } |
|
526 | + } |
|
527 | + |
|
528 | + } |
|
529 | + |
|
530 | + /** |
|
531 | + * @PasswordConfirmationRequired |
|
532 | + * @NoAdminRequired |
|
533 | + * |
|
534 | + * @param string $userId |
|
535 | + * @param string $groupid |
|
536 | + * @return DataResponse |
|
537 | + * @throws OCSException |
|
538 | + */ |
|
539 | + public function addToGroup($userId, $groupid = '') { |
|
540 | + if($groupid === '') { |
|
541 | + throw new OCSException('', 101); |
|
542 | + } |
|
543 | + |
|
544 | + $group = $this->groupManager->get($groupid); |
|
545 | + $targetUser = $this->userManager->get($userId); |
|
546 | + if($group === null) { |
|
547 | + throw new OCSException('', 102); |
|
548 | + } |
|
549 | + if($targetUser === null) { |
|
550 | + throw new OCSException('', 103); |
|
551 | + } |
|
552 | + |
|
553 | + // If they're not an admin, check they are a subadmin of the group in question |
|
554 | + $loggedInUser = $this->userSession->getUser(); |
|
555 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
556 | + if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { |
|
557 | + throw new OCSException('', 104); |
|
558 | + } |
|
559 | + |
|
560 | + // Add user to group |
|
561 | + $group->addUser($targetUser); |
|
562 | + return new DataResponse(); |
|
563 | + } |
|
564 | + |
|
565 | + /** |
|
566 | + * @PasswordConfirmationRequired |
|
567 | + * @NoAdminRequired |
|
568 | + * |
|
569 | + * @param string $userId |
|
570 | + * @param string $groupid |
|
571 | + * @return DataResponse |
|
572 | + * @throws OCSException |
|
573 | + */ |
|
574 | + public function removeFromGroup($userId, $groupid) { |
|
575 | + $loggedInUser = $this->userSession->getUser(); |
|
576 | + |
|
577 | + if($groupid === null) { |
|
578 | + throw new OCSException('', 101); |
|
579 | + } |
|
580 | + |
|
581 | + $group = $this->groupManager->get($groupid); |
|
582 | + if($group === null) { |
|
583 | + throw new OCSException('', 102); |
|
584 | + } |
|
585 | + |
|
586 | + $targetUser = $this->userManager->get($userId); |
|
587 | + if($targetUser === null) { |
|
588 | + throw new OCSException('', 103); |
|
589 | + } |
|
590 | + |
|
591 | + // If they're not an admin, check they are a subadmin of the group in question |
|
592 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
593 | + if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { |
|
594 | + throw new OCSException('', 104); |
|
595 | + } |
|
596 | + |
|
597 | + // Check they aren't removing themselves from 'admin' or their 'subadmin; group |
|
598 | + if ($targetUser->getUID() === $loggedInUser->getUID()) { |
|
599 | + if ($this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
600 | + if ($group->getGID() === 'admin') { |
|
601 | + throw new OCSException('Cannot remove yourself from the admin group', 105); |
|
602 | + } |
|
603 | + } else { |
|
604 | + // Not an admin, so the user must be a subadmin of this group, but that is not allowed. |
|
605 | + throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105); |
|
606 | + } |
|
607 | + |
|
608 | + } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
609 | + /** @var IGroup[] $subAdminGroups */ |
|
610 | + $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); |
|
611 | + $subAdminGroups = array_map(function (IGroup $subAdminGroup) { |
|
612 | + return $subAdminGroup->getGID(); |
|
613 | + }, $subAdminGroups); |
|
614 | + $userGroups = $this->groupManager->getUserGroupIds($targetUser); |
|
615 | + $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups); |
|
616 | + |
|
617 | + if (count($userSubAdminGroups) <= 1) { |
|
618 | + // Subadmin must not be able to remove a user from all their subadmin groups. |
|
619 | + throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105); |
|
620 | + } |
|
621 | + } |
|
622 | + |
|
623 | + // Remove user from group |
|
624 | + $group->removeUser($targetUser); |
|
625 | + return new DataResponse(); |
|
626 | + } |
|
627 | + |
|
628 | + /** |
|
629 | + * Creates a subadmin |
|
630 | + * |
|
631 | + * @PasswordConfirmationRequired |
|
632 | + * |
|
633 | + * @param string $userId |
|
634 | + * @param string $groupid |
|
635 | + * @return DataResponse |
|
636 | + * @throws OCSException |
|
637 | + */ |
|
638 | + public function addSubAdmin($userId, $groupid) { |
|
639 | + $group = $this->groupManager->get($groupid); |
|
640 | + $user = $this->userManager->get($userId); |
|
641 | + |
|
642 | + // Check if the user exists |
|
643 | + if($user === null) { |
|
644 | + throw new OCSException('User does not exist', 101); |
|
645 | + } |
|
646 | + // Check if group exists |
|
647 | + if($group === null) { |
|
648 | + throw new OCSException('Group does not exist', 102); |
|
649 | + } |
|
650 | + // Check if trying to make subadmin of admin group |
|
651 | + if($group->getGID() === 'admin') { |
|
652 | + throw new OCSException('Cannot create subadmins for admin group', 103); |
|
653 | + } |
|
654 | + |
|
655 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
656 | + |
|
657 | + // We cannot be subadmin twice |
|
658 | + if ($subAdminManager->isSubAdminofGroup($user, $group)) { |
|
659 | + return new DataResponse(); |
|
660 | + } |
|
661 | + // Go |
|
662 | + if($subAdminManager->createSubAdmin($user, $group)) { |
|
663 | + return new DataResponse(); |
|
664 | + } else { |
|
665 | + throw new OCSException('Unknown error occurred', 103); |
|
666 | + } |
|
667 | + } |
|
668 | + |
|
669 | + /** |
|
670 | + * Removes a subadmin from a group |
|
671 | + * |
|
672 | + * @PasswordConfirmationRequired |
|
673 | + * |
|
674 | + * @param string $userId |
|
675 | + * @param string $groupid |
|
676 | + * @return DataResponse |
|
677 | + * @throws OCSException |
|
678 | + */ |
|
679 | + public function removeSubAdmin($userId, $groupid) { |
|
680 | + $group = $this->groupManager->get($groupid); |
|
681 | + $user = $this->userManager->get($userId); |
|
682 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
683 | + |
|
684 | + // Check if the user exists |
|
685 | + if($user === null) { |
|
686 | + throw new OCSException('User does not exist', 101); |
|
687 | + } |
|
688 | + // Check if the group exists |
|
689 | + if($group === null) { |
|
690 | + throw new OCSException('Group does not exist', 101); |
|
691 | + } |
|
692 | + // Check if they are a subadmin of this said group |
|
693 | + if(!$subAdminManager->isSubAdminOfGroup($user, $group)) { |
|
694 | + throw new OCSException('User is not a subadmin of this group', 102); |
|
695 | + } |
|
696 | + |
|
697 | + // Go |
|
698 | + if($subAdminManager->deleteSubAdmin($user, $group)) { |
|
699 | + return new DataResponse(); |
|
700 | + } else { |
|
701 | + throw new OCSException('Unknown error occurred', 103); |
|
702 | + } |
|
703 | + } |
|
704 | + |
|
705 | + /** |
|
706 | + * Get the groups a user is a subadmin of |
|
707 | + * |
|
708 | + * @param string $userId |
|
709 | + * @return DataResponse |
|
710 | + * @throws OCSException |
|
711 | + */ |
|
712 | + public function getUserSubAdminGroups($userId) { |
|
713 | + $user = $this->userManager->get($userId); |
|
714 | + // Check if the user exists |
|
715 | + if($user === null) { |
|
716 | + throw new OCSException('User does not exist', 101); |
|
717 | + } |
|
718 | + |
|
719 | + // Get the subadmin groups |
|
720 | + $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user); |
|
721 | + foreach ($groups as $key => $group) { |
|
722 | + $groups[$key] = $group->getGID(); |
|
723 | + } |
|
724 | + |
|
725 | + if(!$groups) { |
|
726 | + throw new OCSException('Unknown error occurred', 102); |
|
727 | + } else { |
|
728 | + return new DataResponse($groups); |
|
729 | + } |
|
730 | + } |
|
731 | + |
|
732 | + /** |
|
733 | + * @param string $userId |
|
734 | + * @return array |
|
735 | + * @throws \OCP\Files\NotFoundException |
|
736 | + */ |
|
737 | + protected function fillStorageInfo($userId) { |
|
738 | + try { |
|
739 | + \OC_Util::tearDownFS(); |
|
740 | + \OC_Util::setupFS($userId); |
|
741 | + $storage = OC_Helper::getStorageInfo('/'); |
|
742 | + $data = [ |
|
743 | + 'free' => $storage['free'], |
|
744 | + 'used' => $storage['used'], |
|
745 | + 'total' => $storage['total'], |
|
746 | + 'relative' => $storage['relative'], |
|
747 | + 'quota' => $storage['quota'], |
|
748 | + ]; |
|
749 | + } catch (NotFoundException $ex) { |
|
750 | + $data = []; |
|
751 | + } |
|
752 | + return $data; |
|
753 | + } |
|
754 | + |
|
755 | + /** |
|
756 | + * @NoAdminRequired |
|
757 | + * @PasswordConfirmationRequired |
|
758 | + * |
|
759 | + * resend welcome message |
|
760 | + * |
|
761 | + * @param string $userId |
|
762 | + * @return DataResponse |
|
763 | + * @throws OCSException |
|
764 | + */ |
|
765 | + public function resendWelcomeMessage($userId) { |
|
766 | + $currentLoggedInUser = $this->userSession->getUser(); |
|
767 | + |
|
768 | + $targetUser = $this->userManager->get($userId); |
|
769 | + if($targetUser === null) { |
|
770 | + throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND); |
|
771 | + } |
|
772 | + |
|
773 | + // Check if admin / subadmin |
|
774 | + $subAdminManager = $this->groupManager->getSubAdmin(); |
|
775 | + if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
776 | + && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
777 | + // No rights |
|
778 | + throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
|
779 | + } |
|
780 | + |
|
781 | + $email = $targetUser->getEMailAddress(); |
|
782 | + if ($email === '' || $email === null) { |
|
783 | + throw new OCSException('Email address not available', 101); |
|
784 | + } |
|
785 | + $username = $targetUser->getUID(); |
|
786 | + $lang = $this->config->getUserValue($username, 'core', 'lang', 'en'); |
|
787 | + if (!$this->l10nFactory->languageExists('settings', $lang)) { |
|
788 | + $lang = 'en'; |
|
789 | + } |
|
790 | + |
|
791 | + $l10n = $this->l10nFactory->get('settings', $lang); |
|
792 | + |
|
793 | + try { |
|
794 | + $this->newUserMailHelper->setL10N($l10n); |
|
795 | + $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false); |
|
796 | + $this->newUserMailHelper->sendMail($targetUser, $emailTemplate); |
|
797 | + } catch(\Exception $e) { |
|
798 | + $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings')); |
|
799 | + throw new OCSException('Sending email failed', 102); |
|
800 | + } |
|
801 | + |
|
802 | + return new DataResponse(); |
|
803 | + } |
|
804 | 804 | } |
@@ -116,7 +116,7 @@ discard block |
||
116 | 116 | // Admin? Or SubAdmin? |
117 | 117 | $uid = $user->getUID(); |
118 | 118 | $subAdminManager = $this->groupManager->getSubAdmin(); |
119 | - if($this->groupManager->isAdmin($uid)){ |
|
119 | + if ($this->groupManager->isAdmin($uid)) { |
|
120 | 120 | $users = $this->userManager->search($search, $limit, $offset); |
121 | 121 | } else if ($subAdminManager->isSubAdmin($user)) { |
122 | 122 | $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user); |
@@ -124,7 +124,7 @@ discard block |
||
124 | 124 | $subAdminOfGroups[$key] = $group->getGID(); |
125 | 125 | } |
126 | 126 | |
127 | - if($offset === null) { |
|
127 | + if ($offset === null) { |
|
128 | 128 | $offset = 0; |
129 | 129 | } |
130 | 130 | |
@@ -158,22 +158,22 @@ discard block |
||
158 | 158 | $isAdmin = $this->groupManager->isAdmin($user->getUID()); |
159 | 159 | $subAdminManager = $this->groupManager->getSubAdmin(); |
160 | 160 | |
161 | - if($this->userManager->userExists($userid)) { |
|
161 | + if ($this->userManager->userExists($userid)) { |
|
162 | 162 | $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); |
163 | 163 | throw new OCSException('User already exists', 102); |
164 | 164 | } |
165 | 165 | |
166 | - if(is_array($groups)) { |
|
166 | + if (is_array($groups)) { |
|
167 | 167 | foreach ($groups as $group) { |
168 | - if(!$this->groupManager->groupExists($group)) { |
|
168 | + if (!$this->groupManager->groupExists($group)) { |
|
169 | 169 | throw new OCSException('group '.$group.' does not exist', 104); |
170 | 170 | } |
171 | - if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) { |
|
172 | - throw new OCSException('insufficient privileges for group '. $group, 105); |
|
171 | + if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) { |
|
172 | + throw new OCSException('insufficient privileges for group '.$group, 105); |
|
173 | 173 | } |
174 | 174 | } |
175 | 175 | } else { |
176 | - if(!$isAdmin) { |
|
176 | + if (!$isAdmin) { |
|
177 | 177 | throw new OCSException('no group specified (required for subadmins)', 106); |
178 | 178 | } |
179 | 179 | } |
@@ -222,7 +222,7 @@ discard block |
||
222 | 222 | public function getCurrentUser() { |
223 | 223 | $user = $this->userSession->getUser(); |
224 | 224 | if ($user) { |
225 | - $data = $this->getUserData($user->getUID()); |
|
225 | + $data = $this->getUserData($user->getUID()); |
|
226 | 226 | // rename "displayname" to "display-name" only for this call to keep |
227 | 227 | // the API stable. |
228 | 228 | $data['display-name'] = $data['displayname']; |
@@ -248,17 +248,17 @@ discard block |
||
248 | 248 | |
249 | 249 | // Check if the target user exists |
250 | 250 | $targetUserObject = $this->userManager->get($userId); |
251 | - if($targetUserObject === null) { |
|
251 | + if ($targetUserObject === null) { |
|
252 | 252 | throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND); |
253 | 253 | } |
254 | 254 | |
255 | 255 | // Admin? Or SubAdmin? |
256 | - if($this->groupManager->isAdmin($currentLoggedInUser->getUID()) |
|
256 | + if ($this->groupManager->isAdmin($currentLoggedInUser->getUID()) |
|
257 | 257 | || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) { |
258 | 258 | $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true'); |
259 | 259 | } else { |
260 | 260 | // Check they are looking up themselves |
261 | - if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) { |
|
261 | + if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) { |
|
262 | 262 | throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
263 | 263 | } |
264 | 264 | } |
@@ -302,12 +302,12 @@ discard block |
||
302 | 302 | $currentLoggedInUser = $this->userSession->getUser(); |
303 | 303 | |
304 | 304 | $targetUser = $this->userManager->get($userId); |
305 | - if($targetUser === null) { |
|
305 | + if ($targetUser === null) { |
|
306 | 306 | throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
307 | 307 | } |
308 | 308 | |
309 | 309 | $permittedFields = []; |
310 | - if($targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
310 | + if ($targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
311 | 311 | // Editing self (display, email) |
312 | 312 | $permittedFields[] = 'display'; |
313 | 313 | $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME; |
@@ -318,13 +318,13 @@ discard block |
||
318 | 318 | $permittedFields[] = AccountManager::PROPERTY_WEBSITE; |
319 | 319 | $permittedFields[] = AccountManager::PROPERTY_TWITTER; |
320 | 320 | // If admin they can edit their own quota |
321 | - if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
321 | + if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
|
322 | 322 | $permittedFields[] = 'quota'; |
323 | 323 | } |
324 | 324 | } else { |
325 | 325 | // Check if admin / subadmin |
326 | 326 | $subAdminManager = $this->groupManager->getSubAdmin(); |
327 | - if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
327 | + if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
328 | 328 | || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
329 | 329 | // They have permissions over the user |
330 | 330 | $permittedFields[] = 'display'; |
@@ -342,18 +342,18 @@ discard block |
||
342 | 342 | } |
343 | 343 | } |
344 | 344 | // Check if permitted to edit this field |
345 | - if(!in_array($key, $permittedFields)) { |
|
345 | + if (!in_array($key, $permittedFields)) { |
|
346 | 346 | throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
347 | 347 | } |
348 | 348 | // Process the edit |
349 | - switch($key) { |
|
349 | + switch ($key) { |
|
350 | 350 | case 'display': |
351 | 351 | case AccountManager::PROPERTY_DISPLAYNAME: |
352 | 352 | $targetUser->setDisplayName($value); |
353 | 353 | break; |
354 | 354 | case 'quota': |
355 | 355 | $quota = $value; |
356 | - if($quota !== 'none' && $quota !== 'default') { |
|
356 | + if ($quota !== 'none' && $quota !== 'default') { |
|
357 | 357 | if (is_numeric($quota)) { |
358 | 358 | $quota = (float) $quota; |
359 | 359 | } else { |
@@ -362,9 +362,9 @@ discard block |
||
362 | 362 | if ($quota === false) { |
363 | 363 | throw new OCSException('Invalid quota value '.$value, 103); |
364 | 364 | } |
365 | - if($quota === 0) { |
|
365 | + if ($quota === 0) { |
|
366 | 366 | $quota = 'default'; |
367 | - }else if($quota === -1) { |
|
367 | + } else if ($quota === -1) { |
|
368 | 368 | $quota = 'none'; |
369 | 369 | } else { |
370 | 370 | $quota = \OCP\Util::humanFileSize($quota); |
@@ -376,7 +376,7 @@ discard block |
||
376 | 376 | $targetUser->setPassword($value); |
377 | 377 | break; |
378 | 378 | case AccountManager::PROPERTY_EMAIL: |
379 | - if(filter_var($value, FILTER_VALIDATE_EMAIL)) { |
|
379 | + if (filter_var($value, FILTER_VALIDATE_EMAIL)) { |
|
380 | 380 | $targetUser->setEMailAddress($value); |
381 | 381 | } else { |
382 | 382 | throw new OCSException('', 102); |
@@ -412,18 +412,18 @@ discard block |
||
412 | 412 | |
413 | 413 | $targetUser = $this->userManager->get($userId); |
414 | 414 | |
415 | - if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
415 | + if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
416 | 416 | throw new OCSException('', 101); |
417 | 417 | } |
418 | 418 | |
419 | 419 | // If not permitted |
420 | 420 | $subAdminManager = $this->groupManager->getSubAdmin(); |
421 | - if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
421 | + if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
422 | 422 | throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
423 | 423 | } |
424 | 424 | |
425 | 425 | // Go ahead with the delete |
426 | - if($targetUser->delete()) { |
|
426 | + if ($targetUser->delete()) { |
|
427 | 427 | return new DataResponse(); |
428 | 428 | } else { |
429 | 429 | throw new OCSException('', 101); |
@@ -467,13 +467,13 @@ discard block |
||
467 | 467 | $currentLoggedInUser = $this->userSession->getUser(); |
468 | 468 | |
469 | 469 | $targetUser = $this->userManager->get($userId); |
470 | - if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
470 | + if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) { |
|
471 | 471 | throw new OCSException('', 101); |
472 | 472 | } |
473 | 473 | |
474 | 474 | // If not permitted |
475 | 475 | $subAdminManager = $this->groupManager->getSubAdmin(); |
476 | - if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
476 | + if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { |
|
477 | 477 | throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
478 | 478 | } |
479 | 479 | |
@@ -494,11 +494,11 @@ discard block |
||
494 | 494 | $loggedInUser = $this->userSession->getUser(); |
495 | 495 | |
496 | 496 | $targetUser = $this->userManager->get($userId); |
497 | - if($targetUser === null) { |
|
497 | + if ($targetUser === null) { |
|
498 | 498 | throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND); |
499 | 499 | } |
500 | 500 | |
501 | - if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
501 | + if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) { |
|
502 | 502 | // Self lookup or admin lookup |
503 | 503 | return new DataResponse([ |
504 | 504 | 'groups' => $this->groupManager->getUserGroupIds($targetUser) |
@@ -507,7 +507,7 @@ discard block |
||
507 | 507 | $subAdminManager = $this->groupManager->getSubAdmin(); |
508 | 508 | |
509 | 509 | // Looking up someone else |
510 | - if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) { |
|
510 | + if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) { |
|
511 | 511 | // Return the group that the method caller is subadmin of for the user in question |
512 | 512 | /** @var IGroup[] $getSubAdminsGroups */ |
513 | 513 | $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); |
@@ -537,16 +537,16 @@ discard block |
||
537 | 537 | * @throws OCSException |
538 | 538 | */ |
539 | 539 | public function addToGroup($userId, $groupid = '') { |
540 | - if($groupid === '') { |
|
540 | + if ($groupid === '') { |
|
541 | 541 | throw new OCSException('', 101); |
542 | 542 | } |
543 | 543 | |
544 | 544 | $group = $this->groupManager->get($groupid); |
545 | 545 | $targetUser = $this->userManager->get($userId); |
546 | - if($group === null) { |
|
546 | + if ($group === null) { |
|
547 | 547 | throw new OCSException('', 102); |
548 | 548 | } |
549 | - if($targetUser === null) { |
|
549 | + if ($targetUser === null) { |
|
550 | 550 | throw new OCSException('', 103); |
551 | 551 | } |
552 | 552 | |
@@ -574,17 +574,17 @@ discard block |
||
574 | 574 | public function removeFromGroup($userId, $groupid) { |
575 | 575 | $loggedInUser = $this->userSession->getUser(); |
576 | 576 | |
577 | - if($groupid === null) { |
|
577 | + if ($groupid === null) { |
|
578 | 578 | throw new OCSException('', 101); |
579 | 579 | } |
580 | 580 | |
581 | 581 | $group = $this->groupManager->get($groupid); |
582 | - if($group === null) { |
|
582 | + if ($group === null) { |
|
583 | 583 | throw new OCSException('', 102); |
584 | 584 | } |
585 | 585 | |
586 | 586 | $targetUser = $this->userManager->get($userId); |
587 | - if($targetUser === null) { |
|
587 | + if ($targetUser === null) { |
|
588 | 588 | throw new OCSException('', 103); |
589 | 589 | } |
590 | 590 | |
@@ -608,7 +608,7 @@ discard block |
||
608 | 608 | } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) { |
609 | 609 | /** @var IGroup[] $subAdminGroups */ |
610 | 610 | $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); |
611 | - $subAdminGroups = array_map(function (IGroup $subAdminGroup) { |
|
611 | + $subAdminGroups = array_map(function(IGroup $subAdminGroup) { |
|
612 | 612 | return $subAdminGroup->getGID(); |
613 | 613 | }, $subAdminGroups); |
614 | 614 | $userGroups = $this->groupManager->getUserGroupIds($targetUser); |
@@ -640,15 +640,15 @@ discard block |
||
640 | 640 | $user = $this->userManager->get($userId); |
641 | 641 | |
642 | 642 | // Check if the user exists |
643 | - if($user === null) { |
|
643 | + if ($user === null) { |
|
644 | 644 | throw new OCSException('User does not exist', 101); |
645 | 645 | } |
646 | 646 | // Check if group exists |
647 | - if($group === null) { |
|
648 | - throw new OCSException('Group does not exist', 102); |
|
647 | + if ($group === null) { |
|
648 | + throw new OCSException('Group does not exist', 102); |
|
649 | 649 | } |
650 | 650 | // Check if trying to make subadmin of admin group |
651 | - if($group->getGID() === 'admin') { |
|
651 | + if ($group->getGID() === 'admin') { |
|
652 | 652 | throw new OCSException('Cannot create subadmins for admin group', 103); |
653 | 653 | } |
654 | 654 | |
@@ -659,7 +659,7 @@ discard block |
||
659 | 659 | return new DataResponse(); |
660 | 660 | } |
661 | 661 | // Go |
662 | - if($subAdminManager->createSubAdmin($user, $group)) { |
|
662 | + if ($subAdminManager->createSubAdmin($user, $group)) { |
|
663 | 663 | return new DataResponse(); |
664 | 664 | } else { |
665 | 665 | throw new OCSException('Unknown error occurred', 103); |
@@ -682,20 +682,20 @@ discard block |
||
682 | 682 | $subAdminManager = $this->groupManager->getSubAdmin(); |
683 | 683 | |
684 | 684 | // Check if the user exists |
685 | - if($user === null) { |
|
685 | + if ($user === null) { |
|
686 | 686 | throw new OCSException('User does not exist', 101); |
687 | 687 | } |
688 | 688 | // Check if the group exists |
689 | - if($group === null) { |
|
689 | + if ($group === null) { |
|
690 | 690 | throw new OCSException('Group does not exist', 101); |
691 | 691 | } |
692 | 692 | // Check if they are a subadmin of this said group |
693 | - if(!$subAdminManager->isSubAdminOfGroup($user, $group)) { |
|
693 | + if (!$subAdminManager->isSubAdminOfGroup($user, $group)) { |
|
694 | 694 | throw new OCSException('User is not a subadmin of this group', 102); |
695 | 695 | } |
696 | 696 | |
697 | 697 | // Go |
698 | - if($subAdminManager->deleteSubAdmin($user, $group)) { |
|
698 | + if ($subAdminManager->deleteSubAdmin($user, $group)) { |
|
699 | 699 | return new DataResponse(); |
700 | 700 | } else { |
701 | 701 | throw new OCSException('Unknown error occurred', 103); |
@@ -712,7 +712,7 @@ discard block |
||
712 | 712 | public function getUserSubAdminGroups($userId) { |
713 | 713 | $user = $this->userManager->get($userId); |
714 | 714 | // Check if the user exists |
715 | - if($user === null) { |
|
715 | + if ($user === null) { |
|
716 | 716 | throw new OCSException('User does not exist', 101); |
717 | 717 | } |
718 | 718 | |
@@ -722,7 +722,7 @@ discard block |
||
722 | 722 | $groups[$key] = $group->getGID(); |
723 | 723 | } |
724 | 724 | |
725 | - if(!$groups) { |
|
725 | + if (!$groups) { |
|
726 | 726 | throw new OCSException('Unknown error occurred', 102); |
727 | 727 | } else { |
728 | 728 | return new DataResponse($groups); |
@@ -766,13 +766,13 @@ discard block |
||
766 | 766 | $currentLoggedInUser = $this->userSession->getUser(); |
767 | 767 | |
768 | 768 | $targetUser = $this->userManager->get($userId); |
769 | - if($targetUser === null) { |
|
769 | + if ($targetUser === null) { |
|
770 | 770 | throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND); |
771 | 771 | } |
772 | 772 | |
773 | 773 | // Check if admin / subadmin |
774 | 774 | $subAdminManager = $this->groupManager->getSubAdmin(); |
775 | - if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
775 | + if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) |
|
776 | 776 | && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) { |
777 | 777 | // No rights |
778 | 778 | throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED); |
@@ -794,8 +794,8 @@ discard block |
||
794 | 794 | $this->newUserMailHelper->setL10N($l10n); |
795 | 795 | $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false); |
796 | 796 | $this->newUserMailHelper->sendMail($targetUser, $emailTemplate); |
797 | - } catch(\Exception $e) { |
|
798 | - $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings')); |
|
797 | + } catch (\Exception $e) { |
|
798 | + $this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings')); |
|
799 | 799 | throw new OCSException('Sending email failed', 102); |
800 | 800 | } |
801 | 801 |
@@ -124,6 +124,9 @@ |
||
124 | 124 | return $nextPrefix; |
125 | 125 | } |
126 | 126 | |
127 | + /** |
|
128 | + * @param string $value |
|
129 | + */ |
|
127 | 130 | private function getServersConfig($value) { |
128 | 131 | $regex = '/' . $value . '$/S'; |
129 | 132 |
@@ -34,126 +34,126 @@ discard block |
||
34 | 34 | |
35 | 35 | class Helper { |
36 | 36 | |
37 | - /** @var IConfig */ |
|
38 | - private $config; |
|
39 | - |
|
40 | - /** |
|
41 | - * Helper constructor. |
|
42 | - * |
|
43 | - * @param IConfig $config |
|
44 | - */ |
|
45 | - public function __construct(IConfig $config) { |
|
46 | - $this->config = $config; |
|
47 | - } |
|
48 | - |
|
49 | - /** |
|
50 | - * returns prefixes for each saved LDAP/AD server configuration. |
|
51 | - * @param bool $activeConfigurations optional, whether only active configuration shall be |
|
52 | - * retrieved, defaults to false |
|
53 | - * @return array with a list of the available prefixes |
|
54 | - * |
|
55 | - * Configuration prefixes are used to set up configurations for n LDAP or |
|
56 | - * AD servers. Since configuration is stored in the database, table |
|
57 | - * appconfig under appid user_ldap, the common identifiers in column |
|
58 | - * 'configkey' have a prefix. The prefix for the very first server |
|
59 | - * configuration is empty. |
|
60 | - * Configkey Examples: |
|
61 | - * Server 1: ldap_login_filter |
|
62 | - * Server 2: s1_ldap_login_filter |
|
63 | - * Server 3: s2_ldap_login_filter |
|
64 | - * |
|
65 | - * The prefix needs to be passed to the constructor of Connection class, |
|
66 | - * except the default (first) server shall be connected to. |
|
67 | - * |
|
68 | - */ |
|
69 | - public function getServerConfigurationPrefixes($activeConfigurations = false) { |
|
70 | - $referenceConfigkey = 'ldap_configuration_active'; |
|
71 | - |
|
72 | - $keys = $this->getServersConfig($referenceConfigkey); |
|
73 | - |
|
74 | - $prefixes = []; |
|
75 | - foreach ($keys as $key) { |
|
76 | - if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') { |
|
77 | - continue; |
|
78 | - } |
|
79 | - |
|
80 | - $len = strlen($key) - strlen($referenceConfigkey); |
|
81 | - $prefixes[] = substr($key, 0, $len); |
|
82 | - } |
|
83 | - |
|
84 | - return $prefixes; |
|
85 | - } |
|
86 | - |
|
87 | - /** |
|
88 | - * |
|
89 | - * determines the host for every configured connection |
|
90 | - * @return array an array with configprefix as keys |
|
91 | - * |
|
92 | - */ |
|
93 | - public function getServerConfigurationHosts() { |
|
94 | - $referenceConfigkey = 'ldap_host'; |
|
95 | - |
|
96 | - $keys = $this->getServersConfig($referenceConfigkey); |
|
97 | - |
|
98 | - $result = array(); |
|
99 | - foreach($keys as $key) { |
|
100 | - $len = strlen($key) - strlen($referenceConfigkey); |
|
101 | - $prefix = substr($key, 0, $len); |
|
102 | - $result[$prefix] = $this->config->getAppValue('user_ldap', $key); |
|
103 | - } |
|
104 | - |
|
105 | - return $result; |
|
106 | - } |
|
107 | - |
|
108 | - /** |
|
109 | - * return the next available configuration prefix |
|
110 | - * |
|
111 | - * @return string |
|
112 | - */ |
|
113 | - public function getNextServerConfigurationPrefix() { |
|
114 | - $serverConnections = $this->getServerConfigurationPrefixes(); |
|
115 | - |
|
116 | - if(count($serverConnections) === 0) { |
|
117 | - return 's01'; |
|
118 | - } |
|
119 | - |
|
120 | - sort($serverConnections); |
|
121 | - $lastKey = array_pop($serverConnections); |
|
122 | - $lastNumber = intval(str_replace('s', '', $lastKey)); |
|
123 | - $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT); |
|
124 | - return $nextPrefix; |
|
125 | - } |
|
126 | - |
|
127 | - private function getServersConfig($value) { |
|
128 | - $regex = '/' . $value . '$/S'; |
|
129 | - |
|
130 | - $keys = $this->config->getAppKeys('user_ldap'); |
|
131 | - $result = []; |
|
132 | - foreach ($keys as $key) { |
|
133 | - if (preg_match($regex, $key) === 1) { |
|
134 | - $result[] = $key; |
|
135 | - } |
|
136 | - } |
|
137 | - |
|
138 | - return $result; |
|
139 | - } |
|
140 | - |
|
141 | - /** |
|
142 | - * deletes a given saved LDAP/AD server configuration. |
|
143 | - * @param string $prefix the configuration prefix of the config to delete |
|
144 | - * @return bool true on success, false otherwise |
|
145 | - */ |
|
146 | - public function deleteServerConfiguration($prefix) { |
|
147 | - if(!in_array($prefix, self::getServerConfigurationPrefixes())) { |
|
148 | - return false; |
|
149 | - } |
|
150 | - |
|
151 | - $saveOtherConfigurations = ''; |
|
152 | - if(empty($prefix)) { |
|
153 | - $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; |
|
154 | - } |
|
155 | - |
|
156 | - $query = \OCP\DB::prepare(' |
|
37 | + /** @var IConfig */ |
|
38 | + private $config; |
|
39 | + |
|
40 | + /** |
|
41 | + * Helper constructor. |
|
42 | + * |
|
43 | + * @param IConfig $config |
|
44 | + */ |
|
45 | + public function __construct(IConfig $config) { |
|
46 | + $this->config = $config; |
|
47 | + } |
|
48 | + |
|
49 | + /** |
|
50 | + * returns prefixes for each saved LDAP/AD server configuration. |
|
51 | + * @param bool $activeConfigurations optional, whether only active configuration shall be |
|
52 | + * retrieved, defaults to false |
|
53 | + * @return array with a list of the available prefixes |
|
54 | + * |
|
55 | + * Configuration prefixes are used to set up configurations for n LDAP or |
|
56 | + * AD servers. Since configuration is stored in the database, table |
|
57 | + * appconfig under appid user_ldap, the common identifiers in column |
|
58 | + * 'configkey' have a prefix. The prefix for the very first server |
|
59 | + * configuration is empty. |
|
60 | + * Configkey Examples: |
|
61 | + * Server 1: ldap_login_filter |
|
62 | + * Server 2: s1_ldap_login_filter |
|
63 | + * Server 3: s2_ldap_login_filter |
|
64 | + * |
|
65 | + * The prefix needs to be passed to the constructor of Connection class, |
|
66 | + * except the default (first) server shall be connected to. |
|
67 | + * |
|
68 | + */ |
|
69 | + public function getServerConfigurationPrefixes($activeConfigurations = false) { |
|
70 | + $referenceConfigkey = 'ldap_configuration_active'; |
|
71 | + |
|
72 | + $keys = $this->getServersConfig($referenceConfigkey); |
|
73 | + |
|
74 | + $prefixes = []; |
|
75 | + foreach ($keys as $key) { |
|
76 | + if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') { |
|
77 | + continue; |
|
78 | + } |
|
79 | + |
|
80 | + $len = strlen($key) - strlen($referenceConfigkey); |
|
81 | + $prefixes[] = substr($key, 0, $len); |
|
82 | + } |
|
83 | + |
|
84 | + return $prefixes; |
|
85 | + } |
|
86 | + |
|
87 | + /** |
|
88 | + * |
|
89 | + * determines the host for every configured connection |
|
90 | + * @return array an array with configprefix as keys |
|
91 | + * |
|
92 | + */ |
|
93 | + public function getServerConfigurationHosts() { |
|
94 | + $referenceConfigkey = 'ldap_host'; |
|
95 | + |
|
96 | + $keys = $this->getServersConfig($referenceConfigkey); |
|
97 | + |
|
98 | + $result = array(); |
|
99 | + foreach($keys as $key) { |
|
100 | + $len = strlen($key) - strlen($referenceConfigkey); |
|
101 | + $prefix = substr($key, 0, $len); |
|
102 | + $result[$prefix] = $this->config->getAppValue('user_ldap', $key); |
|
103 | + } |
|
104 | + |
|
105 | + return $result; |
|
106 | + } |
|
107 | + |
|
108 | + /** |
|
109 | + * return the next available configuration prefix |
|
110 | + * |
|
111 | + * @return string |
|
112 | + */ |
|
113 | + public function getNextServerConfigurationPrefix() { |
|
114 | + $serverConnections = $this->getServerConfigurationPrefixes(); |
|
115 | + |
|
116 | + if(count($serverConnections) === 0) { |
|
117 | + return 's01'; |
|
118 | + } |
|
119 | + |
|
120 | + sort($serverConnections); |
|
121 | + $lastKey = array_pop($serverConnections); |
|
122 | + $lastNumber = intval(str_replace('s', '', $lastKey)); |
|
123 | + $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT); |
|
124 | + return $nextPrefix; |
|
125 | + } |
|
126 | + |
|
127 | + private function getServersConfig($value) { |
|
128 | + $regex = '/' . $value . '$/S'; |
|
129 | + |
|
130 | + $keys = $this->config->getAppKeys('user_ldap'); |
|
131 | + $result = []; |
|
132 | + foreach ($keys as $key) { |
|
133 | + if (preg_match($regex, $key) === 1) { |
|
134 | + $result[] = $key; |
|
135 | + } |
|
136 | + } |
|
137 | + |
|
138 | + return $result; |
|
139 | + } |
|
140 | + |
|
141 | + /** |
|
142 | + * deletes a given saved LDAP/AD server configuration. |
|
143 | + * @param string $prefix the configuration prefix of the config to delete |
|
144 | + * @return bool true on success, false otherwise |
|
145 | + */ |
|
146 | + public function deleteServerConfiguration($prefix) { |
|
147 | + if(!in_array($prefix, self::getServerConfigurationPrefixes())) { |
|
148 | + return false; |
|
149 | + } |
|
150 | + |
|
151 | + $saveOtherConfigurations = ''; |
|
152 | + if(empty($prefix)) { |
|
153 | + $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; |
|
154 | + } |
|
155 | + |
|
156 | + $query = \OCP\DB::prepare(' |
|
157 | 157 | DELETE |
158 | 158 | FROM `*PREFIX*appconfig` |
159 | 159 | WHERE `configkey` LIKE ? |
@@ -161,146 +161,146 @@ discard block |
||
161 | 161 | AND `appid` = \'user_ldap\' |
162 | 162 | AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\') |
163 | 163 | '); |
164 | - $delRows = $query->execute(array($prefix.'%')); |
|
165 | - |
|
166 | - if(\OCP\DB::isError($delRows)) { |
|
167 | - return false; |
|
168 | - } |
|
169 | - |
|
170 | - if($delRows === 0) { |
|
171 | - return false; |
|
172 | - } |
|
173 | - |
|
174 | - return true; |
|
175 | - } |
|
176 | - |
|
177 | - /** |
|
178 | - * checks whether there is one or more disabled LDAP configurations |
|
179 | - * @throws \Exception |
|
180 | - * @return bool |
|
181 | - */ |
|
182 | - public function haveDisabledConfigurations() { |
|
183 | - $all = $this->getServerConfigurationPrefixes(false); |
|
184 | - $active = $this->getServerConfigurationPrefixes(true); |
|
185 | - |
|
186 | - if(!is_array($all) || !is_array($active)) { |
|
187 | - throw new \Exception('Unexpected Return Value'); |
|
188 | - } |
|
189 | - |
|
190 | - return count($all) !== count($active) || count($all) === 0; |
|
191 | - } |
|
192 | - |
|
193 | - /** |
|
194 | - * extracts the domain from a given URL |
|
195 | - * @param string $url the URL |
|
196 | - * @return string|false domain as string on success, false otherwise |
|
197 | - */ |
|
198 | - public function getDomainFromURL($url) { |
|
199 | - $uinfo = parse_url($url); |
|
200 | - if(!is_array($uinfo)) { |
|
201 | - return false; |
|
202 | - } |
|
203 | - |
|
204 | - $domain = false; |
|
205 | - if(isset($uinfo['host'])) { |
|
206 | - $domain = $uinfo['host']; |
|
207 | - } else if(isset($uinfo['path'])) { |
|
208 | - $domain = $uinfo['path']; |
|
209 | - } |
|
210 | - |
|
211 | - return $domain; |
|
212 | - } |
|
164 | + $delRows = $query->execute(array($prefix.'%')); |
|
165 | + |
|
166 | + if(\OCP\DB::isError($delRows)) { |
|
167 | + return false; |
|
168 | + } |
|
169 | + |
|
170 | + if($delRows === 0) { |
|
171 | + return false; |
|
172 | + } |
|
173 | + |
|
174 | + return true; |
|
175 | + } |
|
176 | + |
|
177 | + /** |
|
178 | + * checks whether there is one or more disabled LDAP configurations |
|
179 | + * @throws \Exception |
|
180 | + * @return bool |
|
181 | + */ |
|
182 | + public function haveDisabledConfigurations() { |
|
183 | + $all = $this->getServerConfigurationPrefixes(false); |
|
184 | + $active = $this->getServerConfigurationPrefixes(true); |
|
185 | + |
|
186 | + if(!is_array($all) || !is_array($active)) { |
|
187 | + throw new \Exception('Unexpected Return Value'); |
|
188 | + } |
|
189 | + |
|
190 | + return count($all) !== count($active) || count($all) === 0; |
|
191 | + } |
|
192 | + |
|
193 | + /** |
|
194 | + * extracts the domain from a given URL |
|
195 | + * @param string $url the URL |
|
196 | + * @return string|false domain as string on success, false otherwise |
|
197 | + */ |
|
198 | + public function getDomainFromURL($url) { |
|
199 | + $uinfo = parse_url($url); |
|
200 | + if(!is_array($uinfo)) { |
|
201 | + return false; |
|
202 | + } |
|
203 | + |
|
204 | + $domain = false; |
|
205 | + if(isset($uinfo['host'])) { |
|
206 | + $domain = $uinfo['host']; |
|
207 | + } else if(isset($uinfo['path'])) { |
|
208 | + $domain = $uinfo['path']; |
|
209 | + } |
|
210 | + |
|
211 | + return $domain; |
|
212 | + } |
|
213 | 213 | |
214 | - /** |
|
215 | - * |
|
216 | - * Set the LDAPProvider in the config |
|
217 | - * |
|
218 | - */ |
|
219 | - public function setLDAPProvider() { |
|
220 | - $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); |
|
221 | - if(is_null($current)) { |
|
222 | - \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory'); |
|
223 | - } |
|
224 | - } |
|
214 | + /** |
|
215 | + * |
|
216 | + * Set the LDAPProvider in the config |
|
217 | + * |
|
218 | + */ |
|
219 | + public function setLDAPProvider() { |
|
220 | + $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); |
|
221 | + if(is_null($current)) { |
|
222 | + \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory'); |
|
223 | + } |
|
224 | + } |
|
225 | 225 | |
226 | - /** |
|
227 | - * sanitizes a DN received from the LDAP server |
|
228 | - * @param array $dn the DN in question |
|
229 | - * @return array the sanitized DN |
|
230 | - */ |
|
231 | - public function sanitizeDN($dn) { |
|
232 | - //treating multiple base DNs |
|
233 | - if(is_array($dn)) { |
|
234 | - $result = array(); |
|
235 | - foreach($dn as $singleDN) { |
|
236 | - $result[] = $this->sanitizeDN($singleDN); |
|
237 | - } |
|
238 | - return $result; |
|
239 | - } |
|
240 | - |
|
241 | - //OID sometimes gives back DNs with whitespace after the comma |
|
242 | - // a la "uid=foo, cn=bar, dn=..." We need to tackle this! |
|
243 | - $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn); |
|
244 | - |
|
245 | - //make comparisons and everything work |
|
246 | - $dn = mb_strtolower($dn, 'UTF-8'); |
|
247 | - |
|
248 | - //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn |
|
249 | - //to use the DN in search filters, \ needs to be escaped to \5c additionally |
|
250 | - //to use them in bases, we convert them back to simple backslashes in readAttribute() |
|
251 | - $replacements = array( |
|
252 | - '\,' => '\5c2C', |
|
253 | - '\=' => '\5c3D', |
|
254 | - '\+' => '\5c2B', |
|
255 | - '\<' => '\5c3C', |
|
256 | - '\>' => '\5c3E', |
|
257 | - '\;' => '\5c3B', |
|
258 | - '\"' => '\5c22', |
|
259 | - '\#' => '\5c23', |
|
260 | - '(' => '\28', |
|
261 | - ')' => '\29', |
|
262 | - '*' => '\2A', |
|
263 | - ); |
|
264 | - $dn = str_replace(array_keys($replacements), array_values($replacements), $dn); |
|
265 | - |
|
266 | - return $dn; |
|
267 | - } |
|
226 | + /** |
|
227 | + * sanitizes a DN received from the LDAP server |
|
228 | + * @param array $dn the DN in question |
|
229 | + * @return array the sanitized DN |
|
230 | + */ |
|
231 | + public function sanitizeDN($dn) { |
|
232 | + //treating multiple base DNs |
|
233 | + if(is_array($dn)) { |
|
234 | + $result = array(); |
|
235 | + foreach($dn as $singleDN) { |
|
236 | + $result[] = $this->sanitizeDN($singleDN); |
|
237 | + } |
|
238 | + return $result; |
|
239 | + } |
|
240 | + |
|
241 | + //OID sometimes gives back DNs with whitespace after the comma |
|
242 | + // a la "uid=foo, cn=bar, dn=..." We need to tackle this! |
|
243 | + $dn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn); |
|
244 | + |
|
245 | + //make comparisons and everything work |
|
246 | + $dn = mb_strtolower($dn, 'UTF-8'); |
|
247 | + |
|
248 | + //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn |
|
249 | + //to use the DN in search filters, \ needs to be escaped to \5c additionally |
|
250 | + //to use them in bases, we convert them back to simple backslashes in readAttribute() |
|
251 | + $replacements = array( |
|
252 | + '\,' => '\5c2C', |
|
253 | + '\=' => '\5c3D', |
|
254 | + '\+' => '\5c2B', |
|
255 | + '\<' => '\5c3C', |
|
256 | + '\>' => '\5c3E', |
|
257 | + '\;' => '\5c3B', |
|
258 | + '\"' => '\5c22', |
|
259 | + '\#' => '\5c23', |
|
260 | + '(' => '\28', |
|
261 | + ')' => '\29', |
|
262 | + '*' => '\2A', |
|
263 | + ); |
|
264 | + $dn = str_replace(array_keys($replacements), array_values($replacements), $dn); |
|
265 | + |
|
266 | + return $dn; |
|
267 | + } |
|
268 | 268 | |
269 | - /** |
|
270 | - * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters |
|
271 | - * @param string $dn the DN |
|
272 | - * @return string |
|
273 | - */ |
|
274 | - public function DNasBaseParameter($dn) { |
|
275 | - return str_ireplace('\\5c', '\\', $dn); |
|
276 | - } |
|
277 | - |
|
278 | - /** |
|
279 | - * listens to a hook thrown by server2server sharing and replaces the given |
|
280 | - * login name by a username, if it matches an LDAP user. |
|
281 | - * |
|
282 | - * @param array $param |
|
283 | - * @throws \Exception |
|
284 | - */ |
|
285 | - public static function loginName2UserName($param) { |
|
286 | - if(!isset($param['uid'])) { |
|
287 | - throw new \Exception('key uid is expected to be set in $param'); |
|
288 | - } |
|
289 | - |
|
290 | - //ain't it ironic? |
|
291 | - $helper = new Helper(\OC::$server->getConfig()); |
|
292 | - |
|
293 | - $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
294 | - $ldapWrapper = new LDAP(); |
|
295 | - $ocConfig = \OC::$server->getConfig(); |
|
296 | - $notificationManager = \OC::$server->getNotificationManager(); |
|
297 | - |
|
298 | - $userBackend = new User_Proxy( |
|
299 | - $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager |
|
300 | - ); |
|
301 | - $uid = $userBackend->loginName2UserName($param['uid'] ); |
|
302 | - if($uid !== false) { |
|
303 | - $param['uid'] = $uid; |
|
304 | - } |
|
305 | - } |
|
269 | + /** |
|
270 | + * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters |
|
271 | + * @param string $dn the DN |
|
272 | + * @return string |
|
273 | + */ |
|
274 | + public function DNasBaseParameter($dn) { |
|
275 | + return str_ireplace('\\5c', '\\', $dn); |
|
276 | + } |
|
277 | + |
|
278 | + /** |
|
279 | + * listens to a hook thrown by server2server sharing and replaces the given |
|
280 | + * login name by a username, if it matches an LDAP user. |
|
281 | + * |
|
282 | + * @param array $param |
|
283 | + * @throws \Exception |
|
284 | + */ |
|
285 | + public static function loginName2UserName($param) { |
|
286 | + if(!isset($param['uid'])) { |
|
287 | + throw new \Exception('key uid is expected to be set in $param'); |
|
288 | + } |
|
289 | + |
|
290 | + //ain't it ironic? |
|
291 | + $helper = new Helper(\OC::$server->getConfig()); |
|
292 | + |
|
293 | + $configPrefixes = $helper->getServerConfigurationPrefixes(true); |
|
294 | + $ldapWrapper = new LDAP(); |
|
295 | + $ocConfig = \OC::$server->getConfig(); |
|
296 | + $notificationManager = \OC::$server->getNotificationManager(); |
|
297 | + |
|
298 | + $userBackend = new User_Proxy( |
|
299 | + $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager |
|
300 | + ); |
|
301 | + $uid = $userBackend->loginName2UserName($param['uid'] ); |
|
302 | + if($uid !== false) { |
|
303 | + $param['uid'] = $uid; |
|
304 | + } |
|
305 | + } |
|
306 | 306 | } |
@@ -96,7 +96,7 @@ discard block |
||
96 | 96 | $keys = $this->getServersConfig($referenceConfigkey); |
97 | 97 | |
98 | 98 | $result = array(); |
99 | - foreach($keys as $key) { |
|
99 | + foreach ($keys as $key) { |
|
100 | 100 | $len = strlen($key) - strlen($referenceConfigkey); |
101 | 101 | $prefix = substr($key, 0, $len); |
102 | 102 | $result[$prefix] = $this->config->getAppValue('user_ldap', $key); |
@@ -113,19 +113,19 @@ discard block |
||
113 | 113 | public function getNextServerConfigurationPrefix() { |
114 | 114 | $serverConnections = $this->getServerConfigurationPrefixes(); |
115 | 115 | |
116 | - if(count($serverConnections) === 0) { |
|
116 | + if (count($serverConnections) === 0) { |
|
117 | 117 | return 's01'; |
118 | 118 | } |
119 | 119 | |
120 | 120 | sort($serverConnections); |
121 | 121 | $lastKey = array_pop($serverConnections); |
122 | 122 | $lastNumber = intval(str_replace('s', '', $lastKey)); |
123 | - $nextPrefix = 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT); |
|
123 | + $nextPrefix = 's'.str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT); |
|
124 | 124 | return $nextPrefix; |
125 | 125 | } |
126 | 126 | |
127 | 127 | private function getServersConfig($value) { |
128 | - $regex = '/' . $value . '$/S'; |
|
128 | + $regex = '/'.$value.'$/S'; |
|
129 | 129 | |
130 | 130 | $keys = $this->config->getAppKeys('user_ldap'); |
131 | 131 | $result = []; |
@@ -144,12 +144,12 @@ discard block |
||
144 | 144 | * @return bool true on success, false otherwise |
145 | 145 | */ |
146 | 146 | public function deleteServerConfiguration($prefix) { |
147 | - if(!in_array($prefix, self::getServerConfigurationPrefixes())) { |
|
147 | + if (!in_array($prefix, self::getServerConfigurationPrefixes())) { |
|
148 | 148 | return false; |
149 | 149 | } |
150 | 150 | |
151 | 151 | $saveOtherConfigurations = ''; |
152 | - if(empty($prefix)) { |
|
152 | + if (empty($prefix)) { |
|
153 | 153 | $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\''; |
154 | 154 | } |
155 | 155 | |
@@ -163,11 +163,11 @@ discard block |
||
163 | 163 | '); |
164 | 164 | $delRows = $query->execute(array($prefix.'%')); |
165 | 165 | |
166 | - if(\OCP\DB::isError($delRows)) { |
|
166 | + if (\OCP\DB::isError($delRows)) { |
|
167 | 167 | return false; |
168 | 168 | } |
169 | 169 | |
170 | - if($delRows === 0) { |
|
170 | + if ($delRows === 0) { |
|
171 | 171 | return false; |
172 | 172 | } |
173 | 173 | |
@@ -183,7 +183,7 @@ discard block |
||
183 | 183 | $all = $this->getServerConfigurationPrefixes(false); |
184 | 184 | $active = $this->getServerConfigurationPrefixes(true); |
185 | 185 | |
186 | - if(!is_array($all) || !is_array($active)) { |
|
186 | + if (!is_array($all) || !is_array($active)) { |
|
187 | 187 | throw new \Exception('Unexpected Return Value'); |
188 | 188 | } |
189 | 189 | |
@@ -197,14 +197,14 @@ discard block |
||
197 | 197 | */ |
198 | 198 | public function getDomainFromURL($url) { |
199 | 199 | $uinfo = parse_url($url); |
200 | - if(!is_array($uinfo)) { |
|
200 | + if (!is_array($uinfo)) { |
|
201 | 201 | return false; |
202 | 202 | } |
203 | 203 | |
204 | 204 | $domain = false; |
205 | - if(isset($uinfo['host'])) { |
|
205 | + if (isset($uinfo['host'])) { |
|
206 | 206 | $domain = $uinfo['host']; |
207 | - } else if(isset($uinfo['path'])) { |
|
207 | + } else if (isset($uinfo['path'])) { |
|
208 | 208 | $domain = $uinfo['path']; |
209 | 209 | } |
210 | 210 | |
@@ -218,7 +218,7 @@ discard block |
||
218 | 218 | */ |
219 | 219 | public function setLDAPProvider() { |
220 | 220 | $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null); |
221 | - if(is_null($current)) { |
|
221 | + if (is_null($current)) { |
|
222 | 222 | \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', '\\OCA\\User_LDAP\\LDAPProviderFactory'); |
223 | 223 | } |
224 | 224 | } |
@@ -230,9 +230,9 @@ discard block |
||
230 | 230 | */ |
231 | 231 | public function sanitizeDN($dn) { |
232 | 232 | //treating multiple base DNs |
233 | - if(is_array($dn)) { |
|
233 | + if (is_array($dn)) { |
|
234 | 234 | $result = array(); |
235 | - foreach($dn as $singleDN) { |
|
235 | + foreach ($dn as $singleDN) { |
|
236 | 236 | $result[] = $this->sanitizeDN($singleDN); |
237 | 237 | } |
238 | 238 | return $result; |
@@ -283,7 +283,7 @@ discard block |
||
283 | 283 | * @throws \Exception |
284 | 284 | */ |
285 | 285 | public static function loginName2UserName($param) { |
286 | - if(!isset($param['uid'])) { |
|
286 | + if (!isset($param['uid'])) { |
|
287 | 287 | throw new \Exception('key uid is expected to be set in $param'); |
288 | 288 | } |
289 | 289 | |
@@ -295,11 +295,11 @@ discard block |
||
295 | 295 | $ocConfig = \OC::$server->getConfig(); |
296 | 296 | $notificationManager = \OC::$server->getNotificationManager(); |
297 | 297 | |
298 | - $userBackend = new User_Proxy( |
|
298 | + $userBackend = new User_Proxy( |
|
299 | 299 | $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager |
300 | 300 | ); |
301 | - $uid = $userBackend->loginName2UserName($param['uid'] ); |
|
302 | - if($uid !== false) { |
|
301 | + $uid = $userBackend->loginName2UserName($param['uid']); |
|
302 | + if ($uid !== false) { |
|
303 | 303 | $param['uid'] = $uid; |
304 | 304 | } |
305 | 305 | } |