Completed
Pull Request — master (#5623)
by Thomas
16:49
created
lib/private/Repair.php 1 patch
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -53,179 +53,179 @@
 block discarded – undo
53 53
 use Symfony\Component\EventDispatcher\GenericEvent;
54 54
 
55 55
 class Repair implements IOutput{
56
-	/* @var IRepairStep[] */
57
-	private $repairSteps;
58
-	/** @var EventDispatcher */
59
-	private $dispatcher;
60
-	/** @var string */
61
-	private $currentStep;
62
-
63
-	/**
64
-	 * Creates a new repair step runner
65
-	 *
66
-	 * @param IRepairStep[] $repairSteps array of RepairStep instances
67
-	 * @param EventDispatcher $dispatcher
68
-	 */
69
-	public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
70
-		$this->repairSteps = $repairSteps;
71
-		$this->dispatcher = $dispatcher;
72
-	}
73
-
74
-	/**
75
-	 * Run a series of repair steps for common problems
76
-	 */
77
-	public function run() {
78
-		if (count($this->repairSteps) === 0) {
79
-			$this->emit('\OC\Repair', 'info', array('No repair steps available'));
80
-			return;
81
-		}
82
-		// run each repair step
83
-		foreach ($this->repairSteps as $step) {
84
-			$this->currentStep = $step->getName();
85
-			$this->emit('\OC\Repair', 'step', [$this->currentStep]);
86
-			$step->run($this);
87
-		}
88
-	}
89
-
90
-	/**
91
-	 * Add repair step
92
-	 *
93
-	 * @param IRepairStep|string $repairStep repair step
94
-	 * @throws \Exception
95
-	 */
96
-	public function addStep($repairStep) {
97
-		if (is_string($repairStep)) {
98
-			try {
99
-				$s = \OC::$server->query($repairStep);
100
-			} catch (QueryException $e) {
101
-				if (class_exists($repairStep)) {
102
-					$s = new $repairStep();
103
-				} else {
104
-					throw new \Exception("Repair step '$repairStep' is unknown");
105
-				}
106
-			}
107
-
108
-			if ($s instanceof IRepairStep) {
109
-				$this->repairSteps[] = $s;
110
-			} else {
111
-				throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
112
-			}
113
-		} else {
114
-			$this->repairSteps[] = $repairStep;
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * Returns the default repair steps to be run on the
120
-	 * command line or after an upgrade.
121
-	 *
122
-	 * @return IRepairStep[]
123
-	 */
124
-	public static function getRepairSteps() {
125
-		return [
126
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
127
-			new RepairMimeTypes(\OC::$server->getConfig()),
128
-			new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
129
-			new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
130
-			new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
131
-			new MoveUpdaterStepFile(\OC::$server->getConfig()),
132
-			new MoveAvatars(
133
-				\OC::$server->getJobList(),
134
-				\OC::$server->getConfig()
135
-			),
136
-			new CleanPreviews(
137
-				\OC::$server->getJobList(),
138
-				\OC::$server->getUserManager(),
139
-				\OC::$server->getConfig()
140
-			),
141
-			new FixMountStorages(\OC::$server->getDatabaseConnection()),
142
-			new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
143
-			new InstallCoreBundle(
144
-				\OC::$server->query(BundleFetcher::class),
145
-				\OC::$server->getConfig(),
146
-				\OC::$server->query(Installer::class)
147
-			),
148
-			new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig())
149
-		];
150
-	}
151
-
152
-	/**
153
-	 * Returns expensive repair steps to be run on the
154
-	 * command line with a special option.
155
-	 *
156
-	 * @return IRepairStep[]
157
-	 */
158
-	public static function getExpensiveRepairSteps() {
159
-		return [
160
-			new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager())
161
-		];
162
-	}
163
-
164
-	/**
165
-	 * Returns the repair steps to be run before an
166
-	 * upgrade.
167
-	 *
168
-	 * @return IRepairStep[]
169
-	 */
170
-	public static function getBeforeUpgradeRepairSteps() {
171
-		$connection = \OC::$server->getDatabaseConnection();
172
-		$config = \OC::$server->getConfig();
173
-		$steps = [
174
-			new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
175
-			new SqliteAutoincrement($connection),
176
-			new SaveAccountsTableData($connection, $config),
177
-		];
178
-
179
-		return $steps;
180
-	}
181
-
182
-	/**
183
-	 * @param string $scope
184
-	 * @param string $method
185
-	 * @param array $arguments
186
-	 */
187
-	public function emit($scope, $method, array $arguments = []) {
188
-		if (!is_null($this->dispatcher)) {
189
-			$this->dispatcher->dispatch("$scope::$method",
190
-				new GenericEvent("$scope::$method", $arguments));
191
-		}
192
-	}
193
-
194
-	public function info($string) {
195
-		// for now just emit as we did in the past
196
-		$this->emit('\OC\Repair', 'info', array($string));
197
-	}
198
-
199
-	/**
200
-	 * @param string $message
201
-	 */
202
-	public function warning($message) {
203
-		// for now just emit as we did in the past
204
-		$this->emit('\OC\Repair', 'warning', [$message]);
205
-	}
206
-
207
-	/**
208
-	 * @param int $max
209
-	 */
210
-	public function startProgress($max = 0) {
211
-		// for now just emit as we did in the past
212
-		$this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
213
-	}
214
-
215
-	/**
216
-	 * @param int $step
217
-	 * @param string $description
218
-	 */
219
-	public function advance($step = 1, $description = '') {
220
-		// for now just emit as we did in the past
221
-		$this->emit('\OC\Repair', 'advance', [$step, $description]);
222
-	}
223
-
224
-	/**
225
-	 * @param int $max
226
-	 */
227
-	public function finishProgress() {
228
-		// for now just emit as we did in the past
229
-		$this->emit('\OC\Repair', 'finishProgress', []);
230
-	}
56
+    /* @var IRepairStep[] */
57
+    private $repairSteps;
58
+    /** @var EventDispatcher */
59
+    private $dispatcher;
60
+    /** @var string */
61
+    private $currentStep;
62
+
63
+    /**
64
+     * Creates a new repair step runner
65
+     *
66
+     * @param IRepairStep[] $repairSteps array of RepairStep instances
67
+     * @param EventDispatcher $dispatcher
68
+     */
69
+    public function __construct($repairSteps = [], EventDispatcher $dispatcher = null) {
70
+        $this->repairSteps = $repairSteps;
71
+        $this->dispatcher = $dispatcher;
72
+    }
73
+
74
+    /**
75
+     * Run a series of repair steps for common problems
76
+     */
77
+    public function run() {
78
+        if (count($this->repairSteps) === 0) {
79
+            $this->emit('\OC\Repair', 'info', array('No repair steps available'));
80
+            return;
81
+        }
82
+        // run each repair step
83
+        foreach ($this->repairSteps as $step) {
84
+            $this->currentStep = $step->getName();
85
+            $this->emit('\OC\Repair', 'step', [$this->currentStep]);
86
+            $step->run($this);
87
+        }
88
+    }
89
+
90
+    /**
91
+     * Add repair step
92
+     *
93
+     * @param IRepairStep|string $repairStep repair step
94
+     * @throws \Exception
95
+     */
96
+    public function addStep($repairStep) {
97
+        if (is_string($repairStep)) {
98
+            try {
99
+                $s = \OC::$server->query($repairStep);
100
+            } catch (QueryException $e) {
101
+                if (class_exists($repairStep)) {
102
+                    $s = new $repairStep();
103
+                } else {
104
+                    throw new \Exception("Repair step '$repairStep' is unknown");
105
+                }
106
+            }
107
+
108
+            if ($s instanceof IRepairStep) {
109
+                $this->repairSteps[] = $s;
110
+            } else {
111
+                throw new \Exception("Repair step '$repairStep' is not of type \\OCP\\Migration\\IRepairStep");
112
+            }
113
+        } else {
114
+            $this->repairSteps[] = $repairStep;
115
+        }
116
+    }
117
+
118
+    /**
119
+     * Returns the default repair steps to be run on the
120
+     * command line or after an upgrade.
121
+     *
122
+     * @return IRepairStep[]
123
+     */
124
+    public static function getRepairSteps() {
125
+        return [
126
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), \OC::$server->getDatabaseConnection(), false),
127
+            new RepairMimeTypes(\OC::$server->getConfig()),
128
+            new CleanTags(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager()),
129
+            new RepairInvalidShares(\OC::$server->getConfig(), \OC::$server->getDatabaseConnection()),
130
+            new RemoveRootShares(\OC::$server->getDatabaseConnection(), \OC::$server->getUserManager(), \OC::$server->getLazyRootFolder()),
131
+            new MoveUpdaterStepFile(\OC::$server->getConfig()),
132
+            new MoveAvatars(
133
+                \OC::$server->getJobList(),
134
+                \OC::$server->getConfig()
135
+            ),
136
+            new CleanPreviews(
137
+                \OC::$server->getJobList(),
138
+                \OC::$server->getUserManager(),
139
+                \OC::$server->getConfig()
140
+            ),
141
+            new FixMountStorages(\OC::$server->getDatabaseConnection()),
142
+            new UpdateLanguageCodes(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig()),
143
+            new InstallCoreBundle(
144
+                \OC::$server->query(BundleFetcher::class),
145
+                \OC::$server->getConfig(),
146
+                \OC::$server->query(Installer::class)
147
+            ),
148
+            new RepairInvalidPaths(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig())
149
+        ];
150
+    }
151
+
152
+    /**
153
+     * Returns expensive repair steps to be run on the
154
+     * command line with a special option.
155
+     *
156
+     * @return IRepairStep[]
157
+     */
158
+    public static function getExpensiveRepairSteps() {
159
+        return [
160
+            new OldGroupMembershipShares(\OC::$server->getDatabaseConnection(), \OC::$server->getGroupManager())
161
+        ];
162
+    }
163
+
164
+    /**
165
+     * Returns the repair steps to be run before an
166
+     * upgrade.
167
+     *
168
+     * @return IRepairStep[]
169
+     */
170
+    public static function getBeforeUpgradeRepairSteps() {
171
+        $connection = \OC::$server->getDatabaseConnection();
172
+        $config = \OC::$server->getConfig();
173
+        $steps = [
174
+            new Collation(\OC::$server->getConfig(), \OC::$server->getLogger(), $connection, true),
175
+            new SqliteAutoincrement($connection),
176
+            new SaveAccountsTableData($connection, $config),
177
+        ];
178
+
179
+        return $steps;
180
+    }
181
+
182
+    /**
183
+     * @param string $scope
184
+     * @param string $method
185
+     * @param array $arguments
186
+     */
187
+    public function emit($scope, $method, array $arguments = []) {
188
+        if (!is_null($this->dispatcher)) {
189
+            $this->dispatcher->dispatch("$scope::$method",
190
+                new GenericEvent("$scope::$method", $arguments));
191
+        }
192
+    }
193
+
194
+    public function info($string) {
195
+        // for now just emit as we did in the past
196
+        $this->emit('\OC\Repair', 'info', array($string));
197
+    }
198
+
199
+    /**
200
+     * @param string $message
201
+     */
202
+    public function warning($message) {
203
+        // for now just emit as we did in the past
204
+        $this->emit('\OC\Repair', 'warning', [$message]);
205
+    }
206
+
207
+    /**
208
+     * @param int $max
209
+     */
210
+    public function startProgress($max = 0) {
211
+        // for now just emit as we did in the past
212
+        $this->emit('\OC\Repair', 'startProgress', [$max, $this->currentStep]);
213
+    }
214
+
215
+    /**
216
+     * @param int $step
217
+     * @param string $description
218
+     */
219
+    public function advance($step = 1, $description = '') {
220
+        // for now just emit as we did in the past
221
+        $this->emit('\OC\Repair', 'advance', [$step, $description]);
222
+    }
223
+
224
+    /**
225
+     * @param int $max
226
+     */
227
+    public function finishProgress() {
228
+        // for now just emit as we did in the past
229
+        $this->emit('\OC\Repair', 'finishProgress', []);
230
+    }
231 231
 }
Please login to merge, or discard this patch.
lib/private/NavigationManager.php 1 patch
Indentation   +226 added lines, -226 removed lines patch added patch discarded remove patch
@@ -41,252 +41,252 @@
 block discarded – undo
41 41
  */
42 42
 
43 43
 class NavigationManager implements INavigationManager {
44
-	protected $entries = [];
45
-	protected $closureEntries = [];
46
-	protected $activeEntry;
47
-	/** @var bool */
48
-	protected $init = false;
49
-	/** @var IAppManager|AppManager */
50
-	protected $appManager;
51
-	/** @var IURLGenerator */
52
-	private $urlGenerator;
53
-	/** @var IFactory */
54
-	private $l10nFac;
55
-	/** @var IUserSession */
56
-	private $userSession;
57
-	/** @var IGroupManager|Manager */
58
-	private $groupManager;
59
-	/** @var IConfig */
60
-	private $config;
44
+    protected $entries = [];
45
+    protected $closureEntries = [];
46
+    protected $activeEntry;
47
+    /** @var bool */
48
+    protected $init = false;
49
+    /** @var IAppManager|AppManager */
50
+    protected $appManager;
51
+    /** @var IURLGenerator */
52
+    private $urlGenerator;
53
+    /** @var IFactory */
54
+    private $l10nFac;
55
+    /** @var IUserSession */
56
+    private $userSession;
57
+    /** @var IGroupManager|Manager */
58
+    private $groupManager;
59
+    /** @var IConfig */
60
+    private $config;
61 61
 
62
-	public function __construct(IAppManager $appManager,
63
-						 IURLGenerator $urlGenerator,
64
-						 IFactory $l10nFac,
65
-						 IUserSession $userSession,
66
-						 IGroupManager $groupManager,
67
-						 IConfig $config) {
68
-		$this->appManager = $appManager;
69
-		$this->urlGenerator = $urlGenerator;
70
-		$this->l10nFac = $l10nFac;
71
-		$this->userSession = $userSession;
72
-		$this->groupManager = $groupManager;
73
-		$this->config = $config;
74
-	}
62
+    public function __construct(IAppManager $appManager,
63
+                            IURLGenerator $urlGenerator,
64
+                            IFactory $l10nFac,
65
+                            IUserSession $userSession,
66
+                            IGroupManager $groupManager,
67
+                            IConfig $config) {
68
+        $this->appManager = $appManager;
69
+        $this->urlGenerator = $urlGenerator;
70
+        $this->l10nFac = $l10nFac;
71
+        $this->userSession = $userSession;
72
+        $this->groupManager = $groupManager;
73
+        $this->config = $config;
74
+    }
75 75
 
76
-	/**
77
-	 * Creates a new navigation entry
78
-	 *
79
-	 * @param array|\Closure $entry Array containing: id, name, order, icon and href key
80
-	 *					The use of a closure is preferred, because it will avoid
81
-	 * 					loading the routing of your app, unless required.
82
-	 * @return void
83
-	 */
84
-	public function add($entry) {
85
-		if ($entry instanceof \Closure) {
86
-			$this->closureEntries[] = $entry;
87
-			return;
88
-		}
76
+    /**
77
+     * Creates a new navigation entry
78
+     *
79
+     * @param array|\Closure $entry Array containing: id, name, order, icon and href key
80
+     *					The use of a closure is preferred, because it will avoid
81
+     * 					loading the routing of your app, unless required.
82
+     * @return void
83
+     */
84
+    public function add($entry) {
85
+        if ($entry instanceof \Closure) {
86
+            $this->closureEntries[] = $entry;
87
+            return;
88
+        }
89 89
 
90
-		$entry['active'] = false;
91
-		if(!isset($entry['icon'])) {
92
-			$entry['icon'] = '';
93
-		}
94
-		if(!isset($entry['type'])) {
95
-			$entry['type'] = 'link';
96
-		}
97
-		$this->entries[] = $entry;
98
-	}
90
+        $entry['active'] = false;
91
+        if(!isset($entry['icon'])) {
92
+            $entry['icon'] = '';
93
+        }
94
+        if(!isset($entry['type'])) {
95
+            $entry['type'] = 'link';
96
+        }
97
+        $this->entries[] = $entry;
98
+    }
99 99
 
100
-	/**
101
-	 * returns all the added Menu entries
102
-	 * @param string $type
103
-	 * @return array an array of the added entries
104
-	 */
105
-	public function getAll($type = 'link') {
106
-		$this->init();
107
-		foreach ($this->closureEntries as $c) {
108
-			$this->add($c());
109
-		}
110
-		$this->closureEntries = array();
100
+    /**
101
+     * returns all the added Menu entries
102
+     * @param string $type
103
+     * @return array an array of the added entries
104
+     */
105
+    public function getAll($type = 'link') {
106
+        $this->init();
107
+        foreach ($this->closureEntries as $c) {
108
+            $this->add($c());
109
+        }
110
+        $this->closureEntries = array();
111 111
 
112
-		if ($type === 'all') {
113
-			return $this->entries;
114
-		}
112
+        if ($type === 'all') {
113
+            return $this->entries;
114
+        }
115 115
 
116
-		return array_filter($this->entries, function($entry) use ($type) {
117
-			return $entry['type'] === $type;
118
-		});
119
-	}
116
+        return array_filter($this->entries, function($entry) use ($type) {
117
+            return $entry['type'] === $type;
118
+        });
119
+    }
120 120
 
121
-	/**
122
-	 * removes all the entries
123
-	 */
124
-	public function clear($loadDefaultLinks = true) {
125
-		$this->entries = [];
126
-		$this->closureEntries = [];
127
-		$this->init = !$loadDefaultLinks;
128
-	}
121
+    /**
122
+     * removes all the entries
123
+     */
124
+    public function clear($loadDefaultLinks = true) {
125
+        $this->entries = [];
126
+        $this->closureEntries = [];
127
+        $this->init = !$loadDefaultLinks;
128
+    }
129 129
 
130
-	/**
131
-	 * Sets the current navigation entry of the currently running app
132
-	 * @param string $id of the app entry to activate (from added $entry)
133
-	 */
134
-	public function setActiveEntry($id) {
135
-		$this->activeEntry = $id;
136
-	}
130
+    /**
131
+     * Sets the current navigation entry of the currently running app
132
+     * @param string $id of the app entry to activate (from added $entry)
133
+     */
134
+    public function setActiveEntry($id) {
135
+        $this->activeEntry = $id;
136
+    }
137 137
 
138
-	/**
139
-	 * gets the active Menu entry
140
-	 * @return string id or empty string
141
-	 *
142
-	 * This function returns the id of the active navigation entry (set by
143
-	 * setActiveEntry
144
-	 */
145
-	public function getActiveEntry() {
146
-		return $this->activeEntry;
147
-	}
138
+    /**
139
+     * gets the active Menu entry
140
+     * @return string id or empty string
141
+     *
142
+     * This function returns the id of the active navigation entry (set by
143
+     * setActiveEntry
144
+     */
145
+    public function getActiveEntry() {
146
+        return $this->activeEntry;
147
+    }
148 148
 
149
-	private function init() {
150
-		if ($this->init) {
151
-			return;
152
-		}
153
-		$this->init = true;
149
+    private function init() {
150
+        if ($this->init) {
151
+            return;
152
+        }
153
+        $this->init = true;
154 154
 
155
-		$l = $this->l10nFac->get('lib');
156
-		if ($this->config->getSystemValue('knowledgebaseenabled', true)) {
157
-			$this->add([
158
-				'type' => 'settings',
159
-				'id' => 'help',
160
-				'order' => 5,
161
-				'href' => $this->urlGenerator->linkToRoute('settings_help'),
162
-				'name' => $l->t('Help'),
163
-				'icon' => $this->urlGenerator->imagePath('settings', 'help.svg'),
164
-			]);
165
-		}
155
+        $l = $this->l10nFac->get('lib');
156
+        if ($this->config->getSystemValue('knowledgebaseenabled', true)) {
157
+            $this->add([
158
+                'type' => 'settings',
159
+                'id' => 'help',
160
+                'order' => 5,
161
+                'href' => $this->urlGenerator->linkToRoute('settings_help'),
162
+                'name' => $l->t('Help'),
163
+                'icon' => $this->urlGenerator->imagePath('settings', 'help.svg'),
164
+            ]);
165
+        }
166 166
 
167
-		if ($this->userSession->isLoggedIn()) {
168
-			if ($this->isAdmin()) {
169
-				// App management
170
-				$this->add([
171
-					'type' => 'settings',
172
-					'id' => 'core_apps',
173
-					'order' => 3,
174
-					'href' => $this->urlGenerator->linkToRoute('settings.AppSettings.viewApps'),
175
-					'icon' => $this->urlGenerator->imagePath('settings', 'apps.svg'),
176
-					'name' => $l->t('Apps'),
177
-				]);
178
-			}
167
+        if ($this->userSession->isLoggedIn()) {
168
+            if ($this->isAdmin()) {
169
+                // App management
170
+                $this->add([
171
+                    'type' => 'settings',
172
+                    'id' => 'core_apps',
173
+                    'order' => 3,
174
+                    'href' => $this->urlGenerator->linkToRoute('settings.AppSettings.viewApps'),
175
+                    'icon' => $this->urlGenerator->imagePath('settings', 'apps.svg'),
176
+                    'name' => $l->t('Apps'),
177
+                ]);
178
+            }
179 179
 
180
-			// Personal and (if applicable) admin settings
181
-			$this->add([
182
-				'type' => 'settings',
183
-				'id' => 'settings',
184
-				'order' => 1,
185
-				'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index'),
186
-				'name' => $l->t('Settings'),
187
-				'icon' => $this->urlGenerator->imagePath('settings', 'admin.svg'),
188
-			]);
180
+            // Personal and (if applicable) admin settings
181
+            $this->add([
182
+                'type' => 'settings',
183
+                'id' => 'settings',
184
+                'order' => 1,
185
+                'href' => $this->urlGenerator->linkToRoute('settings.PersonalSettings.index'),
186
+                'name' => $l->t('Settings'),
187
+                'icon' => $this->urlGenerator->imagePath('settings', 'admin.svg'),
188
+            ]);
189 189
 
190
-			// Logout
191
-			$this->add([
192
-				'type' => 'settings',
193
-				'id' => 'logout',
194
-				'order' => 99999,
195
-				'href' => $this->urlGenerator->linkToRouteAbsolute(
196
-					'core.login.logout',
197
-					['requesttoken' => \OCP\Util::callRegister()]
198
-				),
199
-				'name' => $l->t('Log out'),
200
-				'icon' => $this->urlGenerator->imagePath('core', 'actions/logout.svg'),
201
-			]);
190
+            // Logout
191
+            $this->add([
192
+                'type' => 'settings',
193
+                'id' => 'logout',
194
+                'order' => 99999,
195
+                'href' => $this->urlGenerator->linkToRouteAbsolute(
196
+                    'core.login.logout',
197
+                    ['requesttoken' => \OCP\Util::callRegister()]
198
+                ),
199
+                'name' => $l->t('Log out'),
200
+                'icon' => $this->urlGenerator->imagePath('core', 'actions/logout.svg'),
201
+            ]);
202 202
 
203
-			if ($this->isSubadmin()) {
204
-				// User management
205
-				$this->add([
206
-					'type' => 'settings',
207
-					'id' => 'core_users',
208
-					'order' => 4,
209
-					'href' => $this->urlGenerator->linkToRoute('settings_users'),
210
-					'name' => $l->t('Users'),
211
-					'icon' => $this->urlGenerator->imagePath('settings', 'users.svg'),
212
-				]);
213
-			}
214
-		}
203
+            if ($this->isSubadmin()) {
204
+                // User management
205
+                $this->add([
206
+                    'type' => 'settings',
207
+                    'id' => 'core_users',
208
+                    'order' => 4,
209
+                    'href' => $this->urlGenerator->linkToRoute('settings_users'),
210
+                    'name' => $l->t('Users'),
211
+                    'icon' => $this->urlGenerator->imagePath('settings', 'users.svg'),
212
+                ]);
213
+            }
214
+        }
215 215
 
216
-		if ($this->appManager === 'null') {
217
-			return;
218
-		}
216
+        if ($this->appManager === 'null') {
217
+            return;
218
+        }
219 219
 
220
-		if ($this->userSession->isLoggedIn()) {
221
-			$apps = $this->appManager->getEnabledAppsForUser($this->userSession->getUser());
222
-		} else {
223
-			$apps = $this->appManager->getInstalledApps();
224
-		}
220
+        if ($this->userSession->isLoggedIn()) {
221
+            $apps = $this->appManager->getEnabledAppsForUser($this->userSession->getUser());
222
+        } else {
223
+            $apps = $this->appManager->getInstalledApps();
224
+        }
225 225
 
226
-		foreach ($apps as $app) {
227
-			if (!$this->userSession->isLoggedIn() && !$this->appManager->isEnabledForUser($app, $this->userSession->getUser())) {
228
-				continue;
229
-			}
226
+        foreach ($apps as $app) {
227
+            if (!$this->userSession->isLoggedIn() && !$this->appManager->isEnabledForUser($app, $this->userSession->getUser())) {
228
+                continue;
229
+            }
230 230
 
231
-			// load plugins and collections from info.xml
232
-			$info = $this->appManager->getAppInfo($app);
233
-			if (empty($info['navigations'])) {
234
-				continue;
235
-			}
236
-			foreach ($info['navigations'] as $nav) {
237
-				if (!isset($nav['name'])) {
238
-					continue;
239
-				}
240
-				if (!isset($nav['route'])) {
241
-					continue;
242
-				}
243
-				$role = isset($nav['@attributes']['role']) ? $nav['@attributes']['role'] : 'all';
244
-				if ($role === 'admin' && !$this->isAdmin()) {
245
-					continue;
246
-				}
247
-				$l = $this->l10nFac->get($app);
248
-				$id = isset($nav['id']) ? $nav['id'] : $app;
249
-				$order = isset($nav['order']) ? $nav['order'] : 100;
250
-				$type = isset($nav['type']) ? $nav['type'] : 'link';
251
-				$route = $this->urlGenerator->linkToRoute($nav['route']);
252
-				$icon = isset($nav['icon']) ? $nav['icon'] : 'app.svg';
253
-				foreach ([$icon, "$app.svg"] as $i) {
254
-					try {
255
-						$icon = $this->urlGenerator->imagePath($app, $i);
256
-						break;
257
-					} catch (\RuntimeException $ex) {
258
-						// no icon? - ignore it then
259
-					}
260
-				}
261
-				if ($icon === null) {
262
-					$icon = $this->urlGenerator->imagePath('core', 'default-app-icon');
263
-				}
231
+            // load plugins and collections from info.xml
232
+            $info = $this->appManager->getAppInfo($app);
233
+            if (empty($info['navigations'])) {
234
+                continue;
235
+            }
236
+            foreach ($info['navigations'] as $nav) {
237
+                if (!isset($nav['name'])) {
238
+                    continue;
239
+                }
240
+                if (!isset($nav['route'])) {
241
+                    continue;
242
+                }
243
+                $role = isset($nav['@attributes']['role']) ? $nav['@attributes']['role'] : 'all';
244
+                if ($role === 'admin' && !$this->isAdmin()) {
245
+                    continue;
246
+                }
247
+                $l = $this->l10nFac->get($app);
248
+                $id = isset($nav['id']) ? $nav['id'] : $app;
249
+                $order = isset($nav['order']) ? $nav['order'] : 100;
250
+                $type = isset($nav['type']) ? $nav['type'] : 'link';
251
+                $route = $this->urlGenerator->linkToRoute($nav['route']);
252
+                $icon = isset($nav['icon']) ? $nav['icon'] : 'app.svg';
253
+                foreach ([$icon, "$app.svg"] as $i) {
254
+                    try {
255
+                        $icon = $this->urlGenerator->imagePath($app, $i);
256
+                        break;
257
+                    } catch (\RuntimeException $ex) {
258
+                        // no icon? - ignore it then
259
+                    }
260
+                }
261
+                if ($icon === null) {
262
+                    $icon = $this->urlGenerator->imagePath('core', 'default-app-icon');
263
+                }
264 264
 
265
-				$this->add([
266
-					'id' => $id,
267
-					'order' => $order,
268
-					'href' => $route,
269
-					'icon' => $icon,
270
-					'type' => $type,
271
-					'name' => $l->t($nav['name']),
272
-				]);
273
-			}
274
-		}
275
-	}
265
+                $this->add([
266
+                    'id' => $id,
267
+                    'order' => $order,
268
+                    'href' => $route,
269
+                    'icon' => $icon,
270
+                    'type' => $type,
271
+                    'name' => $l->t($nav['name']),
272
+                ]);
273
+            }
274
+        }
275
+    }
276 276
 
277
-	private function isAdmin() {
278
-		$user = $this->userSession->getUser();
279
-		if ($user !== null) {
280
-			return $this->groupManager->isAdmin($user->getUID());
281
-		}
282
-		return false;
283
-	}
277
+    private function isAdmin() {
278
+        $user = $this->userSession->getUser();
279
+        if ($user !== null) {
280
+            return $this->groupManager->isAdmin($user->getUID());
281
+        }
282
+        return false;
283
+    }
284 284
 
285
-	private function isSubadmin() {
286
-		$user = $this->userSession->getUser();
287
-		if ($user !== null) {
288
-			return $this->groupManager->getSubAdmin()->isSubAdmin($user);
289
-		}
290
-		return false;
291
-	}
285
+    private function isSubadmin() {
286
+        $user = $this->userSession->getUser();
287
+        if ($user !== null) {
288
+            return $this->groupManager->getSubAdmin()->isSubAdmin($user);
289
+        }
290
+        return false;
291
+    }
292 292
 }
Please login to merge, or discard this patch.
apps/encryption/lib/AppInfo/Application.php 1 patch
Indentation   +222 added lines, -222 removed lines patch added patch discarded remove patch
@@ -48,226 +48,226 @@
 block discarded – undo
48 48
 
49 49
 class Application extends \OCP\AppFramework\App {
50 50
 
51
-	/** @var IManager */
52
-	private $encryptionManager;
53
-	/** @var IConfig */
54
-	private $config;
55
-
56
-	/**
57
-	 * @param array $urlParams
58
-	 * @param bool $encryptionSystemReady
59
-	 */
60
-	public function __construct($urlParams = array(), $encryptionSystemReady = true) {
61
-		parent::__construct('encryption', $urlParams);
62
-		$this->encryptionManager = \OC::$server->getEncryptionManager();
63
-		$this->config = \OC::$server->getConfig();
64
-		$this->registerServices();
65
-		if($encryptionSystemReady === false) {
66
-			/** @var Session $session */
67
-			$session = $this->getContainer()->query('Session');
68
-			$session->setStatus(Session::RUN_MIGRATION);
69
-		}
70
-
71
-	}
72
-
73
-	public function setUp() {
74
-		if ($this->encryptionManager->isEnabled()) {
75
-			/** @var Setup $setup */
76
-			$setup = $this->getContainer()->query('UserSetup');
77
-			$setup->setupSystem();
78
-		}
79
-	}
80
-
81
-	/**
82
-	 * register hooks
83
-	 */
84
-	public function registerHooks() {
85
-		if (!$this->config->getSystemValue('maintenance', false)) {
86
-
87
-			$container = $this->getContainer();
88
-			$server = $container->getServer();
89
-			// Register our hooks and fire them.
90
-			$hookManager = new HookManager();
91
-
92
-			$hookManager->registerHook([
93
-				new UserHooks($container->query('KeyManager'),
94
-					$server->getUserManager(),
95
-					$server->getLogger(),
96
-					$container->query('UserSetup'),
97
-					$server->getUserSession(),
98
-					$container->query('Util'),
99
-					$container->query('Session'),
100
-					$container->query('Crypt'),
101
-					$container->query('Recovery'))
102
-			]);
103
-
104
-			$hookManager->fireHooks();
105
-
106
-		} else {
107
-			// Logout user if we are in maintenance to force re-login
108
-			$this->getContainer()->getServer()->getUserSession()->logout();
109
-		}
110
-	}
111
-
112
-	public function registerEncryptionModule() {
113
-		$container = $this->getContainer();
114
-
115
-
116
-		$this->encryptionManager->registerEncryptionModule(
117
-			Encryption::ID,
118
-			Encryption::DISPLAY_NAME,
119
-			function() use ($container) {
120
-
121
-			return new Encryption(
122
-				$container->query('Crypt'),
123
-				$container->query('KeyManager'),
124
-				$container->query('Util'),
125
-				$container->query('Session'),
126
-				$container->query('EncryptAll'),
127
-				$container->query('DecryptAll'),
128
-				$container->getServer()->getLogger(),
129
-				$container->getServer()->getL10N($container->getAppName())
130
-			);
131
-		});
132
-
133
-	}
134
-
135
-	public function registerServices() {
136
-		$container = $this->getContainer();
137
-
138
-		$container->registerService('Crypt',
139
-			function (IAppContainer $c) {
140
-				$server = $c->getServer();
141
-				return new Crypt($server->getLogger(),
142
-					$server->getUserSession(),
143
-					$server->getConfig(),
144
-					$server->getL10N($c->getAppName()));
145
-			});
146
-
147
-		$container->registerService('Session',
148
-			function (IAppContainer $c) {
149
-				$server = $c->getServer();
150
-				return new Session($server->getSession());
151
-			}
152
-		);
153
-
154
-		$container->registerService('KeyManager',
155
-			function (IAppContainer $c) {
156
-				$server = $c->getServer();
157
-
158
-				return new KeyManager($server->getEncryptionKeyStorage(),
159
-					$c->query('Crypt'),
160
-					$server->getConfig(),
161
-					$server->getUserSession(),
162
-					new Session($server->getSession()),
163
-					$server->getLogger(),
164
-					$c->query('Util')
165
-				);
166
-			});
167
-
168
-		$container->registerService('Recovery',
169
-			function (IAppContainer $c) {
170
-				$server = $c->getServer();
171
-
172
-				return new Recovery(
173
-					$server->getUserSession(),
174
-					$c->query('Crypt'),
175
-					$server->getSecureRandom(),
176
-					$c->query('KeyManager'),
177
-					$server->getConfig(),
178
-					$server->getEncryptionKeyStorage(),
179
-					$server->getEncryptionFilesHelper(),
180
-					new View());
181
-			});
182
-
183
-		$container->registerService('RecoveryController', function (IAppContainer $c) {
184
-			$server = $c->getServer();
185
-			return new RecoveryController(
186
-				$c->getAppName(),
187
-				$server->getRequest(),
188
-				$server->getConfig(),
189
-				$server->getL10N($c->getAppName()),
190
-				$c->query('Recovery'));
191
-		});
192
-
193
-		$container->registerService('StatusController', function (IAppContainer $c) {
194
-			$server = $c->getServer();
195
-			return new StatusController(
196
-				$c->getAppName(),
197
-				$server->getRequest(),
198
-				$server->getL10N($c->getAppName()),
199
-				$c->query('Session'),
200
-				$server->getEncryptionManager()
201
-			);
202
-		});
203
-
204
-		$container->registerService('SettingsController', function (IAppContainer $c) {
205
-			$server = $c->getServer();
206
-			return new SettingsController(
207
-				$c->getAppName(),
208
-				$server->getRequest(),
209
-				$server->getL10N($c->getAppName()),
210
-				$server->getUserManager(),
211
-				$server->getUserSession(),
212
-				$c->query('KeyManager'),
213
-				$c->query('Crypt'),
214
-				$c->query('Session'),
215
-				$server->getSession(),
216
-				$c->query('Util')
217
-			);
218
-		});
219
-
220
-		$container->registerService('UserSetup',
221
-			function (IAppContainer $c) {
222
-				$server = $c->getServer();
223
-				return new Setup($server->getLogger(),
224
-					$server->getUserSession(),
225
-					$c->query('Crypt'),
226
-					$c->query('KeyManager'));
227
-			});
228
-
229
-		$container->registerService('Util',
230
-			function (IAppContainer $c) {
231
-				$server = $c->getServer();
232
-
233
-				return new Util(
234
-					new View(),
235
-					$c->query('Crypt'),
236
-					$server->getLogger(),
237
-					$server->getUserSession(),
238
-					$server->getConfig(),
239
-					$server->getUserManager());
240
-			});
241
-
242
-		$container->registerService('EncryptAll',
243
-			function (IAppContainer $c) {
244
-				$server = $c->getServer();
245
-				return new EncryptAll(
246
-					$c->query('UserSetup'),
247
-					$c->getServer()->getUserManager(),
248
-					new View(),
249
-					$c->query('KeyManager'),
250
-					$c->query('Util'),
251
-					$server->getConfig(),
252
-					$server->getMailer(),
253
-					$server->getL10N('encryption'),
254
-					new QuestionHelper(),
255
-					$server->getSecureRandom()
256
-				);
257
-			}
258
-		);
259
-
260
-		$container->registerService('DecryptAll',
261
-			function (IAppContainer $c) {
262
-				return new DecryptAll(
263
-					$c->query('Util'),
264
-					$c->query('KeyManager'),
265
-					$c->query('Crypt'),
266
-					$c->query('Session'),
267
-					new QuestionHelper()
268
-				);
269
-			}
270
-		);
271
-
272
-	}
51
+    /** @var IManager */
52
+    private $encryptionManager;
53
+    /** @var IConfig */
54
+    private $config;
55
+
56
+    /**
57
+     * @param array $urlParams
58
+     * @param bool $encryptionSystemReady
59
+     */
60
+    public function __construct($urlParams = array(), $encryptionSystemReady = true) {
61
+        parent::__construct('encryption', $urlParams);
62
+        $this->encryptionManager = \OC::$server->getEncryptionManager();
63
+        $this->config = \OC::$server->getConfig();
64
+        $this->registerServices();
65
+        if($encryptionSystemReady === false) {
66
+            /** @var Session $session */
67
+            $session = $this->getContainer()->query('Session');
68
+            $session->setStatus(Session::RUN_MIGRATION);
69
+        }
70
+
71
+    }
72
+
73
+    public function setUp() {
74
+        if ($this->encryptionManager->isEnabled()) {
75
+            /** @var Setup $setup */
76
+            $setup = $this->getContainer()->query('UserSetup');
77
+            $setup->setupSystem();
78
+        }
79
+    }
80
+
81
+    /**
82
+     * register hooks
83
+     */
84
+    public function registerHooks() {
85
+        if (!$this->config->getSystemValue('maintenance', false)) {
86
+
87
+            $container = $this->getContainer();
88
+            $server = $container->getServer();
89
+            // Register our hooks and fire them.
90
+            $hookManager = new HookManager();
91
+
92
+            $hookManager->registerHook([
93
+                new UserHooks($container->query('KeyManager'),
94
+                    $server->getUserManager(),
95
+                    $server->getLogger(),
96
+                    $container->query('UserSetup'),
97
+                    $server->getUserSession(),
98
+                    $container->query('Util'),
99
+                    $container->query('Session'),
100
+                    $container->query('Crypt'),
101
+                    $container->query('Recovery'))
102
+            ]);
103
+
104
+            $hookManager->fireHooks();
105
+
106
+        } else {
107
+            // Logout user if we are in maintenance to force re-login
108
+            $this->getContainer()->getServer()->getUserSession()->logout();
109
+        }
110
+    }
111
+
112
+    public function registerEncryptionModule() {
113
+        $container = $this->getContainer();
114
+
115
+
116
+        $this->encryptionManager->registerEncryptionModule(
117
+            Encryption::ID,
118
+            Encryption::DISPLAY_NAME,
119
+            function() use ($container) {
120
+
121
+            return new Encryption(
122
+                $container->query('Crypt'),
123
+                $container->query('KeyManager'),
124
+                $container->query('Util'),
125
+                $container->query('Session'),
126
+                $container->query('EncryptAll'),
127
+                $container->query('DecryptAll'),
128
+                $container->getServer()->getLogger(),
129
+                $container->getServer()->getL10N($container->getAppName())
130
+            );
131
+        });
132
+
133
+    }
134
+
135
+    public function registerServices() {
136
+        $container = $this->getContainer();
137
+
138
+        $container->registerService('Crypt',
139
+            function (IAppContainer $c) {
140
+                $server = $c->getServer();
141
+                return new Crypt($server->getLogger(),
142
+                    $server->getUserSession(),
143
+                    $server->getConfig(),
144
+                    $server->getL10N($c->getAppName()));
145
+            });
146
+
147
+        $container->registerService('Session',
148
+            function (IAppContainer $c) {
149
+                $server = $c->getServer();
150
+                return new Session($server->getSession());
151
+            }
152
+        );
153
+
154
+        $container->registerService('KeyManager',
155
+            function (IAppContainer $c) {
156
+                $server = $c->getServer();
157
+
158
+                return new KeyManager($server->getEncryptionKeyStorage(),
159
+                    $c->query('Crypt'),
160
+                    $server->getConfig(),
161
+                    $server->getUserSession(),
162
+                    new Session($server->getSession()),
163
+                    $server->getLogger(),
164
+                    $c->query('Util')
165
+                );
166
+            });
167
+
168
+        $container->registerService('Recovery',
169
+            function (IAppContainer $c) {
170
+                $server = $c->getServer();
171
+
172
+                return new Recovery(
173
+                    $server->getUserSession(),
174
+                    $c->query('Crypt'),
175
+                    $server->getSecureRandom(),
176
+                    $c->query('KeyManager'),
177
+                    $server->getConfig(),
178
+                    $server->getEncryptionKeyStorage(),
179
+                    $server->getEncryptionFilesHelper(),
180
+                    new View());
181
+            });
182
+
183
+        $container->registerService('RecoveryController', function (IAppContainer $c) {
184
+            $server = $c->getServer();
185
+            return new RecoveryController(
186
+                $c->getAppName(),
187
+                $server->getRequest(),
188
+                $server->getConfig(),
189
+                $server->getL10N($c->getAppName()),
190
+                $c->query('Recovery'));
191
+        });
192
+
193
+        $container->registerService('StatusController', function (IAppContainer $c) {
194
+            $server = $c->getServer();
195
+            return new StatusController(
196
+                $c->getAppName(),
197
+                $server->getRequest(),
198
+                $server->getL10N($c->getAppName()),
199
+                $c->query('Session'),
200
+                $server->getEncryptionManager()
201
+            );
202
+        });
203
+
204
+        $container->registerService('SettingsController', function (IAppContainer $c) {
205
+            $server = $c->getServer();
206
+            return new SettingsController(
207
+                $c->getAppName(),
208
+                $server->getRequest(),
209
+                $server->getL10N($c->getAppName()),
210
+                $server->getUserManager(),
211
+                $server->getUserSession(),
212
+                $c->query('KeyManager'),
213
+                $c->query('Crypt'),
214
+                $c->query('Session'),
215
+                $server->getSession(),
216
+                $c->query('Util')
217
+            );
218
+        });
219
+
220
+        $container->registerService('UserSetup',
221
+            function (IAppContainer $c) {
222
+                $server = $c->getServer();
223
+                return new Setup($server->getLogger(),
224
+                    $server->getUserSession(),
225
+                    $c->query('Crypt'),
226
+                    $c->query('KeyManager'));
227
+            });
228
+
229
+        $container->registerService('Util',
230
+            function (IAppContainer $c) {
231
+                $server = $c->getServer();
232
+
233
+                return new Util(
234
+                    new View(),
235
+                    $c->query('Crypt'),
236
+                    $server->getLogger(),
237
+                    $server->getUserSession(),
238
+                    $server->getConfig(),
239
+                    $server->getUserManager());
240
+            });
241
+
242
+        $container->registerService('EncryptAll',
243
+            function (IAppContainer $c) {
244
+                $server = $c->getServer();
245
+                return new EncryptAll(
246
+                    $c->query('UserSetup'),
247
+                    $c->getServer()->getUserManager(),
248
+                    new View(),
249
+                    $c->query('KeyManager'),
250
+                    $c->query('Util'),
251
+                    $server->getConfig(),
252
+                    $server->getMailer(),
253
+                    $server->getL10N('encryption'),
254
+                    new QuestionHelper(),
255
+                    $server->getSecureRandom()
256
+                );
257
+            }
258
+        );
259
+
260
+        $container->registerService('DecryptAll',
261
+            function (IAppContainer $c) {
262
+                return new DecryptAll(
263
+                    $c->query('Util'),
264
+                    $c->query('KeyManager'),
265
+                    $c->query('Crypt'),
266
+                    $c->query('Session'),
267
+                    new QuestionHelper()
268
+                );
269
+            }
270
+        );
271
+
272
+    }
273 273
 }
Please login to merge, or discard this patch.
apps/encryption/appinfo/app.php 1 patch
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -29,7 +29,7 @@
 block discarded – undo
29 29
 
30 30
 $app = new Application([], $encryptionSystemReady);
31 31
 if ($encryptionSystemReady) {
32
-	$app->registerEncryptionModule();
33
-	$app->registerHooks();
34
-	$app->setUp();
32
+    $app->registerEncryptionModule();
33
+    $app->registerHooks();
34
+    $app->setUp();
35 35
 }
Please login to merge, or discard this patch.
settings/Controller/UsersController.php 1 patch
Indentation   +977 added lines, -977 removed lines patch added patch discarded remove patch
@@ -63,982 +63,982 @@
 block discarded – undo
63 63
  * @package OC\Settings\Controller
64 64
  */
65 65
 class UsersController extends Controller {
66
-	/** @var IL10N */
67
-	private $l10n;
68
-	/** @var IUserSession */
69
-	private $userSession;
70
-	/** @var bool */
71
-	private $isAdmin;
72
-	/** @var IUserManager */
73
-	private $userManager;
74
-	/** @var IGroupManager */
75
-	private $groupManager;
76
-	/** @var IConfig */
77
-	private $config;
78
-	/** @var ILogger */
79
-	private $log;
80
-	/** @var IMailer */
81
-	private $mailer;
82
-	/** @var bool contains the state of the encryption app */
83
-	private $isEncryptionAppEnabled;
84
-	/** @var bool contains the state of the admin recovery setting */
85
-	private $isRestoreEnabled = false;
86
-	/** @var IAppManager */
87
-	private $appManager;
88
-	/** @var IAvatarManager */
89
-	private $avatarManager;
90
-	/** @var AccountManager */
91
-	private $accountManager;
92
-	/** @var ISecureRandom */
93
-	private $secureRandom;
94
-	/** @var NewUserMailHelper */
95
-	private $newUserMailHelper;
96
-	/** @var ITimeFactory */
97
-	private $timeFactory;
98
-	/** @var ICrypto */
99
-	private $crypto;
100
-	/** @var Manager */
101
-	private $keyManager;
102
-	/** @var IJobList */
103
-	private $jobList;
104
-
105
-	/** @var IUserMountCache */
106
-	private $userMountCache;
107
-
108
-	/** @var IManager */
109
-	private $encryptionManager;
110
-
111
-
112
-	/**
113
-	 * @param string $appName
114
-	 * @param IRequest $request
115
-	 * @param IUserManager $userManager
116
-	 * @param IGroupManager $groupManager
117
-	 * @param IUserSession $userSession
118
-	 * @param IConfig $config
119
-	 * @param bool $isAdmin
120
-	 * @param IL10N $l10n
121
-	 * @param ILogger $log
122
-	 * @param IMailer $mailer
123
-	 * @param IURLGenerator $urlGenerator
124
-	 * @param IAppManager $appManager
125
-	 * @param IAvatarManager $avatarManager
126
-	 * @param AccountManager $accountManager
127
-	 * @param ISecureRandom $secureRandom
128
-	 * @param NewUserMailHelper $newUserMailHelper
129
-	 * @param ITimeFactory $timeFactory
130
-	 * @param ICrypto $crypto
131
-	 * @param Manager $keyManager
132
-	 * @param IJobList $jobList
133
-	 * @param IUserMountCache $userMountCache
134
-	 * @param IManager $encryptionManager
135
-	 */
136
-	public function __construct($appName,
137
-								IRequest $request,
138
-								IUserManager $userManager,
139
-								IGroupManager $groupManager,
140
-								IUserSession $userSession,
141
-								IConfig $config,
142
-								$isAdmin,
143
-								IL10N $l10n,
144
-								ILogger $log,
145
-								IMailer $mailer,
146
-								IURLGenerator $urlGenerator,
147
-								IAppManager $appManager,
148
-								IAvatarManager $avatarManager,
149
-								AccountManager $accountManager,
150
-								ISecureRandom $secureRandom,
151
-								NewUserMailHelper $newUserMailHelper,
152
-								ITimeFactory $timeFactory,
153
-								ICrypto $crypto,
154
-								Manager $keyManager,
155
-								IJobList $jobList,
156
-								IUserMountCache $userMountCache,
157
-								IManager $encryptionManager) {
158
-		parent::__construct($appName, $request);
159
-		$this->userManager = $userManager;
160
-		$this->groupManager = $groupManager;
161
-		$this->userSession = $userSession;
162
-		$this->config = $config;
163
-		$this->isAdmin = $isAdmin;
164
-		$this->l10n = $l10n;
165
-		$this->log = $log;
166
-		$this->mailer = $mailer;
167
-		$this->appManager = $appManager;
168
-		$this->avatarManager = $avatarManager;
169
-		$this->accountManager = $accountManager;
170
-		$this->secureRandom = $secureRandom;
171
-		$this->newUserMailHelper = $newUserMailHelper;
172
-		$this->timeFactory = $timeFactory;
173
-		$this->crypto = $crypto;
174
-		$this->keyManager = $keyManager;
175
-		$this->jobList = $jobList;
176
-		$this->userMountCache = $userMountCache;
177
-		$this->encryptionManager = $encryptionManager;
178
-
179
-		// check for encryption state - TODO see formatUserForIndex
180
-		$this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
181
-		if ($this->isEncryptionAppEnabled) {
182
-			// putting this directly in empty is possible in PHP 5.5+
183
-			$result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
184
-			$this->isRestoreEnabled = !empty($result);
185
-		}
186
-	}
187
-
188
-	/**
189
-	 * @param IUser $user
190
-	 * @param array $userGroups
191
-	 * @return array
192
-	 */
193
-	private function formatUserForIndex(IUser $user, array $userGroups = null) {
194
-
195
-		// TODO: eliminate this encryption specific code below and somehow
196
-		// hook in additional user info from other apps
197
-
198
-		// recovery isn't possible if admin or user has it disabled and encryption
199
-		// is enabled - so we eliminate the else paths in the conditional tree
200
-		// below
201
-		$restorePossible = false;
202
-
203
-		if ($this->isEncryptionAppEnabled) {
204
-			if ($this->isRestoreEnabled) {
205
-				// check for the users recovery setting
206
-				$recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
207
-				// method call inside empty is possible with PHP 5.5+
208
-				$recoveryModeEnabled = !empty($recoveryMode);
209
-				if ($recoveryModeEnabled) {
210
-					// user also has recovery mode enabled
211
-					$restorePossible = true;
212
-				}
213
-			} else {
214
-				$modules = $this->encryptionManager->getEncryptionModules();
215
-				$restorePossible = true;
216
-				foreach ($modules as $id => $module) {
217
-					/* @var IEncryptionModule $instance */
218
-					$instance = call_user_func($module['callback']);
219
-					if ($instance->needDetailedAccessList()) {
220
-						$restorePossible = false;
221
-						break;
222
-					}
223
-				}
224
-			}
225
-		} else {
226
-			// recovery is possible if encryption is disabled (plain files are
227
-			// available)
228
-			$restorePossible = true;
229
-		}
230
-
231
-		$subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
232
-		foreach ($subAdminGroups as $key => $subAdminGroup) {
233
-			$subAdminGroups[$key] = $subAdminGroup->getGID();
234
-		}
235
-
236
-		$displayName = $user->getEMailAddress();
237
-		if (is_null($displayName)) {
238
-			$displayName = '';
239
-		}
240
-
241
-		$avatarAvailable = false;
242
-		try {
243
-			$avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
244
-		} catch (\Exception $e) {
245
-			//No avatar yet
246
-		}
247
-
248
-		return [
249
-			'name' => $user->getUID(),
250
-			'displayname' => $user->getDisplayName(),
251
-			'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
252
-			'subadmin' => $subAdminGroups,
253
-			'quota' => $user->getQuota(),
254
-			'quota_bytes' => Util::computerFileSize($user->getQuota()),
255
-			'storageLocation' => $user->getHome(),
256
-			'lastLogin' => $user->getLastLogin() * 1000,
257
-			'backend' => $user->getBackendClassName(),
258
-			'email' => $displayName,
259
-			'isRestoreDisabled' => !$restorePossible,
260
-			'isAvatarAvailable' => $avatarAvailable,
261
-			'isEnabled' => $user->isEnabled(),
262
-		];
263
-	}
264
-
265
-	/**
266
-	 * @param array $userIDs Array with schema [$uid => $displayName]
267
-	 * @return IUser[]
268
-	 */
269
-	private function getUsersForUID(array $userIDs) {
270
-		$users = [];
271
-		foreach ($userIDs as $uid => $displayName) {
272
-			$users[$uid] = $this->userManager->get($uid);
273
-		}
274
-		return $users;
275
-	}
276
-
277
-	/**
278
-	 * @NoAdminRequired
279
-	 *
280
-	 * @param int $offset
281
-	 * @param int $limit
282
-	 * @param string $gid GID to filter for
283
-	 * @param string $pattern Pattern to search for in the username
284
-	 * @param string $backend Backend to filter for (class-name)
285
-	 * @return DataResponse
286
-	 *
287
-	 * TODO: Tidy up and write unit tests - code is mainly static method calls
288
-	 */
289
-	public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
290
-		// Remove backends
291
-		if (!empty($backend)) {
292
-			$activeBackends = $this->userManager->getBackends();
293
-			$this->userManager->clearBackends();
294
-			foreach ($activeBackends as $singleActiveBackend) {
295
-				if ($backend === get_class($singleActiveBackend)) {
296
-					$this->userManager->registerBackend($singleActiveBackend);
297
-					break;
298
-				}
299
-			}
300
-		}
301
-
302
-		$userObjects = [];
303
-		$users = [];
304
-		if ($this->isAdmin) {
305
-			if ($gid !== '' && $gid !== '_disabledUsers') {
306
-				$batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
307
-			} else {
308
-				$batch = $this->userManager->search($pattern, $limit, $offset);
309
-			}
310
-
311
-			foreach ($batch as $user) {
312
-				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
313
-					($gid === '_disabledUsers' && !$user->isEnabled())
314
-				) {
315
-					$userObjects[] = $user;
316
-					$users[] = $this->formatUserForIndex($user);
317
-				}
318
-			}
319
-
320
-		} else {
321
-			$subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
322
-			// New class returns IGroup[] so convert back
323
-			$gids = [];
324
-			foreach ($subAdminOfGroups as $group) {
325
-				$gids[] = $group->getGID();
326
-			}
327
-			$subAdminOfGroups = $gids;
328
-
329
-			// Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
330
-			if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
331
-				$gid = '';
332
-			}
333
-
334
-			// Batch all groups the user is subadmin of when a group is specified
335
-			$batch = [];
336
-			if ($gid === '') {
337
-				foreach ($subAdminOfGroups as $group) {
338
-					$groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
339
-
340
-					foreach ($groupUsers as $uid => $displayName) {
341
-						$batch[$uid] = $displayName;
342
-					}
343
-				}
344
-			} else {
345
-				$batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
346
-			}
347
-			$batch = $this->getUsersForUID($batch);
348
-
349
-			foreach ($batch as $user) {
350
-				// Only add the groups, this user is a subadmin of
351
-				$userGroups = array_values(array_intersect(
352
-					$this->groupManager->getUserGroupIds($user),
353
-					$subAdminOfGroups
354
-				));
355
-				if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
356
-					($gid === '_disabledUsers' && !$user->isEnabled())
357
-				) {
358
-					$userObjects[] = $user;
359
-					$users[] = $this->formatUserForIndex($user, $userGroups);
360
-				}
361
-			}
362
-		}
363
-
364
-		$usedSpace = $this->userMountCache->getUsedSpaceForUsers($userObjects);
365
-
366
-		foreach ($users as &$userData) {
367
-			$userData['size'] = isset($usedSpace[$userData['name']]) ? $usedSpace[$userData['name']] : 0;
368
-		}
369
-
370
-		return new DataResponse($users);
371
-	}
372
-
373
-	/**
374
-	 * @NoAdminRequired
375
-	 * @PasswordConfirmationRequired
376
-	 *
377
-	 * @param string $username
378
-	 * @param string $password
379
-	 * @param array $groups
380
-	 * @param string $email
381
-	 * @return DataResponse
382
-	 */
383
-	public function create($username, $password, array $groups = [], $email = '') {
384
-		if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
385
-			return new DataResponse(
386
-				[
387
-					'message' => (string)$this->l10n->t('Invalid mail address')
388
-				],
389
-				Http::STATUS_UNPROCESSABLE_ENTITY
390
-			);
391
-		}
392
-
393
-		$currentUser = $this->userSession->getUser();
394
-
395
-		if (!$this->isAdmin) {
396
-			if (!empty($groups)) {
397
-				foreach ($groups as $key => $group) {
398
-					$groupObject = $this->groupManager->get($group);
399
-					if ($groupObject === null) {
400
-						unset($groups[$key]);
401
-						continue;
402
-					}
403
-
404
-					if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
405
-						unset($groups[$key]);
406
-					}
407
-				}
408
-			}
409
-
410
-			if (empty($groups)) {
411
-				return new DataResponse(
412
-					[
413
-						'message' => $this->l10n->t('No valid group selected'),
414
-					],
415
-					Http::STATUS_FORBIDDEN
416
-				);
417
-			}
418
-		}
419
-
420
-		if ($this->userManager->userExists($username)) {
421
-			return new DataResponse(
422
-				[
423
-					'message' => (string)$this->l10n->t('A user with that name already exists.')
424
-				],
425
-				Http::STATUS_CONFLICT
426
-			);
427
-		}
428
-
429
-		$generatePasswordResetToken = false;
430
-		if ($password === '') {
431
-			if ($email === '') {
432
-				return new DataResponse(
433
-					[
434
-						'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
435
-					],
436
-					Http::STATUS_UNPROCESSABLE_ENTITY
437
-				);
438
-			}
439
-
440
-			$password = $this->secureRandom->generate(32);
441
-			$generatePasswordResetToken = true;
442
-		}
443
-
444
-		try {
445
-			$user = $this->userManager->createUser($username, $password);
446
-		} catch (\Exception $exception) {
447
-			$message = $exception->getMessage();
448
-			if ($exception instanceof HintException && $exception->getHint()) {
449
-				$message = $exception->getHint();
450
-			}
451
-			if (!$message) {
452
-				$message = $this->l10n->t('Unable to create user.');
453
-			}
454
-			return new DataResponse(
455
-				[
456
-					'message' => (string)$message,
457
-				],
458
-				Http::STATUS_FORBIDDEN
459
-			);
460
-		}
461
-
462
-		if ($user instanceof IUser) {
463
-			if ($groups !== null) {
464
-				foreach ($groups as $groupName) {
465
-					$group = $this->groupManager->get($groupName);
466
-
467
-					if (empty($group)) {
468
-						$group = $this->groupManager->createGroup($groupName);
469
-					}
470
-					$group->addUser($user);
471
-				}
472
-			}
473
-			/**
474
-			 * Send new user mail only if a mail is set
475
-			 */
476
-			if ($email !== '') {
477
-				$user->setEMailAddress($email);
478
-				try {
479
-					$emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
480
-					$this->newUserMailHelper->sendMail($user, $emailTemplate);
481
-				} catch (\Exception $e) {
482
-					$this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
483
-				}
484
-			}
485
-			// fetch users groups
486
-			$userGroups = $this->groupManager->getUserGroupIds($user);
487
-
488
-			return new DataResponse(
489
-				$this->formatUserForIndex($user, $userGroups),
490
-				Http::STATUS_CREATED
491
-			);
492
-		}
493
-
494
-		return new DataResponse(
495
-			[
496
-				'message' => (string)$this->l10n->t('Unable to create user.')
497
-			],
498
-			Http::STATUS_FORBIDDEN
499
-		);
500
-
501
-	}
502
-
503
-	/**
504
-	 * @NoAdminRequired
505
-	 * @PasswordConfirmationRequired
506
-	 *
507
-	 * @param string $id
508
-	 * @return DataResponse
509
-	 */
510
-	public function destroy($id) {
511
-		$userId = $this->userSession->getUser()->getUID();
512
-		$user = $this->userManager->get($id);
513
-
514
-		if ($userId === $id) {
515
-			return new DataResponse(
516
-				[
517
-					'status' => 'error',
518
-					'data' => [
519
-						'message' => (string)$this->l10n->t('Unable to delete user.')
520
-					]
521
-				],
522
-				Http::STATUS_FORBIDDEN
523
-			);
524
-		}
525
-
526
-		if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
527
-			return new DataResponse(
528
-				[
529
-					'status' => 'error',
530
-					'data' => [
531
-						'message' => (string)$this->l10n->t('Authentication error')
532
-					]
533
-				],
534
-				Http::STATUS_FORBIDDEN
535
-			);
536
-		}
537
-
538
-		if ($user) {
539
-			if ($user->delete()) {
540
-				return new DataResponse(
541
-					[
542
-						'status' => 'success',
543
-						'data' => [
544
-							'username' => $id
545
-						]
546
-					],
547
-					Http::STATUS_NO_CONTENT
548
-				);
549
-			}
550
-		}
551
-
552
-		return new DataResponse(
553
-			[
554
-				'status' => 'error',
555
-				'data' => [
556
-					'message' => (string)$this->l10n->t('Unable to delete user.')
557
-				]
558
-			],
559
-			Http::STATUS_FORBIDDEN
560
-		);
561
-	}
562
-
563
-	/**
564
-	 * @NoAdminRequired
565
-	 *
566
-	 * @param string $id
567
-	 * @param int $enabled
568
-	 * @return DataResponse
569
-	 */
570
-	public function setEnabled($id, $enabled) {
571
-		$enabled = (bool)$enabled;
572
-		if ($enabled) {
573
-			$errorMsgGeneral = (string)$this->l10n->t('Error while enabling user.');
574
-		} else {
575
-			$errorMsgGeneral = (string)$this->l10n->t('Error while disabling user.');
576
-		}
577
-
578
-		$userId = $this->userSession->getUser()->getUID();
579
-		$user = $this->userManager->get($id);
580
-
581
-		if ($userId === $id) {
582
-			return new DataResponse(
583
-				[
584
-					'status' => 'error',
585
-					'data' => [
586
-						'message' => $errorMsgGeneral
587
-					]
588
-				], Http::STATUS_FORBIDDEN
589
-			);
590
-		}
591
-
592
-		if ($user) {
593
-			if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
594
-				return new DataResponse(
595
-					[
596
-						'status' => 'error',
597
-						'data' => [
598
-							'message' => (string)$this->l10n->t('Authentication error')
599
-						]
600
-					],
601
-					Http::STATUS_FORBIDDEN
602
-				);
603
-			}
604
-
605
-			$user->setEnabled($enabled);
606
-			return new DataResponse(
607
-				[
608
-					'status' => 'success',
609
-					'data' => [
610
-						'username' => $id,
611
-						'enabled' => $enabled
612
-					]
613
-				]
614
-			);
615
-		} else {
616
-			return new DataResponse(
617
-				[
618
-					'status' => 'error',
619
-					'data' => [
620
-						'message' => $errorMsgGeneral
621
-					]
622
-				],
623
-				Http::STATUS_FORBIDDEN
624
-			);
625
-		}
626
-
627
-	}
628
-
629
-	/**
630
-	 * Set the mail address of a user
631
-	 *
632
-	 * @NoAdminRequired
633
-	 * @NoSubadminRequired
634
-	 * @PasswordConfirmationRequired
635
-	 *
636
-	 * @param string $account
637
-	 * @param bool $onlyVerificationCode only return verification code without updating the data
638
-	 * @return DataResponse
639
-	 */
640
-	public function getVerificationCode($account, $onlyVerificationCode) {
641
-
642
-		$user = $this->userSession->getUser();
643
-
644
-		if ($user === null) {
645
-			return new DataResponse([], Http::STATUS_BAD_REQUEST);
646
-		}
647
-
648
-		$accountData = $this->accountManager->getUser($user);
649
-		$cloudId = $user->getCloudId();
650
-		$message = "Use my Federated Cloud ID to share with me: " . $cloudId;
651
-		$signature = $this->signMessage($user, $message);
652
-
653
-		$code = $message . ' ' . $signature;
654
-		$codeMd5 = $message . ' ' . md5($signature);
655
-
656
-		switch ($account) {
657
-			case 'verify-twitter':
658
-				$accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
659
-				$msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
660
-				$code = $codeMd5;
661
-				$type = AccountManager::PROPERTY_TWITTER;
662
-				$data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
663
-				$accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
664
-				break;
665
-			case 'verify-website':
666
-				$accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
667
-				$msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
668
-				$type = AccountManager::PROPERTY_WEBSITE;
669
-				$data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
670
-				$accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
671
-				break;
672
-			default:
673
-				return new DataResponse([], Http::STATUS_BAD_REQUEST);
674
-		}
675
-
676
-		if ($onlyVerificationCode === false) {
677
-			$this->accountManager->updateUser($user, $accountData);
678
-
679
-			$this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
680
-				[
681
-					'verificationCode' => $code,
682
-					'data' => $data,
683
-					'type' => $type,
684
-					'uid' => $user->getUID(),
685
-					'try' => 0,
686
-					'lastRun' => $this->getCurrentTime()
687
-				]
688
-			);
689
-		}
690
-
691
-		return new DataResponse(['msg' => $msg, 'code' => $code]);
692
-	}
693
-
694
-	/**
695
-	 * get current timestamp
696
-	 *
697
-	 * @return int
698
-	 */
699
-	protected function getCurrentTime() {
700
-		return time();
701
-	}
702
-
703
-	/**
704
-	 * sign message with users private key
705
-	 *
706
-	 * @param IUser $user
707
-	 * @param string $message
708
-	 *
709
-	 * @return string base64 encoded signature
710
-	 */
711
-	protected function signMessage(IUser $user, $message) {
712
-		$privateKey = $this->keyManager->getKey($user)->getPrivate();
713
-		openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
714
-		$signatureBase64 = base64_encode($signature);
715
-
716
-		return $signatureBase64;
717
-	}
718
-
719
-	/**
720
-	 * @NoAdminRequired
721
-	 * @NoSubadminRequired
722
-	 * @PasswordConfirmationRequired
723
-	 *
724
-	 * @param string $avatarScope
725
-	 * @param string $displayname
726
-	 * @param string $displaynameScope
727
-	 * @param string $phone
728
-	 * @param string $phoneScope
729
-	 * @param string $email
730
-	 * @param string $emailScope
731
-	 * @param string $website
732
-	 * @param string $websiteScope
733
-	 * @param string $address
734
-	 * @param string $addressScope
735
-	 * @param string $twitter
736
-	 * @param string $twitterScope
737
-	 * @return DataResponse
738
-	 */
739
-	public function setUserSettings($avatarScope,
740
-									$displayname,
741
-									$displaynameScope,
742
-									$phone,
743
-									$phoneScope,
744
-									$email,
745
-									$emailScope,
746
-									$website,
747
-									$websiteScope,
748
-									$address,
749
-									$addressScope,
750
-									$twitter,
751
-									$twitterScope
752
-	) {
753
-
754
-		if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
755
-			return new DataResponse(
756
-				[
757
-					'status' => 'error',
758
-					'data' => [
759
-						'message' => (string)$this->l10n->t('Invalid mail address')
760
-					]
761
-				],
762
-				Http::STATUS_UNPROCESSABLE_ENTITY
763
-			);
764
-		}
765
-
766
-		$user = $this->userSession->getUser();
767
-
768
-		$data = $this->accountManager->getUser($user);
769
-
770
-		$data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
771
-		if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
772
-			$data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
773
-			$data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
774
-		}
775
-
776
-		if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
777
-			$federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
778
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
779
-			if ($shareProvider->isLookupServerUploadEnabled()) {
780
-				$data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
781
-				$data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
782
-				$data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
783
-				$data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
784
-			}
785
-		}
786
-
787
-		try {
788
-			$this->saveUserSettings($user, $data);
789
-			return new DataResponse(
790
-				[
791
-					'status' => 'success',
792
-					'data' => [
793
-						'userId' => $user->getUID(),
794
-						'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
795
-						'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
796
-						'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
797
-						'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
798
-						'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
799
-						'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
800
-						'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
801
-						'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
802
-						'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
803
-						'message' => (string)$this->l10n->t('Settings saved')
804
-					]
805
-				],
806
-				Http::STATUS_OK
807
-			);
808
-		} catch (ForbiddenException $e) {
809
-			return new DataResponse([
810
-				'status' => 'error',
811
-				'data' => [
812
-					'message' => $e->getMessage()
813
-				],
814
-			]);
815
-		}
816
-
817
-	}
818
-
819
-
820
-	/**
821
-	 * update account manager with new user data
822
-	 *
823
-	 * @param IUser $user
824
-	 * @param array $data
825
-	 * @throws ForbiddenException
826
-	 */
827
-	protected function saveUserSettings(IUser $user, $data) {
828
-
829
-		// keep the user back-end up-to-date with the latest display name and email
830
-		// address
831
-		$oldDisplayName = $user->getDisplayName();
832
-		$oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
833
-		if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
834
-			&& $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
835
-		) {
836
-			$result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
837
-			if ($result === false) {
838
-				throw new ForbiddenException($this->l10n->t('Unable to change full name'));
839
-			}
840
-		}
841
-
842
-		$oldEmailAddress = $user->getEMailAddress();
843
-		$oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
844
-		if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
845
-			&& $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
846
-		) {
847
-			// this is the only permission a backend provides and is also used
848
-			// for the permission of setting a email address
849
-			if (!$user->canChangeDisplayName()) {
850
-				throw new ForbiddenException($this->l10n->t('Unable to change email address'));
851
-			}
852
-			$user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
853
-		}
854
-
855
-		$this->accountManager->updateUser($user, $data);
856
-	}
857
-
858
-	/**
859
-	 * Count all unique users visible for the current admin/subadmin.
860
-	 *
861
-	 * @NoAdminRequired
862
-	 *
863
-	 * @return DataResponse
864
-	 */
865
-	public function stats() {
866
-		$userCount = 0;
867
-		if ($this->isAdmin) {
868
-			$countByBackend = $this->userManager->countUsers();
869
-
870
-			if (!empty($countByBackend)) {
871
-				foreach ($countByBackend as $count) {
872
-					$userCount += $count;
873
-				}
874
-			}
875
-		} else {
876
-			$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
877
-
878
-			$uniqueUsers = [];
879
-			foreach ($groups as $group) {
880
-				foreach ($group->getUsers() as $uid => $displayName) {
881
-					$uniqueUsers[$uid] = true;
882
-				}
883
-			}
884
-
885
-			$userCount = count($uniqueUsers);
886
-		}
887
-
888
-		return new DataResponse(
889
-			[
890
-				'totalUsers' => $userCount
891
-			]
892
-		);
893
-	}
894
-
895
-
896
-	/**
897
-	 * Set the displayName of a user
898
-	 *
899
-	 * @NoAdminRequired
900
-	 * @NoSubadminRequired
901
-	 * @PasswordConfirmationRequired
902
-	 * @todo merge into saveUserSettings
903
-	 *
904
-	 * @param string $username
905
-	 * @param string $displayName
906
-	 * @return DataResponse
907
-	 */
908
-	public function setDisplayName($username, $displayName) {
909
-		$currentUser = $this->userSession->getUser();
910
-		$user = $this->userManager->get($username);
911
-
912
-		if ($user === null ||
913
-			!$user->canChangeDisplayName() ||
914
-			(
915
-				!$this->groupManager->isAdmin($currentUser->getUID()) &&
916
-				!$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
917
-				$currentUser->getUID() !== $username
918
-
919
-			)
920
-		) {
921
-			return new DataResponse([
922
-				'status' => 'error',
923
-				'data' => [
924
-					'message' => $this->l10n->t('Authentication error'),
925
-				],
926
-			]);
927
-		}
928
-
929
-		$userData = $this->accountManager->getUser($user);
930
-		$userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
931
-
932
-
933
-		try {
934
-			$this->saveUserSettings($user, $userData);
935
-			return new DataResponse([
936
-				'status' => 'success',
937
-				'data' => [
938
-					'message' => $this->l10n->t('Your full name has been changed.'),
939
-					'username' => $username,
940
-					'displayName' => $displayName,
941
-				],
942
-			]);
943
-		} catch (ForbiddenException $e) {
944
-			return new DataResponse([
945
-				'status' => 'error',
946
-				'data' => [
947
-					'message' => $e->getMessage(),
948
-					'displayName' => $user->getDisplayName(),
949
-				],
950
-			]);
951
-		}
952
-	}
953
-
954
-	/**
955
-	 * Set the mail address of a user
956
-	 *
957
-	 * @NoAdminRequired
958
-	 * @NoSubadminRequired
959
-	 * @PasswordConfirmationRequired
960
-	 *
961
-	 * @param string $id
962
-	 * @param string $mailAddress
963
-	 * @return DataResponse
964
-	 */
965
-	public function setEMailAddress($id, $mailAddress) {
966
-		$user = $this->userManager->get($id);
967
-		if (!$this->isAdmin
968
-			&& !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
969
-		) {
970
-			return new DataResponse(
971
-				[
972
-					'status' => 'error',
973
-					'data' => [
974
-						'message' => (string)$this->l10n->t('Forbidden')
975
-					]
976
-				],
977
-				Http::STATUS_FORBIDDEN
978
-			);
979
-		}
980
-
981
-		if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
982
-			return new DataResponse(
983
-				[
984
-					'status' => 'error',
985
-					'data' => [
986
-						'message' => (string)$this->l10n->t('Invalid mail address')
987
-					]
988
-				],
989
-				Http::STATUS_UNPROCESSABLE_ENTITY
990
-			);
991
-		}
992
-
993
-		if (!$user) {
994
-			return new DataResponse(
995
-				[
996
-					'status' => 'error',
997
-					'data' => [
998
-						'message' => (string)$this->l10n->t('Invalid user')
999
-					]
1000
-				],
1001
-				Http::STATUS_UNPROCESSABLE_ENTITY
1002
-			);
1003
-		}
1004
-		// this is the only permission a backend provides and is also used
1005
-		// for the permission of setting a email address
1006
-		if (!$user->canChangeDisplayName()) {
1007
-			return new DataResponse(
1008
-				[
1009
-					'status' => 'error',
1010
-					'data' => [
1011
-						'message' => (string)$this->l10n->t('Unable to change mail address')
1012
-					]
1013
-				],
1014
-				Http::STATUS_FORBIDDEN
1015
-			);
1016
-		}
1017
-
1018
-		$userData = $this->accountManager->getUser($user);
1019
-		$userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
1020
-
1021
-		try {
1022
-			$this->saveUserSettings($user, $userData);
1023
-			return new DataResponse(
1024
-				[
1025
-					'status' => 'success',
1026
-					'data' => [
1027
-						'username' => $id,
1028
-						'mailAddress' => $mailAddress,
1029
-						'message' => (string)$this->l10n->t('Email saved')
1030
-					]
1031
-				],
1032
-				Http::STATUS_OK
1033
-			);
1034
-		} catch (ForbiddenException $e) {
1035
-			return new DataResponse([
1036
-				'status' => 'error',
1037
-				'data' => [
1038
-					'message' => $e->getMessage()
1039
-				],
1040
-			]);
1041
-		}
1042
-	}
66
+    /** @var IL10N */
67
+    private $l10n;
68
+    /** @var IUserSession */
69
+    private $userSession;
70
+    /** @var bool */
71
+    private $isAdmin;
72
+    /** @var IUserManager */
73
+    private $userManager;
74
+    /** @var IGroupManager */
75
+    private $groupManager;
76
+    /** @var IConfig */
77
+    private $config;
78
+    /** @var ILogger */
79
+    private $log;
80
+    /** @var IMailer */
81
+    private $mailer;
82
+    /** @var bool contains the state of the encryption app */
83
+    private $isEncryptionAppEnabled;
84
+    /** @var bool contains the state of the admin recovery setting */
85
+    private $isRestoreEnabled = false;
86
+    /** @var IAppManager */
87
+    private $appManager;
88
+    /** @var IAvatarManager */
89
+    private $avatarManager;
90
+    /** @var AccountManager */
91
+    private $accountManager;
92
+    /** @var ISecureRandom */
93
+    private $secureRandom;
94
+    /** @var NewUserMailHelper */
95
+    private $newUserMailHelper;
96
+    /** @var ITimeFactory */
97
+    private $timeFactory;
98
+    /** @var ICrypto */
99
+    private $crypto;
100
+    /** @var Manager */
101
+    private $keyManager;
102
+    /** @var IJobList */
103
+    private $jobList;
104
+
105
+    /** @var IUserMountCache */
106
+    private $userMountCache;
107
+
108
+    /** @var IManager */
109
+    private $encryptionManager;
110
+
111
+
112
+    /**
113
+     * @param string $appName
114
+     * @param IRequest $request
115
+     * @param IUserManager $userManager
116
+     * @param IGroupManager $groupManager
117
+     * @param IUserSession $userSession
118
+     * @param IConfig $config
119
+     * @param bool $isAdmin
120
+     * @param IL10N $l10n
121
+     * @param ILogger $log
122
+     * @param IMailer $mailer
123
+     * @param IURLGenerator $urlGenerator
124
+     * @param IAppManager $appManager
125
+     * @param IAvatarManager $avatarManager
126
+     * @param AccountManager $accountManager
127
+     * @param ISecureRandom $secureRandom
128
+     * @param NewUserMailHelper $newUserMailHelper
129
+     * @param ITimeFactory $timeFactory
130
+     * @param ICrypto $crypto
131
+     * @param Manager $keyManager
132
+     * @param IJobList $jobList
133
+     * @param IUserMountCache $userMountCache
134
+     * @param IManager $encryptionManager
135
+     */
136
+    public function __construct($appName,
137
+                                IRequest $request,
138
+                                IUserManager $userManager,
139
+                                IGroupManager $groupManager,
140
+                                IUserSession $userSession,
141
+                                IConfig $config,
142
+                                $isAdmin,
143
+                                IL10N $l10n,
144
+                                ILogger $log,
145
+                                IMailer $mailer,
146
+                                IURLGenerator $urlGenerator,
147
+                                IAppManager $appManager,
148
+                                IAvatarManager $avatarManager,
149
+                                AccountManager $accountManager,
150
+                                ISecureRandom $secureRandom,
151
+                                NewUserMailHelper $newUserMailHelper,
152
+                                ITimeFactory $timeFactory,
153
+                                ICrypto $crypto,
154
+                                Manager $keyManager,
155
+                                IJobList $jobList,
156
+                                IUserMountCache $userMountCache,
157
+                                IManager $encryptionManager) {
158
+        parent::__construct($appName, $request);
159
+        $this->userManager = $userManager;
160
+        $this->groupManager = $groupManager;
161
+        $this->userSession = $userSession;
162
+        $this->config = $config;
163
+        $this->isAdmin = $isAdmin;
164
+        $this->l10n = $l10n;
165
+        $this->log = $log;
166
+        $this->mailer = $mailer;
167
+        $this->appManager = $appManager;
168
+        $this->avatarManager = $avatarManager;
169
+        $this->accountManager = $accountManager;
170
+        $this->secureRandom = $secureRandom;
171
+        $this->newUserMailHelper = $newUserMailHelper;
172
+        $this->timeFactory = $timeFactory;
173
+        $this->crypto = $crypto;
174
+        $this->keyManager = $keyManager;
175
+        $this->jobList = $jobList;
176
+        $this->userMountCache = $userMountCache;
177
+        $this->encryptionManager = $encryptionManager;
178
+
179
+        // check for encryption state - TODO see formatUserForIndex
180
+        $this->isEncryptionAppEnabled = $appManager->isEnabledForUser('encryption');
181
+        if ($this->isEncryptionAppEnabled) {
182
+            // putting this directly in empty is possible in PHP 5.5+
183
+            $result = $config->getAppValue('encryption', 'recoveryAdminEnabled', 0);
184
+            $this->isRestoreEnabled = !empty($result);
185
+        }
186
+    }
187
+
188
+    /**
189
+     * @param IUser $user
190
+     * @param array $userGroups
191
+     * @return array
192
+     */
193
+    private function formatUserForIndex(IUser $user, array $userGroups = null) {
194
+
195
+        // TODO: eliminate this encryption specific code below and somehow
196
+        // hook in additional user info from other apps
197
+
198
+        // recovery isn't possible if admin or user has it disabled and encryption
199
+        // is enabled - so we eliminate the else paths in the conditional tree
200
+        // below
201
+        $restorePossible = false;
202
+
203
+        if ($this->isEncryptionAppEnabled) {
204
+            if ($this->isRestoreEnabled) {
205
+                // check for the users recovery setting
206
+                $recoveryMode = $this->config->getUserValue($user->getUID(), 'encryption', 'recoveryEnabled', '0');
207
+                // method call inside empty is possible with PHP 5.5+
208
+                $recoveryModeEnabled = !empty($recoveryMode);
209
+                if ($recoveryModeEnabled) {
210
+                    // user also has recovery mode enabled
211
+                    $restorePossible = true;
212
+                }
213
+            } else {
214
+                $modules = $this->encryptionManager->getEncryptionModules();
215
+                $restorePossible = true;
216
+                foreach ($modules as $id => $module) {
217
+                    /* @var IEncryptionModule $instance */
218
+                    $instance = call_user_func($module['callback']);
219
+                    if ($instance->needDetailedAccessList()) {
220
+                        $restorePossible = false;
221
+                        break;
222
+                    }
223
+                }
224
+            }
225
+        } else {
226
+            // recovery is possible if encryption is disabled (plain files are
227
+            // available)
228
+            $restorePossible = true;
229
+        }
230
+
231
+        $subAdminGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($user);
232
+        foreach ($subAdminGroups as $key => $subAdminGroup) {
233
+            $subAdminGroups[$key] = $subAdminGroup->getGID();
234
+        }
235
+
236
+        $displayName = $user->getEMailAddress();
237
+        if (is_null($displayName)) {
238
+            $displayName = '';
239
+        }
240
+
241
+        $avatarAvailable = false;
242
+        try {
243
+            $avatarAvailable = $this->avatarManager->getAvatar($user->getUID())->exists();
244
+        } catch (\Exception $e) {
245
+            //No avatar yet
246
+        }
247
+
248
+        return [
249
+            'name' => $user->getUID(),
250
+            'displayname' => $user->getDisplayName(),
251
+            'groups' => (empty($userGroups)) ? $this->groupManager->getUserGroupIds($user) : $userGroups,
252
+            'subadmin' => $subAdminGroups,
253
+            'quota' => $user->getQuota(),
254
+            'quota_bytes' => Util::computerFileSize($user->getQuota()),
255
+            'storageLocation' => $user->getHome(),
256
+            'lastLogin' => $user->getLastLogin() * 1000,
257
+            'backend' => $user->getBackendClassName(),
258
+            'email' => $displayName,
259
+            'isRestoreDisabled' => !$restorePossible,
260
+            'isAvatarAvailable' => $avatarAvailable,
261
+            'isEnabled' => $user->isEnabled(),
262
+        ];
263
+    }
264
+
265
+    /**
266
+     * @param array $userIDs Array with schema [$uid => $displayName]
267
+     * @return IUser[]
268
+     */
269
+    private function getUsersForUID(array $userIDs) {
270
+        $users = [];
271
+        foreach ($userIDs as $uid => $displayName) {
272
+            $users[$uid] = $this->userManager->get($uid);
273
+        }
274
+        return $users;
275
+    }
276
+
277
+    /**
278
+     * @NoAdminRequired
279
+     *
280
+     * @param int $offset
281
+     * @param int $limit
282
+     * @param string $gid GID to filter for
283
+     * @param string $pattern Pattern to search for in the username
284
+     * @param string $backend Backend to filter for (class-name)
285
+     * @return DataResponse
286
+     *
287
+     * TODO: Tidy up and write unit tests - code is mainly static method calls
288
+     */
289
+    public function index($offset = 0, $limit = 10, $gid = '', $pattern = '', $backend = '') {
290
+        // Remove backends
291
+        if (!empty($backend)) {
292
+            $activeBackends = $this->userManager->getBackends();
293
+            $this->userManager->clearBackends();
294
+            foreach ($activeBackends as $singleActiveBackend) {
295
+                if ($backend === get_class($singleActiveBackend)) {
296
+                    $this->userManager->registerBackend($singleActiveBackend);
297
+                    break;
298
+                }
299
+            }
300
+        }
301
+
302
+        $userObjects = [];
303
+        $users = [];
304
+        if ($this->isAdmin) {
305
+            if ($gid !== '' && $gid !== '_disabledUsers') {
306
+                $batch = $this->getUsersForUID($this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset));
307
+            } else {
308
+                $batch = $this->userManager->search($pattern, $limit, $offset);
309
+            }
310
+
311
+            foreach ($batch as $user) {
312
+                if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
313
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
314
+                ) {
315
+                    $userObjects[] = $user;
316
+                    $users[] = $this->formatUserForIndex($user);
317
+                }
318
+            }
319
+
320
+        } else {
321
+            $subAdminOfGroups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
322
+            // New class returns IGroup[] so convert back
323
+            $gids = [];
324
+            foreach ($subAdminOfGroups as $group) {
325
+                $gids[] = $group->getGID();
326
+            }
327
+            $subAdminOfGroups = $gids;
328
+
329
+            // Set the $gid parameter to an empty value if the subadmin has no rights to access a specific group
330
+            if ($gid !== '' && $gid !== '_disabledUsers' && !in_array($gid, $subAdminOfGroups)) {
331
+                $gid = '';
332
+            }
333
+
334
+            // Batch all groups the user is subadmin of when a group is specified
335
+            $batch = [];
336
+            if ($gid === '') {
337
+                foreach ($subAdminOfGroups as $group) {
338
+                    $groupUsers = $this->groupManager->displayNamesInGroup($group, $pattern, $limit, $offset);
339
+
340
+                    foreach ($groupUsers as $uid => $displayName) {
341
+                        $batch[$uid] = $displayName;
342
+                    }
343
+                }
344
+            } else {
345
+                $batch = $this->groupManager->displayNamesInGroup($gid, $pattern, $limit, $offset);
346
+            }
347
+            $batch = $this->getUsersForUID($batch);
348
+
349
+            foreach ($batch as $user) {
350
+                // Only add the groups, this user is a subadmin of
351
+                $userGroups = array_values(array_intersect(
352
+                    $this->groupManager->getUserGroupIds($user),
353
+                    $subAdminOfGroups
354
+                ));
355
+                if (($gid !== '_disabledUsers' && $user->isEnabled()) ||
356
+                    ($gid === '_disabledUsers' && !$user->isEnabled())
357
+                ) {
358
+                    $userObjects[] = $user;
359
+                    $users[] = $this->formatUserForIndex($user, $userGroups);
360
+                }
361
+            }
362
+        }
363
+
364
+        $usedSpace = $this->userMountCache->getUsedSpaceForUsers($userObjects);
365
+
366
+        foreach ($users as &$userData) {
367
+            $userData['size'] = isset($usedSpace[$userData['name']]) ? $usedSpace[$userData['name']] : 0;
368
+        }
369
+
370
+        return new DataResponse($users);
371
+    }
372
+
373
+    /**
374
+     * @NoAdminRequired
375
+     * @PasswordConfirmationRequired
376
+     *
377
+     * @param string $username
378
+     * @param string $password
379
+     * @param array $groups
380
+     * @param string $email
381
+     * @return DataResponse
382
+     */
383
+    public function create($username, $password, array $groups = [], $email = '') {
384
+        if ($email !== '' && !$this->mailer->validateMailAddress($email)) {
385
+            return new DataResponse(
386
+                [
387
+                    'message' => (string)$this->l10n->t('Invalid mail address')
388
+                ],
389
+                Http::STATUS_UNPROCESSABLE_ENTITY
390
+            );
391
+        }
392
+
393
+        $currentUser = $this->userSession->getUser();
394
+
395
+        if (!$this->isAdmin) {
396
+            if (!empty($groups)) {
397
+                foreach ($groups as $key => $group) {
398
+                    $groupObject = $this->groupManager->get($group);
399
+                    if ($groupObject === null) {
400
+                        unset($groups[$key]);
401
+                        continue;
402
+                    }
403
+
404
+                    if (!$this->groupManager->getSubAdmin()->isSubAdminofGroup($currentUser, $groupObject)) {
405
+                        unset($groups[$key]);
406
+                    }
407
+                }
408
+            }
409
+
410
+            if (empty($groups)) {
411
+                return new DataResponse(
412
+                    [
413
+                        'message' => $this->l10n->t('No valid group selected'),
414
+                    ],
415
+                    Http::STATUS_FORBIDDEN
416
+                );
417
+            }
418
+        }
419
+
420
+        if ($this->userManager->userExists($username)) {
421
+            return new DataResponse(
422
+                [
423
+                    'message' => (string)$this->l10n->t('A user with that name already exists.')
424
+                ],
425
+                Http::STATUS_CONFLICT
426
+            );
427
+        }
428
+
429
+        $generatePasswordResetToken = false;
430
+        if ($password === '') {
431
+            if ($email === '') {
432
+                return new DataResponse(
433
+                    [
434
+                        'message' => (string)$this->l10n->t('To send a password link to the user an email address is required.')
435
+                    ],
436
+                    Http::STATUS_UNPROCESSABLE_ENTITY
437
+                );
438
+            }
439
+
440
+            $password = $this->secureRandom->generate(32);
441
+            $generatePasswordResetToken = true;
442
+        }
443
+
444
+        try {
445
+            $user = $this->userManager->createUser($username, $password);
446
+        } catch (\Exception $exception) {
447
+            $message = $exception->getMessage();
448
+            if ($exception instanceof HintException && $exception->getHint()) {
449
+                $message = $exception->getHint();
450
+            }
451
+            if (!$message) {
452
+                $message = $this->l10n->t('Unable to create user.');
453
+            }
454
+            return new DataResponse(
455
+                [
456
+                    'message' => (string)$message,
457
+                ],
458
+                Http::STATUS_FORBIDDEN
459
+            );
460
+        }
461
+
462
+        if ($user instanceof IUser) {
463
+            if ($groups !== null) {
464
+                foreach ($groups as $groupName) {
465
+                    $group = $this->groupManager->get($groupName);
466
+
467
+                    if (empty($group)) {
468
+                        $group = $this->groupManager->createGroup($groupName);
469
+                    }
470
+                    $group->addUser($user);
471
+                }
472
+            }
473
+            /**
474
+             * Send new user mail only if a mail is set
475
+             */
476
+            if ($email !== '') {
477
+                $user->setEMailAddress($email);
478
+                try {
479
+                    $emailTemplate = $this->newUserMailHelper->generateTemplate($user, $generatePasswordResetToken);
480
+                    $this->newUserMailHelper->sendMail($user, $emailTemplate);
481
+                } catch (\Exception $e) {
482
+                    $this->log->error("Can't send new user mail to $email: " . $e->getMessage(), ['app' => 'settings']);
483
+                }
484
+            }
485
+            // fetch users groups
486
+            $userGroups = $this->groupManager->getUserGroupIds($user);
487
+
488
+            return new DataResponse(
489
+                $this->formatUserForIndex($user, $userGroups),
490
+                Http::STATUS_CREATED
491
+            );
492
+        }
493
+
494
+        return new DataResponse(
495
+            [
496
+                'message' => (string)$this->l10n->t('Unable to create user.')
497
+            ],
498
+            Http::STATUS_FORBIDDEN
499
+        );
500
+
501
+    }
502
+
503
+    /**
504
+     * @NoAdminRequired
505
+     * @PasswordConfirmationRequired
506
+     *
507
+     * @param string $id
508
+     * @return DataResponse
509
+     */
510
+    public function destroy($id) {
511
+        $userId = $this->userSession->getUser()->getUID();
512
+        $user = $this->userManager->get($id);
513
+
514
+        if ($userId === $id) {
515
+            return new DataResponse(
516
+                [
517
+                    'status' => 'error',
518
+                    'data' => [
519
+                        'message' => (string)$this->l10n->t('Unable to delete user.')
520
+                    ]
521
+                ],
522
+                Http::STATUS_FORBIDDEN
523
+            );
524
+        }
525
+
526
+        if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
527
+            return new DataResponse(
528
+                [
529
+                    'status' => 'error',
530
+                    'data' => [
531
+                        'message' => (string)$this->l10n->t('Authentication error')
532
+                    ]
533
+                ],
534
+                Http::STATUS_FORBIDDEN
535
+            );
536
+        }
537
+
538
+        if ($user) {
539
+            if ($user->delete()) {
540
+                return new DataResponse(
541
+                    [
542
+                        'status' => 'success',
543
+                        'data' => [
544
+                            'username' => $id
545
+                        ]
546
+                    ],
547
+                    Http::STATUS_NO_CONTENT
548
+                );
549
+            }
550
+        }
551
+
552
+        return new DataResponse(
553
+            [
554
+                'status' => 'error',
555
+                'data' => [
556
+                    'message' => (string)$this->l10n->t('Unable to delete user.')
557
+                ]
558
+            ],
559
+            Http::STATUS_FORBIDDEN
560
+        );
561
+    }
562
+
563
+    /**
564
+     * @NoAdminRequired
565
+     *
566
+     * @param string $id
567
+     * @param int $enabled
568
+     * @return DataResponse
569
+     */
570
+    public function setEnabled($id, $enabled) {
571
+        $enabled = (bool)$enabled;
572
+        if ($enabled) {
573
+            $errorMsgGeneral = (string)$this->l10n->t('Error while enabling user.');
574
+        } else {
575
+            $errorMsgGeneral = (string)$this->l10n->t('Error while disabling user.');
576
+        }
577
+
578
+        $userId = $this->userSession->getUser()->getUID();
579
+        $user = $this->userManager->get($id);
580
+
581
+        if ($userId === $id) {
582
+            return new DataResponse(
583
+                [
584
+                    'status' => 'error',
585
+                    'data' => [
586
+                        'message' => $errorMsgGeneral
587
+                    ]
588
+                ], Http::STATUS_FORBIDDEN
589
+            );
590
+        }
591
+
592
+        if ($user) {
593
+            if (!$this->isAdmin && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)) {
594
+                return new DataResponse(
595
+                    [
596
+                        'status' => 'error',
597
+                        'data' => [
598
+                            'message' => (string)$this->l10n->t('Authentication error')
599
+                        ]
600
+                    ],
601
+                    Http::STATUS_FORBIDDEN
602
+                );
603
+            }
604
+
605
+            $user->setEnabled($enabled);
606
+            return new DataResponse(
607
+                [
608
+                    'status' => 'success',
609
+                    'data' => [
610
+                        'username' => $id,
611
+                        'enabled' => $enabled
612
+                    ]
613
+                ]
614
+            );
615
+        } else {
616
+            return new DataResponse(
617
+                [
618
+                    'status' => 'error',
619
+                    'data' => [
620
+                        'message' => $errorMsgGeneral
621
+                    ]
622
+                ],
623
+                Http::STATUS_FORBIDDEN
624
+            );
625
+        }
626
+
627
+    }
628
+
629
+    /**
630
+     * Set the mail address of a user
631
+     *
632
+     * @NoAdminRequired
633
+     * @NoSubadminRequired
634
+     * @PasswordConfirmationRequired
635
+     *
636
+     * @param string $account
637
+     * @param bool $onlyVerificationCode only return verification code without updating the data
638
+     * @return DataResponse
639
+     */
640
+    public function getVerificationCode($account, $onlyVerificationCode) {
641
+
642
+        $user = $this->userSession->getUser();
643
+
644
+        if ($user === null) {
645
+            return new DataResponse([], Http::STATUS_BAD_REQUEST);
646
+        }
647
+
648
+        $accountData = $this->accountManager->getUser($user);
649
+        $cloudId = $user->getCloudId();
650
+        $message = "Use my Federated Cloud ID to share with me: " . $cloudId;
651
+        $signature = $this->signMessage($user, $message);
652
+
653
+        $code = $message . ' ' . $signature;
654
+        $codeMd5 = $message . ' ' . md5($signature);
655
+
656
+        switch ($account) {
657
+            case 'verify-twitter':
658
+                $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
659
+                $msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
660
+                $code = $codeMd5;
661
+                $type = AccountManager::PROPERTY_TWITTER;
662
+                $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
663
+                $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
664
+                break;
665
+            case 'verify-website':
666
+                $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
667
+                $msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
668
+                $type = AccountManager::PROPERTY_WEBSITE;
669
+                $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
670
+                $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
671
+                break;
672
+            default:
673
+                return new DataResponse([], Http::STATUS_BAD_REQUEST);
674
+        }
675
+
676
+        if ($onlyVerificationCode === false) {
677
+            $this->accountManager->updateUser($user, $accountData);
678
+
679
+            $this->jobList->add('OC\Settings\BackgroundJobs\VerifyUserData',
680
+                [
681
+                    'verificationCode' => $code,
682
+                    'data' => $data,
683
+                    'type' => $type,
684
+                    'uid' => $user->getUID(),
685
+                    'try' => 0,
686
+                    'lastRun' => $this->getCurrentTime()
687
+                ]
688
+            );
689
+        }
690
+
691
+        return new DataResponse(['msg' => $msg, 'code' => $code]);
692
+    }
693
+
694
+    /**
695
+     * get current timestamp
696
+     *
697
+     * @return int
698
+     */
699
+    protected function getCurrentTime() {
700
+        return time();
701
+    }
702
+
703
+    /**
704
+     * sign message with users private key
705
+     *
706
+     * @param IUser $user
707
+     * @param string $message
708
+     *
709
+     * @return string base64 encoded signature
710
+     */
711
+    protected function signMessage(IUser $user, $message) {
712
+        $privateKey = $this->keyManager->getKey($user)->getPrivate();
713
+        openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
714
+        $signatureBase64 = base64_encode($signature);
715
+
716
+        return $signatureBase64;
717
+    }
718
+
719
+    /**
720
+     * @NoAdminRequired
721
+     * @NoSubadminRequired
722
+     * @PasswordConfirmationRequired
723
+     *
724
+     * @param string $avatarScope
725
+     * @param string $displayname
726
+     * @param string $displaynameScope
727
+     * @param string $phone
728
+     * @param string $phoneScope
729
+     * @param string $email
730
+     * @param string $emailScope
731
+     * @param string $website
732
+     * @param string $websiteScope
733
+     * @param string $address
734
+     * @param string $addressScope
735
+     * @param string $twitter
736
+     * @param string $twitterScope
737
+     * @return DataResponse
738
+     */
739
+    public function setUserSettings($avatarScope,
740
+                                    $displayname,
741
+                                    $displaynameScope,
742
+                                    $phone,
743
+                                    $phoneScope,
744
+                                    $email,
745
+                                    $emailScope,
746
+                                    $website,
747
+                                    $websiteScope,
748
+                                    $address,
749
+                                    $addressScope,
750
+                                    $twitter,
751
+                                    $twitterScope
752
+    ) {
753
+
754
+        if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
755
+            return new DataResponse(
756
+                [
757
+                    'status' => 'error',
758
+                    'data' => [
759
+                        'message' => (string)$this->l10n->t('Invalid mail address')
760
+                    ]
761
+                ],
762
+                Http::STATUS_UNPROCESSABLE_ENTITY
763
+            );
764
+        }
765
+
766
+        $user = $this->userSession->getUser();
767
+
768
+        $data = $this->accountManager->getUser($user);
769
+
770
+        $data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
771
+        if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
772
+            $data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
773
+            $data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
774
+        }
775
+
776
+        if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
777
+            $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
778
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
779
+            if ($shareProvider->isLookupServerUploadEnabled()) {
780
+                $data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
781
+                $data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
782
+                $data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
783
+                $data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
784
+            }
785
+        }
786
+
787
+        try {
788
+            $this->saveUserSettings($user, $data);
789
+            return new DataResponse(
790
+                [
791
+                    'status' => 'success',
792
+                    'data' => [
793
+                        'userId' => $user->getUID(),
794
+                        'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
795
+                        'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
796
+                        'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
797
+                        'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
798
+                        'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
799
+                        'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
800
+                        'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
801
+                        'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
802
+                        'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
803
+                        'message' => (string)$this->l10n->t('Settings saved')
804
+                    ]
805
+                ],
806
+                Http::STATUS_OK
807
+            );
808
+        } catch (ForbiddenException $e) {
809
+            return new DataResponse([
810
+                'status' => 'error',
811
+                'data' => [
812
+                    'message' => $e->getMessage()
813
+                ],
814
+            ]);
815
+        }
816
+
817
+    }
818
+
819
+
820
+    /**
821
+     * update account manager with new user data
822
+     *
823
+     * @param IUser $user
824
+     * @param array $data
825
+     * @throws ForbiddenException
826
+     */
827
+    protected function saveUserSettings(IUser $user, $data) {
828
+
829
+        // keep the user back-end up-to-date with the latest display name and email
830
+        // address
831
+        $oldDisplayName = $user->getDisplayName();
832
+        $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
833
+        if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
834
+            && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
835
+        ) {
836
+            $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
837
+            if ($result === false) {
838
+                throw new ForbiddenException($this->l10n->t('Unable to change full name'));
839
+            }
840
+        }
841
+
842
+        $oldEmailAddress = $user->getEMailAddress();
843
+        $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
844
+        if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
845
+            && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
846
+        ) {
847
+            // this is the only permission a backend provides and is also used
848
+            // for the permission of setting a email address
849
+            if (!$user->canChangeDisplayName()) {
850
+                throw new ForbiddenException($this->l10n->t('Unable to change email address'));
851
+            }
852
+            $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
853
+        }
854
+
855
+        $this->accountManager->updateUser($user, $data);
856
+    }
857
+
858
+    /**
859
+     * Count all unique users visible for the current admin/subadmin.
860
+     *
861
+     * @NoAdminRequired
862
+     *
863
+     * @return DataResponse
864
+     */
865
+    public function stats() {
866
+        $userCount = 0;
867
+        if ($this->isAdmin) {
868
+            $countByBackend = $this->userManager->countUsers();
869
+
870
+            if (!empty($countByBackend)) {
871
+                foreach ($countByBackend as $count) {
872
+                    $userCount += $count;
873
+                }
874
+            }
875
+        } else {
876
+            $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($this->userSession->getUser());
877
+
878
+            $uniqueUsers = [];
879
+            foreach ($groups as $group) {
880
+                foreach ($group->getUsers() as $uid => $displayName) {
881
+                    $uniqueUsers[$uid] = true;
882
+                }
883
+            }
884
+
885
+            $userCount = count($uniqueUsers);
886
+        }
887
+
888
+        return new DataResponse(
889
+            [
890
+                'totalUsers' => $userCount
891
+            ]
892
+        );
893
+    }
894
+
895
+
896
+    /**
897
+     * Set the displayName of a user
898
+     *
899
+     * @NoAdminRequired
900
+     * @NoSubadminRequired
901
+     * @PasswordConfirmationRequired
902
+     * @todo merge into saveUserSettings
903
+     *
904
+     * @param string $username
905
+     * @param string $displayName
906
+     * @return DataResponse
907
+     */
908
+    public function setDisplayName($username, $displayName) {
909
+        $currentUser = $this->userSession->getUser();
910
+        $user = $this->userManager->get($username);
911
+
912
+        if ($user === null ||
913
+            !$user->canChangeDisplayName() ||
914
+            (
915
+                !$this->groupManager->isAdmin($currentUser->getUID()) &&
916
+                !$this->groupManager->getSubAdmin()->isUserAccessible($currentUser, $user) &&
917
+                $currentUser->getUID() !== $username
918
+
919
+            )
920
+        ) {
921
+            return new DataResponse([
922
+                'status' => 'error',
923
+                'data' => [
924
+                    'message' => $this->l10n->t('Authentication error'),
925
+                ],
926
+            ]);
927
+        }
928
+
929
+        $userData = $this->accountManager->getUser($user);
930
+        $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'] = $displayName;
931
+
932
+
933
+        try {
934
+            $this->saveUserSettings($user, $userData);
935
+            return new DataResponse([
936
+                'status' => 'success',
937
+                'data' => [
938
+                    'message' => $this->l10n->t('Your full name has been changed.'),
939
+                    'username' => $username,
940
+                    'displayName' => $displayName,
941
+                ],
942
+            ]);
943
+        } catch (ForbiddenException $e) {
944
+            return new DataResponse([
945
+                'status' => 'error',
946
+                'data' => [
947
+                    'message' => $e->getMessage(),
948
+                    'displayName' => $user->getDisplayName(),
949
+                ],
950
+            ]);
951
+        }
952
+    }
953
+
954
+    /**
955
+     * Set the mail address of a user
956
+     *
957
+     * @NoAdminRequired
958
+     * @NoSubadminRequired
959
+     * @PasswordConfirmationRequired
960
+     *
961
+     * @param string $id
962
+     * @param string $mailAddress
963
+     * @return DataResponse
964
+     */
965
+    public function setEMailAddress($id, $mailAddress) {
966
+        $user = $this->userManager->get($id);
967
+        if (!$this->isAdmin
968
+            && !$this->groupManager->getSubAdmin()->isUserAccessible($this->userSession->getUser(), $user)
969
+        ) {
970
+            return new DataResponse(
971
+                [
972
+                    'status' => 'error',
973
+                    'data' => [
974
+                        'message' => (string)$this->l10n->t('Forbidden')
975
+                    ]
976
+                ],
977
+                Http::STATUS_FORBIDDEN
978
+            );
979
+        }
980
+
981
+        if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) {
982
+            return new DataResponse(
983
+                [
984
+                    'status' => 'error',
985
+                    'data' => [
986
+                        'message' => (string)$this->l10n->t('Invalid mail address')
987
+                    ]
988
+                ],
989
+                Http::STATUS_UNPROCESSABLE_ENTITY
990
+            );
991
+        }
992
+
993
+        if (!$user) {
994
+            return new DataResponse(
995
+                [
996
+                    'status' => 'error',
997
+                    'data' => [
998
+                        'message' => (string)$this->l10n->t('Invalid user')
999
+                    ]
1000
+                ],
1001
+                Http::STATUS_UNPROCESSABLE_ENTITY
1002
+            );
1003
+        }
1004
+        // this is the only permission a backend provides and is also used
1005
+        // for the permission of setting a email address
1006
+        if (!$user->canChangeDisplayName()) {
1007
+            return new DataResponse(
1008
+                [
1009
+                    'status' => 'error',
1010
+                    'data' => [
1011
+                        'message' => (string)$this->l10n->t('Unable to change mail address')
1012
+                    ]
1013
+                ],
1014
+                Http::STATUS_FORBIDDEN
1015
+            );
1016
+        }
1017
+
1018
+        $userData = $this->accountManager->getUser($user);
1019
+        $userData[AccountManager::PROPERTY_EMAIL]['value'] = $mailAddress;
1020
+
1021
+        try {
1022
+            $this->saveUserSettings($user, $userData);
1023
+            return new DataResponse(
1024
+                [
1025
+                    'status' => 'success',
1026
+                    'data' => [
1027
+                        'username' => $id,
1028
+                        'mailAddress' => $mailAddress,
1029
+                        'message' => (string)$this->l10n->t('Email saved')
1030
+                    ]
1031
+                ],
1032
+                Http::STATUS_OK
1033
+            );
1034
+        } catch (ForbiddenException $e) {
1035
+            return new DataResponse([
1036
+                'status' => 'error',
1037
+                'data' => [
1038
+                    'message' => $e->getMessage()
1039
+                ],
1040
+            ]);
1041
+        }
1042
+    }
1043 1043
 
1044 1044
 }
Please login to merge, or discard this patch.
lib/private/L10N/Factory.php 3 patches
Doc Comments   +9 added lines patch added patch discarded remove patch
@@ -180,6 +180,10 @@  discard block
 block discarded – undo
180 180
 		return 'en';
181 181
 	}
182 182
 
183
+	/**
184
+	 * @param string $app
185
+	 * @param string $lang
186
+	 */
183 187
 	public function findLocale($app = null, $lang = null)
184 188
 	{
185 189
 		if ($this->config->getSystemValue('installed', false)) {
@@ -367,6 +371,11 @@  discard block
 block discarded – undo
367 371
 	 */
368 372
 	// FIXME This method is only public, until OC_L10N does not need it anymore,
369 373
 	// FIXME This is also the reason, why it is not in the public interface
374
+
375
+	/**
376
+	 * @param string $app
377
+	 * @param string $lang
378
+	 */
370 379
 	public function getL10nFilesForApp($app, $lang) {
371 380
 		$languageFiles = [];
372 381
 
Please login to merge, or discard this patch.
Indentation   +436 added lines, -436 removed lines patch added patch discarded remove patch
@@ -40,440 +40,440 @@
 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
-	 * @param string|null $locale
96
-	 * @return \OCP\IL10N
97
-	 */
98
-	public function get($app, $lang = null, $locale = null) {
99
-		$app = \OC_App::cleanAppId($app);
100
-		if ($lang !== null) {
101
-			$lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
102
-		}
103
-
104
-		$forceLang = $this->config->getSystemValue('force_language', false);
105
-		if (is_string($forceLang)) {
106
-			$lang = $forceLang;
107
-		}
108
-
109
-		if ($lang === null || !$this->languageExists($app, $lang)) {
110
-			$lang = $this->findLanguage($app);
111
-		}
112
-
113
-		if ($locale === null || !$this->localeExists($locale)) {
114
-			$locale = $this->findLocale($app, $lang);
115
-		}
116
-
117
-		if (!isset($this->instances[$lang][$app])) {
118
-			$this->instances[$lang][$app] = new L10N(
119
-				$this, $app, $lang, $locale,
120
-				$this->getL10nFilesForApp($app, $lang)
121
-			);
122
-		}
123
-
124
-		return $this->instances[$lang][$app];
125
-	}
126
-
127
-	/**
128
-	 * Find the best language
129
-	 *
130
-	 * @param string|null $app App id or null for core
131
-	 * @return string language If nothing works it returns 'en'
132
-	 */
133
-	public function findLanguage($app = null) {
134
-		if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
135
-			return $this->requestLanguage;
136
-		}
137
-
138
-		/**
139
-		 * At this point Nextcloud might not yet be installed and thus the lookup
140
-		 * in the preferences table might fail. For this reason we need to check
141
-		 * whether the instance has already been installed
142
-		 *
143
-		 * @link https://github.com/owncloud/core/issues/21955
144
-		 */
145
-		if($this->config->getSystemValue('installed', false)) {
146
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
-			if(!is_null($userId)) {
148
-				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149
-			} else {
150
-				$userLang = null;
151
-			}
152
-		} else {
153
-			$userId = null;
154
-			$userLang = null;
155
-		}
156
-
157
-		if ($userLang) {
158
-			$this->requestLanguage = $userLang;
159
-			if ($this->languageExists($app, $userLang)) {
160
-				return $userLang;
161
-			}
162
-		}
163
-
164
-		try {
165
-			// Try to get the language from the Request
166
-			$lang = $this->getLanguageFromRequest($app);
167
-			if ($userId !== null && $app === null && !$userLang) {
168
-				$this->config->setUserValue($userId, 'core', 'lang', $lang);
169
-			}
170
-			return $lang;
171
-		} catch (LanguageNotFoundException $e) {
172
-			// Finding language from request failed fall back to default language
173
-			$defaultLanguage = $this->config->getSystemValue('default_language', false);
174
-			if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
175
-				return $defaultLanguage;
176
-			}
177
-		}
178
-
179
-		// We could not find any language so fall back to english
180
-		return 'en';
181
-	}
182
-
183
-	public function findLocale($app = null, $lang = null)
184
-	{
185
-		if ($this->config->getSystemValue('installed', false)) {
186
-			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
187
-			$userLocale = null;
188
-			if (null !== $userId) {
189
-				$userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
190
-			}
191
-		} else {
192
-			$userId = null;
193
-			$userLocale = null;
194
-		}
195
-
196
-		if ($userLocale && $this->localeExists($userLocale)) {
197
-			return $userLocale;
198
-		}
199
-
200
-		// If no user locale set, use lang as locale
201
-		if (null !== $lang && $this->localeExists($lang)) {
202
-			return $lang;
203
-		}
204
-
205
-		// Default : use system default locale
206
-		$defaultLocale = $this->config->getSystemValue('default_locale', false);
207
-		if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
208
-			return $defaultLocale;
209
-		}
210
-
211
-		// At last, return USA
212
-		return 'en_US';
213
-	}
214
-
215
-	/**
216
-	 * Find all available languages for an app
217
-	 *
218
-	 * @param string|null $app App id or null for core
219
-	 * @return array an array of available languages
220
-	 */
221
-	public function findAvailableLanguages($app = null) {
222
-		$key = $app;
223
-		if ($key === null) {
224
-			$key = 'null';
225
-		}
226
-
227
-		// also works with null as key
228
-		if (!empty($this->availableLanguages[$key])) {
229
-			return $this->availableLanguages[$key];
230
-		}
231
-
232
-		$available = ['en']; //english is always available
233
-		$dir = $this->findL10nDir($app);
234
-		if (is_dir($dir)) {
235
-			$files = scandir($dir);
236
-			if ($files !== false) {
237
-				foreach ($files as $file) {
238
-					if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
239
-						$available[] = substr($file, 0, -5);
240
-					}
241
-				}
242
-			}
243
-		}
244
-
245
-		// merge with translations from theme
246
-		$theme = $this->config->getSystemValue('theme');
247
-		if (!empty($theme)) {
248
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
249
-
250
-			if (is_dir($themeDir)) {
251
-				$files = scandir($themeDir);
252
-				if ($files !== false) {
253
-					foreach ($files as $file) {
254
-						if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
255
-							$available[] = substr($file, 0, -5);
256
-						}
257
-					}
258
-				}
259
-			}
260
-		}
261
-
262
-		$this->availableLanguages[$key] = $available;
263
-		return $available;
264
-	}
265
-
266
-	public function findAvailableLocales()
267
-	{
268
-		$localeData = file_get_contents(__DIR__ . '/locales.json');
269
-		return json_decode($localeData, true);
270
-	}
271
-
272
-	/**
273
-	 * @param string|null $app App id or null for core
274
-	 * @param string $lang
275
-	 * @return bool
276
-	 */
277
-	public function languageExists($app, $lang) {
278
-		if ($lang === 'en') {//english is always available
279
-			return true;
280
-		}
281
-
282
-		$languages = $this->findAvailableLanguages($app);
283
-		return array_search($lang, $languages) !== false;
284
-	}
285
-
286
-	/**
287
-	 * @param string $locale
288
-	 * @return bool
289
-	 */
290
-	public function localeExists($locale) {
291
-		if ($locale === 'en') { //english is always available
292
-			return true;
293
-		}
294
-
295
-		$locales = $this->findAvailableLocales();
296
-
297
-		$userLocale = array_filter($locales, function($value) use ($locale) {
298
-			return $locale === $value['code'];
299
-		});
300
-
301
-		return !empty($userLocale);
302
-	}
303
-
304
-	/**
305
-	 * @param string|null $app
306
-	 * @return string
307
-	 * @throws LanguageNotFoundException
308
-	 */
309
-	private function getLanguageFromRequest($app) {
310
-		$header = $this->request->getHeader('ACCEPT_LANGUAGE');
311
-		if ($header) {
312
-			$available = $this->findAvailableLanguages($app);
313
-
314
-			// E.g. make sure that 'de' is before 'de_DE'.
315
-			sort($available);
316
-
317
-			$preferences = preg_split('/,\s*/', strtolower($header));
318
-			foreach ($preferences as $preference) {
319
-				list($preferred_language) = explode(';', $preference);
320
-				$preferred_language = str_replace('-', '_', $preferred_language);
321
-
322
-				foreach ($available as $available_language) {
323
-					if ($preferred_language === strtolower($available_language)) {
324
-						return $available_language;
325
-					}
326
-				}
327
-
328
-				// Fallback from de_De to de
329
-				foreach ($available as $available_language) {
330
-					if (substr($preferred_language, 0, 2) === $available_language) {
331
-						return $available_language;
332
-					}
333
-				}
334
-			}
335
-		}
336
-
337
-		throw new LanguageNotFoundException();
338
-	}
339
-
340
-	/**
341
-	 * Checks if $sub is a subdirectory of $parent
342
-	 *
343
-	 * @param string $sub
344
-	 * @param string $parent
345
-	 * @return bool
346
-	 */
347
-	private function isSubDirectory($sub, $parent) {
348
-		// Check whether $sub contains no ".."
349
-		if(strpos($sub, '..') !== false) {
350
-			return false;
351
-		}
352
-
353
-		// Check whether $sub is a subdirectory of $parent
354
-		if (strpos($sub, $parent) === 0) {
355
-			return true;
356
-		}
357
-
358
-		return false;
359
-	}
360
-
361
-	/**
362
-	 * Get a list of language files that should be loaded
363
-	 *
364
-	 * @param string $app
365
-	 * @param string $lang
366
-	 * @return string[]
367
-	 */
368
-	// FIXME This method is only public, until OC_L10N does not need it anymore,
369
-	// FIXME This is also the reason, why it is not in the public interface
370
-	public function getL10nFilesForApp($app, $lang) {
371
-		$languageFiles = [];
372
-
373
-		$i18nDir = $this->findL10nDir($app);
374
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
375
-
376
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
377
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
378
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
379
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
380
-			)
381
-			&& file_exists($transFile)) {
382
-			// load the translations file
383
-			$languageFiles[] = $transFile;
384
-		}
385
-
386
-		// merge with translations from theme
387
-		$theme = $this->config->getSystemValue('theme');
388
-		if (!empty($theme)) {
389
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
390
-			if (file_exists($transFile)) {
391
-				$languageFiles[] = $transFile;
392
-			}
393
-		}
394
-
395
-		return $languageFiles;
396
-	}
397
-
398
-	/**
399
-	 * find the l10n directory
400
-	 *
401
-	 * @param string $app App id or empty string for core
402
-	 * @return string directory
403
-	 */
404
-	protected function findL10nDir($app = null) {
405
-		if (in_array($app, ['core', 'lib', 'settings'])) {
406
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
407
-				return $this->serverRoot . '/' . $app . '/l10n/';
408
-			}
409
-		} else if ($app && \OC_App::getAppPath($app) !== false) {
410
-			// Check if the app is in the app folder
411
-			return \OC_App::getAppPath($app) . '/l10n/';
412
-		}
413
-		return $this->serverRoot . '/core/l10n/';
414
-	}
415
-
416
-
417
-	/**
418
-	 * Creates a function from the plural string
419
-	 *
420
-	 * Parts of the code is copied from Habari:
421
-	 * https://github.com/habari/system/blob/master/classes/locale.php
422
-	 * @param string $string
423
-	 * @return string
424
-	 */
425
-	public function createPluralFunction($string) {
426
-		if (isset($this->pluralFunctions[$string])) {
427
-			return $this->pluralFunctions[$string];
428
-		}
429
-
430
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
431
-			// sanitize
432
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
433
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
434
-
435
-			$body = str_replace(
436
-				array( 'plural', 'n', '$n$plurals', ),
437
-				array( '$plural', '$n', '$nplurals', ),
438
-				'nplurals='. $nplurals . '; plural=' . $plural
439
-			);
440
-
441
-			// add parents
442
-			// important since PHP's ternary evaluates from left to right
443
-			$body .= ';';
444
-			$res = '';
445
-			$p = 0;
446
-			for($i = 0; $i < strlen($body); $i++) {
447
-				$ch = $body[$i];
448
-				switch ( $ch ) {
449
-					case '?':
450
-						$res .= ' ? (';
451
-						$p++;
452
-						break;
453
-					case ':':
454
-						$res .= ') : (';
455
-						break;
456
-					case ';':
457
-						$res .= str_repeat( ')', $p ) . ';';
458
-						$p = 0;
459
-						break;
460
-					default:
461
-						$res .= $ch;
462
-				}
463
-			}
464
-
465
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
466
-			$function = create_function('$n', $body);
467
-			$this->pluralFunctions[$string] = $function;
468
-			return $function;
469
-		} else {
470
-			// default: one plural form for all cases but n==1 (english)
471
-			$function = create_function(
472
-				'$n',
473
-				'$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
474
-			);
475
-			$this->pluralFunctions[$string] = $function;
476
-			return $function;
477
-		}
478
-	}
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
+     * @param string|null $locale
96
+     * @return \OCP\IL10N
97
+     */
98
+    public function get($app, $lang = null, $locale = null) {
99
+        $app = \OC_App::cleanAppId($app);
100
+        if ($lang !== null) {
101
+            $lang = str_replace(array('\0', '/', '\\', '..'), '', (string) $lang);
102
+        }
103
+
104
+        $forceLang = $this->config->getSystemValue('force_language', false);
105
+        if (is_string($forceLang)) {
106
+            $lang = $forceLang;
107
+        }
108
+
109
+        if ($lang === null || !$this->languageExists($app, $lang)) {
110
+            $lang = $this->findLanguage($app);
111
+        }
112
+
113
+        if ($locale === null || !$this->localeExists($locale)) {
114
+            $locale = $this->findLocale($app, $lang);
115
+        }
116
+
117
+        if (!isset($this->instances[$lang][$app])) {
118
+            $this->instances[$lang][$app] = new L10N(
119
+                $this, $app, $lang, $locale,
120
+                $this->getL10nFilesForApp($app, $lang)
121
+            );
122
+        }
123
+
124
+        return $this->instances[$lang][$app];
125
+    }
126
+
127
+    /**
128
+     * Find the best language
129
+     *
130
+     * @param string|null $app App id or null for core
131
+     * @return string language If nothing works it returns 'en'
132
+     */
133
+    public function findLanguage($app = null) {
134
+        if ($this->requestLanguage !== '' && $this->languageExists($app, $this->requestLanguage)) {
135
+            return $this->requestLanguage;
136
+        }
137
+
138
+        /**
139
+         * At this point Nextcloud might not yet be installed and thus the lookup
140
+         * in the preferences table might fail. For this reason we need to check
141
+         * whether the instance has already been installed
142
+         *
143
+         * @link https://github.com/owncloud/core/issues/21955
144
+         */
145
+        if($this->config->getSystemValue('installed', false)) {
146
+            $userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
+            if(!is_null($userId)) {
148
+                $userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149
+            } else {
150
+                $userLang = null;
151
+            }
152
+        } else {
153
+            $userId = null;
154
+            $userLang = null;
155
+        }
156
+
157
+        if ($userLang) {
158
+            $this->requestLanguage = $userLang;
159
+            if ($this->languageExists($app, $userLang)) {
160
+                return $userLang;
161
+            }
162
+        }
163
+
164
+        try {
165
+            // Try to get the language from the Request
166
+            $lang = $this->getLanguageFromRequest($app);
167
+            if ($userId !== null && $app === null && !$userLang) {
168
+                $this->config->setUserValue($userId, 'core', 'lang', $lang);
169
+            }
170
+            return $lang;
171
+        } catch (LanguageNotFoundException $e) {
172
+            // Finding language from request failed fall back to default language
173
+            $defaultLanguage = $this->config->getSystemValue('default_language', false);
174
+            if ($defaultLanguage !== false && $this->languageExists($app, $defaultLanguage)) {
175
+                return $defaultLanguage;
176
+            }
177
+        }
178
+
179
+        // We could not find any language so fall back to english
180
+        return 'en';
181
+    }
182
+
183
+    public function findLocale($app = null, $lang = null)
184
+    {
185
+        if ($this->config->getSystemValue('installed', false)) {
186
+            $userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
187
+            $userLocale = null;
188
+            if (null !== $userId) {
189
+                $userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
190
+            }
191
+        } else {
192
+            $userId = null;
193
+            $userLocale = null;
194
+        }
195
+
196
+        if ($userLocale && $this->localeExists($userLocale)) {
197
+            return $userLocale;
198
+        }
199
+
200
+        // If no user locale set, use lang as locale
201
+        if (null !== $lang && $this->localeExists($lang)) {
202
+            return $lang;
203
+        }
204
+
205
+        // Default : use system default locale
206
+        $defaultLocale = $this->config->getSystemValue('default_locale', false);
207
+        if ($defaultLocale !== false && $this->localeExists($defaultLocale)) {
208
+            return $defaultLocale;
209
+        }
210
+
211
+        // At last, return USA
212
+        return 'en_US';
213
+    }
214
+
215
+    /**
216
+     * Find all available languages for an app
217
+     *
218
+     * @param string|null $app App id or null for core
219
+     * @return array an array of available languages
220
+     */
221
+    public function findAvailableLanguages($app = null) {
222
+        $key = $app;
223
+        if ($key === null) {
224
+            $key = 'null';
225
+        }
226
+
227
+        // also works with null as key
228
+        if (!empty($this->availableLanguages[$key])) {
229
+            return $this->availableLanguages[$key];
230
+        }
231
+
232
+        $available = ['en']; //english is always available
233
+        $dir = $this->findL10nDir($app);
234
+        if (is_dir($dir)) {
235
+            $files = scandir($dir);
236
+            if ($files !== false) {
237
+                foreach ($files as $file) {
238
+                    if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
239
+                        $available[] = substr($file, 0, -5);
240
+                    }
241
+                }
242
+            }
243
+        }
244
+
245
+        // merge with translations from theme
246
+        $theme = $this->config->getSystemValue('theme');
247
+        if (!empty($theme)) {
248
+            $themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
249
+
250
+            if (is_dir($themeDir)) {
251
+                $files = scandir($themeDir);
252
+                if ($files !== false) {
253
+                    foreach ($files as $file) {
254
+                        if (substr($file, -5) === '.json' && substr($file, 0, 4) !== 'l10n') {
255
+                            $available[] = substr($file, 0, -5);
256
+                        }
257
+                    }
258
+                }
259
+            }
260
+        }
261
+
262
+        $this->availableLanguages[$key] = $available;
263
+        return $available;
264
+    }
265
+
266
+    public function findAvailableLocales()
267
+    {
268
+        $localeData = file_get_contents(__DIR__ . '/locales.json');
269
+        return json_decode($localeData, true);
270
+    }
271
+
272
+    /**
273
+     * @param string|null $app App id or null for core
274
+     * @param string $lang
275
+     * @return bool
276
+     */
277
+    public function languageExists($app, $lang) {
278
+        if ($lang === 'en') {//english is always available
279
+            return true;
280
+        }
281
+
282
+        $languages = $this->findAvailableLanguages($app);
283
+        return array_search($lang, $languages) !== false;
284
+    }
285
+
286
+    /**
287
+     * @param string $locale
288
+     * @return bool
289
+     */
290
+    public function localeExists($locale) {
291
+        if ($locale === 'en') { //english is always available
292
+            return true;
293
+        }
294
+
295
+        $locales = $this->findAvailableLocales();
296
+
297
+        $userLocale = array_filter($locales, function($value) use ($locale) {
298
+            return $locale === $value['code'];
299
+        });
300
+
301
+        return !empty($userLocale);
302
+    }
303
+
304
+    /**
305
+     * @param string|null $app
306
+     * @return string
307
+     * @throws LanguageNotFoundException
308
+     */
309
+    private function getLanguageFromRequest($app) {
310
+        $header = $this->request->getHeader('ACCEPT_LANGUAGE');
311
+        if ($header) {
312
+            $available = $this->findAvailableLanguages($app);
313
+
314
+            // E.g. make sure that 'de' is before 'de_DE'.
315
+            sort($available);
316
+
317
+            $preferences = preg_split('/,\s*/', strtolower($header));
318
+            foreach ($preferences as $preference) {
319
+                list($preferred_language) = explode(';', $preference);
320
+                $preferred_language = str_replace('-', '_', $preferred_language);
321
+
322
+                foreach ($available as $available_language) {
323
+                    if ($preferred_language === strtolower($available_language)) {
324
+                        return $available_language;
325
+                    }
326
+                }
327
+
328
+                // Fallback from de_De to de
329
+                foreach ($available as $available_language) {
330
+                    if (substr($preferred_language, 0, 2) === $available_language) {
331
+                        return $available_language;
332
+                    }
333
+                }
334
+            }
335
+        }
336
+
337
+        throw new LanguageNotFoundException();
338
+    }
339
+
340
+    /**
341
+     * Checks if $sub is a subdirectory of $parent
342
+     *
343
+     * @param string $sub
344
+     * @param string $parent
345
+     * @return bool
346
+     */
347
+    private function isSubDirectory($sub, $parent) {
348
+        // Check whether $sub contains no ".."
349
+        if(strpos($sub, '..') !== false) {
350
+            return false;
351
+        }
352
+
353
+        // Check whether $sub is a subdirectory of $parent
354
+        if (strpos($sub, $parent) === 0) {
355
+            return true;
356
+        }
357
+
358
+        return false;
359
+    }
360
+
361
+    /**
362
+     * Get a list of language files that should be loaded
363
+     *
364
+     * @param string $app
365
+     * @param string $lang
366
+     * @return string[]
367
+     */
368
+    // FIXME This method is only public, until OC_L10N does not need it anymore,
369
+    // FIXME This is also the reason, why it is not in the public interface
370
+    public function getL10nFilesForApp($app, $lang) {
371
+        $languageFiles = [];
372
+
373
+        $i18nDir = $this->findL10nDir($app);
374
+        $transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
375
+
376
+        if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
377
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
378
+                || $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
379
+                || $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
380
+            )
381
+            && file_exists($transFile)) {
382
+            // load the translations file
383
+            $languageFiles[] = $transFile;
384
+        }
385
+
386
+        // merge with translations from theme
387
+        $theme = $this->config->getSystemValue('theme');
388
+        if (!empty($theme)) {
389
+            $transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
390
+            if (file_exists($transFile)) {
391
+                $languageFiles[] = $transFile;
392
+            }
393
+        }
394
+
395
+        return $languageFiles;
396
+    }
397
+
398
+    /**
399
+     * find the l10n directory
400
+     *
401
+     * @param string $app App id or empty string for core
402
+     * @return string directory
403
+     */
404
+    protected function findL10nDir($app = null) {
405
+        if (in_array($app, ['core', 'lib', 'settings'])) {
406
+            if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
407
+                return $this->serverRoot . '/' . $app . '/l10n/';
408
+            }
409
+        } else if ($app && \OC_App::getAppPath($app) !== false) {
410
+            // Check if the app is in the app folder
411
+            return \OC_App::getAppPath($app) . '/l10n/';
412
+        }
413
+        return $this->serverRoot . '/core/l10n/';
414
+    }
415
+
416
+
417
+    /**
418
+     * Creates a function from the plural string
419
+     *
420
+     * Parts of the code is copied from Habari:
421
+     * https://github.com/habari/system/blob/master/classes/locale.php
422
+     * @param string $string
423
+     * @return string
424
+     */
425
+    public function createPluralFunction($string) {
426
+        if (isset($this->pluralFunctions[$string])) {
427
+            return $this->pluralFunctions[$string];
428
+        }
429
+
430
+        if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
431
+            // sanitize
432
+            $nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
433
+            $plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
434
+
435
+            $body = str_replace(
436
+                array( 'plural', 'n', '$n$plurals', ),
437
+                array( '$plural', '$n', '$nplurals', ),
438
+                'nplurals='. $nplurals . '; plural=' . $plural
439
+            );
440
+
441
+            // add parents
442
+            // important since PHP's ternary evaluates from left to right
443
+            $body .= ';';
444
+            $res = '';
445
+            $p = 0;
446
+            for($i = 0; $i < strlen($body); $i++) {
447
+                $ch = $body[$i];
448
+                switch ( $ch ) {
449
+                    case '?':
450
+                        $res .= ' ? (';
451
+                        $p++;
452
+                        break;
453
+                    case ':':
454
+                        $res .= ') : (';
455
+                        break;
456
+                    case ';':
457
+                        $res .= str_repeat( ')', $p ) . ';';
458
+                        $p = 0;
459
+                        break;
460
+                    default:
461
+                        $res .= $ch;
462
+                }
463
+            }
464
+
465
+            $body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
466
+            $function = create_function('$n', $body);
467
+            $this->pluralFunctions[$string] = $function;
468
+            return $function;
469
+        } else {
470
+            // default: one plural form for all cases but n==1 (english)
471
+            $function = create_function(
472
+                '$n',
473
+                '$nplurals=2;$plural=($n==1?0:1);return ($plural>=$nplurals?$nplurals-1:$plural);'
474
+            );
475
+            $this->pluralFunctions[$string] = $function;
476
+            return $function;
477
+        }
478
+    }
479 479
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -142,9 +142,9 @@  discard block
 block discarded – undo
142 142
 		 *
143 143
 		 * @link https://github.com/owncloud/core/issues/21955
144 144
 		 */
145
-		if($this->config->getSystemValue('installed', false)) {
146
-			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() :  null;
147
-			if(!is_null($userId)) {
145
+		if ($this->config->getSystemValue('installed', false)) {
146
+			$userId = !is_null($this->userSession->getUser()) ? $this->userSession->getUser()->getUID() : null;
147
+			if (!is_null($userId)) {
148 148
 				$userLang = $this->config->getUserValue($userId, 'core', 'lang', null);
149 149
 			} else {
150 150
 				$userLang = null;
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	public function findLocale($app = null, $lang = null)
184 184
 	{
185 185
 		if ($this->config->getSystemValue('installed', false)) {
186
-			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() :  null;
186
+			$userId = null !== $this->userSession->getUser() ? $this->userSession->getUser()->getUID() : null;
187 187
 			$userLocale = null;
188 188
 			if (null !== $userId) {
189 189
 				$userLocale = $this->config->getUserValue($userId, 'core', 'locale', null);
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 		// merge with translations from theme
246 246
 		$theme = $this->config->getSystemValue('theme');
247 247
 		if (!empty($theme)) {
248
-			$themeDir = $this->serverRoot . '/themes/' . $theme . substr($dir, strlen($this->serverRoot));
248
+			$themeDir = $this->serverRoot.'/themes/'.$theme.substr($dir, strlen($this->serverRoot));
249 249
 
250 250
 			if (is_dir($themeDir)) {
251 251
 				$files = scandir($themeDir);
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
 
266 266
 	public function findAvailableLocales()
267 267
 	{
268
-		$localeData = file_get_contents(__DIR__ . '/locales.json');
268
+		$localeData = file_get_contents(__DIR__.'/locales.json');
269 269
 		return json_decode($localeData, true);
270 270
 	}
271 271
 
@@ -346,7 +346,7 @@  discard block
 block discarded – undo
346 346
 	 */
347 347
 	private function isSubDirectory($sub, $parent) {
348 348
 		// Check whether $sub contains no ".."
349
-		if(strpos($sub, '..') !== false) {
349
+		if (strpos($sub, '..') !== false) {
350 350
 			return false;
351 351
 		}
352 352
 
@@ -371,12 +371,12 @@  discard block
 block discarded – undo
371 371
 		$languageFiles = [];
372 372
 
373 373
 		$i18nDir = $this->findL10nDir($app);
374
-		$transFile = strip_tags($i18nDir) . strip_tags($lang) . '.json';
374
+		$transFile = strip_tags($i18nDir).strip_tags($lang).'.json';
375 375
 
376
-		if (($this->isSubDirectory($transFile, $this->serverRoot . '/core/l10n/')
377
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/lib/l10n/')
378
-				|| $this->isSubDirectory($transFile, $this->serverRoot . '/settings/l10n/')
379
-				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app) . '/l10n/')
376
+		if (($this->isSubDirectory($transFile, $this->serverRoot.'/core/l10n/')
377
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/lib/l10n/')
378
+				|| $this->isSubDirectory($transFile, $this->serverRoot.'/settings/l10n/')
379
+				|| $this->isSubDirectory($transFile, \OC_App::getAppPath($app).'/l10n/')
380 380
 			)
381 381
 			&& file_exists($transFile)) {
382 382
 			// load the translations file
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 		// merge with translations from theme
387 387
 		$theme = $this->config->getSystemValue('theme');
388 388
 		if (!empty($theme)) {
389
-			$transFile = $this->serverRoot . '/themes/' . $theme . substr($transFile, strlen($this->serverRoot));
389
+			$transFile = $this->serverRoot.'/themes/'.$theme.substr($transFile, strlen($this->serverRoot));
390 390
 			if (file_exists($transFile)) {
391 391
 				$languageFiles[] = $transFile;
392 392
 			}
@@ -403,14 +403,14 @@  discard block
 block discarded – undo
403 403
 	 */
404 404
 	protected function findL10nDir($app = null) {
405 405
 		if (in_array($app, ['core', 'lib', 'settings'])) {
406
-			if (file_exists($this->serverRoot . '/' . $app . '/l10n/')) {
407
-				return $this->serverRoot . '/' . $app . '/l10n/';
406
+			if (file_exists($this->serverRoot.'/'.$app.'/l10n/')) {
407
+				return $this->serverRoot.'/'.$app.'/l10n/';
408 408
 			}
409 409
 		} else if ($app && \OC_App::getAppPath($app) !== false) {
410 410
 			// Check if the app is in the app folder
411
-			return \OC_App::getAppPath($app) . '/l10n/';
411
+			return \OC_App::getAppPath($app).'/l10n/';
412 412
 		}
413
-		return $this->serverRoot . '/core/l10n/';
413
+		return $this->serverRoot.'/core/l10n/';
414 414
 	}
415 415
 
416 416
 
@@ -427,15 +427,15 @@  discard block
 block discarded – undo
427 427
 			return $this->pluralFunctions[$string];
428 428
 		}
429 429
 
430
-		if (preg_match( '/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
430
+		if (preg_match('/^\s*nplurals\s*=\s*(\d+)\s*;\s*plural=(.*)$/u', $string, $matches)) {
431 431
 			// sanitize
432
-			$nplurals = preg_replace( '/[^0-9]/', '', $matches[1] );
433
-			$plural = preg_replace( '#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2] );
432
+			$nplurals = preg_replace('/[^0-9]/', '', $matches[1]);
433
+			$plural = preg_replace('#[^n0-9:\(\)\?\|\&=!<>+*/\%-]#', '', $matches[2]);
434 434
 
435 435
 			$body = str_replace(
436
-				array( 'plural', 'n', '$n$plurals', ),
437
-				array( '$plural', '$n', '$nplurals', ),
438
-				'nplurals='. $nplurals . '; plural=' . $plural
436
+				array('plural', 'n', '$n$plurals',),
437
+				array('$plural', '$n', '$nplurals',),
438
+				'nplurals='.$nplurals.'; plural='.$plural
439 439
 			);
440 440
 
441 441
 			// add parents
@@ -443,9 +443,9 @@  discard block
 block discarded – undo
443 443
 			$body .= ';';
444 444
 			$res = '';
445 445
 			$p = 0;
446
-			for($i = 0; $i < strlen($body); $i++) {
446
+			for ($i = 0; $i < strlen($body); $i++) {
447 447
 				$ch = $body[$i];
448
-				switch ( $ch ) {
448
+				switch ($ch) {
449 449
 					case '?':
450 450
 						$res .= ' ? (';
451 451
 						$p++;
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 						$res .= ') : (';
455 455
 						break;
456 456
 					case ';':
457
-						$res .= str_repeat( ')', $p ) . ';';
457
+						$res .= str_repeat(')', $p).';';
458 458
 						$p = 0;
459 459
 						break;
460 460
 					default:
@@ -462,7 +462,7 @@  discard block
 block discarded – undo
462 462
 				}
463 463
 			}
464 464
 
465
-			$body = $res . 'return ($plural>=$nplurals?$nplurals-1:$plural);';
465
+			$body = $res.'return ($plural>=$nplurals?$nplurals-1:$plural);';
466 466
 			$function = create_function('$n', $body);
467 467
 			$this->pluralFunctions[$string] = $function;
468 468
 			return $function;
Please login to merge, or discard this patch.
lib/public/L10N/IFactory.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -25,61 +25,61 @@
 block discarded – undo
25 25
  * @since 8.2.0
26 26
  */
27 27
 interface IFactory {
28
-	/**
29
-	 * Get a language instance
30
-	 *
31
-	 * @param string $app
32
-	 * @param string|null $lang
33
-	 * @return \OCP\IL10N
34
-	 * @since 8.2.0
35
-	 */
36
-	public function get($app, $lang = null);
28
+    /**
29
+     * Get a language instance
30
+     *
31
+     * @param string $app
32
+     * @param string|null $lang
33
+     * @return \OCP\IL10N
34
+     * @since 8.2.0
35
+     */
36
+    public function get($app, $lang = null);
37 37
 
38
-	/**
39
-	 * Find the best language
40
-	 *
41
-	 * @param string|null $app App id or null for core
42
-	 * @return string language If nothing works it returns 'en'
43
-	 * @since 9.0.0
44
-	 */
45
-	public function findLanguage($app = null);
38
+    /**
39
+     * Find the best language
40
+     *
41
+     * @param string|null $app App id or null for core
42
+     * @return string language If nothing works it returns 'en'
43
+     * @since 9.0.0
44
+     */
45
+    public function findLanguage($app = null);
46 46
 
47
-	/**
48
-	 * Find all available languages for an app
49
-	 *
50
-	 * @param string|null $app App id or null for core
51
-	 * @return string[] an array of available languages
52
-	 * @since 9.0.0
53
-	 */
54
-	public function findAvailableLanguages($app = null);
47
+    /**
48
+     * Find all available languages for an app
49
+     *
50
+     * @param string|null $app App id or null for core
51
+     * @return string[] an array of available languages
52
+     * @since 9.0.0
53
+     */
54
+    public function findAvailableLanguages($app = null);
55 55
 
56
-	/**
57
-	 * @return array an array of available
58
-	 * @since 13.0.0
59
-	 */
60
-	public function findAvailableLocales();
56
+    /**
57
+     * @return array an array of available
58
+     * @since 13.0.0
59
+     */
60
+    public function findAvailableLocales();
61 61
 
62
-	/**
63
-	 * @param string|null $app App id or null for core
64
-	 * @param string $lang
65
-	 * @return bool
66
-	 * @since 9.0.0
67
-	 */
68
-	public function languageExists($app, $lang);
62
+    /**
63
+     * @param string|null $app App id or null for core
64
+     * @param string $lang
65
+     * @return bool
66
+     * @since 9.0.0
67
+     */
68
+    public function languageExists($app, $lang);
69 69
 
70
-	/**
71
-	 * @param string $locale
72
-	 * @return bool
73
-	 * @since 13.0.0
74
-	 */
75
-	public function localeExists($locale);
70
+    /**
71
+     * @param string $locale
72
+     * @return bool
73
+     * @since 13.0.0
74
+     */
75
+    public function localeExists($locale);
76 76
 
77
-	/**
78
-	 * Creates a function from the plural string
79
-	 *
80
-	 * @param string $string
81
-	 * @return string Unique function name
82
-	 * @since 9.0.0
83
-	 */
84
-	public function createPluralFunction($string);
77
+    /**
78
+     * Creates a function from the plural string
79
+     *
80
+     * @param string $string
81
+     * @return string Unique function name
82
+     * @since 9.0.0
83
+     */
84
+    public function createPluralFunction($string);
85 85
 }
Please login to merge, or discard this patch.
lib/private/Settings/Personal/PersonalInfo.php 2 patches
Indentation   +277 added lines, -277 removed lines patch added patch discarded remove patch
@@ -40,282 +40,282 @@
 block discarded – undo
40 40
 use OCP\Settings\ISettings;
41 41
 
42 42
 class PersonalInfo implements ISettings {
43
-	/** @var IConfig */
44
-	private $config;
45
-	/** @var IUserManager */
46
-	private $userManager;
47
-	/** @var AccountManager */
48
-	private $accountManager;
49
-	/** @var IGroupManager */
50
-	private $groupManager;
51
-	/** @var IAppManager */
52
-	private $appManager;
53
-	/** @var IFactory */
54
-	private $l10nFactory;
55
-
56
-	const COMMON_LANGUAGE_CODES = [
57
-		'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
58
-		'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
59
-	];
60
-
61
-	/** @var IL10N */
62
-	private $l;
63
-
64
-	/**
65
-	 * @param IConfig $config
66
-	 * @param IUserManager $userManager
67
-	 * @param IGroupManager $groupManager
68
-	 * @param AccountManager $accountManager
69
-	 * @param IFactory $l10nFactory
70
-	 * @param IL10N $l
71
-	 */
72
-	public function __construct(
73
-		IConfig $config,
74
-		IUserManager $userManager,
75
-		IGroupManager $groupManager,
76
-		AccountManager $accountManager,
77
-		IAppManager $appManager,
78
-		IFactory $l10nFactory,
79
-		IL10N $l
80
-	) {
81
-		$this->config = $config;
82
-		$this->userManager = $userManager;
83
-		$this->accountManager = $accountManager;
84
-		$this->groupManager = $groupManager;
85
-		$this->appManager = $appManager;
86
-		$this->l10nFactory = $l10nFactory;
87
-		$this->l = $l;
88
-	}
89
-
90
-	/**
91
-	 * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
92
-	 * @since 9.1
93
-	 */
94
-	public function getForm() {
95
-		$federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
96
-		$lookupServerUploadEnabled = false;
97
-		if($federatedFileSharingEnabled) {
98
-			$federatedFileSharing = new Application();
99
-			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
100
-			$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
101
-		}
102
-
103
-		$uid = \OC_User::getUser();
104
-		$user = $this->userManager->get($uid);
105
-		$userData = $this->accountManager->getUser($user);
106
-
107
-		$storageInfo = \OC_Helper::getStorageInfo('/');
108
-		if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) {
109
-			$totalSpace = $this->l->t('Unlimited');
110
-		} else {
111
-			$totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
112
-		}
113
-
114
-		$languageParameters = $this->getLanguages($user);
115
-		$localeParameters = $this->getLocales($user);
116
-		$messageParameters = $this->getMessageParameters($userData);
117
-
118
-		$parameters = [
119
-			'total_space' => $totalSpace,
120
-			'usage' => \OC_Helper::humanFileSize($storageInfo['used']),
121
-			'usage_relative' => $storageInfo['relative'],
122
-			'quota' => $storageInfo['quota'],
123
-			'avatarChangeSupported' => \OC_User::canUserChangeAvatar($uid),
124
-			'lookupServerUploadEnabled' => $lookupServerUploadEnabled,
125
-			'avatarScope' => $userData[AccountManager::PROPERTY_AVATAR]['scope'],
126
-			'displayNameChangeSupported' => \OC_User::canUserChangeDisplayName($uid),
127
-			'displayName' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'],
128
-			'displayNameScope' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
129
-			'email' => $userData[AccountManager::PROPERTY_EMAIL]['value'],
130
-			'emailScope' => $userData[AccountManager::PROPERTY_EMAIL]['scope'],
131
-			'emailVerification' => $userData[AccountManager::PROPERTY_EMAIL]['verified'],
132
-			'phone' => $userData[AccountManager::PROPERTY_PHONE]['value'],
133
-			'phoneScope' => $userData[AccountManager::PROPERTY_PHONE]['scope'],
134
-			'address' => $userData[AccountManager::PROPERTY_ADDRESS]['value'],
135
-			'addressScope' => $userData[AccountManager::PROPERTY_ADDRESS]['scope'],
136
-			'website' =>  $userData[AccountManager::PROPERTY_WEBSITE]['value'],
137
-			'websiteScope' =>  $userData[AccountManager::PROPERTY_WEBSITE]['scope'],
138
-			'websiteVerification' => $userData[AccountManager::PROPERTY_WEBSITE]['verified'],
139
-			'twitter' => $userData[AccountManager::PROPERTY_TWITTER]['value'],
140
-			'twitterScope' => $userData[AccountManager::PROPERTY_TWITTER]['scope'],
141
-			'twitterVerification' => $userData[AccountManager::PROPERTY_TWITTER]['verified'],
142
-			'groups' => $this->getGroups($user),
143
-			'passwordChangeSupported' => \OC_User::canUserChangePassword($uid),
144
-		] + $messageParameters + $languageParameters + $localeParameters;
145
-
146
-
147
-		return new TemplateResponse('settings', 'settings/personal/personal.info', $parameters, '');
148
-	}
149
-
150
-	/**
151
-	 * @return string the section ID, e.g. 'sharing'
152
-	 * @since 9.1
153
-	 */
154
-	public function getSection() {
155
-		return 'personal-info';
156
-	}
157
-
158
-	/**
159
-	 * @return int whether the form should be rather on the top or bottom of
160
-	 * the admin section. The forms are arranged in ascending order of the
161
-	 * priority values. It is required to return a value between 0 and 100.
162
-	 *
163
-	 * E.g.: 70
164
-	 * @since 9.1
165
-	 */
166
-	public function getPriority() {
167
-		return 10;
168
-	}
169
-
170
-	/**
171
-	 * returns a sorted list of the user's group GIDs
172
-	 *
173
-	 * @param IUser $user
174
-	 * @return array
175
-	 */
176
-	private function getGroups(IUser $user) {
177
-		$groups = array_map(
178
-			function(IGroup $group) {
179
-				return $group->getGID();
180
-			},
181
-			$this->groupManager->getUserGroups($user)
182
-		);
183
-		sort($groups);
184
-
185
-		return $groups;
186
-	}
187
-
188
-	/**
189
-	 * returns the user language, common language and other languages in an
190
-	 * associative array
191
-	 *
192
-	 * @param IUser $user
193
-	 * @return array
194
-	 */
195
-	private function getLanguages(IUser $user) {
196
-		$forceLanguage = $this->config->getSystemValue('force_language', false);
197
-		if($forceLanguage !== false) {
198
-			return [];
199
-		}
200
-
201
-		$uid = $user->getUID();
202
-
203
-		$userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
204
-		$languageCodes = $this->l10nFactory->findAvailableLanguages();
205
-
206
-		$commonLanguages = [];
207
-		$languages = [];
208
-
209
-		foreach($languageCodes as $lang) {
210
-			$l = \OC::$server->getL10N('settings', $lang);
211
-			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
212
-			$potentialName = (string) $l->t('__language_name__');
213
-			if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
214
-				$ln = array('code' => $lang, 'name' => $potentialName);
215
-			} elseif ($lang === 'en') {
216
-				$ln = ['code' => $lang, 'name' => 'English (US)'];
217
-			}else{//fallback to language code
218
-				$ln=array('code'=>$lang, 'name'=>$lang);
219
-			}
220
-
221
-			// put appropriate languages into appropriate arrays, to print them sorted
222
-			// used language -> common languages -> divider -> other languages
223
-			if ($lang === $userLang) {
224
-				$userLang = $ln;
225
-			} elseif (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
226
-				$commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)]=$ln;
227
-			} else {
228
-				$languages[]=$ln;
229
-			}
230
-		}
231
-
232
-		// if user language is not available but set somehow: show the actual code as name
233
-		if (!is_array($userLang)) {
234
-			$userLang = [
235
-				'code' => $userLang,
236
-				'name' => $userLang,
237
-			];
238
-		}
239
-
240
-		ksort($commonLanguages);
241
-
242
-		// sort now by displayed language not the iso-code
243
-		usort( $languages, function ($a, $b) {
244
-			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
245
-				// If a doesn't have a name, but b does, list b before a
246
-				return 1;
247
-			}
248
-			if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
249
-				// If a does have a name, but b doesn't, list a before b
250
-				return -1;
251
-			}
252
-			// Otherwise compare the names
253
-			return strcmp($a['name'], $b['name']);
254
-		});
255
-
256
-		return [
257
-			'activelanguage' => $userLang,
258
-			'commonlanguages' => $commonLanguages,
259
-			'languages' => $languages
260
-		];
261
-	}
262
-
263
-	private function getLocales(IUser $user) {
264
-		$forceLanguage = $this->config->getSystemValue('force_locale', false);
265
-		if($forceLanguage !== false) {
266
-			return [];
267
-		}
268
-
269
-		$uid = $user->getUID();
270
-
271
-		$userLocaleString = $this->config->getUserValue($uid, 'core', 'locale', 'en_US');
272
-
273
-		$userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
274
-
275
-		$localeCodes = $this->l10nFactory->findAvailableLocales();
276
-
277
-		$userLocale = array_filter($localeCodes, function($value) use ($userLocaleString) {
278
-			return $userLocaleString === $value['code'];
279
-		});
280
-
281
-		if (!empty($userLocale))
282
-		{
283
-			$userLocale = reset($userLocale);
284
-		}
285
-
286
-		$localesForLanguage = array_filter($localeCodes, function($localeCode) use ($userLang) {
287
-			return 0 === strpos($localeCode['code'], $userLang);
288
-		});
289
-
290
-		return [
291
-			'activelocaleLang' => $userLocaleString,
292
-			'activelocale' => $userLocale,
293
-			'locales' => $localeCodes,
294
-			'localesforlanguage' => $localesForLanguage,
295
-		];
296
-	}
297
-
298
-	/**
299
-	 * @param array $userData
300
-	 * @return array
301
-	 */
302
-	private function getMessageParameters(array $userData) {
303
-		$needVerifyMessage = [AccountManager::PROPERTY_EMAIL, AccountManager::PROPERTY_WEBSITE, AccountManager::PROPERTY_TWITTER];
304
-		$messageParameters = [];
305
-		foreach ($needVerifyMessage as $property) {
306
-			switch ($userData[$property]['verified']) {
307
-				case AccountManager::VERIFIED:
308
-					$message = $this->l->t('Verifying');
309
-					break;
310
-				case AccountManager::VERIFICATION_IN_PROGRESS:
311
-					$message = $this->l->t('Verifying …');
312
-					break;
313
-				default:
314
-					$message = $this->l->t('Verify');
315
-			}
316
-			$messageParameters[$property . 'Message'] = $message;
317
-		}
318
-		return $messageParameters;
319
-	}
43
+    /** @var IConfig */
44
+    private $config;
45
+    /** @var IUserManager */
46
+    private $userManager;
47
+    /** @var AccountManager */
48
+    private $accountManager;
49
+    /** @var IGroupManager */
50
+    private $groupManager;
51
+    /** @var IAppManager */
52
+    private $appManager;
53
+    /** @var IFactory */
54
+    private $l10nFactory;
55
+
56
+    const COMMON_LANGUAGE_CODES = [
57
+        'en', 'es', 'fr', 'de', 'de_DE', 'ja', 'ar', 'ru', 'nl', 'it',
58
+        'pt_BR', 'pt_PT', 'da', 'fi_FI', 'nb_NO', 'sv', 'tr', 'zh_CN', 'ko'
59
+    ];
60
+
61
+    /** @var IL10N */
62
+    private $l;
63
+
64
+    /**
65
+     * @param IConfig $config
66
+     * @param IUserManager $userManager
67
+     * @param IGroupManager $groupManager
68
+     * @param AccountManager $accountManager
69
+     * @param IFactory $l10nFactory
70
+     * @param IL10N $l
71
+     */
72
+    public function __construct(
73
+        IConfig $config,
74
+        IUserManager $userManager,
75
+        IGroupManager $groupManager,
76
+        AccountManager $accountManager,
77
+        IAppManager $appManager,
78
+        IFactory $l10nFactory,
79
+        IL10N $l
80
+    ) {
81
+        $this->config = $config;
82
+        $this->userManager = $userManager;
83
+        $this->accountManager = $accountManager;
84
+        $this->groupManager = $groupManager;
85
+        $this->appManager = $appManager;
86
+        $this->l10nFactory = $l10nFactory;
87
+        $this->l = $l;
88
+    }
89
+
90
+    /**
91
+     * @return TemplateResponse returns the instance with all parameters set, ready to be rendered
92
+     * @since 9.1
93
+     */
94
+    public function getForm() {
95
+        $federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
96
+        $lookupServerUploadEnabled = false;
97
+        if($federatedFileSharingEnabled) {
98
+            $federatedFileSharing = new Application();
99
+            $shareProvider = $federatedFileSharing->getFederatedShareProvider();
100
+            $lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
101
+        }
102
+
103
+        $uid = \OC_User::getUser();
104
+        $user = $this->userManager->get($uid);
105
+        $userData = $this->accountManager->getUser($user);
106
+
107
+        $storageInfo = \OC_Helper::getStorageInfo('/');
108
+        if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) {
109
+            $totalSpace = $this->l->t('Unlimited');
110
+        } else {
111
+            $totalSpace = \OC_Helper::humanFileSize($storageInfo['total']);
112
+        }
113
+
114
+        $languageParameters = $this->getLanguages($user);
115
+        $localeParameters = $this->getLocales($user);
116
+        $messageParameters = $this->getMessageParameters($userData);
117
+
118
+        $parameters = [
119
+            'total_space' => $totalSpace,
120
+            'usage' => \OC_Helper::humanFileSize($storageInfo['used']),
121
+            'usage_relative' => $storageInfo['relative'],
122
+            'quota' => $storageInfo['quota'],
123
+            'avatarChangeSupported' => \OC_User::canUserChangeAvatar($uid),
124
+            'lookupServerUploadEnabled' => $lookupServerUploadEnabled,
125
+            'avatarScope' => $userData[AccountManager::PROPERTY_AVATAR]['scope'],
126
+            'displayNameChangeSupported' => \OC_User::canUserChangeDisplayName($uid),
127
+            'displayName' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['value'],
128
+            'displayNameScope' => $userData[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
129
+            'email' => $userData[AccountManager::PROPERTY_EMAIL]['value'],
130
+            'emailScope' => $userData[AccountManager::PROPERTY_EMAIL]['scope'],
131
+            'emailVerification' => $userData[AccountManager::PROPERTY_EMAIL]['verified'],
132
+            'phone' => $userData[AccountManager::PROPERTY_PHONE]['value'],
133
+            'phoneScope' => $userData[AccountManager::PROPERTY_PHONE]['scope'],
134
+            'address' => $userData[AccountManager::PROPERTY_ADDRESS]['value'],
135
+            'addressScope' => $userData[AccountManager::PROPERTY_ADDRESS]['scope'],
136
+            'website' =>  $userData[AccountManager::PROPERTY_WEBSITE]['value'],
137
+            'websiteScope' =>  $userData[AccountManager::PROPERTY_WEBSITE]['scope'],
138
+            'websiteVerification' => $userData[AccountManager::PROPERTY_WEBSITE]['verified'],
139
+            'twitter' => $userData[AccountManager::PROPERTY_TWITTER]['value'],
140
+            'twitterScope' => $userData[AccountManager::PROPERTY_TWITTER]['scope'],
141
+            'twitterVerification' => $userData[AccountManager::PROPERTY_TWITTER]['verified'],
142
+            'groups' => $this->getGroups($user),
143
+            'passwordChangeSupported' => \OC_User::canUserChangePassword($uid),
144
+        ] + $messageParameters + $languageParameters + $localeParameters;
145
+
146
+
147
+        return new TemplateResponse('settings', 'settings/personal/personal.info', $parameters, '');
148
+    }
149
+
150
+    /**
151
+     * @return string the section ID, e.g. 'sharing'
152
+     * @since 9.1
153
+     */
154
+    public function getSection() {
155
+        return 'personal-info';
156
+    }
157
+
158
+    /**
159
+     * @return int whether the form should be rather on the top or bottom of
160
+     * the admin section. The forms are arranged in ascending order of the
161
+     * priority values. It is required to return a value between 0 and 100.
162
+     *
163
+     * E.g.: 70
164
+     * @since 9.1
165
+     */
166
+    public function getPriority() {
167
+        return 10;
168
+    }
169
+
170
+    /**
171
+     * returns a sorted list of the user's group GIDs
172
+     *
173
+     * @param IUser $user
174
+     * @return array
175
+     */
176
+    private function getGroups(IUser $user) {
177
+        $groups = array_map(
178
+            function(IGroup $group) {
179
+                return $group->getGID();
180
+            },
181
+            $this->groupManager->getUserGroups($user)
182
+        );
183
+        sort($groups);
184
+
185
+        return $groups;
186
+    }
187
+
188
+    /**
189
+     * returns the user language, common language and other languages in an
190
+     * associative array
191
+     *
192
+     * @param IUser $user
193
+     * @return array
194
+     */
195
+    private function getLanguages(IUser $user) {
196
+        $forceLanguage = $this->config->getSystemValue('force_language', false);
197
+        if($forceLanguage !== false) {
198
+            return [];
199
+        }
200
+
201
+        $uid = $user->getUID();
202
+
203
+        $userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
204
+        $languageCodes = $this->l10nFactory->findAvailableLanguages();
205
+
206
+        $commonLanguages = [];
207
+        $languages = [];
208
+
209
+        foreach($languageCodes as $lang) {
210
+            $l = \OC::$server->getL10N('settings', $lang);
211
+            // TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
212
+            $potentialName = (string) $l->t('__language_name__');
213
+            if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
214
+                $ln = array('code' => $lang, 'name' => $potentialName);
215
+            } elseif ($lang === 'en') {
216
+                $ln = ['code' => $lang, 'name' => 'English (US)'];
217
+            }else{//fallback to language code
218
+                $ln=array('code'=>$lang, 'name'=>$lang);
219
+            }
220
+
221
+            // put appropriate languages into appropriate arrays, to print them sorted
222
+            // used language -> common languages -> divider -> other languages
223
+            if ($lang === $userLang) {
224
+                $userLang = $ln;
225
+            } elseif (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
226
+                $commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)]=$ln;
227
+            } else {
228
+                $languages[]=$ln;
229
+            }
230
+        }
231
+
232
+        // if user language is not available but set somehow: show the actual code as name
233
+        if (!is_array($userLang)) {
234
+            $userLang = [
235
+                'code' => $userLang,
236
+                'name' => $userLang,
237
+            ];
238
+        }
239
+
240
+        ksort($commonLanguages);
241
+
242
+        // sort now by displayed language not the iso-code
243
+        usort( $languages, function ($a, $b) {
244
+            if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
245
+                // If a doesn't have a name, but b does, list b before a
246
+                return 1;
247
+            }
248
+            if ($a['code'] !== $a['name'] && $b['code'] === $b['name']) {
249
+                // If a does have a name, but b doesn't, list a before b
250
+                return -1;
251
+            }
252
+            // Otherwise compare the names
253
+            return strcmp($a['name'], $b['name']);
254
+        });
255
+
256
+        return [
257
+            'activelanguage' => $userLang,
258
+            'commonlanguages' => $commonLanguages,
259
+            'languages' => $languages
260
+        ];
261
+    }
262
+
263
+    private function getLocales(IUser $user) {
264
+        $forceLanguage = $this->config->getSystemValue('force_locale', false);
265
+        if($forceLanguage !== false) {
266
+            return [];
267
+        }
268
+
269
+        $uid = $user->getUID();
270
+
271
+        $userLocaleString = $this->config->getUserValue($uid, 'core', 'locale', 'en_US');
272
+
273
+        $userLang = $this->config->getUserValue($uid, 'core', 'lang', $this->l10nFactory->findLanguage());
274
+
275
+        $localeCodes = $this->l10nFactory->findAvailableLocales();
276
+
277
+        $userLocale = array_filter($localeCodes, function($value) use ($userLocaleString) {
278
+            return $userLocaleString === $value['code'];
279
+        });
280
+
281
+        if (!empty($userLocale))
282
+        {
283
+            $userLocale = reset($userLocale);
284
+        }
285
+
286
+        $localesForLanguage = array_filter($localeCodes, function($localeCode) use ($userLang) {
287
+            return 0 === strpos($localeCode['code'], $userLang);
288
+        });
289
+
290
+        return [
291
+            'activelocaleLang' => $userLocaleString,
292
+            'activelocale' => $userLocale,
293
+            'locales' => $localeCodes,
294
+            'localesforlanguage' => $localesForLanguage,
295
+        ];
296
+    }
297
+
298
+    /**
299
+     * @param array $userData
300
+     * @return array
301
+     */
302
+    private function getMessageParameters(array $userData) {
303
+        $needVerifyMessage = [AccountManager::PROPERTY_EMAIL, AccountManager::PROPERTY_WEBSITE, AccountManager::PROPERTY_TWITTER];
304
+        $messageParameters = [];
305
+        foreach ($needVerifyMessage as $property) {
306
+            switch ($userData[$property]['verified']) {
307
+                case AccountManager::VERIFIED:
308
+                    $message = $this->l->t('Verifying');
309
+                    break;
310
+                case AccountManager::VERIFICATION_IN_PROGRESS:
311
+                    $message = $this->l->t('Verifying …');
312
+                    break;
313
+                default:
314
+                    $message = $this->l->t('Verify');
315
+            }
316
+            $messageParameters[$property . 'Message'] = $message;
317
+        }
318
+        return $messageParameters;
319
+    }
320 320
 
321 321
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -94,7 +94,7 @@  discard block
 block discarded – undo
94 94
 	public function getForm() {
95 95
 		$federatedFileSharingEnabled = $this->appManager->isEnabledForUser('federatedfilesharing');
96 96
 		$lookupServerUploadEnabled = false;
97
-		if($federatedFileSharingEnabled) {
97
+		if ($federatedFileSharingEnabled) {
98 98
 			$federatedFileSharing = new Application();
99 99
 			$shareProvider = $federatedFileSharing->getFederatedShareProvider();
100 100
 			$lookupServerUploadEnabled = $shareProvider->isLookupServerUploadEnabled();
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 	 */
195 195
 	private function getLanguages(IUser $user) {
196 196
 		$forceLanguage = $this->config->getSystemValue('force_language', false);
197
-		if($forceLanguage !== false) {
197
+		if ($forceLanguage !== false) {
198 198
 			return [];
199 199
 		}
200 200
 
@@ -206,16 +206,16 @@  discard block
 block discarded – undo
206 206
 		$commonLanguages = [];
207 207
 		$languages = [];
208 208
 
209
-		foreach($languageCodes as $lang) {
209
+		foreach ($languageCodes as $lang) {
210 210
 			$l = \OC::$server->getL10N('settings', $lang);
211 211
 			// TRANSLATORS this is the language name for the language switcher in the personal settings and should be the localized version
212 212
 			$potentialName = (string) $l->t('__language_name__');
213
-			if($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
213
+			if ($l->getLanguageCode() === $lang && substr($potentialName, 0, 1) !== '_') {//first check if the language name is in the translation file
214 214
 				$ln = array('code' => $lang, 'name' => $potentialName);
215 215
 			} elseif ($lang === 'en') {
216 216
 				$ln = ['code' => $lang, 'name' => 'English (US)'];
217
-			}else{//fallback to language code
218
-				$ln=array('code'=>$lang, 'name'=>$lang);
217
+			} else {//fallback to language code
218
+				$ln = array('code'=>$lang, 'name'=>$lang);
219 219
 			}
220 220
 
221 221
 			// put appropriate languages into appropriate arrays, to print them sorted
@@ -223,9 +223,9 @@  discard block
 block discarded – undo
223 223
 			if ($lang === $userLang) {
224 224
 				$userLang = $ln;
225 225
 			} elseif (in_array($lang, self::COMMON_LANGUAGE_CODES)) {
226
-				$commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)]=$ln;
226
+				$commonLanguages[array_search($lang, self::COMMON_LANGUAGE_CODES)] = $ln;
227 227
 			} else {
228
-				$languages[]=$ln;
228
+				$languages[] = $ln;
229 229
 			}
230 230
 		}
231 231
 
@@ -240,7 +240,7 @@  discard block
 block discarded – undo
240 240
 		ksort($commonLanguages);
241 241
 
242 242
 		// sort now by displayed language not the iso-code
243
-		usort( $languages, function ($a, $b) {
243
+		usort($languages, function($a, $b) {
244 244
 			if ($a['code'] === $a['name'] && $b['code'] !== $b['name']) {
245 245
 				// If a doesn't have a name, but b does, list b before a
246 246
 				return 1;
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 
263 263
 	private function getLocales(IUser $user) {
264 264
 		$forceLanguage = $this->config->getSystemValue('force_locale', false);
265
-		if($forceLanguage !== false) {
265
+		if ($forceLanguage !== false) {
266 266
 			return [];
267 267
 		}
268 268
 
@@ -313,7 +313,7 @@  discard block
 block discarded – undo
313 313
 				default:
314 314
 					$message = $this->l->t('Verify');
315 315
 			}
316
-			$messageParameters[$property . 'Message'] = $message;
316
+			$messageParameters[$property.'Message'] = $message;
317 317
 		}
318 318
 		return $messageParameters;
319 319
 	}
Please login to merge, or discard this patch.
lib/private/legacy/template/functions.php 2 patches
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
  * @param string $string the string which will be escaped and printed
36 36
  */
37 37
 function p($string) {
38
-	print(\OCP\Util::sanitizeHTML($string));
38
+    print(\OCP\Util::sanitizeHTML($string));
39 39
 }
40 40
 
41 41
 
@@ -45,14 +45,14 @@  discard block
 block discarded – undo
45 45
  * @param string $opts, additional optional options
46 46
 */
47 47
 function emit_css_tag($href, $opts = '') {
48
-	$s='<link rel="stylesheet"';
49
-	if (!empty($href)) {
50
-		$s.=' href="' . $href .'"';
51
-	}
52
-	if (!empty($opts)) {
53
-		$s.=' '.$opts;
54
-	}
55
-	print_unescaped($s.">\n");
48
+    $s='<link rel="stylesheet"';
49
+    if (!empty($href)) {
50
+        $s.=' href="' . $href .'"';
51
+    }
52
+    if (!empty($opts)) {
53
+        $s.=' '.$opts;
54
+    }
55
+    print_unescaped($s.">\n");
56 56
 }
57 57
 
58 58
 /**
@@ -60,12 +60,12 @@  discard block
 block discarded – undo
60 60
  * @param hash $obj all the script information from template
61 61
 */
62 62
 function emit_css_loading_tags($obj) {
63
-	foreach($obj['cssfiles'] as $css) {
64
-		emit_css_tag($css);
65
-	}
66
-	foreach($obj['printcssfiles'] as $css) {
67
-		emit_css_tag($css, 'media="print"');
68
-	}
63
+    foreach($obj['cssfiles'] as $css) {
64
+        emit_css_tag($css);
65
+    }
66
+    foreach($obj['printcssfiles'] as $css) {
67
+        emit_css_tag($css, 'media="print"');
68
+    }
69 69
 }
70 70
 
71 71
 /**
@@ -75,20 +75,20 @@  discard block
 block discarded – undo
75 75
  * @param bool $defer_flag deferred loading or not
76 76
 */
77 77
 function emit_script_tag($src, $script_content='') {
78
-	$defer_str=' defer';
79
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
80
-	if (!empty($src)) {
81
-		 // emit script tag for deferred loading from $src
82
-		$s.=$defer_str.' src="' . $src .'">';
83
-	} else if (!empty($script_content)) {
84
-		// emit script tag for inline script from $script_content without defer (see MDN)
85
-		$s.=">\n".$script_content."\n";
86
-	} else {
87
-		// no $src nor $src_content, really useless empty tag
88
-		$s.='>';
89
-	}
90
-	$s.='</script>';
91
-	print_unescaped($s."\n");
78
+    $defer_str=' defer';
79
+    $s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
80
+    if (!empty($src)) {
81
+            // emit script tag for deferred loading from $src
82
+        $s.=$defer_str.' src="' . $src .'">';
83
+    } else if (!empty($script_content)) {
84
+        // emit script tag for inline script from $script_content without defer (see MDN)
85
+        $s.=">\n".$script_content."\n";
86
+    } else {
87
+        // no $src nor $src_content, really useless empty tag
88
+        $s.='>';
89
+    }
90
+    $s.='</script>';
91
+    print_unescaped($s."\n");
92 92
 }
93 93
 
94 94
 /**
@@ -96,12 +96,12 @@  discard block
 block discarded – undo
96 96
  * @param hash $obj all the script information from template
97 97
 */
98 98
 function emit_script_loading_tags($obj) {
99
-	foreach($obj['jsfiles'] as $jsfile) {
100
-		emit_script_tag($jsfile, '');
101
-	}
102
-	if (!empty($obj['inline_ocjs'])) {
103
-		emit_script_tag('', $obj['inline_ocjs']);
104
-	}
99
+    foreach($obj['jsfiles'] as $jsfile) {
100
+        emit_script_tag($jsfile, '');
101
+    }
102
+    if (!empty($obj['inline_ocjs'])) {
103
+        emit_script_tag('', $obj['inline_ocjs']);
104
+    }
105 105
 }
106 106
 
107 107
 /**
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
  * @param string|array $string the string which will be printed as it is
111 111
  */
112 112
 function print_unescaped($string) {
113
-	print($string);
113
+    print($string);
114 114
 }
115 115
 
116 116
 /**
@@ -120,13 +120,13 @@  discard block
 block discarded – undo
120 120
  * if an array is given it will add all scripts
121 121
  */
122 122
 function script($app, $file = null) {
123
-	if(is_array($file)) {
124
-		foreach($file as $f) {
125
-			OC_Util::addScript($app, $f);
126
-		}
127
-	} else {
128
-		OC_Util::addScript($app, $file);
129
-	}
123
+    if(is_array($file)) {
124
+        foreach($file as $f) {
125
+            OC_Util::addScript($app, $f);
126
+        }
127
+    } else {
128
+        OC_Util::addScript($app, $file);
129
+    }
130 130
 }
131 131
 
132 132
 /**
@@ -136,13 +136,13 @@  discard block
 block discarded – undo
136 136
  * if an array is given it will add all scripts
137 137
  */
138 138
 function vendor_script($app, $file = null) {
139
-	if(is_array($file)) {
140
-		foreach($file as $f) {
141
-			OC_Util::addVendorScript($app, $f);
142
-		}
143
-	} else {
144
-		OC_Util::addVendorScript($app, $file);
145
-	}
139
+    if(is_array($file)) {
140
+        foreach($file as $f) {
141
+            OC_Util::addVendorScript($app, $f);
142
+        }
143
+    } else {
144
+        OC_Util::addVendorScript($app, $file);
145
+    }
146 146
 }
147 147
 
148 148
 /**
@@ -152,13 +152,13 @@  discard block
 block discarded – undo
152 152
  * if an array is given it will add all styles
153 153
  */
154 154
 function style($app, $file = null) {
155
-	if(is_array($file)) {
156
-		foreach($file as $f) {
157
-			OC_Util::addStyle($app, $f);
158
-		}
159
-	} else {
160
-		OC_Util::addStyle($app, $file);
161
-	}
155
+    if(is_array($file)) {
156
+        foreach($file as $f) {
157
+            OC_Util::addStyle($app, $f);
158
+        }
159
+    } else {
160
+        OC_Util::addStyle($app, $file);
161
+    }
162 162
 }
163 163
 
164 164
 /**
@@ -168,13 +168,13 @@  discard block
 block discarded – undo
168 168
  * if an array is given it will add all styles
169 169
  */
170 170
 function vendor_style($app, $file = null) {
171
-	if(is_array($file)) {
172
-		foreach($file as $f) {
173
-			OC_Util::addVendorStyle($app, $f);
174
-		}
175
-	} else {
176
-		OC_Util::addVendorStyle($app, $file);
177
-	}
171
+    if(is_array($file)) {
172
+        foreach($file as $f) {
173
+            OC_Util::addVendorStyle($app, $f);
174
+        }
175
+    } else {
176
+        OC_Util::addVendorStyle($app, $file);
177
+    }
178 178
 }
179 179
 
180 180
 /**
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
  * if an array is given it will add all styles
184 184
  */
185 185
 function translation($app) {
186
-	OC_Util::addTranslations($app);
186
+    OC_Util::addTranslations($app);
187 187
 }
188 188
 
189 189
 /**
@@ -193,15 +193,15 @@  discard block
 block discarded – undo
193 193
  * if an array is given it will add all components
194 194
  */
195 195
 function component($app, $file) {
196
-	if(is_array($file)) {
197
-		foreach($file as $f) {
198
-			$url = link_to($app, 'component/' . $f . '.html');
199
-			OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
200
-		}
201
-	} else {
202
-		$url = link_to($app, 'component/' . $file . '.html');
203
-		OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
204
-	}
196
+    if(is_array($file)) {
197
+        foreach($file as $f) {
198
+            $url = link_to($app, 'component/' . $f . '.html');
199
+            OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
200
+        }
201
+    } else {
202
+        $url = link_to($app, 'component/' . $file . '.html');
203
+        OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
204
+    }
205 205
 }
206 206
 
207 207
 /**
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
  * For further information have a look at \OCP\IURLGenerator::linkTo
215 215
  */
216 216
 function link_to( $app, $file, $args = array() ) {
217
-	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
217
+    return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
218 218
 }
219 219
 
220 220
 /**
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
  * @return string url to the online documentation
223 223
  */
224 224
 function link_to_docs($key) {
225
-	return \OC::$server->getURLGenerator()->linkToDocs($key);
225
+    return \OC::$server->getURLGenerator()->linkToDocs($key);
226 226
 }
227 227
 
228 228
 /**
@@ -234,7 +234,7 @@  discard block
 block discarded – undo
234 234
  * For further information have a look at \OCP\IURLGenerator::imagePath
235 235
  */
236 236
 function image_path( $app, $image ) {
237
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
237
+    return \OC::$server->getURLGenerator()->imagePath( $app, $image );
238 238
 }
239 239
 
240 240
 /**
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
  * @return string link to the image
244 244
  */
245 245
 function mimetype_icon( $mimetype ) {
246
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
246
+    return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
247 247
 }
248 248
 
249 249
 /**
@@ -253,14 +253,14 @@  discard block
 block discarded – undo
253 253
  * @return link to the preview
254 254
  */
255 255
 function preview_icon( $path ) {
256
-	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
256
+    return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
257 257
 }
258 258
 
259 259
 /**
260 260
  * @param string $path
261 261
  */
262 262
 function publicPreview_icon ( $path, $token ) {
263
-	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
263
+    return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
264 264
 }
265 265
 
266 266
 /**
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
  * For further information have a look at OC_Helper::humanFileSize
272 272
  */
273 273
 function human_file_size( $bytes ) {
274
-	return OC_Helper::humanFileSize( $bytes );
274
+    return OC_Helper::humanFileSize( $bytes );
275 275
 }
276 276
 
277 277
 /**
@@ -280,9 +280,9 @@  discard block
 block discarded – undo
280 280
  * @return $timestamp without time value
281 281
  */
282 282
 function strip_time($timestamp){
283
-	$date = new \DateTime("@{$timestamp}");
284
-	$date->setTime(0, 0, 0);
285
-	return intval($date->format('U'));
283
+    $date = new \DateTime("@{$timestamp}");
284
+    $date->setTime(0, 0, 0);
285
+    return intval($date->format('U'));
286 286
 }
287 287
 
288 288
 /**
@@ -294,39 +294,39 @@  discard block
 block discarded – undo
294 294
  * @return string timestamp
295 295
  */
296 296
 function relative_modified_date($timestamp, $fromTime = null, $dateOnly = false) {
297
-	/** @var \OC\DateTimeFormatter $formatter */
298
-	$formatter = \OC::$server->query('DateTimeFormatter');
297
+    /** @var \OC\DateTimeFormatter $formatter */
298
+    $formatter = \OC::$server->query('DateTimeFormatter');
299 299
 
300
-	if ($dateOnly){
301
-		return $formatter->formatDateSpan($timestamp, $fromTime);
302
-	}
303
-	return $formatter->formatTimeSpan($timestamp, $fromTime);
300
+    if ($dateOnly){
301
+        return $formatter->formatDateSpan($timestamp, $fromTime);
302
+    }
303
+    return $formatter->formatTimeSpan($timestamp, $fromTime);
304 304
 }
305 305
 
306 306
 function html_select_options($options, $selected, $params=array()) {
307
-	if (!is_array($selected)) {
308
-		$selected=array($selected);
309
-	}
310
-	if (isset($params['combine']) && $params['combine']) {
311
-		$options = array_combine($options, $options);
312
-	}
313
-	$value_name = $label_name = false;
314
-	if (isset($params['value'])) {
315
-		$value_name = $params['value'];
316
-	}
317
-	if (isset($params['label'])) {
318
-		$label_name = $params['label'];
319
-	}
320
-	$html = '';
321
-	foreach($options as $value => $label) {
322
-		if ($value_name && is_array($label)) {
323
-			$value = $label[$value_name];
324
-		}
325
-		if ($label_name && is_array($label)) {
326
-			$label = $label[$label_name];
327
-		}
328
-		$select = in_array($value, $selected) ? ' selected="selected"' : '';
329
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
330
-	}
331
-	return $html;
307
+    if (!is_array($selected)) {
308
+        $selected=array($selected);
309
+    }
310
+    if (isset($params['combine']) && $params['combine']) {
311
+        $options = array_combine($options, $options);
312
+    }
313
+    $value_name = $label_name = false;
314
+    if (isset($params['value'])) {
315
+        $value_name = $params['value'];
316
+    }
317
+    if (isset($params['label'])) {
318
+        $label_name = $params['label'];
319
+    }
320
+    $html = '';
321
+    foreach($options as $value => $label) {
322
+        if ($value_name && is_array($label)) {
323
+            $value = $label[$value_name];
324
+        }
325
+        if ($label_name && is_array($label)) {
326
+            $label = $label[$label_name];
327
+        }
328
+        $select = in_array($value, $selected) ? ' selected="selected"' : '';
329
+        $html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
330
+    }
331
+    return $html;
332 332
 }
Please login to merge, or discard this patch.
Spacing   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -45,12 +45,12 @@  discard block
 block discarded – undo
45 45
  * @param string $opts, additional optional options
46 46
 */
47 47
 function emit_css_tag($href, $opts = '') {
48
-	$s='<link rel="stylesheet"';
48
+	$s = '<link rel="stylesheet"';
49 49
 	if (!empty($href)) {
50
-		$s.=' href="' . $href .'"';
50
+		$s .= ' href="'.$href.'"';
51 51
 	}
52 52
 	if (!empty($opts)) {
53
-		$s.=' '.$opts;
53
+		$s .= ' '.$opts;
54 54
 	}
55 55
 	print_unescaped($s.">\n");
56 56
 }
@@ -60,10 +60,10 @@  discard block
 block discarded – undo
60 60
  * @param hash $obj all the script information from template
61 61
 */
62 62
 function emit_css_loading_tags($obj) {
63
-	foreach($obj['cssfiles'] as $css) {
63
+	foreach ($obj['cssfiles'] as $css) {
64 64
 		emit_css_tag($css);
65 65
 	}
66
-	foreach($obj['printcssfiles'] as $css) {
66
+	foreach ($obj['printcssfiles'] as $css) {
67 67
 		emit_css_tag($css, 'media="print"');
68 68
 	}
69 69
 }
@@ -74,20 +74,20 @@  discard block
 block discarded – undo
74 74
  * @param string $script_content the inline script content, ignored when empty
75 75
  * @param bool $defer_flag deferred loading or not
76 76
 */
77
-function emit_script_tag($src, $script_content='') {
78
-	$defer_str=' defer';
79
-	$s='<script nonce="' . \OC::$server->getContentSecurityPolicyNonceManager()->getNonce() . '"';
77
+function emit_script_tag($src, $script_content = '') {
78
+	$defer_str = ' defer';
79
+	$s = '<script nonce="'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'"';
80 80
 	if (!empty($src)) {
81 81
 		 // emit script tag for deferred loading from $src
82
-		$s.=$defer_str.' src="' . $src .'">';
82
+		$s .= $defer_str.' src="'.$src.'">';
83 83
 	} else if (!empty($script_content)) {
84 84
 		// emit script tag for inline script from $script_content without defer (see MDN)
85
-		$s.=">\n".$script_content."\n";
85
+		$s .= ">\n".$script_content."\n";
86 86
 	} else {
87 87
 		// no $src nor $src_content, really useless empty tag
88
-		$s.='>';
88
+		$s .= '>';
89 89
 	}
90
-	$s.='</script>';
90
+	$s .= '</script>';
91 91
 	print_unescaped($s."\n");
92 92
 }
93 93
 
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
  * @param hash $obj all the script information from template
97 97
 */
98 98
 function emit_script_loading_tags($obj) {
99
-	foreach($obj['jsfiles'] as $jsfile) {
99
+	foreach ($obj['jsfiles'] as $jsfile) {
100 100
 		emit_script_tag($jsfile, '');
101 101
 	}
102 102
 	if (!empty($obj['inline_ocjs'])) {
@@ -120,8 +120,8 @@  discard block
 block discarded – undo
120 120
  * if an array is given it will add all scripts
121 121
  */
122 122
 function script($app, $file = null) {
123
-	if(is_array($file)) {
124
-		foreach($file as $f) {
123
+	if (is_array($file)) {
124
+		foreach ($file as $f) {
125 125
 			OC_Util::addScript($app, $f);
126 126
 		}
127 127
 	} else {
@@ -136,8 +136,8 @@  discard block
 block discarded – undo
136 136
  * if an array is given it will add all scripts
137 137
  */
138 138
 function vendor_script($app, $file = null) {
139
-	if(is_array($file)) {
140
-		foreach($file as $f) {
139
+	if (is_array($file)) {
140
+		foreach ($file as $f) {
141 141
 			OC_Util::addVendorScript($app, $f);
142 142
 		}
143 143
 	} else {
@@ -152,8 +152,8 @@  discard block
 block discarded – undo
152 152
  * if an array is given it will add all styles
153 153
  */
154 154
 function style($app, $file = null) {
155
-	if(is_array($file)) {
156
-		foreach($file as $f) {
155
+	if (is_array($file)) {
156
+		foreach ($file as $f) {
157 157
 			OC_Util::addStyle($app, $f);
158 158
 		}
159 159
 	} else {
@@ -168,8 +168,8 @@  discard block
 block discarded – undo
168 168
  * if an array is given it will add all styles
169 169
  */
170 170
 function vendor_style($app, $file = null) {
171
-	if(is_array($file)) {
172
-		foreach($file as $f) {
171
+	if (is_array($file)) {
172
+		foreach ($file as $f) {
173 173
 			OC_Util::addVendorStyle($app, $f);
174 174
 		}
175 175
 	} else {
@@ -193,13 +193,13 @@  discard block
 block discarded – undo
193 193
  * if an array is given it will add all components
194 194
  */
195 195
 function component($app, $file) {
196
-	if(is_array($file)) {
197
-		foreach($file as $f) {
198
-			$url = link_to($app, 'component/' . $f . '.html');
196
+	if (is_array($file)) {
197
+		foreach ($file as $f) {
198
+			$url = link_to($app, 'component/'.$f.'.html');
199 199
 			OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
200 200
 		}
201 201
 	} else {
202
-		$url = link_to($app, 'component/' . $file . '.html');
202
+		$url = link_to($app, 'component/'.$file.'.html');
203 203
 		OC_Util::addHeader('link', array('rel' => 'import', 'href' => $url));
204 204
 	}
205 205
 }
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
  *
214 214
  * For further information have a look at \OCP\IURLGenerator::linkTo
215 215
  */
216
-function link_to( $app, $file, $args = array() ) {
216
+function link_to($app, $file, $args = array()) {
217 217
 	return \OC::$server->getURLGenerator()->linkTo($app, $file, $args);
218 218
 }
219 219
 
@@ -233,8 +233,8 @@  discard block
 block discarded – undo
233 233
  *
234 234
  * For further information have a look at \OCP\IURLGenerator::imagePath
235 235
  */
236
-function image_path( $app, $image ) {
237
-	return \OC::$server->getURLGenerator()->imagePath( $app, $image );
236
+function image_path($app, $image) {
237
+	return \OC::$server->getURLGenerator()->imagePath($app, $image);
238 238
 }
239 239
 
240 240
 /**
@@ -242,8 +242,8 @@  discard block
 block discarded – undo
242 242
  * @param string $mimetype mimetype
243 243
  * @return string link to the image
244 244
  */
245
-function mimetype_icon( $mimetype ) {
246
-	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon( $mimetype );
245
+function mimetype_icon($mimetype) {
246
+	return \OC::$server->getMimeTypeDetector()->mimeTypeIcon($mimetype);
247 247
 }
248 248
 
249 249
 /**
@@ -252,14 +252,14 @@  discard block
 block discarded – undo
252 252
  * @param string $path path of file
253 253
  * @return link to the preview
254 254
  */
255
-function preview_icon( $path ) {
255
+function preview_icon($path) {
256 256
 	return \OC::$server->getURLGenerator()->linkToRoute('core.Preview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path]);
257 257
 }
258 258
 
259 259
 /**
260 260
  * @param string $path
261 261
  */
262
-function publicPreview_icon ( $path, $token ) {
262
+function publicPreview_icon($path, $token) {
263 263
 	return \OC::$server->getURLGenerator()->linkToRoute('files_sharing.PublicPreview.getPreview', ['x' => 32, 'y' => 32, 'file' => $path, 't' => $token]);
264 264
 }
265 265
 
@@ -270,8 +270,8 @@  discard block
 block discarded – undo
270 270
  *
271 271
  * For further information have a look at OC_Helper::humanFileSize
272 272
  */
273
-function human_file_size( $bytes ) {
274
-	return OC_Helper::humanFileSize( $bytes );
273
+function human_file_size($bytes) {
274
+	return OC_Helper::humanFileSize($bytes);
275 275
 }
276 276
 
277 277
 /**
@@ -279,7 +279,7 @@  discard block
 block discarded – undo
279 279
  * @param int $timestamp UNIX timestamp to strip
280 280
  * @return $timestamp without time value
281 281
  */
282
-function strip_time($timestamp){
282
+function strip_time($timestamp) {
283 283
 	$date = new \DateTime("@{$timestamp}");
284 284
 	$date->setTime(0, 0, 0);
285 285
 	return intval($date->format('U'));
@@ -297,15 +297,15 @@  discard block
 block discarded – undo
297 297
 	/** @var \OC\DateTimeFormatter $formatter */
298 298
 	$formatter = \OC::$server->query('DateTimeFormatter');
299 299
 
300
-	if ($dateOnly){
300
+	if ($dateOnly) {
301 301
 		return $formatter->formatDateSpan($timestamp, $fromTime);
302 302
 	}
303 303
 	return $formatter->formatTimeSpan($timestamp, $fromTime);
304 304
 }
305 305
 
306
-function html_select_options($options, $selected, $params=array()) {
306
+function html_select_options($options, $selected, $params = array()) {
307 307
 	if (!is_array($selected)) {
308
-		$selected=array($selected);
308
+		$selected = array($selected);
309 309
 	}
310 310
 	if (isset($params['combine']) && $params['combine']) {
311 311
 		$options = array_combine($options, $options);
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 		$label_name = $params['label'];
319 319
 	}
320 320
 	$html = '';
321
-	foreach($options as $value => $label) {
321
+	foreach ($options as $value => $label) {
322 322
 		if ($value_name && is_array($label)) {
323 323
 			$value = $label[$value_name];
324 324
 		}
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 			$label = $label[$label_name];
327 327
 		}
328 328
 		$select = in_array($value, $selected) ? ' selected="selected"' : '';
329
-		$html .= '<option value="' . \OCP\Util::sanitizeHTML($value) . '"' . $select . '>' . \OCP\Util::sanitizeHTML($label) . '</option>'."\n";
329
+		$html .= '<option value="'.\OCP\Util::sanitizeHTML($value).'"'.$select.'>'.\OCP\Util::sanitizeHTML($label).'</option>'."\n";
330 330
 	}
331 331
 	return $html;
332 332
 }
Please login to merge, or discard this patch.