Completed
Pull Request — master (#6637)
by Tobia
13:14
created
lib/public/Settings/IIconSection.php 2 patches
Doc Comments   +1 added lines patch added patch discarded remove patch
@@ -33,6 +33,7 @@
 block discarded – undo
33 33
 	 *
34 34
 	 * @returns string
35 35
 	 * @since 12
36
+	 * @return string
36 37
 	 */
37 38
 	public function getIcon();
38 39
 }
Please login to merge, or discard this patch.
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -27,12 +27,12 @@
 block discarded – undo
27 27
  * @since 12
28 28
  */
29 29
 interface IIconSection extends ISection {
30
-	/**
31
-	 * returns the relative path to an 16*16 icon describing the section.
32
-	 * e.g. '/core/img/places/files.svg'
33
-	 *
34
-	 * @returns string
35
-	 * @since 12
36
-	 */
37
-	public function getIcon();
30
+    /**
31
+     * returns the relative path to an 16*16 icon describing the section.
32
+     * e.g. '/core/img/places/files.svg'
33
+     *
34
+     * @returns string
35
+     * @since 12
36
+     */
37
+    public function getIcon();
38 38
 }
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/FTP.php 4 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -139,6 +139,9 @@
 block discarded – undo
139 139
 		return false;
140 140
 	}
141 141
 
142
+	/**
143
+	 * @param string $path
144
+	 */
142 145
 	public function writeBack($tmpFile, $path) {
143 146
 		$this->uploadFile($tmpFile, $path);
144 147
 		unlink($tmpFile);
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -93,8 +93,7 @@
 block discarded – undo
93 93
 	public function unlink($path) {
94 94
 		if ($this->is_dir($path)) {
95 95
 			return $this->rmdir($path);
96
-		}
97
-		else {
96
+		} else {
98 97
 			$url = $this->constructUrl($path);
99 98
 			$result = unlink($url);
100 99
 			clearstatcache(true, $url);
Please login to merge, or discard this patch.
Indentation   +109 added lines, -109 removed lines patch added patch discarded remove patch
@@ -37,122 +37,122 @@
 block discarded – undo
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39 39
 class FTP extends StreamWrapper{
40
-	private $password;
41
-	private $user;
42
-	private $host;
43
-	private $secure;
44
-	private $root;
40
+    private $password;
41
+    private $user;
42
+    private $host;
43
+    private $secure;
44
+    private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+    private static $tempFiles=array();
47 47
 
48
-	public function __construct($params) {
49
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
53
-			if (isset($params['secure'])) {
54
-				$this->secure = $params['secure'];
55
-			} else {
56
-				$this->secure = false;
57
-			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!=='/') {
60
-				$this->root='/'.$this->root;
61
-			}
62
-			if (substr($this->root, -1) !== '/') {
63
-				$this->root .= '/';
64
-			}
65
-		} else {
66
-			throw new \Exception('Creating FTP storage failed');
67
-		}
48
+    public function __construct($params) {
49
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
+            $this->host=$params['host'];
51
+            $this->user=$params['user'];
52
+            $this->password=$params['password'];
53
+            if (isset($params['secure'])) {
54
+                $this->secure = $params['secure'];
55
+            } else {
56
+                $this->secure = false;
57
+            }
58
+            $this->root=isset($params['root'])?$params['root']:'/';
59
+            if ( ! $this->root || $this->root[0]!=='/') {
60
+                $this->root='/'.$this->root;
61
+            }
62
+            if (substr($this->root, -1) !== '/') {
63
+                $this->root .= '/';
64
+            }
65
+        } else {
66
+            throw new \Exception('Creating FTP storage failed');
67
+        }
68 68
 		
69
-	}
69
+    }
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
73
-	}
71
+    public function getId(){
72
+        return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
73
+    }
74 74
 
75
-	/**
76
-	 * construct the ftp url
77
-	 * @param string $path
78
-	 * @return string
79
-	 */
80
-	public function constructUrl($path) {
81
-		$url='ftp';
82
-		if ($this->secure) {
83
-			$url.='s';
84
-		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
-		return $url;
87
-	}
75
+    /**
76
+     * construct the ftp url
77
+     * @param string $path
78
+     * @return string
79
+     */
80
+    public function constructUrl($path) {
81
+        $url='ftp';
82
+        if ($this->secure) {
83
+            $url.='s';
84
+        }
85
+        $url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86
+        return $url;
87
+    }
88 88
 
89
-	/**
90
-	 * Unlinks file or directory
91
-	 * @param string $path
92
-	 */
93
-	public function unlink($path) {
94
-		if ($this->is_dir($path)) {
95
-			return $this->rmdir($path);
96
-		}
97
-		else {
98
-			$url = $this->constructUrl($path);
99
-			$result = unlink($url);
100
-			clearstatcache(true, $url);
101
-			return $result;
102
-		}
103
-	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
106
-			case 'r':
107
-			case 'rb':
108
-			case 'w':
109
-			case 'wb':
110
-			case 'a':
111
-			case 'ab':
112
-				//these are supported by the wrapper
113
-				$context = stream_context_create(array('ftp' => array('overwrite' => true)));
114
-				$handle = fopen($this->constructUrl($path), $mode, false, $context);
115
-				return RetryWrapper::wrap($handle);
116
-			case 'r+':
117
-			case 'w+':
118
-			case 'wb+':
119
-			case 'a+':
120
-			case 'x':
121
-			case 'x+':
122
-			case 'c':
123
-			case 'c+':
124
-				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
127
-				} else {
128
-					$ext='';
129
-				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
131
-				if ($this->file_exists($path)) {
132
-					$this->getFile($path, $tmpFile);
133
-				}
134
-				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
-					$this->writeBack($tmpFile, $path);
137
-				});
138
-		}
139
-		return false;
140
-	}
89
+    /**
90
+     * Unlinks file or directory
91
+     * @param string $path
92
+     */
93
+    public function unlink($path) {
94
+        if ($this->is_dir($path)) {
95
+            return $this->rmdir($path);
96
+        }
97
+        else {
98
+            $url = $this->constructUrl($path);
99
+            $result = unlink($url);
100
+            clearstatcache(true, $url);
101
+            return $result;
102
+        }
103
+    }
104
+    public function fopen($path,$mode) {
105
+        switch($mode) {
106
+            case 'r':
107
+            case 'rb':
108
+            case 'w':
109
+            case 'wb':
110
+            case 'a':
111
+            case 'ab':
112
+                //these are supported by the wrapper
113
+                $context = stream_context_create(array('ftp' => array('overwrite' => true)));
114
+                $handle = fopen($this->constructUrl($path), $mode, false, $context);
115
+                return RetryWrapper::wrap($handle);
116
+            case 'r+':
117
+            case 'w+':
118
+            case 'wb+':
119
+            case 'a+':
120
+            case 'x':
121
+            case 'x+':
122
+            case 'c':
123
+            case 'c+':
124
+                //emulate these
125
+                if (strrpos($path, '.')!==false) {
126
+                    $ext=substr($path, strrpos($path, '.'));
127
+                } else {
128
+                    $ext='';
129
+                }
130
+                $tmpFile=\OCP\Files::tmpFile($ext);
131
+                if ($this->file_exists($path)) {
132
+                    $this->getFile($path, $tmpFile);
133
+                }
134
+                $handle = fopen($tmpFile, $mode);
135
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
136
+                    $this->writeBack($tmpFile, $path);
137
+                });
138
+        }
139
+        return false;
140
+    }
141 141
 
142
-	public function writeBack($tmpFile, $path) {
143
-		$this->uploadFile($tmpFile, $path);
144
-		unlink($tmpFile);
145
-	}
142
+    public function writeBack($tmpFile, $path) {
143
+        $this->uploadFile($tmpFile, $path);
144
+        unlink($tmpFile);
145
+    }
146 146
 
147
-	/**
148
-	 * check if php-ftp is installed
149
-	 */
150
-	public static function checkDependencies() {
151
-		if (function_exists('ftp_login')) {
152
-			return(true);
153
-		} else {
154
-			return array('ftp');
155
-		}
156
-	}
147
+    /**
148
+     * check if php-ftp is installed
149
+     */
150
+    public static function checkDependencies() {
151
+        if (function_exists('ftp_login')) {
152
+            return(true);
153
+        } else {
154
+            return array('ftp');
155
+        }
156
+    }
157 157
 
158 158
 }
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -36,28 +36,28 @@  discard block
 block discarded – undo
36 36
 use Icewind\Streams\CallbackWrapper;
37 37
 use Icewind\Streams\RetryWrapper;
38 38
 
39
-class FTP extends StreamWrapper{
39
+class FTP extends StreamWrapper {
40 40
 	private $password;
41 41
 	private $user;
42 42
 	private $host;
43 43
 	private $secure;
44 44
 	private $root;
45 45
 
46
-	private static $tempFiles=array();
46
+	private static $tempFiles = array();
47 47
 
48 48
 	public function __construct($params) {
49 49
 		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
50
-			$this->host=$params['host'];
51
-			$this->user=$params['user'];
52
-			$this->password=$params['password'];
50
+			$this->host = $params['host'];
51
+			$this->user = $params['user'];
52
+			$this->password = $params['password'];
53 53
 			if (isset($params['secure'])) {
54 54
 				$this->secure = $params['secure'];
55 55
 			} else {
56 56
 				$this->secure = false;
57 57
 			}
58
-			$this->root=isset($params['root'])?$params['root']:'/';
59
-			if ( ! $this->root || $this->root[0]!=='/') {
60
-				$this->root='/'.$this->root;
58
+			$this->root = isset($params['root']) ? $params['root'] : '/';
59
+			if (!$this->root || $this->root[0] !== '/') {
60
+				$this->root = '/'.$this->root;
61 61
 			}
62 62
 			if (substr($this->root, -1) !== '/') {
63 63
 				$this->root .= '/';
@@ -68,8 +68,8 @@  discard block
 block discarded – undo
68 68
 		
69 69
 	}
70 70
 
71
-	public function getId(){
72
-		return 'ftp::' . $this->user . '@' . $this->host . '/' . $this->root;
71
+	public function getId() {
72
+		return 'ftp::'.$this->user.'@'.$this->host.'/'.$this->root;
73 73
 	}
74 74
 
75 75
 	/**
@@ -78,11 +78,11 @@  discard block
 block discarded – undo
78 78
 	 * @return string
79 79
 	 */
80 80
 	public function constructUrl($path) {
81
-		$url='ftp';
81
+		$url = 'ftp';
82 82
 		if ($this->secure) {
83
-			$url.='s';
83
+			$url .= 's';
84 84
 		}
85
-		$url.='://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
85
+		$url .= '://'.urlencode($this->user).':'.urlencode($this->password).'@'.$this->host.$this->root.$path;
86 86
 		return $url;
87 87
 	}
88 88
 
@@ -101,8 +101,8 @@  discard block
 block discarded – undo
101 101
 			return $result;
102 102
 		}
103 103
 	}
104
-	public function fopen($path,$mode) {
105
-		switch($mode) {
104
+	public function fopen($path, $mode) {
105
+		switch ($mode) {
106 106
 			case 'r':
107 107
 			case 'rb':
108 108
 			case 'w':
@@ -122,17 +122,17 @@  discard block
 block discarded – undo
122 122
 			case 'c':
123 123
 			case 'c+':
124 124
 				//emulate these
125
-				if (strrpos($path, '.')!==false) {
126
-					$ext=substr($path, strrpos($path, '.'));
125
+				if (strrpos($path, '.') !== false) {
126
+					$ext = substr($path, strrpos($path, '.'));
127 127
 				} else {
128
-					$ext='';
128
+					$ext = '';
129 129
 				}
130
-				$tmpFile=\OCP\Files::tmpFile($ext);
130
+				$tmpFile = \OCP\Files::tmpFile($ext);
131 131
 				if ($this->file_exists($path)) {
132 132
 					$this->getFile($path, $tmpFile);
133 133
 				}
134 134
 				$handle = fopen($tmpFile, $mode);
135
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
135
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
136 136
 					$this->writeBack($tmpFile, $path);
137 137
 				});
138 138
 		}
Please login to merge, or discard this patch.
apps/files_external/lib/Lib/Storage/Swift.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -616,6 +616,9 @@
 block discarded – undo
616 616
 		return $this->container;
617 617
 	}
618 618
 
619
+	/**
620
+	 * @param string $path
621
+	 */
619 622
 	public function writeBack($tmpFile, $path) {
620 623
 		$fileData = fopen($tmpFile, 'r');
621 624
 		$this->getContainer()->uploadObject($path, $fileData);
Please login to merge, or discard this patch.
Indentation   +596 added lines, -596 removed lines patch added patch discarded remove patch
@@ -53,601 +53,601 @@
 block discarded – undo
53 53
 
54 54
 class Swift extends \OC\Files\Storage\Common {
55 55
 
56
-	/**
57
-	 * @var \OpenCloud\ObjectStore\Service
58
-	 */
59
-	private $connection;
60
-	/**
61
-	 * @var \OpenCloud\ObjectStore\Resource\Container
62
-	 */
63
-	private $container;
64
-	/**
65
-	 * @var \OpenCloud\OpenStack
66
-	 */
67
-	private $anchor;
68
-	/**
69
-	 * @var string
70
-	 */
71
-	private $bucket;
72
-	/**
73
-	 * Connection parameters
74
-	 *
75
-	 * @var array
76
-	 */
77
-	private $params;
78
-
79
-	/** @var string  */
80
-	private $id;
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\ObjectStore\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) && $file !== '.') {
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
-					/** @var \OpenCloud\Common\Http\Client $client */
386
-					$client = $c->getClient();
387
-					$streamInterface = $streamFactory->fromRequest($client->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 RetryWrapper::wrap($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($path);
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
-	}
56
+    /**
57
+     * @var \OpenCloud\ObjectStore\Service
58
+     */
59
+    private $connection;
60
+    /**
61
+     * @var \OpenCloud\ObjectStore\Resource\Container
62
+     */
63
+    private $container;
64
+    /**
65
+     * @var \OpenCloud\OpenStack
66
+     */
67
+    private $anchor;
68
+    /**
69
+     * @var string
70
+     */
71
+    private $bucket;
72
+    /**
73
+     * Connection parameters
74
+     *
75
+     * @var array
76
+     */
77
+    private $params;
78
+
79
+    /** @var string  */
80
+    private $id;
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\ObjectStore\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) && $file !== '.') {
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
+                    /** @var \OpenCloud\Common\Http\Client $client */
386
+                    $client = $c->getClient();
387
+                    $streamInterface = $streamFactory->fromRequest($client->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 RetryWrapper::wrap($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($path);
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
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
164 164
 		}
165 165
 
166
-		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);
166
+		$this->id = 'swift::'.$params['user'].md5($params['bucket']);
167 167
 
168 168
 		$bucketUrl = Url::factory($params['bucket']);
169 169
 		if ($bucketUrl->isAbsolute()) {
@@ -236,16 +236,16 @@  discard block
 block discarded – undo
236 236
 				continue;
237 237
 			}
238 238
 
239
-			if ($this->is_dir($path . '/' . $file)) {
240
-				$this->rmdir($path . '/' . $file);
239
+			if ($this->is_dir($path.'/'.$file)) {
240
+				$this->rmdir($path.'/'.$file);
241 241
 			} else {
242
-				$this->unlink($path . '/' . $file);
242
+				$this->unlink($path.'/'.$file);
243 243
 			}
244 244
 		}
245 245
 
246 246
 		try {
247
-			$this->getContainer()->dataObject()->setName($path . '/')->delete();
248
-			$this->objectCache->remove($path . '/');
247
+			$this->getContainer()->dataObject()->setName($path.'/')->delete();
248
+			$this->objectCache->remove($path.'/');
249 249
 		} catch (Exceptions\DeleteError $e) {
250 250
 			\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
251 251
 			return false;
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		}
327 327
 
328 328
 		$stat = array();
329
-		$stat['size'] = (int)$object->getContentLength();
329
+		$stat['size'] = (int) $object->getContentLength();
330 330
 		$stat['mtime'] = $mtime;
331 331
 		$stat['atime'] = time();
332 332
 		return $stat;
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 		try {
359 359
 			$this->getContainer()->dataObject()->setName($path)->delete();
360 360
 			$this->objectCache->remove($path);
361
-			$this->objectCache->remove($path . '/');
361
+			$this->objectCache->remove($path.'/');
362 362
 		} catch (ClientErrorResponseException $e) {
363 363
 			if ($e->getResponse()->getStatusCode() !== 404) {
364 364
 				\OCP\Util::writeLog('files_external', $e->getMessage(), \OCP\Util::ERROR);
@@ -387,8 +387,8 @@  discard block
 block discarded – undo
387 387
 					$streamInterface = $streamFactory->fromRequest($client->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 RetryWrapper::wrap($stream);
394 394
 					}
@@ -422,7 +422,7 @@  discard block
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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);
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareController.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -597,7 +597,7 @@
 block discarded – undo
597 597
 	 * publish activity
598 598
 	 *
599 599
 	 * @param string $subject
600
-	 * @param array $parameters
600
+	 * @param string[] $parameters
601 601
 	 * @param string $affectedUser
602 602
 	 * @param int $fileId
603 603
 	 * @param string $filePath
Please login to merge, or discard this patch.
Indentation   +564 added lines, -564 removed lines patch added patch discarded remove patch
@@ -64,572 +64,572 @@
 block discarded – undo
64 64
  */
65 65
 class ShareController extends Controller {
66 66
 
67
-	/** @var IConfig */
68
-	protected $config;
69
-	/** @var IURLGenerator */
70
-	protected $urlGenerator;
71
-	/** @var IUserManager */
72
-	protected $userManager;
73
-	/** @var ILogger */
74
-	protected $logger;
75
-	/** @var \OCP\Activity\IManager */
76
-	protected $activityManager;
77
-	/** @var \OCP\Share\IManager */
78
-	protected $shareManager;
79
-	/** @var ISession */
80
-	protected $session;
81
-	/** @var IPreview */
82
-	protected $previewManager;
83
-	/** @var IRootFolder */
84
-	protected $rootFolder;
85
-	/** @var FederatedShareProvider */
86
-	protected $federatedShareProvider;
87
-	/** @var EventDispatcherInterface */
88
-	protected $eventDispatcher;
89
-	/** @var IL10N */
90
-	protected $l10n;
91
-	/** @var Defaults */
92
-	protected $defaults;
93
-
94
-	/**
95
-	 * @param string $appName
96
-	 * @param IRequest $request
97
-	 * @param IConfig $config
98
-	 * @param IURLGenerator $urlGenerator
99
-	 * @param IUserManager $userManager
100
-	 * @param ILogger $logger
101
-	 * @param \OCP\Activity\IManager $activityManager
102
-	 * @param \OCP\Share\IManager $shareManager
103
-	 * @param ISession $session
104
-	 * @param IPreview $previewManager
105
-	 * @param IRootFolder $rootFolder
106
-	 * @param FederatedShareProvider $federatedShareProvider
107
-	 * @param EventDispatcherInterface $eventDispatcher
108
-	 * @param IL10N $l10n
109
-	 * @param 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
-		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
376
-		$ogPreview = '';
377
-		if ($shareTmpl['previewSupported']) {
378
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
379
-				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
380
-			$ogPreview = $shareTmpl['previewImage'];
381
-
382
-			// We just have direct previews for image files
383
-			if ($share->getNode()->getMimePart() === 'image') {
384
-				$shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
385
-				$ogPreview = $shareTmpl['previewURL'];
386
-			}
387
-		} else {
388
-			$shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
389
-			$ogPreview = $shareTmpl['previewImage'];
390
-		}
391
-
392
-		// Load files we need
393
-		\OCP\Util::addScript('files', 'file-upload');
394
-		\OCP\Util::addStyle('files_sharing', 'publicView');
395
-		\OCP\Util::addScript('files_sharing', 'public');
396
-		\OCP\Util::addScript('files', 'fileactions');
397
-		\OCP\Util::addScript('files', 'fileactionsmenu');
398
-		\OCP\Util::addScript('files', 'jquery.fileupload');
399
-		\OCP\Util::addScript('files_sharing', 'files_drop');
400
-
401
-		if (isset($shareTmpl['folder'])) {
402
-			// JS required for folders
403
-			\OCP\Util::addStyle('files', 'merged');
404
-			\OCP\Util::addScript('files', 'filesummary');
405
-			\OCP\Util::addScript('files', 'breadcrumb');
406
-			\OCP\Util::addScript('files', 'fileinfomodel');
407
-			\OCP\Util::addScript('files', 'newfilemenu');
408
-			\OCP\Util::addScript('files', 'files');
409
-			\OCP\Util::addScript('files', 'filelist');
410
-			\OCP\Util::addScript('files', 'keyboardshortcuts');
411
-		}
412
-
413
-		// OpenGraph Support: http://ogp.me/
414
-		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
415
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
416
-		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
417
-		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
418
-		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
419
-		\OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
420
-
421
-		$this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
422
-
423
-		$csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
424
-		$csp->addAllowedFrameDomain('\'self\'');
425
-		$response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
426
-		$response->setContentSecurityPolicy($csp);
427
-
428
-		$this->emitAccessShareHook($share);
429
-
430
-		return $response;
431
-	}
432
-
433
-	/**
434
-	 * @PublicPage
435
-	 * @NoCSRFRequired
436
-	 *
437
-	 * @param string $token
438
-	 * @param string $files
439
-	 * @param string $path
440
-	 * @param string $downloadStartSecret
441
-	 * @return void|\OCP\AppFramework\Http\Response
442
-	 * @throws NotFoundException
443
-	 */
444
-	public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
445
-		\OC_User::setIncognitoMode(true);
446
-
447
-		$share = $this->shareManager->getShareByToken($token);
448
-
449
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
450
-			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
451
-		}
452
-
453
-		// Share is password protected - check whether the user is permitted to access the share
454
-		if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
455
-			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
456
-				['token' => $token]));
457
-		}
458
-
459
-		$files_list = null;
460
-		if (!is_null($files)) { // download selected files
461
-			$files_list = json_decode($files);
462
-			// in case we get only a single file
463
-			if ($files_list === null) {
464
-				$files_list = [$files];
465
-			}
466
-			// Just in case $files is a single int like '1234'
467
-			if (!is_array($files_list)) {
468
-				$files_list = [$files_list];
469
-			}
470
-		}
471
-
472
-		$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
473
-		$originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
474
-
475
-		if (!$this->validateShare($share)) {
476
-			throw new NotFoundException();
477
-		}
478
-
479
-		// Single file share
480
-		if ($share->getNode() instanceof \OCP\Files\File) {
481
-			// Single file download
482
-			$this->singleFileDownloaded($share, $share->getNode());
483
-		}
484
-		// Directory share
485
-		else {
486
-			/** @var \OCP\Files\Folder $node */
487
-			$node = $share->getNode();
488
-
489
-			// Try to get the path
490
-			if ($path !== '') {
491
-				try {
492
-					$node = $node->get($path);
493
-				} catch (NotFoundException $e) {
494
-					$this->emitAccessShareHook($share, 404, 'Share not found');
495
-					return new NotFoundResponse();
496
-				}
497
-			}
498
-
499
-			$originalSharePath = $userFolder->getRelativePath($node->getPath());
500
-
501
-			if ($node instanceof \OCP\Files\File) {
502
-				// Single file download
503
-				$this->singleFileDownloaded($share, $share->getNode());
504
-			} else if (!empty($files_list)) {
505
-				$this->fileListDownloaded($share, $files_list, $node);
506
-			} else {
507
-				// The folder is downloaded
508
-				$this->singleFileDownloaded($share, $share->getNode());
509
-			}
510
-		}
511
-
512
-		/* FIXME: We should do this all nicely in OCP */
513
-		OC_Util::tearDownFS();
514
-		OC_Util::setupFS($share->getShareOwner());
515
-
516
-		/**
517
-		 * this sets a cookie to be able to recognize the start of the download
518
-		 * the content must not be longer than 32 characters and must only contain
519
-		 * alphanumeric characters
520
-		 */
521
-		if (!empty($downloadStartSecret)
522
-			&& !isset($downloadStartSecret[32])
523
-			&& preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
524
-
525
-			// FIXME: set on the response once we use an actual app framework response
526
-			setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
527
-		}
528
-
529
-		$this->emitAccessShareHook($share);
530
-
531
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
532
-
533
-		/**
534
-		 * Http range requests support
535
-		 */
536
-		if (isset($_SERVER['HTTP_RANGE'])) {
537
-			$server_params['range'] = $this->request->getHeader('Range');
538
-		}
539
-
540
-		// download selected files
541
-		if (!is_null($files) && $files !== '') {
542
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
543
-			// after dispatching the request which results in a "Cannot modify header information" notice.
544
-			OC_Files::get($originalSharePath, $files_list, $server_params);
545
-			exit();
546
-		} else {
547
-			// FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
548
-			// after dispatching the request which results in a "Cannot modify header information" notice.
549
-			OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
550
-			exit();
551
-		}
552
-	}
553
-
554
-	/**
555
-	 * create activity for every downloaded file
556
-	 *
557
-	 * @param Share\IShare $share
558
-	 * @param array $files_list
559
-	 * @param \OCP\Files\Folder $node
560
-	 */
561
-	protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
562
-		foreach ($files_list as $file) {
563
-			$subNode = $node->get($file);
564
-			$this->singleFileDownloaded($share, $subNode);
565
-		}
566
-
567
-	}
568
-
569
-	/**
570
-	 * create activity if a single file was downloaded from a link share
571
-	 *
572
-	 * @param Share\IShare $share
573
-	 */
574
-	protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
575
-
576
-		$fileId = $node->getId();
577
-
578
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
579
-		$userNodeList = $userFolder->getById($fileId);
580
-		$userNode = $userNodeList[0];
581
-		$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
582
-		$userPath = $userFolder->getRelativePath($userNode->getPath());
583
-		$ownerPath = $ownerFolder->getRelativePath($node->getPath());
584
-
585
-		$parameters = [$userPath];
586
-
587
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
588
-			if ($node instanceof \OCP\Files\File) {
589
-				$subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
590
-			} else {
591
-				$subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
592
-			}
593
-			$parameters[] = $share->getSharedWith();
594
-		} else {
595
-			if ($node instanceof \OCP\Files\File) {
596
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
597
-			} else {
598
-				$subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
599
-			}
600
-		}
601
-
602
-		$this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
603
-
604
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
605
-			$parameters[0] = $ownerPath;
606
-			$this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
607
-		}
608
-	}
609
-
610
-	/**
611
-	 * publish activity
612
-	 *
613
-	 * @param string $subject
614
-	 * @param array $parameters
615
-	 * @param string $affectedUser
616
-	 * @param int $fileId
617
-	 * @param string $filePath
618
-	 */
619
-	protected function publishActivity($subject,
620
-										array $parameters,
621
-										$affectedUser,
622
-										$fileId,
623
-										$filePath) {
624
-
625
-		$event = $this->activityManager->generateEvent();
626
-		$event->setApp('files_sharing')
627
-			->setType('public_links')
628
-			->setSubject($subject, $parameters)
629
-			->setAffectedUser($affectedUser)
630
-			->setObject('files', $fileId, $filePath);
631
-		$this->activityManager->publish($event);
632
-	}
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
+        $shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
376
+        $ogPreview = '';
377
+        if ($shareTmpl['previewSupported']) {
378
+            $shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
379
+                ['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
380
+            $ogPreview = $shareTmpl['previewImage'];
381
+
382
+            // We just have direct previews for image files
383
+            if ($share->getNode()->getMimePart() === 'image') {
384
+                $shareTmpl['previewURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.publicpreview.directLink', ['token' => $token]);
385
+                $ogPreview = $shareTmpl['previewURL'];
386
+            }
387
+        } else {
388
+            $shareTmpl['previewImage'] = $this->urlGenerator->getAbsoluteURL($this->urlGenerator->imagePath('core', 'favicon-fb.png'));
389
+            $ogPreview = $shareTmpl['previewImage'];
390
+        }
391
+
392
+        // Load files we need
393
+        \OCP\Util::addScript('files', 'file-upload');
394
+        \OCP\Util::addStyle('files_sharing', 'publicView');
395
+        \OCP\Util::addScript('files_sharing', 'public');
396
+        \OCP\Util::addScript('files', 'fileactions');
397
+        \OCP\Util::addScript('files', 'fileactionsmenu');
398
+        \OCP\Util::addScript('files', 'jquery.fileupload');
399
+        \OCP\Util::addScript('files_sharing', 'files_drop');
400
+
401
+        if (isset($shareTmpl['folder'])) {
402
+            // JS required for folders
403
+            \OCP\Util::addStyle('files', 'merged');
404
+            \OCP\Util::addScript('files', 'filesummary');
405
+            \OCP\Util::addScript('files', 'breadcrumb');
406
+            \OCP\Util::addScript('files', 'fileinfomodel');
407
+            \OCP\Util::addScript('files', 'newfilemenu');
408
+            \OCP\Util::addScript('files', 'files');
409
+            \OCP\Util::addScript('files', 'filelist');
410
+            \OCP\Util::addScript('files', 'keyboardshortcuts');
411
+        }
412
+
413
+        // OpenGraph Support: http://ogp.me/
414
+        \OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
415
+        \OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
416
+        \OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
417
+        \OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
418
+        \OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
419
+        \OCP\Util::addHeader('meta', ['property' => "og:image", 'content' => $ogPreview]);
420
+
421
+        $this->eventDispatcher->dispatch('OCA\Files_Sharing::loadAdditionalScripts');
422
+
423
+        $csp = new \OCP\AppFramework\Http\ContentSecurityPolicy();
424
+        $csp->addAllowedFrameDomain('\'self\'');
425
+        $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base');
426
+        $response->setContentSecurityPolicy($csp);
427
+
428
+        $this->emitAccessShareHook($share);
429
+
430
+        return $response;
431
+    }
432
+
433
+    /**
434
+     * @PublicPage
435
+     * @NoCSRFRequired
436
+     *
437
+     * @param string $token
438
+     * @param string $files
439
+     * @param string $path
440
+     * @param string $downloadStartSecret
441
+     * @return void|\OCP\AppFramework\Http\Response
442
+     * @throws NotFoundException
443
+     */
444
+    public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
445
+        \OC_User::setIncognitoMode(true);
446
+
447
+        $share = $this->shareManager->getShareByToken($token);
448
+
449
+        if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
450
+            return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
451
+        }
452
+
453
+        // Share is password protected - check whether the user is permitted to access the share
454
+        if ($share->getPassword() !== null && !$this->linkShareAuth($share)) {
455
+            return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate',
456
+                ['token' => $token]));
457
+        }
458
+
459
+        $files_list = null;
460
+        if (!is_null($files)) { // download selected files
461
+            $files_list = json_decode($files);
462
+            // in case we get only a single file
463
+            if ($files_list === null) {
464
+                $files_list = [$files];
465
+            }
466
+            // Just in case $files is a single int like '1234'
467
+            if (!is_array($files_list)) {
468
+                $files_list = [$files_list];
469
+            }
470
+        }
471
+
472
+        $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
473
+        $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
474
+
475
+        if (!$this->validateShare($share)) {
476
+            throw new NotFoundException();
477
+        }
478
+
479
+        // Single file share
480
+        if ($share->getNode() instanceof \OCP\Files\File) {
481
+            // Single file download
482
+            $this->singleFileDownloaded($share, $share->getNode());
483
+        }
484
+        // Directory share
485
+        else {
486
+            /** @var \OCP\Files\Folder $node */
487
+            $node = $share->getNode();
488
+
489
+            // Try to get the path
490
+            if ($path !== '') {
491
+                try {
492
+                    $node = $node->get($path);
493
+                } catch (NotFoundException $e) {
494
+                    $this->emitAccessShareHook($share, 404, 'Share not found');
495
+                    return new NotFoundResponse();
496
+                }
497
+            }
498
+
499
+            $originalSharePath = $userFolder->getRelativePath($node->getPath());
500
+
501
+            if ($node instanceof \OCP\Files\File) {
502
+                // Single file download
503
+                $this->singleFileDownloaded($share, $share->getNode());
504
+            } else if (!empty($files_list)) {
505
+                $this->fileListDownloaded($share, $files_list, $node);
506
+            } else {
507
+                // The folder is downloaded
508
+                $this->singleFileDownloaded($share, $share->getNode());
509
+            }
510
+        }
511
+
512
+        /* FIXME: We should do this all nicely in OCP */
513
+        OC_Util::tearDownFS();
514
+        OC_Util::setupFS($share->getShareOwner());
515
+
516
+        /**
517
+         * this sets a cookie to be able to recognize the start of the download
518
+         * the content must not be longer than 32 characters and must only contain
519
+         * alphanumeric characters
520
+         */
521
+        if (!empty($downloadStartSecret)
522
+            && !isset($downloadStartSecret[32])
523
+            && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
524
+
525
+            // FIXME: set on the response once we use an actual app framework response
526
+            setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
527
+        }
528
+
529
+        $this->emitAccessShareHook($share);
530
+
531
+        $server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
532
+
533
+        /**
534
+         * Http range requests support
535
+         */
536
+        if (isset($_SERVER['HTTP_RANGE'])) {
537
+            $server_params['range'] = $this->request->getHeader('Range');
538
+        }
539
+
540
+        // download selected files
541
+        if (!is_null($files) && $files !== '') {
542
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
543
+            // after dispatching the request which results in a "Cannot modify header information" notice.
544
+            OC_Files::get($originalSharePath, $files_list, $server_params);
545
+            exit();
546
+        } else {
547
+            // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
548
+            // after dispatching the request which results in a "Cannot modify header information" notice.
549
+            OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
550
+            exit();
551
+        }
552
+    }
553
+
554
+    /**
555
+     * create activity for every downloaded file
556
+     *
557
+     * @param Share\IShare $share
558
+     * @param array $files_list
559
+     * @param \OCP\Files\Folder $node
560
+     */
561
+    protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
562
+        foreach ($files_list as $file) {
563
+            $subNode = $node->get($file);
564
+            $this->singleFileDownloaded($share, $subNode);
565
+        }
566
+
567
+    }
568
+
569
+    /**
570
+     * create activity if a single file was downloaded from a link share
571
+     *
572
+     * @param Share\IShare $share
573
+     */
574
+    protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
575
+
576
+        $fileId = $node->getId();
577
+
578
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
579
+        $userNodeList = $userFolder->getById($fileId);
580
+        $userNode = $userNodeList[0];
581
+        $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
582
+        $userPath = $userFolder->getRelativePath($userNode->getPath());
583
+        $ownerPath = $ownerFolder->getRelativePath($node->getPath());
584
+
585
+        $parameters = [$userPath];
586
+
587
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
588
+            if ($node instanceof \OCP\Files\File) {
589
+                $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
590
+            } else {
591
+                $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
592
+            }
593
+            $parameters[] = $share->getSharedWith();
594
+        } else {
595
+            if ($node instanceof \OCP\Files\File) {
596
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
597
+            } else {
598
+                $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
599
+            }
600
+        }
601
+
602
+        $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
603
+
604
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
605
+            $parameters[0] = $ownerPath;
606
+            $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
607
+        }
608
+    }
609
+
610
+    /**
611
+     * publish activity
612
+     *
613
+     * @param string $subject
614
+     * @param array $parameters
615
+     * @param string $affectedUser
616
+     * @param int $fileId
617
+     * @param string $filePath
618
+     */
619
+    protected function publishActivity($subject,
620
+                                        array $parameters,
621
+                                        $affectedUser,
622
+                                        $fileId,
623
+                                        $filePath) {
624
+
625
+        $event = $this->activityManager->generateEvent();
626
+        $event->setApp('files_sharing')
627
+            ->setType('public_links')
628
+            ->setSubject($subject, $parameters)
629
+            ->setAffectedUser($affectedUser)
630
+            ->setObject('files', $fileId, $filePath);
631
+        $this->activityManager->publish($event);
632
+    }
633 633
 
634 634
 
635 635
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	public function showAuthenticate($token) {
151 151
 		$share = $this->shareManager->getShareByToken($token);
152 152
 
153
-		if($this->linkShareAuth($share)) {
153
+		if ($this->linkShareAuth($share)) {
154 154
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
155 155
 		}
156 156
 
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 
179 179
 		$authenticate = $this->linkShareAuth($share, $password);
180 180
 
181
-		if($authenticate === true) {
181
+		if ($authenticate === true) {
182 182
 			return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.showShare', array('token' => $token)));
183 183
 		}
184 184
 
@@ -201,15 +201,15 @@  discard block
 block discarded – undo
201 201
 	private function linkShareAuth(\OCP\Share\IShare $share, $password = null) {
202 202
 		if ($password !== null) {
203 203
 			if ($this->shareManager->checkPassword($share, $password)) {
204
-				$this->session->set('public_link_authenticated', (string)$share->getId());
204
+				$this->session->set('public_link_authenticated', (string) $share->getId());
205 205
 			} else {
206 206
 				$this->emitAccessShareHook($share, 403, 'Wrong password');
207 207
 				return false;
208 208
 			}
209 209
 		} else {
210 210
 			// not authenticated ?
211
-			if ( ! $this->session->exists('public_link_authenticated')
212
-				|| $this->session->get('public_link_authenticated') !== (string)$share->getId()) {
211
+			if (!$this->session->exists('public_link_authenticated')
212
+				|| $this->session->get('public_link_authenticated') !== (string) $share->getId()) {
213 213
 				return false;
214 214
 			}
215 215
 		}
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		$itemType = $itemSource = $uidOwner = '';
231 231
 		$token = $share;
232 232
 		$exception = null;
233
-		if($share instanceof \OCP\Share\IShare) {
233
+		if ($share instanceof \OCP\Share\IShare) {
234 234
 			try {
235 235
 				$token = $share->getToken();
236 236
 				$uidOwner = $share->getSharedBy();
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 			'errorCode' => $errorCode,
250 250
 			'errorMessage' => $errorMessage,
251 251
 		]);
252
-		if(!is_null($exception)) {
252
+		if (!is_null($exception)) {
253 253
 			throw $exception;
254 254
 		}
255 255
 	}
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 		$shareTmpl['previewURL'] = $shareTmpl['downloadURL'];
376 376
 		$ogPreview = '';
377 377
 		if ($shareTmpl['previewSupported']) {
378
-			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute( 'files_sharing.PublicPreview.getPreview',
378
+			$shareTmpl['previewImage'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.PublicPreview.getPreview',
379 379
 				['x' => 200, 'y' => 200, 'file' => $shareTmpl['directory_path'], 't' => $shareTmpl['dirToken']]);
380 380
 			$ogPreview = $shareTmpl['previewImage'];
381 381
 
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
 
413 413
 		// OpenGraph Support: http://ogp.me/
414 414
 		\OCP\Util::addHeader('meta', ['property' => "og:title", 'content' => $shareTmpl['filename']]);
415
-		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName() . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : '')]);
415
+		\OCP\Util::addHeader('meta', ['property' => "og:description", 'content' => $this->defaults->getName().($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : '')]);
416 416
 		\OCP\Util::addHeader('meta', ['property' => "og:site_name", 'content' => $this->defaults->getName()]);
417 417
 		\OCP\Util::addHeader('meta', ['property' => "og:url", 'content' => $shareTmpl['shareUrl']]);
418 418
 		\OCP\Util::addHeader('meta', ['property' => "og:type", 'content' => "object"]);
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 
447 447
 		$share = $this->shareManager->getShareByToken($token);
448 448
 
449
-		if(!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
449
+		if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
450 450
 			return new \OCP\AppFramework\Http\DataResponse('Share is read-only');
451 451
 		}
452 452
 
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
 
529 529
 		$this->emitAccessShareHook($share);
530 530
 
531
-		$server_params = array( 'head' => $this->request->getMethod() === 'HEAD' );
531
+		$server_params = array('head' => $this->request->getMethod() === 'HEAD');
532 532
 
533 533
 		/**
534 534
 		 * Http range requests support
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -225,7 +225,7 @@
 block discarded – undo
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
 	 */
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -335,7 +335,7 @@
 block discarded – undo
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);
Please login to merge, or discard this patch.
Indentation   +782 added lines, -782 removed lines patch added patch discarded remove patch
@@ -49,786 +49,786 @@
 block discarded – undo
49 49
 
50 50
 class UsersController extends OCSController {
51 51
 
52
-	/** @var IUserManager */
53
-	private $userManager;
54
-	/** @var IConfig */
55
-	private $config;
56
-	/** @var IAppManager */
57
-	private $appManager;
58
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
59
-	private $groupManager;
60
-	/** @var IUserSession */
61
-	private $userSession;
62
-	/** @var AccountManager */
63
-	private $accountManager;
64
-	/** @var ILogger */
65
-	private $logger;
66
-	/** @var IFactory */
67
-	private $l10nFactory;
68
-	/** @var NewUserMailHelper */
69
-	private $newUserMailHelper;
70
-
71
-	/**
72
-	 * @param string $appName
73
-	 * @param IRequest $request
74
-	 * @param IUserManager $userManager
75
-	 * @param IConfig $config
76
-	 * @param IAppManager $appManager
77
-	 * @param IGroupManager $groupManager
78
-	 * @param IUserSession $userSession
79
-	 * @param AccountManager $accountManager
80
-	 * @param ILogger $logger
81
-	 * @param IFactory $l10nFactory
82
-	 * @param NewUserMailHelper $newUserMailHelper
83
-	 */
84
-	public function __construct($appName,
85
-								IRequest $request,
86
-								IUserManager $userManager,
87
-								IConfig $config,
88
-								IAppManager $appManager,
89
-								IGroupManager $groupManager,
90
-								IUserSession $userSession,
91
-								AccountManager $accountManager,
92
-								ILogger $logger,
93
-								IFactory $l10nFactory,
94
-								NewUserMailHelper $newUserMailHelper) {
95
-		parent::__construct($appName, $request);
96
-
97
-		$this->userManager = $userManager;
98
-		$this->config = $config;
99
-		$this->appManager = $appManager;
100
-		$this->groupManager = $groupManager;
101
-		$this->userSession = $userSession;
102
-		$this->accountManager = $accountManager;
103
-		$this->logger = $logger;
104
-		$this->l10nFactory = $l10nFactory;
105
-		$this->newUserMailHelper = $newUserMailHelper;
106
-	}
107
-
108
-	/**
109
-	 * @NoAdminRequired
110
-	 *
111
-	 * returns a list of users
112
-	 *
113
-	 * @param string $search
114
-	 * @param int $limit
115
-	 * @param int $offset
116
-	 * @return DataResponse
117
-	 */
118
-	public function getUsers($search = '', $limit = null, $offset = null) {
119
-		$user = $this->userSession->getUser();
120
-		$users = [];
121
-
122
-		// Admin? Or SubAdmin?
123
-		$uid = $user->getUID();
124
-		$subAdminManager = $this->groupManager->getSubAdmin();
125
-		if($this->groupManager->isAdmin($uid)){
126
-			$users = $this->userManager->search($search, $limit, $offset);
127
-		} else if ($subAdminManager->isSubAdmin($user)) {
128
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
129
-			foreach ($subAdminOfGroups as $key => $group) {
130
-				$subAdminOfGroups[$key] = $group->getGID();
131
-			}
132
-
133
-			if($offset === null) {
134
-				$offset = 0;
135
-			}
136
-
137
-			$users = [];
138
-			foreach ($subAdminOfGroups as $group) {
139
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
140
-			}
141
-
142
-			$users = array_slice($users, $offset, $limit);
143
-		}
144
-
145
-		$users = array_keys($users);
146
-
147
-		return new DataResponse([
148
-			'users' => $users
149
-		]);
150
-	}
151
-
152
-	/**
153
-	 * @PasswordConfirmationRequired
154
-	 * @NoAdminRequired
155
-	 *
156
-	 * @param string $userid
157
-	 * @param string $password
158
-	 * @param array $groups
159
-	 * @return DataResponse
160
-	 * @throws OCSException
161
-	 */
162
-	public function addUser($userid, $password, $groups = null) {
163
-		$user = $this->userSession->getUser();
164
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
165
-		$subAdminManager = $this->groupManager->getSubAdmin();
166
-
167
-		if($this->userManager->userExists($userid)) {
168
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
169
-			throw new OCSException('User already exists', 102);
170
-		}
171
-
172
-		if(is_array($groups)) {
173
-			foreach ($groups as $group) {
174
-				if(!$this->groupManager->groupExists($group)) {
175
-					throw new OCSException('group '.$group.' does not exist', 104);
176
-				}
177
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
-					throw new OCSException('insufficient privileges for group '. $group, 105);
179
-				}
180
-			}
181
-		} else {
182
-			if(!$isAdmin) {
183
-				throw new OCSException('no group specified (required for subadmins)', 106);
184
-			}
185
-		}
186
-
187
-		try {
188
-			$newUser = $this->userManager->createUser($userid, $password);
189
-			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
190
-
191
-			if (is_array($groups)) {
192
-				foreach ($groups as $group) {
193
-					$this->groupManager->get($group)->addUser($newUser);
194
-					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
195
-				}
196
-			}
197
-			return new DataResponse();
198
-		} catch (\Exception $e) {
199
-			$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
200
-			throw new OCSException('Bad request', 101);
201
-		}
202
-	}
203
-
204
-	/**
205
-	 * @NoAdminRequired
206
-	 * @NoSubAdminRequired
207
-	 *
208
-	 * gets user info
209
-	 *
210
-	 * @param string $userId
211
-	 * @return DataResponse
212
-	 * @throws OCSException
213
-	 */
214
-	public function getUser($userId) {
215
-		$data = $this->getUserData($userId);
216
-		return new DataResponse($data);
217
-	}
218
-
219
-	/**
220
-	 * @NoAdminRequired
221
-	 * @NoSubAdminRequired
222
-	 *
223
-	 * gets user info from the currently logged in user
224
-	 *
225
-	 * @return DataResponse
226
-	 * @throws OCSException
227
-	 */
228
-	public function getCurrentUser() {
229
-		$user = $this->userSession->getUser();
230
-		if ($user) {
231
-			$data =  $this->getUserData($user->getUID());
232
-			// rename "displayname" to "display-name" only for this call to keep
233
-			// the API stable.
234
-			$data['display-name'] = $data['displayname'];
235
-			unset($data['displayname']);
236
-			return new DataResponse($data);
237
-
238
-		}
239
-
240
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
241
-	}
242
-
243
-	/**
244
-	 * creates a array with all user data
245
-	 *
246
-	 * @param $userId
247
-	 * @return array
248
-	 * @throws OCSException
249
-	 */
250
-	protected function getUserData($userId) {
251
-		$currentLoggedInUser = $this->userSession->getUser();
252
-
253
-		$data = [];
254
-
255
-		// Check if the target user exists
256
-		$targetUserObject = $this->userManager->get($userId);
257
-		if($targetUserObject === null) {
258
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
259
-		}
260
-
261
-		// Admin? Or SubAdmin?
262
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
264
-			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
265
-		} else {
266
-			// Check they are looking up themselves
267
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
269
-			}
270
-		}
271
-
272
-		$userAccount = $this->accountManager->getUser($targetUserObject);
273
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
274
-		$gids = [];
275
-		foreach ($groups as $group) {
276
-			$gids[] = $group->getDisplayName();
277
-		}
278
-
279
-		// Find the data
280
-		$data['id'] = $targetUserObject->getUID();
281
-		$data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
282
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
283
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
284
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
285
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
286
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
287
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
288
-		$data['groups'] = $gids;
289
-		$data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
290
-
291
-		return $data;
292
-	}
293
-
294
-	/**
295
-	 * @NoAdminRequired
296
-	 * @NoSubAdminRequired
297
-	 * @PasswordConfirmationRequired
298
-	 *
299
-	 * edit users
300
-	 *
301
-	 * @param string $userId
302
-	 * @param string $key
303
-	 * @param string $value
304
-	 * @return DataResponse
305
-	 * @throws OCSException
306
-	 * @throws OCSForbiddenException
307
-	 */
308
-	public function editUser($userId, $key, $value) {
309
-		$currentLoggedInUser = $this->userSession->getUser();
310
-
311
-		$targetUser = $this->userManager->get($userId);
312
-		if($targetUser === null) {
313
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
314
-		}
315
-
316
-		$permittedFields = [];
317
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
318
-			// Editing self (display, email)
319
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
320
-				$permittedFields[] = 'display';
321
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
322
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
323
-			}
324
-
325
-			$permittedFields[] = 'password';
326
-			if ($this->config->getSystemValue('force_language', false) === false ||
327
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
328
-				$permittedFields[] = 'language';
329
-			}
330
-
331
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
332
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
333
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
334
-				if ($shareProvider->isLookupServerUploadEnabled()) {
335
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
336
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
337
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
338
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
339
-				}
340
-			}
341
-
342
-			// If admin they can edit their own quota
343
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344
-				$permittedFields[] = 'quota';
345
-			}
346
-		} else {
347
-			// Check if admin / subadmin
348
-			$subAdminManager = $this->groupManager->getSubAdmin();
349
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
351
-				// They have permissions over the user
352
-				$permittedFields[] = 'display';
353
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
354
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
355
-				$permittedFields[] = 'password';
356
-				$permittedFields[] = 'language';
357
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
358
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
359
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
360
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
361
-				$permittedFields[] = 'quota';
362
-			} else {
363
-				// No rights
364
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
365
-			}
366
-		}
367
-		// Check if permitted to edit this field
368
-		if(!in_array($key, $permittedFields)) {
369
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370
-		}
371
-		// Process the edit
372
-		switch($key) {
373
-			case 'display':
374
-			case AccountManager::PROPERTY_DISPLAYNAME:
375
-				$targetUser->setDisplayName($value);
376
-				break;
377
-			case 'quota':
378
-				$quota = $value;
379
-				if($quota !== 'none' && $quota !== 'default') {
380
-					if (is_numeric($quota)) {
381
-						$quota = (float) $quota;
382
-					} else {
383
-						$quota = \OCP\Util::computerFileSize($quota);
384
-					}
385
-					if ($quota === false) {
386
-						throw new OCSException('Invalid quota value '.$value, 103);
387
-					}
388
-					if($quota === 0) {
389
-						$quota = 'default';
390
-					}else if($quota === -1) {
391
-						$quota = 'none';
392
-					} else {
393
-						$quota = \OCP\Util::humanFileSize($quota);
394
-					}
395
-				}
396
-				$targetUser->setQuota($quota);
397
-				break;
398
-			case 'password':
399
-				$targetUser->setPassword($value);
400
-				break;
401
-			case 'language':
402
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
403
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
404
-					throw new OCSException('Invalid language', 102);
405
-				}
406
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
407
-				break;
408
-			case AccountManager::PROPERTY_EMAIL:
409
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
410
-					$targetUser->setEMailAddress($value);
411
-				} else {
412
-					throw new OCSException('', 102);
413
-				}
414
-				break;
415
-			case AccountManager::PROPERTY_PHONE:
416
-			case AccountManager::PROPERTY_ADDRESS:
417
-			case AccountManager::PROPERTY_WEBSITE:
418
-			case AccountManager::PROPERTY_TWITTER:
419
-				$userAccount = $this->accountManager->getUser($targetUser);
420
-				if ($userAccount[$key]['value'] !== $value) {
421
-					$userAccount[$key]['value'] = $value;
422
-					$this->accountManager->updateUser($targetUser, $userAccount);
423
-				}
424
-				break;
425
-			default:
426
-				throw new OCSException('', 103);
427
-		}
428
-		return new DataResponse();
429
-	}
430
-
431
-	/**
432
-	 * @PasswordConfirmationRequired
433
-	 * @NoAdminRequired
434
-	 *
435
-	 * @param string $userId
436
-	 * @return DataResponse
437
-	 * @throws OCSException
438
-	 * @throws OCSForbiddenException
439
-	 */
440
-	public function deleteUser($userId) {
441
-		$currentLoggedInUser = $this->userSession->getUser();
442
-
443
-		$targetUser = $this->userManager->get($userId);
444
-
445
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
446
-			throw new OCSException('', 101);
447
-		}
448
-
449
-		// If not permitted
450
-		$subAdminManager = $this->groupManager->getSubAdmin();
451
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
452
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
453
-		}
454
-
455
-		// Go ahead with the delete
456
-		if($targetUser->delete()) {
457
-			return new DataResponse();
458
-		} else {
459
-			throw new OCSException('', 101);
460
-		}
461
-	}
462
-
463
-	/**
464
-	 * @PasswordConfirmationRequired
465
-	 * @NoAdminRequired
466
-	 *
467
-	 * @param string $userId
468
-	 * @return DataResponse
469
-	 * @throws OCSException
470
-	 * @throws OCSForbiddenException
471
-	 */
472
-	public function disableUser($userId) {
473
-		return $this->setEnabled($userId, false);
474
-	}
475
-
476
-	/**
477
-	 * @PasswordConfirmationRequired
478
-	 * @NoAdminRequired
479
-	 *
480
-	 * @param string $userId
481
-	 * @return DataResponse
482
-	 * @throws OCSException
483
-	 * @throws OCSForbiddenException
484
-	 */
485
-	public function enableUser($userId) {
486
-		return $this->setEnabled($userId, true);
487
-	}
488
-
489
-	/**
490
-	 * @param string $userId
491
-	 * @param bool $value
492
-	 * @return DataResponse
493
-	 * @throws OCSException
494
-	 * @throws OCSForbiddenException
495
-	 */
496
-	private function setEnabled($userId, $value) {
497
-		$currentLoggedInUser = $this->userSession->getUser();
498
-
499
-		$targetUser = $this->userManager->get($userId);
500
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
501
-			throw new OCSException('', 101);
502
-		}
503
-
504
-		// If not permitted
505
-		$subAdminManager = $this->groupManager->getSubAdmin();
506
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
507
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
508
-		}
509
-
510
-		// enable/disable the user now
511
-		$targetUser->setEnabled($value);
512
-		return new DataResponse();
513
-	}
514
-
515
-	/**
516
-	 * @NoAdminRequired
517
-	 * @NoSubAdminRequired
518
-	 *
519
-	 * @param string $userId
520
-	 * @return DataResponse
521
-	 * @throws OCSException
522
-	 */
523
-	public function getUsersGroups($userId) {
524
-		$loggedInUser = $this->userSession->getUser();
525
-
526
-		$targetUser = $this->userManager->get($userId);
527
-		if($targetUser === null) {
528
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
529
-		}
530
-
531
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
532
-			// Self lookup or admin lookup
533
-			return new DataResponse([
534
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
535
-			]);
536
-		} else {
537
-			$subAdminManager = $this->groupManager->getSubAdmin();
538
-
539
-			// Looking up someone else
540
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
541
-				// Return the group that the method caller is subadmin of for the user in question
542
-				/** @var IGroup[] $getSubAdminsGroups */
543
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
544
-				foreach ($getSubAdminsGroups as $key => $group) {
545
-					$getSubAdminsGroups[$key] = $group->getGID();
546
-				}
547
-				$groups = array_intersect(
548
-					$getSubAdminsGroups,
549
-					$this->groupManager->getUserGroupIds($targetUser)
550
-				);
551
-				return new DataResponse(['groups' => $groups]);
552
-			} else {
553
-				// Not permitted
554
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
555
-			}
556
-		}
557
-
558
-	}
559
-
560
-	/**
561
-	 * @PasswordConfirmationRequired
562
-	 * @NoAdminRequired
563
-	 *
564
-	 * @param string $userId
565
-	 * @param string $groupid
566
-	 * @return DataResponse
567
-	 * @throws OCSException
568
-	 */
569
-	public function addToGroup($userId, $groupid = '') {
570
-		if($groupid === '') {
571
-			throw new OCSException('', 101);
572
-		}
573
-
574
-		$group = $this->groupManager->get($groupid);
575
-		$targetUser = $this->userManager->get($userId);
576
-		if($group === null) {
577
-			throw new OCSException('', 102);
578
-		}
579
-		if($targetUser === null) {
580
-			throw new OCSException('', 103);
581
-		}
582
-
583
-		// If they're not an admin, check they are a subadmin of the group in question
584
-		$loggedInUser = $this->userSession->getUser();
585
-		$subAdminManager = $this->groupManager->getSubAdmin();
586
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
587
-			throw new OCSException('', 104);
588
-		}
589
-
590
-		// Add user to group
591
-		$group->addUser($targetUser);
592
-		return new DataResponse();
593
-	}
594
-
595
-	/**
596
-	 * @PasswordConfirmationRequired
597
-	 * @NoAdminRequired
598
-	 *
599
-	 * @param string $userId
600
-	 * @param string $groupid
601
-	 * @return DataResponse
602
-	 * @throws OCSException
603
-	 */
604
-	public function removeFromGroup($userId, $groupid) {
605
-		$loggedInUser = $this->userSession->getUser();
606
-
607
-		if($groupid === null || trim($groupid) === '') {
608
-			throw new OCSException('', 101);
609
-		}
610
-
611
-		$group = $this->groupManager->get($groupid);
612
-		if($group === null) {
613
-			throw new OCSException('', 102);
614
-		}
615
-
616
-		$targetUser = $this->userManager->get($userId);
617
-		if($targetUser === null) {
618
-			throw new OCSException('', 103);
619
-		}
620
-
621
-		// If they're not an admin, check they are a subadmin of the group in question
622
-		$subAdminManager = $this->groupManager->getSubAdmin();
623
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
624
-			throw new OCSException('', 104);
625
-		}
626
-
627
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
628
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
629
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
630
-				if ($group->getGID() === 'admin') {
631
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
632
-				}
633
-			} else {
634
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
635
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
636
-			}
637
-
638
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
639
-			/** @var IGroup[] $subAdminGroups */
640
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
641
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
642
-				return $subAdminGroup->getGID();
643
-			}, $subAdminGroups);
644
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
645
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
646
-
647
-			if (count($userSubAdminGroups) <= 1) {
648
-				// Subadmin must not be able to remove a user from all their subadmin groups.
649
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
650
-			}
651
-		}
652
-
653
-		// Remove user from group
654
-		$group->removeUser($targetUser);
655
-		return new DataResponse();
656
-	}
657
-
658
-	/**
659
-	 * Creates a subadmin
660
-	 *
661
-	 * @PasswordConfirmationRequired
662
-	 *
663
-	 * @param string $userId
664
-	 * @param string $groupid
665
-	 * @return DataResponse
666
-	 * @throws OCSException
667
-	 */
668
-	public function addSubAdmin($userId, $groupid) {
669
-		$group = $this->groupManager->get($groupid);
670
-		$user = $this->userManager->get($userId);
671
-
672
-		// Check if the user exists
673
-		if($user === null) {
674
-			throw new OCSException('User does not exist', 101);
675
-		}
676
-		// Check if group exists
677
-		if($group === null) {
678
-			throw new OCSException('Group does not exist',  102);
679
-		}
680
-		// Check if trying to make subadmin of admin group
681
-		if($group->getGID() === 'admin') {
682
-			throw new OCSException('Cannot create subadmins for admin group', 103);
683
-		}
684
-
685
-		$subAdminManager = $this->groupManager->getSubAdmin();
686
-
687
-		// We cannot be subadmin twice
688
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
689
-			return new DataResponse();
690
-		}
691
-		// Go
692
-		if($subAdminManager->createSubAdmin($user, $group)) {
693
-			return new DataResponse();
694
-		} else {
695
-			throw new OCSException('Unknown error occurred', 103);
696
-		}
697
-	}
698
-
699
-	/**
700
-	 * Removes a subadmin from a group
701
-	 *
702
-	 * @PasswordConfirmationRequired
703
-	 *
704
-	 * @param string $userId
705
-	 * @param string $groupid
706
-	 * @return DataResponse
707
-	 * @throws OCSException
708
-	 */
709
-	public function removeSubAdmin($userId, $groupid) {
710
-		$group = $this->groupManager->get($groupid);
711
-		$user = $this->userManager->get($userId);
712
-		$subAdminManager = $this->groupManager->getSubAdmin();
713
-
714
-		// Check if the user exists
715
-		if($user === null) {
716
-			throw new OCSException('User does not exist', 101);
717
-		}
718
-		// Check if the group exists
719
-		if($group === null) {
720
-			throw new OCSException('Group does not exist', 101);
721
-		}
722
-		// Check if they are a subadmin of this said group
723
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
724
-			throw new OCSException('User is not a subadmin of this group', 102);
725
-		}
726
-
727
-		// Go
728
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
729
-			return new DataResponse();
730
-		} else {
731
-			throw new OCSException('Unknown error occurred', 103);
732
-		}
733
-	}
734
-
735
-	/**
736
-	 * Get the groups a user is a subadmin of
737
-	 *
738
-	 * @param string $userId
739
-	 * @return DataResponse
740
-	 * @throws OCSException
741
-	 */
742
-	public function getUserSubAdminGroups($userId) {
743
-		$user = $this->userManager->get($userId);
744
-		// Check if the user exists
745
-		if($user === null) {
746
-			throw new OCSException('User does not exist', 101);
747
-		}
748
-
749
-		// Get the subadmin groups
750
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
751
-		foreach ($groups as $key => $group) {
752
-			$groups[$key] = $group->getGID();
753
-		}
754
-
755
-		if(!$groups) {
756
-			throw new OCSException('Unknown error occurred', 102);
757
-		} else {
758
-			return new DataResponse($groups);
759
-		}
760
-	}
761
-
762
-	/**
763
-	 * @param string $userId
764
-	 * @return array
765
-	 * @throws \OCP\Files\NotFoundException
766
-	 */
767
-	protected function fillStorageInfo($userId) {
768
-		try {
769
-			\OC_Util::tearDownFS();
770
-			\OC_Util::setupFS($userId);
771
-			$storage = OC_Helper::getStorageInfo('/');
772
-			$data = [
773
-				'free' => $storage['free'],
774
-				'used' => $storage['used'],
775
-				'total' => $storage['total'],
776
-				'relative' => $storage['relative'],
777
-				'quota' => $storage['quota'],
778
-			];
779
-		} catch (NotFoundException $ex) {
780
-			$data = [];
781
-		}
782
-		return $data;
783
-	}
784
-
785
-	/**
786
-	 * @NoAdminRequired
787
-	 * @PasswordConfirmationRequired
788
-	 *
789
-	 * resend welcome message
790
-	 *
791
-	 * @param string $userId
792
-	 * @return DataResponse
793
-	 * @throws OCSException
794
-	 */
795
-	public function resendWelcomeMessage($userId) {
796
-		$currentLoggedInUser = $this->userSession->getUser();
797
-
798
-		$targetUser = $this->userManager->get($userId);
799
-		if($targetUser === null) {
800
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
801
-		}
802
-
803
-		// Check if admin / subadmin
804
-		$subAdminManager = $this->groupManager->getSubAdmin();
805
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
806
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
807
-			// No rights
808
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
809
-		}
810
-
811
-		$email = $targetUser->getEMailAddress();
812
-		if ($email === '' || $email === null) {
813
-			throw new OCSException('Email address not available', 101);
814
-		}
815
-		$username = $targetUser->getUID();
816
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
817
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
818
-			$lang = 'en';
819
-		}
820
-
821
-		$l10n = $this->l10nFactory->get('settings', $lang);
822
-
823
-		try {
824
-			$this->newUserMailHelper->setL10N($l10n);
825
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
826
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
827
-		} catch(\Exception $e) {
828
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
829
-			throw new OCSException('Sending email failed', 102);
830
-		}
831
-
832
-		return new DataResponse();
833
-	}
52
+    /** @var IUserManager */
53
+    private $userManager;
54
+    /** @var IConfig */
55
+    private $config;
56
+    /** @var IAppManager */
57
+    private $appManager;
58
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
59
+    private $groupManager;
60
+    /** @var IUserSession */
61
+    private $userSession;
62
+    /** @var AccountManager */
63
+    private $accountManager;
64
+    /** @var ILogger */
65
+    private $logger;
66
+    /** @var IFactory */
67
+    private $l10nFactory;
68
+    /** @var NewUserMailHelper */
69
+    private $newUserMailHelper;
70
+
71
+    /**
72
+     * @param string $appName
73
+     * @param IRequest $request
74
+     * @param IUserManager $userManager
75
+     * @param IConfig $config
76
+     * @param IAppManager $appManager
77
+     * @param IGroupManager $groupManager
78
+     * @param IUserSession $userSession
79
+     * @param AccountManager $accountManager
80
+     * @param ILogger $logger
81
+     * @param IFactory $l10nFactory
82
+     * @param NewUserMailHelper $newUserMailHelper
83
+     */
84
+    public function __construct($appName,
85
+                                IRequest $request,
86
+                                IUserManager $userManager,
87
+                                IConfig $config,
88
+                                IAppManager $appManager,
89
+                                IGroupManager $groupManager,
90
+                                IUserSession $userSession,
91
+                                AccountManager $accountManager,
92
+                                ILogger $logger,
93
+                                IFactory $l10nFactory,
94
+                                NewUserMailHelper $newUserMailHelper) {
95
+        parent::__construct($appName, $request);
96
+
97
+        $this->userManager = $userManager;
98
+        $this->config = $config;
99
+        $this->appManager = $appManager;
100
+        $this->groupManager = $groupManager;
101
+        $this->userSession = $userSession;
102
+        $this->accountManager = $accountManager;
103
+        $this->logger = $logger;
104
+        $this->l10nFactory = $l10nFactory;
105
+        $this->newUserMailHelper = $newUserMailHelper;
106
+    }
107
+
108
+    /**
109
+     * @NoAdminRequired
110
+     *
111
+     * returns a list of users
112
+     *
113
+     * @param string $search
114
+     * @param int $limit
115
+     * @param int $offset
116
+     * @return DataResponse
117
+     */
118
+    public function getUsers($search = '', $limit = null, $offset = null) {
119
+        $user = $this->userSession->getUser();
120
+        $users = [];
121
+
122
+        // Admin? Or SubAdmin?
123
+        $uid = $user->getUID();
124
+        $subAdminManager = $this->groupManager->getSubAdmin();
125
+        if($this->groupManager->isAdmin($uid)){
126
+            $users = $this->userManager->search($search, $limit, $offset);
127
+        } else if ($subAdminManager->isSubAdmin($user)) {
128
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
129
+            foreach ($subAdminOfGroups as $key => $group) {
130
+                $subAdminOfGroups[$key] = $group->getGID();
131
+            }
132
+
133
+            if($offset === null) {
134
+                $offset = 0;
135
+            }
136
+
137
+            $users = [];
138
+            foreach ($subAdminOfGroups as $group) {
139
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
140
+            }
141
+
142
+            $users = array_slice($users, $offset, $limit);
143
+        }
144
+
145
+        $users = array_keys($users);
146
+
147
+        return new DataResponse([
148
+            'users' => $users
149
+        ]);
150
+    }
151
+
152
+    /**
153
+     * @PasswordConfirmationRequired
154
+     * @NoAdminRequired
155
+     *
156
+     * @param string $userid
157
+     * @param string $password
158
+     * @param array $groups
159
+     * @return DataResponse
160
+     * @throws OCSException
161
+     */
162
+    public function addUser($userid, $password, $groups = null) {
163
+        $user = $this->userSession->getUser();
164
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
165
+        $subAdminManager = $this->groupManager->getSubAdmin();
166
+
167
+        if($this->userManager->userExists($userid)) {
168
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
169
+            throw new OCSException('User already exists', 102);
170
+        }
171
+
172
+        if(is_array($groups)) {
173
+            foreach ($groups as $group) {
174
+                if(!$this->groupManager->groupExists($group)) {
175
+                    throw new OCSException('group '.$group.' does not exist', 104);
176
+                }
177
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
179
+                }
180
+            }
181
+        } else {
182
+            if(!$isAdmin) {
183
+                throw new OCSException('no group specified (required for subadmins)', 106);
184
+            }
185
+        }
186
+
187
+        try {
188
+            $newUser = $this->userManager->createUser($userid, $password);
189
+            $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
190
+
191
+            if (is_array($groups)) {
192
+                foreach ($groups as $group) {
193
+                    $this->groupManager->get($group)->addUser($newUser);
194
+                    $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
195
+                }
196
+            }
197
+            return new DataResponse();
198
+        } catch (\Exception $e) {
199
+            $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
200
+            throw new OCSException('Bad request', 101);
201
+        }
202
+    }
203
+
204
+    /**
205
+     * @NoAdminRequired
206
+     * @NoSubAdminRequired
207
+     *
208
+     * gets user info
209
+     *
210
+     * @param string $userId
211
+     * @return DataResponse
212
+     * @throws OCSException
213
+     */
214
+    public function getUser($userId) {
215
+        $data = $this->getUserData($userId);
216
+        return new DataResponse($data);
217
+    }
218
+
219
+    /**
220
+     * @NoAdminRequired
221
+     * @NoSubAdminRequired
222
+     *
223
+     * gets user info from the currently logged in user
224
+     *
225
+     * @return DataResponse
226
+     * @throws OCSException
227
+     */
228
+    public function getCurrentUser() {
229
+        $user = $this->userSession->getUser();
230
+        if ($user) {
231
+            $data =  $this->getUserData($user->getUID());
232
+            // rename "displayname" to "display-name" only for this call to keep
233
+            // the API stable.
234
+            $data['display-name'] = $data['displayname'];
235
+            unset($data['displayname']);
236
+            return new DataResponse($data);
237
+
238
+        }
239
+
240
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
241
+    }
242
+
243
+    /**
244
+     * creates a array with all user data
245
+     *
246
+     * @param $userId
247
+     * @return array
248
+     * @throws OCSException
249
+     */
250
+    protected function getUserData($userId) {
251
+        $currentLoggedInUser = $this->userSession->getUser();
252
+
253
+        $data = [];
254
+
255
+        // Check if the target user exists
256
+        $targetUserObject = $this->userManager->get($userId);
257
+        if($targetUserObject === null) {
258
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
259
+        }
260
+
261
+        // Admin? Or SubAdmin?
262
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
264
+            $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
265
+        } else {
266
+            // Check they are looking up themselves
267
+            if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
269
+            }
270
+        }
271
+
272
+        $userAccount = $this->accountManager->getUser($targetUserObject);
273
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
274
+        $gids = [];
275
+        foreach ($groups as $group) {
276
+            $gids[] = $group->getDisplayName();
277
+        }
278
+
279
+        // Find the data
280
+        $data['id'] = $targetUserObject->getUID();
281
+        $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
282
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
283
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
284
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
285
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
286
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
287
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
288
+        $data['groups'] = $gids;
289
+        $data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
290
+
291
+        return $data;
292
+    }
293
+
294
+    /**
295
+     * @NoAdminRequired
296
+     * @NoSubAdminRequired
297
+     * @PasswordConfirmationRequired
298
+     *
299
+     * edit users
300
+     *
301
+     * @param string $userId
302
+     * @param string $key
303
+     * @param string $value
304
+     * @return DataResponse
305
+     * @throws OCSException
306
+     * @throws OCSForbiddenException
307
+     */
308
+    public function editUser($userId, $key, $value) {
309
+        $currentLoggedInUser = $this->userSession->getUser();
310
+
311
+        $targetUser = $this->userManager->get($userId);
312
+        if($targetUser === null) {
313
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
314
+        }
315
+
316
+        $permittedFields = [];
317
+        if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
318
+            // Editing self (display, email)
319
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
320
+                $permittedFields[] = 'display';
321
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
322
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
323
+            }
324
+
325
+            $permittedFields[] = 'password';
326
+            if ($this->config->getSystemValue('force_language', false) === false ||
327
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
328
+                $permittedFields[] = 'language';
329
+            }
330
+
331
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
332
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
333
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
334
+                if ($shareProvider->isLookupServerUploadEnabled()) {
335
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
336
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
337
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
338
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
339
+                }
340
+            }
341
+
342
+            // If admin they can edit their own quota
343
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344
+                $permittedFields[] = 'quota';
345
+            }
346
+        } else {
347
+            // Check if admin / subadmin
348
+            $subAdminManager = $this->groupManager->getSubAdmin();
349
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
351
+                // They have permissions over the user
352
+                $permittedFields[] = 'display';
353
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
354
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
355
+                $permittedFields[] = 'password';
356
+                $permittedFields[] = 'language';
357
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
358
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
359
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
360
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
361
+                $permittedFields[] = 'quota';
362
+            } else {
363
+                // No rights
364
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
365
+            }
366
+        }
367
+        // Check if permitted to edit this field
368
+        if(!in_array($key, $permittedFields)) {
369
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370
+        }
371
+        // Process the edit
372
+        switch($key) {
373
+            case 'display':
374
+            case AccountManager::PROPERTY_DISPLAYNAME:
375
+                $targetUser->setDisplayName($value);
376
+                break;
377
+            case 'quota':
378
+                $quota = $value;
379
+                if($quota !== 'none' && $quota !== 'default') {
380
+                    if (is_numeric($quota)) {
381
+                        $quota = (float) $quota;
382
+                    } else {
383
+                        $quota = \OCP\Util::computerFileSize($quota);
384
+                    }
385
+                    if ($quota === false) {
386
+                        throw new OCSException('Invalid quota value '.$value, 103);
387
+                    }
388
+                    if($quota === 0) {
389
+                        $quota = 'default';
390
+                    }else if($quota === -1) {
391
+                        $quota = 'none';
392
+                    } else {
393
+                        $quota = \OCP\Util::humanFileSize($quota);
394
+                    }
395
+                }
396
+                $targetUser->setQuota($quota);
397
+                break;
398
+            case 'password':
399
+                $targetUser->setPassword($value);
400
+                break;
401
+            case 'language':
402
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
403
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
404
+                    throw new OCSException('Invalid language', 102);
405
+                }
406
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
407
+                break;
408
+            case AccountManager::PROPERTY_EMAIL:
409
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
410
+                    $targetUser->setEMailAddress($value);
411
+                } else {
412
+                    throw new OCSException('', 102);
413
+                }
414
+                break;
415
+            case AccountManager::PROPERTY_PHONE:
416
+            case AccountManager::PROPERTY_ADDRESS:
417
+            case AccountManager::PROPERTY_WEBSITE:
418
+            case AccountManager::PROPERTY_TWITTER:
419
+                $userAccount = $this->accountManager->getUser($targetUser);
420
+                if ($userAccount[$key]['value'] !== $value) {
421
+                    $userAccount[$key]['value'] = $value;
422
+                    $this->accountManager->updateUser($targetUser, $userAccount);
423
+                }
424
+                break;
425
+            default:
426
+                throw new OCSException('', 103);
427
+        }
428
+        return new DataResponse();
429
+    }
430
+
431
+    /**
432
+     * @PasswordConfirmationRequired
433
+     * @NoAdminRequired
434
+     *
435
+     * @param string $userId
436
+     * @return DataResponse
437
+     * @throws OCSException
438
+     * @throws OCSForbiddenException
439
+     */
440
+    public function deleteUser($userId) {
441
+        $currentLoggedInUser = $this->userSession->getUser();
442
+
443
+        $targetUser = $this->userManager->get($userId);
444
+
445
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
446
+            throw new OCSException('', 101);
447
+        }
448
+
449
+        // If not permitted
450
+        $subAdminManager = $this->groupManager->getSubAdmin();
451
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
452
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
453
+        }
454
+
455
+        // Go ahead with the delete
456
+        if($targetUser->delete()) {
457
+            return new DataResponse();
458
+        } else {
459
+            throw new OCSException('', 101);
460
+        }
461
+    }
462
+
463
+    /**
464
+     * @PasswordConfirmationRequired
465
+     * @NoAdminRequired
466
+     *
467
+     * @param string $userId
468
+     * @return DataResponse
469
+     * @throws OCSException
470
+     * @throws OCSForbiddenException
471
+     */
472
+    public function disableUser($userId) {
473
+        return $this->setEnabled($userId, false);
474
+    }
475
+
476
+    /**
477
+     * @PasswordConfirmationRequired
478
+     * @NoAdminRequired
479
+     *
480
+     * @param string $userId
481
+     * @return DataResponse
482
+     * @throws OCSException
483
+     * @throws OCSForbiddenException
484
+     */
485
+    public function enableUser($userId) {
486
+        return $this->setEnabled($userId, true);
487
+    }
488
+
489
+    /**
490
+     * @param string $userId
491
+     * @param bool $value
492
+     * @return DataResponse
493
+     * @throws OCSException
494
+     * @throws OCSForbiddenException
495
+     */
496
+    private function setEnabled($userId, $value) {
497
+        $currentLoggedInUser = $this->userSession->getUser();
498
+
499
+        $targetUser = $this->userManager->get($userId);
500
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
501
+            throw new OCSException('', 101);
502
+        }
503
+
504
+        // If not permitted
505
+        $subAdminManager = $this->groupManager->getSubAdmin();
506
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
507
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
508
+        }
509
+
510
+        // enable/disable the user now
511
+        $targetUser->setEnabled($value);
512
+        return new DataResponse();
513
+    }
514
+
515
+    /**
516
+     * @NoAdminRequired
517
+     * @NoSubAdminRequired
518
+     *
519
+     * @param string $userId
520
+     * @return DataResponse
521
+     * @throws OCSException
522
+     */
523
+    public function getUsersGroups($userId) {
524
+        $loggedInUser = $this->userSession->getUser();
525
+
526
+        $targetUser = $this->userManager->get($userId);
527
+        if($targetUser === null) {
528
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
529
+        }
530
+
531
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
532
+            // Self lookup or admin lookup
533
+            return new DataResponse([
534
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
535
+            ]);
536
+        } else {
537
+            $subAdminManager = $this->groupManager->getSubAdmin();
538
+
539
+            // Looking up someone else
540
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
541
+                // Return the group that the method caller is subadmin of for the user in question
542
+                /** @var IGroup[] $getSubAdminsGroups */
543
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
544
+                foreach ($getSubAdminsGroups as $key => $group) {
545
+                    $getSubAdminsGroups[$key] = $group->getGID();
546
+                }
547
+                $groups = array_intersect(
548
+                    $getSubAdminsGroups,
549
+                    $this->groupManager->getUserGroupIds($targetUser)
550
+                );
551
+                return new DataResponse(['groups' => $groups]);
552
+            } else {
553
+                // Not permitted
554
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
555
+            }
556
+        }
557
+
558
+    }
559
+
560
+    /**
561
+     * @PasswordConfirmationRequired
562
+     * @NoAdminRequired
563
+     *
564
+     * @param string $userId
565
+     * @param string $groupid
566
+     * @return DataResponse
567
+     * @throws OCSException
568
+     */
569
+    public function addToGroup($userId, $groupid = '') {
570
+        if($groupid === '') {
571
+            throw new OCSException('', 101);
572
+        }
573
+
574
+        $group = $this->groupManager->get($groupid);
575
+        $targetUser = $this->userManager->get($userId);
576
+        if($group === null) {
577
+            throw new OCSException('', 102);
578
+        }
579
+        if($targetUser === null) {
580
+            throw new OCSException('', 103);
581
+        }
582
+
583
+        // If they're not an admin, check they are a subadmin of the group in question
584
+        $loggedInUser = $this->userSession->getUser();
585
+        $subAdminManager = $this->groupManager->getSubAdmin();
586
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
587
+            throw new OCSException('', 104);
588
+        }
589
+
590
+        // Add user to group
591
+        $group->addUser($targetUser);
592
+        return new DataResponse();
593
+    }
594
+
595
+    /**
596
+     * @PasswordConfirmationRequired
597
+     * @NoAdminRequired
598
+     *
599
+     * @param string $userId
600
+     * @param string $groupid
601
+     * @return DataResponse
602
+     * @throws OCSException
603
+     */
604
+    public function removeFromGroup($userId, $groupid) {
605
+        $loggedInUser = $this->userSession->getUser();
606
+
607
+        if($groupid === null || trim($groupid) === '') {
608
+            throw new OCSException('', 101);
609
+        }
610
+
611
+        $group = $this->groupManager->get($groupid);
612
+        if($group === null) {
613
+            throw new OCSException('', 102);
614
+        }
615
+
616
+        $targetUser = $this->userManager->get($userId);
617
+        if($targetUser === null) {
618
+            throw new OCSException('', 103);
619
+        }
620
+
621
+        // If they're not an admin, check they are a subadmin of the group in question
622
+        $subAdminManager = $this->groupManager->getSubAdmin();
623
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
624
+            throw new OCSException('', 104);
625
+        }
626
+
627
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
628
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
629
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
630
+                if ($group->getGID() === 'admin') {
631
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
632
+                }
633
+            } else {
634
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
635
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
636
+            }
637
+
638
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
639
+            /** @var IGroup[] $subAdminGroups */
640
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
641
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
642
+                return $subAdminGroup->getGID();
643
+            }, $subAdminGroups);
644
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
645
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
646
+
647
+            if (count($userSubAdminGroups) <= 1) {
648
+                // Subadmin must not be able to remove a user from all their subadmin groups.
649
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
650
+            }
651
+        }
652
+
653
+        // Remove user from group
654
+        $group->removeUser($targetUser);
655
+        return new DataResponse();
656
+    }
657
+
658
+    /**
659
+     * Creates a subadmin
660
+     *
661
+     * @PasswordConfirmationRequired
662
+     *
663
+     * @param string $userId
664
+     * @param string $groupid
665
+     * @return DataResponse
666
+     * @throws OCSException
667
+     */
668
+    public function addSubAdmin($userId, $groupid) {
669
+        $group = $this->groupManager->get($groupid);
670
+        $user = $this->userManager->get($userId);
671
+
672
+        // Check if the user exists
673
+        if($user === null) {
674
+            throw new OCSException('User does not exist', 101);
675
+        }
676
+        // Check if group exists
677
+        if($group === null) {
678
+            throw new OCSException('Group does not exist',  102);
679
+        }
680
+        // Check if trying to make subadmin of admin group
681
+        if($group->getGID() === 'admin') {
682
+            throw new OCSException('Cannot create subadmins for admin group', 103);
683
+        }
684
+
685
+        $subAdminManager = $this->groupManager->getSubAdmin();
686
+
687
+        // We cannot be subadmin twice
688
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
689
+            return new DataResponse();
690
+        }
691
+        // Go
692
+        if($subAdminManager->createSubAdmin($user, $group)) {
693
+            return new DataResponse();
694
+        } else {
695
+            throw new OCSException('Unknown error occurred', 103);
696
+        }
697
+    }
698
+
699
+    /**
700
+     * Removes a subadmin from a group
701
+     *
702
+     * @PasswordConfirmationRequired
703
+     *
704
+     * @param string $userId
705
+     * @param string $groupid
706
+     * @return DataResponse
707
+     * @throws OCSException
708
+     */
709
+    public function removeSubAdmin($userId, $groupid) {
710
+        $group = $this->groupManager->get($groupid);
711
+        $user = $this->userManager->get($userId);
712
+        $subAdminManager = $this->groupManager->getSubAdmin();
713
+
714
+        // Check if the user exists
715
+        if($user === null) {
716
+            throw new OCSException('User does not exist', 101);
717
+        }
718
+        // Check if the group exists
719
+        if($group === null) {
720
+            throw new OCSException('Group does not exist', 101);
721
+        }
722
+        // Check if they are a subadmin of this said group
723
+        if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
724
+            throw new OCSException('User is not a subadmin of this group', 102);
725
+        }
726
+
727
+        // Go
728
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
729
+            return new DataResponse();
730
+        } else {
731
+            throw new OCSException('Unknown error occurred', 103);
732
+        }
733
+    }
734
+
735
+    /**
736
+     * Get the groups a user is a subadmin of
737
+     *
738
+     * @param string $userId
739
+     * @return DataResponse
740
+     * @throws OCSException
741
+     */
742
+    public function getUserSubAdminGroups($userId) {
743
+        $user = $this->userManager->get($userId);
744
+        // Check if the user exists
745
+        if($user === null) {
746
+            throw new OCSException('User does not exist', 101);
747
+        }
748
+
749
+        // Get the subadmin groups
750
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
751
+        foreach ($groups as $key => $group) {
752
+            $groups[$key] = $group->getGID();
753
+        }
754
+
755
+        if(!$groups) {
756
+            throw new OCSException('Unknown error occurred', 102);
757
+        } else {
758
+            return new DataResponse($groups);
759
+        }
760
+    }
761
+
762
+    /**
763
+     * @param string $userId
764
+     * @return array
765
+     * @throws \OCP\Files\NotFoundException
766
+     */
767
+    protected function fillStorageInfo($userId) {
768
+        try {
769
+            \OC_Util::tearDownFS();
770
+            \OC_Util::setupFS($userId);
771
+            $storage = OC_Helper::getStorageInfo('/');
772
+            $data = [
773
+                'free' => $storage['free'],
774
+                'used' => $storage['used'],
775
+                'total' => $storage['total'],
776
+                'relative' => $storage['relative'],
777
+                'quota' => $storage['quota'],
778
+            ];
779
+        } catch (NotFoundException $ex) {
780
+            $data = [];
781
+        }
782
+        return $data;
783
+    }
784
+
785
+    /**
786
+     * @NoAdminRequired
787
+     * @PasswordConfirmationRequired
788
+     *
789
+     * resend welcome message
790
+     *
791
+     * @param string $userId
792
+     * @return DataResponse
793
+     * @throws OCSException
794
+     */
795
+    public function resendWelcomeMessage($userId) {
796
+        $currentLoggedInUser = $this->userSession->getUser();
797
+
798
+        $targetUser = $this->userManager->get($userId);
799
+        if($targetUser === null) {
800
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
801
+        }
802
+
803
+        // Check if admin / subadmin
804
+        $subAdminManager = $this->groupManager->getSubAdmin();
805
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
806
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
807
+            // No rights
808
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
809
+        }
810
+
811
+        $email = $targetUser->getEMailAddress();
812
+        if ($email === '' || $email === null) {
813
+            throw new OCSException('Email address not available', 101);
814
+        }
815
+        $username = $targetUser->getUID();
816
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
817
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
818
+            $lang = 'en';
819
+        }
820
+
821
+        $l10n = $this->l10nFactory->get('settings', $lang);
822
+
823
+        try {
824
+            $this->newUserMailHelper->setL10N($l10n);
825
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
826
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
827
+        } catch(\Exception $e) {
828
+            $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
829
+            throw new OCSException('Sending email failed', 102);
830
+        }
831
+
832
+        return new DataResponse();
833
+    }
834 834
 }
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 		// Admin? Or SubAdmin?
123 123
 		$uid = $user->getUID();
124 124
 		$subAdminManager = $this->groupManager->getSubAdmin();
125
-		if($this->groupManager->isAdmin($uid)){
125
+		if ($this->groupManager->isAdmin($uid)) {
126 126
 			$users = $this->userManager->search($search, $limit, $offset);
127 127
 		} else if ($subAdminManager->isSubAdmin($user)) {
128 128
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 				$subAdminOfGroups[$key] = $group->getGID();
131 131
 			}
132 132
 
133
-			if($offset === null) {
133
+			if ($offset === null) {
134 134
 				$offset = 0;
135 135
 			}
136 136
 
@@ -164,22 +164,22 @@  discard block
 block discarded – undo
164 164
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
165 165
 		$subAdminManager = $this->groupManager->getSubAdmin();
166 166
 
167
-		if($this->userManager->userExists($userid)) {
167
+		if ($this->userManager->userExists($userid)) {
168 168
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
169 169
 			throw new OCSException('User already exists', 102);
170 170
 		}
171 171
 
172
-		if(is_array($groups)) {
172
+		if (is_array($groups)) {
173 173
 			foreach ($groups as $group) {
174
-				if(!$this->groupManager->groupExists($group)) {
174
+				if (!$this->groupManager->groupExists($group)) {
175 175
 					throw new OCSException('group '.$group.' does not exist', 104);
176 176
 				}
177
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
-					throw new OCSException('insufficient privileges for group '. $group, 105);
177
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
+					throw new OCSException('insufficient privileges for group '.$group, 105);
179 179
 				}
180 180
 			}
181 181
 		} else {
182
-			if(!$isAdmin) {
182
+			if (!$isAdmin) {
183 183
 				throw new OCSException('no group specified (required for subadmins)', 106);
184 184
 			}
185 185
 		}
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	public function getCurrentUser() {
229 229
 		$user = $this->userSession->getUser();
230 230
 		if ($user) {
231
-			$data =  $this->getUserData($user->getUID());
231
+			$data = $this->getUserData($user->getUID());
232 232
 			// rename "displayname" to "display-name" only for this call to keep
233 233
 			// the API stable.
234 234
 			$data['display-name'] = $data['displayname'];
@@ -254,17 +254,17 @@  discard block
 block discarded – undo
254 254
 
255 255
 		// Check if the target user exists
256 256
 		$targetUserObject = $this->userManager->get($userId);
257
-		if($targetUserObject === null) {
257
+		if ($targetUserObject === null) {
258 258
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
259 259
 		}
260 260
 
261 261
 		// Admin? Or SubAdmin?
262
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
262
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263 263
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
264 264
 			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
265 265
 		} else {
266 266
 			// Check they are looking up themselves
267
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
267
+			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268 268
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
269 269
 			}
270 270
 		}
@@ -309,12 +309,12 @@  discard block
 block discarded – undo
309 309
 		$currentLoggedInUser = $this->userSession->getUser();
310 310
 
311 311
 		$targetUser = $this->userManager->get($userId);
312
-		if($targetUser === null) {
312
+		if ($targetUser === null) {
313 313
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
314 314
 		}
315 315
 
316 316
 		$permittedFields = [];
317
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
317
+		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
318 318
 			// Editing self (display, email)
319 319
 			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
320 320
 				$permittedFields[] = 'display';
@@ -340,13 +340,13 @@  discard block
 block discarded – undo
340 340
 			}
341 341
 
342 342
 			// If admin they can edit their own quota
343
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
343
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344 344
 				$permittedFields[] = 'quota';
345 345
 			}
346 346
 		} else {
347 347
 			// Check if admin / subadmin
348 348
 			$subAdminManager = $this->groupManager->getSubAdmin();
349
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
349
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350 350
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
351 351
 				// They have permissions over the user
352 352
 				$permittedFields[] = 'display';
@@ -365,18 +365,18 @@  discard block
 block discarded – undo
365 365
 			}
366 366
 		}
367 367
 		// Check if permitted to edit this field
368
-		if(!in_array($key, $permittedFields)) {
368
+		if (!in_array($key, $permittedFields)) {
369 369
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370 370
 		}
371 371
 		// Process the edit
372
-		switch($key) {
372
+		switch ($key) {
373 373
 			case 'display':
374 374
 			case AccountManager::PROPERTY_DISPLAYNAME:
375 375
 				$targetUser->setDisplayName($value);
376 376
 				break;
377 377
 			case 'quota':
378 378
 				$quota = $value;
379
-				if($quota !== 'none' && $quota !== 'default') {
379
+				if ($quota !== 'none' && $quota !== 'default') {
380 380
 					if (is_numeric($quota)) {
381 381
 						$quota = (float) $quota;
382 382
 					} else {
@@ -385,9 +385,9 @@  discard block
 block discarded – undo
385 385
 					if ($quota === false) {
386 386
 						throw new OCSException('Invalid quota value '.$value, 103);
387 387
 					}
388
-					if($quota === 0) {
388
+					if ($quota === 0) {
389 389
 						$quota = 'default';
390
-					}else if($quota === -1) {
390
+					} else if ($quota === -1) {
391 391
 						$quota = 'none';
392 392
 					} else {
393 393
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
407 407
 				break;
408 408
 			case AccountManager::PROPERTY_EMAIL:
409
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
409
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
410 410
 					$targetUser->setEMailAddress($value);
411 411
 				} else {
412 412
 					throw new OCSException('', 102);
@@ -442,18 +442,18 @@  discard block
 block discarded – undo
442 442
 
443 443
 		$targetUser = $this->userManager->get($userId);
444 444
 
445
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
445
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
446 446
 			throw new OCSException('', 101);
447 447
 		}
448 448
 
449 449
 		// If not permitted
450 450
 		$subAdminManager = $this->groupManager->getSubAdmin();
451
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
451
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
452 452
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
453 453
 		}
454 454
 
455 455
 		// Go ahead with the delete
456
-		if($targetUser->delete()) {
456
+		if ($targetUser->delete()) {
457 457
 			return new DataResponse();
458 458
 		} else {
459 459
 			throw new OCSException('', 101);
@@ -497,13 +497,13 @@  discard block
 block discarded – undo
497 497
 		$currentLoggedInUser = $this->userSession->getUser();
498 498
 
499 499
 		$targetUser = $this->userManager->get($userId);
500
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
500
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
501 501
 			throw new OCSException('', 101);
502 502
 		}
503 503
 
504 504
 		// If not permitted
505 505
 		$subAdminManager = $this->groupManager->getSubAdmin();
506
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
506
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
507 507
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
508 508
 		}
509 509
 
@@ -524,11 +524,11 @@  discard block
 block discarded – undo
524 524
 		$loggedInUser = $this->userSession->getUser();
525 525
 
526 526
 		$targetUser = $this->userManager->get($userId);
527
-		if($targetUser === null) {
527
+		if ($targetUser === null) {
528 528
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
529 529
 		}
530 530
 
531
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
531
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
532 532
 			// Self lookup or admin lookup
533 533
 			return new DataResponse([
534 534
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
 			$subAdminManager = $this->groupManager->getSubAdmin();
538 538
 
539 539
 			// Looking up someone else
540
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
540
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
541 541
 				// Return the group that the method caller is subadmin of for the user in question
542 542
 				/** @var IGroup[] $getSubAdminsGroups */
543 543
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -567,16 +567,16 @@  discard block
 block discarded – undo
567 567
 	 * @throws OCSException
568 568
 	 */
569 569
 	public function addToGroup($userId, $groupid = '') {
570
-		if($groupid === '') {
570
+		if ($groupid === '') {
571 571
 			throw new OCSException('', 101);
572 572
 		}
573 573
 
574 574
 		$group = $this->groupManager->get($groupid);
575 575
 		$targetUser = $this->userManager->get($userId);
576
-		if($group === null) {
576
+		if ($group === null) {
577 577
 			throw new OCSException('', 102);
578 578
 		}
579
-		if($targetUser === null) {
579
+		if ($targetUser === null) {
580 580
 			throw new OCSException('', 103);
581 581
 		}
582 582
 
@@ -604,17 +604,17 @@  discard block
 block discarded – undo
604 604
 	public function removeFromGroup($userId, $groupid) {
605 605
 		$loggedInUser = $this->userSession->getUser();
606 606
 
607
-		if($groupid === null || trim($groupid) === '') {
607
+		if ($groupid === null || trim($groupid) === '') {
608 608
 			throw new OCSException('', 101);
609 609
 		}
610 610
 
611 611
 		$group = $this->groupManager->get($groupid);
612
-		if($group === null) {
612
+		if ($group === null) {
613 613
 			throw new OCSException('', 102);
614 614
 		}
615 615
 
616 616
 		$targetUser = $this->userManager->get($userId);
617
-		if($targetUser === null) {
617
+		if ($targetUser === null) {
618 618
 			throw new OCSException('', 103);
619 619
 		}
620 620
 
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
639 639
 			/** @var IGroup[] $subAdminGroups */
640 640
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
641
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
641
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
642 642
 				return $subAdminGroup->getGID();
643 643
 			}, $subAdminGroups);
644 644
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -670,15 +670,15 @@  discard block
 block discarded – undo
670 670
 		$user = $this->userManager->get($userId);
671 671
 
672 672
 		// Check if the user exists
673
-		if($user === null) {
673
+		if ($user === null) {
674 674
 			throw new OCSException('User does not exist', 101);
675 675
 		}
676 676
 		// Check if group exists
677
-		if($group === null) {
678
-			throw new OCSException('Group does not exist',  102);
677
+		if ($group === null) {
678
+			throw new OCSException('Group does not exist', 102);
679 679
 		}
680 680
 		// Check if trying to make subadmin of admin group
681
-		if($group->getGID() === 'admin') {
681
+		if ($group->getGID() === 'admin') {
682 682
 			throw new OCSException('Cannot create subadmins for admin group', 103);
683 683
 		}
684 684
 
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 			return new DataResponse();
690 690
 		}
691 691
 		// Go
692
-		if($subAdminManager->createSubAdmin($user, $group)) {
692
+		if ($subAdminManager->createSubAdmin($user, $group)) {
693 693
 			return new DataResponse();
694 694
 		} else {
695 695
 			throw new OCSException('Unknown error occurred', 103);
@@ -712,20 +712,20 @@  discard block
 block discarded – undo
712 712
 		$subAdminManager = $this->groupManager->getSubAdmin();
713 713
 
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
 		// Check if the group exists
719
-		if($group === null) {
719
+		if ($group === null) {
720 720
 			throw new OCSException('Group does not exist', 101);
721 721
 		}
722 722
 		// Check if they are a subadmin of this said group
723
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
723
+		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
724 724
 			throw new OCSException('User is not a subadmin of this group', 102);
725 725
 		}
726 726
 
727 727
 		// Go
728
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
728
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
729 729
 			return new DataResponse();
730 730
 		} else {
731 731
 			throw new OCSException('Unknown error occurred', 103);
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 	public function getUserSubAdminGroups($userId) {
743 743
 		$user = $this->userManager->get($userId);
744 744
 		// Check if the user exists
745
-		if($user === null) {
745
+		if ($user === null) {
746 746
 			throw new OCSException('User does not exist', 101);
747 747
 		}
748 748
 
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
 			$groups[$key] = $group->getGID();
753 753
 		}
754 754
 
755
-		if(!$groups) {
755
+		if (!$groups) {
756 756
 			throw new OCSException('Unknown error occurred', 102);
757 757
 		} else {
758 758
 			return new DataResponse($groups);
@@ -796,13 +796,13 @@  discard block
 block discarded – undo
796 796
 		$currentLoggedInUser = $this->userSession->getUser();
797 797
 
798 798
 		$targetUser = $this->userManager->get($userId);
799
-		if($targetUser === null) {
799
+		if ($targetUser === null) {
800 800
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
801 801
 		}
802 802
 
803 803
 		// Check if admin / subadmin
804 804
 		$subAdminManager = $this->groupManager->getSubAdmin();
805
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
805
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
806 806
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
807 807
 			// No rights
808 808
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -824,8 +824,8 @@  discard block
 block discarded – undo
824 824
 			$this->newUserMailHelper->setL10N($l10n);
825 825
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
826 826
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
827
-		} catch(\Exception $e) {
828
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
827
+		} catch (\Exception $e) {
828
+			$this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
829 829
 			throw new OCSException('Sending email failed', 102);
830 830
 		}
831 831
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Helper.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -124,6 +124,9 @@
 block discarded – undo
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
 
Please login to merge, or discard this patch.
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -34,126 +34,126 @@  discard block
 block discarded – undo
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,149 +161,149 @@  discard block
 block discarded – undo
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
-		$userSession = \OC::$server->getUserSession();
299
-		$userPluginManager = \OC::$server->query('LDAPUserPluginManager');
300
-
301
-		$userBackend  = new User_Proxy(
302
-			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
303
-		);
304
-		$uid = $userBackend->loginName2UserName($param['uid'] );
305
-		if($uid !== false) {
306
-			$param['uid'] = $uid;
307
-		}
308
-	}
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
+        $userSession = \OC::$server->getUserSession();
299
+        $userPluginManager = \OC::$server->query('LDAPUserPluginManager');
300
+
301
+        $userBackend  = new User_Proxy(
302
+            $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
303
+        );
304
+        $uid = $userBackend->loginName2UserName($param['uid'] );
305
+        if($uid !== false) {
306
+            $param['uid'] = $uid;
307
+        }
308
+    }
309 309
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 block discarded – undo
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
 
@@ -298,11 +298,11 @@  discard block
 block discarded – undo
298 298
 		$userSession = \OC::$server->getUserSession();
299 299
 		$userPluginManager = \OC::$server->query('LDAPUserPluginManager');
300 300
 
301
-		$userBackend  = new User_Proxy(
301
+		$userBackend = new User_Proxy(
302 302
 			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
303 303
 		);
304
-		$uid = $userBackend->loginName2UserName($param['uid'] );
305
-		if($uid !== false) {
304
+		$uid = $userBackend->loginName2UserName($param['uid']);
305
+		if ($uid !== false) {
306 306
 			$param['uid'] = $uid;
307 307
 		}
308 308
 	}
Please login to merge, or discard this patch.
lib/private/Files/Cache/Wrapper/CacheJail.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -194,6 +194,9 @@
 block discarded – undo
194 194
 		return $this->getCache()->getStatus($this->getSourcePath($file));
195 195
 	}
196 196
 
197
+	/**
198
+	 * @param ICacheEntry[] $results
199
+	 */
197 200
 	private function formatSearchResults($results) {
198 201
 		$results = array_filter($results, array($this, 'filterCacheEntry'));
199 202
 		$results = array_values($results);
Please login to merge, or discard this patch.
Indentation   +294 added lines, -294 removed lines patch added patch discarded remove patch
@@ -36,298 +36,298 @@
 block discarded – undo
36 36
  * Jail to a subdirectory of the wrapped cache
37 37
  */
38 38
 class CacheJail extends CacheWrapper {
39
-	/**
40
-	 * @var string
41
-	 */
42
-	protected $root;
43
-
44
-	/**
45
-	 * @param \OCP\Files\Cache\ICache $cache
46
-	 * @param string $root
47
-	 */
48
-	public function __construct($cache, $root) {
49
-		parent::__construct($cache);
50
-		$this->root = $root;
51
-	}
52
-
53
-	protected function getRoot() {
54
-		return $this->root;
55
-	}
56
-
57
-	protected function getSourcePath($path) {
58
-		if ($path === '') {
59
-			return $this->getRoot();
60
-		} else {
61
-			return $this->getRoot() . '/' . ltrim($path, '/');
62
-		}
63
-	}
64
-
65
-	/**
66
-	 * @param string $path
67
-	 * @return null|string the jailed path or null if the path is outside the jail
68
-	 */
69
-	protected function getJailedPath($path) {
70
-		if ($this->getRoot() === '') {
71
-			return $path;
72
-		}
73
-		$rootLength = strlen($this->getRoot()) + 1;
74
-		if ($path === $this->getRoot()) {
75
-			return '';
76
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
77
-			return substr($path, $rootLength);
78
-		} else {
79
-			return null;
80
-		}
81
-	}
82
-
83
-	/**
84
-	 * @param ICacheEntry|array $entry
85
-	 * @return array
86
-	 */
87
-	protected function formatCacheEntry($entry) {
88
-		if (isset($entry['path'])) {
89
-			$entry['path'] = $this->getJailedPath($entry['path']);
90
-		}
91
-		return $entry;
92
-	}
93
-
94
-	protected function filterCacheEntry($entry) {
95
-		$rootLength = strlen($this->getRoot()) + 1;
96
-		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
97
-	}
98
-
99
-	/**
100
-	 * get the stored metadata of a file or folder
101
-	 *
102
-	 * @param string /int $file
103
-	 * @return ICacheEntry|false
104
-	 */
105
-	public function get($file) {
106
-		if (is_string($file) or $file == '') {
107
-			$file = $this->getSourcePath($file);
108
-		}
109
-		return parent::get($file);
110
-	}
111
-
112
-	/**
113
-	 * insert meta data for a new file or folder
114
-	 *
115
-	 * @param string $file
116
-	 * @param array $data
117
-	 *
118
-	 * @return int file id
119
-	 * @throws \RuntimeException
120
-	 */
121
-	public function insert($file, array $data) {
122
-		return $this->getCache()->insert($this->getSourcePath($file), $data);
123
-	}
124
-
125
-	/**
126
-	 * update the metadata in the cache
127
-	 *
128
-	 * @param int $id
129
-	 * @param array $data
130
-	 */
131
-	public function update($id, array $data) {
132
-		$this->getCache()->update($id, $data);
133
-	}
134
-
135
-	/**
136
-	 * get the file id for a file
137
-	 *
138
-	 * @param string $file
139
-	 * @return int
140
-	 */
141
-	public function getId($file) {
142
-		return $this->getCache()->getId($this->getSourcePath($file));
143
-	}
144
-
145
-	/**
146
-	 * get the id of the parent folder of a file
147
-	 *
148
-	 * @param string $file
149
-	 * @return int
150
-	 */
151
-	public function getParentId($file) {
152
-		return $this->getCache()->getParentId($this->getSourcePath($file));
153
-	}
154
-
155
-	/**
156
-	 * check if a file is available in the cache
157
-	 *
158
-	 * @param string $file
159
-	 * @return bool
160
-	 */
161
-	public function inCache($file) {
162
-		return $this->getCache()->inCache($this->getSourcePath($file));
163
-	}
164
-
165
-	/**
166
-	 * remove a file or folder from the cache
167
-	 *
168
-	 * @param string $file
169
-	 */
170
-	public function remove($file) {
171
-		$this->getCache()->remove($this->getSourcePath($file));
172
-	}
173
-
174
-	/**
175
-	 * Move a file or folder in the cache
176
-	 *
177
-	 * @param string $source
178
-	 * @param string $target
179
-	 */
180
-	public function move($source, $target) {
181
-		$this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
182
-	}
183
-
184
-	/**
185
-	 * Get the storage id and path needed for a move
186
-	 *
187
-	 * @param string $path
188
-	 * @return array [$storageId, $internalPath]
189
-	 */
190
-	protected function getMoveInfo($path) {
191
-		return [$this->getNumericStorageId(), $this->getSourcePath($path)];
192
-	}
193
-
194
-	/**
195
-	 * remove all entries for files that are stored on the storage from the cache
196
-	 */
197
-	public function clear() {
198
-		$this->getCache()->remove($this->getRoot());
199
-	}
200
-
201
-	/**
202
-	 * @param string $file
203
-	 *
204
-	 * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
205
-	 */
206
-	public function getStatus($file) {
207
-		return $this->getCache()->getStatus($this->getSourcePath($file));
208
-	}
209
-
210
-	private function formatSearchResults($results) {
211
-		$results = array_filter($results, array($this, 'filterCacheEntry'));
212
-		$results = array_values($results);
213
-		return array_map(array($this, 'formatCacheEntry'), $results);
214
-	}
215
-
216
-	/**
217
-	 * search for files matching $pattern
218
-	 *
219
-	 * @param string $pattern
220
-	 * @return array an array of file data
221
-	 */
222
-	public function search($pattern) {
223
-		$results = $this->getCache()->search($pattern);
224
-		return $this->formatSearchResults($results);
225
-	}
226
-
227
-	/**
228
-	 * search for files by mimetype
229
-	 *
230
-	 * @param string $mimetype
231
-	 * @return array
232
-	 */
233
-	public function searchByMime($mimetype) {
234
-		$results = $this->getCache()->searchByMime($mimetype);
235
-		return $this->formatSearchResults($results);
236
-	}
237
-
238
-	public function searchQuery(ISearchQuery $query) {
239
-		$results = $this->getCache()->searchQuery($query);
240
-		return $this->formatSearchResults($results);
241
-	}
242
-
243
-	/**
244
-	 * search for files by mimetype
245
-	 *
246
-	 * @param string|int $tag name or tag id
247
-	 * @param string $userId owner of the tags
248
-	 * @return array
249
-	 */
250
-	public function searchByTag($tag, $userId) {
251
-		$results = $this->getCache()->searchByTag($tag, $userId);
252
-		return $this->formatSearchResults($results);
253
-	}
254
-
255
-	/**
256
-	 * update the folder size and the size of all parent folders
257
-	 *
258
-	 * @param string|boolean $path
259
-	 * @param array $data (optional) meta data of the folder
260
-	 */
261
-	public function correctFolderSize($path, $data = null) {
262
-		if ($this->getCache() instanceof Cache) {
263
-			$this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * get the size of a folder and set it in the cache
269
-	 *
270
-	 * @param string $path
271
-	 * @param array $entry (optional) meta data of the folder
272
-	 * @return int
273
-	 */
274
-	public function calculateFolderSize($path, $entry = null) {
275
-		if ($this->getCache() instanceof Cache) {
276
-			return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
277
-		} else {
278
-			return 0;
279
-		}
280
-
281
-	}
282
-
283
-	/**
284
-	 * get all file ids on the files on the storage
285
-	 *
286
-	 * @return int[]
287
-	 */
288
-	public function getAll() {
289
-		// not supported
290
-		return array();
291
-	}
292
-
293
-	/**
294
-	 * find a folder in the cache which has not been fully scanned
295
-	 *
296
-	 * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
297
-	 * use the one with the highest id gives the best result with the background scanner, since that is most
298
-	 * likely the folder where we stopped scanning previously
299
-	 *
300
-	 * @return string|bool the path of the folder or false when no folder matched
301
-	 */
302
-	public function getIncomplete() {
303
-		// not supported
304
-		return false;
305
-	}
306
-
307
-	/**
308
-	 * get the path of a file on this storage by it's id
309
-	 *
310
-	 * @param int $id
311
-	 * @return string|null
312
-	 */
313
-	public function getPathById($id) {
314
-		$path = $this->getCache()->getPathById($id);
315
-		return $this->getJailedPath($path);
316
-	}
317
-
318
-	/**
319
-	 * Move a file or folder in the cache
320
-	 *
321
-	 * Note that this should make sure the entries are removed from the source cache
322
-	 *
323
-	 * @param \OCP\Files\Cache\ICache $sourceCache
324
-	 * @param string $sourcePath
325
-	 * @param string $targetPath
326
-	 */
327
-	public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
328
-		if ($sourceCache === $this) {
329
-			return $this->move($sourcePath, $targetPath);
330
-		}
331
-		return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
332
-	}
39
+    /**
40
+     * @var string
41
+     */
42
+    protected $root;
43
+
44
+    /**
45
+     * @param \OCP\Files\Cache\ICache $cache
46
+     * @param string $root
47
+     */
48
+    public function __construct($cache, $root) {
49
+        parent::__construct($cache);
50
+        $this->root = $root;
51
+    }
52
+
53
+    protected function getRoot() {
54
+        return $this->root;
55
+    }
56
+
57
+    protected function getSourcePath($path) {
58
+        if ($path === '') {
59
+            return $this->getRoot();
60
+        } else {
61
+            return $this->getRoot() . '/' . ltrim($path, '/');
62
+        }
63
+    }
64
+
65
+    /**
66
+     * @param string $path
67
+     * @return null|string the jailed path or null if the path is outside the jail
68
+     */
69
+    protected function getJailedPath($path) {
70
+        if ($this->getRoot() === '') {
71
+            return $path;
72
+        }
73
+        $rootLength = strlen($this->getRoot()) + 1;
74
+        if ($path === $this->getRoot()) {
75
+            return '';
76
+        } else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
77
+            return substr($path, $rootLength);
78
+        } else {
79
+            return null;
80
+        }
81
+    }
82
+
83
+    /**
84
+     * @param ICacheEntry|array $entry
85
+     * @return array
86
+     */
87
+    protected function formatCacheEntry($entry) {
88
+        if (isset($entry['path'])) {
89
+            $entry['path'] = $this->getJailedPath($entry['path']);
90
+        }
91
+        return $entry;
92
+    }
93
+
94
+    protected function filterCacheEntry($entry) {
95
+        $rootLength = strlen($this->getRoot()) + 1;
96
+        return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
97
+    }
98
+
99
+    /**
100
+     * get the stored metadata of a file or folder
101
+     *
102
+     * @param string /int $file
103
+     * @return ICacheEntry|false
104
+     */
105
+    public function get($file) {
106
+        if (is_string($file) or $file == '') {
107
+            $file = $this->getSourcePath($file);
108
+        }
109
+        return parent::get($file);
110
+    }
111
+
112
+    /**
113
+     * insert meta data for a new file or folder
114
+     *
115
+     * @param string $file
116
+     * @param array $data
117
+     *
118
+     * @return int file id
119
+     * @throws \RuntimeException
120
+     */
121
+    public function insert($file, array $data) {
122
+        return $this->getCache()->insert($this->getSourcePath($file), $data);
123
+    }
124
+
125
+    /**
126
+     * update the metadata in the cache
127
+     *
128
+     * @param int $id
129
+     * @param array $data
130
+     */
131
+    public function update($id, array $data) {
132
+        $this->getCache()->update($id, $data);
133
+    }
134
+
135
+    /**
136
+     * get the file id for a file
137
+     *
138
+     * @param string $file
139
+     * @return int
140
+     */
141
+    public function getId($file) {
142
+        return $this->getCache()->getId($this->getSourcePath($file));
143
+    }
144
+
145
+    /**
146
+     * get the id of the parent folder of a file
147
+     *
148
+     * @param string $file
149
+     * @return int
150
+     */
151
+    public function getParentId($file) {
152
+        return $this->getCache()->getParentId($this->getSourcePath($file));
153
+    }
154
+
155
+    /**
156
+     * check if a file is available in the cache
157
+     *
158
+     * @param string $file
159
+     * @return bool
160
+     */
161
+    public function inCache($file) {
162
+        return $this->getCache()->inCache($this->getSourcePath($file));
163
+    }
164
+
165
+    /**
166
+     * remove a file or folder from the cache
167
+     *
168
+     * @param string $file
169
+     */
170
+    public function remove($file) {
171
+        $this->getCache()->remove($this->getSourcePath($file));
172
+    }
173
+
174
+    /**
175
+     * Move a file or folder in the cache
176
+     *
177
+     * @param string $source
178
+     * @param string $target
179
+     */
180
+    public function move($source, $target) {
181
+        $this->getCache()->move($this->getSourcePath($source), $this->getSourcePath($target));
182
+    }
183
+
184
+    /**
185
+     * Get the storage id and path needed for a move
186
+     *
187
+     * @param string $path
188
+     * @return array [$storageId, $internalPath]
189
+     */
190
+    protected function getMoveInfo($path) {
191
+        return [$this->getNumericStorageId(), $this->getSourcePath($path)];
192
+    }
193
+
194
+    /**
195
+     * remove all entries for files that are stored on the storage from the cache
196
+     */
197
+    public function clear() {
198
+        $this->getCache()->remove($this->getRoot());
199
+    }
200
+
201
+    /**
202
+     * @param string $file
203
+     *
204
+     * @return int Cache::NOT_FOUND, Cache::PARTIAL, Cache::SHALLOW or Cache::COMPLETE
205
+     */
206
+    public function getStatus($file) {
207
+        return $this->getCache()->getStatus($this->getSourcePath($file));
208
+    }
209
+
210
+    private function formatSearchResults($results) {
211
+        $results = array_filter($results, array($this, 'filterCacheEntry'));
212
+        $results = array_values($results);
213
+        return array_map(array($this, 'formatCacheEntry'), $results);
214
+    }
215
+
216
+    /**
217
+     * search for files matching $pattern
218
+     *
219
+     * @param string $pattern
220
+     * @return array an array of file data
221
+     */
222
+    public function search($pattern) {
223
+        $results = $this->getCache()->search($pattern);
224
+        return $this->formatSearchResults($results);
225
+    }
226
+
227
+    /**
228
+     * search for files by mimetype
229
+     *
230
+     * @param string $mimetype
231
+     * @return array
232
+     */
233
+    public function searchByMime($mimetype) {
234
+        $results = $this->getCache()->searchByMime($mimetype);
235
+        return $this->formatSearchResults($results);
236
+    }
237
+
238
+    public function searchQuery(ISearchQuery $query) {
239
+        $results = $this->getCache()->searchQuery($query);
240
+        return $this->formatSearchResults($results);
241
+    }
242
+
243
+    /**
244
+     * search for files by mimetype
245
+     *
246
+     * @param string|int $tag name or tag id
247
+     * @param string $userId owner of the tags
248
+     * @return array
249
+     */
250
+    public function searchByTag($tag, $userId) {
251
+        $results = $this->getCache()->searchByTag($tag, $userId);
252
+        return $this->formatSearchResults($results);
253
+    }
254
+
255
+    /**
256
+     * update the folder size and the size of all parent folders
257
+     *
258
+     * @param string|boolean $path
259
+     * @param array $data (optional) meta data of the folder
260
+     */
261
+    public function correctFolderSize($path, $data = null) {
262
+        if ($this->getCache() instanceof Cache) {
263
+            $this->getCache()->correctFolderSize($this->getSourcePath($path), $data);
264
+        }
265
+    }
266
+
267
+    /**
268
+     * get the size of a folder and set it in the cache
269
+     *
270
+     * @param string $path
271
+     * @param array $entry (optional) meta data of the folder
272
+     * @return int
273
+     */
274
+    public function calculateFolderSize($path, $entry = null) {
275
+        if ($this->getCache() instanceof Cache) {
276
+            return $this->getCache()->calculateFolderSize($this->getSourcePath($path), $entry);
277
+        } else {
278
+            return 0;
279
+        }
280
+
281
+    }
282
+
283
+    /**
284
+     * get all file ids on the files on the storage
285
+     *
286
+     * @return int[]
287
+     */
288
+    public function getAll() {
289
+        // not supported
290
+        return array();
291
+    }
292
+
293
+    /**
294
+     * find a folder in the cache which has not been fully scanned
295
+     *
296
+     * If multiply incomplete folders are in the cache, the one with the highest id will be returned,
297
+     * use the one with the highest id gives the best result with the background scanner, since that is most
298
+     * likely the folder where we stopped scanning previously
299
+     *
300
+     * @return string|bool the path of the folder or false when no folder matched
301
+     */
302
+    public function getIncomplete() {
303
+        // not supported
304
+        return false;
305
+    }
306
+
307
+    /**
308
+     * get the path of a file on this storage by it's id
309
+     *
310
+     * @param int $id
311
+     * @return string|null
312
+     */
313
+    public function getPathById($id) {
314
+        $path = $this->getCache()->getPathById($id);
315
+        return $this->getJailedPath($path);
316
+    }
317
+
318
+    /**
319
+     * Move a file or folder in the cache
320
+     *
321
+     * Note that this should make sure the entries are removed from the source cache
322
+     *
323
+     * @param \OCP\Files\Cache\ICache $sourceCache
324
+     * @param string $sourcePath
325
+     * @param string $targetPath
326
+     */
327
+    public function moveFromCache(\OCP\Files\Cache\ICache $sourceCache, $sourcePath, $targetPath) {
328
+        if ($sourceCache === $this) {
329
+            return $this->move($sourcePath, $targetPath);
330
+        }
331
+        return $this->getCache()->moveFromCache($sourceCache, $sourcePath, $this->getSourcePath($targetPath));
332
+    }
333 333
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 		if ($path === '') {
59 59
 			return $this->getRoot();
60 60
 		} else {
61
-			return $this->getRoot() . '/' . ltrim($path, '/');
61
+			return $this->getRoot().'/'.ltrim($path, '/');
62 62
 		}
63 63
 	}
64 64
 
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		$rootLength = strlen($this->getRoot()) + 1;
74 74
 		if ($path === $this->getRoot()) {
75 75
 			return '';
76
-		} else if (substr($path, 0, $rootLength) === $this->getRoot() . '/') {
76
+		} else if (substr($path, 0, $rootLength) === $this->getRoot().'/') {
77 77
 			return substr($path, $rootLength);
78 78
 		} else {
79 79
 			return null;
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
 
94 94
 	protected function filterCacheEntry($entry) {
95 95
 		$rootLength = strlen($this->getRoot()) + 1;
96
-		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot() . '/');
96
+		return ($entry['path'] === $this->getRoot()) or (substr($entry['path'], 0, $rootLength) === $this->getRoot().'/');
97 97
 	}
98 98
 
99 99
 	/**
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -156,7 +156,7 @@
 block discarded – undo
156 156
 	/**
157 157
 	 * @param string $gid
158 158
 	 * @param string $displayName
159
-	 * @return \OCP\IGroup
159
+	 * @return null|Group
160 160
 	 */
161 161
 	protected function getGroupObject($gid, $displayName = null) {
162 162
 		$backends = array();
Please login to merge, or discard this patch.
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 	 * @param IUser|null $user
250 250
 	 * @return \OC\Group\Group[]
251 251
 	 */
252
-	public function getUserGroups(IUser $user= null) {
252
+	public function getUserGroups(IUser $user = null) {
253 253
 		if (!$user instanceof IUser) {
254 254
 			return [];
255 255
 		}
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362 362
 		}
363 363
 		return $matchingUsers;
Please login to merge, or discard this patch.
Indentation   +333 added lines, -333 removed lines patch added patch discarded remove patch
@@ -58,337 +58,337 @@
 block discarded – undo
58 58
  * @package OC\Group
59 59
  */
60 60
 class Manager extends PublicEmitter implements IGroupManager {
61
-	/**
62
-	 * @var GroupInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\Manager $userManager
68
-	 */
69
-	private $userManager;
70
-
71
-	/**
72
-	 * @var \OC\Group\Group[]
73
-	 */
74
-	private $cachedGroups = array();
75
-
76
-	/**
77
-	 * @var \OC\Group\Group[]
78
-	 */
79
-	private $cachedUserGroups = array();
80
-
81
-	/** @var \OC\SubAdmin */
82
-	private $subAdmin = null;
83
-
84
-	/** @var ILogger */
85
-	private $logger;
86
-
87
-	/**
88
-	 * @param \OC\User\Manager $userManager
89
-	 * @param ILogger $logger
90
-	 */
91
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
-		$this->userManager = $userManager;
93
-		$this->logger = $logger;
94
-		$cachedGroups = & $this->cachedGroups;
95
-		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
-			/**
98
-			 * @var \OC\Group\Group $group
99
-			 */
100
-			unset($cachedGroups[$group->getGID()]);
101
-			$cachedUserGroups = array();
102
-		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
-			/**
105
-			 * @var \OC\Group\Group $group
106
-			 */
107
-			$cachedUserGroups = array();
108
-		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
-			/**
111
-			 * @var \OC\Group\Group $group
112
-			 */
113
-			$cachedUserGroups = array();
114
-		});
115
-	}
116
-
117
-	/**
118
-	 * Checks whether a given backend is used
119
-	 *
120
-	 * @param string $backendClass Full classname including complete namespace
121
-	 * @return bool
122
-	 */
123
-	public function isBackendUsed($backendClass) {
124
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
125
-
126
-		foreach ($this->backends as $backend) {
127
-			if (strtolower(get_class($backend)) === $backendClass) {
128
-				return true;
129
-			}
130
-		}
131
-
132
-		return false;
133
-	}
134
-
135
-	/**
136
-	 * @param \OCP\GroupInterface $backend
137
-	 */
138
-	public function addBackend($backend) {
139
-		$this->backends[] = $backend;
140
-		$this->clearCaches();
141
-	}
142
-
143
-	public function clearBackends() {
144
-		$this->backends = array();
145
-		$this->clearCaches();
146
-	}
147
-
148
-	/**
149
-	 * Get the active backends
150
-	 * @return \OCP\GroupInterface[]
151
-	 */
152
-	public function getBackends() {
153
-		return $this->backends;
154
-	}
155
-
156
-
157
-	protected function clearCaches() {
158
-		$this->cachedGroups = array();
159
-		$this->cachedUserGroups = array();
160
-	}
161
-
162
-	/**
163
-	 * @param string $gid
164
-	 * @return \OC\Group\Group
165
-	 */
166
-	public function get($gid) {
167
-		if (isset($this->cachedGroups[$gid])) {
168
-			return $this->cachedGroups[$gid];
169
-		}
170
-		return $this->getGroupObject($gid);
171
-	}
172
-
173
-	/**
174
-	 * @param string $gid
175
-	 * @param string $displayName
176
-	 * @return \OCP\IGroup
177
-	 */
178
-	protected function getGroupObject($gid, $displayName = null) {
179
-		$backends = array();
180
-		foreach ($this->backends as $backend) {
181
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
182
-				$groupData = $backend->getGroupDetails($gid);
183
-				if (is_array($groupData)) {
184
-					// take the display name from the first backend that has a non-null one
185
-					if (is_null($displayName) && isset($groupData['displayName'])) {
186
-						$displayName = $groupData['displayName'];
187
-					}
188
-					$backends[] = $backend;
189
-				}
190
-			} else if ($backend->groupExists($gid)) {
191
-				$backends[] = $backend;
192
-			}
193
-		}
194
-		if (count($backends) === 0) {
195
-			return null;
196
-		}
197
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
198
-		return $this->cachedGroups[$gid];
199
-	}
200
-
201
-	/**
202
-	 * @param string $gid
203
-	 * @return bool
204
-	 */
205
-	public function groupExists($gid) {
206
-		return $this->get($gid) instanceof IGroup;
207
-	}
208
-
209
-	/**
210
-	 * @param string $gid
211
-	 * @return \OC\Group\Group
212
-	 */
213
-	public function createGroup($gid) {
214
-		if ($gid === '' || $gid === null) {
215
-			return false;
216
-		} else if ($group = $this->get($gid)) {
217
-			return $group;
218
-		} else {
219
-			$this->emit('\OC\Group', 'preCreate', array($gid));
220
-			foreach ($this->backends as $backend) {
221
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
222
-					$backend->createGroup($gid);
223
-					$group = $this->getGroupObject($gid);
224
-					$this->emit('\OC\Group', 'postCreate', array($group));
225
-					return $group;
226
-				}
227
-			}
228
-			return null;
229
-		}
230
-	}
231
-
232
-	/**
233
-	 * @param string $search
234
-	 * @param int $limit
235
-	 * @param int $offset
236
-	 * @return \OC\Group\Group[]
237
-	 */
238
-	public function search($search, $limit = null, $offset = null) {
239
-		$groups = array();
240
-		foreach ($this->backends as $backend) {
241
-			$groupIds = $backend->getGroups($search, $limit, $offset);
242
-			foreach ($groupIds as $groupId) {
243
-				$aGroup = $this->get($groupId);
244
-				if ($aGroup instanceof IGroup) {
245
-					$groups[$groupId] = $aGroup;
246
-				} else {
247
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
248
-				}
249
-			}
250
-			if (!is_null($limit) and $limit <= 0) {
251
-				return array_values($groups);
252
-			}
253
-		}
254
-		return array_values($groups);
255
-	}
256
-
257
-	/**
258
-	 * @param IUser|null $user
259
-	 * @return \OC\Group\Group[]
260
-	 */
261
-	public function getUserGroups(IUser $user= null) {
262
-		if (!$user instanceof IUser) {
263
-			return [];
264
-		}
265
-		return $this->getUserIdGroups($user->getUID());
266
-	}
267
-
268
-	/**
269
-	 * @param string $uid the user id
270
-	 * @return \OC\Group\Group[]
271
-	 */
272
-	public function getUserIdGroups($uid) {
273
-		if (isset($this->cachedUserGroups[$uid])) {
274
-			return $this->cachedUserGroups[$uid];
275
-		}
276
-		$groups = array();
277
-		foreach ($this->backends as $backend) {
278
-			$groupIds = $backend->getUserGroups($uid);
279
-			if (is_array($groupIds)) {
280
-				foreach ($groupIds as $groupId) {
281
-					$aGroup = $this->get($groupId);
282
-					if ($aGroup instanceof IGroup) {
283
-						$groups[$groupId] = $aGroup;
284
-					} else {
285
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
286
-					}
287
-				}
288
-			}
289
-		}
290
-		$this->cachedUserGroups[$uid] = $groups;
291
-		return $this->cachedUserGroups[$uid];
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in the admin group
296
-	 * @param string $userId
297
-	 * @return bool if admin
298
-	 */
299
-	public function isAdmin($userId) {
300
-		foreach ($this->backends as $backend) {
301
-			if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
302
-				return true;
303
-			}
304
-		}
305
-		return $this->isInGroup($userId, 'admin');
306
-	}
307
-
308
-	/**
309
-	 * Checks if a userId is in a group
310
-	 * @param string $userId
311
-	 * @param string $group
312
-	 * @return bool if in group
313
-	 */
314
-	public function isInGroup($userId, $group) {
315
-		return array_key_exists($group, $this->getUserIdGroups($userId));
316
-	}
317
-
318
-	/**
319
-	 * get a list of group ids for a user
320
-	 * @param IUser $user
321
-	 * @return array with group ids
322
-	 */
323
-	public function getUserGroupIds(IUser $user) {
324
-		return array_map(function($value) {
325
-			return (string) $value;
326
-		}, array_keys($this->getUserGroups($user)));
327
-	}
328
-
329
-	/**
330
-	 * get a list of all display names in a group
331
-	 * @param string $gid
332
-	 * @param string $search
333
-	 * @param int $limit
334
-	 * @param int $offset
335
-	 * @return array an array of display names (value) and user ids (key)
336
-	 */
337
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
338
-		$group = $this->get($gid);
339
-		if(is_null($group)) {
340
-			return array();
341
-		}
342
-
343
-		$search = trim($search);
344
-		$groupUsers = array();
345
-
346
-		if(!empty($search)) {
347
-			// only user backends have the capability to do a complex search for users
348
-			$searchOffset = 0;
349
-			$searchLimit = $limit * 100;
350
-			if($limit === -1) {
351
-				$searchLimit = 500;
352
-			}
353
-
354
-			do {
355
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
356
-				foreach($filteredUsers as $filteredUser) {
357
-					if($group->inGroup($filteredUser)) {
358
-						$groupUsers[]= $filteredUser;
359
-					}
360
-				}
361
-				$searchOffset += $searchLimit;
362
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
363
-
364
-			if($limit === -1) {
365
-				$groupUsers = array_slice($groupUsers, $offset);
366
-			} else {
367
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
368
-			}
369
-		} else {
370
-			$groupUsers = $group->searchUsers('', $limit, $offset);
371
-		}
372
-
373
-		$matchingUsers = array();
374
-		foreach($groupUsers as $groupUser) {
375
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
376
-		}
377
-		return $matchingUsers;
378
-	}
379
-
380
-	/**
381
-	 * @return \OC\SubAdmin
382
-	 */
383
-	public function getSubAdmin() {
384
-		if (!$this->subAdmin) {
385
-			$this->subAdmin = new \OC\SubAdmin(
386
-				$this->userManager,
387
-				$this,
388
-				\OC::$server->getDatabaseConnection()
389
-			);
390
-		}
391
-
392
-		return $this->subAdmin;
393
-	}
61
+    /**
62
+     * @var GroupInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\Manager $userManager
68
+     */
69
+    private $userManager;
70
+
71
+    /**
72
+     * @var \OC\Group\Group[]
73
+     */
74
+    private $cachedGroups = array();
75
+
76
+    /**
77
+     * @var \OC\Group\Group[]
78
+     */
79
+    private $cachedUserGroups = array();
80
+
81
+    /** @var \OC\SubAdmin */
82
+    private $subAdmin = null;
83
+
84
+    /** @var ILogger */
85
+    private $logger;
86
+
87
+    /**
88
+     * @param \OC\User\Manager $userManager
89
+     * @param ILogger $logger
90
+     */
91
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
+        $this->userManager = $userManager;
93
+        $this->logger = $logger;
94
+        $cachedGroups = & $this->cachedGroups;
95
+        $cachedUserGroups = & $this->cachedUserGroups;
96
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
+            /**
98
+             * @var \OC\Group\Group $group
99
+             */
100
+            unset($cachedGroups[$group->getGID()]);
101
+            $cachedUserGroups = array();
102
+        });
103
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
+            /**
105
+             * @var \OC\Group\Group $group
106
+             */
107
+            $cachedUserGroups = array();
108
+        });
109
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
+            /**
111
+             * @var \OC\Group\Group $group
112
+             */
113
+            $cachedUserGroups = array();
114
+        });
115
+    }
116
+
117
+    /**
118
+     * Checks whether a given backend is used
119
+     *
120
+     * @param string $backendClass Full classname including complete namespace
121
+     * @return bool
122
+     */
123
+    public function isBackendUsed($backendClass) {
124
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
125
+
126
+        foreach ($this->backends as $backend) {
127
+            if (strtolower(get_class($backend)) === $backendClass) {
128
+                return true;
129
+            }
130
+        }
131
+
132
+        return false;
133
+    }
134
+
135
+    /**
136
+     * @param \OCP\GroupInterface $backend
137
+     */
138
+    public function addBackend($backend) {
139
+        $this->backends[] = $backend;
140
+        $this->clearCaches();
141
+    }
142
+
143
+    public function clearBackends() {
144
+        $this->backends = array();
145
+        $this->clearCaches();
146
+    }
147
+
148
+    /**
149
+     * Get the active backends
150
+     * @return \OCP\GroupInterface[]
151
+     */
152
+    public function getBackends() {
153
+        return $this->backends;
154
+    }
155
+
156
+
157
+    protected function clearCaches() {
158
+        $this->cachedGroups = array();
159
+        $this->cachedUserGroups = array();
160
+    }
161
+
162
+    /**
163
+     * @param string $gid
164
+     * @return \OC\Group\Group
165
+     */
166
+    public function get($gid) {
167
+        if (isset($this->cachedGroups[$gid])) {
168
+            return $this->cachedGroups[$gid];
169
+        }
170
+        return $this->getGroupObject($gid);
171
+    }
172
+
173
+    /**
174
+     * @param string $gid
175
+     * @param string $displayName
176
+     * @return \OCP\IGroup
177
+     */
178
+    protected function getGroupObject($gid, $displayName = null) {
179
+        $backends = array();
180
+        foreach ($this->backends as $backend) {
181
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
182
+                $groupData = $backend->getGroupDetails($gid);
183
+                if (is_array($groupData)) {
184
+                    // take the display name from the first backend that has a non-null one
185
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
186
+                        $displayName = $groupData['displayName'];
187
+                    }
188
+                    $backends[] = $backend;
189
+                }
190
+            } else if ($backend->groupExists($gid)) {
191
+                $backends[] = $backend;
192
+            }
193
+        }
194
+        if (count($backends) === 0) {
195
+            return null;
196
+        }
197
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
198
+        return $this->cachedGroups[$gid];
199
+    }
200
+
201
+    /**
202
+     * @param string $gid
203
+     * @return bool
204
+     */
205
+    public function groupExists($gid) {
206
+        return $this->get($gid) instanceof IGroup;
207
+    }
208
+
209
+    /**
210
+     * @param string $gid
211
+     * @return \OC\Group\Group
212
+     */
213
+    public function createGroup($gid) {
214
+        if ($gid === '' || $gid === null) {
215
+            return false;
216
+        } else if ($group = $this->get($gid)) {
217
+            return $group;
218
+        } else {
219
+            $this->emit('\OC\Group', 'preCreate', array($gid));
220
+            foreach ($this->backends as $backend) {
221
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
222
+                    $backend->createGroup($gid);
223
+                    $group = $this->getGroupObject($gid);
224
+                    $this->emit('\OC\Group', 'postCreate', array($group));
225
+                    return $group;
226
+                }
227
+            }
228
+            return null;
229
+        }
230
+    }
231
+
232
+    /**
233
+     * @param string $search
234
+     * @param int $limit
235
+     * @param int $offset
236
+     * @return \OC\Group\Group[]
237
+     */
238
+    public function search($search, $limit = null, $offset = null) {
239
+        $groups = array();
240
+        foreach ($this->backends as $backend) {
241
+            $groupIds = $backend->getGroups($search, $limit, $offset);
242
+            foreach ($groupIds as $groupId) {
243
+                $aGroup = $this->get($groupId);
244
+                if ($aGroup instanceof IGroup) {
245
+                    $groups[$groupId] = $aGroup;
246
+                } else {
247
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
248
+                }
249
+            }
250
+            if (!is_null($limit) and $limit <= 0) {
251
+                return array_values($groups);
252
+            }
253
+        }
254
+        return array_values($groups);
255
+    }
256
+
257
+    /**
258
+     * @param IUser|null $user
259
+     * @return \OC\Group\Group[]
260
+     */
261
+    public function getUserGroups(IUser $user= null) {
262
+        if (!$user instanceof IUser) {
263
+            return [];
264
+        }
265
+        return $this->getUserIdGroups($user->getUID());
266
+    }
267
+
268
+    /**
269
+     * @param string $uid the user id
270
+     * @return \OC\Group\Group[]
271
+     */
272
+    public function getUserIdGroups($uid) {
273
+        if (isset($this->cachedUserGroups[$uid])) {
274
+            return $this->cachedUserGroups[$uid];
275
+        }
276
+        $groups = array();
277
+        foreach ($this->backends as $backend) {
278
+            $groupIds = $backend->getUserGroups($uid);
279
+            if (is_array($groupIds)) {
280
+                foreach ($groupIds as $groupId) {
281
+                    $aGroup = $this->get($groupId);
282
+                    if ($aGroup instanceof IGroup) {
283
+                        $groups[$groupId] = $aGroup;
284
+                    } else {
285
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
286
+                    }
287
+                }
288
+            }
289
+        }
290
+        $this->cachedUserGroups[$uid] = $groups;
291
+        return $this->cachedUserGroups[$uid];
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in the admin group
296
+     * @param string $userId
297
+     * @return bool if admin
298
+     */
299
+    public function isAdmin($userId) {
300
+        foreach ($this->backends as $backend) {
301
+            if ($backend->implementsActions(\OC\Group\Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
302
+                return true;
303
+            }
304
+        }
305
+        return $this->isInGroup($userId, 'admin');
306
+    }
307
+
308
+    /**
309
+     * Checks if a userId is in a group
310
+     * @param string $userId
311
+     * @param string $group
312
+     * @return bool if in group
313
+     */
314
+    public function isInGroup($userId, $group) {
315
+        return array_key_exists($group, $this->getUserIdGroups($userId));
316
+    }
317
+
318
+    /**
319
+     * get a list of group ids for a user
320
+     * @param IUser $user
321
+     * @return array with group ids
322
+     */
323
+    public function getUserGroupIds(IUser $user) {
324
+        return array_map(function($value) {
325
+            return (string) $value;
326
+        }, array_keys($this->getUserGroups($user)));
327
+    }
328
+
329
+    /**
330
+     * get a list of all display names in a group
331
+     * @param string $gid
332
+     * @param string $search
333
+     * @param int $limit
334
+     * @param int $offset
335
+     * @return array an array of display names (value) and user ids (key)
336
+     */
337
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
338
+        $group = $this->get($gid);
339
+        if(is_null($group)) {
340
+            return array();
341
+        }
342
+
343
+        $search = trim($search);
344
+        $groupUsers = array();
345
+
346
+        if(!empty($search)) {
347
+            // only user backends have the capability to do a complex search for users
348
+            $searchOffset = 0;
349
+            $searchLimit = $limit * 100;
350
+            if($limit === -1) {
351
+                $searchLimit = 500;
352
+            }
353
+
354
+            do {
355
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
356
+                foreach($filteredUsers as $filteredUser) {
357
+                    if($group->inGroup($filteredUser)) {
358
+                        $groupUsers[]= $filteredUser;
359
+                    }
360
+                }
361
+                $searchOffset += $searchLimit;
362
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
363
+
364
+            if($limit === -1) {
365
+                $groupUsers = array_slice($groupUsers, $offset);
366
+            } else {
367
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
368
+            }
369
+        } else {
370
+            $groupUsers = $group->searchUsers('', $limit, $offset);
371
+        }
372
+
373
+        $matchingUsers = array();
374
+        foreach($groupUsers as $groupUser) {
375
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
376
+        }
377
+        return $matchingUsers;
378
+    }
379
+
380
+    /**
381
+     * @return \OC\SubAdmin
382
+     */
383
+    public function getSubAdmin() {
384
+        if (!$this->subAdmin) {
385
+            $this->subAdmin = new \OC\SubAdmin(
386
+                $this->userManager,
387
+                $this,
388
+                \OC::$server->getDatabaseConnection()
389
+            );
390
+        }
391
+
392
+        return $this->subAdmin;
393
+    }
394 394
 }
Please login to merge, or discard this patch.
lib/private/Memcache/APCu.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
 	 * Set a value in the cache if it's not already stored
66 66
 	 *
67 67
 	 * @param string $key
68
-	 * @param mixed $value
68
+	 * @param integer $value
69 69
 	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
70 70
 	 * @return bool
71 71
 	 */
Please login to merge, or discard this patch.
Indentation   +125 added lines, -125 removed lines patch added patch discarded remove patch
@@ -30,140 +30,140 @@
 block discarded – undo
30 30
 use OCP\IMemcache;
31 31
 
32 32
 class APCu extends Cache implements IMemcache {
33
-	use CASTrait {
34
-		cas as casEmulated;
35
-	}
33
+    use CASTrait {
34
+        cas as casEmulated;
35
+    }
36 36
 
37
-	use CADTrait;
37
+    use CADTrait;
38 38
 
39
-	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
41
-		if (!$success) {
42
-			return null;
43
-		}
44
-		return $result;
45
-	}
39
+    public function get($key) {
40
+        $result = apcu_fetch($this->getPrefix() . $key, $success);
41
+        if (!$success) {
42
+            return null;
43
+        }
44
+        return $result;
45
+    }
46 46
 
47
-	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
-	}
47
+    public function set($key, $value, $ttl = 0) {
48
+        return apcu_store($this->getPrefix() . $key, $value, $ttl);
49
+    }
50 50
 
51
-	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
53
-	}
51
+    public function hasKey($key) {
52
+        return apcu_exists($this->getPrefix() . $key);
53
+    }
54 54
 
55
-	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
57
-	}
55
+    public function remove($key) {
56
+        return apcu_delete($this->getPrefix() . $key);
57
+    }
58 58
 
59
-	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
61
-		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
-		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
-		}
67
-		return apcu_delete($iter);
68
-	}
59
+    public function clear($prefix = '') {
60
+        $ns = $this->getPrefix() . $prefix;
61
+        $ns = preg_quote($ns, '/');
62
+        if(class_exists('\APCIterator')) {
63
+            $iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
64
+        } else {
65
+            $iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
66
+        }
67
+        return apcu_delete($iter);
68
+    }
69 69
 
70
-	/**
71
-	 * Set a value in the cache if it's not already stored
72
-	 *
73
-	 * @param string $key
74
-	 * @param mixed $value
75
-	 * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
-	 * @return bool
77
-	 */
78
-	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
-	}
70
+    /**
71
+     * Set a value in the cache if it's not already stored
72
+     *
73
+     * @param string $key
74
+     * @param mixed $value
75
+     * @param int $ttl Time To Live in seconds. Defaults to 60*60*24
76
+     * @return bool
77
+     */
78
+    public function add($key, $value, $ttl = 0) {
79
+        return apcu_add($this->getPrefix() . $key, $value, $ttl);
80
+    }
81 81
 
82
-	/**
83
-	 * Increase a stored number
84
-	 *
85
-	 * @param string $key
86
-	 * @param int $step
87
-	 * @return int | bool
88
-	 */
89
-	public function inc($key, $step = 1) {
90
-		$this->add($key, 0);
91
-		/**
92
-		 * TODO - hack around a PHP 7 specific issue in APCu
93
-		 *
94
-		 * on PHP 7 the apcu_inc method on a non-existing object will increment
95
-		 * "0" and result in "1" as value - therefore we check for existence
96
-		 * first
97
-		 *
98
-		 * on PHP 5.6 this is not the case
99
-		 *
100
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
-		 * for details
102
-		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
105
-			: false;
106
-	}
82
+    /**
83
+     * Increase a stored number
84
+     *
85
+     * @param string $key
86
+     * @param int $step
87
+     * @return int | bool
88
+     */
89
+    public function inc($key, $step = 1) {
90
+        $this->add($key, 0);
91
+        /**
92
+         * TODO - hack around a PHP 7 specific issue in APCu
93
+         *
94
+         * on PHP 7 the apcu_inc method on a non-existing object will increment
95
+         * "0" and result in "1" as value - therefore we check for existence
96
+         * first
97
+         *
98
+         * on PHP 5.6 this is not the case
99
+         *
100
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101
+         * for details
102
+         */
103
+        return apcu_exists($this->getPrefix() . $key)
104
+            ? apcu_inc($this->getPrefix() . $key, $step)
105
+            : false;
106
+    }
107 107
 
108
-	/**
109
-	 * Decrease a stored number
110
-	 *
111
-	 * @param string $key
112
-	 * @param int $step
113
-	 * @return int | bool
114
-	 */
115
-	public function dec($key, $step = 1) {
116
-		/**
117
-		 * TODO - hack around a PHP 7 specific issue in APCu
118
-		 *
119
-		 * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
-		 * "0" and result in "-1" as value - therefore we check for existence
121
-		 * first
122
-		 *
123
-		 * on PHP 5.6 this is not the case
124
-		 *
125
-		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
-		 * for details
127
-		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
130
-			: false;
131
-	}
108
+    /**
109
+     * Decrease a stored number
110
+     *
111
+     * @param string $key
112
+     * @param int $step
113
+     * @return int | bool
114
+     */
115
+    public function dec($key, $step = 1) {
116
+        /**
117
+         * TODO - hack around a PHP 7 specific issue in APCu
118
+         *
119
+         * on PHP 7 the apcu_dec method on a non-existing object will decrement
120
+         * "0" and result in "-1" as value - therefore we check for existence
121
+         * first
122
+         *
123
+         * on PHP 5.6 this is not the case
124
+         *
125
+         * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126
+         * for details
127
+         */
128
+        return apcu_exists($this->getPrefix() . $key)
129
+            ? apcu_dec($this->getPrefix() . $key, $step)
130
+            : false;
131
+    }
132 132
 
133
-	/**
134
-	 * Compare and set
135
-	 *
136
-	 * @param string $key
137
-	 * @param mixed $old
138
-	 * @param mixed $new
139
-	 * @return bool
140
-	 */
141
-	public function cas($key, $old, $new) {
142
-		// apc only does cas for ints
143
-		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
145
-		} else {
146
-			return $this->casEmulated($key, $old, $new);
147
-		}
148
-	}
133
+    /**
134
+     * Compare and set
135
+     *
136
+     * @param string $key
137
+     * @param mixed $old
138
+     * @param mixed $new
139
+     * @return bool
140
+     */
141
+    public function cas($key, $old, $new) {
142
+        // apc only does cas for ints
143
+        if (is_int($old) and is_int($new)) {
144
+            return apcu_cas($this->getPrefix() . $key, $old, $new);
145
+        } else {
146
+            return $this->casEmulated($key, $old, $new);
147
+        }
148
+    }
149 149
 
150
-	/**
151
-	 * @return bool
152
-	 */
153
-	static public function isAvailable() {
154
-		if (!extension_loaded('apcu')) {
155
-			return false;
156
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
-			return false;
158
-		} elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
-			return false;
160
-		} elseif (
161
-				version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
-				version_compare(phpversion('apcu'), '5.1.0') === -1
163
-		) {
164
-			return false;
165
-		} else {
166
-			return true;
167
-		}
168
-	}
150
+    /**
151
+     * @return bool
152
+     */
153
+    static public function isAvailable() {
154
+        if (!extension_loaded('apcu')) {
155
+            return false;
156
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enabled')) {
157
+            return false;
158
+        } elseif (!\OC::$server->getIniWrapper()->getBool('apc.enable_cli') && \OC::$CLI) {
159
+            return false;
160
+        } elseif (
161
+                version_compare(phpversion('apc'), '4.0.6') === -1 &&
162
+                version_compare(phpversion('apcu'), '5.1.0') === -1
163
+        ) {
164
+            return false;
165
+        } else {
166
+            return true;
167
+        }
168
+    }
169 169
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	use CADTrait;
38 38
 
39 39
 	public function get($key) {
40
-		$result = apcu_fetch($this->getPrefix() . $key, $success);
40
+		$result = apcu_fetch($this->getPrefix().$key, $success);
41 41
 		if (!$success) {
42 42
 			return null;
43 43
 		}
@@ -45,24 +45,24 @@  discard block
 block discarded – undo
45 45
 	}
46 46
 
47 47
 	public function set($key, $value, $ttl = 0) {
48
-		return apcu_store($this->getPrefix() . $key, $value, $ttl);
48
+		return apcu_store($this->getPrefix().$key, $value, $ttl);
49 49
 	}
50 50
 
51 51
 	public function hasKey($key) {
52
-		return apcu_exists($this->getPrefix() . $key);
52
+		return apcu_exists($this->getPrefix().$key);
53 53
 	}
54 54
 
55 55
 	public function remove($key) {
56
-		return apcu_delete($this->getPrefix() . $key);
56
+		return apcu_delete($this->getPrefix().$key);
57 57
 	}
58 58
 
59 59
 	public function clear($prefix = '') {
60
-		$ns = $this->getPrefix() . $prefix;
60
+		$ns = $this->getPrefix().$prefix;
61 61
 		$ns = preg_quote($ns, '/');
62
-		if(class_exists('\APCIterator')) {
63
-			$iter = new \APCIterator('user', '/^' . $ns . '/', APC_ITER_KEY);
62
+		if (class_exists('\APCIterator')) {
63
+			$iter = new \APCIterator('user', '/^'.$ns.'/', APC_ITER_KEY);
64 64
 		} else {
65
-			$iter = new \APCUIterator('/^' . $ns . '/', APC_ITER_KEY);
65
+			$iter = new \APCUIterator('/^'.$ns.'/', APC_ITER_KEY);
66 66
 		}
67 67
 		return apcu_delete($iter);
68 68
 	}
@@ -76,7 +76,7 @@  discard block
 block discarded – undo
76 76
 	 * @return bool
77 77
 	 */
78 78
 	public function add($key, $value, $ttl = 0) {
79
-		return apcu_add($this->getPrefix() . $key, $value, $ttl);
79
+		return apcu_add($this->getPrefix().$key, $value, $ttl);
80 80
 	}
81 81
 
82 82
 	/**
@@ -100,8 +100,8 @@  discard block
 block discarded – undo
100 100
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
101 101
 		 * for details
102 102
 		 */
103
-		return apcu_exists($this->getPrefix() . $key)
104
-			? apcu_inc($this->getPrefix() . $key, $step)
103
+		return apcu_exists($this->getPrefix().$key)
104
+			? apcu_inc($this->getPrefix().$key, $step)
105 105
 			: false;
106 106
 	}
107 107
 
@@ -125,8 +125,8 @@  discard block
 block discarded – undo
125 125
 		 * see https://github.com/krakjoe/apcu/issues/183#issuecomment-244038221
126 126
 		 * for details
127 127
 		 */
128
-		return apcu_exists($this->getPrefix() . $key)
129
-			? apcu_dec($this->getPrefix() . $key, $step)
128
+		return apcu_exists($this->getPrefix().$key)
129
+			? apcu_dec($this->getPrefix().$key, $step)
130 130
 			: false;
131 131
 	}
132 132
 
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 	public function cas($key, $old, $new) {
142 142
 		// apc only does cas for ints
143 143
 		if (is_int($old) and is_int($new)) {
144
-			return apcu_cas($this->getPrefix() . $key, $old, $new);
144
+			return apcu_cas($this->getPrefix().$key, $old, $new);
145 145
 		} else {
146 146
 			return $this->casEmulated($key, $old, $new);
147 147
 		}
Please login to merge, or discard this patch.