Completed
Pull Request — master (#5498)
by Joas
16:49
created
lib/private/L10N/Factory.php 1 patch
Indentation   +375 added lines, -375 removed lines patch added patch discarded remove patch
@@ -40,379 +40,379 @@
 block discarded – undo
40 40
  */
41 41
 class Factory implements IFactory {
42 42
 
43
-	/** @var string */
44
-	protected $requestLanguage = '';
45
-
46
-	/**
47
-	 * cached instances
48
-	 * @var array Structure: Lang => App => \OCP\IL10N
49
-	 */
50
-	protected $instances = [];
51
-
52
-	/**
53
-	 * @var array Structure: App => string[]
54
-	 */
55
-	protected $availableLanguages = [];
56
-
57
-	/**
58
-	 * @var array Structure: string => callable
59
-	 */
60
-	protected $pluralFunctions = [];
61
-
62
-	/** @var IConfig */
63
-	protected $config;
64
-
65
-	/** @var IRequest */
66
-	protected $request;
67
-
68
-	/** @var IUserSession */
69
-	protected $userSession;
70
-
71
-	/** @var string */
72
-	protected $serverRoot;
73
-
74
-	/**
75
-	 * @param IConfig $config
76
-	 * @param IRequest $request
77
-	 * @param IUserSession $userSession
78
-	 * @param string $serverRoot
79
-	 */
80
-	public function __construct(IConfig $config,
81
-								IRequest $request,
82
-								IUserSession $userSession,
83
-								$serverRoot) {
84
-		$this->config = $config;
85
-		$this->request = $request;
86
-		$this->userSession = $userSession;
87
-		$this->serverRoot = $serverRoot;
88
-	}
89
-
90
-	/**
91
-	 * Get a language instance
92
-	 *
93
-	 * @param string $app
94
-	 * @param string|null $lang
95
-	 * @return \OCP\IL10N
96
-	 */
97
-	public function get($app, $lang = null) {
98
-		$app = \OC_App::cleanAppId($app);
99
-		if ($lang !== null) {
100
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
-		}
102
-
103
-		$forceLang = $this->config->getSystemValue('force_language', false);
104
-		if (is_string($forceLang)) {
105
-			$lang = $forceLang;
106
-		}
107
-
108
-		if ($lang === null || !$this->languageExists($app, $lang)) {
109
-			$lang = $this->findLanguage($app);
110
-		}
111
-
112
-		if (!isset($this->instances[$lang][$app])) {
113
-			$this->instances[$lang][$app] = new L10N(
114
-				$this, $app, $lang,
115
-				$this->getL10nFilesForApp($app, $lang)
116
-			);
117
-		}
118
-
119
-		return $this->instances[$lang][$app];
120
-	}
121
-
122
-	/**
123
-	 * Find the best language
124
-	 *
125
-	 * @param string|null $app App id or null for core
126
-	 * @return string language If nothing works it returns 'en'
127
-	 */
128
-	public function findLanguage($app = null) {
129
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
-			return $this->requestLanguage;
131
-		}
132
-
133
-		/**
134
-		 * At this point Nextcloud might not yet be installed and thus the lookup
135
-		 * in the preferences table might fail. For this reason we need to check
136
-		 * whether the instance has already been installed
137
-		 *
138
-		 * @link https://github.com/owncloud/core/issues/21955
139
-		 */
140
-		if($this->config->getSystemValue('installed', false)) {
141
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
-			if(!is_null($userId)) {
143
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
-			} else {
145
-				$userLang = null;
146
-			}
147
-		} else {
148
-			$userId = null;
149
-			$userLang = null;
150
-		}
151
-
152
-		if ($userLang) {
153
-			$this->requestLanguage = $userLang;
154
-			if ($this->languageExists($app, $userLang)) {
155
-				return $userLang;
156
-			}
157
-		}
158
-
159
-		try {
160
-			// Try to get the language from the Request
161
-			$lang = $this->getLanguageFromRequest($app);
162
-			if ($userId !== null && $app === null && !$userLang) {
163
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
164
-			}
165
-			return $lang;
166
-		} catch (LanguageNotFoundException $e) {
167
-			// Finding language from request failed fall back to default language
168
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
169
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
-				return $defaultLanguage;
171
-			}
172
-		}
173
-
174
-		// We could not find any language so fall back to english
175
-		return 'en';
176
-	}
177
-
178
-	/**
179
-	 * Find all available languages for an app
180
-	 *
181
-	 * @param string|null $app App id or null for core
182
-	 * @return array an array of available languages
183
-	 */
184
-	public function findAvailableLanguages($app = null) {
185
-		$key = $app;
186
-		if ($key === null) {
187
-			$key = 'null';
188
-		}
189
-
190
-		// also works with null as key
191
-		if (!empty($this->availableLanguages[$key])) {
192
-			return $this->availableLanguages[$key];
193
-		}
194
-
195
-		$available = ['en']; //english is always available
196
-		$dir = $this->findL10nDir($app);
197
-		if (is_dir($dir)) {
198
-			$files = scandir($dir);
199
-			if ($files !== false) {
200
-				foreach ($files as $file) {
201
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
-						$available[] = substr($file, 0, -5);
203
-					}
204
-				}
205
-			}
206
-		}
207
-
208
-		// merge with translations from theme
209
-		$theme = $this->config->getSystemValue('theme');
210
-		if (!empty($theme)) {
211
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
-
213
-			if (is_dir($themeDir)) {
214
-				$files = scandir($themeDir);
215
-				if ($files !== false) {
216
-					foreach ($files as $file) {
217
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
-							$available[] = substr($file, 0, -5);
219
-						}
220
-					}
221
-				}
222
-			}
223
-		}
224
-
225
-		$this->availableLanguages[$key] = $available;
226
-		return $available;
227
-	}
228
-
229
-	/**
230
-	 * @param string|null $app App id or null for core
231
-	 * @param string $lang
232
-	 * @return bool
233
-	 */
234
-	public function languageExists($app, $lang) {
235
-		if ($lang === 'en') {//english is always available
236
-			return true;
237
-		}
238
-
239
-		$languages = $this->findAvailableLanguages($app);
240
-		return array_search($lang, $languages) !== false;
241
-	}
242
-
243
-	/**
244
-	 * @param string|null $app
245
-	 * @return string
246
-	 * @throws LanguageNotFoundException
247
-	 */
248
-	private function getLanguageFromRequest($app) {
249
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
-		if ($header) {
251
-			$available = $this->findAvailableLanguages($app);
252
-
253
-			// E.g. make sure that 'de' is before 'de_DE'.
254
-			sort($available);
255
-
256
-			$preferences = preg_split('/,\s*/', strtolower($header));
257
-			foreach ($preferences as $preference) {
258
-				list($preferred_language) = explode(';', $preference);
259
-				$preferred_language = str_replace('-', '_', $preferred_language);
260
-
261
-				foreach ($available as $available_language) {
262
-					if ($preferred_language === strtolower($available_language)) {
263
-						return $available_language;
264
-					}
265
-				}
266
-
267
-				// Fallback from de_De to de
268
-				foreach ($available as $available_language) {
269
-					if (substr($preferred_language, 0, 2) === $available_language) {
270
-						return $available_language;
271
-					}
272
-				}
273
-			}
274
-		}
275
-
276
-		throw new LanguageNotFoundException();
277
-	}
278
-
279
-	/**
280
-	 * Checks if $sub is a subdirectory of $parent
281
-	 *
282
-	 * @param string $sub
283
-	 * @param string $parent
284
-	 * @return bool
285
-	 */
286
-	private function isSubDirectory($sub, $parent) {
287
-		// Check whether $sub contains no ".."
288
-		if(strpos($sub, '..') !== false) {
289
-			return false;
290
-		}
291
-
292
-		// Check whether $sub is a subdirectory of $parent
293
-		if (strpos($sub, $parent) === 0) {
294
-			return true;
295
-		}
296
-
297
-		return false;
298
-	}
299
-
300
-	/**
301
-	 * Get a list of language files that should be loaded
302
-	 *
303
-	 * @param string $app
304
-	 * @param string $lang
305
-	 * @return string[]
306
-	 */
307
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
308
-	// FIXME This is also the reason, why it is not in the public interface
309
-	public function getL10nFilesForApp($app, $lang) {
310
-		$languageFiles = [];
311
-
312
-		$i18nDir = $this->findL10nDir($app);
313
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
314
-
315
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
316
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
317
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
318
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
319
-			)
320
-			&& file_exists($transFile)) {
321
-			// load the translations file
322
-			$languageFiles[] = $transFile;
323
-		}
324
-
325
-		// merge with translations from theme
326
-		$theme = $this->config->getSystemValue('theme');
327
-		if (!empty($theme)) {
328
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
329
-			if (file_exists($transFile)) {
330
-				$languageFiles[] = $transFile;
331
-			}
332
-		}
333
-
334
-		return $languageFiles;
335
-	}
336
-
337
-	/**
338
-	 * find the l10n directory
339
-	 *
340
-	 * @param string $app App id or empty string for core
341
-	 * @return string directory
342
-	 */
343
-	protected function findL10nDir($app = null) {
344
-		if (in_array($app, ['core', 'lib', 'settings'])) {
345
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
346
-				return $this->serverRoot . '/' . $app . '/l10n/';
347
-			}
348
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
349
-			// Check if the app is in the app folder
350
-			return \OC_App::getAppPath($app) . '/l10n/';
351
-		}
352
-		return $this->serverRoot . '/core/l10n/';
353
-	}
354
-
355
-
356
-	/**
357
-	 * Creates a function from the plural string
358
-	 *
359
-	 * Parts of the code is copied from Habari:
360
-	 * https://github.com/habari/system/blob/master/classes/locale.php
361
-	 * @param string $string
362
-	 * @return string
363
-	 */
364
-	public function createPluralFunction($string) {
365
-		if (isset($this->pluralFunctions[$string])) {
366
-			return $this->pluralFunctions[$string];
367
-		}
368
-
369
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
370
-			// sanitize
371
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
372
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
373
-
374
-			$body = str_replace(
375
-				array( 'plural', 'n', '$n$plurals', ),
376
-				array( '$plural', '$n', '$nplurals', ),
377
-				'nplurals='. $nplurals . '; plural=' . $plural
378
-			);
379
-
380
-			// add parents
381
-			// important since PHP's ternary evaluates from left to right
382
-			$body .= ';';
383
-			$res = '';
384
-			$p = 0;
385
-			for($i = 0; $i < strlen($body); $i++) {
386
-				$ch = $body[$i];
387
-				switch ( $ch ) {
388
-					case '?':
389
-						$res .= ' ? (';
390
-						$p++;
391
-						break;
392
-					case ':':
393
-						$res .= ') : (';
394
-						break;
395
-					case ';':
396
-						$res .= str_repeat( ')', $p ) . ';';
397
-						$p = 0;
398
-						break;
399
-					default:
400
-						$res .= $ch;
401
-				}
402
-			}
403
-
404
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
405
-			$function = create_function('$n', $body);
406
-			$this->pluralFunctions[$string] = $function;
407
-			return $function;
408
-		} else {
409
-			// default: one plural form for all cases but n==1 (english)
410
-			$function = create_function(
411
-				'$n',
412
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
413
-			);
414
-			$this->pluralFunctions[$string] = $function;
415
-			return $function;
416
-		}
417
-	}
43
+    /** @var string */
44
+    protected $requestLanguage = '';
45
+
46
+    /**
47
+     * cached instances
48
+     * @var array Structure: Lang => App => \OCP\IL10N
49
+     */
50
+    protected $instances = [];
51
+
52
+    /**
53
+     * @var array Structure: App => string[]
54
+     */
55
+    protected $availableLanguages = [];
56
+
57
+    /**
58
+     * @var array Structure: string => callable
59
+     */
60
+    protected $pluralFunctions = [];
61
+
62
+    /** @var IConfig */
63
+    protected $config;
64
+
65
+    /** @var IRequest */
66
+    protected $request;
67
+
68
+    /** @var IUserSession */
69
+    protected $userSession;
70
+
71
+    /** @var string */
72
+    protected $serverRoot;
73
+
74
+    /**
75
+     * @param IConfig $config
76
+     * @param IRequest $request
77
+     * @param IUserSession $userSession
78
+     * @param string $serverRoot
79
+     */
80
+    public function __construct(IConfig $config,
81
+                                IRequest $request,
82
+                                IUserSession $userSession,
83
+                                $serverRoot) {
84
+        $this->config = $config;
85
+        $this->request = $request;
86
+        $this->userSession = $userSession;
87
+        $this->serverRoot = $serverRoot;
88
+    }
89
+
90
+    /**
91
+     * Get a language instance
92
+     *
93
+     * @param string $app
94
+     * @param string|null $lang
95
+     * @return \OCP\IL10N
96
+     */
97
+    public function get($app, $lang = null) {
98
+        $app = \OC_App::cleanAppId($app);
99
+        if ($lang !== null) {
100
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
101
+        }
102
+
103
+        $forceLang = $this->config->getSystemValue('force_language', false);
104
+        if (is_string($forceLang)) {
105
+            $lang = $forceLang;
106
+        }
107
+
108
+        if ($lang === null || !$this->languageExists($app, $lang)) {
109
+            $lang = $this->findLanguage($app);
110
+        }
111
+
112
+        if (!isset($this->instances[$lang][$app])) {
113
+            $this->instances[$lang][$app] = new L10N(
114
+                $this, $app, $lang,
115
+                $this->getL10nFilesForApp($app, $lang)
116
+            );
117
+        }
118
+
119
+        return $this->instances[$lang][$app];
120
+    }
121
+
122
+    /**
123
+     * Find the best language
124
+     *
125
+     * @param string|null $app App id or null for core
126
+     * @return string language If nothing works it returns 'en'
127
+     */
128
+    public function findLanguage($app = null) {
129
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
130
+            return $this->requestLanguage;
131
+        }
132
+
133
+        /**
134
+         * At this point Nextcloud might not yet be installed and thus the lookup
135
+         * in the preferences table might fail. For this reason we need to check
136
+         * whether the instance has already been installed
137
+         *
138
+         * @link https://github.com/owncloud/core/issues/21955
139
+         */
140
+        if($this->config->getSystemValue('installed', false)) {
141
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
142
+            if(!is_null($userId)) {
143
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
144
+            } else {
145
+                $userLang = null;
146
+            }
147
+        } else {
148
+            $userId = null;
149
+            $userLang = null;
150
+        }
151
+
152
+        if ($userLang) {
153
+            $this->requestLanguage = $userLang;
154
+            if ($this->languageExists($app, $userLang)) {
155
+                return $userLang;
156
+            }
157
+        }
158
+
159
+        try {
160
+            // Try to get the language from the Request
161
+            $lang = $this->getLanguageFromRequest($app);
162
+            if ($userId !== null && $app === null && !$userLang) {
163
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
164
+            }
165
+            return $lang;
166
+        } catch (LanguageNotFoundException $e) {
167
+            // Finding language from request failed fall back to default language
168
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
169
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
170
+                return $defaultLanguage;
171
+            }
172
+        }
173
+
174
+        // We could not find any language so fall back to english
175
+        return 'en';
176
+    }
177
+
178
+    /**
179
+     * Find all available languages for an app
180
+     *
181
+     * @param string|null $app App id or null for core
182
+     * @return array an array of available languages
183
+     */
184
+    public function findAvailableLanguages($app = null) {
185
+        $key = $app;
186
+        if ($key === null) {
187
+            $key = 'null';
188
+        }
189
+
190
+        // also works with null as key
191
+        if (!empty($this->availableLanguages[$key])) {
192
+            return $this->availableLanguages[$key];
193
+        }
194
+
195
+        $available = ['en']; //english is always available
196
+        $dir = $this->findL10nDir($app);
197
+        if (is_dir($dir)) {
198
+            $files = scandir($dir);
199
+            if ($files !== false) {
200
+                foreach ($files as $file) {
201
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
202
+                        $available[] = substr($file, 0, -5);
203
+                    }
204
+                }
205
+            }
206
+        }
207
+
208
+        // merge with translations from theme
209
+        $theme = $this->config->getSystemValue('theme');
210
+        if (!empty($theme)) {
211
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
212
+
213
+            if (is_dir($themeDir)) {
214
+                $files = scandir($themeDir);
215
+                if ($files !== false) {
216
+                    foreach ($files as $file) {
217
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
218
+                            $available[] = substr($file, 0, -5);
219
+                        }
220
+                    }
221
+                }
222
+            }
223
+        }
224
+
225
+        $this->availableLanguages[$key] = $available;
226
+        return $available;
227
+    }
228
+
229
+    /**
230
+     * @param string|null $app App id or null for core
231
+     * @param string $lang
232
+     * @return bool
233
+     */
234
+    public function languageExists($app, $lang) {
235
+        if ($lang === 'en') {//english is always available
236
+            return true;
237
+        }
238
+
239
+        $languages = $this->findAvailableLanguages($app);
240
+        return array_search($lang, $languages) !== false;
241
+    }
242
+
243
+    /**
244
+     * @param string|null $app
245
+     * @return string
246
+     * @throws LanguageNotFoundException
247
+     */
248
+    private function getLanguageFromRequest($app) {
249
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
250
+        if ($header) {
251
+            $available = $this->findAvailableLanguages($app);
252
+
253
+            // E.g. make sure that 'de' is before 'de_DE'.
254
+            sort($available);
255
+
256
+            $preferences = preg_split('/,\s*/', strtolower($header));
257
+            foreach ($preferences as $preference) {
258
+                list($preferred_language) = explode(';', $preference);
259
+                $preferred_language = str_replace('-', '_', $preferred_language);
260
+
261
+                foreach ($available as $available_language) {
262
+                    if ($preferred_language === strtolower($available_language)) {
263
+                        return $available_language;
264
+                    }
265
+                }
266
+
267
+                // Fallback from de_De to de
268
+                foreach ($available as $available_language) {
269
+                    if (substr($preferred_language, 0, 2) === $available_language) {
270
+                        return $available_language;
271
+                    }
272
+                }
273
+            }
274
+        }
275
+
276
+        throw new LanguageNotFoundException();
277
+    }
278
+
279
+    /**
280
+     * Checks if $sub is a subdirectory of $parent
281
+     *
282
+     * @param string $sub
283
+     * @param string $parent
284
+     * @return bool
285
+     */
286
+    private function isSubDirectory($sub, $parent) {
287
+        // Check whether $sub contains no ".."
288
+        if(strpos($sub, '..') !== false) {
289
+            return false;
290
+        }
291
+
292
+        // Check whether $sub is a subdirectory of $parent
293
+        if (strpos($sub, $parent) === 0) {
294
+            return true;
295
+        }
296
+
297
+        return false;
298
+    }
299
+
300
+    /**
301
+     * Get a list of language files that should be loaded
302
+     *
303
+     * @param string $app
304
+     * @param string $lang
305
+     * @return string[]
306
+     */
307
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
308
+    // FIXME This is also the reason, why it is not in the public interface
309
+    public function getL10nFilesForApp($app, $lang) {
310
+        $languageFiles = [];
311
+
312
+        $i18nDir = $this->findL10nDir($app);
313
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
314
+
315
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
316
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
317
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
318
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
319
+            )
320
+            && file_exists($transFile)) {
321
+            // load the translations file
322
+            $languageFiles[] = $transFile;
323
+        }
324
+
325
+        // merge with translations from theme
326
+        $theme = $this->config->getSystemValue('theme');
327
+        if (!empty($theme)) {
328
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
329
+            if (file_exists($transFile)) {
330
+                $languageFiles[] = $transFile;
331
+            }
332
+        }
333
+
334
+        return $languageFiles;
335
+    }
336
+
337
+    /**
338
+     * find the l10n directory
339
+     *
340
+     * @param string $app App id or empty string for core
341
+     * @return string directory
342
+     */
343
+    protected function findL10nDir($app = null) {
344
+        if (in_array($app, ['core', 'lib', 'settings'])) {
345
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
346
+                return $this->serverRoot . '/' . $app . '/l10n/';
347
+            }
348
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
349
+            // Check if the app is in the app folder
350
+            return \OC_App::getAppPath($app) . '/l10n/';
351
+        }
352
+        return $this->serverRoot . '/core/l10n/';
353
+    }
354
+
355
+
356
+    /**
357
+     * Creates a function from the plural string
358
+     *
359
+     * Parts of the code is copied from Habari:
360
+     * https://github.com/habari/system/blob/master/classes/locale.php
361
+     * @param string $string
362
+     * @return string
363
+     */
364
+    public function createPluralFunction($string) {
365
+        if (isset($this->pluralFunctions[$string])) {
366
+            return $this->pluralFunctions[$string];
367
+        }
368
+
369
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
370
+            // sanitize
371
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
372
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
373
+
374
+            $body = str_replace(
375
+                array( 'plural', 'n', '$n$plurals', ),
376
+                array( '$plural', '$n', '$nplurals', ),
377
+                'nplurals='. $nplurals . '; plural=' . $plural
378
+            );
379
+
380
+            // add parents
381
+            // important since PHP's ternary evaluates from left to right
382
+            $body .= ';';
383
+            $res = '';
384
+            $p = 0;
385
+            for($i = 0; $i < strlen($body); $i++) {
386
+                $ch = $body[$i];
387
+                switch ( $ch ) {
388
+                    case '?':
389
+                        $res .= ' ? (';
390
+                        $p++;
391
+                        break;
392
+                    case ':':
393
+                        $res .= ') : (';
394
+                        break;
395
+                    case ';':
396
+                        $res .= str_repeat( ')', $p ) . ';';
397
+                        $p = 0;
398
+                        break;
399
+                    default:
400
+                        $res .= $ch;
401
+                }
402
+            }
403
+
404
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
405
+            $function = create_function('$n', $body);
406
+            $this->pluralFunctions[$string] = $function;
407
+            return $function;
408
+        } else {
409
+            // default: one plural form for all cases but n==1 (english)
410
+            $function = create_function(
411
+                '$n',
412
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
413
+            );
414
+            $this->pluralFunctions[$string] = $function;
415
+            return $function;
416
+        }
417
+    }
418 418
 }
Please login to merge, or discard this patch.
settings/personal.php 3 patches
Indentation   +111 added lines, -111 removed lines patch added patch discarded remove patch
@@ -41,9 +41,9 @@  discard block
 block discarded – undo
41 41
 $defaults = \OC::$server->getThemingDefaults();
42 42
 $certificateManager = \OC::$server->getCertificateManager();
43 43
 $accountManager = new \OC\Accounts\AccountManager(
44
-	\OC::$server->getDatabaseConnection(),
45
-	\OC::$server->getEventDispatcher(),
46
-	\OC::$server->getJobList()
44
+    \OC::$server->getDatabaseConnection(),
45
+    \OC::$server->getEventDispatcher(),
46
+    \OC::$server->getJobList()
47 47
 );
48 48
 $config = \OC::$server->getConfig();
49 49
 $urlGenerator = \OC::$server->getURLGenerator();
@@ -75,78 +75,78 @@  discard block
 block discarded – undo
75 75
 
76 76
 $forceLanguage = $config->getSystemValue('force_language', false);
77 77
 if ($forceLanguage === false) {
78
-	$userLang=$config->getUserValue( OC_User::getUser(), 'core', 'lang', \OC::$server->getL10NFactory()->findLanguage() );
79
-	$languageCodes = \OC::$server->getL10NFactory()->findAvailableLanguages();
80
-
81
-	// array of common languages
82
-	$commonLangCodes = array(
83
-		'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
84
-	);
85
-
86
-	$languages=array();
87
-	$commonLanguages = array();
88
-	foreach($languageCodes as $lang) {
89
-		$l = \OC::$server->getL10N('settings', $lang);
90
-		// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
91
-		$potentialName = (string) $l->t('__language_name__');
92
-		if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
93
-			$ln = array('code' => $lang, 'name' => $potentialName);
94
-		} elseif ($lang === 'en') {
95
-			$ln = ['code' => $lang, 'name' => 'English (US)'];
96
-		}else{//fallback to language code
97
-			$ln=array('code'=>$lang, 'name'=>$lang);
98
-		}
99
-
100
-		// put appropriate languages into appropriate arrays, to print them sorted
101
-		// used language -> common languages -> divider -> other languages
102
-		if ($lang === $userLang) {
103
-			$userLang = $ln;
104
-		} elseif (in_array($lang, $commonLangCodes)) {
105
-			$commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
106
-		} else {
107
-			$languages[]=$ln;
108
-		}
109
-	}
110
-
111
-	// if user language is not available but set somehow: show the actual code as name
112
-	if (!is_array($userLang)) {
113
-		$userLang = [
114
-			'code' => $userLang,
115
-			'name' => $userLang,
116
-		];
117
-	}
118
-
119
-	ksort($commonLanguages);
120
-
121
-	// sort now by displayed language not the iso-code
122
-	usort( $languages, function ($a, $b) {
123
-		if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
124
-			// If a doesn't have a name, but b does, list b before a
125
-			return 1;
126
-		}
127
-		if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
128
-			// If a does have a name, but b doesn't, list a before b
129
-			return -1;
130
-		}
131
-		// Otherwise compare the names
132
-		return strcmp($a['name'], $b['name']);
133
-	});
78
+    $userLang=$config->getUserValue( OC_User::getUser(), 'core', 'lang', \OC::$server->getL10NFactory()->findLanguage() );
79
+    $languageCodes = \OC::$server->getL10NFactory()->findAvailableLanguages();
80
+
81
+    // array of common languages
82
+    $commonLangCodes = array(
83
+        'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
84
+    );
85
+
86
+    $languages=array();
87
+    $commonLanguages = array();
88
+    foreach($languageCodes as $lang) {
89
+        $l = \OC::$server->getL10N('settings', $lang);
90
+        // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
91
+        $potentialName = (string) $l->t('__language_name__');
92
+        if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
93
+            $ln = array('code' => $lang, 'name' => $potentialName);
94
+        } elseif ($lang === 'en') {
95
+            $ln = ['code' => $lang, 'name' => 'English (US)'];
96
+        }else{//fallback to language code
97
+            $ln=array('code'=>$lang, 'name'=>$lang);
98
+        }
99
+
100
+        // put appropriate languages into appropriate arrays, to print them sorted
101
+        // used language -> common languages -> divider -> other languages
102
+        if ($lang === $userLang) {
103
+            $userLang = $ln;
104
+        } elseif (in_array($lang, $commonLangCodes)) {
105
+            $commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
106
+        } else {
107
+            $languages[]=$ln;
108
+        }
109
+    }
110
+
111
+    // if user language is not available but set somehow: show the actual code as name
112
+    if (!is_array($userLang)) {
113
+        $userLang = [
114
+            'code' => $userLang,
115
+            'name' => $userLang,
116
+        ];
117
+    }
118
+
119
+    ksort($commonLanguages);
120
+
121
+    // sort now by displayed language not the iso-code
122
+    usort( $languages, function ($a, $b) {
123
+        if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
124
+            // If a doesn't have a name, but b does, list b before a
125
+            return 1;
126
+        }
127
+        if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
128
+            // If a does have a name, but b doesn't, list a before b
129
+            return -1;
130
+        }
131
+        // Otherwise compare the names
132
+        return strcmp($a['name'], $b['name']);
133
+    });
134 134
 }
135 135
 
136 136
 //links to clients
137 137
 $clients = array(
138
-	'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
139
-	'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
140
-	'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
138
+    'desktop' => $config->getSystemValue('customclient_desktop', $defaults->getSyncClientUrl()),
139
+    'android' => $config->getSystemValue('customclient_android', $defaults->getAndroidClientUrl()),
140
+    'ios'     => $config->getSystemValue('customclient_ios', $defaults->getiOSClientUrl())
141 141
 );
142 142
 
143 143
 // only show root certificate import if external storages are enabled
144 144
 $enableCertImport = false;
145 145
 $externalStorageEnabled = \OC::$server->getAppManager()->isEnabledForUser('files_external');
146 146
 if ($externalStorageEnabled) {
147
-	/** @var \OCA\Files_External\Service\BackendService $backendService */
148
-	$backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
149
-	$enableCertImport = $backendService->isUserMountingAllowed();
147
+    /** @var \OCA\Files_External\Service\BackendService $backendService */
148
+    $backendService = \OC_Mount_Config::$app->getContainer()->query('\OCA\Files_External\Service\BackendService');
149
+    $enableCertImport = $backendService->isUserMountingAllowed();
150 150
 }
151 151
 
152 152
 
@@ -155,9 +155,9 @@  discard block
 block discarded – undo
155 155
 $tmpl = new OC_Template( 'settings', 'personal', 'user');
156 156
 $tmpl->assign('usage', OC_Helper::humanFileSize($storageInfo['used']));
157 157
 if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
158
-	$totalSpace = $l->t('Unlimited');
158
+    $totalSpace = $l->t('Unlimited');
159 159
 } else {
160
-	$totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
160
+    $totalSpace = OC_Helper::humanFileSize($storageInfo['total']);
161 161
 }
162 162
 
163 163
 $uid = $user->getUID();
@@ -169,9 +169,9 @@  discard block
 block discarded – undo
169 169
 $tmpl->assign('clients', $clients);
170 170
 $tmpl->assign('email', $userData[\OC\Accounts\AccountManager::PROPERTY_EMAIL]['value']);
171 171
 if ($forceLanguage === false) {
172
-	$tmpl->assign('languages', $languages);
173
-	$tmpl->assign('commonlanguages', $commonLanguages);
174
-	$tmpl->assign('activelanguage', $userLang);
172
+    $tmpl->assign('languages', $languages);
173
+    $tmpl->assign('commonlanguages', $commonLanguages);
174
+    $tmpl->assign('activelanguage', $userLang);
175 175
 }
176 176
 $tmpl->assign('passwordChangeSupported', OC_User::canUserChangePassword(OC_User::getUser()));
177 177
 $tmpl->assign('displayNameChangeSupported', OC_User::canUserChangeDisplayName(OC_User::getUser()));
@@ -198,18 +198,18 @@  discard block
 block discarded – undo
198 198
 
199 199
 foreach ($needVerifyMessage as $property) {
200 200
 
201
-	switch ($userData[$property]['verified']) {
202
-		case \OC\Accounts\AccountManager::VERIFIED:
203
-			$message = $l->t('Verifying');
204
-			break;
205
-		case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
206
-			$message = $l->t('Verifying …');
207
-			break;
208
-		default:
209
-			$message = $l->t('Verify');
210
-	}
211
-
212
-	$tmpl->assign($property . 'Message', $message);
201
+    switch ($userData[$property]['verified']) {
202
+        case \OC\Accounts\AccountManager::VERIFIED:
203
+            $message = $l->t('Verifying');
204
+            break;
205
+        case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
206
+            $message = $l->t('Verifying …');
207
+            break;
208
+        default:
209
+            $message = $l->t('Verify');
210
+    }
211
+
212
+    $tmpl->assign($property . 'Message', $message);
213 213
 }
214 214
 
215 215
 $tmpl->assign('avatarChangeSupported', OC_User::canUserChangeAvatar(OC_User::getUser()));
@@ -220,9 +220,9 @@  discard block
 block discarded – undo
220 220
 $federatedFileSharingEnabled = \OC::$server->getAppManager()->isEnabledForUser('federatedfilesharing');
221 221
 $lookupServerUploadEnabled = false;
222 222
 if ($federatedFileSharingEnabled) {
223
-	$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
224
-	$shareProvider = $federatedFileSharing->getFederatedShareProvider();
225
-	$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
223
+    $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
224
+    $shareProvider = $federatedFileSharing->getFederatedShareProvider();
225
+    $lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
226 226
 }
227 227
 
228 228
 $tmpl->assign('lookupServerUploadEnabled', $lookupServerUploadEnabled);
@@ -244,35 +244,35 @@  discard block
 block discarded – undo
244 244
 
245 245
 // add bottom hardcoded forms from the template
246 246
 if ($enableCertImport) {
247
-	$certificatesTemplate = new OC_Template('settings', 'certificates');
248
-	$certificatesTemplate->assign('type', 'personal');
249
-	$certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
250
-	$certificatesTemplate->assign('certs', $certificateManager->listCertificates());
251
-	$certificatesTemplate->assign('urlGenerator', $urlGenerator);
252
-	$forms[] = $certificatesTemplate->fetchPage();
247
+    $certificatesTemplate = new OC_Template('settings', 'certificates');
248
+    $certificatesTemplate->assign('type', 'personal');
249
+    $certificatesTemplate->assign('uploadRoute', 'settings.Certificate.addPersonalRootCertificate');
250
+    $certificatesTemplate->assign('certs', $certificateManager->listCertificates());
251
+    $certificatesTemplate->assign('urlGenerator', $urlGenerator);
252
+    $forms[] = $certificatesTemplate->fetchPage();
253 253
 }
254 254
 
255 255
 $formsMap = array_map(function($form){
256
-	if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
257
-		$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
258
-		$sectionName = str_replace('</h2>', '', $sectionName);
259
-		if (strpos($regs['class'], 'data-anchor-name') !== false) {
260
-			preg_match('%.*data-anchor-name="(?P<anchor>[^"]*)"%i', $regs['class'], $matches);
261
-			$anchor = $matches['anchor'];
262
-		} else {
263
-			$anchor = strtolower($sectionName);
264
-			$anchor = str_replace(' ', '-', $anchor);
265
-		}
266
-
267
-		return array(
268
-			'anchor' => $anchor,
269
-			'section-name' => $sectionName,
270
-			'form' => $form
271
-		);
272
-	}
273
-	return array(
274
-		'form' => $form
275
-	);
256
+    if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
257
+        $sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
258
+        $sectionName = str_replace('</h2>', '', $sectionName);
259
+        if (strpos($regs['class'], 'data-anchor-name') !== false) {
260
+            preg_match('%.*data-anchor-name="(?P<anchor>[^"]*)"%i', $regs['class'], $matches);
261
+            $anchor = $matches['anchor'];
262
+        } else {
263
+            $anchor = strtolower($sectionName);
264
+            $anchor = str_replace(' ', '-', $anchor);
265
+        }
266
+
267
+        return array(
268
+            'anchor' => $anchor,
269
+            'section-name' => $sectionName,
270
+            'form' => $form
271
+        );
272
+    }
273
+    return array(
274
+        'form' => $form
275
+    );
276 276
 }, $forms);
277 277
 
278 278
 $formsAndMore = array_merge($formsAndMore, $formsMap);
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 OC_Util::addScript('settings', 'federationscopemenu');
58 58
 OC_Util::addScript('settings', 'personal');
59 59
 OC_Util::addScript('settings', 'certificates');
60
-OC_Util::addStyle( 'settings', 'settings' );
60
+OC_Util::addStyle('settings', 'settings');
61 61
 \OC_Util::addVendorScript('strengthify/jquery.strengthify');
62 62
 \OC_Util::addVendorStyle('strengthify/strengthify');
63 63
 \OC_Util::addScript('files', 'jquery.fileupload');
@@ -69,13 +69,13 @@  discard block
 block discarded – undo
69 69
 // Highlight navigation entry
70 70
 OC::$server->getNavigationManager()->setActiveEntry('personal');
71 71
 
72
-$storageInfo=OC_Helper::getStorageInfo('/');
72
+$storageInfo = OC_Helper::getStorageInfo('/');
73 73
 
74 74
 $user = OC::$server->getUserManager()->get(OC_User::getUser());
75 75
 
76 76
 $forceLanguage = $config->getSystemValue('force_language', false);
77 77
 if ($forceLanguage === false) {
78
-	$userLang=$config->getUserValue( OC_User::getUser(), 'core', 'lang', \OC::$server->getL10NFactory()->findLanguage() );
78
+	$userLang = $config->getUserValue(OC_User::getUser(), 'core', 'lang', \OC::$server->getL10NFactory()->findLanguage());
79 79
 	$languageCodes = \OC::$server->getL10NFactory()->findAvailableLanguages();
80 80
 
81 81
 	// array of common languages
@@ -83,18 +83,18 @@  discard block
 block discarded – undo
83 83
 		'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it', 'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
84 84
 	);
85 85
 
86
-	$languages=array();
86
+	$languages = array();
87 87
 	$commonLanguages = array();
88
-	foreach($languageCodes as $lang) {
88
+	foreach ($languageCodes as $lang) {
89 89
 		$l = \OC::$server->getL10N('settings', $lang);
90 90
 		// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
91 91
 		$potentialName = (string) $l->t('__language_name__');
92
-		if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
92
+		if ($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
93 93
 			$ln = array('code' => $lang, 'name' => $potentialName);
94 94
 		} elseif ($lang === 'en') {
95 95
 			$ln = ['code' => $lang, 'name' => 'English (US)'];
96
-		}else{//fallback to language code
97
-			$ln=array('code'=>$lang, 'name'=>$lang);
96
+		} else {//fallback to language code
97
+			$ln = array('code'=>$lang, 'name'=>$lang);
98 98
 		}
99 99
 
100 100
 		// put appropriate languages into appropriate arrays, to print them sorted
@@ -102,9 +102,9 @@  discard block
 block discarded – undo
102 102
 		if ($lang === $userLang) {
103 103
 			$userLang = $ln;
104 104
 		} elseif (in_array($lang, $commonLangCodes)) {
105
-			$commonLanguages[array_search($lang, $commonLangCodes)]=$ln;
105
+			$commonLanguages[array_search($lang, $commonLangCodes)] = $ln;
106 106
 		} else {
107
-			$languages[]=$ln;
107
+			$languages[] = $ln;
108 108
 		}
109 109
 	}
110 110
 
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	ksort($commonLanguages);
120 120
 
121 121
 	// sort now by displayed language not the iso-code
122
-	usort( $languages, function ($a, $b) {
122
+	usort($languages, function($a, $b) {
123 123
 		if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
124 124
 			// If a doesn't have a name, but b does, list b before a
125 125
 			return 1;
@@ -152,7 +152,7 @@  discard block
 block discarded – undo
152 152
 
153 153
 // Return template
154 154
 $l = \OC::$server->getL10N('settings');
155
-$tmpl = new OC_Template( 'settings', 'personal', 'user');
155
+$tmpl = new OC_Template('settings', 'personal', 'user');
156 156
 $tmpl->assign('usage', OC_Helper::humanFileSize($storageInfo['used']));
157 157
 if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) {
158 158
 	$totalSpace = $l->t('Unlimited');
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
 			$message = $l->t('Verify');
210 210
 	}
211 211
 
212
-	$tmpl->assign($property . 'Message', $message);
212
+	$tmpl->assign($property.'Message', $message);
213 213
 }
214 214
 
215 215
 $tmpl->assign('avatarChangeSupported', OC_User::canUserChangeAvatar(OC_User::getUser()));
@@ -235,11 +235,11 @@  discard block
 block discarded – undo
235 235
 
236 236
 // add hardcoded forms from the template
237 237
 $formsAndMore = [];
238
-$formsAndMore[]= ['anchor' => 'personal-settings', 'section-name' => $l->t('Personal info')];
239
-$formsAndMore[]= ['anchor' => 'security', 'section-name' => $l->t('Security')];
240
-$formsAndMore[]= ['anchor' => 'clientsbox', 'section-name' => $l->t('Sync clients')];
238
+$formsAndMore[] = ['anchor' => 'personal-settings', 'section-name' => $l->t('Personal info')];
239
+$formsAndMore[] = ['anchor' => 'security', 'section-name' => $l->t('Security')];
240
+$formsAndMore[] = ['anchor' => 'clientsbox', 'section-name' => $l->t('Sync clients')];
241 241
 
242
-$forms=OC_App::getForms('personal');
242
+$forms = OC_App::getForms('personal');
243 243
 
244 244
 
245 245
 // add bottom hardcoded forms from the template
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 	$forms[] = $certificatesTemplate->fetchPage();
253 253
 }
254 254
 
255
-$formsMap = array_map(function($form){
255
+$formsMap = array_map(function($form) {
256 256
 	if (preg_match('%(<h2(?P<class>[^>]*)>.*?</h2>)%i', $form, $regs)) {
257 257
 		$sectionName = str_replace('<h2'.$regs['class'].'>', '', $regs[0]);
258 258
 		$sectionName = str_replace('</h2>', '', $sectionName);
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -93,7 +93,7 @@
 block discarded – undo
93 93
 			$ln = array('code' => $lang, 'name' => $potentialName);
94 94
 		} elseif ($lang === 'en') {
95 95
 			$ln = ['code' => $lang, 'name' => 'English (US)'];
96
-		}else{//fallback to language code
96
+		} else{//fallback to language code
97 97
 			$ln=array('code'=>$lang, 'name'=>$lang);
98 98
 		}
99 99
 
Please login to merge, or discard this patch.
settings/routes.php 1 patch
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -36,77 +36,77 @@
 block discarded – undo
36 36
 
37 37
 $application = new Application();
38 38
 $application->registerRoutes($this, [
39
-	'resources' => [
40
-		'users' => ['url' => '/settings/users/users'],
41
-		'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
-	],
43
-	'routes' => [
44
-		['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
-		['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
-		['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
-		['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
-		['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
-		['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
-		['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
-		['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
-		['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
-		['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
-		['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
-		['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
-		['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
57
-		['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
58
-		['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
59
-		['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
60
-		['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
61
-		['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
62
-		['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
63
-		['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
64
-		['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
65
-		['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
-		['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
67
-		['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
-		['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
69
-		['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
70
-		['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
71
-		['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
72
-		['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
-		['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
-		['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
-		['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
-		['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
-	]
39
+    'resources' => [
40
+        'users' => ['url' => '/settings/users/users'],
41
+        'AuthSettings' => ['url' => '/settings/personal/authtokens'],
42
+    ],
43
+    'routes' => [
44
+        ['name' => 'MailSettings#setMailSettings', 'url' => '/settings/admin/mailsettings', 'verb' => 'POST'],
45
+        ['name' => 'MailSettings#storeCredentials', 'url' => '/settings/admin/mailsettings/credentials', 'verb' => 'POST'],
46
+        ['name' => 'MailSettings#sendTestMail', 'url' => '/settings/admin/mailtest', 'verb' => 'POST'],
47
+        ['name' => 'Encryption#startMigration', 'url' => '/settings/admin/startmigration', 'verb' => 'POST'],
48
+        ['name' => 'AppSettings#listCategories', 'url' => '/settings/apps/categories', 'verb' => 'GET'],
49
+        ['name' => 'AppSettings#viewApps', 'url' => '/settings/apps', 'verb' => 'GET'],
50
+        ['name' => 'AppSettings#listApps', 'url' => '/settings/apps/list', 'verb' => 'GET'],
51
+        ['name' => 'SecuritySettings#trustedDomains', 'url' => '/settings/admin/security/trustedDomains', 'verb' => 'POST'],
52
+        ['name' => 'Users#setDisplayName', 'url' => '/settings/users/{username}/displayName', 'verb' => 'POST'],
53
+        ['name' => 'Users#setEMailAddress', 'url' => '/settings/users/{id}/mailAddress', 'verb' => 'PUT'],
54
+        ['name' => 'Users#setUserSettings', 'url' => '/settings/users/{username}/settings', 'verb' => 'PUT'],
55
+        ['name' => 'Users#getVerificationCode', 'url' => '/settings/users/{account}/verify', 'verb' => 'GET'],
56
+        ['name' => 'Users#setEnabled', 'url' => '/settings/users/{id}/setEnabled', 'verb' => 'POST'],
57
+        ['name' => 'Users#stats', 'url' => '/settings/users/stats', 'verb' => 'GET'],
58
+        ['name' => 'LogSettings#setLogLevel', 'url' => '/settings/admin/log/level', 'verb' => 'POST'],
59
+        ['name' => 'LogSettings#getEntries', 'url' => '/settings/admin/log/entries', 'verb' => 'GET'],
60
+        ['name' => 'LogSettings#download', 'url' => '/settings/admin/log/download', 'verb' => 'GET'],
61
+        ['name' => 'CheckSetup#check', 'url' => '/settings/ajax/checksetup', 'verb' => 'GET'],
62
+        ['name' => 'CheckSetup#getFailedIntegrityCheckFiles', 'url' => '/settings/integrity/failed', 'verb' => 'GET'],
63
+        ['name' => 'CheckSetup#rescanFailedIntegrityCheck', 'url' => '/settings/integrity/rescan', 'verb' => 'GET'],
64
+        ['name' => 'Certificate#addPersonalRootCertificate', 'url' => '/settings/personal/certificate', 'verb' => 'POST'],
65
+        ['name' => 'Certificate#removePersonalRootCertificate', 'url' => '/settings/personal/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
66
+        ['name' => 'Certificate#addSystemRootCertificate', 'url' => '/settings/admin/certificate', 'verb' => 'POST'],
67
+        ['name' => 'Certificate#removeSystemRootCertificate', 'url' => '/settings/admin/certificate/{certificateIdentifier}', 'verb' => 'DELETE'],
68
+        ['name' => 'AdminSettings#index', 'url' => '/settings/admin/{section}', 'verb' => 'GET', 'defaults' => ['section' => 'server']],
69
+        ['name' => 'AdminSettings#form', 'url' => '/settings/admin/{section}', 'verb' => 'GET'],
70
+        ['name' => 'ChangePassword#changePersonalPassword', 'url' => '/settings/personal/changepassword', 'verb' => 'POST'],
71
+        ['name' => 'ChangePassword#changeUserPassword', 'url' => '/settings/users/changepassword', 'verb' => 'POST'],
72
+        ['name' => 'Groups#index', 'url' => '/settings/users/groups', 'verb' => 'GET'],
73
+        ['name' => 'Groups#show', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'GET'],
74
+        ['name' => 'Groups#create', 'url' => '/settings/users/groups', 'verb' => 'POST'],
75
+        ['name' => 'Groups#update', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'PUT'],
76
+        ['name' => 'Groups#destroy', 'url' => '/settings/users/groups/{id}', 'requirements' => ['id' => '[^?]*'], 'verb' => 'DELETE'],
77
+    ]
78 78
 ]);
79 79
 
80 80
 /** @var $this \OCP\Route\IRouter */
81 81
 
82 82
 // Settings pages
83 83
 $this->create('settings_help', '/settings/help')
84
-	->actionInclude('settings/help.php');
84
+    ->actionInclude('settings/help.php');
85 85
 $this->create('settings_personal', '/settings/personal')
86
-	->actionInclude('settings/personal.php');
86
+    ->actionInclude('settings/personal.php');
87 87
 $this->create('settings_users', '/settings/users')
88
-	->actionInclude('settings/users.php');
88
+    ->actionInclude('settings/users.php');
89 89
 // Settings ajax actions
90 90
 // users
91 91
 $this->create('settings_ajax_setquota', '/settings/ajax/setquota.php')
92
-	->actionInclude('settings/ajax/setquota.php');
92
+    ->actionInclude('settings/ajax/setquota.php');
93 93
 $this->create('settings_ajax_togglegroups', '/settings/ajax/togglegroups.php')
94
-	->actionInclude('settings/ajax/togglegroups.php');
94
+    ->actionInclude('settings/ajax/togglegroups.php');
95 95
 $this->create('settings_ajax_togglesubadmins', '/settings/ajax/togglesubadmins.php')
96
-	->actionInclude('settings/ajax/togglesubadmins.php');
96
+    ->actionInclude('settings/ajax/togglesubadmins.php');
97 97
 $this->create('settings_ajax_changegorupname', '/settings/ajax/changegroupname.php')
98
-	->actionInclude('settings/ajax/changegroupname.php');
98
+    ->actionInclude('settings/ajax/changegroupname.php');
99 99
 // apps
100 100
 $this->create('settings_ajax_enableapp', '/settings/ajax/enableapp.php')
101
-	->actionInclude('settings/ajax/enableapp.php');
101
+    ->actionInclude('settings/ajax/enableapp.php');
102 102
 $this->create('settings_ajax_disableapp', '/settings/ajax/disableapp.php')
103
-	->actionInclude('settings/ajax/disableapp.php');
103
+    ->actionInclude('settings/ajax/disableapp.php');
104 104
 $this->create('settings_ajax_updateapp', '/settings/ajax/updateapp.php')
105
-	->actionInclude('settings/ajax/updateapp.php');
105
+    ->actionInclude('settings/ajax/updateapp.php');
106 106
 $this->create('settings_ajax_uninstallapp', '/settings/ajax/uninstallapp.php')
107
-	->actionInclude('settings/ajax/uninstallapp.php');
107
+    ->actionInclude('settings/ajax/uninstallapp.php');
108 108
 $this->create('settings_ajax_navigationdetect', '/settings/ajax/navigationdetect.php')
109
-	->actionInclude('settings/ajax/navigationdetect.php');
109
+    ->actionInclude('settings/ajax/navigationdetect.php');
110 110
 // admin
111 111
 $this->create('settings_ajax_excludegroups', '/settings/ajax/excludegroups.php')
112
-	->actionInclude('settings/ajax/excludegroups.php');
112
+    ->actionInclude('settings/ajax/excludegroups.php');
Please login to merge, or discard this patch.
settings/templates/personal.php 1 patch
Spacing   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -10,10 +10,10 @@  discard block
 block discarded – undo
10 10
 
11 11
 <div id="app-navigation">
12 12
 	<ul class="with-icon">
13
-	<?php foreach($_['forms'] as $form) {
13
+	<?php foreach ($_['forms'] as $form) {
14 14
 		if (isset($form['anchor'])) {
15
-			$anchor = '#' . $form['anchor'];
16
-			$class = 'nav-icon-' . $form['anchor'];
15
+			$anchor = '#'.$form['anchor'];
16
+			$class = 'nav-icon-'.$form['anchor'];
17 17
 			$sectionName = $form['section-name'];
18 18
 			print_unescaped(sprintf("<li><a href='%s' class='%s'>%s</a></li>", \OCP\Util::sanitizeHTML($anchor),
19 19
 			\OCP\Util::sanitizeHTML($class), \OCP\Util::sanitizeHTML($sectionName)));
@@ -25,15 +25,15 @@  discard block
 block discarded – undo
25 25
 <div id="app-content">
26 26
 
27 27
 <div id="quota" class="section">
28
-	<div style="width:<?php p($_['usage_relative']);?>%"
29
-		<?php if($_['usage_relative'] > 80): ?> class="quota-warning" <?php endif; ?>>
28
+	<div style="width:<?php p($_['usage_relative']); ?>%"
29
+		<?php if ($_['usage_relative'] > 80): ?> class="quota-warning" <?php endif; ?>>
30 30
 		<p id="quotatext">
31 31
 			<?php if ($_['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED): ?>
32 32
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong>',
33
-					[$_['usage'], $_['total_space']]));?>
33
+					[$_['usage'], $_['total_space']])); ?>
34 34
 			<?php else: ?>
35 35
 				<?php print_unescaped($l->t('You are using <strong>%s</strong> of <strong>%s</strong> (<strong>%s %%</strong>)',
36
-					[$_['usage'], $_['total_space'],  $_['usage_relative']]));?>
36
+					[$_['usage'], $_['total_space'], $_['usage_relative']])); ?>
37 37
 			<?php endif ?>
38 38
 		</p>
39 39
 	</div>
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 			</div>
68 68
 		</div>
69 69
 		<span class="icon-checkmark hidden"/>
70
-		<?php if($_['lookupServerUploadEnabled']) { ?>
70
+		<?php if ($_['lookupServerUploadEnabled']) { ?>
71 71
 		<input type="hidden" id="avatarscope" value="<?php p($_['avatarScope']) ?>">
72 72
 		<?php } ?>
73 73
 	</form>
@@ -81,11 +81,11 @@  discard block
 block discarded – undo
81 81
 				<span class="icon-password"/>
82 82
 			</h2>
83 83
 			<input type="text" id="displayname" name="displayname"
84
-				<?php if(!$_['displayNameChangeSupported']) { print_unescaped('disabled="1"'); } ?>
84
+				<?php if (!$_['displayNameChangeSupported']) { print_unescaped('disabled="1"'); } ?>
85 85
 				value="<?php p($_['displayName']) ?>"
86 86
 				autocomplete="on" autocapitalize="none" autocorrect="off" />
87 87
 			<span class="icon-checkmark hidden"/>
88
-			<?php if($_['lookupServerUploadEnabled']) { ?>
88
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
89 89
 			<input type="hidden" id="displaynamescope" value="<?php p($_['displayNameScope']) ?>">
90 90
 			<?php } ?>
91 91
 		</form>
@@ -96,10 +96,10 @@  discard block
 block discarded – undo
96 96
 				<label for="email"><?php p($l->t('Email')); ?></label>
97 97
 				<span class="icon-password"/>
98 98
 			</h2>
99
-			<div class="verify <?php if ($_['email'] === ''  || $_['emailScope'] !== 'public') p('hidden'); ?>">
99
+			<div class="verify <?php if ($_['email'] === '' || $_['emailScope'] !== 'public') p('hidden'); ?>">
100 100
 				<img id="verify-email" title="<?php p($_['emailMessage']); ?>" data-status="<?php p($_['emailVerification']) ?>" src="
101 101
 				<?php
102
-				switch($_['emailVerification']) {
102
+				switch ($_['emailVerification']) {
103 103
 					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
104 104
 						p(image_path('core', 'actions/verifying.svg'));
105 105
 						break;
@@ -111,16 +111,16 @@  discard block
 block discarded – undo
111 111
 				}
112 112
 				?>">
113 113
 			</div>
114
-			<input type="email" name="email" id="email" value="<?php if(!$_['displayNameChangeSupported'] && empty($_['email'])) p($l->t('No email address set')); else p($_['email']); ?>"
115
-				<?php if(!$_['displayNameChangeSupported']) { print_unescaped('disabled="1"'); } ?>
114
+			<input type="email" name="email" id="email" value="<?php if (!$_['displayNameChangeSupported'] && empty($_['email'])) p($l->t('No email address set')); else p($_['email']); ?>"
115
+				<?php if (!$_['displayNameChangeSupported']) { print_unescaped('disabled="1"'); } ?>
116 116
 				placeholder="<?php p($l->t('Your email address')) ?>"
117 117
 				autocomplete="on" autocapitalize="none" autocorrect="off" />
118
-			<?php if($_['displayNameChangeSupported']) { ?>
118
+			<?php if ($_['displayNameChangeSupported']) { ?>
119 119
 				<br />
120 120
 				<em><?php p($l->t('For password reset and notifications')); ?></em>
121 121
 			<?php } ?>
122 122
 			<span class="icon-checkmark hidden"/>
123
-			<?php if($_['lookupServerUploadEnabled']) { ?>
123
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
124 124
 			<input type="hidden" id="emailscope" value="<?php p($_['emailScope']) ?>">
125 125
 			<?php } ?>
126 126
 		</form>
@@ -132,12 +132,12 @@  discard block
 block discarded – undo
132 132
 				<label for="phone"><?php p($l->t('Phone number')); ?></label>
133 133
 				<span class="icon-password"/>
134 134
 			</h2>
135
-			<input type="tel" id="phone" name="phone" <?php if(!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"'); ?>
135
+			<input type="tel" id="phone" name="phone" <?php if (!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"'); ?>
136 136
 				   value="<?php p($_['phone']) ?>"
137 137
 				   placeholder="<?php p($l->t('Your phone number')); ?>"
138 138
 			       autocomplete="on" autocapitalize="none" autocorrect="off" />
139 139
 			<span class="icon-checkmark hidden"/>
140
-			<?php if($_['lookupServerUploadEnabled']) { ?>
140
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
141 141
 			<input type="hidden" id="phonescope" value="<?php p($_['phoneScope']) ?>">
142 142
 			<?php } ?>
143 143
 		</form>
@@ -150,12 +150,12 @@  discard block
 block discarded – undo
150 150
 				<label for="address"><?php p($l->t('Address')); ?></label>
151 151
 				<span class="icon-password"/>
152 152
 			</h2>
153
-			<input type="text" id="address" name="address" <?php if(!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"');  ?>
153
+			<input type="text" id="address" name="address" <?php if (!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"'); ?>
154 154
 				   placeholder="<?php p($l->t('Your postal address')); ?>"
155 155
 				   value="<?php p($_['address']) ?>"
156 156
 				   autocomplete="on" autocapitalize="none" autocorrect="off" />
157 157
 			<span class="icon-checkmark hidden"/>
158
-			<?php if($_['lookupServerUploadEnabled']) { ?>
158
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
159 159
 			<input type="hidden" id="addressscope" value="<?php p($_['addressScope']) ?>">
160 160
 			<?php } ?>
161 161
 		</form>
@@ -168,11 +168,11 @@  discard block
 block discarded – undo
168 168
 				<label for="website"><?php p($l->t('Website')); ?></label>
169 169
 				<span class="icon-password"/>
170 170
 			</h2>
171
-			<?php if($_['lookupServerUploadEnabled']) { ?>
172
-			<div class="verify <?php if ($_['website'] === ''  || $_['websiteScope'] !== 'public') p('hidden'); ?>">
171
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
172
+			<div class="verify <?php if ($_['website'] === '' || $_['websiteScope'] !== 'public') p('hidden'); ?>">
173 173
 				<img id="verify-website" title="<?php p($_['websiteMessage']); ?>" data-status="<?php p($_['websiteVerification']) ?>" src="
174 174
 				<?php
175
-				switch($_['websiteVerification']) {
175
+				switch ($_['websiteVerification']) {
176 176
 					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
177 177
 						p(image_path('core', 'actions/verifying.svg'));
178 178
 						break;
@@ -183,13 +183,13 @@  discard block
 block discarded – undo
183 183
 						p(image_path('core', 'actions/verify.svg'));
184 184
 				}
185 185
 				?>"
186
-				<?php if($_['websiteVerification'] === \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS || $_['websiteVerification'] === \OC\Accounts\AccountManager::NOT_VERIFIED) print_unescaped(' class="verify-action"') ?>
186
+				<?php if ($_['websiteVerification'] === \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS || $_['websiteVerification'] === \OC\Accounts\AccountManager::NOT_VERIFIED) print_unescaped(' class="verify-action"') ?>
187 187
 				>
188 188
 				<div class="verification-dialog popovermenu bubble menu">
189 189
 					<div class="verification-dialog-content">
190 190
 						<p class="explainVerification"></p>
191 191
 						<p class="verificationCode"></p>
192
-						<p><?php p($l->t('It can take up to 24 hours before the account is displayed as verified.'));?></p>
192
+						<p><?php p($l->t('It can take up to 24 hours before the account is displayed as verified.')); ?></p>
193 193
 					</div>
194 194
 				</div>
195 195
 			</div>
@@ -197,10 +197,10 @@  discard block
 block discarded – undo
197 197
 			<input type="text" name="website" id="website" value="<?php p($_['website']); ?>"
198 198
 			       placeholder="<?php p($l->t('Link https://…')); ?>"
199 199
 			       autocomplete="on" autocapitalize="none" autocorrect="off"
200
-				   <?php if(!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"');  ?>
200
+				   <?php if (!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"'); ?>
201 201
 			/>
202 202
 			<span class="icon-checkmark hidden"/>
203
-			<?php if($_['lookupServerUploadEnabled']) { ?>
203
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
204 204
 			<input type="hidden" id="websitescope" value="<?php p($_['websiteScope']) ?>">
205 205
 			<?php } ?>
206 206
 		</form>
@@ -213,11 +213,11 @@  discard block
 block discarded – undo
213 213
 				<label for="twitter"><?php p($l->t('Twitter')); ?></label>
214 214
 				<span class="icon-password"/>
215 215
 			</h2>
216
-			<?php if($_['lookupServerUploadEnabled']) { ?>
217
-			<div class="verify <?php if ($_['twitter'] === ''  || $_['twitterScope'] !== 'public') p('hidden'); ?>">
216
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
217
+			<div class="verify <?php if ($_['twitter'] === '' || $_['twitterScope'] !== 'public') p('hidden'); ?>">
218 218
 				<img id="verify-twitter" title="<?php p($_['twitterMessage']); ?>" data-status="<?php p($_['twitterVerification']) ?>" src="
219 219
 				<?php
220
-				switch($_['twitterVerification']) {
220
+				switch ($_['twitterVerification']) {
221 221
 					case \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS:
222 222
 						p(image_path('core', 'actions/verifying.svg'));
223 223
 						break;
@@ -228,13 +228,13 @@  discard block
 block discarded – undo
228 228
 						p(image_path('core', 'actions/verify.svg'));
229 229
 				}
230 230
 				?>"
231
-				<?php if($_['twitterVerification'] === \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS || $_['twitterVerification'] === \OC\Accounts\AccountManager::NOT_VERIFIED) print_unescaped(' class="verify-action"') ?>
231
+				<?php if ($_['twitterVerification'] === \OC\Accounts\AccountManager::VERIFICATION_IN_PROGRESS || $_['twitterVerification'] === \OC\Accounts\AccountManager::NOT_VERIFIED) print_unescaped(' class="verify-action"') ?>
232 232
 				>
233 233
 				<div class="verification-dialog popovermenu bubble menu">
234 234
 					<div class="verification-dialog-content">
235 235
 						<p class="explainVerification"></p>
236 236
 						<p class="verificationCode"></p>
237
-						<p><?php p($l->t('It can take up to 24 hours before the account is displayed as verified.'));?></p>
237
+						<p><?php p($l->t('It can take up to 24 hours before the account is displayed as verified.')); ?></p>
238 238
 					</div>
239 239
 				</div>
240 240
 			</div>
@@ -242,10 +242,10 @@  discard block
 block discarded – undo
242 242
 			<input type="text" name="twitter" id="twitter" value="<?php p($_['twitter']); ?>"
243 243
 				   placeholder="<?php p($l->t('Twitter handle @…')); ?>"
244 244
 				   autocomplete="on" autocapitalize="none" autocorrect="off"
245
-				   <?php if(!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"');  ?>
245
+				   <?php if (!$_['lookupServerUploadEnabled']) print_unescaped('disabled="1"'); ?>
246 246
 			/>
247 247
 			<span class="icon-checkmark hidden"/>
248
-			<?php if($_['lookupServerUploadEnabled']) { ?>
248
+			<?php if ($_['lookupServerUploadEnabled']) { ?>
249 249
 			<input type="hidden" id="twitterscope" value="<?php p($_['twitterScope']) ?>">
250 250
 			<?php } ?>
251 251
 		</form>
@@ -266,19 +266,19 @@  discard block
 block discarded – undo
266 266
 </div>
267 267
 
268 268
 <?php
269
-if($_['passwordChangeSupported']) {
269
+if ($_['passwordChangeSupported']) {
270 270
 	script('jquery-showpassword');
271 271
 ?>
272 272
 <form id="passwordform" class="section">
273
-	<h2 class="inlineblock"><?php p($l->t('Password'));?></h2>
273
+	<h2 class="inlineblock"><?php p($l->t('Password')); ?></h2>
274 274
 	<div id="password-error-msg" class="msg success inlineblock" style="display: none;">Saved</div>
275 275
 	<br>
276 276
 	<label for="pass1" class="hidden-visually"><?php p($l->t('Current password')); ?>: </label>
277 277
 	<input type="password" id="pass1" name="oldpassword"
278
-		placeholder="<?php p($l->t('Current password'));?>"
278
+		placeholder="<?php p($l->t('Current password')); ?>"
279 279
 		autocomplete="off" autocapitalize="none" autocorrect="off" />
280 280
 	<div class="personal-show-container">
281
-		<label for="pass2" class="hidden-visually"><?php p($l->t('New password'));?>: </label>
281
+		<label for="pass2" class="hidden-visually"><?php p($l->t('New password')); ?>: </label>
282 282
 		<input type="password" id="pass2" name="newpassword"
283 283
 			placeholder="<?php p($l->t('New password')); ?>"
284 284
 			data-typetoggle="#personal-show"
@@ -295,45 +295,45 @@  discard block
 block discarded – undo
295 295
 <?php if (isset($_['activelanguage'])) { ?>
296 296
 <form id="language" class="section">
297 297
 	<h2>
298
-		<label for="languageinput"><?php p($l->t('Language'));?></label>
298
+		<label for="languageinput"><?php p($l->t('Language')); ?></label>
299 299
 	</h2>
300
-	<select id="languageinput" name="lang" data-placeholder="<?php p($l->t('Language'));?>">
301
-		<option value="<?php p($_['activelanguage']['code']);?>">
302
-			<?php p($_['activelanguage']['name']);?>
300
+	<select id="languageinput" name="lang" data-placeholder="<?php p($l->t('Language')); ?>">
301
+		<option value="<?php p($_['activelanguage']['code']); ?>">
302
+			<?php p($_['activelanguage']['name']); ?>
303 303
 		</option>
304
-		<?php foreach($_['commonlanguages'] as $language):?>
305
-			<option value="<?php p($language['code']);?>">
306
-				<?php p($language['name']);?>
304
+		<?php foreach ($_['commonlanguages'] as $language):?>
305
+			<option value="<?php p($language['code']); ?>">
306
+				<?php p($language['name']); ?>
307 307
 			</option>
308
-		<?php endforeach;?>
308
+		<?php endforeach; ?>
309 309
 		<optgroup label="––––––––––"></optgroup>
310
-		<?php foreach($_['languages'] as $language):?>
311
-			<option value="<?php p($language['code']);?>">
312
-				<?php p($language['name']);?>
310
+		<?php foreach ($_['languages'] as $language):?>
311
+			<option value="<?php p($language['code']); ?>">
312
+				<?php p($language['name']); ?>
313 313
 			</option>
314
-		<?php endforeach;?>
314
+		<?php endforeach; ?>
315 315
 	</select>
316 316
 	<a href="https://www.transifex.com/nextcloud/nextcloud/"
317 317
 		target="_blank" rel="noreferrer">
318
-		<em><?php p($l->t('Help translate'));?></em>
318
+		<em><?php p($l->t('Help translate')); ?></em>
319 319
 	</a>
320 320
 </form>
321 321
 <?php } ?>
322 322
 
323 323
 
324 324
 <div id="clientsbox" class="section clientsbox">
325
-	<h2><?php p($l->t('Get the apps to sync your files'));?></h2>
325
+	<h2><?php p($l->t('Get the apps to sync your files')); ?></h2>
326 326
 	<a href="<?php p($_['clients']['desktop']); ?>" rel="noreferrer" target="_blank">
327 327
 		<img src="<?php print_unescaped(image_path('core', 'desktopapp.svg')); ?>"
328
-			 alt="<?php p($l->t('Desktop client'));?>" />
328
+			 alt="<?php p($l->t('Desktop client')); ?>" />
329 329
 	</a>
330 330
 	<a href="<?php p($_['clients']['android']); ?>" rel="noreferrer" target="_blank">
331 331
 		<img src="<?php print_unescaped(image_path('core', 'googleplay.png')); ?>"
332
-			 alt="<?php p($l->t('Android app'));?>" />
332
+			 alt="<?php p($l->t('Android app')); ?>" />
333 333
 	</a>
334 334
 	<a href="<?php p($_['clients']['ios']); ?>" rel="noreferrer" target="_blank">
335 335
 		<img src="<?php print_unescaped(image_path('core', 'appstore.svg')); ?>"
336
-			 alt="<?php p($l->t('iOS app'));?>" />
336
+			 alt="<?php p($l->t('iOS app')); ?>" />
337 337
 	</a>
338 338
 
339 339
 		<p>
@@ -349,19 +349,19 @@  discard block
 block discarded – undo
349 349
 				$l->t('If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!'))); ?>
350 350
 		</p>
351 351
 
352
-	<?php if(OC_APP::isEnabled('firstrunwizard')) {?>
353
-		<p><a class="button" href="#" id="showWizard"><?php p($l->t('Show First Run Wizard again'));?></a></p>
352
+	<?php if (OC_APP::isEnabled('firstrunwizard')) {?>
353
+		<p><a class="button" href="#" id="showWizard"><?php p($l->t('Show First Run Wizard again')); ?></a></p>
354 354
 	<?php }?>
355 355
 </div>
356 356
 
357 357
 <div id="security" class="section">
358
-	<h2><?php p($l->t('Security'));?></h2>
359
-	<p class="settings-hint hidden-when-empty"><?php p($l->t('Web, desktop, mobile clients and app specific passwords that currently have access to your account.'));?></p>
358
+	<h2><?php p($l->t('Security')); ?></h2>
359
+	<p class="settings-hint hidden-when-empty"><?php p($l->t('Web, desktop, mobile clients and app specific passwords that currently have access to your account.')); ?></p>
360 360
 	<table class="icon-loading">
361 361
 		<thead class="token-list-header">
362 362
 			<tr>
363
-				<th><?php p($l->t('Device'));?></th>
364
-				<th><?php p($l->t('Last activity'));?></th>
363
+				<th><?php p($l->t('Device')); ?></th>
364
+				<th><?php p($l->t('Last activity')); ?></th>
365 365
 				<th></th>
366 366
 			</tr>
367 367
 		</thead>
@@ -369,8 +369,8 @@  discard block
 block discarded – undo
369 369
 		</tbody>
370 370
 	</table>
371 371
 
372
-	<h3><?php p($l->t('App passwords'));?></h3>
373
-	<p class="settings-hint"><?php p($l->t('Here you can generate individual passwords for apps so you don’t have to give out your password. You can revoke them individually too.'));?></p>
372
+	<h3><?php p($l->t('App passwords')); ?></h3>
373
+	<p class="settings-hint"><?php p($l->t('Here you can generate individual passwords for apps so you don’t have to give out your password. You can revoke them individually too.')); ?></p>
374 374
 
375 375
 	<div id="app-password-form">
376 376
 		<input id="app-password-name" type="text" placeholder="<?php p($l->t('App name')); ?>">
@@ -394,14 +394,14 @@  discard block
 block discarded – undo
394 394
 	</div>
395 395
 </div>
396 396
 
397
-<?php foreach($_['forms'] as $form) {
397
+<?php foreach ($_['forms'] as $form) {
398 398
 	if (isset($form['form'])) {?>
399
-	<div id="<?php isset($form['anchor']) ? p($form['anchor']) : p('');?>"><?php print_unescaped($form['form']);?></div>
399
+	<div id="<?php isset($form['anchor']) ? p($form['anchor']) : p(''); ?>"><?php print_unescaped($form['form']); ?></div>
400 400
 	<?php }
401 401
 };?>
402 402
 
403 403
 <div class="section">
404
-	<h2><?php p($l->t('Version'));?></h2>
404
+	<h2><?php p($l->t('Version')); ?></h2>
405 405
 	<p><a href="<?php print_unescaped($theme->getBaseUrl()); ?>" target="_blank"><?php p($theme->getTitle()); ?></a> <?php p(OC_Util::getHumanVersion()) ?></p>
406 406
 	<p><?php include('settings.development.notice.php'); ?></p>
407 407
 </div>
Please login to merge, or discard this patch.
apps/provisioning_api/lib/Controller/UsersController.php 2 patches
Indentation   +782 added lines, -782 removed lines patch added patch discarded remove patch
@@ -49,786 +49,786 @@
 block discarded – undo
49 49
 
50 50
 class UsersController extends OCSController {
51 51
 
52
-	/** @var IUserManager */
53
-	private $userManager;
54
-	/** @var IConfig */
55
-	private $config;
56
-	/** @var IAppManager */
57
-	private $appManager;
58
-	/** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
59
-	private $groupManager;
60
-	/** @var IUserSession */
61
-	private $userSession;
62
-	/** @var AccountManager */
63
-	private $accountManager;
64
-	/** @var ILogger */
65
-	private $logger;
66
-	/** @var IFactory */
67
-	private $l10nFactory;
68
-	/** @var NewUserMailHelper */
69
-	private $newUserMailHelper;
70
-
71
-	/**
72
-	 * @param string $appName
73
-	 * @param IRequest $request
74
-	 * @param IUserManager $userManager
75
-	 * @param IConfig $config
76
-	 * @param IAppManager $appManager
77
-	 * @param IGroupManager $groupManager
78
-	 * @param IUserSession $userSession
79
-	 * @param AccountManager $accountManager
80
-	 * @param ILogger $logger
81
-	 * @param IFactory $l10nFactory
82
-	 * @param NewUserMailHelper $newUserMailHelper
83
-	 */
84
-	public function __construct($appName,
85
-								IRequest $request,
86
-								IUserManager $userManager,
87
-								IConfig $config,
88
-								IAppManager $appManager,
89
-								IGroupManager $groupManager,
90
-								IUserSession $userSession,
91
-								AccountManager $accountManager,
92
-								ILogger $logger,
93
-								IFactory $l10nFactory,
94
-								NewUserMailHelper $newUserMailHelper) {
95
-		parent::__construct($appName, $request);
96
-
97
-		$this->userManager = $userManager;
98
-		$this->config = $config;
99
-		$this->appManager = $appManager;
100
-		$this->groupManager = $groupManager;
101
-		$this->userSession = $userSession;
102
-		$this->accountManager = $accountManager;
103
-		$this->logger = $logger;
104
-		$this->l10nFactory = $l10nFactory;
105
-		$this->newUserMailHelper = $newUserMailHelper;
106
-	}
107
-
108
-	/**
109
-	 * @NoAdminRequired
110
-	 *
111
-	 * returns a list of users
112
-	 *
113
-	 * @param string $search
114
-	 * @param int $limit
115
-	 * @param int $offset
116
-	 * @return DataResponse
117
-	 */
118
-	public function getUsers($search = '', $limit = null, $offset = null) {
119
-		$user = $this->userSession->getUser();
120
-		$users = [];
121
-
122
-		// Admin? Or SubAdmin?
123
-		$uid = $user->getUID();
124
-		$subAdminManager = $this->groupManager->getSubAdmin();
125
-		if($this->groupManager->isAdmin($uid)){
126
-			$users = $this->userManager->search($search, $limit, $offset);
127
-		} else if ($subAdminManager->isSubAdmin($user)) {
128
-			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
129
-			foreach ($subAdminOfGroups as $key => $group) {
130
-				$subAdminOfGroups[$key] = $group->getGID();
131
-			}
132
-
133
-			if($offset === null) {
134
-				$offset = 0;
135
-			}
136
-
137
-			$users = [];
138
-			foreach ($subAdminOfGroups as $group) {
139
-				$users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
140
-			}
141
-
142
-			$users = array_slice($users, $offset, $limit);
143
-		}
144
-
145
-		$users = array_keys($users);
146
-
147
-		return new DataResponse([
148
-			'users' => $users
149
-		]);
150
-	}
151
-
152
-	/**
153
-	 * @PasswordConfirmationRequired
154
-	 * @NoAdminRequired
155
-	 *
156
-	 * @param string $userid
157
-	 * @param string $password
158
-	 * @param array $groups
159
-	 * @return DataResponse
160
-	 * @throws OCSException
161
-	 */
162
-	public function addUser($userid, $password, $groups = null) {
163
-		$user = $this->userSession->getUser();
164
-		$isAdmin = $this->groupManager->isAdmin($user->getUID());
165
-		$subAdminManager = $this->groupManager->getSubAdmin();
166
-
167
-		if($this->userManager->userExists($userid)) {
168
-			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
169
-			throw new OCSException('User already exists', 102);
170
-		}
171
-
172
-		if(is_array($groups)) {
173
-			foreach ($groups as $group) {
174
-				if(!$this->groupManager->groupExists($group)) {
175
-					throw new OCSException('group '.$group.' does not exist', 104);
176
-				}
177
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
-					throw new OCSException('insufficient privileges for group '. $group, 105);
179
-				}
180
-			}
181
-		} else {
182
-			if(!$isAdmin) {
183
-				throw new OCSException('no group specified (required for subadmins)', 106);
184
-			}
185
-		}
186
-
187
-		try {
188
-			$newUser = $this->userManager->createUser($userid, $password);
189
-			$this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
190
-
191
-			if (is_array($groups)) {
192
-				foreach ($groups as $group) {
193
-					$this->groupManager->get($group)->addUser($newUser);
194
-					$this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
195
-				}
196
-			}
197
-			return new DataResponse();
198
-		} catch (\Exception $e) {
199
-			$this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
200
-			throw new OCSException('Bad request', 101);
201
-		}
202
-	}
203
-
204
-	/**
205
-	 * @NoAdminRequired
206
-	 * @NoSubAdminRequired
207
-	 *
208
-	 * gets user info
209
-	 *
210
-	 * @param string $userId
211
-	 * @return DataResponse
212
-	 * @throws OCSException
213
-	 */
214
-	public function getUser($userId) {
215
-		$data = $this->getUserData($userId);
216
-		return new DataResponse($data);
217
-	}
218
-
219
-	/**
220
-	 * @NoAdminRequired
221
-	 * @NoSubAdminRequired
222
-	 *
223
-	 * gets user info from the currently logged in user
224
-	 *
225
-	 * @return DataResponse
226
-	 * @throws OCSException
227
-	 */
228
-	public function getCurrentUser() {
229
-		$user = $this->userSession->getUser();
230
-		if ($user) {
231
-			$data =  $this->getUserData($user->getUID());
232
-			// rename "displayname" to "display-name" only for this call to keep
233
-			// the API stable.
234
-			$data['display-name'] = $data['displayname'];
235
-			unset($data['displayname']);
236
-			return new DataResponse($data);
237
-
238
-		}
239
-
240
-		throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
241
-	}
242
-
243
-	/**
244
-	 * creates a array with all user data
245
-	 *
246
-	 * @param $userId
247
-	 * @return array
248
-	 * @throws OCSException
249
-	 */
250
-	protected function getUserData($userId) {
251
-		$currentLoggedInUser = $this->userSession->getUser();
252
-
253
-		$data = [];
254
-
255
-		// Check if the target user exists
256
-		$targetUserObject = $this->userManager->get($userId);
257
-		if($targetUserObject === null) {
258
-			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
259
-		}
260
-
261
-		// Admin? Or SubAdmin?
262
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263
-			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
264
-			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
265
-		} else {
266
-			// Check they are looking up themselves
267
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
269
-			}
270
-		}
271
-
272
-		$userAccount = $this->accountManager->getUser($targetUserObject);
273
-		$groups = $this->groupManager->getUserGroups($targetUserObject);
274
-		$gids = [];
275
-		foreach ($groups as $group) {
276
-			$gids[] = $group->getDisplayName();
277
-		}
278
-
279
-		// Find the data
280
-		$data['id'] = $targetUserObject->getUID();
281
-		$data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
282
-		$data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
283
-		$data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
284
-		$data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
285
-		$data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
286
-		$data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
287
-		$data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
288
-		$data['groups'] = $gids;
289
-		$data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
290
-
291
-		return $data;
292
-	}
293
-
294
-	/**
295
-	 * @NoAdminRequired
296
-	 * @NoSubAdminRequired
297
-	 * @PasswordConfirmationRequired
298
-	 *
299
-	 * edit users
300
-	 *
301
-	 * @param string $userId
302
-	 * @param string $key
303
-	 * @param string $value
304
-	 * @return DataResponse
305
-	 * @throws OCSException
306
-	 * @throws OCSForbiddenException
307
-	 */
308
-	public function editUser($userId, $key, $value) {
309
-		$currentLoggedInUser = $this->userSession->getUser();
310
-
311
-		$targetUser = $this->userManager->get($userId);
312
-		if($targetUser === null) {
313
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
314
-		}
315
-
316
-		$permittedFields = [];
317
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
318
-			// Editing self (display, email)
319
-			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
320
-				$permittedFields[] = 'display';
321
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
322
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
323
-			}
324
-
325
-			$permittedFields[] = 'password';
326
-			if ($this->config->getSystemValue('force_language', false) === false ||
327
-				$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
328
-				$permittedFields[] = 'language';
329
-			}
330
-
331
-			if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
332
-				$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
333
-				$shareProvider = $federatedFileSharing->getFederatedShareProvider();
334
-				if ($shareProvider->isLookupServerUploadEnabled()) {
335
-					$permittedFields[] = AccountManager::PROPERTY_PHONE;
336
-					$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
337
-					$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
338
-					$permittedFields[] = AccountManager::PROPERTY_TWITTER;
339
-				}
340
-			}
341
-
342
-			// If admin they can edit their own quota
343
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344
-				$permittedFields[] = 'quota';
345
-			}
346
-		} else {
347
-			// Check if admin / subadmin
348
-			$subAdminManager = $this->groupManager->getSubAdmin();
349
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350
-			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
351
-				// They have permissions over the user
352
-				$permittedFields[] = 'display';
353
-				$permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
354
-				$permittedFields[] = AccountManager::PROPERTY_EMAIL;
355
-				$permittedFields[] = 'password';
356
-				$permittedFields[] = 'language';
357
-				$permittedFields[] = AccountManager::PROPERTY_PHONE;
358
-				$permittedFields[] = AccountManager::PROPERTY_ADDRESS;
359
-				$permittedFields[] = AccountManager::PROPERTY_WEBSITE;
360
-				$permittedFields[] = AccountManager::PROPERTY_TWITTER;
361
-				$permittedFields[] = 'quota';
362
-			} else {
363
-				// No rights
364
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
365
-			}
366
-		}
367
-		// Check if permitted to edit this field
368
-		if(!in_array($key, $permittedFields)) {
369
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370
-		}
371
-		// Process the edit
372
-		switch($key) {
373
-			case 'display':
374
-			case AccountManager::PROPERTY_DISPLAYNAME:
375
-				$targetUser->setDisplayName($value);
376
-				break;
377
-			case 'quota':
378
-				$quota = $value;
379
-				if($quota !== 'none' && $quota !== 'default') {
380
-					if (is_numeric($quota)) {
381
-						$quota = (float) $quota;
382
-					} else {
383
-						$quota = \OCP\Util::computerFileSize($quota);
384
-					}
385
-					if ($quota === false) {
386
-						throw new OCSException('Invalid quota value '.$value, 103);
387
-					}
388
-					if($quota === 0) {
389
-						$quota = 'default';
390
-					}else if($quota === -1) {
391
-						$quota = 'none';
392
-					} else {
393
-						$quota = \OCP\Util::humanFileSize($quota);
394
-					}
395
-				}
396
-				$targetUser->setQuota($quota);
397
-				break;
398
-			case 'password':
399
-				$targetUser->setPassword($value);
400
-				break;
401
-			case 'language':
402
-				$languagesCodes = $this->l10nFactory->findAvailableLanguages();
403
-				if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
404
-					throw new OCSException('Invalid language', 102);
405
-				}
406
-				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
407
-				break;
408
-			case AccountManager::PROPERTY_EMAIL:
409
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
410
-					$targetUser->setEMailAddress($value);
411
-				} else {
412
-					throw new OCSException('', 102);
413
-				}
414
-				break;
415
-			case AccountManager::PROPERTY_PHONE:
416
-			case AccountManager::PROPERTY_ADDRESS:
417
-			case AccountManager::PROPERTY_WEBSITE:
418
-			case AccountManager::PROPERTY_TWITTER:
419
-				$userAccount = $this->accountManager->getUser($targetUser);
420
-				if ($userAccount[$key]['value'] !== $value) {
421
-					$userAccount[$key]['value'] = $value;
422
-					$this->accountManager->updateUser($targetUser, $userAccount);
423
-				}
424
-				break;
425
-			default:
426
-				throw new OCSException('', 103);
427
-		}
428
-		return new DataResponse();
429
-	}
430
-
431
-	/**
432
-	 * @PasswordConfirmationRequired
433
-	 * @NoAdminRequired
434
-	 *
435
-	 * @param string $userId
436
-	 * @return DataResponse
437
-	 * @throws OCSException
438
-	 * @throws OCSForbiddenException
439
-	 */
440
-	public function deleteUser($userId) {
441
-		$currentLoggedInUser = $this->userSession->getUser();
442
-
443
-		$targetUser = $this->userManager->get($userId);
444
-
445
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
446
-			throw new OCSException('', 101);
447
-		}
448
-
449
-		// If not permitted
450
-		$subAdminManager = $this->groupManager->getSubAdmin();
451
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
452
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
453
-		}
454
-
455
-		// Go ahead with the delete
456
-		if($targetUser->delete()) {
457
-			return new DataResponse();
458
-		} else {
459
-			throw new OCSException('', 101);
460
-		}
461
-	}
462
-
463
-	/**
464
-	 * @PasswordConfirmationRequired
465
-	 * @NoAdminRequired
466
-	 *
467
-	 * @param string $userId
468
-	 * @return DataResponse
469
-	 * @throws OCSException
470
-	 * @throws OCSForbiddenException
471
-	 */
472
-	public function disableUser($userId) {
473
-		return $this->setEnabled($userId, false);
474
-	}
475
-
476
-	/**
477
-	 * @PasswordConfirmationRequired
478
-	 * @NoAdminRequired
479
-	 *
480
-	 * @param string $userId
481
-	 * @return DataResponse
482
-	 * @throws OCSException
483
-	 * @throws OCSForbiddenException
484
-	 */
485
-	public function enableUser($userId) {
486
-		return $this->setEnabled($userId, true);
487
-	}
488
-
489
-	/**
490
-	 * @param string $userId
491
-	 * @param bool $value
492
-	 * @return DataResponse
493
-	 * @throws OCSException
494
-	 * @throws OCSForbiddenException
495
-	 */
496
-	private function setEnabled($userId, $value) {
497
-		$currentLoggedInUser = $this->userSession->getUser();
498
-
499
-		$targetUser = $this->userManager->get($userId);
500
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
501
-			throw new OCSException('', 101);
502
-		}
503
-
504
-		// If not permitted
505
-		$subAdminManager = $this->groupManager->getSubAdmin();
506
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
507
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
508
-		}
509
-
510
-		// enable/disable the user now
511
-		$targetUser->setEnabled($value);
512
-		return new DataResponse();
513
-	}
514
-
515
-	/**
516
-	 * @NoAdminRequired
517
-	 * @NoSubAdminRequired
518
-	 *
519
-	 * @param string $userId
520
-	 * @return DataResponse
521
-	 * @throws OCSException
522
-	 */
523
-	public function getUsersGroups($userId) {
524
-		$loggedInUser = $this->userSession->getUser();
525
-
526
-		$targetUser = $this->userManager->get($userId);
527
-		if($targetUser === null) {
528
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
529
-		}
530
-
531
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
532
-			// Self lookup or admin lookup
533
-			return new DataResponse([
534
-				'groups' => $this->groupManager->getUserGroupIds($targetUser)
535
-			]);
536
-		} else {
537
-			$subAdminManager = $this->groupManager->getSubAdmin();
538
-
539
-			// Looking up someone else
540
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
541
-				// Return the group that the method caller is subadmin of for the user in question
542
-				/** @var IGroup[] $getSubAdminsGroups */
543
-				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
544
-				foreach ($getSubAdminsGroups as $key => $group) {
545
-					$getSubAdminsGroups[$key] = $group->getGID();
546
-				}
547
-				$groups = array_intersect(
548
-					$getSubAdminsGroups,
549
-					$this->groupManager->getUserGroupIds($targetUser)
550
-				);
551
-				return new DataResponse(['groups' => $groups]);
552
-			} else {
553
-				// Not permitted
554
-				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
555
-			}
556
-		}
557
-
558
-	}
559
-
560
-	/**
561
-	 * @PasswordConfirmationRequired
562
-	 * @NoAdminRequired
563
-	 *
564
-	 * @param string $userId
565
-	 * @param string $groupid
566
-	 * @return DataResponse
567
-	 * @throws OCSException
568
-	 */
569
-	public function addToGroup($userId, $groupid = '') {
570
-		if($groupid === '') {
571
-			throw new OCSException('', 101);
572
-		}
573
-
574
-		$group = $this->groupManager->get($groupid);
575
-		$targetUser = $this->userManager->get($userId);
576
-		if($group === null) {
577
-			throw new OCSException('', 102);
578
-		}
579
-		if($targetUser === null) {
580
-			throw new OCSException('', 103);
581
-		}
582
-
583
-		// If they're not an admin, check they are a subadmin of the group in question
584
-		$loggedInUser = $this->userSession->getUser();
585
-		$subAdminManager = $this->groupManager->getSubAdmin();
586
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
587
-			throw new OCSException('', 104);
588
-		}
589
-
590
-		// Add user to group
591
-		$group->addUser($targetUser);
592
-		return new DataResponse();
593
-	}
594
-
595
-	/**
596
-	 * @PasswordConfirmationRequired
597
-	 * @NoAdminRequired
598
-	 *
599
-	 * @param string $userId
600
-	 * @param string $groupid
601
-	 * @return DataResponse
602
-	 * @throws OCSException
603
-	 */
604
-	public function removeFromGroup($userId, $groupid) {
605
-		$loggedInUser = $this->userSession->getUser();
606
-
607
-		if($groupid === null) {
608
-			throw new OCSException('', 101);
609
-		}
610
-
611
-		$group = $this->groupManager->get($groupid);
612
-		if($group === null) {
613
-			throw new OCSException('', 102);
614
-		}
615
-
616
-		$targetUser = $this->userManager->get($userId);
617
-		if($targetUser === null) {
618
-			throw new OCSException('', 103);
619
-		}
620
-
621
-		// If they're not an admin, check they are a subadmin of the group in question
622
-		$subAdminManager = $this->groupManager->getSubAdmin();
623
-		if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
624
-			throw new OCSException('', 104);
625
-		}
626
-
627
-		// Check they aren't removing themselves from 'admin' or their 'subadmin; group
628
-		if ($targetUser->getUID() === $loggedInUser->getUID()) {
629
-			if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
630
-				if ($group->getGID() === 'admin') {
631
-					throw new OCSException('Cannot remove yourself from the admin group', 105);
632
-				}
633
-			} else {
634
-				// Not an admin, so the user must be a subadmin of this group, but that is not allowed.
635
-				throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
636
-			}
637
-
638
-		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
639
-			/** @var IGroup[] $subAdminGroups */
640
-			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
641
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
642
-				return $subAdminGroup->getGID();
643
-			}, $subAdminGroups);
644
-			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
645
-			$userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
646
-
647
-			if (count($userSubAdminGroups) <= 1) {
648
-				// Subadmin must not be able to remove a user from all their subadmin groups.
649
-				throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
650
-			}
651
-		}
652
-
653
-		// Remove user from group
654
-		$group->removeUser($targetUser);
655
-		return new DataResponse();
656
-	}
657
-
658
-	/**
659
-	 * Creates a subadmin
660
-	 *
661
-	 * @PasswordConfirmationRequired
662
-	 *
663
-	 * @param string $userId
664
-	 * @param string $groupid
665
-	 * @return DataResponse
666
-	 * @throws OCSException
667
-	 */
668
-	public function addSubAdmin($userId, $groupid) {
669
-		$group = $this->groupManager->get($groupid);
670
-		$user = $this->userManager->get($userId);
671
-
672
-		// Check if the user exists
673
-		if($user === null) {
674
-			throw new OCSException('User does not exist', 101);
675
-		}
676
-		// Check if group exists
677
-		if($group === null) {
678
-			throw new OCSException('Group does not exist',  102);
679
-		}
680
-		// Check if trying to make subadmin of admin group
681
-		if($group->getGID() === 'admin') {
682
-			throw new OCSException('Cannot create subadmins for admin group', 103);
683
-		}
684
-
685
-		$subAdminManager = $this->groupManager->getSubAdmin();
686
-
687
-		// We cannot be subadmin twice
688
-		if ($subAdminManager->isSubAdminofGroup($user, $group)) {
689
-			return new DataResponse();
690
-		}
691
-		// Go
692
-		if($subAdminManager->createSubAdmin($user, $group)) {
693
-			return new DataResponse();
694
-		} else {
695
-			throw new OCSException('Unknown error occurred', 103);
696
-		}
697
-	}
698
-
699
-	/**
700
-	 * Removes a subadmin from a group
701
-	 *
702
-	 * @PasswordConfirmationRequired
703
-	 *
704
-	 * @param string $userId
705
-	 * @param string $groupid
706
-	 * @return DataResponse
707
-	 * @throws OCSException
708
-	 */
709
-	public function removeSubAdmin($userId, $groupid) {
710
-		$group = $this->groupManager->get($groupid);
711
-		$user = $this->userManager->get($userId);
712
-		$subAdminManager = $this->groupManager->getSubAdmin();
713
-
714
-		// Check if the user exists
715
-		if($user === null) {
716
-			throw new OCSException('User does not exist', 101);
717
-		}
718
-		// Check if the group exists
719
-		if($group === null) {
720
-			throw new OCSException('Group does not exist', 101);
721
-		}
722
-		// Check if they are a subadmin of this said group
723
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
724
-			throw new OCSException('User is not a subadmin of this group', 102);
725
-		}
726
-
727
-		// Go
728
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
729
-			return new DataResponse();
730
-		} else {
731
-			throw new OCSException('Unknown error occurred', 103);
732
-		}
733
-	}
734
-
735
-	/**
736
-	 * Get the groups a user is a subadmin of
737
-	 *
738
-	 * @param string $userId
739
-	 * @return DataResponse
740
-	 * @throws OCSException
741
-	 */
742
-	public function getUserSubAdminGroups($userId) {
743
-		$user = $this->userManager->get($userId);
744
-		// Check if the user exists
745
-		if($user === null) {
746
-			throw new OCSException('User does not exist', 101);
747
-		}
748
-
749
-		// Get the subadmin groups
750
-		$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
751
-		foreach ($groups as $key => $group) {
752
-			$groups[$key] = $group->getGID();
753
-		}
754
-
755
-		if(!$groups) {
756
-			throw new OCSException('Unknown error occurred', 102);
757
-		} else {
758
-			return new DataResponse($groups);
759
-		}
760
-	}
761
-
762
-	/**
763
-	 * @param string $userId
764
-	 * @return array
765
-	 * @throws \OCP\Files\NotFoundException
766
-	 */
767
-	protected function fillStorageInfo($userId) {
768
-		try {
769
-			\OC_Util::tearDownFS();
770
-			\OC_Util::setupFS($userId);
771
-			$storage = OC_Helper::getStorageInfo('/');
772
-			$data = [
773
-				'free' => $storage['free'],
774
-				'used' => $storage['used'],
775
-				'total' => $storage['total'],
776
-				'relative' => $storage['relative'],
777
-				'quota' => $storage['quota'],
778
-			];
779
-		} catch (NotFoundException $ex) {
780
-			$data = [];
781
-		}
782
-		return $data;
783
-	}
784
-
785
-	/**
786
-	 * @NoAdminRequired
787
-	 * @PasswordConfirmationRequired
788
-	 *
789
-	 * resend welcome message
790
-	 *
791
-	 * @param string $userId
792
-	 * @return DataResponse
793
-	 * @throws OCSException
794
-	 */
795
-	public function resendWelcomeMessage($userId) {
796
-		$currentLoggedInUser = $this->userSession->getUser();
797
-
798
-		$targetUser = $this->userManager->get($userId);
799
-		if($targetUser === null) {
800
-			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
801
-		}
802
-
803
-		// Check if admin / subadmin
804
-		$subAdminManager = $this->groupManager->getSubAdmin();
805
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
806
-			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
807
-			// No rights
808
-			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
809
-		}
810
-
811
-		$email = $targetUser->getEMailAddress();
812
-		if ($email === '' || $email === null) {
813
-			throw new OCSException('Email address not available', 101);
814
-		}
815
-		$username = $targetUser->getUID();
816
-		$lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
817
-		if (!$this->l10nFactory->languageExists('settings', $lang)) {
818
-			$lang = 'en';
819
-		}
820
-
821
-		$l10n = $this->l10nFactory->get('settings', $lang);
822
-
823
-		try {
824
-			$this->newUserMailHelper->setL10N($l10n);
825
-			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
826
-			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
827
-		} catch(\Exception $e) {
828
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
829
-			throw new OCSException('Sending email failed', 102);
830
-		}
831
-
832
-		return new DataResponse();
833
-	}
52
+    /** @var IUserManager */
53
+    private $userManager;
54
+    /** @var IConfig */
55
+    private $config;
56
+    /** @var IAppManager */
57
+    private $appManager;
58
+    /** @var IGroupManager|\OC\Group\Manager */ // FIXME Requires a method that is not on the interface
59
+    private $groupManager;
60
+    /** @var IUserSession */
61
+    private $userSession;
62
+    /** @var AccountManager */
63
+    private $accountManager;
64
+    /** @var ILogger */
65
+    private $logger;
66
+    /** @var IFactory */
67
+    private $l10nFactory;
68
+    /** @var NewUserMailHelper */
69
+    private $newUserMailHelper;
70
+
71
+    /**
72
+     * @param string $appName
73
+     * @param IRequest $request
74
+     * @param IUserManager $userManager
75
+     * @param IConfig $config
76
+     * @param IAppManager $appManager
77
+     * @param IGroupManager $groupManager
78
+     * @param IUserSession $userSession
79
+     * @param AccountManager $accountManager
80
+     * @param ILogger $logger
81
+     * @param IFactory $l10nFactory
82
+     * @param NewUserMailHelper $newUserMailHelper
83
+     */
84
+    public function __construct($appName,
85
+                                IRequest $request,
86
+                                IUserManager $userManager,
87
+                                IConfig $config,
88
+                                IAppManager $appManager,
89
+                                IGroupManager $groupManager,
90
+                                IUserSession $userSession,
91
+                                AccountManager $accountManager,
92
+                                ILogger $logger,
93
+                                IFactory $l10nFactory,
94
+                                NewUserMailHelper $newUserMailHelper) {
95
+        parent::__construct($appName, $request);
96
+
97
+        $this->userManager = $userManager;
98
+        $this->config = $config;
99
+        $this->appManager = $appManager;
100
+        $this->groupManager = $groupManager;
101
+        $this->userSession = $userSession;
102
+        $this->accountManager = $accountManager;
103
+        $this->logger = $logger;
104
+        $this->l10nFactory = $l10nFactory;
105
+        $this->newUserMailHelper = $newUserMailHelper;
106
+    }
107
+
108
+    /**
109
+     * @NoAdminRequired
110
+     *
111
+     * returns a list of users
112
+     *
113
+     * @param string $search
114
+     * @param int $limit
115
+     * @param int $offset
116
+     * @return DataResponse
117
+     */
118
+    public function getUsers($search = '', $limit = null, $offset = null) {
119
+        $user = $this->userSession->getUser();
120
+        $users = [];
121
+
122
+        // Admin? Or SubAdmin?
123
+        $uid = $user->getUID();
124
+        $subAdminManager = $this->groupManager->getSubAdmin();
125
+        if($this->groupManager->isAdmin($uid)){
126
+            $users = $this->userManager->search($search, $limit, $offset);
127
+        } else if ($subAdminManager->isSubAdmin($user)) {
128
+            $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
129
+            foreach ($subAdminOfGroups as $key => $group) {
130
+                $subAdminOfGroups[$key] = $group->getGID();
131
+            }
132
+
133
+            if($offset === null) {
134
+                $offset = 0;
135
+            }
136
+
137
+            $users = [];
138
+            foreach ($subAdminOfGroups as $group) {
139
+                $users = array_merge($users, $this->groupManager->displayNamesInGroup($group, $search));
140
+            }
141
+
142
+            $users = array_slice($users, $offset, $limit);
143
+        }
144
+
145
+        $users = array_keys($users);
146
+
147
+        return new DataResponse([
148
+            'users' => $users
149
+        ]);
150
+    }
151
+
152
+    /**
153
+     * @PasswordConfirmationRequired
154
+     * @NoAdminRequired
155
+     *
156
+     * @param string $userid
157
+     * @param string $password
158
+     * @param array $groups
159
+     * @return DataResponse
160
+     * @throws OCSException
161
+     */
162
+    public function addUser($userid, $password, $groups = null) {
163
+        $user = $this->userSession->getUser();
164
+        $isAdmin = $this->groupManager->isAdmin($user->getUID());
165
+        $subAdminManager = $this->groupManager->getSubAdmin();
166
+
167
+        if($this->userManager->userExists($userid)) {
168
+            $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
169
+            throw new OCSException('User already exists', 102);
170
+        }
171
+
172
+        if(is_array($groups)) {
173
+            foreach ($groups as $group) {
174
+                if(!$this->groupManager->groupExists($group)) {
175
+                    throw new OCSException('group '.$group.' does not exist', 104);
176
+                }
177
+                if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
+                    throw new OCSException('insufficient privileges for group '. $group, 105);
179
+                }
180
+            }
181
+        } else {
182
+            if(!$isAdmin) {
183
+                throw new OCSException('no group specified (required for subadmins)', 106);
184
+            }
185
+        }
186
+
187
+        try {
188
+            $newUser = $this->userManager->createUser($userid, $password);
189
+            $this->logger->info('Successful addUser call with userid: '.$userid, ['app' => 'ocs_api']);
190
+
191
+            if (is_array($groups)) {
192
+                foreach ($groups as $group) {
193
+                    $this->groupManager->get($group)->addUser($newUser);
194
+                    $this->logger->info('Added userid '.$userid.' to group '.$group, ['app' => 'ocs_api']);
195
+                }
196
+            }
197
+            return new DataResponse();
198
+        } catch (\Exception $e) {
199
+            $this->logger->error('Failed addUser attempt with exception: '.$e->getMessage(), ['app' => 'ocs_api']);
200
+            throw new OCSException('Bad request', 101);
201
+        }
202
+    }
203
+
204
+    /**
205
+     * @NoAdminRequired
206
+     * @NoSubAdminRequired
207
+     *
208
+     * gets user info
209
+     *
210
+     * @param string $userId
211
+     * @return DataResponse
212
+     * @throws OCSException
213
+     */
214
+    public function getUser($userId) {
215
+        $data = $this->getUserData($userId);
216
+        return new DataResponse($data);
217
+    }
218
+
219
+    /**
220
+     * @NoAdminRequired
221
+     * @NoSubAdminRequired
222
+     *
223
+     * gets user info from the currently logged in user
224
+     *
225
+     * @return DataResponse
226
+     * @throws OCSException
227
+     */
228
+    public function getCurrentUser() {
229
+        $user = $this->userSession->getUser();
230
+        if ($user) {
231
+            $data =  $this->getUserData($user->getUID());
232
+            // rename "displayname" to "display-name" only for this call to keep
233
+            // the API stable.
234
+            $data['display-name'] = $data['displayname'];
235
+            unset($data['displayname']);
236
+            return new DataResponse($data);
237
+
238
+        }
239
+
240
+        throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
241
+    }
242
+
243
+    /**
244
+     * creates a array with all user data
245
+     *
246
+     * @param $userId
247
+     * @return array
248
+     * @throws OCSException
249
+     */
250
+    protected function getUserData($userId) {
251
+        $currentLoggedInUser = $this->userSession->getUser();
252
+
253
+        $data = [];
254
+
255
+        // Check if the target user exists
256
+        $targetUserObject = $this->userManager->get($userId);
257
+        if($targetUserObject === null) {
258
+            throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
259
+        }
260
+
261
+        // Admin? Or SubAdmin?
262
+        if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263
+            || $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
264
+            $data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
265
+        } else {
266
+            // Check they are looking up themselves
267
+            if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
269
+            }
270
+        }
271
+
272
+        $userAccount = $this->accountManager->getUser($targetUserObject);
273
+        $groups = $this->groupManager->getUserGroups($targetUserObject);
274
+        $gids = [];
275
+        foreach ($groups as $group) {
276
+            $gids[] = $group->getDisplayName();
277
+        }
278
+
279
+        // Find the data
280
+        $data['id'] = $targetUserObject->getUID();
281
+        $data['quota'] = $this->fillStorageInfo($targetUserObject->getUID());
282
+        $data[AccountManager::PROPERTY_EMAIL] = $targetUserObject->getEMailAddress();
283
+        $data[AccountManager::PROPERTY_DISPLAYNAME] = $targetUserObject->getDisplayName();
284
+        $data[AccountManager::PROPERTY_PHONE] = $userAccount[AccountManager::PROPERTY_PHONE]['value'];
285
+        $data[AccountManager::PROPERTY_ADDRESS] = $userAccount[AccountManager::PROPERTY_ADDRESS]['value'];
286
+        $data[AccountManager::PROPERTY_WEBSITE] = $userAccount[AccountManager::PROPERTY_WEBSITE]['value'];
287
+        $data[AccountManager::PROPERTY_TWITTER] = $userAccount[AccountManager::PROPERTY_TWITTER]['value'];
288
+        $data['groups'] = $gids;
289
+        $data['language'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'lang');
290
+
291
+        return $data;
292
+    }
293
+
294
+    /**
295
+     * @NoAdminRequired
296
+     * @NoSubAdminRequired
297
+     * @PasswordConfirmationRequired
298
+     *
299
+     * edit users
300
+     *
301
+     * @param string $userId
302
+     * @param string $key
303
+     * @param string $value
304
+     * @return DataResponse
305
+     * @throws OCSException
306
+     * @throws OCSForbiddenException
307
+     */
308
+    public function editUser($userId, $key, $value) {
309
+        $currentLoggedInUser = $this->userSession->getUser();
310
+
311
+        $targetUser = $this->userManager->get($userId);
312
+        if($targetUser === null) {
313
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
314
+        }
315
+
316
+        $permittedFields = [];
317
+        if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
318
+            // Editing self (display, email)
319
+            if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
320
+                $permittedFields[] = 'display';
321
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
322
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
323
+            }
324
+
325
+            $permittedFields[] = 'password';
326
+            if ($this->config->getSystemValue('force_language', false) === false ||
327
+                $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
328
+                $permittedFields[] = 'language';
329
+            }
330
+
331
+            if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
332
+                $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
333
+                $shareProvider = $federatedFileSharing->getFederatedShareProvider();
334
+                if ($shareProvider->isLookupServerUploadEnabled()) {
335
+                    $permittedFields[] = AccountManager::PROPERTY_PHONE;
336
+                    $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
337
+                    $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
338
+                    $permittedFields[] = AccountManager::PROPERTY_TWITTER;
339
+                }
340
+            }
341
+
342
+            // If admin they can edit their own quota
343
+            if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344
+                $permittedFields[] = 'quota';
345
+            }
346
+        } else {
347
+            // Check if admin / subadmin
348
+            $subAdminManager = $this->groupManager->getSubAdmin();
349
+            if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350
+            || $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
351
+                // They have permissions over the user
352
+                $permittedFields[] = 'display';
353
+                $permittedFields[] = AccountManager::PROPERTY_DISPLAYNAME;
354
+                $permittedFields[] = AccountManager::PROPERTY_EMAIL;
355
+                $permittedFields[] = 'password';
356
+                $permittedFields[] = 'language';
357
+                $permittedFields[] = AccountManager::PROPERTY_PHONE;
358
+                $permittedFields[] = AccountManager::PROPERTY_ADDRESS;
359
+                $permittedFields[] = AccountManager::PROPERTY_WEBSITE;
360
+                $permittedFields[] = AccountManager::PROPERTY_TWITTER;
361
+                $permittedFields[] = 'quota';
362
+            } else {
363
+                // No rights
364
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
365
+            }
366
+        }
367
+        // Check if permitted to edit this field
368
+        if(!in_array($key, $permittedFields)) {
369
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370
+        }
371
+        // Process the edit
372
+        switch($key) {
373
+            case 'display':
374
+            case AccountManager::PROPERTY_DISPLAYNAME:
375
+                $targetUser->setDisplayName($value);
376
+                break;
377
+            case 'quota':
378
+                $quota = $value;
379
+                if($quota !== 'none' && $quota !== 'default') {
380
+                    if (is_numeric($quota)) {
381
+                        $quota = (float) $quota;
382
+                    } else {
383
+                        $quota = \OCP\Util::computerFileSize($quota);
384
+                    }
385
+                    if ($quota === false) {
386
+                        throw new OCSException('Invalid quota value '.$value, 103);
387
+                    }
388
+                    if($quota === 0) {
389
+                        $quota = 'default';
390
+                    }else if($quota === -1) {
391
+                        $quota = 'none';
392
+                    } else {
393
+                        $quota = \OCP\Util::humanFileSize($quota);
394
+                    }
395
+                }
396
+                $targetUser->setQuota($quota);
397
+                break;
398
+            case 'password':
399
+                $targetUser->setPassword($value);
400
+                break;
401
+            case 'language':
402
+                $languagesCodes = $this->l10nFactory->findAvailableLanguages();
403
+                if (!in_array($value, $languagesCodes, true) && $value !== 'en') {
404
+                    throw new OCSException('Invalid language', 102);
405
+                }
406
+                $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
407
+                break;
408
+            case AccountManager::PROPERTY_EMAIL:
409
+                if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
410
+                    $targetUser->setEMailAddress($value);
411
+                } else {
412
+                    throw new OCSException('', 102);
413
+                }
414
+                break;
415
+            case AccountManager::PROPERTY_PHONE:
416
+            case AccountManager::PROPERTY_ADDRESS:
417
+            case AccountManager::PROPERTY_WEBSITE:
418
+            case AccountManager::PROPERTY_TWITTER:
419
+                $userAccount = $this->accountManager->getUser($targetUser);
420
+                if ($userAccount[$key]['value'] !== $value) {
421
+                    $userAccount[$key]['value'] = $value;
422
+                    $this->accountManager->updateUser($targetUser, $userAccount);
423
+                }
424
+                break;
425
+            default:
426
+                throw new OCSException('', 103);
427
+        }
428
+        return new DataResponse();
429
+    }
430
+
431
+    /**
432
+     * @PasswordConfirmationRequired
433
+     * @NoAdminRequired
434
+     *
435
+     * @param string $userId
436
+     * @return DataResponse
437
+     * @throws OCSException
438
+     * @throws OCSForbiddenException
439
+     */
440
+    public function deleteUser($userId) {
441
+        $currentLoggedInUser = $this->userSession->getUser();
442
+
443
+        $targetUser = $this->userManager->get($userId);
444
+
445
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
446
+            throw new OCSException('', 101);
447
+        }
448
+
449
+        // If not permitted
450
+        $subAdminManager = $this->groupManager->getSubAdmin();
451
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
452
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
453
+        }
454
+
455
+        // Go ahead with the delete
456
+        if($targetUser->delete()) {
457
+            return new DataResponse();
458
+        } else {
459
+            throw new OCSException('', 101);
460
+        }
461
+    }
462
+
463
+    /**
464
+     * @PasswordConfirmationRequired
465
+     * @NoAdminRequired
466
+     *
467
+     * @param string $userId
468
+     * @return DataResponse
469
+     * @throws OCSException
470
+     * @throws OCSForbiddenException
471
+     */
472
+    public function disableUser($userId) {
473
+        return $this->setEnabled($userId, false);
474
+    }
475
+
476
+    /**
477
+     * @PasswordConfirmationRequired
478
+     * @NoAdminRequired
479
+     *
480
+     * @param string $userId
481
+     * @return DataResponse
482
+     * @throws OCSException
483
+     * @throws OCSForbiddenException
484
+     */
485
+    public function enableUser($userId) {
486
+        return $this->setEnabled($userId, true);
487
+    }
488
+
489
+    /**
490
+     * @param string $userId
491
+     * @param bool $value
492
+     * @return DataResponse
493
+     * @throws OCSException
494
+     * @throws OCSForbiddenException
495
+     */
496
+    private function setEnabled($userId, $value) {
497
+        $currentLoggedInUser = $this->userSession->getUser();
498
+
499
+        $targetUser = $this->userManager->get($userId);
500
+        if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
501
+            throw new OCSException('', 101);
502
+        }
503
+
504
+        // If not permitted
505
+        $subAdminManager = $this->groupManager->getSubAdmin();
506
+        if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
507
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
508
+        }
509
+
510
+        // enable/disable the user now
511
+        $targetUser->setEnabled($value);
512
+        return new DataResponse();
513
+    }
514
+
515
+    /**
516
+     * @NoAdminRequired
517
+     * @NoSubAdminRequired
518
+     *
519
+     * @param string $userId
520
+     * @return DataResponse
521
+     * @throws OCSException
522
+     */
523
+    public function getUsersGroups($userId) {
524
+        $loggedInUser = $this->userSession->getUser();
525
+
526
+        $targetUser = $this->userManager->get($userId);
527
+        if($targetUser === null) {
528
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
529
+        }
530
+
531
+        if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
532
+            // Self lookup or admin lookup
533
+            return new DataResponse([
534
+                'groups' => $this->groupManager->getUserGroupIds($targetUser)
535
+            ]);
536
+        } else {
537
+            $subAdminManager = $this->groupManager->getSubAdmin();
538
+
539
+            // Looking up someone else
540
+            if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
541
+                // Return the group that the method caller is subadmin of for the user in question
542
+                /** @var IGroup[] $getSubAdminsGroups */
543
+                $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
544
+                foreach ($getSubAdminsGroups as $key => $group) {
545
+                    $getSubAdminsGroups[$key] = $group->getGID();
546
+                }
547
+                $groups = array_intersect(
548
+                    $getSubAdminsGroups,
549
+                    $this->groupManager->getUserGroupIds($targetUser)
550
+                );
551
+                return new DataResponse(['groups' => $groups]);
552
+            } else {
553
+                // Not permitted
554
+                throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
555
+            }
556
+        }
557
+
558
+    }
559
+
560
+    /**
561
+     * @PasswordConfirmationRequired
562
+     * @NoAdminRequired
563
+     *
564
+     * @param string $userId
565
+     * @param string $groupid
566
+     * @return DataResponse
567
+     * @throws OCSException
568
+     */
569
+    public function addToGroup($userId, $groupid = '') {
570
+        if($groupid === '') {
571
+            throw new OCSException('', 101);
572
+        }
573
+
574
+        $group = $this->groupManager->get($groupid);
575
+        $targetUser = $this->userManager->get($userId);
576
+        if($group === null) {
577
+            throw new OCSException('', 102);
578
+        }
579
+        if($targetUser === null) {
580
+            throw new OCSException('', 103);
581
+        }
582
+
583
+        // If they're not an admin, check they are a subadmin of the group in question
584
+        $loggedInUser = $this->userSession->getUser();
585
+        $subAdminManager = $this->groupManager->getSubAdmin();
586
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
587
+            throw new OCSException('', 104);
588
+        }
589
+
590
+        // Add user to group
591
+        $group->addUser($targetUser);
592
+        return new DataResponse();
593
+    }
594
+
595
+    /**
596
+     * @PasswordConfirmationRequired
597
+     * @NoAdminRequired
598
+     *
599
+     * @param string $userId
600
+     * @param string $groupid
601
+     * @return DataResponse
602
+     * @throws OCSException
603
+     */
604
+    public function removeFromGroup($userId, $groupid) {
605
+        $loggedInUser = $this->userSession->getUser();
606
+
607
+        if($groupid === null) {
608
+            throw new OCSException('', 101);
609
+        }
610
+
611
+        $group = $this->groupManager->get($groupid);
612
+        if($group === null) {
613
+            throw new OCSException('', 102);
614
+        }
615
+
616
+        $targetUser = $this->userManager->get($userId);
617
+        if($targetUser === null) {
618
+            throw new OCSException('', 103);
619
+        }
620
+
621
+        // If they're not an admin, check they are a subadmin of the group in question
622
+        $subAdminManager = $this->groupManager->getSubAdmin();
623
+        if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) {
624
+            throw new OCSException('', 104);
625
+        }
626
+
627
+        // Check they aren't removing themselves from 'admin' or their 'subadmin; group
628
+        if ($targetUser->getUID() === $loggedInUser->getUID()) {
629
+            if ($this->groupManager->isAdmin($loggedInUser->getUID())) {
630
+                if ($group->getGID() === 'admin') {
631
+                    throw new OCSException('Cannot remove yourself from the admin group', 105);
632
+                }
633
+            } else {
634
+                // Not an admin, so the user must be a subadmin of this group, but that is not allowed.
635
+                throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105);
636
+            }
637
+
638
+        } else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
639
+            /** @var IGroup[] $subAdminGroups */
640
+            $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
641
+            $subAdminGroups = array_map(function (IGroup $subAdminGroup) {
642
+                return $subAdminGroup->getGID();
643
+            }, $subAdminGroups);
644
+            $userGroups = $this->groupManager->getUserGroupIds($targetUser);
645
+            $userSubAdminGroups = array_intersect($subAdminGroups, $userGroups);
646
+
647
+            if (count($userSubAdminGroups) <= 1) {
648
+                // Subadmin must not be able to remove a user from all their subadmin groups.
649
+                throw new OCSException('Cannot remove user from this group as this is the only remaining group you are a SubAdmin of', 105);
650
+            }
651
+        }
652
+
653
+        // Remove user from group
654
+        $group->removeUser($targetUser);
655
+        return new DataResponse();
656
+    }
657
+
658
+    /**
659
+     * Creates a subadmin
660
+     *
661
+     * @PasswordConfirmationRequired
662
+     *
663
+     * @param string $userId
664
+     * @param string $groupid
665
+     * @return DataResponse
666
+     * @throws OCSException
667
+     */
668
+    public function addSubAdmin($userId, $groupid) {
669
+        $group = $this->groupManager->get($groupid);
670
+        $user = $this->userManager->get($userId);
671
+
672
+        // Check if the user exists
673
+        if($user === null) {
674
+            throw new OCSException('User does not exist', 101);
675
+        }
676
+        // Check if group exists
677
+        if($group === null) {
678
+            throw new OCSException('Group does not exist',  102);
679
+        }
680
+        // Check if trying to make subadmin of admin group
681
+        if($group->getGID() === 'admin') {
682
+            throw new OCSException('Cannot create subadmins for admin group', 103);
683
+        }
684
+
685
+        $subAdminManager = $this->groupManager->getSubAdmin();
686
+
687
+        // We cannot be subadmin twice
688
+        if ($subAdminManager->isSubAdminofGroup($user, $group)) {
689
+            return new DataResponse();
690
+        }
691
+        // Go
692
+        if($subAdminManager->createSubAdmin($user, $group)) {
693
+            return new DataResponse();
694
+        } else {
695
+            throw new OCSException('Unknown error occurred', 103);
696
+        }
697
+    }
698
+
699
+    /**
700
+     * Removes a subadmin from a group
701
+     *
702
+     * @PasswordConfirmationRequired
703
+     *
704
+     * @param string $userId
705
+     * @param string $groupid
706
+     * @return DataResponse
707
+     * @throws OCSException
708
+     */
709
+    public function removeSubAdmin($userId, $groupid) {
710
+        $group = $this->groupManager->get($groupid);
711
+        $user = $this->userManager->get($userId);
712
+        $subAdminManager = $this->groupManager->getSubAdmin();
713
+
714
+        // Check if the user exists
715
+        if($user === null) {
716
+            throw new OCSException('User does not exist', 101);
717
+        }
718
+        // Check if the group exists
719
+        if($group === null) {
720
+            throw new OCSException('Group does not exist', 101);
721
+        }
722
+        // Check if they are a subadmin of this said group
723
+        if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
724
+            throw new OCSException('User is not a subadmin of this group', 102);
725
+        }
726
+
727
+        // Go
728
+        if($subAdminManager->deleteSubAdmin($user, $group)) {
729
+            return new DataResponse();
730
+        } else {
731
+            throw new OCSException('Unknown error occurred', 103);
732
+        }
733
+    }
734
+
735
+    /**
736
+     * Get the groups a user is a subadmin of
737
+     *
738
+     * @param string $userId
739
+     * @return DataResponse
740
+     * @throws OCSException
741
+     */
742
+    public function getUserSubAdminGroups($userId) {
743
+        $user = $this->userManager->get($userId);
744
+        // Check if the user exists
745
+        if($user === null) {
746
+            throw new OCSException('User does not exist', 101);
747
+        }
748
+
749
+        // Get the subadmin groups
750
+        $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
751
+        foreach ($groups as $key => $group) {
752
+            $groups[$key] = $group->getGID();
753
+        }
754
+
755
+        if(!$groups) {
756
+            throw new OCSException('Unknown error occurred', 102);
757
+        } else {
758
+            return new DataResponse($groups);
759
+        }
760
+    }
761
+
762
+    /**
763
+     * @param string $userId
764
+     * @return array
765
+     * @throws \OCP\Files\NotFoundException
766
+     */
767
+    protected function fillStorageInfo($userId) {
768
+        try {
769
+            \OC_Util::tearDownFS();
770
+            \OC_Util::setupFS($userId);
771
+            $storage = OC_Helper::getStorageInfo('/');
772
+            $data = [
773
+                'free' => $storage['free'],
774
+                'used' => $storage['used'],
775
+                'total' => $storage['total'],
776
+                'relative' => $storage['relative'],
777
+                'quota' => $storage['quota'],
778
+            ];
779
+        } catch (NotFoundException $ex) {
780
+            $data = [];
781
+        }
782
+        return $data;
783
+    }
784
+
785
+    /**
786
+     * @NoAdminRequired
787
+     * @PasswordConfirmationRequired
788
+     *
789
+     * resend welcome message
790
+     *
791
+     * @param string $userId
792
+     * @return DataResponse
793
+     * @throws OCSException
794
+     */
795
+    public function resendWelcomeMessage($userId) {
796
+        $currentLoggedInUser = $this->userSession->getUser();
797
+
798
+        $targetUser = $this->userManager->get($userId);
799
+        if($targetUser === null) {
800
+            throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
801
+        }
802
+
803
+        // Check if admin / subadmin
804
+        $subAdminManager = $this->groupManager->getSubAdmin();
805
+        if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
806
+            && !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
807
+            // No rights
808
+            throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
809
+        }
810
+
811
+        $email = $targetUser->getEMailAddress();
812
+        if ($email === '' || $email === null) {
813
+            throw new OCSException('Email address not available', 101);
814
+        }
815
+        $username = $targetUser->getUID();
816
+        $lang = $this->config->getUserValue($username, 'core', 'lang', 'en');
817
+        if (!$this->l10nFactory->languageExists('settings', $lang)) {
818
+            $lang = 'en';
819
+        }
820
+
821
+        $l10n = $this->l10nFactory->get('settings', $lang);
822
+
823
+        try {
824
+            $this->newUserMailHelper->setL10N($l10n);
825
+            $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
826
+            $this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
827
+        } catch(\Exception $e) {
828
+            $this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
829
+            throw new OCSException('Sending email failed', 102);
830
+        }
831
+
832
+        return new DataResponse();
833
+    }
834 834
 }
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
 		// Admin? Or SubAdmin?
123 123
 		$uid = $user->getUID();
124 124
 		$subAdminManager = $this->groupManager->getSubAdmin();
125
-		if($this->groupManager->isAdmin($uid)){
125
+		if ($this->groupManager->isAdmin($uid)) {
126 126
 			$users = $this->userManager->search($search, $limit, $offset);
127 127
 		} else if ($subAdminManager->isSubAdmin($user)) {
128 128
 			$subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user);
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 				$subAdminOfGroups[$key] = $group->getGID();
131 131
 			}
132 132
 
133
-			if($offset === null) {
133
+			if ($offset === null) {
134 134
 				$offset = 0;
135 135
 			}
136 136
 
@@ -164,22 +164,22 @@  discard block
 block discarded – undo
164 164
 		$isAdmin = $this->groupManager->isAdmin($user->getUID());
165 165
 		$subAdminManager = $this->groupManager->getSubAdmin();
166 166
 
167
-		if($this->userManager->userExists($userid)) {
167
+		if ($this->userManager->userExists($userid)) {
168 168
 			$this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']);
169 169
 			throw new OCSException('User already exists', 102);
170 170
 		}
171 171
 
172
-		if(is_array($groups)) {
172
+		if (is_array($groups)) {
173 173
 			foreach ($groups as $group) {
174
-				if(!$this->groupManager->groupExists($group)) {
174
+				if (!$this->groupManager->groupExists($group)) {
175 175
 					throw new OCSException('group '.$group.' does not exist', 104);
176 176
 				}
177
-				if(!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
-					throw new OCSException('insufficient privileges for group '. $group, 105);
177
+				if (!$isAdmin && !$subAdminManager->isSubAdminofGroup($user, $this->groupManager->get($group))) {
178
+					throw new OCSException('insufficient privileges for group '.$group, 105);
179 179
 				}
180 180
 			}
181 181
 		} else {
182
-			if(!$isAdmin) {
182
+			if (!$isAdmin) {
183 183
 				throw new OCSException('no group specified (required for subadmins)', 106);
184 184
 			}
185 185
 		}
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	public function getCurrentUser() {
229 229
 		$user = $this->userSession->getUser();
230 230
 		if ($user) {
231
-			$data =  $this->getUserData($user->getUID());
231
+			$data = $this->getUserData($user->getUID());
232 232
 			// rename "displayname" to "display-name" only for this call to keep
233 233
 			// the API stable.
234 234
 			$data['display-name'] = $data['displayname'];
@@ -254,17 +254,17 @@  discard block
 block discarded – undo
254 254
 
255 255
 		// Check if the target user exists
256 256
 		$targetUserObject = $this->userManager->get($userId);
257
-		if($targetUserObject === null) {
257
+		if ($targetUserObject === null) {
258 258
 			throw new OCSException('The requested user could not be found', \OCP\API::RESPOND_NOT_FOUND);
259 259
 		}
260 260
 
261 261
 		// Admin? Or SubAdmin?
262
-		if($this->groupManager->isAdmin($currentLoggedInUser->getUID())
262
+		if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())
263 263
 			|| $this->groupManager->getSubAdmin()->isUserAccessible($currentLoggedInUser, $targetUserObject)) {
264 264
 			$data['enabled'] = $this->config->getUserValue($targetUserObject->getUID(), 'core', 'enabled', 'true');
265 265
 		} else {
266 266
 			// Check they are looking up themselves
267
-			if($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
267
+			if ($currentLoggedInUser->getUID() !== $targetUserObject->getUID()) {
268 268
 				throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
269 269
 			}
270 270
 		}
@@ -309,12 +309,12 @@  discard block
 block discarded – undo
309 309
 		$currentLoggedInUser = $this->userSession->getUser();
310 310
 
311 311
 		$targetUser = $this->userManager->get($userId);
312
-		if($targetUser === null) {
312
+		if ($targetUser === null) {
313 313
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
314 314
 		}
315 315
 
316 316
 		$permittedFields = [];
317
-		if($targetUser->getUID() === $currentLoggedInUser->getUID()) {
317
+		if ($targetUser->getUID() === $currentLoggedInUser->getUID()) {
318 318
 			// Editing self (display, email)
319 319
 			if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
320 320
 				$permittedFields[] = 'display';
@@ -340,13 +340,13 @@  discard block
 block discarded – undo
340 340
 			}
341 341
 
342 342
 			// If admin they can edit their own quota
343
-			if($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
343
+			if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
344 344
 				$permittedFields[] = 'quota';
345 345
 			}
346 346
 		} else {
347 347
 			// Check if admin / subadmin
348 348
 			$subAdminManager = $this->groupManager->getSubAdmin();
349
-			if($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
349
+			if ($subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
350 350
 			|| $this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
351 351
 				// They have permissions over the user
352 352
 				$permittedFields[] = 'display';
@@ -365,18 +365,18 @@  discard block
 block discarded – undo
365 365
 			}
366 366
 		}
367 367
 		// Check if permitted to edit this field
368
-		if(!in_array($key, $permittedFields)) {
368
+		if (!in_array($key, $permittedFields)) {
369 369
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
370 370
 		}
371 371
 		// Process the edit
372
-		switch($key) {
372
+		switch ($key) {
373 373
 			case 'display':
374 374
 			case AccountManager::PROPERTY_DISPLAYNAME:
375 375
 				$targetUser->setDisplayName($value);
376 376
 				break;
377 377
 			case 'quota':
378 378
 				$quota = $value;
379
-				if($quota !== 'none' && $quota !== 'default') {
379
+				if ($quota !== 'none' && $quota !== 'default') {
380 380
 					if (is_numeric($quota)) {
381 381
 						$quota = (float) $quota;
382 382
 					} else {
@@ -385,9 +385,9 @@  discard block
 block discarded – undo
385 385
 					if ($quota === false) {
386 386
 						throw new OCSException('Invalid quota value '.$value, 103);
387 387
 					}
388
-					if($quota === 0) {
388
+					if ($quota === 0) {
389 389
 						$quota = 'default';
390
-					}else if($quota === -1) {
390
+					} else if ($quota === -1) {
391 391
 						$quota = 'none';
392 392
 					} else {
393 393
 						$quota = \OCP\Util::humanFileSize($quota);
@@ -406,7 +406,7 @@  discard block
 block discarded – undo
406 406
 				$this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value);
407 407
 				break;
408 408
 			case AccountManager::PROPERTY_EMAIL:
409
-				if(filter_var($value, FILTER_VALIDATE_EMAIL)) {
409
+				if (filter_var($value, FILTER_VALIDATE_EMAIL)) {
410 410
 					$targetUser->setEMailAddress($value);
411 411
 				} else {
412 412
 					throw new OCSException('', 102);
@@ -442,18 +442,18 @@  discard block
 block discarded – undo
442 442
 
443 443
 		$targetUser = $this->userManager->get($userId);
444 444
 
445
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
445
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
446 446
 			throw new OCSException('', 101);
447 447
 		}
448 448
 
449 449
 		// If not permitted
450 450
 		$subAdminManager = $this->groupManager->getSubAdmin();
451
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
451
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
452 452
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
453 453
 		}
454 454
 
455 455
 		// Go ahead with the delete
456
-		if($targetUser->delete()) {
456
+		if ($targetUser->delete()) {
457 457
 			return new DataResponse();
458 458
 		} else {
459 459
 			throw new OCSException('', 101);
@@ -497,13 +497,13 @@  discard block
 block discarded – undo
497 497
 		$currentLoggedInUser = $this->userSession->getUser();
498 498
 
499 499
 		$targetUser = $this->userManager->get($userId);
500
-		if($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
500
+		if ($targetUser === null || $targetUser->getUID() === $currentLoggedInUser->getUID()) {
501 501
 			throw new OCSException('', 101);
502 502
 		}
503 503
 
504 504
 		// If not permitted
505 505
 		$subAdminManager = $this->groupManager->getSubAdmin();
506
-		if(!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
506
+		if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) {
507 507
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
508 508
 		}
509 509
 
@@ -524,11 +524,11 @@  discard block
 block discarded – undo
524 524
 		$loggedInUser = $this->userSession->getUser();
525 525
 
526 526
 		$targetUser = $this->userManager->get($userId);
527
-		if($targetUser === null) {
527
+		if ($targetUser === null) {
528 528
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
529 529
 		}
530 530
 
531
-		if($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
531
+		if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) {
532 532
 			// Self lookup or admin lookup
533 533
 			return new DataResponse([
534 534
 				'groups' => $this->groupManager->getUserGroupIds($targetUser)
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
 			$subAdminManager = $this->groupManager->getSubAdmin();
538 538
 
539 539
 			// Looking up someone else
540
-			if($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
540
+			if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) {
541 541
 				// Return the group that the method caller is subadmin of for the user in question
542 542
 				/** @var IGroup[] $getSubAdminsGroups */
543 543
 				$getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
@@ -567,16 +567,16 @@  discard block
 block discarded – undo
567 567
 	 * @throws OCSException
568 568
 	 */
569 569
 	public function addToGroup($userId, $groupid = '') {
570
-		if($groupid === '') {
570
+		if ($groupid === '') {
571 571
 			throw new OCSException('', 101);
572 572
 		}
573 573
 
574 574
 		$group = $this->groupManager->get($groupid);
575 575
 		$targetUser = $this->userManager->get($userId);
576
-		if($group === null) {
576
+		if ($group === null) {
577 577
 			throw new OCSException('', 102);
578 578
 		}
579
-		if($targetUser === null) {
579
+		if ($targetUser === null) {
580 580
 			throw new OCSException('', 103);
581 581
 		}
582 582
 
@@ -604,17 +604,17 @@  discard block
 block discarded – undo
604 604
 	public function removeFromGroup($userId, $groupid) {
605 605
 		$loggedInUser = $this->userSession->getUser();
606 606
 
607
-		if($groupid === null) {
607
+		if ($groupid === null) {
608 608
 			throw new OCSException('', 101);
609 609
 		}
610 610
 
611 611
 		$group = $this->groupManager->get($groupid);
612
-		if($group === null) {
612
+		if ($group === null) {
613 613
 			throw new OCSException('', 102);
614 614
 		}
615 615
 
616 616
 		$targetUser = $this->userManager->get($userId);
617
-		if($targetUser === null) {
617
+		if ($targetUser === null) {
618 618
 			throw new OCSException('', 103);
619 619
 		}
620 620
 
@@ -638,7 +638,7 @@  discard block
 block discarded – undo
638 638
 		} else if (!$this->groupManager->isAdmin($loggedInUser->getUID())) {
639 639
 			/** @var IGroup[] $subAdminGroups */
640 640
 			$subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser);
641
-			$subAdminGroups = array_map(function (IGroup $subAdminGroup) {
641
+			$subAdminGroups = array_map(function(IGroup $subAdminGroup) {
642 642
 				return $subAdminGroup->getGID();
643 643
 			}, $subAdminGroups);
644 644
 			$userGroups = $this->groupManager->getUserGroupIds($targetUser);
@@ -670,15 +670,15 @@  discard block
 block discarded – undo
670 670
 		$user = $this->userManager->get($userId);
671 671
 
672 672
 		// Check if the user exists
673
-		if($user === null) {
673
+		if ($user === null) {
674 674
 			throw new OCSException('User does not exist', 101);
675 675
 		}
676 676
 		// Check if group exists
677
-		if($group === null) {
678
-			throw new OCSException('Group does not exist',  102);
677
+		if ($group === null) {
678
+			throw new OCSException('Group does not exist', 102);
679 679
 		}
680 680
 		// Check if trying to make subadmin of admin group
681
-		if($group->getGID() === 'admin') {
681
+		if ($group->getGID() === 'admin') {
682 682
 			throw new OCSException('Cannot create subadmins for admin group', 103);
683 683
 		}
684 684
 
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 			return new DataResponse();
690 690
 		}
691 691
 		// Go
692
-		if($subAdminManager->createSubAdmin($user, $group)) {
692
+		if ($subAdminManager->createSubAdmin($user, $group)) {
693 693
 			return new DataResponse();
694 694
 		} else {
695 695
 			throw new OCSException('Unknown error occurred', 103);
@@ -712,20 +712,20 @@  discard block
 block discarded – undo
712 712
 		$subAdminManager = $this->groupManager->getSubAdmin();
713 713
 
714 714
 		// Check if the user exists
715
-		if($user === null) {
715
+		if ($user === null) {
716 716
 			throw new OCSException('User does not exist', 101);
717 717
 		}
718 718
 		// Check if the group exists
719
-		if($group === null) {
719
+		if ($group === null) {
720 720
 			throw new OCSException('Group does not exist', 101);
721 721
 		}
722 722
 		// Check if they are a subadmin of this said group
723
-		if(!$subAdminManager->isSubAdminOfGroup($user, $group)) {
723
+		if (!$subAdminManager->isSubAdminOfGroup($user, $group)) {
724 724
 			throw new OCSException('User is not a subadmin of this group', 102);
725 725
 		}
726 726
 
727 727
 		// Go
728
-		if($subAdminManager->deleteSubAdmin($user, $group)) {
728
+		if ($subAdminManager->deleteSubAdmin($user, $group)) {
729 729
 			return new DataResponse();
730 730
 		} else {
731 731
 			throw new OCSException('Unknown error occurred', 103);
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 	public function getUserSubAdminGroups($userId) {
743 743
 		$user = $this->userManager->get($userId);
744 744
 		// Check if the user exists
745
-		if($user === null) {
745
+		if ($user === null) {
746 746
 			throw new OCSException('User does not exist', 101);
747 747
 		}
748 748
 
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
 			$groups[$key] = $group->getGID();
753 753
 		}
754 754
 
755
-		if(!$groups) {
755
+		if (!$groups) {
756 756
 			throw new OCSException('Unknown error occurred', 102);
757 757
 		} else {
758 758
 			return new DataResponse($groups);
@@ -796,13 +796,13 @@  discard block
 block discarded – undo
796 796
 		$currentLoggedInUser = $this->userSession->getUser();
797 797
 
798 798
 		$targetUser = $this->userManager->get($userId);
799
-		if($targetUser === null) {
799
+		if ($targetUser === null) {
800 800
 			throw new OCSException('', \OCP\API::RESPOND_NOT_FOUND);
801 801
 		}
802 802
 
803 803
 		// Check if admin / subadmin
804 804
 		$subAdminManager = $this->groupManager->getSubAdmin();
805
-		if(!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
805
+		if (!$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)
806 806
 			&& !$this->groupManager->isAdmin($currentLoggedInUser->getUID())) {
807 807
 			// No rights
808 808
 			throw new OCSException('', \OCP\API::RESPOND_UNAUTHORISED);
@@ -824,8 +824,8 @@  discard block
 block discarded – undo
824 824
 			$this->newUserMailHelper->setL10N($l10n);
825 825
 			$emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false);
826 826
 			$this->newUserMailHelper->sendMail($targetUser, $emailTemplate);
827
-		} catch(\Exception $e) {
828
-			$this->logger->error("Can't send new user mail to $email: " . $e->getMessage(), array('app' => 'settings'));
827
+		} catch (\Exception $e) {
828
+			$this->logger->error("Can't send new user mail to $email: ".$e->getMessage(), array('app' => 'settings'));
829 829
 			throw new OCSException('Sending email failed', 102);
830 830
 		}
831 831
 
Please login to merge, or discard this patch.