Completed
Pull Request — master (#9293)
by Blizzz
31:50 queued 12:06
created
lib/private/App/AppStore/Fetcher/Fetcher.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -36,7 +36,6 @@
 block discarded – undo
36 36
 use OCP\Http\Client\IClientService;
37 37
 use OCP\IConfig;
38 38
 use OCP\ILogger;
39
-use OCP\Util;
40 39
 
41 40
 abstract class Fetcher {
42 41
 	const INVALIDATE_AFTER_SECONDS = 300;
Please login to merge, or discard this patch.
Indentation   +158 added lines, -158 removed lines patch added patch discarded remove patch
@@ -39,162 +39,162 @@
 block discarded – undo
39 39
 use OCP\Util;
40 40
 
41 41
 abstract class Fetcher {
42
-	const INVALIDATE_AFTER_SECONDS = 300;
43
-
44
-	/** @var IAppData */
45
-	protected $appData;
46
-	/** @var IClientService */
47
-	protected $clientService;
48
-	/** @var ITimeFactory */
49
-	protected $timeFactory;
50
-	/** @var IConfig */
51
-	protected $config;
52
-	/** @var Ilogger */
53
-	protected $logger;
54
-	/** @var string */
55
-	protected $fileName;
56
-	/** @var string */
57
-	protected $endpointUrl;
58
-	/** @var string */
59
-	protected $version;
60
-
61
-	/**
62
-	 * @param Factory $appDataFactory
63
-	 * @param IClientService $clientService
64
-	 * @param ITimeFactory $timeFactory
65
-	 * @param IConfig $config
66
-	 * @param ILogger $logger
67
-	 */
68
-	public function __construct(Factory $appDataFactory,
69
-								IClientService $clientService,
70
-								ITimeFactory $timeFactory,
71
-								IConfig $config,
72
-								ILogger $logger) {
73
-		$this->appData = $appDataFactory->get('appstore');
74
-		$this->clientService = $clientService;
75
-		$this->timeFactory = $timeFactory;
76
-		$this->config = $config;
77
-		$this->logger = $logger;
78
-	}
79
-
80
-	/**
81
-	 * Fetches the response from the server
82
-	 *
83
-	 * @param string $ETag
84
-	 * @param string $content
85
-	 *
86
-	 * @return array
87
-	 */
88
-	protected function fetch($ETag, $content) {
89
-		$appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
90
-
91
-		if (!$appstoreenabled) {
92
-			return [];
93
-		}
94
-
95
-		$options = [
96
-			'timeout' => 10,
97
-		];
98
-
99
-		if ($ETag !== '') {
100
-			$options['headers'] = [
101
-				'If-None-Match' => $ETag,
102
-			];
103
-		}
104
-
105
-		$client = $this->clientService->newClient();
106
-		$response = $client->get($this->endpointUrl, $options);
107
-
108
-		$responseJson = [];
109
-		if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
110
-			$responseJson['data'] = json_decode($content, true);
111
-		} else {
112
-			$responseJson['data'] = json_decode($response->getBody(), true);
113
-			$ETag = $response->getHeader('ETag');
114
-		}
115
-
116
-		$responseJson['timestamp'] = $this->timeFactory->getTime();
117
-		$responseJson['ncversion'] = $this->getVersion();
118
-		if ($ETag !== '') {
119
-			$responseJson['ETag'] = $ETag;
120
-		}
121
-
122
-		return $responseJson;
123
-	}
124
-
125
-	/**
126
-	 * Returns the array with the categories on the appstore server
127
-	 *
128
-	 * @return array
129
-	 */
130
-	public function get() {
131
-		$appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
132
-		$internetavailable = $this->config->getSystemValue('has_internet_connection', true);
133
-
134
-		if (!$appstoreenabled || !$internetavailable) {
135
-			return [];
136
-		}
137
-
138
-		$rootFolder = $this->appData->getFolder('/');
139
-
140
-		$ETag = '';
141
-		$content = '';
142
-
143
-		try {
144
-			// File does already exists
145
-			$file = $rootFolder->getFile($this->fileName);
146
-			$jsonBlob = json_decode($file->getContent(), true);
147
-			if (is_array($jsonBlob)) {
148
-
149
-				// No caching when the version has been updated
150
-				if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
151
-
152
-					// If the timestamp is older than 300 seconds request the files new
153
-					if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
154
-						return $jsonBlob['data'];
155
-					}
156
-
157
-					if (isset($jsonBlob['ETag'])) {
158
-						$ETag = $jsonBlob['ETag'];
159
-						$content = json_encode($jsonBlob['data']);
160
-					}
161
-				}
162
-			}
163
-		} catch (NotFoundException $e) {
164
-			// File does not already exists
165
-			$file = $rootFolder->newFile($this->fileName);
166
-		}
167
-
168
-		// Refresh the file content
169
-		try {
170
-			$responseJson = $this->fetch($ETag, $content);
171
-			$file->putContent(json_encode($responseJson));
172
-			return json_decode($file->getContent(), true)['data'];
173
-		} catch (ConnectException $e) {
174
-			$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO, 'message' => 'Could not connect to appstore']);
175
-			return [];
176
-		} catch (\Exception $e) {
177
-			$this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO]);
178
-			return [];
179
-		}
180
-	}
181
-
182
-	/**
183
-	 * Get the currently Nextcloud version
184
-	 * @return string
185
-	 */
186
-	protected function getVersion() {
187
-		if ($this->version === null) {
188
-			$this->version = $this->config->getSystemValue('version', '0.0.0');
189
-		}
190
-		return $this->version;
191
-	}
192
-
193
-	/**
194
-	 * Set the current Nextcloud version
195
-	 * @param string $version
196
-	 */
197
-	public function setVersion(string $version) {
198
-		$this->version = $version;
199
-	}
42
+    const INVALIDATE_AFTER_SECONDS = 300;
43
+
44
+    /** @var IAppData */
45
+    protected $appData;
46
+    /** @var IClientService */
47
+    protected $clientService;
48
+    /** @var ITimeFactory */
49
+    protected $timeFactory;
50
+    /** @var IConfig */
51
+    protected $config;
52
+    /** @var Ilogger */
53
+    protected $logger;
54
+    /** @var string */
55
+    protected $fileName;
56
+    /** @var string */
57
+    protected $endpointUrl;
58
+    /** @var string */
59
+    protected $version;
60
+
61
+    /**
62
+     * @param Factory $appDataFactory
63
+     * @param IClientService $clientService
64
+     * @param ITimeFactory $timeFactory
65
+     * @param IConfig $config
66
+     * @param ILogger $logger
67
+     */
68
+    public function __construct(Factory $appDataFactory,
69
+                                IClientService $clientService,
70
+                                ITimeFactory $timeFactory,
71
+                                IConfig $config,
72
+                                ILogger $logger) {
73
+        $this->appData = $appDataFactory->get('appstore');
74
+        $this->clientService = $clientService;
75
+        $this->timeFactory = $timeFactory;
76
+        $this->config = $config;
77
+        $this->logger = $logger;
78
+    }
79
+
80
+    /**
81
+     * Fetches the response from the server
82
+     *
83
+     * @param string $ETag
84
+     * @param string $content
85
+     *
86
+     * @return array
87
+     */
88
+    protected function fetch($ETag, $content) {
89
+        $appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
90
+
91
+        if (!$appstoreenabled) {
92
+            return [];
93
+        }
94
+
95
+        $options = [
96
+            'timeout' => 10,
97
+        ];
98
+
99
+        if ($ETag !== '') {
100
+            $options['headers'] = [
101
+                'If-None-Match' => $ETag,
102
+            ];
103
+        }
104
+
105
+        $client = $this->clientService->newClient();
106
+        $response = $client->get($this->endpointUrl, $options);
107
+
108
+        $responseJson = [];
109
+        if ($response->getStatusCode() === Http::STATUS_NOT_MODIFIED) {
110
+            $responseJson['data'] = json_decode($content, true);
111
+        } else {
112
+            $responseJson['data'] = json_decode($response->getBody(), true);
113
+            $ETag = $response->getHeader('ETag');
114
+        }
115
+
116
+        $responseJson['timestamp'] = $this->timeFactory->getTime();
117
+        $responseJson['ncversion'] = $this->getVersion();
118
+        if ($ETag !== '') {
119
+            $responseJson['ETag'] = $ETag;
120
+        }
121
+
122
+        return $responseJson;
123
+    }
124
+
125
+    /**
126
+     * Returns the array with the categories on the appstore server
127
+     *
128
+     * @return array
129
+     */
130
+    public function get() {
131
+        $appstoreenabled = $this->config->getSystemValue('appstoreenabled', true);
132
+        $internetavailable = $this->config->getSystemValue('has_internet_connection', true);
133
+
134
+        if (!$appstoreenabled || !$internetavailable) {
135
+            return [];
136
+        }
137
+
138
+        $rootFolder = $this->appData->getFolder('/');
139
+
140
+        $ETag = '';
141
+        $content = '';
142
+
143
+        try {
144
+            // File does already exists
145
+            $file = $rootFolder->getFile($this->fileName);
146
+            $jsonBlob = json_decode($file->getContent(), true);
147
+            if (is_array($jsonBlob)) {
148
+
149
+                // No caching when the version has been updated
150
+                if (isset($jsonBlob['ncversion']) && $jsonBlob['ncversion'] === $this->getVersion()) {
151
+
152
+                    // If the timestamp is older than 300 seconds request the files new
153
+                    if ((int)$jsonBlob['timestamp'] > ($this->timeFactory->getTime() - self::INVALIDATE_AFTER_SECONDS)) {
154
+                        return $jsonBlob['data'];
155
+                    }
156
+
157
+                    if (isset($jsonBlob['ETag'])) {
158
+                        $ETag = $jsonBlob['ETag'];
159
+                        $content = json_encode($jsonBlob['data']);
160
+                    }
161
+                }
162
+            }
163
+        } catch (NotFoundException $e) {
164
+            // File does not already exists
165
+            $file = $rootFolder->newFile($this->fileName);
166
+        }
167
+
168
+        // Refresh the file content
169
+        try {
170
+            $responseJson = $this->fetch($ETag, $content);
171
+            $file->putContent(json_encode($responseJson));
172
+            return json_decode($file->getContent(), true)['data'];
173
+        } catch (ConnectException $e) {
174
+            $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO, 'message' => 'Could not connect to appstore']);
175
+            return [];
176
+        } catch (\Exception $e) {
177
+            $this->logger->logException($e, ['app' => 'appstoreFetcher', 'level' => ILogger::INFO]);
178
+            return [];
179
+        }
180
+    }
181
+
182
+    /**
183
+     * Get the currently Nextcloud version
184
+     * @return string
185
+     */
186
+    protected function getVersion() {
187
+        if ($this->version === null) {
188
+            $this->version = $this->config->getSystemValue('version', '0.0.0');
189
+        }
190
+        return $this->version;
191
+    }
192
+
193
+    /**
194
+     * Set the current Nextcloud version
195
+     * @param string $version
196
+     */
197
+    public function setVersion(string $version) {
198
+        $this->version = $version;
199
+    }
200 200
 }
Please login to merge, or discard this patch.
lib/private/Files/Storage/DAV.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -34,7 +34,6 @@
 block discarded – undo
34 34
 namespace OC\Files\Storage;
35 35
 
36 36
 use Exception;
37
-use GuzzleHttp\Exception\RequestException;
38 37
 use OCP\ILogger;
39 38
 use Psr\Http\Message\ResponseInterface;
40 39
 use Icewind\Streams\CallbackWrapper;
Please login to merge, or discard this patch.
Indentation   +796 added lines, -796 removed lines patch added patch discarded remove patch
@@ -58,801 +58,801 @@
 block discarded – undo
58 58
  * @package OC\Files\Storage
59 59
  */
60 60
 class DAV extends Common {
61
-	/** @var string */
62
-	protected $password;
63
-	/** @var string */
64
-	protected $user;
65
-	/** @var string */
66
-	protected $authType;
67
-	/** @var string */
68
-	protected $host;
69
-	/** @var bool */
70
-	protected $secure;
71
-	/** @var string */
72
-	protected $root;
73
-	/** @var string */
74
-	protected $certPath;
75
-	/** @var bool */
76
-	protected $ready;
77
-	/** @var Client */
78
-	protected $client;
79
-	/** @var ArrayCache */
80
-	protected $statCache;
81
-	/** @var \OCP\Http\Client\IClientService */
82
-	protected $httpClientService;
83
-
84
-	/**
85
-	 * @param array $params
86
-	 * @throws \Exception
87
-	 */
88
-	public function __construct($params) {
89
-		$this->statCache = new ArrayCache();
90
-		$this->httpClientService = \OC::$server->getHTTPClientService();
91
-		if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
92
-			$host = $params['host'];
93
-			//remove leading http[s], will be generated in createBaseUri()
94
-			if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
95
-			else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
96
-			$this->host = $host;
97
-			$this->user = $params['user'];
98
-			$this->password = $params['password'];
99
-			if (isset($params['authType'])) {
100
-				$this->authType = $params['authType'];
101
-			}
102
-			if (isset($params['secure'])) {
103
-				if (is_string($params['secure'])) {
104
-					$this->secure = ($params['secure'] === 'true');
105
-				} else {
106
-					$this->secure = (bool)$params['secure'];
107
-				}
108
-			} else {
109
-				$this->secure = false;
110
-			}
111
-			if ($this->secure === true) {
112
-				// inject mock for testing
113
-				$certManager = \OC::$server->getCertificateManager();
114
-				if (is_null($certManager)) { //no user
115
-					$certManager = \OC::$server->getCertificateManager(null);
116
-				}
117
-				$certPath = $certManager->getAbsoluteBundlePath();
118
-				if (file_exists($certPath)) {
119
-					$this->certPath = $certPath;
120
-				}
121
-			}
122
-			$this->root = $params['root'] ?? '/';
123
-			$this->root = '/' . ltrim($this->root, '/');
124
-			$this->root = rtrim($this->root, '/') . '/';
125
-		} else {
126
-			throw new \Exception('Invalid webdav storage configuration');
127
-		}
128
-	}
129
-
130
-	protected function init() {
131
-		if ($this->ready) {
132
-			return;
133
-		}
134
-		$this->ready = true;
135
-
136
-		$settings = [
137
-			'baseUri' => $this->createBaseUri(),
138
-			'userName' => $this->user,
139
-			'password' => $this->password,
140
-		];
141
-		if (isset($this->authType)) {
142
-			$settings['authType'] = $this->authType;
143
-		}
144
-
145
-		$proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
146
-		if ($proxy !== '') {
147
-			$settings['proxy'] = $proxy;
148
-		}
149
-
150
-		$this->client = new Client($settings);
151
-		$this->client->setThrowExceptions(true);
152
-		if ($this->secure === true && $this->certPath) {
153
-			$this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
154
-		}
155
-	}
156
-
157
-	/**
158
-	 * Clear the stat cache
159
-	 */
160
-	public function clearStatCache() {
161
-		$this->statCache->clear();
162
-	}
163
-
164
-	/** {@inheritdoc} */
165
-	public function getId() {
166
-		return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
167
-	}
168
-
169
-	/** {@inheritdoc} */
170
-	public function createBaseUri() {
171
-		$baseUri = 'http';
172
-		if ($this->secure) {
173
-			$baseUri .= 's';
174
-		}
175
-		$baseUri .= '://' . $this->host . $this->root;
176
-		return $baseUri;
177
-	}
178
-
179
-	/** {@inheritdoc} */
180
-	public function mkdir($path) {
181
-		$this->init();
182
-		$path = $this->cleanPath($path);
183
-		$result = $this->simpleResponse('MKCOL', $path, null, 201);
184
-		if ($result) {
185
-			$this->statCache->set($path, true);
186
-		}
187
-		return $result;
188
-	}
189
-
190
-	/** {@inheritdoc} */
191
-	public function rmdir($path) {
192
-		$this->init();
193
-		$path = $this->cleanPath($path);
194
-		// FIXME: some WebDAV impl return 403 when trying to DELETE
195
-		// a non-empty folder
196
-		$result = $this->simpleResponse('DELETE', $path . '/', null, 204);
197
-		$this->statCache->clear($path . '/');
198
-		$this->statCache->remove($path);
199
-		return $result;
200
-	}
201
-
202
-	/** {@inheritdoc} */
203
-	public function opendir($path) {
204
-		$this->init();
205
-		$path = $this->cleanPath($path);
206
-		try {
207
-			$response = $this->client->propFind(
208
-				$this->encodePath($path),
209
-				['{DAV:}href'],
210
-				1
211
-			);
212
-			if ($response === false) {
213
-				return false;
214
-			}
215
-			$content = [];
216
-			$files = array_keys($response);
217
-			array_shift($files); //the first entry is the current directory
218
-
219
-			if (!$this->statCache->hasKey($path)) {
220
-				$this->statCache->set($path, true);
221
-			}
222
-			foreach ($files as $file) {
223
-				$file = urldecode($file);
224
-				// do not store the real entry, we might not have all properties
225
-				if (!$this->statCache->hasKey($path)) {
226
-					$this->statCache->set($file, true);
227
-				}
228
-				$file = basename($file);
229
-				$content[] = $file;
230
-			}
231
-			return IteratorDirectory::wrap($content);
232
-		} catch (\Exception $e) {
233
-			$this->convertException($e, $path);
234
-		}
235
-		return false;
236
-	}
237
-
238
-	/**
239
-	 * Propfind call with cache handling.
240
-	 *
241
-	 * First checks if information is cached.
242
-	 * If not, request it from the server then store to cache.
243
-	 *
244
-	 * @param string $path path to propfind
245
-	 *
246
-	 * @return array|boolean propfind response or false if the entry was not found
247
-	 *
248
-	 * @throws ClientHttpException
249
-	 */
250
-	protected function propfind($path) {
251
-		$path = $this->cleanPath($path);
252
-		$cachedResponse = $this->statCache->get($path);
253
-		// we either don't know it, or we know it exists but need more details
254
-		if (is_null($cachedResponse) || $cachedResponse === true) {
255
-			$this->init();
256
-			try {
257
-				$response = $this->client->propFind(
258
-					$this->encodePath($path),
259
-					array(
260
-						'{DAV:}getlastmodified',
261
-						'{DAV:}getcontentlength',
262
-						'{DAV:}getcontenttype',
263
-						'{http://owncloud.org/ns}permissions',
264
-						'{http://open-collaboration-services.org/ns}share-permissions',
265
-						'{DAV:}resourcetype',
266
-						'{DAV:}getetag',
267
-					)
268
-				);
269
-				$this->statCache->set($path, $response);
270
-			} catch (ClientHttpException $e) {
271
-				if ($e->getHttpStatus() === 404) {
272
-					$this->statCache->clear($path . '/');
273
-					$this->statCache->set($path, false);
274
-					return false;
275
-				}
276
-				$this->convertException($e, $path);
277
-			} catch (\Exception $e) {
278
-				$this->convertException($e, $path);
279
-			}
280
-		} else {
281
-			$response = $cachedResponse;
282
-		}
283
-		return $response;
284
-	}
285
-
286
-	/** {@inheritdoc} */
287
-	public function filetype($path) {
288
-		try {
289
-			$response = $this->propfind($path);
290
-			if ($response === false) {
291
-				return false;
292
-			}
293
-			$responseType = [];
294
-			if (isset($response["{DAV:}resourcetype"])) {
295
-				/** @var ResourceType[] $response */
296
-				$responseType = $response["{DAV:}resourcetype"]->getValue();
297
-			}
298
-			return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
299
-		} catch (\Exception $e) {
300
-			$this->convertException($e, $path);
301
-		}
302
-		return false;
303
-	}
304
-
305
-	/** {@inheritdoc} */
306
-	public function file_exists($path) {
307
-		try {
308
-			$path = $this->cleanPath($path);
309
-			$cachedState = $this->statCache->get($path);
310
-			if ($cachedState === false) {
311
-				// we know the file doesn't exist
312
-				return false;
313
-			} else if (!is_null($cachedState)) {
314
-				return true;
315
-			}
316
-			// need to get from server
317
-			return ($this->propfind($path) !== false);
318
-		} catch (\Exception $e) {
319
-			$this->convertException($e, $path);
320
-		}
321
-		return false;
322
-	}
323
-
324
-	/** {@inheritdoc} */
325
-	public function unlink($path) {
326
-		$this->init();
327
-		$path = $this->cleanPath($path);
328
-		$result = $this->simpleResponse('DELETE', $path, null, 204);
329
-		$this->statCache->clear($path . '/');
330
-		$this->statCache->remove($path);
331
-		return $result;
332
-	}
333
-
334
-	/** {@inheritdoc} */
335
-	public function fopen($path, $mode) {
336
-		$this->init();
337
-		$path = $this->cleanPath($path);
338
-		switch ($mode) {
339
-			case 'r':
340
-			case 'rb':
341
-				try {
342
-					$response = $this->httpClientService
343
-						->newClient()
344
-						->get($this->createBaseUri() . $this->encodePath($path), [
345
-							'auth' => [$this->user, $this->password],
346
-							'stream' => true
347
-						]);
348
-				} catch (\GuzzleHttp\Exception\ClientException $e) {
349
-					if ($e->getResponse() instanceof ResponseInterface
350
-						&& $e->getResponse()->getStatusCode() === 404) {
351
-						return false;
352
-					} else {
353
-						throw $e;
354
-					}
355
-				}
356
-
357
-				if ($response->getStatusCode() !== Http::STATUS_OK) {
358
-					if ($response->getStatusCode() === Http::STATUS_LOCKED) {
359
-						throw new \OCP\Lock\LockedException($path);
360
-					} else {
361
-						Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), ILogger::ERROR);
362
-					}
363
-				}
364
-
365
-				return $response->getBody();
366
-			case 'w':
367
-			case 'wb':
368
-			case 'a':
369
-			case 'ab':
370
-			case 'r+':
371
-			case 'w+':
372
-			case 'wb+':
373
-			case 'a+':
374
-			case 'x':
375
-			case 'x+':
376
-			case 'c':
377
-			case 'c+':
378
-				//emulate these
379
-				$tempManager = \OC::$server->getTempManager();
380
-				if (strrpos($path, '.') !== false) {
381
-					$ext = substr($path, strrpos($path, '.'));
382
-				} else {
383
-					$ext = '';
384
-				}
385
-				if ($this->file_exists($path)) {
386
-					if (!$this->isUpdatable($path)) {
387
-						return false;
388
-					}
389
-					if ($mode === 'w' or $mode === 'w+') {
390
-						$tmpFile = $tempManager->getTemporaryFile($ext);
391
-					} else {
392
-						$tmpFile = $this->getCachedFile($path);
393
-					}
394
-				} else {
395
-					if (!$this->isCreatable(dirname($path))) {
396
-						return false;
397
-					}
398
-					$tmpFile = $tempManager->getTemporaryFile($ext);
399
-				}
400
-				$handle = fopen($tmpFile, $mode);
401
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
402
-					$this->writeBack($tmpFile, $path);
403
-				});
404
-		}
405
-	}
406
-
407
-	/**
408
-	 * @param string $tmpFile
409
-	 */
410
-	public function writeBack($tmpFile, $path) {
411
-		$this->uploadFile($tmpFile, $path);
412
-		unlink($tmpFile);
413
-	}
414
-
415
-	/** {@inheritdoc} */
416
-	public function free_space($path) {
417
-		$this->init();
418
-		$path = $this->cleanPath($path);
419
-		try {
420
-			// TODO: cacheable ?
421
-			$response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
422
-			if ($response === false) {
423
-				return FileInfo::SPACE_UNKNOWN;
424
-			}
425
-			if (isset($response['{DAV:}quota-available-bytes'])) {
426
-				return (int)$response['{DAV:}quota-available-bytes'];
427
-			} else {
428
-				return FileInfo::SPACE_UNKNOWN;
429
-			}
430
-		} catch (\Exception $e) {
431
-			return FileInfo::SPACE_UNKNOWN;
432
-		}
433
-	}
434
-
435
-	/** {@inheritdoc} */
436
-	public function touch($path, $mtime = null) {
437
-		$this->init();
438
-		if (is_null($mtime)) {
439
-			$mtime = time();
440
-		}
441
-		$path = $this->cleanPath($path);
442
-
443
-		// if file exists, update the mtime, else create a new empty file
444
-		if ($this->file_exists($path)) {
445
-			try {
446
-				$this->statCache->remove($path);
447
-				$this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
448
-				// non-owncloud clients might not have accepted the property, need to recheck it
449
-				$response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
450
-				if ($response === false) {
451
-					return false;
452
-				}
453
-				if (isset($response['{DAV:}getlastmodified'])) {
454
-					$remoteMtime = strtotime($response['{DAV:}getlastmodified']);
455
-					if ($remoteMtime !== $mtime) {
456
-						// server has not accepted the mtime
457
-						return false;
458
-					}
459
-				}
460
-			} catch (ClientHttpException $e) {
461
-				if ($e->getHttpStatus() === 501) {
462
-					return false;
463
-				}
464
-				$this->convertException($e, $path);
465
-				return false;
466
-			} catch (\Exception $e) {
467
-				$this->convertException($e, $path);
468
-				return false;
469
-			}
470
-		} else {
471
-			$this->file_put_contents($path, '');
472
-		}
473
-		return true;
474
-	}
475
-
476
-	/**
477
-	 * @param string $path
478
-	 * @param string $data
479
-	 * @return int
480
-	 */
481
-	public function file_put_contents($path, $data) {
482
-		$path = $this->cleanPath($path);
483
-		$result = parent::file_put_contents($path, $data);
484
-		$this->statCache->remove($path);
485
-		return $result;
486
-	}
487
-
488
-	/**
489
-	 * @param string $path
490
-	 * @param string $target
491
-	 */
492
-	protected function uploadFile($path, $target) {
493
-		$this->init();
494
-
495
-		// invalidate
496
-		$target = $this->cleanPath($target);
497
-		$this->statCache->remove($target);
498
-		$source = fopen($path, 'r');
499
-
500
-		$this->httpClientService
501
-			->newClient()
502
-			->put($this->createBaseUri() . $this->encodePath($target), [
503
-				'body' => $source,
504
-				'auth' => [$this->user, $this->password]
505
-			]);
506
-
507
-		$this->removeCachedFile($target);
508
-	}
509
-
510
-	/** {@inheritdoc} */
511
-	public function rename($path1, $path2) {
512
-		$this->init();
513
-		$path1 = $this->cleanPath($path1);
514
-		$path2 = $this->cleanPath($path2);
515
-		try {
516
-			// overwrite directory ?
517
-			if ($this->is_dir($path2)) {
518
-				// needs trailing slash in destination
519
-				$path2 = rtrim($path2, '/') . '/';
520
-			}
521
-			$this->client->request(
522
-				'MOVE',
523
-				$this->encodePath($path1),
524
-				null,
525
-				[
526
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
527
-				]
528
-			);
529
-			$this->statCache->clear($path1 . '/');
530
-			$this->statCache->clear($path2 . '/');
531
-			$this->statCache->set($path1, false);
532
-			$this->statCache->set($path2, true);
533
-			$this->removeCachedFile($path1);
534
-			$this->removeCachedFile($path2);
535
-			return true;
536
-		} catch (\Exception $e) {
537
-			$this->convertException($e);
538
-		}
539
-		return false;
540
-	}
541
-
542
-	/** {@inheritdoc} */
543
-	public function copy($path1, $path2) {
544
-		$this->init();
545
-		$path1 = $this->cleanPath($path1);
546
-		$path2 = $this->cleanPath($path2);
547
-		try {
548
-			// overwrite directory ?
549
-			if ($this->is_dir($path2)) {
550
-				// needs trailing slash in destination
551
-				$path2 = rtrim($path2, '/') . '/';
552
-			}
553
-			$this->client->request(
554
-				'COPY',
555
-				$this->encodePath($path1),
556
-				null,
557
-				[
558
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
559
-				]
560
-			);
561
-			$this->statCache->clear($path2 . '/');
562
-			$this->statCache->set($path2, true);
563
-			$this->removeCachedFile($path2);
564
-			return true;
565
-		} catch (\Exception $e) {
566
-			$this->convertException($e);
567
-		}
568
-		return false;
569
-	}
570
-
571
-	/** {@inheritdoc} */
572
-	public function stat($path) {
573
-		try {
574
-			$response = $this->propfind($path);
575
-			if (!$response) {
576
-				return false;
577
-			}
578
-			return [
579
-				'mtime' => strtotime($response['{DAV:}getlastmodified']),
580
-				'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
581
-			];
582
-		} catch (\Exception $e) {
583
-			$this->convertException($e, $path);
584
-		}
585
-		return array();
586
-	}
587
-
588
-	/** {@inheritdoc} */
589
-	public function getMimeType($path) {
590
-		$remoteMimetype = $this->getMimeTypeFromRemote($path);
591
-		if ($remoteMimetype === 'application/octet-stream') {
592
-			return \OC::$server->getMimeTypeDetector()->detectPath($path);
593
-		} else {
594
-			return $remoteMimetype;
595
-		}
596
-	}
597
-
598
-	public function getMimeTypeFromRemote($path) {
599
-		try {
600
-			$response = $this->propfind($path);
601
-			if ($response === false) {
602
-				return false;
603
-			}
604
-			$responseType = [];
605
-			if (isset($response["{DAV:}resourcetype"])) {
606
-				/** @var ResourceType[] $response */
607
-				$responseType = $response["{DAV:}resourcetype"]->getValue();
608
-			}
609
-			$type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
610
-			if ($type == 'dir') {
611
-				return 'httpd/unix-directory';
612
-			} elseif (isset($response['{DAV:}getcontenttype'])) {
613
-				return $response['{DAV:}getcontenttype'];
614
-			} else {
615
-				return 'application/octet-stream';
616
-			}
617
-		} catch (\Exception $e) {
618
-			return false;
619
-		}
620
-	}
621
-
622
-	/**
623
-	 * @param string $path
624
-	 * @return string
625
-	 */
626
-	public function cleanPath($path) {
627
-		if ($path === '') {
628
-			return $path;
629
-		}
630
-		$path = Filesystem::normalizePath($path);
631
-		// remove leading slash
632
-		return substr($path, 1);
633
-	}
634
-
635
-	/**
636
-	 * URL encodes the given path but keeps the slashes
637
-	 *
638
-	 * @param string $path to encode
639
-	 * @return string encoded path
640
-	 */
641
-	protected function encodePath($path) {
642
-		// slashes need to stay
643
-		return str_replace('%2F', '/', rawurlencode($path));
644
-	}
645
-
646
-	/**
647
-	 * @param string $method
648
-	 * @param string $path
649
-	 * @param string|resource|null $body
650
-	 * @param int $expected
651
-	 * @return bool
652
-	 * @throws StorageInvalidException
653
-	 * @throws StorageNotAvailableException
654
-	 */
655
-	protected function simpleResponse($method, $path, $body, $expected) {
656
-		$path = $this->cleanPath($path);
657
-		try {
658
-			$response = $this->client->request($method, $this->encodePath($path), $body);
659
-			return $response['statusCode'] == $expected;
660
-		} catch (ClientHttpException $e) {
661
-			if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
662
-				$this->statCache->clear($path . '/');
663
-				$this->statCache->set($path, false);
664
-				return false;
665
-			}
666
-
667
-			$this->convertException($e, $path);
668
-		} catch (\Exception $e) {
669
-			$this->convertException($e, $path);
670
-		}
671
-		return false;
672
-	}
673
-
674
-	/**
675
-	 * check if curl is installed
676
-	 */
677
-	public static function checkDependencies() {
678
-		return true;
679
-	}
680
-
681
-	/** {@inheritdoc} */
682
-	public function isUpdatable($path) {
683
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
684
-	}
685
-
686
-	/** {@inheritdoc} */
687
-	public function isCreatable($path) {
688
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
689
-	}
690
-
691
-	/** {@inheritdoc} */
692
-	public function isSharable($path) {
693
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
694
-	}
695
-
696
-	/** {@inheritdoc} */
697
-	public function isDeletable($path) {
698
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
699
-	}
700
-
701
-	/** {@inheritdoc} */
702
-	public function getPermissions($path) {
703
-		$this->init();
704
-		$path = $this->cleanPath($path);
705
-		$response = $this->propfind($path);
706
-		if ($response === false) {
707
-			return 0;
708
-		}
709
-		if (isset($response['{http://owncloud.org/ns}permissions'])) {
710
-			return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
711
-		} else if ($this->is_dir($path)) {
712
-			return Constants::PERMISSION_ALL;
713
-		} else if ($this->file_exists($path)) {
714
-			return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
715
-		} else {
716
-			return 0;
717
-		}
718
-	}
719
-
720
-	/** {@inheritdoc} */
721
-	public function getETag($path) {
722
-		$this->init();
723
-		$path = $this->cleanPath($path);
724
-		$response = $this->propfind($path);
725
-		if ($response === false) {
726
-			return null;
727
-		}
728
-		if (isset($response['{DAV:}getetag'])) {
729
-			return trim($response['{DAV:}getetag'], '"');
730
-		}
731
-		return parent::getEtag($path);
732
-	}
733
-
734
-	/**
735
-	 * @param string $permissionsString
736
-	 * @return int
737
-	 */
738
-	protected function parsePermissions($permissionsString) {
739
-		$permissions = Constants::PERMISSION_READ;
740
-		if (strpos($permissionsString, 'R') !== false) {
741
-			$permissions |= Constants::PERMISSION_SHARE;
742
-		}
743
-		if (strpos($permissionsString, 'D') !== false) {
744
-			$permissions |= Constants::PERMISSION_DELETE;
745
-		}
746
-		if (strpos($permissionsString, 'W') !== false) {
747
-			$permissions |= Constants::PERMISSION_UPDATE;
748
-		}
749
-		if (strpos($permissionsString, 'CK') !== false) {
750
-			$permissions |= Constants::PERMISSION_CREATE;
751
-			$permissions |= Constants::PERMISSION_UPDATE;
752
-		}
753
-		return $permissions;
754
-	}
755
-
756
-	/**
757
-	 * check if a file or folder has been updated since $time
758
-	 *
759
-	 * @param string $path
760
-	 * @param int $time
761
-	 * @throws \OCP\Files\StorageNotAvailableException
762
-	 * @return bool
763
-	 */
764
-	public function hasUpdated($path, $time) {
765
-		$this->init();
766
-		$path = $this->cleanPath($path);
767
-		try {
768
-			// force refresh for $path
769
-			$this->statCache->remove($path);
770
-			$response = $this->propfind($path);
771
-			if ($response === false) {
772
-				if ($path === '') {
773
-					// if root is gone it means the storage is not available
774
-					throw new StorageNotAvailableException('root is gone');
775
-				}
776
-				return false;
777
-			}
778
-			if (isset($response['{DAV:}getetag'])) {
779
-				$cachedData = $this->getCache()->get($path);
780
-				$etag = null;
781
-				if (isset($response['{DAV:}getetag'])) {
782
-					$etag = trim($response['{DAV:}getetag'], '"');
783
-				}
784
-				if (!empty($etag) && $cachedData['etag'] !== $etag) {
785
-					return true;
786
-				} else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
787
-					$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
788
-					return $sharePermissions !== $cachedData['permissions'];
789
-				} else if (isset($response['{http://owncloud.org/ns}permissions'])) {
790
-					$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
791
-					return $permissions !== $cachedData['permissions'];
792
-				} else {
793
-					return false;
794
-				}
795
-			} else {
796
-				$remoteMtime = strtotime($response['{DAV:}getlastmodified']);
797
-				return $remoteMtime > $time;
798
-			}
799
-		} catch (ClientHttpException $e) {
800
-			if ($e->getHttpStatus() === 405) {
801
-				if ($path === '') {
802
-					// if root is gone it means the storage is not available
803
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
804
-				}
805
-				return false;
806
-			}
807
-			$this->convertException($e, $path);
808
-			return false;
809
-		} catch (\Exception $e) {
810
-			$this->convertException($e, $path);
811
-			return false;
812
-		}
813
-	}
814
-
815
-	/**
816
-	 * Interpret the given exception and decide whether it is due to an
817
-	 * unavailable storage, invalid storage or other.
818
-	 * This will either throw StorageInvalidException, StorageNotAvailableException
819
-	 * or do nothing.
820
-	 *
821
-	 * @param Exception $e sabre exception
822
-	 * @param string $path optional path from the operation
823
-	 *
824
-	 * @throws StorageInvalidException if the storage is invalid, for example
825
-	 * when the authentication expired or is invalid
826
-	 * @throws StorageNotAvailableException if the storage is not available,
827
-	 * which might be temporary
828
-	 */
829
-	protected function convertException(Exception $e, $path = '') {
830
-		\OC::$server->getLogger()->logException($e, ['app' => 'files_external']);
831
-		if ($e instanceof ClientHttpException) {
832
-			if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
833
-				throw new \OCP\Lock\LockedException($path);
834
-			}
835
-			if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
836
-				// either password was changed or was invalid all along
837
-				throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
838
-			} else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
839
-				// ignore exception for MethodNotAllowed, false will be returned
840
-				return;
841
-			}
842
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
843
-		} else if ($e instanceof ClientException) {
844
-			// connection timeout or refused, server could be temporarily down
845
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
846
-		} else if ($e instanceof \InvalidArgumentException) {
847
-			// parse error because the server returned HTML instead of XML,
848
-			// possibly temporarily down
849
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
850
-		} else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
851
-			// rethrow
852
-			throw $e;
853
-		}
854
-
855
-		// TODO: only log for now, but in the future need to wrap/rethrow exception
856
-	}
61
+    /** @var string */
62
+    protected $password;
63
+    /** @var string */
64
+    protected $user;
65
+    /** @var string */
66
+    protected $authType;
67
+    /** @var string */
68
+    protected $host;
69
+    /** @var bool */
70
+    protected $secure;
71
+    /** @var string */
72
+    protected $root;
73
+    /** @var string */
74
+    protected $certPath;
75
+    /** @var bool */
76
+    protected $ready;
77
+    /** @var Client */
78
+    protected $client;
79
+    /** @var ArrayCache */
80
+    protected $statCache;
81
+    /** @var \OCP\Http\Client\IClientService */
82
+    protected $httpClientService;
83
+
84
+    /**
85
+     * @param array $params
86
+     * @throws \Exception
87
+     */
88
+    public function __construct($params) {
89
+        $this->statCache = new ArrayCache();
90
+        $this->httpClientService = \OC::$server->getHTTPClientService();
91
+        if (isset($params['host']) && isset($params['user']) && isset($params['password'])) {
92
+            $host = $params['host'];
93
+            //remove leading http[s], will be generated in createBaseUri()
94
+            if (substr($host, 0, 8) == "https://") $host = substr($host, 8);
95
+            else if (substr($host, 0, 7) == "http://") $host = substr($host, 7);
96
+            $this->host = $host;
97
+            $this->user = $params['user'];
98
+            $this->password = $params['password'];
99
+            if (isset($params['authType'])) {
100
+                $this->authType = $params['authType'];
101
+            }
102
+            if (isset($params['secure'])) {
103
+                if (is_string($params['secure'])) {
104
+                    $this->secure = ($params['secure'] === 'true');
105
+                } else {
106
+                    $this->secure = (bool)$params['secure'];
107
+                }
108
+            } else {
109
+                $this->secure = false;
110
+            }
111
+            if ($this->secure === true) {
112
+                // inject mock for testing
113
+                $certManager = \OC::$server->getCertificateManager();
114
+                if (is_null($certManager)) { //no user
115
+                    $certManager = \OC::$server->getCertificateManager(null);
116
+                }
117
+                $certPath = $certManager->getAbsoluteBundlePath();
118
+                if (file_exists($certPath)) {
119
+                    $this->certPath = $certPath;
120
+                }
121
+            }
122
+            $this->root = $params['root'] ?? '/';
123
+            $this->root = '/' . ltrim($this->root, '/');
124
+            $this->root = rtrim($this->root, '/') . '/';
125
+        } else {
126
+            throw new \Exception('Invalid webdav storage configuration');
127
+        }
128
+    }
129
+
130
+    protected function init() {
131
+        if ($this->ready) {
132
+            return;
133
+        }
134
+        $this->ready = true;
135
+
136
+        $settings = [
137
+            'baseUri' => $this->createBaseUri(),
138
+            'userName' => $this->user,
139
+            'password' => $this->password,
140
+        ];
141
+        if (isset($this->authType)) {
142
+            $settings['authType'] = $this->authType;
143
+        }
144
+
145
+        $proxy = \OC::$server->getConfig()->getSystemValue('proxy', '');
146
+        if ($proxy !== '') {
147
+            $settings['proxy'] = $proxy;
148
+        }
149
+
150
+        $this->client = new Client($settings);
151
+        $this->client->setThrowExceptions(true);
152
+        if ($this->secure === true && $this->certPath) {
153
+            $this->client->addCurlSetting(CURLOPT_CAINFO, $this->certPath);
154
+        }
155
+    }
156
+
157
+    /**
158
+     * Clear the stat cache
159
+     */
160
+    public function clearStatCache() {
161
+        $this->statCache->clear();
162
+    }
163
+
164
+    /** {@inheritdoc} */
165
+    public function getId() {
166
+        return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
167
+    }
168
+
169
+    /** {@inheritdoc} */
170
+    public function createBaseUri() {
171
+        $baseUri = 'http';
172
+        if ($this->secure) {
173
+            $baseUri .= 's';
174
+        }
175
+        $baseUri .= '://' . $this->host . $this->root;
176
+        return $baseUri;
177
+    }
178
+
179
+    /** {@inheritdoc} */
180
+    public function mkdir($path) {
181
+        $this->init();
182
+        $path = $this->cleanPath($path);
183
+        $result = $this->simpleResponse('MKCOL', $path, null, 201);
184
+        if ($result) {
185
+            $this->statCache->set($path, true);
186
+        }
187
+        return $result;
188
+    }
189
+
190
+    /** {@inheritdoc} */
191
+    public function rmdir($path) {
192
+        $this->init();
193
+        $path = $this->cleanPath($path);
194
+        // FIXME: some WebDAV impl return 403 when trying to DELETE
195
+        // a non-empty folder
196
+        $result = $this->simpleResponse('DELETE', $path . '/', null, 204);
197
+        $this->statCache->clear($path . '/');
198
+        $this->statCache->remove($path);
199
+        return $result;
200
+    }
201
+
202
+    /** {@inheritdoc} */
203
+    public function opendir($path) {
204
+        $this->init();
205
+        $path = $this->cleanPath($path);
206
+        try {
207
+            $response = $this->client->propFind(
208
+                $this->encodePath($path),
209
+                ['{DAV:}href'],
210
+                1
211
+            );
212
+            if ($response === false) {
213
+                return false;
214
+            }
215
+            $content = [];
216
+            $files = array_keys($response);
217
+            array_shift($files); //the first entry is the current directory
218
+
219
+            if (!$this->statCache->hasKey($path)) {
220
+                $this->statCache->set($path, true);
221
+            }
222
+            foreach ($files as $file) {
223
+                $file = urldecode($file);
224
+                // do not store the real entry, we might not have all properties
225
+                if (!$this->statCache->hasKey($path)) {
226
+                    $this->statCache->set($file, true);
227
+                }
228
+                $file = basename($file);
229
+                $content[] = $file;
230
+            }
231
+            return IteratorDirectory::wrap($content);
232
+        } catch (\Exception $e) {
233
+            $this->convertException($e, $path);
234
+        }
235
+        return false;
236
+    }
237
+
238
+    /**
239
+     * Propfind call with cache handling.
240
+     *
241
+     * First checks if information is cached.
242
+     * If not, request it from the server then store to cache.
243
+     *
244
+     * @param string $path path to propfind
245
+     *
246
+     * @return array|boolean propfind response or false if the entry was not found
247
+     *
248
+     * @throws ClientHttpException
249
+     */
250
+    protected function propfind($path) {
251
+        $path = $this->cleanPath($path);
252
+        $cachedResponse = $this->statCache->get($path);
253
+        // we either don't know it, or we know it exists but need more details
254
+        if (is_null($cachedResponse) || $cachedResponse === true) {
255
+            $this->init();
256
+            try {
257
+                $response = $this->client->propFind(
258
+                    $this->encodePath($path),
259
+                    array(
260
+                        '{DAV:}getlastmodified',
261
+                        '{DAV:}getcontentlength',
262
+                        '{DAV:}getcontenttype',
263
+                        '{http://owncloud.org/ns}permissions',
264
+                        '{http://open-collaboration-services.org/ns}share-permissions',
265
+                        '{DAV:}resourcetype',
266
+                        '{DAV:}getetag',
267
+                    )
268
+                );
269
+                $this->statCache->set($path, $response);
270
+            } catch (ClientHttpException $e) {
271
+                if ($e->getHttpStatus() === 404) {
272
+                    $this->statCache->clear($path . '/');
273
+                    $this->statCache->set($path, false);
274
+                    return false;
275
+                }
276
+                $this->convertException($e, $path);
277
+            } catch (\Exception $e) {
278
+                $this->convertException($e, $path);
279
+            }
280
+        } else {
281
+            $response = $cachedResponse;
282
+        }
283
+        return $response;
284
+    }
285
+
286
+    /** {@inheritdoc} */
287
+    public function filetype($path) {
288
+        try {
289
+            $response = $this->propfind($path);
290
+            if ($response === false) {
291
+                return false;
292
+            }
293
+            $responseType = [];
294
+            if (isset($response["{DAV:}resourcetype"])) {
295
+                /** @var ResourceType[] $response */
296
+                $responseType = $response["{DAV:}resourcetype"]->getValue();
297
+            }
298
+            return (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
299
+        } catch (\Exception $e) {
300
+            $this->convertException($e, $path);
301
+        }
302
+        return false;
303
+    }
304
+
305
+    /** {@inheritdoc} */
306
+    public function file_exists($path) {
307
+        try {
308
+            $path = $this->cleanPath($path);
309
+            $cachedState = $this->statCache->get($path);
310
+            if ($cachedState === false) {
311
+                // we know the file doesn't exist
312
+                return false;
313
+            } else if (!is_null($cachedState)) {
314
+                return true;
315
+            }
316
+            // need to get from server
317
+            return ($this->propfind($path) !== false);
318
+        } catch (\Exception $e) {
319
+            $this->convertException($e, $path);
320
+        }
321
+        return false;
322
+    }
323
+
324
+    /** {@inheritdoc} */
325
+    public function unlink($path) {
326
+        $this->init();
327
+        $path = $this->cleanPath($path);
328
+        $result = $this->simpleResponse('DELETE', $path, null, 204);
329
+        $this->statCache->clear($path . '/');
330
+        $this->statCache->remove($path);
331
+        return $result;
332
+    }
333
+
334
+    /** {@inheritdoc} */
335
+    public function fopen($path, $mode) {
336
+        $this->init();
337
+        $path = $this->cleanPath($path);
338
+        switch ($mode) {
339
+            case 'r':
340
+            case 'rb':
341
+                try {
342
+                    $response = $this->httpClientService
343
+                        ->newClient()
344
+                        ->get($this->createBaseUri() . $this->encodePath($path), [
345
+                            'auth' => [$this->user, $this->password],
346
+                            'stream' => true
347
+                        ]);
348
+                } catch (\GuzzleHttp\Exception\ClientException $e) {
349
+                    if ($e->getResponse() instanceof ResponseInterface
350
+                        && $e->getResponse()->getStatusCode() === 404) {
351
+                        return false;
352
+                    } else {
353
+                        throw $e;
354
+                    }
355
+                }
356
+
357
+                if ($response->getStatusCode() !== Http::STATUS_OK) {
358
+                    if ($response->getStatusCode() === Http::STATUS_LOCKED) {
359
+                        throw new \OCP\Lock\LockedException($path);
360
+                    } else {
361
+                        Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), ILogger::ERROR);
362
+                    }
363
+                }
364
+
365
+                return $response->getBody();
366
+            case 'w':
367
+            case 'wb':
368
+            case 'a':
369
+            case 'ab':
370
+            case 'r+':
371
+            case 'w+':
372
+            case 'wb+':
373
+            case 'a+':
374
+            case 'x':
375
+            case 'x+':
376
+            case 'c':
377
+            case 'c+':
378
+                //emulate these
379
+                $tempManager = \OC::$server->getTempManager();
380
+                if (strrpos($path, '.') !== false) {
381
+                    $ext = substr($path, strrpos($path, '.'));
382
+                } else {
383
+                    $ext = '';
384
+                }
385
+                if ($this->file_exists($path)) {
386
+                    if (!$this->isUpdatable($path)) {
387
+                        return false;
388
+                    }
389
+                    if ($mode === 'w' or $mode === 'w+') {
390
+                        $tmpFile = $tempManager->getTemporaryFile($ext);
391
+                    } else {
392
+                        $tmpFile = $this->getCachedFile($path);
393
+                    }
394
+                } else {
395
+                    if (!$this->isCreatable(dirname($path))) {
396
+                        return false;
397
+                    }
398
+                    $tmpFile = $tempManager->getTemporaryFile($ext);
399
+                }
400
+                $handle = fopen($tmpFile, $mode);
401
+                return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
402
+                    $this->writeBack($tmpFile, $path);
403
+                });
404
+        }
405
+    }
406
+
407
+    /**
408
+     * @param string $tmpFile
409
+     */
410
+    public function writeBack($tmpFile, $path) {
411
+        $this->uploadFile($tmpFile, $path);
412
+        unlink($tmpFile);
413
+    }
414
+
415
+    /** {@inheritdoc} */
416
+    public function free_space($path) {
417
+        $this->init();
418
+        $path = $this->cleanPath($path);
419
+        try {
420
+            // TODO: cacheable ?
421
+            $response = $this->client->propfind($this->encodePath($path), ['{DAV:}quota-available-bytes']);
422
+            if ($response === false) {
423
+                return FileInfo::SPACE_UNKNOWN;
424
+            }
425
+            if (isset($response['{DAV:}quota-available-bytes'])) {
426
+                return (int)$response['{DAV:}quota-available-bytes'];
427
+            } else {
428
+                return FileInfo::SPACE_UNKNOWN;
429
+            }
430
+        } catch (\Exception $e) {
431
+            return FileInfo::SPACE_UNKNOWN;
432
+        }
433
+    }
434
+
435
+    /** {@inheritdoc} */
436
+    public function touch($path, $mtime = null) {
437
+        $this->init();
438
+        if (is_null($mtime)) {
439
+            $mtime = time();
440
+        }
441
+        $path = $this->cleanPath($path);
442
+
443
+        // if file exists, update the mtime, else create a new empty file
444
+        if ($this->file_exists($path)) {
445
+            try {
446
+                $this->statCache->remove($path);
447
+                $this->client->proppatch($this->encodePath($path), ['{DAV:}lastmodified' => $mtime]);
448
+                // non-owncloud clients might not have accepted the property, need to recheck it
449
+                $response = $this->client->propfind($this->encodePath($path), ['{DAV:}getlastmodified'], 0);
450
+                if ($response === false) {
451
+                    return false;
452
+                }
453
+                if (isset($response['{DAV:}getlastmodified'])) {
454
+                    $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
455
+                    if ($remoteMtime !== $mtime) {
456
+                        // server has not accepted the mtime
457
+                        return false;
458
+                    }
459
+                }
460
+            } catch (ClientHttpException $e) {
461
+                if ($e->getHttpStatus() === 501) {
462
+                    return false;
463
+                }
464
+                $this->convertException($e, $path);
465
+                return false;
466
+            } catch (\Exception $e) {
467
+                $this->convertException($e, $path);
468
+                return false;
469
+            }
470
+        } else {
471
+            $this->file_put_contents($path, '');
472
+        }
473
+        return true;
474
+    }
475
+
476
+    /**
477
+     * @param string $path
478
+     * @param string $data
479
+     * @return int
480
+     */
481
+    public function file_put_contents($path, $data) {
482
+        $path = $this->cleanPath($path);
483
+        $result = parent::file_put_contents($path, $data);
484
+        $this->statCache->remove($path);
485
+        return $result;
486
+    }
487
+
488
+    /**
489
+     * @param string $path
490
+     * @param string $target
491
+     */
492
+    protected function uploadFile($path, $target) {
493
+        $this->init();
494
+
495
+        // invalidate
496
+        $target = $this->cleanPath($target);
497
+        $this->statCache->remove($target);
498
+        $source = fopen($path, 'r');
499
+
500
+        $this->httpClientService
501
+            ->newClient()
502
+            ->put($this->createBaseUri() . $this->encodePath($target), [
503
+                'body' => $source,
504
+                'auth' => [$this->user, $this->password]
505
+            ]);
506
+
507
+        $this->removeCachedFile($target);
508
+    }
509
+
510
+    /** {@inheritdoc} */
511
+    public function rename($path1, $path2) {
512
+        $this->init();
513
+        $path1 = $this->cleanPath($path1);
514
+        $path2 = $this->cleanPath($path2);
515
+        try {
516
+            // overwrite directory ?
517
+            if ($this->is_dir($path2)) {
518
+                // needs trailing slash in destination
519
+                $path2 = rtrim($path2, '/') . '/';
520
+            }
521
+            $this->client->request(
522
+                'MOVE',
523
+                $this->encodePath($path1),
524
+                null,
525
+                [
526
+                    'Destination' => $this->createBaseUri() . $this->encodePath($path2),
527
+                ]
528
+            );
529
+            $this->statCache->clear($path1 . '/');
530
+            $this->statCache->clear($path2 . '/');
531
+            $this->statCache->set($path1, false);
532
+            $this->statCache->set($path2, true);
533
+            $this->removeCachedFile($path1);
534
+            $this->removeCachedFile($path2);
535
+            return true;
536
+        } catch (\Exception $e) {
537
+            $this->convertException($e);
538
+        }
539
+        return false;
540
+    }
541
+
542
+    /** {@inheritdoc} */
543
+    public function copy($path1, $path2) {
544
+        $this->init();
545
+        $path1 = $this->cleanPath($path1);
546
+        $path2 = $this->cleanPath($path2);
547
+        try {
548
+            // overwrite directory ?
549
+            if ($this->is_dir($path2)) {
550
+                // needs trailing slash in destination
551
+                $path2 = rtrim($path2, '/') . '/';
552
+            }
553
+            $this->client->request(
554
+                'COPY',
555
+                $this->encodePath($path1),
556
+                null,
557
+                [
558
+                    'Destination' => $this->createBaseUri() . $this->encodePath($path2),
559
+                ]
560
+            );
561
+            $this->statCache->clear($path2 . '/');
562
+            $this->statCache->set($path2, true);
563
+            $this->removeCachedFile($path2);
564
+            return true;
565
+        } catch (\Exception $e) {
566
+            $this->convertException($e);
567
+        }
568
+        return false;
569
+    }
570
+
571
+    /** {@inheritdoc} */
572
+    public function stat($path) {
573
+        try {
574
+            $response = $this->propfind($path);
575
+            if (!$response) {
576
+                return false;
577
+            }
578
+            return [
579
+                'mtime' => strtotime($response['{DAV:}getlastmodified']),
580
+                'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
581
+            ];
582
+        } catch (\Exception $e) {
583
+            $this->convertException($e, $path);
584
+        }
585
+        return array();
586
+    }
587
+
588
+    /** {@inheritdoc} */
589
+    public function getMimeType($path) {
590
+        $remoteMimetype = $this->getMimeTypeFromRemote($path);
591
+        if ($remoteMimetype === 'application/octet-stream') {
592
+            return \OC::$server->getMimeTypeDetector()->detectPath($path);
593
+        } else {
594
+            return $remoteMimetype;
595
+        }
596
+    }
597
+
598
+    public function getMimeTypeFromRemote($path) {
599
+        try {
600
+            $response = $this->propfind($path);
601
+            if ($response === false) {
602
+                return false;
603
+            }
604
+            $responseType = [];
605
+            if (isset($response["{DAV:}resourcetype"])) {
606
+                /** @var ResourceType[] $response */
607
+                $responseType = $response["{DAV:}resourcetype"]->getValue();
608
+            }
609
+            $type = (count($responseType) > 0 and $responseType[0] == "{DAV:}collection") ? 'dir' : 'file';
610
+            if ($type == 'dir') {
611
+                return 'httpd/unix-directory';
612
+            } elseif (isset($response['{DAV:}getcontenttype'])) {
613
+                return $response['{DAV:}getcontenttype'];
614
+            } else {
615
+                return 'application/octet-stream';
616
+            }
617
+        } catch (\Exception $e) {
618
+            return false;
619
+        }
620
+    }
621
+
622
+    /**
623
+     * @param string $path
624
+     * @return string
625
+     */
626
+    public function cleanPath($path) {
627
+        if ($path === '') {
628
+            return $path;
629
+        }
630
+        $path = Filesystem::normalizePath($path);
631
+        // remove leading slash
632
+        return substr($path, 1);
633
+    }
634
+
635
+    /**
636
+     * URL encodes the given path but keeps the slashes
637
+     *
638
+     * @param string $path to encode
639
+     * @return string encoded path
640
+     */
641
+    protected function encodePath($path) {
642
+        // slashes need to stay
643
+        return str_replace('%2F', '/', rawurlencode($path));
644
+    }
645
+
646
+    /**
647
+     * @param string $method
648
+     * @param string $path
649
+     * @param string|resource|null $body
650
+     * @param int $expected
651
+     * @return bool
652
+     * @throws StorageInvalidException
653
+     * @throws StorageNotAvailableException
654
+     */
655
+    protected function simpleResponse($method, $path, $body, $expected) {
656
+        $path = $this->cleanPath($path);
657
+        try {
658
+            $response = $this->client->request($method, $this->encodePath($path), $body);
659
+            return $response['statusCode'] == $expected;
660
+        } catch (ClientHttpException $e) {
661
+            if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
662
+                $this->statCache->clear($path . '/');
663
+                $this->statCache->set($path, false);
664
+                return false;
665
+            }
666
+
667
+            $this->convertException($e, $path);
668
+        } catch (\Exception $e) {
669
+            $this->convertException($e, $path);
670
+        }
671
+        return false;
672
+    }
673
+
674
+    /**
675
+     * check if curl is installed
676
+     */
677
+    public static function checkDependencies() {
678
+        return true;
679
+    }
680
+
681
+    /** {@inheritdoc} */
682
+    public function isUpdatable($path) {
683
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
684
+    }
685
+
686
+    /** {@inheritdoc} */
687
+    public function isCreatable($path) {
688
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
689
+    }
690
+
691
+    /** {@inheritdoc} */
692
+    public function isSharable($path) {
693
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
694
+    }
695
+
696
+    /** {@inheritdoc} */
697
+    public function isDeletable($path) {
698
+        return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
699
+    }
700
+
701
+    /** {@inheritdoc} */
702
+    public function getPermissions($path) {
703
+        $this->init();
704
+        $path = $this->cleanPath($path);
705
+        $response = $this->propfind($path);
706
+        if ($response === false) {
707
+            return 0;
708
+        }
709
+        if (isset($response['{http://owncloud.org/ns}permissions'])) {
710
+            return $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
711
+        } else if ($this->is_dir($path)) {
712
+            return Constants::PERMISSION_ALL;
713
+        } else if ($this->file_exists($path)) {
714
+            return Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE;
715
+        } else {
716
+            return 0;
717
+        }
718
+    }
719
+
720
+    /** {@inheritdoc} */
721
+    public function getETag($path) {
722
+        $this->init();
723
+        $path = $this->cleanPath($path);
724
+        $response = $this->propfind($path);
725
+        if ($response === false) {
726
+            return null;
727
+        }
728
+        if (isset($response['{DAV:}getetag'])) {
729
+            return trim($response['{DAV:}getetag'], '"');
730
+        }
731
+        return parent::getEtag($path);
732
+    }
733
+
734
+    /**
735
+     * @param string $permissionsString
736
+     * @return int
737
+     */
738
+    protected function parsePermissions($permissionsString) {
739
+        $permissions = Constants::PERMISSION_READ;
740
+        if (strpos($permissionsString, 'R') !== false) {
741
+            $permissions |= Constants::PERMISSION_SHARE;
742
+        }
743
+        if (strpos($permissionsString, 'D') !== false) {
744
+            $permissions |= Constants::PERMISSION_DELETE;
745
+        }
746
+        if (strpos($permissionsString, 'W') !== false) {
747
+            $permissions |= Constants::PERMISSION_UPDATE;
748
+        }
749
+        if (strpos($permissionsString, 'CK') !== false) {
750
+            $permissions |= Constants::PERMISSION_CREATE;
751
+            $permissions |= Constants::PERMISSION_UPDATE;
752
+        }
753
+        return $permissions;
754
+    }
755
+
756
+    /**
757
+     * check if a file or folder has been updated since $time
758
+     *
759
+     * @param string $path
760
+     * @param int $time
761
+     * @throws \OCP\Files\StorageNotAvailableException
762
+     * @return bool
763
+     */
764
+    public function hasUpdated($path, $time) {
765
+        $this->init();
766
+        $path = $this->cleanPath($path);
767
+        try {
768
+            // force refresh for $path
769
+            $this->statCache->remove($path);
770
+            $response = $this->propfind($path);
771
+            if ($response === false) {
772
+                if ($path === '') {
773
+                    // if root is gone it means the storage is not available
774
+                    throw new StorageNotAvailableException('root is gone');
775
+                }
776
+                return false;
777
+            }
778
+            if (isset($response['{DAV:}getetag'])) {
779
+                $cachedData = $this->getCache()->get($path);
780
+                $etag = null;
781
+                if (isset($response['{DAV:}getetag'])) {
782
+                    $etag = trim($response['{DAV:}getetag'], '"');
783
+                }
784
+                if (!empty($etag) && $cachedData['etag'] !== $etag) {
785
+                    return true;
786
+                } else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
787
+                    $sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
788
+                    return $sharePermissions !== $cachedData['permissions'];
789
+                } else if (isset($response['{http://owncloud.org/ns}permissions'])) {
790
+                    $permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
791
+                    return $permissions !== $cachedData['permissions'];
792
+                } else {
793
+                    return false;
794
+                }
795
+            } else {
796
+                $remoteMtime = strtotime($response['{DAV:}getlastmodified']);
797
+                return $remoteMtime > $time;
798
+            }
799
+        } catch (ClientHttpException $e) {
800
+            if ($e->getHttpStatus() === 405) {
801
+                if ($path === '') {
802
+                    // if root is gone it means the storage is not available
803
+                    throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
804
+                }
805
+                return false;
806
+            }
807
+            $this->convertException($e, $path);
808
+            return false;
809
+        } catch (\Exception $e) {
810
+            $this->convertException($e, $path);
811
+            return false;
812
+        }
813
+    }
814
+
815
+    /**
816
+     * Interpret the given exception and decide whether it is due to an
817
+     * unavailable storage, invalid storage or other.
818
+     * This will either throw StorageInvalidException, StorageNotAvailableException
819
+     * or do nothing.
820
+     *
821
+     * @param Exception $e sabre exception
822
+     * @param string $path optional path from the operation
823
+     *
824
+     * @throws StorageInvalidException if the storage is invalid, for example
825
+     * when the authentication expired or is invalid
826
+     * @throws StorageNotAvailableException if the storage is not available,
827
+     * which might be temporary
828
+     */
829
+    protected function convertException(Exception $e, $path = '') {
830
+        \OC::$server->getLogger()->logException($e, ['app' => 'files_external']);
831
+        if ($e instanceof ClientHttpException) {
832
+            if ($e->getHttpStatus() === Http::STATUS_LOCKED) {
833
+                throw new \OCP\Lock\LockedException($path);
834
+            }
835
+            if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
836
+                // either password was changed or was invalid all along
837
+                throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
838
+            } else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
839
+                // ignore exception for MethodNotAllowed, false will be returned
840
+                return;
841
+            }
842
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
843
+        } else if ($e instanceof ClientException) {
844
+            // connection timeout or refused, server could be temporarily down
845
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
846
+        } else if ($e instanceof \InvalidArgumentException) {
847
+            // parse error because the server returned HTML instead of XML,
848
+            // possibly temporarily down
849
+            throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
850
+        } else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
851
+            // rethrow
852
+            throw $e;
853
+        }
854
+
855
+        // TODO: only log for now, but in the future need to wrap/rethrow exception
856
+    }
857 857
 }
858 858
 
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 				if (is_string($params['secure'])) {
104 104
 					$this->secure = ($params['secure'] === 'true');
105 105
 				} else {
106
-					$this->secure = (bool)$params['secure'];
106
+					$this->secure = (bool) $params['secure'];
107 107
 				}
108 108
 			} else {
109 109
 				$this->secure = false;
@@ -120,8 +120,8 @@  discard block
 block discarded – undo
120 120
 				}
121 121
 			}
122 122
 			$this->root = $params['root'] ?? '/';
123
-			$this->root = '/' . ltrim($this->root, '/');
124
-			$this->root = rtrim($this->root, '/') . '/';
123
+			$this->root = '/'.ltrim($this->root, '/');
124
+			$this->root = rtrim($this->root, '/').'/';
125 125
 		} else {
126 126
 			throw new \Exception('Invalid webdav storage configuration');
127 127
 		}
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 
164 164
 	/** {@inheritdoc} */
165 165
 	public function getId() {
166
-		return 'webdav::' . $this->user . '@' . $this->host . '/' . $this->root;
166
+		return 'webdav::'.$this->user.'@'.$this->host.'/'.$this->root;
167 167
 	}
168 168
 
169 169
 	/** {@inheritdoc} */
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		if ($this->secure) {
173 173
 			$baseUri .= 's';
174 174
 		}
175
-		$baseUri .= '://' . $this->host . $this->root;
175
+		$baseUri .= '://'.$this->host.$this->root;
176 176
 		return $baseUri;
177 177
 	}
178 178
 
@@ -193,8 +193,8 @@  discard block
 block discarded – undo
193 193
 		$path = $this->cleanPath($path);
194 194
 		// FIXME: some WebDAV impl return 403 when trying to DELETE
195 195
 		// a non-empty folder
196
-		$result = $this->simpleResponse('DELETE', $path . '/', null, 204);
197
-		$this->statCache->clear($path . '/');
196
+		$result = $this->simpleResponse('DELETE', $path.'/', null, 204);
197
+		$this->statCache->clear($path.'/');
198 198
 		$this->statCache->remove($path);
199 199
 		return $result;
200 200
 	}
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 				$this->statCache->set($path, $response);
270 270
 			} catch (ClientHttpException $e) {
271 271
 				if ($e->getHttpStatus() === 404) {
272
-					$this->statCache->clear($path . '/');
272
+					$this->statCache->clear($path.'/');
273 273
 					$this->statCache->set($path, false);
274 274
 					return false;
275 275
 				}
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 		$this->init();
327 327
 		$path = $this->cleanPath($path);
328 328
 		$result = $this->simpleResponse('DELETE', $path, null, 204);
329
-		$this->statCache->clear($path . '/');
329
+		$this->statCache->clear($path.'/');
330 330
 		$this->statCache->remove($path);
331 331
 		return $result;
332 332
 	}
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 				try {
342 342
 					$response = $this->httpClientService
343 343
 						->newClient()
344
-						->get($this->createBaseUri() . $this->encodePath($path), [
344
+						->get($this->createBaseUri().$this->encodePath($path), [
345 345
 							'auth' => [$this->user, $this->password],
346 346
 							'stream' => true
347 347
 						]);
@@ -358,7 +358,7 @@  discard block
 block discarded – undo
358 358
 					if ($response->getStatusCode() === Http::STATUS_LOCKED) {
359 359
 						throw new \OCP\Lock\LockedException($path);
360 360
 					} else {
361
-						Util::writeLog("webdav client", 'Guzzle get returned status code ' . $response->getStatusCode(), ILogger::ERROR);
361
+						Util::writeLog("webdav client", 'Guzzle get returned status code '.$response->getStatusCode(), ILogger::ERROR);
362 362
 					}
363 363
 				}
364 364
 
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 					$tmpFile = $tempManager->getTemporaryFile($ext);
399 399
 				}
400 400
 				$handle = fopen($tmpFile, $mode);
401
-				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
401
+				return CallbackWrapper::wrap($handle, null, null, function() use ($path, $tmpFile) {
402 402
 					$this->writeBack($tmpFile, $path);
403 403
 				});
404 404
 		}
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
 				return FileInfo::SPACE_UNKNOWN;
424 424
 			}
425 425
 			if (isset($response['{DAV:}quota-available-bytes'])) {
426
-				return (int)$response['{DAV:}quota-available-bytes'];
426
+				return (int) $response['{DAV:}quota-available-bytes'];
427 427
 			} else {
428 428
 				return FileInfo::SPACE_UNKNOWN;
429 429
 			}
@@ -499,7 +499,7 @@  discard block
 block discarded – undo
499 499
 
500 500
 		$this->httpClientService
501 501
 			->newClient()
502
-			->put($this->createBaseUri() . $this->encodePath($target), [
502
+			->put($this->createBaseUri().$this->encodePath($target), [
503 503
 				'body' => $source,
504 504
 				'auth' => [$this->user, $this->password]
505 505
 			]);
@@ -516,18 +516,18 @@  discard block
 block discarded – undo
516 516
 			// overwrite directory ?
517 517
 			if ($this->is_dir($path2)) {
518 518
 				// needs trailing slash in destination
519
-				$path2 = rtrim($path2, '/') . '/';
519
+				$path2 = rtrim($path2, '/').'/';
520 520
 			}
521 521
 			$this->client->request(
522 522
 				'MOVE',
523 523
 				$this->encodePath($path1),
524 524
 				null,
525 525
 				[
526
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
526
+					'Destination' => $this->createBaseUri().$this->encodePath($path2),
527 527
 				]
528 528
 			);
529
-			$this->statCache->clear($path1 . '/');
530
-			$this->statCache->clear($path2 . '/');
529
+			$this->statCache->clear($path1.'/');
530
+			$this->statCache->clear($path2.'/');
531 531
 			$this->statCache->set($path1, false);
532 532
 			$this->statCache->set($path2, true);
533 533
 			$this->removeCachedFile($path1);
@@ -548,17 +548,17 @@  discard block
 block discarded – undo
548 548
 			// overwrite directory ?
549 549
 			if ($this->is_dir($path2)) {
550 550
 				// needs trailing slash in destination
551
-				$path2 = rtrim($path2, '/') . '/';
551
+				$path2 = rtrim($path2, '/').'/';
552 552
 			}
553 553
 			$this->client->request(
554 554
 				'COPY',
555 555
 				$this->encodePath($path1),
556 556
 				null,
557 557
 				[
558
-					'Destination' => $this->createBaseUri() . $this->encodePath($path2),
558
+					'Destination' => $this->createBaseUri().$this->encodePath($path2),
559 559
 				]
560 560
 			);
561
-			$this->statCache->clear($path2 . '/');
561
+			$this->statCache->clear($path2.'/');
562 562
 			$this->statCache->set($path2, true);
563 563
 			$this->removeCachedFile($path2);
564 564
 			return true;
@@ -577,7 +577,7 @@  discard block
 block discarded – undo
577 577
 			}
578 578
 			return [
579 579
 				'mtime' => strtotime($response['{DAV:}getlastmodified']),
580
-				'size' => (int)isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
580
+				'size' => (int) isset($response['{DAV:}getcontentlength']) ? $response['{DAV:}getcontentlength'] : 0,
581 581
 			];
582 582
 		} catch (\Exception $e) {
583 583
 			$this->convertException($e, $path);
@@ -659,7 +659,7 @@  discard block
 block discarded – undo
659 659
 			return $response['statusCode'] == $expected;
660 660
 		} catch (ClientHttpException $e) {
661 661
 			if ($e->getHttpStatus() === 404 && $method === 'DELETE') {
662
-				$this->statCache->clear($path . '/');
662
+				$this->statCache->clear($path.'/');
663 663
 				$this->statCache->set($path, false);
664 664
 				return false;
665 665
 			}
@@ -680,22 +680,22 @@  discard block
 block discarded – undo
680 680
 
681 681
 	/** {@inheritdoc} */
682 682
 	public function isUpdatable($path) {
683
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
683
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_UPDATE);
684 684
 	}
685 685
 
686 686
 	/** {@inheritdoc} */
687 687
 	public function isCreatable($path) {
688
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_CREATE);
688
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_CREATE);
689 689
 	}
690 690
 
691 691
 	/** {@inheritdoc} */
692 692
 	public function isSharable($path) {
693
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_SHARE);
693
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_SHARE);
694 694
 	}
695 695
 
696 696
 	/** {@inheritdoc} */
697 697
 	public function isDeletable($path) {
698
-		return (bool)($this->getPermissions($path) & Constants::PERMISSION_DELETE);
698
+		return (bool) ($this->getPermissions($path) & Constants::PERMISSION_DELETE);
699 699
 	}
700 700
 
701 701
 	/** {@inheritdoc} */
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
 				if (!empty($etag) && $cachedData['etag'] !== $etag) {
785 785
 					return true;
786 786
 				} else if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
787
-					$sharePermissions = (int)$response['{http://open-collaboration-services.org/ns}share-permissions'];
787
+					$sharePermissions = (int) $response['{http://open-collaboration-services.org/ns}share-permissions'];
788 788
 					return $sharePermissions !== $cachedData['permissions'];
789 789
 				} else if (isset($response['{http://owncloud.org/ns}permissions'])) {
790 790
 					$permissions = $this->parsePermissions($response['{http://owncloud.org/ns}permissions']);
@@ -800,7 +800,7 @@  discard block
 block discarded – undo
800 800
 			if ($e->getHttpStatus() === 405) {
801 801
 				if ($path === '') {
802 802
 					// if root is gone it means the storage is not available
803
-					throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
803
+					throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
804 804
 				}
805 805
 				return false;
806 806
 			}
@@ -834,19 +834,19 @@  discard block
 block discarded – undo
834 834
 			}
835 835
 			if ($e->getHttpStatus() === Http::STATUS_UNAUTHORIZED) {
836 836
 				// either password was changed or was invalid all along
837
-				throw new StorageInvalidException(get_class($e) . ': ' . $e->getMessage());
837
+				throw new StorageInvalidException(get_class($e).': '.$e->getMessage());
838 838
 			} else if ($e->getHttpStatus() === Http::STATUS_METHOD_NOT_ALLOWED) {
839 839
 				// ignore exception for MethodNotAllowed, false will be returned
840 840
 				return;
841 841
 			}
842
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
842
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
843 843
 		} else if ($e instanceof ClientException) {
844 844
 			// connection timeout or refused, server could be temporarily down
845
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
845
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
846 846
 		} else if ($e instanceof \InvalidArgumentException) {
847 847
 			// parse error because the server returned HTML instead of XML,
848 848
 			// possibly temporarily down
849
-			throw new StorageNotAvailableException(get_class($e) . ': ' . $e->getMessage());
849
+			throw new StorageNotAvailableException(get_class($e).': '.$e->getMessage());
850 850
 		} else if (($e instanceof StorageNotAvailableException) || ($e instanceof StorageInvalidException)) {
851 851
 			// rethrow
852 852
 			throw $e;
Please login to merge, or discard this patch.
lib/private/Settings/Manager.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,6 @@
 block discarded – undo
46 46
 use OCP\Settings\ISettings;
47 47
 use OCP\Settings\IManager;
48 48
 use OCP\Settings\ISection;
49
-use OCP\Util;
50 49
 
51 50
 class Manager implements IManager {
52 51
 	/** @var ILogger */
Please login to merge, or discard this patch.
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -49,356 +49,356 @@
 block discarded – undo
49 49
 use OCP\Util;
50 50
 
51 51
 class Manager implements IManager {
52
-	/** @var ILogger */
53
-	private $log;
54
-	/** @var IDBConnection */
55
-	private $dbc;
56
-	/** @var IL10N */
57
-	private $l;
58
-	/** @var IConfig */
59
-	private $config;
60
-	/** @var EncryptionManager */
61
-	private $encryptionManager;
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-	/** @var ILockingProvider */
65
-	private $lockingProvider;
66
-	/** @var IRequest */
67
-	private $request;
68
-	/** @var IURLGenerator */
69
-	private $url;
70
-	/** @var AccountManager */
71
-	private $accountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IFactory */
75
-	private $l10nFactory;
76
-	/** @var IAppManager */
77
-	private $appManager;
78
-
79
-	/**
80
-	 * @param ILogger $log
81
-	 * @param IDBConnection $dbc
82
-	 * @param IL10N $l
83
-	 * @param IConfig $config
84
-	 * @param EncryptionManager $encryptionManager
85
-	 * @param IUserManager $userManager
86
-	 * @param ILockingProvider $lockingProvider
87
-	 * @param IRequest $request
88
-	 * @param IURLGenerator $url
89
-	 * @param AccountManager $accountManager
90
-	 * @param IGroupManager $groupManager
91
-	 * @param IFactory $l10nFactory
92
-	 * @param IAppManager $appManager
93
-	 */
94
-	public function __construct(
95
-		ILogger $log,
96
-		IDBConnection $dbc,
97
-		IL10N $l,
98
-		IConfig $config,
99
-		EncryptionManager $encryptionManager,
100
-		IUserManager $userManager,
101
-		ILockingProvider $lockingProvider,
102
-		IRequest $request,
103
-		IURLGenerator $url,
104
-		AccountManager $accountManager,
105
-		IGroupManager $groupManager,
106
-		IFactory $l10nFactory,
107
-		IAppManager $appManager
108
-	) {
109
-		$this->log = $log;
110
-		$this->dbc = $dbc;
111
-		$this->l = $l;
112
-		$this->config = $config;
113
-		$this->encryptionManager = $encryptionManager;
114
-		$this->userManager = $userManager;
115
-		$this->lockingProvider = $lockingProvider;
116
-		$this->request = $request;
117
-		$this->url = $url;
118
-		$this->accountManager = $accountManager;
119
-		$this->groupManager = $groupManager;
120
-		$this->l10nFactory = $l10nFactory;
121
-		$this->appManager = $appManager;
122
-	}
123
-
124
-	/** @var array */
125
-	protected $sectionClasses = [];
126
-
127
-	/** @var array */
128
-	protected $sections = [];
129
-
130
-	/**
131
-	 * @param string $type 'admin' or 'personal'
132
-	 * @param string $section Class must implement OCP\Settings\ISection
133
-	 * @return void
134
-	 */
135
-	public function registerSection(string $type, string $section) {
136
-		$this->sectionClasses[$section] = $type;
137
-	}
138
-
139
-	/**
140
-	 * @param string $type 'admin' or 'personal'
141
-	 * @return ISection[]
142
-	 */
143
-	protected function getSections(string $type): array {
144
-		if (!isset($this->sections[$type])) {
145
-			$this->sections[$type] = [];
146
-		}
147
-
148
-		foreach ($this->sectionClasses as $class => $sectionType) {
149
-			try {
150
-				/** @var ISection $section */
151
-				$section = \OC::$server->query($class);
152
-			} catch (QueryException $e) {
153
-				$this->log->logException($e, ['level' => ILogger::INFO]);
154
-				continue;
155
-			}
156
-
157
-			if (!$section instanceof ISection) {
158
-				$this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => ILogger::INFO]);
159
-				continue;
160
-			}
161
-
162
-			$this->sections[$sectionType][$section->getID()] = $section;
163
-
164
-			unset($this->sectionClasses[$class]);
165
-		}
166
-
167
-		return $this->sections[$type];
168
-	}
169
-
170
-	/** @var array */
171
-	protected $settingClasses = [];
172
-
173
-	/** @var array */
174
-	protected $settings = [];
175
-
176
-	/**
177
-	 * @param string $type 'admin' or 'personal'
178
-	 * @param string $setting Class must implement OCP\Settings\ISetting
179
-	 * @return void
180
-	 */
181
-	public function registerSetting(string $type, string $setting) {
182
-		$this->settingClasses[$setting] = $type;
183
-	}
184
-
185
-	/**
186
-	 * @param string $type 'admin' or 'personal'
187
-	 * @param string $section
188
-	 * @return ISettings[]
189
-	 */
190
-	protected function getSettings(string $type, string $section): array {
191
-		if (!isset($this->settings[$type])) {
192
-			$this->settings[$type] = [];
193
-		}
194
-		if (!isset($this->settings[$type][$section])) {
195
-			$this->settings[$type][$section] = [];
196
-		}
197
-
198
-		foreach ($this->settingClasses as $class => $settingsType) {
199
-			try {
200
-				/** @var ISettings $setting */
201
-				$setting = \OC::$server->query($class);
202
-			} catch (QueryException $e) {
203
-				$this->log->logException($e, ['level' => ILogger::INFO]);
204
-				continue;
205
-			}
206
-
207
-			if (!$setting instanceof ISettings) {
208
-				$this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => ILogger::INFO]);
209
-				continue;
210
-			}
211
-
212
-			if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
-				$this->settings[$settingsType][$setting->getSection()] = [];
214
-			}
215
-			$this->settings[$settingsType][$setting->getSection()][] = $setting;
216
-
217
-			unset($this->settingClasses[$class]);
218
-		}
219
-
220
-		return $this->settings[$type][$section];
221
-	}
222
-
223
-	/**
224
-	 * @inheritdoc
225
-	 */
226
-	public function getAdminSections(): array {
227
-		// built-in sections
228
-		$sections = [
229
-			0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
-			5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
-			10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
-			45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
-			98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
-			99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
-		];
236
-
237
-		$appSections = $this->getSections('admin');
238
-
239
-		foreach ($appSections as $section) {
240
-			/** @var ISection $section */
241
-			if (!isset($sections[$section->getPriority()])) {
242
-				$sections[$section->getPriority()] = [];
243
-			}
244
-
245
-			$sections[$section->getPriority()][] = $section;
246
-		}
247
-
248
-		ksort($sections);
249
-
250
-		return $sections;
251
-	}
252
-
253
-	/**
254
-	 * @param string $section
255
-	 * @return ISection[]
256
-	 */
257
-	private function getBuiltInAdminSettings($section): array {
258
-		$forms = [];
259
-
260
-		if ($section === 'server') {
261
-			/** @var ISettings $form */
262
-			$form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
-			$forms[$form->getPriority()] = [$form];
264
-			$form = new Admin\ServerDevNotice();
265
-			$forms[$form->getPriority()] = [$form];
266
-		}
267
-		if ($section === 'encryption') {
268
-			/** @var ISettings $form */
269
-			$form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
-			$forms[$form->getPriority()] = [$form];
271
-		}
272
-		if ($section === 'sharing') {
273
-			/** @var ISettings $form */
274
-			$form = new Admin\Sharing($this->config, $this->l);
275
-			$forms[$form->getPriority()] = [$form];
276
-		}
277
-		if ($section === 'additional') {
278
-			/** @var ISettings $form */
279
-			$form = new Admin\Additional($this->config);
280
-			$forms[$form->getPriority()] = [$form];
281
-		}
282
-		if ($section === 'tips-tricks') {
283
-			/** @var ISettings $form */
284
-			$form = new Admin\TipsTricks($this->config);
285
-			$forms[$form->getPriority()] = [$form];
286
-		}
287
-
288
-		return $forms;
289
-	}
290
-
291
-	/**
292
-	 * @param string $section
293
-	 * @return ISection[]
294
-	 */
295
-	private function getBuiltInPersonalSettings($section): array {
296
-		$forms = [];
297
-
298
-		if ($section === 'personal-info') {
299
-			/** @var ISettings $form */
300
-			$form = new Personal\PersonalInfo(
301
-				$this->config,
302
-				$this->userManager,
303
-				$this->groupManager,
304
-				$this->accountManager,
305
-				$this->appManager,
306
-				$this->l10nFactory,
307
-				$this->l
308
-			);
309
-			$forms[$form->getPriority()] = [$form];
310
-		}
311
-		if($section === 'security') {
312
-			/** @var ISettings $form */
313
-			$form = new Personal\Security();
314
-			$forms[$form->getPriority()] = [$form];
315
-		}
316
-		if ($section === 'additional') {
317
-			/** @var ISettings $form */
318
-			$form = new Personal\Additional();
319
-			$forms[$form->getPriority()] = [$form];
320
-		}
321
-
322
-		return $forms;
323
-	}
324
-
325
-	/**
326
-	 * @inheritdoc
327
-	 */
328
-	public function getAdminSettings($section): array {
329
-		$settings = $this->getBuiltInAdminSettings($section);
330
-		$appSettings = $this->getSettings('admin', $section);
331
-
332
-		foreach ($appSettings as $setting) {
333
-			if (!isset($settings[$setting->getPriority()])) {
334
-				$settings[$setting->getPriority()] = [];
335
-			}
336
-			$settings[$setting->getPriority()][] = $setting;
337
-		}
338
-
339
-		ksort($settings);
340
-		return $settings;
341
-	}
342
-
343
-	/**
344
-	 * @inheritdoc
345
-	 */
346
-	public function getPersonalSections(): array {
347
-		$sections = [
348
-			0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
-			5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
-			15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
-		];
352
-
353
-		$legacyForms = \OC_App::getForms('personal');
354
-		if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
-			$sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
-		}
357
-
358
-		$appSections = $this->getSections('personal');
359
-
360
-		foreach ($appSections as $section) {
361
-			/** @var ISection $section */
362
-			if (!isset($sections[$section->getPriority()])) {
363
-				$sections[$section->getPriority()] = [];
364
-			}
365
-
366
-			$sections[$section->getPriority()][] = $section;
367
-		}
368
-
369
-		ksort($sections);
370
-
371
-		return $sections;
372
-	}
373
-
374
-	/**
375
-	 * @param string[] $forms
376
-	 * @return bool
377
-	 */
378
-	private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
-		foreach ($forms as $form) {
380
-			if(trim($form) !== '') {
381
-				return true;
382
-			}
383
-		}
384
-		return false;
385
-	}
386
-
387
-	/**
388
-	 * @inheritdoc
389
-	 */
390
-	public function getPersonalSettings($section): array {
391
-		$settings = $this->getBuiltInPersonalSettings($section);
392
-		$appSettings = $this->getSettings('personal', $section);
393
-
394
-		foreach ($appSettings as $setting) {
395
-			if (!isset($settings[$setting->getPriority()])) {
396
-				$settings[$setting->getPriority()] = [];
397
-			}
398
-			$settings[$setting->getPriority()][] = $setting;
399
-		}
400
-
401
-		ksort($settings);
402
-		return $settings;
403
-	}
52
+    /** @var ILogger */
53
+    private $log;
54
+    /** @var IDBConnection */
55
+    private $dbc;
56
+    /** @var IL10N */
57
+    private $l;
58
+    /** @var IConfig */
59
+    private $config;
60
+    /** @var EncryptionManager */
61
+    private $encryptionManager;
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+    /** @var ILockingProvider */
65
+    private $lockingProvider;
66
+    /** @var IRequest */
67
+    private $request;
68
+    /** @var IURLGenerator */
69
+    private $url;
70
+    /** @var AccountManager */
71
+    private $accountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IFactory */
75
+    private $l10nFactory;
76
+    /** @var IAppManager */
77
+    private $appManager;
78
+
79
+    /**
80
+     * @param ILogger $log
81
+     * @param IDBConnection $dbc
82
+     * @param IL10N $l
83
+     * @param IConfig $config
84
+     * @param EncryptionManager $encryptionManager
85
+     * @param IUserManager $userManager
86
+     * @param ILockingProvider $lockingProvider
87
+     * @param IRequest $request
88
+     * @param IURLGenerator $url
89
+     * @param AccountManager $accountManager
90
+     * @param IGroupManager $groupManager
91
+     * @param IFactory $l10nFactory
92
+     * @param IAppManager $appManager
93
+     */
94
+    public function __construct(
95
+        ILogger $log,
96
+        IDBConnection $dbc,
97
+        IL10N $l,
98
+        IConfig $config,
99
+        EncryptionManager $encryptionManager,
100
+        IUserManager $userManager,
101
+        ILockingProvider $lockingProvider,
102
+        IRequest $request,
103
+        IURLGenerator $url,
104
+        AccountManager $accountManager,
105
+        IGroupManager $groupManager,
106
+        IFactory $l10nFactory,
107
+        IAppManager $appManager
108
+    ) {
109
+        $this->log = $log;
110
+        $this->dbc = $dbc;
111
+        $this->l = $l;
112
+        $this->config = $config;
113
+        $this->encryptionManager = $encryptionManager;
114
+        $this->userManager = $userManager;
115
+        $this->lockingProvider = $lockingProvider;
116
+        $this->request = $request;
117
+        $this->url = $url;
118
+        $this->accountManager = $accountManager;
119
+        $this->groupManager = $groupManager;
120
+        $this->l10nFactory = $l10nFactory;
121
+        $this->appManager = $appManager;
122
+    }
123
+
124
+    /** @var array */
125
+    protected $sectionClasses = [];
126
+
127
+    /** @var array */
128
+    protected $sections = [];
129
+
130
+    /**
131
+     * @param string $type 'admin' or 'personal'
132
+     * @param string $section Class must implement OCP\Settings\ISection
133
+     * @return void
134
+     */
135
+    public function registerSection(string $type, string $section) {
136
+        $this->sectionClasses[$section] = $type;
137
+    }
138
+
139
+    /**
140
+     * @param string $type 'admin' or 'personal'
141
+     * @return ISection[]
142
+     */
143
+    protected function getSections(string $type): array {
144
+        if (!isset($this->sections[$type])) {
145
+            $this->sections[$type] = [];
146
+        }
147
+
148
+        foreach ($this->sectionClasses as $class => $sectionType) {
149
+            try {
150
+                /** @var ISection $section */
151
+                $section = \OC::$server->query($class);
152
+            } catch (QueryException $e) {
153
+                $this->log->logException($e, ['level' => ILogger::INFO]);
154
+                continue;
155
+            }
156
+
157
+            if (!$section instanceof ISection) {
158
+                $this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => ILogger::INFO]);
159
+                continue;
160
+            }
161
+
162
+            $this->sections[$sectionType][$section->getID()] = $section;
163
+
164
+            unset($this->sectionClasses[$class]);
165
+        }
166
+
167
+        return $this->sections[$type];
168
+    }
169
+
170
+    /** @var array */
171
+    protected $settingClasses = [];
172
+
173
+    /** @var array */
174
+    protected $settings = [];
175
+
176
+    /**
177
+     * @param string $type 'admin' or 'personal'
178
+     * @param string $setting Class must implement OCP\Settings\ISetting
179
+     * @return void
180
+     */
181
+    public function registerSetting(string $type, string $setting) {
182
+        $this->settingClasses[$setting] = $type;
183
+    }
184
+
185
+    /**
186
+     * @param string $type 'admin' or 'personal'
187
+     * @param string $section
188
+     * @return ISettings[]
189
+     */
190
+    protected function getSettings(string $type, string $section): array {
191
+        if (!isset($this->settings[$type])) {
192
+            $this->settings[$type] = [];
193
+        }
194
+        if (!isset($this->settings[$type][$section])) {
195
+            $this->settings[$type][$section] = [];
196
+        }
197
+
198
+        foreach ($this->settingClasses as $class => $settingsType) {
199
+            try {
200
+                /** @var ISettings $setting */
201
+                $setting = \OC::$server->query($class);
202
+            } catch (QueryException $e) {
203
+                $this->log->logException($e, ['level' => ILogger::INFO]);
204
+                continue;
205
+            }
206
+
207
+            if (!$setting instanceof ISettings) {
208
+                $this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => ILogger::INFO]);
209
+                continue;
210
+            }
211
+
212
+            if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
+                $this->settings[$settingsType][$setting->getSection()] = [];
214
+            }
215
+            $this->settings[$settingsType][$setting->getSection()][] = $setting;
216
+
217
+            unset($this->settingClasses[$class]);
218
+        }
219
+
220
+        return $this->settings[$type][$section];
221
+    }
222
+
223
+    /**
224
+     * @inheritdoc
225
+     */
226
+    public function getAdminSections(): array {
227
+        // built-in sections
228
+        $sections = [
229
+            0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
+            5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
+            10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
+            45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
+            98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
+            99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
+        ];
236
+
237
+        $appSections = $this->getSections('admin');
238
+
239
+        foreach ($appSections as $section) {
240
+            /** @var ISection $section */
241
+            if (!isset($sections[$section->getPriority()])) {
242
+                $sections[$section->getPriority()] = [];
243
+            }
244
+
245
+            $sections[$section->getPriority()][] = $section;
246
+        }
247
+
248
+        ksort($sections);
249
+
250
+        return $sections;
251
+    }
252
+
253
+    /**
254
+     * @param string $section
255
+     * @return ISection[]
256
+     */
257
+    private function getBuiltInAdminSettings($section): array {
258
+        $forms = [];
259
+
260
+        if ($section === 'server') {
261
+            /** @var ISettings $form */
262
+            $form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
+            $forms[$form->getPriority()] = [$form];
264
+            $form = new Admin\ServerDevNotice();
265
+            $forms[$form->getPriority()] = [$form];
266
+        }
267
+        if ($section === 'encryption') {
268
+            /** @var ISettings $form */
269
+            $form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
+            $forms[$form->getPriority()] = [$form];
271
+        }
272
+        if ($section === 'sharing') {
273
+            /** @var ISettings $form */
274
+            $form = new Admin\Sharing($this->config, $this->l);
275
+            $forms[$form->getPriority()] = [$form];
276
+        }
277
+        if ($section === 'additional') {
278
+            /** @var ISettings $form */
279
+            $form = new Admin\Additional($this->config);
280
+            $forms[$form->getPriority()] = [$form];
281
+        }
282
+        if ($section === 'tips-tricks') {
283
+            /** @var ISettings $form */
284
+            $form = new Admin\TipsTricks($this->config);
285
+            $forms[$form->getPriority()] = [$form];
286
+        }
287
+
288
+        return $forms;
289
+    }
290
+
291
+    /**
292
+     * @param string $section
293
+     * @return ISection[]
294
+     */
295
+    private function getBuiltInPersonalSettings($section): array {
296
+        $forms = [];
297
+
298
+        if ($section === 'personal-info') {
299
+            /** @var ISettings $form */
300
+            $form = new Personal\PersonalInfo(
301
+                $this->config,
302
+                $this->userManager,
303
+                $this->groupManager,
304
+                $this->accountManager,
305
+                $this->appManager,
306
+                $this->l10nFactory,
307
+                $this->l
308
+            );
309
+            $forms[$form->getPriority()] = [$form];
310
+        }
311
+        if($section === 'security') {
312
+            /** @var ISettings $form */
313
+            $form = new Personal\Security();
314
+            $forms[$form->getPriority()] = [$form];
315
+        }
316
+        if ($section === 'additional') {
317
+            /** @var ISettings $form */
318
+            $form = new Personal\Additional();
319
+            $forms[$form->getPriority()] = [$form];
320
+        }
321
+
322
+        return $forms;
323
+    }
324
+
325
+    /**
326
+     * @inheritdoc
327
+     */
328
+    public function getAdminSettings($section): array {
329
+        $settings = $this->getBuiltInAdminSettings($section);
330
+        $appSettings = $this->getSettings('admin', $section);
331
+
332
+        foreach ($appSettings as $setting) {
333
+            if (!isset($settings[$setting->getPriority()])) {
334
+                $settings[$setting->getPriority()] = [];
335
+            }
336
+            $settings[$setting->getPriority()][] = $setting;
337
+        }
338
+
339
+        ksort($settings);
340
+        return $settings;
341
+    }
342
+
343
+    /**
344
+     * @inheritdoc
345
+     */
346
+    public function getPersonalSections(): array {
347
+        $sections = [
348
+            0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
+            5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
+            15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
+        ];
352
+
353
+        $legacyForms = \OC_App::getForms('personal');
354
+        if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
+            $sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
+        }
357
+
358
+        $appSections = $this->getSections('personal');
359
+
360
+        foreach ($appSections as $section) {
361
+            /** @var ISection $section */
362
+            if (!isset($sections[$section->getPriority()])) {
363
+                $sections[$section->getPriority()] = [];
364
+            }
365
+
366
+            $sections[$section->getPriority()][] = $section;
367
+        }
368
+
369
+        ksort($sections);
370
+
371
+        return $sections;
372
+    }
373
+
374
+    /**
375
+     * @param string[] $forms
376
+     * @return bool
377
+     */
378
+    private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
+        foreach ($forms as $form) {
380
+            if(trim($form) !== '') {
381
+                return true;
382
+            }
383
+        }
384
+        return false;
385
+    }
386
+
387
+    /**
388
+     * @inheritdoc
389
+     */
390
+    public function getPersonalSettings($section): array {
391
+        $settings = $this->getBuiltInPersonalSettings($section);
392
+        $appSettings = $this->getSettings('personal', $section);
393
+
394
+        foreach ($appSettings as $setting) {
395
+            if (!isset($settings[$setting->getPriority()])) {
396
+                $settings[$setting->getPriority()] = [];
397
+            }
398
+            $settings[$setting->getPriority()][] = $setting;
399
+        }
400
+
401
+        ksort($settings);
402
+        return $settings;
403
+    }
404 404
 }
Please login to merge, or discard this patch.
core/ajax/update.php 2 patches
Indentation   +178 added lines, -178 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 use Symfony\Component\EventDispatcher\GenericEvent;
34 34
 
35 35
 if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
36
-	@set_time_limit(0);
36
+    @set_time_limit(0);
37 37
 }
38 38
 
39 39
 require_once '../../lib/base.php';
@@ -47,188 +47,188 @@  discard block
 block discarded – undo
47 47
 $eventSource->send('success', (string)$l->t('Preparing update'));
48 48
 
49 49
 class FeedBackHandler {
50
-	/** @var integer */
51
-	private $progressStateMax = 100;
52
-	/** @var integer */
53
-	private $progressStateStep = 0;
54
-	/** @var string */
55
-	private $currentStep;
56
-	/** @var \OCP\IEventSource */
57
-	private $eventSource;
58
-	/** @var \OCP\IL10N */
59
-	private $l10n;
60
-
61
-	public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
62
-		$this->eventSource = $eventSource;
63
-		$this->l10n = $l10n;
64
-	}
65
-
66
-	public function handleRepairFeedback($event) {
67
-		if (!$event instanceof GenericEvent) {
68
-			return;
69
-		}
70
-
71
-		switch ($event->getSubject()) {
72
-			case '\OC\Repair::startProgress':
73
-				$this->progressStateMax = $event->getArgument(0);
74
-				$this->progressStateStep = 0;
75
-				$this->currentStep = $event->getArgument(1);
76
-				break;
77
-			case '\OC\Repair::advance':
78
-				$this->progressStateStep += $event->getArgument(0);
79
-				$desc = $event->getArgument(1);
80
-				if (empty($desc)) {
81
-					$desc = $this->currentStep;
82
-				}
83
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84
-				break;
85
-			case '\OC\Repair::finishProgress':
86
-				$this->progressStateMax = $this->progressStateStep;
87
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88
-				break;
89
-			case '\OC\Repair::step':
90
-				break;
91
-			case '\OC\Repair::info':
92
-				break;
93
-			case '\OC\Repair::warning':
94
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
95
-				break;
96
-			case '\OC\Repair::error':
97
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
98
-				break;
99
-		}
100
-	}
50
+    /** @var integer */
51
+    private $progressStateMax = 100;
52
+    /** @var integer */
53
+    private $progressStateStep = 0;
54
+    /** @var string */
55
+    private $currentStep;
56
+    /** @var \OCP\IEventSource */
57
+    private $eventSource;
58
+    /** @var \OCP\IL10N */
59
+    private $l10n;
60
+
61
+    public function __construct(\OCP\IEventSource $eventSource, \OCP\IL10N $l10n) {
62
+        $this->eventSource = $eventSource;
63
+        $this->l10n = $l10n;
64
+    }
65
+
66
+    public function handleRepairFeedback($event) {
67
+        if (!$event instanceof GenericEvent) {
68
+            return;
69
+        }
70
+
71
+        switch ($event->getSubject()) {
72
+            case '\OC\Repair::startProgress':
73
+                $this->progressStateMax = $event->getArgument(0);
74
+                $this->progressStateStep = 0;
75
+                $this->currentStep = $event->getArgument(1);
76
+                break;
77
+            case '\OC\Repair::advance':
78
+                $this->progressStateStep += $event->getArgument(0);
79
+                $desc = $event->getArgument(1);
80
+                if (empty($desc)) {
81
+                    $desc = $this->currentStep;
82
+                }
83
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84
+                break;
85
+            case '\OC\Repair::finishProgress':
86
+                $this->progressStateMax = $this->progressStateStep;
87
+                $this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88
+                break;
89
+            case '\OC\Repair::step':
90
+                break;
91
+            case '\OC\Repair::info':
92
+                break;
93
+            case '\OC\Repair::warning':
94
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
95
+                break;
96
+            case '\OC\Repair::error':
97
+                $this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
98
+                break;
99
+        }
100
+    }
101 101
 }
102 102
 
103 103
 if (\OCP\Util::needUpgrade()) {
104 104
 
105
-	$config = \OC::$server->getSystemConfig();
106
-	if ($config->getValue('upgrade.disable-web', false)) {
107
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108
-		$eventSource->close();
109
-		exit();
110
-	}
111
-
112
-	// if a user is currently logged in, their session must be ignored to
113
-	// avoid side effects
114
-	\OC_User::setIncognitoMode(true);
115
-
116
-	$logger = \OC::$server->getLogger();
117
-	$config = \OC::$server->getConfig();
118
-	$updater = new \OC\Updater(
119
-			$config,
120
-			\OC::$server->getIntegrityCodeChecker(),
121
-			$logger,
122
-			\OC::$server->query(\OC\Installer::class)
123
-	);
124
-	$incompatibleApps = [];
125
-
126
-	$dispatcher = \OC::$server->getEventDispatcher();
127
-	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128
-		if ($event instanceof GenericEvent) {
129
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130
-		}
131
-	});
132
-	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133
-		if ($event instanceof GenericEvent) {
134
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135
-		}
136
-	});
137
-	$feedBack = new FeedBackHandler($eventSource, $l);
138
-	$dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
139
-	$dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
140
-	$dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
141
-	$dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
142
-	$dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
143
-	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144
-	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145
-
146
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
148
-	});
149
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
151
-	});
152
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
154
-	});
155
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
157
-	});
158
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
-		$eventSource->send('success', (string)$l->t('Updated database'));
160
-	});
161
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163
-	});
164
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
166
-	});
167
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
169
-	});
170
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
172
-	});
173
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
175
-	});
176
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
178
-	});
179
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181
-	});
182
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
184
-	});
185
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
-		$eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
187
-	});
188
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
-		$incompatibleApps[]= $app;
190
-	});
191
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
192
-		$eventSource->send('failure', $message);
193
-		$eventSource->close();
194
-		$config->setSystemValue('maintenance', false);
195
-	});
196
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
198
-	});
199
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
-		$eventSource->send('success', (string)$l->t('Reset log level'));
201
-	});
202
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
204
-	});
205
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
207
-	});
208
-
209
-	try {
210
-		$updater->upgrade();
211
-	} catch (\Exception $e) {
212
-		\OC::$server->getLogger()->logException($e, [
213
-			'level' => ILogger::ERROR,
214
-			'app' => 'update',
215
-		]);
216
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
217
-		$eventSource->close();
218
-		exit();
219
-	}
220
-
221
-	$disabledApps = [];
222
-	foreach ($incompatibleApps as $app) {
223
-		$disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
224
-	}
225
-
226
-	if (!empty($disabledApps)) {
227
-		$eventSource->send('notice',
228
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229
-	}
105
+    $config = \OC::$server->getSystemConfig();
106
+    if ($config->getValue('upgrade.disable-web', false)) {
107
+        $eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108
+        $eventSource->close();
109
+        exit();
110
+    }
111
+
112
+    // if a user is currently logged in, their session must be ignored to
113
+    // avoid side effects
114
+    \OC_User::setIncognitoMode(true);
115
+
116
+    $logger = \OC::$server->getLogger();
117
+    $config = \OC::$server->getConfig();
118
+    $updater = new \OC\Updater(
119
+            $config,
120
+            \OC::$server->getIntegrityCodeChecker(),
121
+            $logger,
122
+            \OC::$server->query(\OC\Installer::class)
123
+    );
124
+    $incompatibleApps = [];
125
+
126
+    $dispatcher = \OC::$server->getEventDispatcher();
127
+    $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128
+        if ($event instanceof GenericEvent) {
129
+            $eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130
+        }
131
+    });
132
+    $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133
+        if ($event instanceof GenericEvent) {
134
+            $eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135
+        }
136
+    });
137
+    $feedBack = new FeedBackHandler($eventSource, $l);
138
+    $dispatcher->addListener('\OC\Repair::startProgress', [$feedBack, 'handleRepairFeedback']);
139
+    $dispatcher->addListener('\OC\Repair::advance', [$feedBack, 'handleRepairFeedback']);
140
+    $dispatcher->addListener('\OC\Repair::finishProgress', [$feedBack, 'handleRepairFeedback']);
141
+    $dispatcher->addListener('\OC\Repair::step', [$feedBack, 'handleRepairFeedback']);
142
+    $dispatcher->addListener('\OC\Repair::info', [$feedBack, 'handleRepairFeedback']);
143
+    $dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144
+    $dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145
+
146
+    $updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
+        $eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
148
+    });
149
+    $updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
+        $eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
151
+    });
152
+    $updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
+        $eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
154
+    });
155
+    $updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
+        $eventSource->send('success', (string)$l->t('Updating database schema'));
157
+    });
158
+    $updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
+        $eventSource->send('success', (string)$l->t('Updated database'));
160
+    });
161
+    $updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163
+    });
164
+    $updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
+        $eventSource->send('success', (string)$l->t('Checked database schema update'));
166
+    });
167
+    $updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
+        $eventSource->send('success', (string)$l->t('Checking updates of apps'));
169
+    });
170
+    $updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
+        $eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
172
+    });
173
+    $updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
+        $eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
175
+    });
176
+    $updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
+        $eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
178
+    });
179
+    $updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
+        $eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181
+    });
182
+    $updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
+        $eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
184
+    });
185
+    $updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
+        $eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
187
+    });
188
+    $updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
+        $incompatibleApps[]= $app;
190
+    });
191
+    $updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
192
+        $eventSource->send('failure', $message);
193
+        $eventSource->close();
194
+        $config->setSystemValue('maintenance', false);
195
+    });
196
+    $updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
+        $eventSource->send('success', (string)$l->t('Set log level to debug'));
198
+    });
199
+    $updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
+        $eventSource->send('success', (string)$l->t('Reset log level'));
201
+    });
202
+    $updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
+        $eventSource->send('success', (string)$l->t('Starting code integrity check'));
204
+    });
205
+    $updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
+        $eventSource->send('success', (string)$l->t('Finished code integrity check'));
207
+    });
208
+
209
+    try {
210
+        $updater->upgrade();
211
+    } catch (\Exception $e) {
212
+        \OC::$server->getLogger()->logException($e, [
213
+            'level' => ILogger::ERROR,
214
+            'app' => 'update',
215
+        ]);
216
+        $eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
217
+        $eventSource->close();
218
+        exit();
219
+    }
220
+
221
+    $disabledApps = [];
222
+    foreach ($incompatibleApps as $app) {
223
+        $disabledApps[$app] = (string) $l->t('%s (incompatible)', [$app]);
224
+    }
225
+
226
+    if (!empty($disabledApps)) {
227
+        $eventSource->send('notice',
228
+            (string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229
+    }
230 230
 } else {
231
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
231
+    $eventSource->send('notice', (string)$l->t('Already up to date'));
232 232
 }
233 233
 
234 234
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 // need to send an initial message to force-init the event source,
45 45
 // which will then trigger its own CSRF check and produces its own CSRF error
46 46
 // message
47
-$eventSource->send('success', (string)$l->t('Preparing update'));
47
+$eventSource->send('success', (string) $l->t('Preparing update'));
48 48
 
49 49
 class FeedBackHandler {
50 50
 	/** @var integer */
@@ -80,21 +80,21 @@  discard block
 block discarded – undo
80 80
 				if (empty($desc)) {
81 81
 					$desc = $this->currentStep;
82 82
 				}
83
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
83
+				$this->eventSource->send('success', (string) $this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $desc]));
84 84
 				break;
85 85
 			case '\OC\Repair::finishProgress':
86 86
 				$this->progressStateMax = $this->progressStateStep;
87
-				$this->eventSource->send('success', (string)$this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
87
+				$this->eventSource->send('success', (string) $this->l10n->t('[%d / %d]: %s', [$this->progressStateStep, $this->progressStateMax, $this->currentStep]));
88 88
 				break;
89 89
 			case '\OC\Repair::step':
90 90
 				break;
91 91
 			case '\OC\Repair::info':
92 92
 				break;
93 93
 			case '\OC\Repair::warning':
94
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair warning: ') . $event->getArgument(0));
94
+				$this->eventSource->send('notice', (string) $this->l10n->t('Repair warning: ').$event->getArgument(0));
95 95
 				break;
96 96
 			case '\OC\Repair::error':
97
-				$this->eventSource->send('notice', (string)$this->l10n->t('Repair error: ') . $event->getArgument(0));
97
+				$this->eventSource->send('notice', (string) $this->l10n->t('Repair error: ').$event->getArgument(0));
98 98
 				break;
99 99
 		}
100 100
 	}
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 
105 105
 	$config = \OC::$server->getSystemConfig();
106 106
 	if ($config->getValue('upgrade.disable-web', false)) {
107
-		$eventSource->send('failure', (string)$l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
107
+		$eventSource->send('failure', (string) $l->t('Please use the command line updater because automatic updating is disabled in the config.php.'));
108 108
 		$eventSource->close();
109 109
 		exit();
110 110
 	}
@@ -126,12 +126,12 @@  discard block
 block discarded – undo
126 126
 	$dispatcher = \OC::$server->getEventDispatcher();
127 127
 	$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($eventSource, $l) {
128 128
 		if ($event instanceof GenericEvent) {
129
-			$eventSource->send('success', (string)$l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
129
+			$eventSource->send('success', (string) $l->t('[%d / %d]: %s', [$event[0], $event[1], $event->getSubject()]));
130 130
 		}
131 131
 	});
132 132
 	$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($eventSource, $l) {
133 133
 		if ($event instanceof GenericEvent) {
134
-			$eventSource->send('success', (string)$l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
134
+			$eventSource->send('success', (string) $l->t('[%d / %d]: Checking table %s', [$event[0], $event[1], $event->getSubject()]));
135 135
 		}
136 136
 	});
137 137
 	$feedBack = new FeedBackHandler($eventSource, $l);
@@ -143,67 +143,67 @@  discard block
 block discarded – undo
143 143
 	$dispatcher->addListener('\OC\Repair::warning', [$feedBack, 'handleRepairFeedback']);
144 144
 	$dispatcher->addListener('\OC\Repair::error', [$feedBack, 'handleRepairFeedback']);
145 145
 
146
-	$updater->listen('\OC\Updater', 'maintenanceEnabled', function () use ($eventSource, $l) {
147
-		$eventSource->send('success', (string)$l->t('Turned on maintenance mode'));
146
+	$updater->listen('\OC\Updater', 'maintenanceEnabled', function() use ($eventSource, $l) {
147
+		$eventSource->send('success', (string) $l->t('Turned on maintenance mode'));
148 148
 	});
149
-	$updater->listen('\OC\Updater', 'maintenanceDisabled', function () use ($eventSource, $l) {
150
-		$eventSource->send('success', (string)$l->t('Turned off maintenance mode'));
149
+	$updater->listen('\OC\Updater', 'maintenanceDisabled', function() use ($eventSource, $l) {
150
+		$eventSource->send('success', (string) $l->t('Turned off maintenance mode'));
151 151
 	});
152
-	$updater->listen('\OC\Updater', 'maintenanceActive', function () use ($eventSource, $l) {
153
-		$eventSource->send('success', (string)$l->t('Maintenance mode is kept active'));
152
+	$updater->listen('\OC\Updater', 'maintenanceActive', function() use ($eventSource, $l) {
153
+		$eventSource->send('success', (string) $l->t('Maintenance mode is kept active'));
154 154
 	});
155
-	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function () use($eventSource, $l) {
156
-		$eventSource->send('success', (string)$l->t('Updating database schema'));
155
+	$updater->listen('\OC\Updater', 'dbUpgradeBefore', function() use($eventSource, $l) {
156
+		$eventSource->send('success', (string) $l->t('Updating database schema'));
157 157
 	});
158
-	$updater->listen('\OC\Updater', 'dbUpgrade', function () use ($eventSource, $l) {
159
-		$eventSource->send('success', (string)$l->t('Updated database'));
158
+	$updater->listen('\OC\Updater', 'dbUpgrade', function() use ($eventSource, $l) {
159
+		$eventSource->send('success', (string) $l->t('Updated database'));
160 160
 	});
161
-	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($eventSource, $l) {
162
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
161
+	$updater->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function() use($eventSource, $l) {
162
+		$eventSource->send('success', (string) $l->t('Checking whether the database schema can be updated (this can take a long time depending on the database size)'));
163 163
 	});
164
-	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function () use ($eventSource, $l) {
165
-		$eventSource->send('success', (string)$l->t('Checked database schema update'));
164
+	$updater->listen('\OC\Updater', 'dbSimulateUpgrade', function() use ($eventSource, $l) {
165
+		$eventSource->send('success', (string) $l->t('Checked database schema update'));
166 166
 	});
167
-	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($eventSource, $l) {
168
-		$eventSource->send('success', (string)$l->t('Checking updates of apps'));
167
+	$updater->listen('\OC\Updater', 'appUpgradeCheckBefore', function() use ($eventSource, $l) {
168
+		$eventSource->send('success', (string) $l->t('Checking updates of apps'));
169 169
 	});
170
-	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use ($eventSource, $l) {
171
-		$eventSource->send('success', (string)$l->t('Checking for update of app "%s" in appstore', [$app]));
170
+	$updater->listen('\OC\Updater', 'checkAppStoreAppBefore', function($app) use ($eventSource, $l) {
171
+		$eventSource->send('success', (string) $l->t('Checking for update of app "%s" in appstore', [$app]));
172 172
 	});
173
-	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use ($eventSource, $l) {
174
-		$eventSource->send('success', (string)$l->t('Update app "%s" from appstore', [$app]));
173
+	$updater->listen('\OC\Updater', 'upgradeAppStoreApp', function($app) use ($eventSource, $l) {
174
+		$eventSource->send('success', (string) $l->t('Update app "%s" from appstore', [$app]));
175 175
 	});
176
-	$updater->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use ($eventSource, $l) {
177
-		$eventSource->send('success', (string)$l->t('Checked for update of app "%s" in appstore', [$app]));
176
+	$updater->listen('\OC\Updater', 'checkAppStoreApp', function($app) use ($eventSource, $l) {
177
+		$eventSource->send('success', (string) $l->t('Checked for update of app "%s" in appstore', [$app]));
178 178
 	});
179
-	$updater->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($eventSource, $l) {
180
-		$eventSource->send('success', (string)$l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
179
+	$updater->listen('\OC\Updater', 'appSimulateUpdate', function($app) use ($eventSource, $l) {
180
+		$eventSource->send('success', (string) $l->t('Checking whether the database schema for %s can be updated (this can take a long time depending on the database size)', [$app]));
181 181
 	});
182
-	$updater->listen('\OC\Updater', 'appUpgradeCheck', function () use ($eventSource, $l) {
183
-		$eventSource->send('success', (string)$l->t('Checked database schema update for apps'));
182
+	$updater->listen('\OC\Updater', 'appUpgradeCheck', function() use ($eventSource, $l) {
183
+		$eventSource->send('success', (string) $l->t('Checked database schema update for apps'));
184 184
 	});
185
-	$updater->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($eventSource, $l) {
186
-		$eventSource->send('success', (string)$l->t('Updated "%s" to %s', array($app, $version)));
185
+	$updater->listen('\OC\Updater', 'appUpgrade', function($app, $version) use ($eventSource, $l) {
186
+		$eventSource->send('success', (string) $l->t('Updated "%s" to %s', array($app, $version)));
187 187
 	});
188
-	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use (&$incompatibleApps) {
189
-		$incompatibleApps[]= $app;
188
+	$updater->listen('\OC\Updater', 'incompatibleAppDisabled', function($app) use (&$incompatibleApps) {
189
+		$incompatibleApps[] = $app;
190 190
 	});
191
-	$updater->listen('\OC\Updater', 'failure', function ($message) use ($eventSource, $config) {
191
+	$updater->listen('\OC\Updater', 'failure', function($message) use ($eventSource, $config) {
192 192
 		$eventSource->send('failure', $message);
193 193
 		$eventSource->close();
194 194
 		$config->setSystemValue('maintenance', false);
195 195
 	});
196
-	$updater->listen('\OC\Updater', 'setDebugLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
197
-		$eventSource->send('success', (string)$l->t('Set log level to debug'));
196
+	$updater->listen('\OC\Updater', 'setDebugLogLevel', function($logLevel, $logLevelName) use($eventSource, $l) {
197
+		$eventSource->send('success', (string) $l->t('Set log level to debug'));
198 198
 	});
199
-	$updater->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($eventSource, $l) {
200
-		$eventSource->send('success', (string)$l->t('Reset log level'));
199
+	$updater->listen('\OC\Updater', 'resetLogLevel', function($logLevel, $logLevelName) use($eventSource, $l) {
200
+		$eventSource->send('success', (string) $l->t('Reset log level'));
201 201
 	});
202
-	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($eventSource, $l) {
203
-		$eventSource->send('success', (string)$l->t('Starting code integrity check'));
202
+	$updater->listen('\OC\Updater', 'startCheckCodeIntegrity', function() use($eventSource, $l) {
203
+		$eventSource->send('success', (string) $l->t('Starting code integrity check'));
204 204
 	});
205
-	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($eventSource, $l) {
206
-		$eventSource->send('success', (string)$l->t('Finished code integrity check'));
205
+	$updater->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function() use($eventSource, $l) {
206
+		$eventSource->send('success', (string) $l->t('Finished code integrity check'));
207 207
 	});
208 208
 
209 209
 	try {
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 			'level' => ILogger::ERROR,
214 214
 			'app' => 'update',
215 215
 		]);
216
-		$eventSource->send('failure', get_class($e) . ': ' . $e->getMessage());
216
+		$eventSource->send('failure', get_class($e).': '.$e->getMessage());
217 217
 		$eventSource->close();
218 218
 		exit();
219 219
 	}
@@ -225,10 +225,10 @@  discard block
 block discarded – undo
225 225
 
226 226
 	if (!empty($disabledApps)) {
227 227
 		$eventSource->send('notice',
228
-			(string)$l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
228
+			(string) $l->t('Following apps have been disabled: %s', [implode(', ', $disabledApps)]));
229 229
 	}
230 230
 } else {
231
-	$eventSource->send('notice', (string)$l->t('Already up to date'));
231
+	$eventSource->send('notice', (string) $l->t('Already up to date'));
232 232
 }
233 233
 
234 234
 $eventSource->send('done', '');
Please login to merge, or discard this patch.
core/Controller/SetupController.php 2 patches
Indentation   +81 added lines, -81 removed lines patch added patch discarded remove patch
@@ -33,97 +33,97 @@
 block discarded – undo
33 33
 use OCP\ILogger;
34 34
 
35 35
 class SetupController {
36
-	/** @var Setup */
37
-	protected $setupHelper;
38
-	/** @var string */
39
-	private $autoConfigFile;
36
+    /** @var Setup */
37
+    protected $setupHelper;
38
+    /** @var string */
39
+    private $autoConfigFile;
40 40
 
41
-	/**
42
-	 * @param Setup $setupHelper
43
-	 */
44
-	function __construct(Setup $setupHelper) {
45
-		$this->autoConfigFile = \OC::$configDir.'autoconfig.php';
46
-		$this->setupHelper = $setupHelper;
47
-	}
41
+    /**
42
+     * @param Setup $setupHelper
43
+     */
44
+    function __construct(Setup $setupHelper) {
45
+        $this->autoConfigFile = \OC::$configDir.'autoconfig.php';
46
+        $this->setupHelper = $setupHelper;
47
+    }
48 48
 
49
-	/**
50
-	 * @param $post
51
-	 */
52
-	public function run($post) {
53
-		// Check for autosetup:
54
-		$post = $this->loadAutoConfig($post);
55
-		$opts = $this->setupHelper->getSystemInfo();
49
+    /**
50
+     * @param $post
51
+     */
52
+    public function run($post) {
53
+        // Check for autosetup:
54
+        $post = $this->loadAutoConfig($post);
55
+        $opts = $this->setupHelper->getSystemInfo();
56 56
 
57
-		// convert 'abcpassword' to 'abcpass'
58
-		if (isset($post['adminpassword'])) {
59
-			$post['adminpass'] = $post['adminpassword'];
60
-		}
61
-		if (isset($post['dbpassword'])) {
62
-			$post['dbpass'] = $post['dbpassword'];
63
-		}
57
+        // convert 'abcpassword' to 'abcpass'
58
+        if (isset($post['adminpassword'])) {
59
+            $post['adminpass'] = $post['adminpassword'];
60
+        }
61
+        if (isset($post['dbpassword'])) {
62
+            $post['dbpass'] = $post['dbpassword'];
63
+        }
64 64
 
65
-		if(isset($post['install']) AND $post['install']=='true') {
66
-			// We have to launch the installation process :
67
-			$e = $this->setupHelper->install($post);
68
-			$errors = array('errors' => $e);
65
+        if(isset($post['install']) AND $post['install']=='true') {
66
+            // We have to launch the installation process :
67
+            $e = $this->setupHelper->install($post);
68
+            $errors = array('errors' => $e);
69 69
 
70
-			if(count($e) > 0) {
71
-				$options = array_merge($opts, $post, $errors);
72
-				$this->display($options);
73
-			} else {
74
-				$this->finishSetup();
75
-			}
76
-		} else {
77
-			$options = array_merge($opts, $post);
78
-			$this->display($options);
79
-		}
80
-	}
70
+            if(count($e) > 0) {
71
+                $options = array_merge($opts, $post, $errors);
72
+                $this->display($options);
73
+            } else {
74
+                $this->finishSetup();
75
+            }
76
+        } else {
77
+            $options = array_merge($opts, $post);
78
+            $this->display($options);
79
+        }
80
+    }
81 81
 
82
-	public function display($post) {
83
-		$defaults = array(
84
-			'adminlogin' => '',
85
-			'adminpass' => '',
86
-			'dbuser' => '',
87
-			'dbpass' => '',
88
-			'dbname' => '',
89
-			'dbtablespace' => '',
90
-			'dbhost' => 'localhost',
91
-			'dbtype' => '',
92
-		);
93
-		$parameters = array_merge($defaults, $post);
82
+    public function display($post) {
83
+        $defaults = array(
84
+            'adminlogin' => '',
85
+            'adminpass' => '',
86
+            'dbuser' => '',
87
+            'dbpass' => '',
88
+            'dbname' => '',
89
+            'dbtablespace' => '',
90
+            'dbhost' => 'localhost',
91
+            'dbtype' => '',
92
+        );
93
+        $parameters = array_merge($defaults, $post);
94 94
 
95
-		\OC_Util::addVendorScript('strengthify/jquery.strengthify');
96
-		\OC_Util::addVendorStyle('strengthify/strengthify');
97
-		\OC_Util::addScript('setup');
98
-		\OC_Template::printGuestPage('', 'installation', $parameters);
99
-	}
95
+        \OC_Util::addVendorScript('strengthify/jquery.strengthify');
96
+        \OC_Util::addVendorStyle('strengthify/strengthify');
97
+        \OC_Util::addScript('setup');
98
+        \OC_Template::printGuestPage('', 'installation', $parameters);
99
+    }
100 100
 
101
-	public function finishSetup() {
102
-		if( file_exists( $this->autoConfigFile )) {
103
-			unlink($this->autoConfigFile);
104
-		}
105
-		\OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
106
-		\OC_Util::redirectToDefaultPage();
107
-	}
101
+    public function finishSetup() {
102
+        if( file_exists( $this->autoConfigFile )) {
103
+            unlink($this->autoConfigFile);
104
+        }
105
+        \OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
106
+        \OC_Util::redirectToDefaultPage();
107
+    }
108 108
 
109
-	public function loadAutoConfig($post) {
110
-		if( file_exists($this->autoConfigFile)) {
111
-			\OCP\Util::writeLog('core', 'Autoconfig file found, setting up ownCloud…', ILogger::INFO);
112
-			$AUTOCONFIG = array();
113
-			include $this->autoConfigFile;
114
-			$post = array_merge ($post, $AUTOCONFIG);
115
-		}
109
+    public function loadAutoConfig($post) {
110
+        if( file_exists($this->autoConfigFile)) {
111
+            \OCP\Util::writeLog('core', 'Autoconfig file found, setting up ownCloud…', ILogger::INFO);
112
+            $AUTOCONFIG = array();
113
+            include $this->autoConfigFile;
114
+            $post = array_merge ($post, $AUTOCONFIG);
115
+        }
116 116
 
117
-		$dbIsSet = isset($post['dbtype']);
118
-		$directoryIsSet = isset($post['directory']);
119
-		$adminAccountIsSet = isset($post['adminlogin']);
117
+        $dbIsSet = isset($post['dbtype']);
118
+        $directoryIsSet = isset($post['directory']);
119
+        $adminAccountIsSet = isset($post['adminlogin']);
120 120
 
121
-		if ($dbIsSet AND $directoryIsSet AND $adminAccountIsSet) {
122
-			$post['install'] = 'true';
123
-		}
124
-		$post['dbIsSet'] = $dbIsSet;
125
-		$post['directoryIsSet'] = $directoryIsSet;
121
+        if ($dbIsSet AND $directoryIsSet AND $adminAccountIsSet) {
122
+            $post['install'] = 'true';
123
+        }
124
+        $post['dbIsSet'] = $dbIsSet;
125
+        $post['directoryIsSet'] = $directoryIsSet;
126 126
 
127
-		return $post;
128
-	}
127
+        return $post;
128
+    }
129 129
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -62,12 +62,12 @@  discard block
 block discarded – undo
62 62
 			$post['dbpass'] = $post['dbpassword'];
63 63
 		}
64 64
 
65
-		if(isset($post['install']) AND $post['install']=='true') {
65
+		if (isset($post['install']) AND $post['install'] == 'true') {
66 66
 			// We have to launch the installation process :
67 67
 			$e = $this->setupHelper->install($post);
68 68
 			$errors = array('errors' => $e);
69 69
 
70
-			if(count($e) > 0) {
70
+			if (count($e) > 0) {
71 71
 				$options = array_merge($opts, $post, $errors);
72 72
 				$this->display($options);
73 73
 			} else {
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
 	}
100 100
 
101 101
 	public function finishSetup() {
102
-		if( file_exists( $this->autoConfigFile )) {
102
+		if (file_exists($this->autoConfigFile)) {
103 103
 			unlink($this->autoConfigFile);
104 104
 		}
105 105
 		\OC::$server->getIntegrityCodeChecker()->runInstanceVerification();
@@ -107,11 +107,11 @@  discard block
 block discarded – undo
107 107
 	}
108 108
 
109 109
 	public function loadAutoConfig($post) {
110
-		if( file_exists($this->autoConfigFile)) {
110
+		if (file_exists($this->autoConfigFile)) {
111 111
 			\OCP\Util::writeLog('core', 'Autoconfig file found, setting up ownCloud…', ILogger::INFO);
112 112
 			$AUTOCONFIG = array();
113 113
 			include $this->autoConfigFile;
114
-			$post = array_merge ($post, $AUTOCONFIG);
114
+			$post = array_merge($post, $AUTOCONFIG);
115 115
 		}
116 116
 
117 117
 		$dbIsSet = isset($post['dbtype']);
Please login to merge, or discard this patch.
apps/files_trashbin/lib/Storage.php 1 patch
Indentation   +279 added lines, -279 removed lines patch added patch discarded remove patch
@@ -40,284 +40,284 @@
 block discarded – undo
40 40
 
41 41
 class Storage extends Wrapper {
42 42
 
43
-	private $mountPoint;
44
-	// remember already deleted files to avoid infinite loops if the trash bin
45
-	// move files across storages
46
-	private $deletedFiles = array();
47
-
48
-	/**
49
-	 * Disable trash logic
50
-	 *
51
-	 * @var bool
52
-	 */
53
-	private static $disableTrash = false;
54
-
55
-	/**
56
-	 * remember which file/folder was moved out of s shared folder
57
-	 * in this case we want to add a copy to the owners trash bin
58
-	 *
59
-	 * @var array
60
-	 */
61
-	private static $moveOutOfSharedFolder = [];
62
-
63
-	/** @var  IUserManager */
64
-	private $userManager;
65
-
66
-	/** @var ILogger */
67
-	private $logger;
68
-
69
-	/** @var EventDispatcher */
70
-	private $eventDispatcher;
71
-
72
-	/** @var IRootFolder */
73
-	private $rootFolder;
74
-
75
-	/**
76
-	 * Storage constructor.
77
-	 *
78
-	 * @param array $parameters
79
-	 * @param IUserManager|null $userManager
80
-	 * @param ILogger|null $logger
81
-	 * @param EventDispatcher|null $eventDispatcher
82
-	 * @param IRootFolder|null $rootFolder
83
-	 */
84
-	public function __construct($parameters,
85
-								IUserManager $userManager = null,
86
-								ILogger $logger = null,
87
-								EventDispatcher $eventDispatcher = null,
88
-								IRootFolder $rootFolder = null) {
89
-		$this->mountPoint = $parameters['mountPoint'];
90
-		$this->userManager = $userManager;
91
-		$this->logger = $logger;
92
-		$this->eventDispatcher = $eventDispatcher;
93
-		$this->rootFolder = $rootFolder;
94
-		parent::__construct($parameters);
95
-	}
96
-
97
-	/**
98
-	 * @internal
99
-	 */
100
-	public static function preRenameHook($params) {
101
-		// in cross-storage cases, a rename is a copy + unlink,
102
-		// that last unlink must not go to trash, only exception:
103
-		// if the file was moved from a shared storage to a local folder,
104
-		// in this case the owner should get a copy in his trash bin so that
105
-		// they can restore the files again
106
-
107
-		$oldPath = $params['oldpath'];
108
-		$newPath = dirname($params['newpath']);
109
-		$currentUser = \OC::$server->getUserSession()->getUser();
110
-
111
-		$fileMovedOutOfSharedFolder = false;
112
-
113
-		try {
114
-			if ($currentUser) {
115
-				$currentUserId = $currentUser->getUID();
116
-
117
-				$view = new View($currentUserId . '/files');
118
-				$fileInfo = $view->getFileInfo($oldPath);
119
-				if ($fileInfo) {
120
-					$sourceStorage = $fileInfo->getStorage();
121
-					$sourceOwner = $view->getOwner($oldPath);
122
-					$targetOwner = $view->getOwner($newPath);
123
-
124
-					if ($sourceOwner !== $targetOwner
125
-						&& $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
126
-					) {
127
-						$fileMovedOutOfSharedFolder = true;
128
-					}
129
-				}
130
-			}
131
-		} catch (\Exception $e) {
132
-			// do nothing, in this case we just disable the trashbin and continue
133
-			\OC::$server->getLogger()->logException($e, [
134
-				'message' => 'Trashbin storage could not check if a file was moved out of a shared folder.',
135
-				'level' => ILogger::DEBUG,
136
-				'app' => 'files_trashbin',
137
-			]);
138
-		}
139
-
140
-		if($fileMovedOutOfSharedFolder) {
141
-			self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
142
-		} else {
143
-			self::$disableTrash = true;
144
-		}
145
-
146
-	}
147
-
148
-	/**
149
-	 * @internal
150
-	 */
151
-	public static function postRenameHook($params) {
152
-		self::$disableTrash = false;
153
-	}
154
-
155
-	/**
156
-	 * Rename path1 to path2 by calling the wrapped storage.
157
-	 *
158
-	 * @param string $path1 first path
159
-	 * @param string $path2 second path
160
-	 * @return bool
161
-	 */
162
-	public function rename($path1, $path2) {
163
-		$result = $this->storage->rename($path1, $path2);
164
-		if ($result === false) {
165
-			// when rename failed, the post_rename hook isn't triggered,
166
-			// but we still want to reenable the trash logic
167
-			self::$disableTrash = false;
168
-		}
169
-		return $result;
170
-	}
171
-
172
-	/**
173
-	 * Deletes the given file by moving it into the trashbin.
174
-	 *
175
-	 * @param string $path path of file or folder to delete
176
-	 *
177
-	 * @return bool true if the operation succeeded, false otherwise
178
-	 */
179
-	public function unlink($path) {
180
-		try {
181
-			if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
182
-				$result = $this->doDelete($path, 'unlink', true);
183
-				unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
184
-			} else {
185
-				$result = $this->doDelete($path, 'unlink');
186
-			}
187
-		} catch (GenericEncryptionException $e) {
188
-			// in case of a encryption exception we delete the file right away
189
-			$this->logger->info(
190
-				"Can't move file" .  $path .
191
-				"to the trash bin, therefore it was deleted right away");
192
-
193
-			$result = $this->storage->unlink($path);
194
-		}
195
-
196
-		return $result;
197
-	}
198
-
199
-	/**
200
-	 * Deletes the given folder by moving it into the trashbin.
201
-	 *
202
-	 * @param string $path path of folder to delete
203
-	 *
204
-	 * @return bool true if the operation succeeded, false otherwise
205
-	 */
206
-	public function rmdir($path) {
207
-		if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
208
-			$result = $this->doDelete($path, 'rmdir', true);
209
-			unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
210
-		} else {
211
-			$result = $this->doDelete($path, 'rmdir');
212
-		}
213
-
214
-		return $result;
215
-	}
216
-
217
-	/**
218
-	 * check if it is a file located in data/user/files only files in the
219
-	 * 'files' directory should be moved to the trash
220
-	 *
221
-	 * @param $path
222
-	 * @return bool
223
-	 */
224
-	protected function shouldMoveToTrash($path){
225
-
226
-		// check if there is a app which want to disable the trash bin for this file
227
-		$fileId = $this->storage->getCache()->getId($path);
228
-		$nodes = $this->rootFolder->getById($fileId);
229
-		foreach ($nodes as $node) {
230
-			$event = $this->createMoveToTrashEvent($node);
231
-			$this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event);
232
-			if ($event->shouldMoveToTrashBin() === false) {
233
-				return false;
234
-			}
235
-		}
236
-
237
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
238
-		$parts = explode('/', $normalized);
239
-		if (count($parts) < 4) {
240
-			return false;
241
-		}
242
-
243
-		if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) {
244
-			return true;
245
-		}
246
-
247
-		return false;
248
-	}
249
-
250
-	/**
251
-	 * get move to trash event
252
-	 *
253
-	 * @param Node $node
254
-	 * @return MoveToTrashEvent
255
-	 */
256
-	protected function createMoveToTrashEvent(Node $node) {
257
-		return new MoveToTrashEvent($node);
258
-	}
259
-
260
-	/**
261
-	 * Run the delete operation with the given method
262
-	 *
263
-	 * @param string $path path of file or folder to delete
264
-	 * @param string $method either "unlink" or "rmdir"
265
-	 * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
266
-	 *
267
-	 * @return bool true if the operation succeeded, false otherwise
268
-	 */
269
-	private function doDelete($path, $method, $ownerOnly = false) {
270
-		if (self::$disableTrash
271
-			|| !\OC::$server->getAppManager()->isEnabledForUser('files_trashbin')
272
-			|| (pathinfo($path, PATHINFO_EXTENSION) === 'part')
273
-			|| $this->shouldMoveToTrash($path) === false
274
-		) {
275
-			return call_user_func_array([$this->storage, $method], [$path]);
276
-		}
277
-
278
-		// check permissions before we continue, this is especially important for
279
-		// shared files
280
-		if (!$this->isDeletable($path)) {
281
-			return false;
282
-		}
283
-
284
-		$normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
285
-		$result = true;
286
-		$view = Filesystem::getView();
287
-		if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
288
-			$this->deletedFiles[$normalized] = $normalized;
289
-			if ($filesPath = $view->getRelativePath($normalized)) {
290
-				$filesPath = trim($filesPath, '/');
291
-				$result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
292
-				// in cross-storage cases the file will be copied
293
-				// but not deleted, so we delete it here
294
-				if ($result) {
295
-					call_user_func_array([$this->storage, $method], [$path]);
296
-				}
297
-			} else {
298
-				$result = call_user_func_array([$this->storage, $method], [$path]);
299
-			}
300
-			unset($this->deletedFiles[$normalized]);
301
-		} else if ($this->storage->file_exists($path)) {
302
-			$result = call_user_func_array([$this->storage, $method], [$path]);
303
-		}
304
-
305
-		return $result;
306
-	}
307
-
308
-	/**
309
-	 * Setup the storate wrapper callback
310
-	 */
311
-	public static function setupStorage() {
312
-		\OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
313
-			return new \OCA\Files_Trashbin\Storage(
314
-				array('storage' => $storage, 'mountPoint' => $mountPoint),
315
-				\OC::$server->getUserManager(),
316
-				\OC::$server->getLogger(),
317
-				\OC::$server->getEventDispatcher(),
318
-				\OC::$server->getLazyRootFolder()
319
-			);
320
-		}, 1);
321
-	}
43
+    private $mountPoint;
44
+    // remember already deleted files to avoid infinite loops if the trash bin
45
+    // move files across storages
46
+    private $deletedFiles = array();
47
+
48
+    /**
49
+     * Disable trash logic
50
+     *
51
+     * @var bool
52
+     */
53
+    private static $disableTrash = false;
54
+
55
+    /**
56
+     * remember which file/folder was moved out of s shared folder
57
+     * in this case we want to add a copy to the owners trash bin
58
+     *
59
+     * @var array
60
+     */
61
+    private static $moveOutOfSharedFolder = [];
62
+
63
+    /** @var  IUserManager */
64
+    private $userManager;
65
+
66
+    /** @var ILogger */
67
+    private $logger;
68
+
69
+    /** @var EventDispatcher */
70
+    private $eventDispatcher;
71
+
72
+    /** @var IRootFolder */
73
+    private $rootFolder;
74
+
75
+    /**
76
+     * Storage constructor.
77
+     *
78
+     * @param array $parameters
79
+     * @param IUserManager|null $userManager
80
+     * @param ILogger|null $logger
81
+     * @param EventDispatcher|null $eventDispatcher
82
+     * @param IRootFolder|null $rootFolder
83
+     */
84
+    public function __construct($parameters,
85
+                                IUserManager $userManager = null,
86
+                                ILogger $logger = null,
87
+                                EventDispatcher $eventDispatcher = null,
88
+                                IRootFolder $rootFolder = null) {
89
+        $this->mountPoint = $parameters['mountPoint'];
90
+        $this->userManager = $userManager;
91
+        $this->logger = $logger;
92
+        $this->eventDispatcher = $eventDispatcher;
93
+        $this->rootFolder = $rootFolder;
94
+        parent::__construct($parameters);
95
+    }
96
+
97
+    /**
98
+     * @internal
99
+     */
100
+    public static function preRenameHook($params) {
101
+        // in cross-storage cases, a rename is a copy + unlink,
102
+        // that last unlink must not go to trash, only exception:
103
+        // if the file was moved from a shared storage to a local folder,
104
+        // in this case the owner should get a copy in his trash bin so that
105
+        // they can restore the files again
106
+
107
+        $oldPath = $params['oldpath'];
108
+        $newPath = dirname($params['newpath']);
109
+        $currentUser = \OC::$server->getUserSession()->getUser();
110
+
111
+        $fileMovedOutOfSharedFolder = false;
112
+
113
+        try {
114
+            if ($currentUser) {
115
+                $currentUserId = $currentUser->getUID();
116
+
117
+                $view = new View($currentUserId . '/files');
118
+                $fileInfo = $view->getFileInfo($oldPath);
119
+                if ($fileInfo) {
120
+                    $sourceStorage = $fileInfo->getStorage();
121
+                    $sourceOwner = $view->getOwner($oldPath);
122
+                    $targetOwner = $view->getOwner($newPath);
123
+
124
+                    if ($sourceOwner !== $targetOwner
125
+                        && $sourceStorage->instanceOfStorage('OCA\Files_Sharing\SharedStorage')
126
+                    ) {
127
+                        $fileMovedOutOfSharedFolder = true;
128
+                    }
129
+                }
130
+            }
131
+        } catch (\Exception $e) {
132
+            // do nothing, in this case we just disable the trashbin and continue
133
+            \OC::$server->getLogger()->logException($e, [
134
+                'message' => 'Trashbin storage could not check if a file was moved out of a shared folder.',
135
+                'level' => ILogger::DEBUG,
136
+                'app' => 'files_trashbin',
137
+            ]);
138
+        }
139
+
140
+        if($fileMovedOutOfSharedFolder) {
141
+            self::$moveOutOfSharedFolder['/' . $currentUserId . '/files' . $oldPath] = true;
142
+        } else {
143
+            self::$disableTrash = true;
144
+        }
145
+
146
+    }
147
+
148
+    /**
149
+     * @internal
150
+     */
151
+    public static function postRenameHook($params) {
152
+        self::$disableTrash = false;
153
+    }
154
+
155
+    /**
156
+     * Rename path1 to path2 by calling the wrapped storage.
157
+     *
158
+     * @param string $path1 first path
159
+     * @param string $path2 second path
160
+     * @return bool
161
+     */
162
+    public function rename($path1, $path2) {
163
+        $result = $this->storage->rename($path1, $path2);
164
+        if ($result === false) {
165
+            // when rename failed, the post_rename hook isn't triggered,
166
+            // but we still want to reenable the trash logic
167
+            self::$disableTrash = false;
168
+        }
169
+        return $result;
170
+    }
171
+
172
+    /**
173
+     * Deletes the given file by moving it into the trashbin.
174
+     *
175
+     * @param string $path path of file or folder to delete
176
+     *
177
+     * @return bool true if the operation succeeded, false otherwise
178
+     */
179
+    public function unlink($path) {
180
+        try {
181
+            if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
182
+                $result = $this->doDelete($path, 'unlink', true);
183
+                unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
184
+            } else {
185
+                $result = $this->doDelete($path, 'unlink');
186
+            }
187
+        } catch (GenericEncryptionException $e) {
188
+            // in case of a encryption exception we delete the file right away
189
+            $this->logger->info(
190
+                "Can't move file" .  $path .
191
+                "to the trash bin, therefore it was deleted right away");
192
+
193
+            $result = $this->storage->unlink($path);
194
+        }
195
+
196
+        return $result;
197
+    }
198
+
199
+    /**
200
+     * Deletes the given folder by moving it into the trashbin.
201
+     *
202
+     * @param string $path path of folder to delete
203
+     *
204
+     * @return bool true if the operation succeeded, false otherwise
205
+     */
206
+    public function rmdir($path) {
207
+        if (isset(self::$moveOutOfSharedFolder[$this->mountPoint . $path])) {
208
+            $result = $this->doDelete($path, 'rmdir', true);
209
+            unset(self::$moveOutOfSharedFolder[$this->mountPoint . $path]);
210
+        } else {
211
+            $result = $this->doDelete($path, 'rmdir');
212
+        }
213
+
214
+        return $result;
215
+    }
216
+
217
+    /**
218
+     * check if it is a file located in data/user/files only files in the
219
+     * 'files' directory should be moved to the trash
220
+     *
221
+     * @param $path
222
+     * @return bool
223
+     */
224
+    protected function shouldMoveToTrash($path){
225
+
226
+        // check if there is a app which want to disable the trash bin for this file
227
+        $fileId = $this->storage->getCache()->getId($path);
228
+        $nodes = $this->rootFolder->getById($fileId);
229
+        foreach ($nodes as $node) {
230
+            $event = $this->createMoveToTrashEvent($node);
231
+            $this->eventDispatcher->dispatch('OCA\Files_Trashbin::moveToTrash', $event);
232
+            if ($event->shouldMoveToTrashBin() === false) {
233
+                return false;
234
+            }
235
+        }
236
+
237
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path);
238
+        $parts = explode('/', $normalized);
239
+        if (count($parts) < 4) {
240
+            return false;
241
+        }
242
+
243
+        if ($parts[2] === 'files' && $this->userManager->userExists($parts[1])) {
244
+            return true;
245
+        }
246
+
247
+        return false;
248
+    }
249
+
250
+    /**
251
+     * get move to trash event
252
+     *
253
+     * @param Node $node
254
+     * @return MoveToTrashEvent
255
+     */
256
+    protected function createMoveToTrashEvent(Node $node) {
257
+        return new MoveToTrashEvent($node);
258
+    }
259
+
260
+    /**
261
+     * Run the delete operation with the given method
262
+     *
263
+     * @param string $path path of file or folder to delete
264
+     * @param string $method either "unlink" or "rmdir"
265
+     * @param bool $ownerOnly delete for owner only (if file gets moved out of a shared folder)
266
+     *
267
+     * @return bool true if the operation succeeded, false otherwise
268
+     */
269
+    private function doDelete($path, $method, $ownerOnly = false) {
270
+        if (self::$disableTrash
271
+            || !\OC::$server->getAppManager()->isEnabledForUser('files_trashbin')
272
+            || (pathinfo($path, PATHINFO_EXTENSION) === 'part')
273
+            || $this->shouldMoveToTrash($path) === false
274
+        ) {
275
+            return call_user_func_array([$this->storage, $method], [$path]);
276
+        }
277
+
278
+        // check permissions before we continue, this is especially important for
279
+        // shared files
280
+        if (!$this->isDeletable($path)) {
281
+            return false;
282
+        }
283
+
284
+        $normalized = Filesystem::normalizePath($this->mountPoint . '/' . $path, true, false, true);
285
+        $result = true;
286
+        $view = Filesystem::getView();
287
+        if (!isset($this->deletedFiles[$normalized]) && $view instanceof View) {
288
+            $this->deletedFiles[$normalized] = $normalized;
289
+            if ($filesPath = $view->getRelativePath($normalized)) {
290
+                $filesPath = trim($filesPath, '/');
291
+                $result = \OCA\Files_Trashbin\Trashbin::move2trash($filesPath, $ownerOnly);
292
+                // in cross-storage cases the file will be copied
293
+                // but not deleted, so we delete it here
294
+                if ($result) {
295
+                    call_user_func_array([$this->storage, $method], [$path]);
296
+                }
297
+            } else {
298
+                $result = call_user_func_array([$this->storage, $method], [$path]);
299
+            }
300
+            unset($this->deletedFiles[$normalized]);
301
+        } else if ($this->storage->file_exists($path)) {
302
+            $result = call_user_func_array([$this->storage, $method], [$path]);
303
+        }
304
+
305
+        return $result;
306
+    }
307
+
308
+    /**
309
+     * Setup the storate wrapper callback
310
+     */
311
+    public static function setupStorage() {
312
+        \OC\Files\Filesystem::addStorageWrapper('oc_trashbin', function ($mountPoint, $storage) {
313
+            return new \OCA\Files_Trashbin\Storage(
314
+                array('storage' => $storage, 'mountPoint' => $mountPoint),
315
+                \OC::$server->getUserManager(),
316
+                \OC::$server->getLogger(),
317
+                \OC::$server->getEventDispatcher(),
318
+                \OC::$server->getLazyRootFolder()
319
+            );
320
+        }, 1);
321
+    }
322 322
 
323 323
 }
Please login to merge, or discard this patch.
apps/files_trashbin/ajax/delete.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -35,19 +35,19 @@  discard block
 block discarded – undo
35 35
 
36 36
 // "empty trash" command
37 37
 if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true'){
38
-	$deleteAll = true;
39
-	if ($folder === '/' || $folder === '') {
40
-		OCA\Files_Trashbin\Trashbin::deleteAll();
41
-		$list = array();
42
-	} else {
43
-		$list[] = $folder;
44
-		$folder = dirname($folder);
45
-	}
38
+    $deleteAll = true;
39
+    if ($folder === '/' || $folder === '') {
40
+        OCA\Files_Trashbin\Trashbin::deleteAll();
41
+        $list = array();
42
+    } else {
43
+        $list[] = $folder;
44
+        $folder = dirname($folder);
45
+    }
46 46
 }
47 47
 else {
48
-	$deleteAll = false;
49
-	$files = (string)$_POST['files'];
50
-	$list = json_decode($files);
48
+    $deleteAll = false;
49
+    $files = (string)$_POST['files'];
50
+    $list = json_decode($files);
51 51
 }
52 52
 
53 53
 $folder = rtrim($folder, '/') . '/';
@@ -56,38 +56,38 @@  discard block
 block discarded – undo
56 56
 
57 57
 $i = 0;
58 58
 foreach ($list as $file) {
59
-	if ($folder === '/') {
60
-		$file = ltrim($file, '/');
61
-		$delimiter = strrpos($file, '.d');
62
-		$filename = substr($file, 0, $delimiter);
63
-		$timestamp =  substr($file, $delimiter+2);
64
-	} else {
65
-		$filename = $folder . '/' . $file;
66
-		$timestamp = null;
67
-	}
59
+    if ($folder === '/') {
60
+        $file = ltrim($file, '/');
61
+        $delimiter = strrpos($file, '.d');
62
+        $filename = substr($file, 0, $delimiter);
63
+        $timestamp =  substr($file, $delimiter+2);
64
+    } else {
65
+        $filename = $folder . '/' . $file;
66
+        $timestamp = null;
67
+    }
68 68
 
69
-	OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
70
-	if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
71
-		$error[] = $filename;
72
-		\OCP\Util::writeLog('trashbin','can\'t delete ' . $filename . ' permanently.', ILogger::ERROR);
73
-	}
74
-	// only list deleted files if not deleting everything
75
-	else if (!$deleteAll) {
76
-		$success[$i]['filename'] = $file;
77
-		$success[$i]['timestamp'] = $timestamp;
78
-		$i++;
79
-	}
69
+    OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
70
+    if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
71
+        $error[] = $filename;
72
+        \OCP\Util::writeLog('trashbin','can\'t delete ' . $filename . ' permanently.', ILogger::ERROR);
73
+    }
74
+    // only list deleted files if not deleting everything
75
+    else if (!$deleteAll) {
76
+        $success[$i]['filename'] = $file;
77
+        $success[$i]['timestamp'] = $timestamp;
78
+        $i++;
79
+    }
80 80
 }
81 81
 
82 82
 if ( $error ) {
83
-	$filelist = '';
84
-	foreach ( $error as $e ) {
85
-		$filelist .= $e.', ';
86
-	}
87
-	$l = \OC::$server->getL10N('files_trashbin');
88
-	$message = $l->t("Couldn't delete %s permanently", array(rtrim($filelist, ', ')));
89
-	\OC_JSON::error(array("data" => array("message" => $message,
90
-			                               "success" => $success, "error" => $error)));
83
+    $filelist = '';
84
+    foreach ( $error as $e ) {
85
+        $filelist .= $e.', ';
86
+    }
87
+    $l = \OC::$server->getL10N('files_trashbin');
88
+    $message = $l->t("Couldn't delete %s permanently", array(rtrim($filelist, ', ')));
89
+    \OC_JSON::error(array("data" => array("message" => $message,
90
+                                            "success" => $success, "error" => $error)));
91 91
 } else {
92
-	\OC_JSON::success(array("data" => array("success" => $success)));
92
+    \OC_JSON::success(array("data" => array("success" => $success)));
93 93
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@  discard block
 block discarded – undo
34 34
 $folder = isset($_POST['dir']) ? $_POST['dir'] : '/';
35 35
 
36 36
 // "empty trash" command
37
-if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true'){
37
+if (isset($_POST['allfiles']) && (string) $_POST['allfiles'] === 'true') {
38 38
 	$deleteAll = true;
39 39
 	if ($folder === '/' || $folder === '') {
40 40
 		OCA\Files_Trashbin\Trashbin::deleteAll();
@@ -46,11 +46,11 @@  discard block
 block discarded – undo
46 46
 }
47 47
 else {
48 48
 	$deleteAll = false;
49
-	$files = (string)$_POST['files'];
49
+	$files = (string) $_POST['files'];
50 50
 	$list = json_decode($files);
51 51
 }
52 52
 
53
-$folder = rtrim($folder, '/') . '/';
53
+$folder = rtrim($folder, '/').'/';
54 54
 $error = array();
55 55
 $success = array();
56 56
 
@@ -60,16 +60,16 @@  discard block
 block discarded – undo
60 60
 		$file = ltrim($file, '/');
61 61
 		$delimiter = strrpos($file, '.d');
62 62
 		$filename = substr($file, 0, $delimiter);
63
-		$timestamp =  substr($file, $delimiter+2);
63
+		$timestamp = substr($file, $delimiter + 2);
64 64
 	} else {
65
-		$filename = $folder . '/' . $file;
65
+		$filename = $folder.'/'.$file;
66 66
 		$timestamp = null;
67 67
 	}
68 68
 
69 69
 	OCA\Files_Trashbin\Trashbin::delete($filename, \OCP\User::getUser(), $timestamp);
70 70
 	if (OCA\Files_Trashbin\Trashbin::file_exists($filename, $timestamp)) {
71 71
 		$error[] = $filename;
72
-		\OCP\Util::writeLog('trashbin','can\'t delete ' . $filename . ' permanently.', ILogger::ERROR);
72
+		\OCP\Util::writeLog('trashbin', 'can\'t delete '.$filename.' permanently.', ILogger::ERROR);
73 73
 	}
74 74
 	// only list deleted files if not deleting everything
75 75
 	else if (!$deleteAll) {
@@ -79,9 +79,9 @@  discard block
 block discarded – undo
79 79
 	}
80 80
 }
81 81
 
82
-if ( $error ) {
82
+if ($error) {
83 83
 	$filelist = '';
84
-	foreach ( $error as $e ) {
84
+	foreach ($error as $e) {
85 85
 		$filelist .= $e.', ';
86 86
 	}
87 87
 	$l = \OC::$server->getL10N('files_trashbin');
Please login to merge, or discard this patch.
apps/files_trashbin/ajax/undelete.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -35,25 +35,25 @@  discard block
 block discarded – undo
35 35
 
36 36
 $dir = '/';
37 37
 if (isset($_POST['dir'])) {
38
-	$dir = rtrim((string)$_POST['dir'], '/'). '/';
38
+    $dir = rtrim((string)$_POST['dir'], '/'). '/';
39 39
 }
40 40
 $allFiles = false;
41 41
 if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true') {
42
-	$allFiles = true;
43
-	$list = array();
44
-	$dirListing = true;
45
-	if ($dir === '' || $dir === '/') {
46
-		$dirListing = false;
47
-	}
48
-	foreach (OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser()) as $file) {
49
-		$fileName = $file['name'];
50
-		if (!$dirListing) {
51
-			$fileName .= '.d' . $file['mtime'];
52
-		}
53
-		$list[] = $fileName;
54
-	}
42
+    $allFiles = true;
43
+    $list = array();
44
+    $dirListing = true;
45
+    if ($dir === '' || $dir === '/') {
46
+        $dirListing = false;
47
+    }
48
+    foreach (OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser()) as $file) {
49
+        $fileName = $file['name'];
50
+        if (!$dirListing) {
51
+            $fileName .= '.d' . $file['mtime'];
52
+        }
53
+        $list[] = $fileName;
54
+    }
55 55
 } else {
56
-	$list = json_decode($_POST['files']);
56
+    $list = json_decode($_POST['files']);
57 57
 }
58 58
 
59 59
 $error = array();
@@ -61,38 +61,38 @@  discard block
 block discarded – undo
61 61
 
62 62
 $i = 0;
63 63
 foreach ($list as $file) {
64
-	$path = $dir . '/' . $file;
65
-	if ($dir === '/') {
66
-		$file = ltrim($file, '/');
67
-		$delimiter = strrpos($file, '.d');
68
-		$filename = substr($file, 0, $delimiter);
69
-		$timestamp =  substr($file, $delimiter+2);
70
-	} else {
71
-		$path_parts = pathinfo($file);
72
-		$filename = $path_parts['basename'];
73
-		$timestamp = null;
74
-	}
64
+    $path = $dir . '/' . $file;
65
+    if ($dir === '/') {
66
+        $file = ltrim($file, '/');
67
+        $delimiter = strrpos($file, '.d');
68
+        $filename = substr($file, 0, $delimiter);
69
+        $timestamp =  substr($file, $delimiter+2);
70
+    } else {
71
+        $path_parts = pathinfo($file);
72
+        $filename = $path_parts['basename'];
73
+        $timestamp = null;
74
+    }
75 75
 
76
-	if ( !OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp) ) {
77
-		$error[] = $filename;
78
-		\OCP\Util::writeLog('trashbin', 'can\'t restore ' . $filename, ILogger::ERROR);
79
-	} else {
80
-		$success[$i]['filename'] = $file;
81
-		$success[$i]['timestamp'] = $timestamp;
82
-		$i++;
83
-	}
76
+    if ( !OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp) ) {
77
+        $error[] = $filename;
78
+        \OCP\Util::writeLog('trashbin', 'can\'t restore ' . $filename, ILogger::ERROR);
79
+    } else {
80
+        $success[$i]['filename'] = $file;
81
+        $success[$i]['timestamp'] = $timestamp;
82
+        $i++;
83
+    }
84 84
 
85 85
 }
86 86
 
87 87
 if ( $error ) {
88
-	$filelist = '';
89
-	foreach ( $error as $e ) {
90
-		$filelist .= $e.', ';
91
-	}
92
-	$l = OC::$server->getL10N('files_trashbin');
93
-	$message = $l->t("Couldn't restore %s", array(rtrim($filelist, ', ')));
94
-	\OC_JSON::error(array("data" => array("message" => $message,
95
-										  "success" => $success, "error" => $error)));
88
+    $filelist = '';
89
+    foreach ( $error as $e ) {
90
+        $filelist .= $e.', ';
91
+    }
92
+    $l = OC::$server->getL10N('files_trashbin');
93
+    $message = $l->t("Couldn't restore %s", array(rtrim($filelist, ', ')));
94
+    \OC_JSON::error(array("data" => array("message" => $message,
95
+                                            "success" => $success, "error" => $error)));
96 96
 } else {
97
-	\OC_JSON::success(array("data" => array("success" => $success)));
97
+    \OC_JSON::success(array("data" => array("success" => $success)));
98 98
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -35,10 +35,10 @@  discard block
 block discarded – undo
35 35
 
36 36
 $dir = '/';
37 37
 if (isset($_POST['dir'])) {
38
-	$dir = rtrim((string)$_POST['dir'], '/'). '/';
38
+	$dir = rtrim((string) $_POST['dir'], '/').'/';
39 39
 }
40 40
 $allFiles = false;
41
-if (isset($_POST['allfiles']) && (string)$_POST['allfiles'] === 'true') {
41
+if (isset($_POST['allfiles']) && (string) $_POST['allfiles'] === 'true') {
42 42
 	$allFiles = true;
43 43
 	$list = array();
44 44
 	$dirListing = true;
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 	foreach (OCA\Files_Trashbin\Helper::getTrashFiles($dir, \OCP\User::getUser()) as $file) {
49 49
 		$fileName = $file['name'];
50 50
 		if (!$dirListing) {
51
-			$fileName .= '.d' . $file['mtime'];
51
+			$fileName .= '.d'.$file['mtime'];
52 52
 		}
53 53
 		$list[] = $fileName;
54 54
 	}
@@ -61,21 +61,21 @@  discard block
 block discarded – undo
61 61
 
62 62
 $i = 0;
63 63
 foreach ($list as $file) {
64
-	$path = $dir . '/' . $file;
64
+	$path = $dir.'/'.$file;
65 65
 	if ($dir === '/') {
66 66
 		$file = ltrim($file, '/');
67 67
 		$delimiter = strrpos($file, '.d');
68 68
 		$filename = substr($file, 0, $delimiter);
69
-		$timestamp =  substr($file, $delimiter+2);
69
+		$timestamp = substr($file, $delimiter + 2);
70 70
 	} else {
71 71
 		$path_parts = pathinfo($file);
72 72
 		$filename = $path_parts['basename'];
73 73
 		$timestamp = null;
74 74
 	}
75 75
 
76
-	if ( !OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp) ) {
76
+	if (!OCA\Files_Trashbin\Trashbin::restore($path, $filename, $timestamp)) {
77 77
 		$error[] = $filename;
78
-		\OCP\Util::writeLog('trashbin', 'can\'t restore ' . $filename, ILogger::ERROR);
78
+		\OCP\Util::writeLog('trashbin', 'can\'t restore '.$filename, ILogger::ERROR);
79 79
 	} else {
80 80
 		$success[$i]['filename'] = $file;
81 81
 		$success[$i]['timestamp'] = $timestamp;
@@ -84,9 +84,9 @@  discard block
 block discarded – undo
84 84
 
85 85
 }
86 86
 
87
-if ( $error ) {
87
+if ($error) {
88 88
 	$filelist = '';
89
-	foreach ( $error as $e ) {
89
+	foreach ($error as $e) {
90 90
 		$filelist .= $e.', ';
91 91
 	}
92 92
 	$l = OC::$server->getL10N('files_trashbin');
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 2 patches
Indentation   +841 added lines, -841 removed lines patch added patch discarded remove patch
@@ -52,845 +52,845 @@
 block discarded – undo
52 52
 
53 53
 class UsersController extends AUserData {
54 54
 
55
-	/** @var IAppManager */
56
-	private $appManager;
57
-	/** @var ILogger */
58
-	private $logger;
59
-	/** @var IFactory */
60
-	private $l10nFactory;
61
-	/** @var NewUserMailHelper */
62
-	private $newUserMailHelper;
63
-	/** @var FederatedFileSharingFactory */
64
-	private $federatedFileSharingFactory;
65
-	/** @var ISecureRandom */
66
-	private $secureRandom;
67
-
68
-	/**
69
-	 * @param string $appName
70
-	 * @param IRequest $request
71
-	 * @param IUserManager $userManager
72
-	 * @param IConfig $config
73
-	 * @param IAppManager $appManager
74
-	 * @param IGroupManager $groupManager
75
-	 * @param IUserSession $userSession
76
-	 * @param AccountManager $accountManager
77
-	 * @param ILogger $logger
78
-	 * @param IFactory $l10nFactory
79
-	 * @param NewUserMailHelper $newUserMailHelper
80
-	 * @param FederatedFileSharingFactory $federatedFileSharingFactory
81
-	 * @param ISecureRandom $secureRandom
82
-	 */
83
-	public function __construct(string $appName,
84
-								IRequest $request,
85
-								IUserManager $userManager,
86
-								IConfig $config,
87
-								IAppManager $appManager,
88
-								IGroupManager $groupManager,
89
-								IUserSession $userSession,
90
-								AccountManager $accountManager,
91
-								ILogger $logger,
92
-								IFactory $l10nFactory,
93
-								NewUserMailHelper $newUserMailHelper,
94
-								FederatedFileSharingFactory $federatedFileSharingFactory,
95
-								ISecureRandom $secureRandom) {
96
-		parent::__construct($appName,
97
-							$request,
98
-							$userManager,
99
-							$config,
100
-							$groupManager,
101
-							$userSession,
102
-							$accountManager);
103
-
104
-		$this->appManager = $appManager;
105
-		$this->logger = $logger;
106
-		$this->l10nFactory = $l10nFactory;
107
-		$this->newUserMailHelper = $newUserMailHelper;
108
-		$this->federatedFileSharingFactory = $federatedFileSharingFactory;
109
-		$this->secureRandom = $secureRandom;
110
-	}
111
-
112
-	/**
113
-	 * @NoAdminRequired
114
-	 *
115
-	 * returns a list of users
116
-	 *
117
-	 * @param string $search
118
-	 * @param int $limit
119
-	 * @param int $offset
120
-	 * @return DataResponse
121
-	 */
122
-	public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
123
-		$user = $this->userSession->getUser();
124
-		$users = [];
125
-
126
-		// Admin? Or SubAdmin?
127
-		$uid = $user->getUID();
128
-		$subAdminManager = $this->groupManager->getSubAdmin();
129
-		if ($this->groupManager->isAdmin($uid)){
130
-			$users = $this->userManager->search($search, $limit, $offset);
131
-		} else if ($subAdminManager->isSubAdmin($user)) {
132
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
133
-			foreach ($subAdminOfGroups as $key => $group) {
134
-				$subAdminOfGroups[$key] = $group->getGID();
135
-			}
136
-
137
-			$users = [];
138
-			foreach ($subAdminOfGroups as $group) {
139
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
140
-			}
141
-		}
142
-
143
-		$users = array_keys($users);
144
-
145
-		return new DataResponse([
146
-			'users' => $users
147
-		]);
148
-	}
149
-
150
-	/**
151
-	 * @NoAdminRequired
152
-	 *
153
-	 * returns a list of users and their data
154
-	 */
155
-	public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
156
-		$user = $this->userSession->getUser();
157
-		$users = [];
158
-
159
-		// Admin? Or SubAdmin?
160
-		$uid = $user->getUID();
161
-		$subAdminManager = $this->groupManager->getSubAdmin();
162
-		if ($this->groupManager->isAdmin($uid)){
163
-			$users = $this->userManager->search($search, $limit, $offset);
164
-		} else if ($subAdminManager->isSubAdmin($user)) {
165
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
166
-			foreach ($subAdminOfGroups as $key => $group) {
167
-				$subAdminOfGroups[$key] = $group->getGID();
168
-			}
169
-
170
-			$users = [];
171
-			foreach ($subAdminOfGroups as $group) {
172
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
173
-			}
174
-		}
175
-
176
-		$users = array_keys($users);
177
-		$usersDetails = [];
178
-		foreach ($users as $key => $userId) {
179
-			$userData = $this->getUserData($userId);
180
-			// Do not insert empty entry
181
-			if (!empty($userData)) {
182
-				$usersDetails[$userId] = $userData;
183
-			}
184
-		}
185
-
186
-		return new DataResponse([
187
-			'users' => $usersDetails
188
-		]);
189
-	}
190
-
191
-	/**
192
-	 * @PasswordConfirmationRequired
193
-	 * @NoAdminRequired
194
-	 *
195
-	 * @param string $userid
196
-	 * @param string $password
197
-	 * @param string $email
198
-	 * @param array $groups
199
-	 * @param array $subadmins
200
-	 * @param string $quota
201
-	 * @param string $language
202
-	 * @return DataResponse
203
-	 * @throws OCSException
204
-	 */
205
-	public function addUser(string $userid,
206
-							string $password = '',
207
-							string $email = '',
208
-							array $groups = [],
209
-							array $subadmin = [],
210
-							string $quota = '',
211
-							string $language = ''): DataResponse {
212
-		$user = $this->userSession->getUser();
213
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
214
-		$subAdminManager = $this->groupManager->getSubAdmin();
215
-
216
-		if ($this->userManager->userExists($userid)) {
217
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
218
-			throw new OCSException('User already exists', 102);
219
-		}
220
-
221
-		if ($groups !== []) {
222
-			foreach ($groups as $group) {
223
-				if (!$this->groupManager->groupExists($group)) {
224
-					throw new OCSException('group '.$group.' does not exist', 104);
225
-				}
226
-				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
227
-					throw new OCSException('insufficient privileges for group '. $group, 105);
228
-				}
229
-			}
230
-		} else {
231
-			if (!$isAdmin) {
232
-				throw new OCSException('no group specified (required for subadmins)', 106);
233
-			}
234
-		}
235
-
236
-		$subadminGroups = [];
237
-		if ($subadmin !== []) {
238
-			foreach ($subadmin as $groupid) {
239
-				$group = $this->groupManager->get($groupid);
240
-				// Check if group exists
241
-				if ($group === null) {
242
-					throw new OCSException('Subadmin group does not exist',  102);
243
-				}
244
-				// Check if trying to make subadmin of admin group
245
-				if ($group->getGID() === 'admin') {
246
-					throw new OCSException('Cannot create subadmins for admin group', 103);
247
-				}
248
-				// Check if has permission to promote subadmins
249
-				if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
250
-					throw new OCSForbiddenException('No permissions to promote subadmins');
251
-				}
252
-				$subadminGroups[] = $group;
253
-			}
254
-		}
255
-
256
-		$generatePasswordResetToken = false;
257
-		if ($password === '') {
258
-			if ($email === '') {
259
-				throw new OCSException('To send a password link to the user an email address is required.', 108);
260
-			}
261
-
262
-			$password = $this->secureRandom->generate(10);
263
-			// Make sure we pass the password_policy
264
-			$password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
265
-			$generatePasswordResetToken = true;
266
-		}
267
-
268
-		try {
269
-			$newUser = $this->userManager->createUser($userid, $password);
270
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
271
-
272
-			foreach ($groups as $group) {
273
-				$this->groupManager->get($group)->addUser($newUser);
274
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
275
-			}
276
-			foreach ($subadminGroups as $group) {
277
-				$subAdminManager->createSubAdmin($newUser, $group);
278
-			}
279
-
280
-			if ($quota !== '') {
281
-				$this->editUser($userid, 'quota', $quota);
282
-			}
283
-
284
-			if ($language !== '') {
285
-				$this->editUser($userid, 'language', $language);
286
-			}
287
-
288
-			// Send new user mail only if a mail is set
289
-			if ($email !== '') {
290
-				$newUser->setEMailAddress($email);
291
-				try {
292
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
293
-					$this->newUserMailHelper->sendMail($newUser, $emailTemplate);
294
-				} catch (\Exception $e) {
295
-					$this->logger->logException($e, [
296
-						'message' => "Can't send new user mail to $email",
297
-						'level' => ILogger::ERROR,
298
-						'app' => 'ocs_api',
299
-					]);
300
-					throw new OCSException('Unable to send the invitation mail', 109);
301
-				}
302
-			}
303
-
304
-			return new DataResponse();
305
-
306
-		} catch (HintException $e ) {
307
-			$this->logger->logException($e, [
308
-				'message' => 'Failed addUser attempt with hint exception.',
309
-				'level' => ILogger::WARN,
310
-				'app' => 'ocs_api',
311
-			]);
312
-			throw new OCSException($e->getHint(), 107);
313
-		} catch (\Exception $e) {
314
-			$this->logger->logException($e, [
315
-				'message' => 'Failed addUser attempt with exception.',
316
-				'level' => ILogger::ERROR,
317
-				'app' => 'ocs_api',
318
-			]);
319
-			throw new OCSException('Bad request', 101);
320
-		}
321
-	}
322
-
323
-	/**
324
-	 * @NoAdminRequired
325
-	 * @NoSubAdminRequired
326
-	 *
327
-	 * gets user info
328
-	 *
329
-	 * @param string $userId
330
-	 * @return DataResponse
331
-	 * @throws OCSException
332
-	 */
333
-	public function getUser(string $userId): DataResponse {
334
-		$data = $this->getUserData($userId);
335
-		// getUserData returns empty array if not enough permissions
336
-		if (empty($data)) {
337
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
338
-		}
339
-		return new DataResponse($data);
340
-	}
341
-
342
-	/**
343
-	 * @NoAdminRequired
344
-	 * @NoSubAdminRequired
345
-	 *
346
-	 * gets user info from the currently logged in user
347
-	 *
348
-	 * @return DataResponse
349
-	 * @throws OCSException
350
-	 */
351
-	public function getCurrentUser(): DataResponse {
352
-		$user = $this->userSession->getUser();
353
-		if ($user) {
354
-			$data =  $this->getUserData($user->getUID());
355
-			// rename "displayname" to "display-name" only for this call to keep
356
-			// the API stable.
357
-			$data['display-name'] = $data['displayname'];
358
-			unset($data['displayname']);
359
-			return new DataResponse($data);
360
-
361
-		}
362
-
363
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
364
-	}
365
-
366
-	/**
367
-	 * @NoAdminRequired
368
-	 * @NoSubAdminRequired
369
-	 */
370
-	public function getEditableFields(): DataResponse {
371
-		$permittedFields = [];
372
-
373
-		// Editing self (display, email)
374
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
375
-			$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
376
-			$permittedFields[] = AccountManager::PROPERTY_EMAIL;
377
-		}
378
-
379
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
380
-			$federatedFileSharing = $this->federatedFileSharingFactory->get();
381
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
382
-			if ($shareProvider->isLookupServerUploadEnabled()) {
383
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
384
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
385
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
386
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
387
-			}
388
-		}
389
-
390
-		return new DataResponse($permittedFields);
391
-	}
392
-
393
-	/**
394
-	 * @NoAdminRequired
395
-	 * @NoSubAdminRequired
396
-	 * @PasswordConfirmationRequired
397
-	 *
398
-	 * edit users
399
-	 *
400
-	 * @param string $userId
401
-	 * @param string $key
402
-	 * @param string $value
403
-	 * @return DataResponse
404
-	 * @throws OCSException
405
-	 */
406
-	public function editUser(string $userId, string $key, string $value): DataResponse {
407
-		$currentLoggedInUser = $this->userSession->getUser();
408
-
409
-		$targetUser = $this->userManager->get($userId);
410
-		if ($targetUser === null) {
411
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
412
-		}
413
-
414
-		$permittedFields = [];
415
-		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
416
-			// Editing self (display, email)
417
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
418
-				$permittedFields[] = 'display';
419
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
420
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
421
-			}
422
-
423
-			$permittedFields[] = 'password';
424
-			if ($this->config->getSystemValue('force_language', false) === false ||
425
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
426
-				$permittedFields[] = 'language';
427
-			}
428
-
429
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
430
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
431
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
432
-				if ($shareProvider->isLookupServerUploadEnabled()) {
433
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
434
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
435
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
436
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
437
-				}
438
-			}
439
-
440
-			// If admin they can edit their own quota
441
-			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
442
-				$permittedFields[] = 'quota';
443
-			}
444
-		} else {
445
-			// Check if admin / subadmin
446
-			$subAdminManager = $this->groupManager->getSubAdmin();
447
-			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
448
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
449
-				// They have permissions over the user
450
-				$permittedFields[] = 'display';
451
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
452
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
453
-				$permittedFields[] = 'password';
454
-				$permittedFields[] = 'language';
455
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
456
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
457
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
458
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
459
-				$permittedFields[] = 'quota';
460
-			} else {
461
-				// No rights
462
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
463
-			}
464
-		}
465
-		// Check if permitted to edit this field
466
-		if (!in_array($key, $permittedFields)) {
467
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
468
-		}
469
-		// Process the edit
470
-		switch($key) {
471
-			case 'display':
472
-			case AccountManager::PROPERTY_DISPLAYNAME:
473
-				$targetUser->setDisplayName($value);
474
-				break;
475
-			case 'quota':
476
-				$quota = $value;
477
-				if ($quota !== 'none' && $quota !== 'default') {
478
-					if (is_numeric($quota)) {
479
-						$quota = (float) $quota;
480
-					} else {
481
-						$quota = \OCP\Util::computerFileSize($quota);
482
-					}
483
-					if ($quota === false) {
484
-						throw new OCSException('Invalid quota value '.$value, 103);
485
-					}
486
-					if ($quota === 0) {
487
-						$quota = 'default';
488
-					}else if ($quota === -1) {
489
-						$quota = 'none';
490
-					} else {
491
-						$quota = \OCP\Util::humanFileSize($quota);
492
-					}
493
-				}
494
-				$targetUser->setQuota($quota);
495
-				break;
496
-			case 'password':
497
-				$targetUser->setPassword($value);
498
-				break;
499
-			case 'language':
500
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
501
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
502
-					throw new OCSException('Invalid language', 102);
503
-				}
504
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
505
-				break;
506
-			case AccountManager::PROPERTY_EMAIL:
507
-				if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
508
-					$targetUser->setEMailAddress($value);
509
-				} else {
510
-					throw new OCSException('', 102);
511
-				}
512
-				break;
513
-			case AccountManager::PROPERTY_PHONE:
514
-			case AccountManager::PROPERTY_ADDRESS:
515
-			case AccountManager::PROPERTY_WEBSITE:
516
-			case AccountManager::PROPERTY_TWITTER:
517
-				$userAccount = $this->accountManager->getUser($targetUser);
518
-				if ($userAccount[$key]['value'] !== $value) {
519
-					$userAccount[$key]['value'] = $value;
520
-					$this->accountManager->updateUser($targetUser, $userAccount);
521
-				}
522
-				break;
523
-			default:
524
-				throw new OCSException('', 103);
525
-		}
526
-		return new DataResponse();
527
-	}
528
-
529
-	/**
530
-	 * @PasswordConfirmationRequired
531
-	 * @NoAdminRequired
532
-	 *
533
-	 * @param string $userId
534
-	 * @return DataResponse
535
-	 * @throws OCSException
536
-	 */
537
-	public function deleteUser(string $userId): DataResponse {
538
-		$currentLoggedInUser = $this->userSession->getUser();
539
-
540
-		$targetUser = $this->userManager->get($userId);
541
-
542
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
543
-			throw new OCSException('', 101);
544
-		}
545
-
546
-		// If not permitted
547
-		$subAdminManager = $this->groupManager->getSubAdmin();
548
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
549
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
550
-		}
551
-
552
-		// Go ahead with the delete
553
-		if ($targetUser->delete()) {
554
-			return new DataResponse();
555
-		} else {
556
-			throw new OCSException('', 101);
557
-		}
558
-	}
559
-
560
-	/**
561
-	 * @PasswordConfirmationRequired
562
-	 * @NoAdminRequired
563
-	 *
564
-	 * @param string $userId
565
-	 * @return DataResponse
566
-	 * @throws OCSException
567
-	 * @throws OCSForbiddenException
568
-	 */
569
-	public function disableUser(string $userId): DataResponse {
570
-		return $this->setEnabled($userId, false);
571
-	}
572
-
573
-	/**
574
-	 * @PasswordConfirmationRequired
575
-	 * @NoAdminRequired
576
-	 *
577
-	 * @param string $userId
578
-	 * @return DataResponse
579
-	 * @throws OCSException
580
-	 * @throws OCSForbiddenException
581
-	 */
582
-	public function enableUser(string $userId): DataResponse {
583
-		return $this->setEnabled($userId, true);
584
-	}
585
-
586
-	/**
587
-	 * @param string $userId
588
-	 * @param bool $value
589
-	 * @return DataResponse
590
-	 * @throws OCSException
591
-	 */
592
-	private function setEnabled(string $userId, bool $value): DataResponse {
593
-		$currentLoggedInUser = $this->userSession->getUser();
594
-
595
-		$targetUser = $this->userManager->get($userId);
596
-		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
597
-			throw new OCSException('', 101);
598
-		}
599
-
600
-		// If not permitted
601
-		$subAdminManager = $this->groupManager->getSubAdmin();
602
-		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
603
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
604
-		}
605
-
606
-		// enable/disable the user now
607
-		$targetUser->setEnabled($value);
608
-		return new DataResponse();
609
-	}
610
-
611
-	/**
612
-	 * @NoAdminRequired
613
-	 * @NoSubAdminRequired
614
-	 *
615
-	 * @param string $userId
616
-	 * @return DataResponse
617
-	 * @throws OCSException
618
-	 */
619
-	public function getUsersGroups(string $userId): DataResponse {
620
-		$loggedInUser = $this->userSession->getUser();
621
-
622
-		$targetUser = $this->userManager->get($userId);
623
-		if ($targetUser === null) {
624
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
625
-		}
626
-
627
-		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
628
-			// Self lookup or admin lookup
629
-			return new DataResponse([
630
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
631
-			]);
632
-		} else {
633
-			$subAdminManager = $this->groupManager->getSubAdmin();
634
-
635
-			// Looking up someone else
636
-			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
637
-				// Return the group that the method caller is subadmin of for the user in question
638
-				/** @var IGroup[] $getSubAdminsGroups */
639
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
640
-				foreach ($getSubAdminsGroups as $key => $group) {
641
-					$getSubAdminsGroups[$key] = $group->getGID();
642
-				}
643
-				$groups = array_intersect(
644
-					$getSubAdminsGroups,
645
-					$this->groupManager->getUserGroupIds($targetUser)
646
-				);
647
-				return new DataResponse(['groups' => $groups]);
648
-			} else {
649
-				// Not permitted
650
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
651
-			}
652
-		}
653
-
654
-	}
655
-
656
-	/**
657
-	 * @PasswordConfirmationRequired
658
-	 * @NoAdminRequired
659
-	 *
660
-	 * @param string $userId
661
-	 * @param string $groupid
662
-	 * @return DataResponse
663
-	 * @throws OCSException
664
-	 */
665
-	public function addToGroup(string $userId, string $groupid = ''): DataResponse {
666
-		if ($groupid === '') {
667
-			throw new OCSException('', 101);
668
-		}
669
-
670
-		$group = $this->groupManager->get($groupid);
671
-		$targetUser = $this->userManager->get($userId);
672
-		if ($group === null) {
673
-			throw new OCSException('', 102);
674
-		}
675
-		if ($targetUser === null) {
676
-			throw new OCSException('', 103);
677
-		}
678
-
679
-		// If they're not an admin, check they are a subadmin of the group in question
680
-		$loggedInUser = $this->userSession->getUser();
681
-		$subAdminManager = $this->groupManager->getSubAdmin();
682
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
683
-			throw new OCSException('', 104);
684
-		}
685
-
686
-		// Add user to group
687
-		$group->addUser($targetUser);
688
-		return new DataResponse();
689
-	}
690
-
691
-	/**
692
-	 * @PasswordConfirmationRequired
693
-	 * @NoAdminRequired
694
-	 *
695
-	 * @param string $userId
696
-	 * @param string $groupid
697
-	 * @return DataResponse
698
-	 * @throws OCSException
699
-	 */
700
-	public function removeFromGroup(string $userId, string $groupid): DataResponse {
701
-		$loggedInUser = $this->userSession->getUser();
702
-
703
-		if ($groupid === null || trim($groupid) === '') {
704
-			throw new OCSException('', 101);
705
-		}
706
-
707
-		$group = $this->groupManager->get($groupid);
708
-		if ($group === null) {
709
-			throw new OCSException('', 102);
710
-		}
711
-
712
-		$targetUser = $this->userManager->get($userId);
713
-		if ($targetUser === null) {
714
-			throw new OCSException('', 103);
715
-		}
716
-
717
-		// If they're not an admin, check they are a subadmin of the group in question
718
-		$subAdminManager = $this->groupManager->getSubAdmin();
719
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
720
-			throw new OCSException('', 104);
721
-		}
722
-
723
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
724
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
725
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
726
-				if ($group->getGID() === 'admin') {
727
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
728
-				}
729
-			} else {
730
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
731
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
732
-			}
733
-
734
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
735
-			/** @var IGroup[] $subAdminGroups */
736
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
737
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
738
-				return $subAdminGroup->getGID();
739
-			}, $subAdminGroups);
740
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
741
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
742
-
743
-			if (count($userSubAdminGroups) <= 1) {
744
-				// Subadmin must not be able to remove a user from all their subadmin groups.
745
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
746
-			}
747
-		}
748
-
749
-		// Remove user from group
750
-		$group->removeUser($targetUser);
751
-		return new DataResponse();
752
-	}
753
-
754
-	/**
755
-	 * Creates a subadmin
756
-	 *
757
-	 * @PasswordConfirmationRequired
758
-	 *
759
-	 * @param string $userId
760
-	 * @param string $groupid
761
-	 * @return DataResponse
762
-	 * @throws OCSException
763
-	 */
764
-	public function addSubAdmin(string $userId, string $groupid): DataResponse {
765
-		$group = $this->groupManager->get($groupid);
766
-		$user = $this->userManager->get($userId);
767
-
768
-		// Check if the user exists
769
-		if ($user === null) {
770
-			throw new OCSException('User does not exist', 101);
771
-		}
772
-		// Check if group exists
773
-		if ($group === null) {
774
-			throw new OCSException('Group does not exist',  102);
775
-		}
776
-		// Check if trying to make subadmin of admin group
777
-		if ($group->getGID() === 'admin') {
778
-			throw new OCSException('Cannot create subadmins for admin group', 103);
779
-		}
780
-
781
-		$subAdminManager = $this->groupManager->getSubAdmin();
782
-
783
-		// We cannot be subadmin twice
784
-		if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
785
-			return new DataResponse();
786
-		}
787
-		// Go
788
-		if ($subAdminManager->createSubAdmin($user, $group)) {
789
-			return new DataResponse();
790
-		} else {
791
-			throw new OCSException('Unknown error occurred', 103);
792
-		}
793
-	}
794
-
795
-	/**
796
-	 * Removes a subadmin from a group
797
-	 *
798
-	 * @PasswordConfirmationRequired
799
-	 *
800
-	 * @param string $userId
801
-	 * @param string $groupid
802
-	 * @return DataResponse
803
-	 * @throws OCSException
804
-	 */
805
-	public function removeSubAdmin(string $userId, string $groupid): DataResponse {
806
-		$group = $this->groupManager->get($groupid);
807
-		$user = $this->userManager->get($userId);
808
-		$subAdminManager = $this->groupManager->getSubAdmin();
809
-
810
-		// Check if the user exists
811
-		if ($user === null) {
812
-			throw new OCSException('User does not exist', 101);
813
-		}
814
-		// Check if the group exists
815
-		if ($group === null) {
816
-			throw new OCSException('Group does not exist', 101);
817
-		}
818
-		// Check if they are a subadmin of this said group
819
-		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
820
-			throw new OCSException('User is not a subadmin of this group', 102);
821
-		}
822
-
823
-		// Go
824
-		if ($subAdminManager->deleteSubAdmin($user, $group)) {
825
-			return new DataResponse();
826
-		} else {
827
-			throw new OCSException('Unknown error occurred', 103);
828
-		}
829
-	}
830
-
831
-	/**
832
-	 * Get the groups a user is a subadmin of
833
-	 *
834
-	 * @param string $userId
835
-	 * @return DataResponse
836
-	 * @throws OCSException
837
-	 */
838
-	public function getUserSubAdminGroups(string $userId): DataResponse {
839
-		$groups = $this->getUserSubAdminGroupsData($userId);
840
-		return new DataResponse($groups);
841
-	}
842
-
843
-	/**
844
-	 * @NoAdminRequired
845
-	 * @PasswordConfirmationRequired
846
-	 *
847
-	 * resend welcome message
848
-	 *
849
-	 * @param string $userId
850
-	 * @return DataResponse
851
-	 * @throws OCSException
852
-	 */
853
-	public function resendWelcomeMessage(string $userId): DataResponse {
854
-		$currentLoggedInUser = $this->userSession->getUser();
855
-
856
-		$targetUser = $this->userManager->get($userId);
857
-		if ($targetUser === null) {
858
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
859
-		}
860
-
861
-		// Check if admin / subadmin
862
-		$subAdminManager = $this->groupManager->getSubAdmin();
863
-		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
864
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
865
-			// No rights
866
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
867
-		}
868
-
869
-		$email = $targetUser->getEMailAddress();
870
-		if ($email === '' || $email === null) {
871
-			throw new OCSException('Email address not available', 101);
872
-		}
873
-		$username = $targetUser->getUID();
874
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
875
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
876
-			$lang = 'en';
877
-		}
878
-
879
-		$l10n = $this->l10nFactory->get('settings', $lang);
880
-
881
-		try {
882
-			$this->newUserMailHelper->setL10N($l10n);
883
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
884
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
885
-		} catch(\Exception $e) {
886
-			$this->logger->logException($e, [
887
-				'message' => "Can't send new user mail to $email",
888
-				'level' => ILogger::ERROR,
889
-				'app' => 'settings',
890
-			]);
891
-			throw new OCSException('Sending email failed', 102);
892
-		}
893
-
894
-		return new DataResponse();
895
-	}
55
+    /** @var IAppManager */
56
+    private $appManager;
57
+    /** @var ILogger */
58
+    private $logger;
59
+    /** @var IFactory */
60
+    private $l10nFactory;
61
+    /** @var NewUserMailHelper */
62
+    private $newUserMailHelper;
63
+    /** @var FederatedFileSharingFactory */
64
+    private $federatedFileSharingFactory;
65
+    /** @var ISecureRandom */
66
+    private $secureRandom;
67
+
68
+    /**
69
+     * @param string $appName
70
+     * @param IRequest $request
71
+     * @param IUserManager $userManager
72
+     * @param IConfig $config
73
+     * @param IAppManager $appManager
74
+     * @param IGroupManager $groupManager
75
+     * @param IUserSession $userSession
76
+     * @param AccountManager $accountManager
77
+     * @param ILogger $logger
78
+     * @param IFactory $l10nFactory
79
+     * @param NewUserMailHelper $newUserMailHelper
80
+     * @param FederatedFileSharingFactory $federatedFileSharingFactory
81
+     * @param ISecureRandom $secureRandom
82
+     */
83
+    public function __construct(string $appName,
84
+                                IRequest $request,
85
+                                IUserManager $userManager,
86
+                                IConfig $config,
87
+                                IAppManager $appManager,
88
+                                IGroupManager $groupManager,
89
+                                IUserSession $userSession,
90
+                                AccountManager $accountManager,
91
+                                ILogger $logger,
92
+                                IFactory $l10nFactory,
93
+                                NewUserMailHelper $newUserMailHelper,
94
+                                FederatedFileSharingFactory $federatedFileSharingFactory,
95
+                                ISecureRandom $secureRandom) {
96
+        parent::__construct($appName,
97
+                            $request,
98
+                            $userManager,
99
+                            $config,
100
+                            $groupManager,
101
+                            $userSession,
102
+                            $accountManager);
103
+
104
+        $this->appManager = $appManager;
105
+        $this->logger = $logger;
106
+        $this->l10nFactory = $l10nFactory;
107
+        $this->newUserMailHelper = $newUserMailHelper;
108
+        $this->federatedFileSharingFactory = $federatedFileSharingFactory;
109
+        $this->secureRandom = $secureRandom;
110
+    }
111
+
112
+    /**
113
+     * @NoAdminRequired
114
+     *
115
+     * returns a list of users
116
+     *
117
+     * @param string $search
118
+     * @param int $limit
119
+     * @param int $offset
120
+     * @return DataResponse
121
+     */
122
+    public function getUsers(string $search = '', $limit = null, $offset = 0): DataResponse {
123
+        $user = $this->userSession->getUser();
124
+        $users = [];
125
+
126
+        // Admin? Or SubAdmin?
127
+        $uid = $user->getUID();
128
+        $subAdminManager = $this->groupManager->getSubAdmin();
129
+        if ($this->groupManager->isAdmin($uid)){
130
+            $users = $this->userManager->search($search, $limit, $offset);
131
+        } else if ($subAdminManager->isSubAdmin($user)) {
132
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
133
+            foreach ($subAdminOfGroups as $key => $group) {
134
+                $subAdminOfGroups[$key] = $group->getGID();
135
+            }
136
+
137
+            $users = [];
138
+            foreach ($subAdminOfGroups as $group) {
139
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
140
+            }
141
+        }
142
+
143
+        $users = array_keys($users);
144
+
145
+        return new DataResponse([
146
+            'users' => $users
147
+        ]);
148
+    }
149
+
150
+    /**
151
+     * @NoAdminRequired
152
+     *
153
+     * returns a list of users and their data
154
+     */
155
+    public function getUsersDetails(string $search = '', $limit = null, $offset = 0): DataResponse {
156
+        $user = $this->userSession->getUser();
157
+        $users = [];
158
+
159
+        // Admin? Or SubAdmin?
160
+        $uid = $user->getUID();
161
+        $subAdminManager = $this->groupManager->getSubAdmin();
162
+        if ($this->groupManager->isAdmin($uid)){
163
+            $users = $this->userManager->search($search, $limit, $offset);
164
+        } else if ($subAdminManager->isSubAdmin($user)) {
165
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
166
+            foreach ($subAdminOfGroups as $key => $group) {
167
+                $subAdminOfGroups[$key] = $group->getGID();
168
+            }
169
+
170
+            $users = [];
171
+            foreach ($subAdminOfGroups as $group) {
172
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search, $limit, $offset));
173
+            }
174
+        }
175
+
176
+        $users = array_keys($users);
177
+        $usersDetails = [];
178
+        foreach ($users as $key => $userId) {
179
+            $userData = $this->getUserData($userId);
180
+            // Do not insert empty entry
181
+            if (!empty($userData)) {
182
+                $usersDetails[$userId] = $userData;
183
+            }
184
+        }
185
+
186
+        return new DataResponse([
187
+            'users' => $usersDetails
188
+        ]);
189
+    }
190
+
191
+    /**
192
+     * @PasswordConfirmationRequired
193
+     * @NoAdminRequired
194
+     *
195
+     * @param string $userid
196
+     * @param string $password
197
+     * @param string $email
198
+     * @param array $groups
199
+     * @param array $subadmins
200
+     * @param string $quota
201
+     * @param string $language
202
+     * @return DataResponse
203
+     * @throws OCSException
204
+     */
205
+    public function addUser(string $userid,
206
+                            string $password = '',
207
+                            string $email = '',
208
+                            array $groups = [],
209
+                            array $subadmin = [],
210
+                            string $quota = '',
211
+                            string $language = ''): DataResponse {
212
+        $user = $this->userSession->getUser();
213
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
214
+        $subAdminManager = $this->groupManager->getSubAdmin();
215
+
216
+        if ($this->userManager->userExists($userid)) {
217
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
218
+            throw new OCSException('User already exists', 102);
219
+        }
220
+
221
+        if ($groups !== []) {
222
+            foreach ($groups as $group) {
223
+                if (!$this->groupManager->groupExists($group)) {
224
+                    throw new OCSException('group '.$group.' does not exist', 104);
225
+                }
226
+                if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
227
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
228
+                }
229
+            }
230
+        } else {
231
+            if (!$isAdmin) {
232
+                throw new OCSException('no group specified (required for subadmins)', 106);
233
+            }
234
+        }
235
+
236
+        $subadminGroups = [];
237
+        if ($subadmin !== []) {
238
+            foreach ($subadmin as $groupid) {
239
+                $group = $this->groupManager->get($groupid);
240
+                // Check if group exists
241
+                if ($group === null) {
242
+                    throw new OCSException('Subadmin group does not exist',  102);
243
+                }
244
+                // Check if trying to make subadmin of admin group
245
+                if ($group->getGID() === 'admin') {
246
+                    throw new OCSException('Cannot create subadmins for admin group', 103);
247
+                }
248
+                // Check if has permission to promote subadmins
249
+                if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) {
250
+                    throw new OCSForbiddenException('No permissions to promote subadmins');
251
+                }
252
+                $subadminGroups[] = $group;
253
+            }
254
+        }
255
+
256
+        $generatePasswordResetToken = false;
257
+        if ($password === '') {
258
+            if ($email === '') {
259
+                throw new OCSException('To send a password link to the user an email address is required.', 108);
260
+            }
261
+
262
+            $password = $this->secureRandom->generate(10);
263
+            // Make sure we pass the password_policy
264
+            $password .= $this->secureRandom->generate(2, '$!.,;:-~+*[]{}()');
265
+            $generatePasswordResetToken = true;
266
+        }
267
+
268
+        try {
269
+            $newUser = $this->userManager->createUser($userid, $password);
270
+            $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
271
+
272
+            foreach ($groups as $group) {
273
+                $this->groupManager->get($group)->addUser($newUser);
274
+                $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
275
+            }
276
+            foreach ($subadminGroups as $group) {
277
+                $subAdminManager->createSubAdmin($newUser, $group);
278
+            }
279
+
280
+            if ($quota !== '') {
281
+                $this->editUser($userid, 'quota', $quota);
282
+            }
283
+
284
+            if ($language !== '') {
285
+                $this->editUser($userid, 'language', $language);
286
+            }
287
+
288
+            // Send new user mail only if a mail is set
289
+            if ($email !== '') {
290
+                $newUser->setEMailAddress($email);
291
+                try {
292
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken);
293
+                    $this->newUserMailHelper->sendMail($newUser, $emailTemplate);
294
+                } catch (\Exception $e) {
295
+                    $this->logger->logException($e, [
296
+                        'message' => "Can't send new user mail to $email",
297
+                        'level' => ILogger::ERROR,
298
+                        'app' => 'ocs_api',
299
+                    ]);
300
+                    throw new OCSException('Unable to send the invitation mail', 109);
301
+                }
302
+            }
303
+
304
+            return new DataResponse();
305
+
306
+        } catch (HintException $e ) {
307
+            $this->logger->logException($e, [
308
+                'message' => 'Failed addUser attempt with hint exception.',
309
+                'level' => ILogger::WARN,
310
+                'app' => 'ocs_api',
311
+            ]);
312
+            throw new OCSException($e->getHint(), 107);
313
+        } catch (\Exception $e) {
314
+            $this->logger->logException($e, [
315
+                'message' => 'Failed addUser attempt with exception.',
316
+                'level' => ILogger::ERROR,
317
+                'app' => 'ocs_api',
318
+            ]);
319
+            throw new OCSException('Bad request', 101);
320
+        }
321
+    }
322
+
323
+    /**
324
+     * @NoAdminRequired
325
+     * @NoSubAdminRequired
326
+     *
327
+     * gets user info
328
+     *
329
+     * @param string $userId
330
+     * @return DataResponse
331
+     * @throws OCSException
332
+     */
333
+    public function getUser(string $userId): DataResponse {
334
+        $data = $this->getUserData($userId);
335
+        // getUserData returns empty array if not enough permissions
336
+        if (empty($data)) {
337
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
338
+        }
339
+        return new DataResponse($data);
340
+    }
341
+
342
+    /**
343
+     * @NoAdminRequired
344
+     * @NoSubAdminRequired
345
+     *
346
+     * gets user info from the currently logged in user
347
+     *
348
+     * @return DataResponse
349
+     * @throws OCSException
350
+     */
351
+    public function getCurrentUser(): DataResponse {
352
+        $user = $this->userSession->getUser();
353
+        if ($user) {
354
+            $data =  $this->getUserData($user->getUID());
355
+            // rename "displayname" to "display-name" only for this call to keep
356
+            // the API stable.
357
+            $data['display-name'] = $data['displayname'];
358
+            unset($data['displayname']);
359
+            return new DataResponse($data);
360
+
361
+        }
362
+
363
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
364
+    }
365
+
366
+    /**
367
+     * @NoAdminRequired
368
+     * @NoSubAdminRequired
369
+     */
370
+    public function getEditableFields(): DataResponse {
371
+        $permittedFields = [];
372
+
373
+        // Editing self (display, email)
374
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
375
+            $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
376
+            $permittedFields[] = AccountManager::PROPERTY_EMAIL;
377
+        }
378
+
379
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
380
+            $federatedFileSharing = $this->federatedFileSharingFactory->get();
381
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
382
+            if ($shareProvider->isLookupServerUploadEnabled()) {
383
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
384
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
385
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
386
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
387
+            }
388
+        }
389
+
390
+        return new DataResponse($permittedFields);
391
+    }
392
+
393
+    /**
394
+     * @NoAdminRequired
395
+     * @NoSubAdminRequired
396
+     * @PasswordConfirmationRequired
397
+     *
398
+     * edit users
399
+     *
400
+     * @param string $userId
401
+     * @param string $key
402
+     * @param string $value
403
+     * @return DataResponse
404
+     * @throws OCSException
405
+     */
406
+    public function editUser(string $userId, string $key, string $value): DataResponse {
407
+        $currentLoggedInUser = $this->userSession->getUser();
408
+
409
+        $targetUser = $this->userManager->get($userId);
410
+        if ($targetUser === null) {
411
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
412
+        }
413
+
414
+        $permittedFields = [];
415
+        if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
416
+            // Editing self (display, email)
417
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
418
+                $permittedFields[] = 'display';
419
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
420
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
421
+            }
422
+
423
+            $permittedFields[] = 'password';
424
+            if ($this->config->getSystemValue('force_language', false) === false ||
425
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
426
+                $permittedFields[] = 'language';
427
+            }
428
+
429
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
430
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
431
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
432
+                if ($shareProvider->isLookupServerUploadEnabled()) {
433
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
434
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
435
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
436
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
437
+                }
438
+            }
439
+
440
+            // If admin they can edit their own quota
441
+            if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
442
+                $permittedFields[] = 'quota';
443
+            }
444
+        } else {
445
+            // Check if admin / subadmin
446
+            $subAdminManager = $this->groupManager->getSubAdmin();
447
+            if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
448
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
449
+                // They have permissions over the user
450
+                $permittedFields[] = 'display';
451
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
452
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
453
+                $permittedFields[] = 'password';
454
+                $permittedFields[] = 'language';
455
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
456
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
457
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
458
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
459
+                $permittedFields[] = 'quota';
460
+            } else {
461
+                // No rights
462
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
463
+            }
464
+        }
465
+        // Check if permitted to edit this field
466
+        if (!in_array($key, $permittedFields)) {
467
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
468
+        }
469
+        // Process the edit
470
+        switch($key) {
471
+            case 'display':
472
+            case AccountManager::PROPERTY_DISPLAYNAME:
473
+                $targetUser->setDisplayName($value);
474
+                break;
475
+            case 'quota':
476
+                $quota = $value;
477
+                if ($quota !== 'none' && $quota !== 'default') {
478
+                    if (is_numeric($quota)) {
479
+                        $quota = (float) $quota;
480
+                    } else {
481
+                        $quota = \OCP\Util::computerFileSize($quota);
482
+                    }
483
+                    if ($quota === false) {
484
+                        throw new OCSException('Invalid quota value '.$value, 103);
485
+                    }
486
+                    if ($quota === 0) {
487
+                        $quota = 'default';
488
+                    }else if ($quota === -1) {
489
+                        $quota = 'none';
490
+                    } else {
491
+                        $quota = \OCP\Util::humanFileSize($quota);
492
+                    }
493
+                }
494
+                $targetUser->setQuota($quota);
495
+                break;
496
+            case 'password':
497
+                $targetUser->setPassword($value);
498
+                break;
499
+            case 'language':
500
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
501
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
502
+                    throw new OCSException('Invalid language', 102);
503
+                }
504
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
505
+                break;
506
+            case AccountManager::PROPERTY_EMAIL:
507
+                if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') {
508
+                    $targetUser->setEMailAddress($value);
509
+                } else {
510
+                    throw new OCSException('', 102);
511
+                }
512
+                break;
513
+            case AccountManager::PROPERTY_PHONE:
514
+            case AccountManager::PROPERTY_ADDRESS:
515
+            case AccountManager::PROPERTY_WEBSITE:
516
+            case AccountManager::PROPERTY_TWITTER:
517
+                $userAccount = $this->accountManager->getUser($targetUser);
518
+                if ($userAccount[$key]['value'] !== $value) {
519
+                    $userAccount[$key]['value'] = $value;
520
+                    $this->accountManager->updateUser($targetUser, $userAccount);
521
+                }
522
+                break;
523
+            default:
524
+                throw new OCSException('', 103);
525
+        }
526
+        return new DataResponse();
527
+    }
528
+
529
+    /**
530
+     * @PasswordConfirmationRequired
531
+     * @NoAdminRequired
532
+     *
533
+     * @param string $userId
534
+     * @return DataResponse
535
+     * @throws OCSException
536
+     */
537
+    public function deleteUser(string $userId): DataResponse {
538
+        $currentLoggedInUser = $this->userSession->getUser();
539
+
540
+        $targetUser = $this->userManager->get($userId);
541
+
542
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
543
+            throw new OCSException('', 101);
544
+        }
545
+
546
+        // If not permitted
547
+        $subAdminManager = $this->groupManager->getSubAdmin();
548
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
549
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
550
+        }
551
+
552
+        // Go ahead with the delete
553
+        if ($targetUser->delete()) {
554
+            return new DataResponse();
555
+        } else {
556
+            throw new OCSException('', 101);
557
+        }
558
+    }
559
+
560
+    /**
561
+     * @PasswordConfirmationRequired
562
+     * @NoAdminRequired
563
+     *
564
+     * @param string $userId
565
+     * @return DataResponse
566
+     * @throws OCSException
567
+     * @throws OCSForbiddenException
568
+     */
569
+    public function disableUser(string $userId): DataResponse {
570
+        return $this->setEnabled($userId, false);
571
+    }
572
+
573
+    /**
574
+     * @PasswordConfirmationRequired
575
+     * @NoAdminRequired
576
+     *
577
+     * @param string $userId
578
+     * @return DataResponse
579
+     * @throws OCSException
580
+     * @throws OCSForbiddenException
581
+     */
582
+    public function enableUser(string $userId): DataResponse {
583
+        return $this->setEnabled($userId, true);
584
+    }
585
+
586
+    /**
587
+     * @param string $userId
588
+     * @param bool $value
589
+     * @return DataResponse
590
+     * @throws OCSException
591
+     */
592
+    private function setEnabled(string $userId, bool $value): DataResponse {
593
+        $currentLoggedInUser = $this->userSession->getUser();
594
+
595
+        $targetUser = $this->userManager->get($userId);
596
+        if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
597
+            throw new OCSException('', 101);
598
+        }
599
+
600
+        // If not permitted
601
+        $subAdminManager = $this->groupManager->getSubAdmin();
602
+        if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
603
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
604
+        }
605
+
606
+        // enable/disable the user now
607
+        $targetUser->setEnabled($value);
608
+        return new DataResponse();
609
+    }
610
+
611
+    /**
612
+     * @NoAdminRequired
613
+     * @NoSubAdminRequired
614
+     *
615
+     * @param string $userId
616
+     * @return DataResponse
617
+     * @throws OCSException
618
+     */
619
+    public function getUsersGroups(string $userId): DataResponse {
620
+        $loggedInUser = $this->userSession->getUser();
621
+
622
+        $targetUser = $this->userManager->get($userId);
623
+        if ($targetUser === null) {
624
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
625
+        }
626
+
627
+        if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
628
+            // Self lookup or admin lookup
629
+            return new DataResponse([
630
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
631
+            ]);
632
+        } else {
633
+            $subAdminManager = $this->groupManager->getSubAdmin();
634
+
635
+            // Looking up someone else
636
+            if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
637
+                // Return the group that the method caller is subadmin of for the user in question
638
+                /** @var IGroup[] $getSubAdminsGroups */
639
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
640
+                foreach ($getSubAdminsGroups as $key => $group) {
641
+                    $getSubAdminsGroups[$key] = $group->getGID();
642
+                }
643
+                $groups = array_intersect(
644
+                    $getSubAdminsGroups,
645
+                    $this->groupManager->getUserGroupIds($targetUser)
646
+                );
647
+                return new DataResponse(['groups' => $groups]);
648
+            } else {
649
+                // Not permitted
650
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
651
+            }
652
+        }
653
+
654
+    }
655
+
656
+    /**
657
+     * @PasswordConfirmationRequired
658
+     * @NoAdminRequired
659
+     *
660
+     * @param string $userId
661
+     * @param string $groupid
662
+     * @return DataResponse
663
+     * @throws OCSException
664
+     */
665
+    public function addToGroup(string $userId, string $groupid = ''): DataResponse {
666
+        if ($groupid === '') {
667
+            throw new OCSException('', 101);
668
+        }
669
+
670
+        $group = $this->groupManager->get($groupid);
671
+        $targetUser = $this->userManager->get($userId);
672
+        if ($group === null) {
673
+            throw new OCSException('', 102);
674
+        }
675
+        if ($targetUser === null) {
676
+            throw new OCSException('', 103);
677
+        }
678
+
679
+        // If they're not an admin, check they are a subadmin of the group in question
680
+        $loggedInUser = $this->userSession->getUser();
681
+        $subAdminManager = $this->groupManager->getSubAdmin();
682
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
683
+            throw new OCSException('', 104);
684
+        }
685
+
686
+        // Add user to group
687
+        $group->addUser($targetUser);
688
+        return new DataResponse();
689
+    }
690
+
691
+    /**
692
+     * @PasswordConfirmationRequired
693
+     * @NoAdminRequired
694
+     *
695
+     * @param string $userId
696
+     * @param string $groupid
697
+     * @return DataResponse
698
+     * @throws OCSException
699
+     */
700
+    public function removeFromGroup(string $userId, string $groupid): DataResponse {
701
+        $loggedInUser = $this->userSession->getUser();
702
+
703
+        if ($groupid === null || trim($groupid) === '') {
704
+            throw new OCSException('', 101);
705
+        }
706
+
707
+        $group = $this->groupManager->get($groupid);
708
+        if ($group === null) {
709
+            throw new OCSException('', 102);
710
+        }
711
+
712
+        $targetUser = $this->userManager->get($userId);
713
+        if ($targetUser === null) {
714
+            throw new OCSException('', 103);
715
+        }
716
+
717
+        // If they're not an admin, check they are a subadmin of the group in question
718
+        $subAdminManager = $this->groupManager->getSubAdmin();
719
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
720
+            throw new OCSException('', 104);
721
+        }
722
+
723
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
724
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
725
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
726
+                if ($group->getGID() === 'admin') {
727
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
728
+                }
729
+            } else {
730
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
731
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
732
+            }
733
+
734
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
735
+            /** @var IGroup[] $subAdminGroups */
736
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
737
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
738
+                return $subAdminGroup->getGID();
739
+            }, $subAdminGroups);
740
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
741
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
742
+
743
+            if (count($userSubAdminGroups) <= 1) {
744
+                // Subadmin must not be able to remove a user from all their subadmin groups.
745
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
746
+            }
747
+        }
748
+
749
+        // Remove user from group
750
+        $group->removeUser($targetUser);
751
+        return new DataResponse();
752
+    }
753
+
754
+    /**
755
+     * Creates a subadmin
756
+     *
757
+     * @PasswordConfirmationRequired
758
+     *
759
+     * @param string $userId
760
+     * @param string $groupid
761
+     * @return DataResponse
762
+     * @throws OCSException
763
+     */
764
+    public function addSubAdmin(string $userId, string $groupid): DataResponse {
765
+        $group = $this->groupManager->get($groupid);
766
+        $user = $this->userManager->get($userId);
767
+
768
+        // Check if the user exists
769
+        if ($user === null) {
770
+            throw new OCSException('User does not exist', 101);
771
+        }
772
+        // Check if group exists
773
+        if ($group === null) {
774
+            throw new OCSException('Group does not exist',  102);
775
+        }
776
+        // Check if trying to make subadmin of admin group
777
+        if ($group->getGID() === 'admin') {
778
+            throw new OCSException('Cannot create subadmins for admin group', 103);
779
+        }
780
+
781
+        $subAdminManager = $this->groupManager->getSubAdmin();
782
+
783
+        // We cannot be subadmin twice
784
+        if ($subAdminManager->isSubAdminOfGroup($user, $group)) {
785
+            return new DataResponse();
786
+        }
787
+        // Go
788
+        if ($subAdminManager->createSubAdmin($user, $group)) {
789
+            return new DataResponse();
790
+        } else {
791
+            throw new OCSException('Unknown error occurred', 103);
792
+        }
793
+    }
794
+
795
+    /**
796
+     * Removes a subadmin from a group
797
+     *
798
+     * @PasswordConfirmationRequired
799
+     *
800
+     * @param string $userId
801
+     * @param string $groupid
802
+     * @return DataResponse
803
+     * @throws OCSException
804
+     */
805
+    public function removeSubAdmin(string $userId, string $groupid): DataResponse {
806
+        $group = $this->groupManager->get($groupid);
807
+        $user = $this->userManager->get($userId);
808
+        $subAdminManager = $this->groupManager->getSubAdmin();
809
+
810
+        // Check if the user exists
811
+        if ($user === null) {
812
+            throw new OCSException('User does not exist', 101);
813
+        }
814
+        // Check if the group exists
815
+        if ($group === null) {
816
+            throw new OCSException('Group does not exist', 101);
817
+        }
818
+        // Check if they are a subadmin of this said group
819
+        if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
820
+            throw new OCSException('User is not a subadmin of this group', 102);
821
+        }
822
+
823
+        // Go
824
+        if ($subAdminManager->deleteSubAdmin($user, $group)) {
825
+            return new DataResponse();
826
+        } else {
827
+            throw new OCSException('Unknown error occurred', 103);
828
+        }
829
+    }
830
+
831
+    /**
832
+     * Get the groups a user is a subadmin of
833
+     *
834
+     * @param string $userId
835
+     * @return DataResponse
836
+     * @throws OCSException
837
+     */
838
+    public function getUserSubAdminGroups(string $userId): DataResponse {
839
+        $groups = $this->getUserSubAdminGroupsData($userId);
840
+        return new DataResponse($groups);
841
+    }
842
+
843
+    /**
844
+     * @NoAdminRequired
845
+     * @PasswordConfirmationRequired
846
+     *
847
+     * resend welcome message
848
+     *
849
+     * @param string $userId
850
+     * @return DataResponse
851
+     * @throws OCSException
852
+     */
853
+    public function resendWelcomeMessage(string $userId): DataResponse {
854
+        $currentLoggedInUser = $this->userSession->getUser();
855
+
856
+        $targetUser = $this->userManager->get($userId);
857
+        if ($targetUser === null) {
858
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
859
+        }
860
+
861
+        // Check if admin / subadmin
862
+        $subAdminManager = $this->groupManager->getSubAdmin();
863
+        if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
864
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
865
+            // No rights
866
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
867
+        }
868
+
869
+        $email = $targetUser->getEMailAddress();
870
+        if ($email === '' || $email === null) {
871
+            throw new OCSException('Email address not available', 101);
872
+        }
873
+        $username = $targetUser->getUID();
874
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
875
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
876
+            $lang = 'en';
877
+        }
878
+
879
+        $l10n = $this->l10nFactory->get('settings', $lang);
880
+
881
+        try {
882
+            $this->newUserMailHelper->setL10N($l10n);
883
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
884
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
885
+        } catch(\Exception $e) {
886
+            $this->logger->logException($e, [
887
+                'message' => "Can't send new user mail to $email",
888
+                'level' => ILogger::ERROR,
889
+                'app' => 'settings',
890
+            ]);
891
+            throw new OCSException('Sending email failed', 102);
892
+        }
893
+
894
+        return new DataResponse();
895
+    }
896 896
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
 		// Admin? Or SubAdmin?
127 127
 		$uid = $user->getUID();
128 128
 		$subAdminManager = $this->groupManager->getSubAdmin();
129
-		if ($this->groupManager->isAdmin($uid)){
129
+		if ($this->groupManager->isAdmin($uid)) {
130 130
 			$users = $this->userManager->search($search, $limit, $offset);
131 131
 		} else if ($subAdminManager->isSubAdmin($user)) {
132 132
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		// Admin? Or SubAdmin?
160 160
 		$uid = $user->getUID();
161 161
 		$subAdminManager = $this->groupManager->getSubAdmin();
162
-		if ($this->groupManager->isAdmin($uid)){
162
+		if ($this->groupManager->isAdmin($uid)) {
163 163
 			$users = $this->userManager->search($search, $limit, $offset);
164 164
 		} else if ($subAdminManager->isSubAdmin($user)) {
165 165
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
 					throw new OCSException('group '.$group.' does not exist', 104);
225 225
 				}
226 226
 				if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) {
227
-					throw new OCSException('insufficient privileges for group '. $group, 105);
227
+					throw new OCSException('insufficient privileges for group '.$group, 105);
228 228
 				}
229 229
 			}
230 230
 		} else {
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
 				$group = $this->groupManager->get($groupid);
240 240
 				// Check if group exists
241 241
 				if ($group === null) {
242
-					throw new OCSException('Subadmin group does not exist',  102);
242
+					throw new OCSException('Subadmin group does not exist', 102);
243 243
 				}
244 244
 				// Check if trying to make subadmin of admin group
245 245
 				if ($group->getGID() === 'admin') {
@@ -267,11 +267,11 @@  discard block
 block discarded – undo
267 267
 
268 268
 		try {
269 269
 			$newUser = $this->userManager->createUser($userid, $password);
270
-			$this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']);
270
+			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
271 271
 
272 272
 			foreach ($groups as $group) {
273 273
 				$this->groupManager->get($group)->addUser($newUser);
274
-				$this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']);
274
+				$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
275 275
 			}
276 276
 			foreach ($subadminGroups as $group) {
277 277
 				$subAdminManager->createSubAdmin($newUser, $group);
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
 
304 304
 			return new DataResponse();
305 305
 
306
-		} catch (HintException $e ) {
306
+		} catch (HintException $e) {
307 307
 			$this->logger->logException($e, [
308 308
 				'message' => 'Failed addUser attempt with hint exception.',
309 309
 				'level' => ILogger::WARN,
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
 	public function getCurrentUser(): DataResponse {
352 352
 		$user = $this->userSession->getUser();
353 353
 		if ($user) {
354
-			$data =  $this->getUserData($user->getUID());
354
+			$data = $this->getUserData($user->getUID());
355 355
 			// rename "displayname" to "display-name" only for this call to keep
356 356
 			// the API stable.
357 357
 			$data['display-name'] = $data['displayname'];
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
468 468
 		}
469 469
 		// Process the edit
470
-		switch($key) {
470
+		switch ($key) {
471 471
 			case 'display':
472 472
 			case AccountManager::PROPERTY_DISPLAYNAME:
473 473
 				$targetUser->setDisplayName($value);
@@ -485,7 +485,7 @@  discard block
 block discarded – undo
485 485
 					}
486 486
 					if ($quota === 0) {
487 487
 						$quota = 'default';
488
-					}else if ($quota === -1) {
488
+					} else if ($quota === -1) {
489 489
 						$quota = 'none';
490 490
 					} else {
491 491
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
735 735
 			/** @var IGroup[] $subAdminGroups */
736 736
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
737
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
737
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
738 738
 				return $subAdminGroup->getGID();
739 739
 			}, $subAdminGroups);
740 740
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -771,7 +771,7 @@  discard block
 block discarded – undo
771 771
 		}
772 772
 		// Check if group exists
773 773
 		if ($group === null) {
774
-			throw new OCSException('Group does not exist',  102);
774
+			throw new OCSException('Group does not exist', 102);
775 775
 		}
776 776
 		// Check if trying to make subadmin of admin group
777 777
 		if ($group->getGID() === 'admin') {
@@ -882,7 +882,7 @@  discard block
 block discarded – undo
882 882
 			$this->newUserMailHelper->setL10N($l10n);
883 883
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
884 884
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
885
-		} catch(\Exception $e) {
885
+		} catch (\Exception $e) {
886 886
 			$this->logger->logException($e, [
887 887
 				'message' => "Can't send new user mail to $email",
888 888
 				'level' => ILogger::ERROR,
Please login to merge, or discard this patch.