Completed
Pull Request — master (#8096)
by Morris
63:13 queued 41:38
created
core/Migrations/Version14000Date20180129121024.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -31,22 +31,22 @@
 block discarded – undo
31 31
  */
32 32
 class Version14000Date20180129121024 extends SimpleMigrationStep {
33 33
 
34
-	/**
35
-	 * @param IOutput $output
36
-	 * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
37
-	 * @param array $options
38
-	 * @return null|ISchemaWrapper
39
-	 * @since 13.0.0
40
-	 */
41
-	public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
42
-		/** @var ISchemaWrapper $schema */
43
-		$schema = $schemaClosure();
34
+    /**
35
+     * @param IOutput $output
36
+     * @param \Closure $schemaClosure The `\Closure` returns a `ISchemaWrapper`
37
+     * @param array $options
38
+     * @return null|ISchemaWrapper
39
+     * @since 13.0.0
40
+     */
41
+    public function changeSchema(IOutput $output, \Closure $schemaClosure, array $options) {
42
+        /** @var ISchemaWrapper $schema */
43
+        $schema = $schemaClosure();
44 44
 
45
-		$schema->dropTable('admin_sections');
46
-		$schema->dropTable('admin_settings');
47
-		$schema->dropTable('personal_sections');
48
-		$schema->dropTable('personal_settings');
45
+        $schema->dropTable('admin_sections');
46
+        $schema->dropTable('admin_settings');
47
+        $schema->dropTable('personal_sections');
48
+        $schema->dropTable('personal_settings');
49 49
 
50
-		return $schema;
51
-	}
50
+        return $schema;
51
+    }
52 52
 }
Please login to merge, or discard this patch.
lib/private/Settings/Manager.php 2 patches
Indentation   +352 added lines, -352 removed lines patch added patch discarded remove patch
@@ -49,356 +49,356 @@
 block discarded – undo
49 49
 use OCP\Util;
50 50
 
51 51
 class Manager implements IManager {
52
-	/** @var ILogger */
53
-	private $log;
54
-	/** @var IDBConnection */
55
-	private $dbc;
56
-	/** @var IL10N */
57
-	private $l;
58
-	/** @var IConfig */
59
-	private $config;
60
-	/** @var EncryptionManager */
61
-	private $encryptionManager;
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-	/** @var ILockingProvider */
65
-	private $lockingProvider;
66
-	/** @var IRequest */
67
-	private $request;
68
-	/** @var IURLGenerator */
69
-	private $url;
70
-	/** @var AccountManager */
71
-	private $accountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IFactory */
75
-	private $l10nFactory;
76
-	/** @var IAppManager */
77
-	private $appManager;
78
-
79
-	/**
80
-	 * @param ILogger $log
81
-	 * @param IDBConnection $dbc
82
-	 * @param IL10N $l
83
-	 * @param IConfig $config
84
-	 * @param EncryptionManager $encryptionManager
85
-	 * @param IUserManager $userManager
86
-	 * @param ILockingProvider $lockingProvider
87
-	 * @param IRequest $request
88
-	 * @param IURLGenerator $url
89
-	 * @param AccountManager $accountManager
90
-	 * @param IGroupManager $groupManager
91
-	 * @param IFactory $l10nFactory
92
-	 * @param IAppManager $appManager
93
-	 */
94
-	public function __construct(
95
-		ILogger $log,
96
-		IDBConnection $dbc,
97
-		IL10N $l,
98
-		IConfig $config,
99
-		EncryptionManager $encryptionManager,
100
-		IUserManager $userManager,
101
-		ILockingProvider $lockingProvider,
102
-		IRequest $request,
103
-		IURLGenerator $url,
104
-		AccountManager $accountManager,
105
-		IGroupManager $groupManager,
106
-		IFactory $l10nFactory,
107
-		IAppManager $appManager
108
-	) {
109
-		$this->log = $log;
110
-		$this->dbc = $dbc;
111
-		$this->l = $l;
112
-		$this->config = $config;
113
-		$this->encryptionManager = $encryptionManager;
114
-		$this->userManager = $userManager;
115
-		$this->lockingProvider = $lockingProvider;
116
-		$this->request = $request;
117
-		$this->url = $url;
118
-		$this->accountManager = $accountManager;
119
-		$this->groupManager = $groupManager;
120
-		$this->l10nFactory = $l10nFactory;
121
-		$this->appManager = $appManager;
122
-	}
123
-
124
-	/** @var array */
125
-	protected $sectionClasses = [];
126
-
127
-	/** @var array */
128
-	protected $sections = [];
129
-
130
-	/**
131
-	 * @param string $type 'admin' or 'personal'
132
-	 * @param string $section Class must implement OCP\Settings\ISection
133
-	 * @return void
134
-	 */
135
-	public function registerSection(string $type, string $section) {
136
-		$this->sectionClasses[$section] = $type;
137
-	}
138
-
139
-	/**
140
-	 * @param string $type 'admin' or 'personal'
141
-	 * @return ISection[]
142
-	 */
143
-	protected function getSections(string $type): array {
144
-		if (!isset($this->sections[$type])) {
145
-			$this->sections[$type] = [];
146
-		}
147
-
148
-		foreach ($this->sectionClasses as $class => $sectionType) {
149
-			try {
150
-				/** @var ISection $section */
151
-				$section = \OC::$server->query($class);
152
-			} catch (QueryException $e) {
153
-				$this->log->logException($e, ['level' => Util::INFO]);
154
-				continue;
155
-			}
156
-
157
-			if (!$section instanceof ISection) {
158
-				$this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => Util::INFO]);
159
-				continue;
160
-			}
161
-
162
-			$this->sections[$sectionType][$section->getID()] = $section;
163
-
164
-			unset($this->sectionClasses[$class]);
165
-		}
166
-
167
-		return $this->sections[$type];
168
-	}
169
-
170
-	/** @var array */
171
-	protected $settingClasses = [];
172
-
173
-	/** @var array */
174
-	protected $settings = [];
175
-
176
-	/**
177
-	 * @param string $type 'admin' or 'personal'
178
-	 * @param string $setting Class must implement OCP\Settings\ISetting
179
-	 * @return void
180
-	 */
181
-	public function registerSetting(string $type, string $setting) {
182
-		$this->settingClasses[$setting] = $type;
183
-	}
184
-
185
-	/**
186
-	 * @param string $type 'admin' or 'personal'
187
-	 * @param string $section
188
-	 * @return ISettings[]
189
-	 */
190
-	protected function getSettings(string $type, string $section): array {
191
-		if (!isset($this->settings[$type])) {
192
-			$this->settings[$type] = [];
193
-		}
194
-		if (!isset($this->settings[$type][$section])) {
195
-			$this->settings[$type][$section] = [];
196
-		}
197
-
198
-		foreach ($this->settingClasses as $class => $settingsType) {
199
-			try {
200
-				/** @var ISettings $setting */
201
-				$setting = \OC::$server->query($class);
202
-			} catch (QueryException $e) {
203
-				$this->log->logException($e, ['level' => Util::INFO]);
204
-				continue;
205
-			}
206
-
207
-			if (!$setting instanceof ISettings) {
208
-				$this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => Util::INFO]);
209
-				continue;
210
-			}
211
-
212
-			if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
-				$this->settings[$settingsType][$setting->getSection()] = [];
214
-			}
215
-			$this->settings[$settingsType][$setting->getSection()][] = $setting;
216
-
217
-			unset($this->settingClasses[$class]);
218
-		}
219
-
220
-		return $this->settings[$type][$section];
221
-	}
222
-
223
-	/**
224
-	 * @inheritdoc
225
-	 */
226
-	public function getAdminSections(): array {
227
-		// built-in sections
228
-		$sections = [
229
-			0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
-			5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
-			10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
-			45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
-			98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
-			99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
-		];
236
-
237
-		$appSections = $this->getSections('admin');
238
-
239
-		foreach ($appSections as $section) {
240
-			/** @var ISection $section */
241
-			if (!isset($sections[$section->getPriority()])) {
242
-				$sections[$section->getPriority()] = [];
243
-			}
244
-
245
-			$sections[$section->getPriority()][] = $section;
246
-		}
247
-
248
-		ksort($sections);
249
-
250
-		return $sections;
251
-	}
252
-
253
-	/**
254
-	 * @param string $section
255
-	 * @return ISection[]
256
-	 */
257
-	private function getBuiltInAdminSettings($section): array {
258
-		$forms = [];
259
-
260
-		if ($section === 'server') {
261
-			/** @var ISettings $form */
262
-			$form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
-			$forms[$form->getPriority()] = [$form];
264
-			$form = new Admin\ServerDevNotice();
265
-			$forms[$form->getPriority()] = [$form];
266
-		}
267
-		if ($section === 'encryption') {
268
-			/** @var ISettings $form */
269
-			$form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
-			$forms[$form->getPriority()] = [$form];
271
-		}
272
-		if ($section === 'sharing') {
273
-			/** @var ISettings $form */
274
-			$form = new Admin\Sharing($this->config);
275
-			$forms[$form->getPriority()] = [$form];
276
-		}
277
-		if ($section === 'additional') {
278
-			/** @var ISettings $form */
279
-			$form = new Admin\Additional($this->config);
280
-			$forms[$form->getPriority()] = [$form];
281
-		}
282
-		if ($section === 'tips-tricks') {
283
-			/** @var ISettings $form */
284
-			$form = new Admin\TipsTricks($this->config);
285
-			$forms[$form->getPriority()] = [$form];
286
-		}
287
-
288
-		return $forms;
289
-	}
290
-
291
-	/**
292
-	 * @param string $section
293
-	 * @return ISection[]
294
-	 */
295
-	private function getBuiltInPersonalSettings($section): array {
296
-		$forms = [];
297
-
298
-		if ($section === 'personal-info') {
299
-			/** @var ISettings $form */
300
-			$form = new Personal\PersonalInfo(
301
-				$this->config,
302
-				$this->userManager,
303
-				$this->groupManager,
304
-				$this->accountManager,
305
-				$this->appManager,
306
-				$this->l10nFactory,
307
-				$this->l
308
-			);
309
-			$forms[$form->getPriority()] = [$form];
310
-		}
311
-		if($section === 'security') {
312
-			/** @var ISettings $form */
313
-			$form = new Personal\Security();
314
-			$forms[$form->getPriority()] = [$form];
315
-		}
316
-		if ($section === 'additional') {
317
-			/** @var ISettings $form */
318
-			$form = new Personal\Additional();
319
-			$forms[$form->getPriority()] = [$form];
320
-		}
321
-
322
-		return $forms;
323
-	}
324
-
325
-	/**
326
-	 * @inheritdoc
327
-	 */
328
-	public function getAdminSettings($section): array {
329
-		$settings = $this->getBuiltInAdminSettings($section);
330
-		$appSettings = $this->getSettings('admin', $section);
331
-
332
-		foreach ($appSettings as $setting) {
333
-			if (!isset($settings[$setting->getPriority()])) {
334
-				$settings[$setting->getPriority()] = [];
335
-			}
336
-			$settings[$setting->getPriority()][] = $setting;
337
-		}
338
-
339
-		ksort($settings);
340
-		return $settings;
341
-	}
342
-
343
-	/**
344
-	 * @inheritdoc
345
-	 */
346
-	public function getPersonalSections(): array {
347
-		$sections = [
348
-			0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
-			5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
-			15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
-		];
352
-
353
-		$legacyForms = \OC_App::getForms('personal');
354
-		if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
-			$sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
-		}
357
-
358
-		$appSections = $this->getSections('personal');
359
-
360
-		foreach ($appSections as $section) {
361
-			/** @var ISection $section */
362
-			if (!isset($sections[$section->getPriority()])) {
363
-				$sections[$section->getPriority()] = [];
364
-			}
365
-
366
-			$sections[$section->getPriority()][] = $section;
367
-		}
368
-
369
-		ksort($sections);
370
-
371
-		return $sections;
372
-	}
373
-
374
-	/**
375
-	 * @param string[] $forms
376
-	 * @return bool
377
-	 */
378
-	private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
-		foreach ($forms as $form) {
380
-			if(trim($form) !== '') {
381
-				return true;
382
-			}
383
-		}
384
-		return false;
385
-	}
386
-
387
-	/**
388
-	 * @inheritdoc
389
-	 */
390
-	public function getPersonalSettings($section): array {
391
-		$settings = $this->getBuiltInPersonalSettings($section);
392
-		$appSettings = $this->getSettings('personal', $section);
393
-
394
-		foreach ($appSettings as $setting) {
395
-			if (!isset($settings[$setting->getPriority()])) {
396
-				$settings[$setting->getPriority()] = [];
397
-			}
398
-			$settings[$setting->getPriority()][] = $setting;
399
-		}
400
-
401
-		ksort($settings);
402
-		return $settings;
403
-	}
52
+    /** @var ILogger */
53
+    private $log;
54
+    /** @var IDBConnection */
55
+    private $dbc;
56
+    /** @var IL10N */
57
+    private $l;
58
+    /** @var IConfig */
59
+    private $config;
60
+    /** @var EncryptionManager */
61
+    private $encryptionManager;
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+    /** @var ILockingProvider */
65
+    private $lockingProvider;
66
+    /** @var IRequest */
67
+    private $request;
68
+    /** @var IURLGenerator */
69
+    private $url;
70
+    /** @var AccountManager */
71
+    private $accountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IFactory */
75
+    private $l10nFactory;
76
+    /** @var IAppManager */
77
+    private $appManager;
78
+
79
+    /**
80
+     * @param ILogger $log
81
+     * @param IDBConnection $dbc
82
+     * @param IL10N $l
83
+     * @param IConfig $config
84
+     * @param EncryptionManager $encryptionManager
85
+     * @param IUserManager $userManager
86
+     * @param ILockingProvider $lockingProvider
87
+     * @param IRequest $request
88
+     * @param IURLGenerator $url
89
+     * @param AccountManager $accountManager
90
+     * @param IGroupManager $groupManager
91
+     * @param IFactory $l10nFactory
92
+     * @param IAppManager $appManager
93
+     */
94
+    public function __construct(
95
+        ILogger $log,
96
+        IDBConnection $dbc,
97
+        IL10N $l,
98
+        IConfig $config,
99
+        EncryptionManager $encryptionManager,
100
+        IUserManager $userManager,
101
+        ILockingProvider $lockingProvider,
102
+        IRequest $request,
103
+        IURLGenerator $url,
104
+        AccountManager $accountManager,
105
+        IGroupManager $groupManager,
106
+        IFactory $l10nFactory,
107
+        IAppManager $appManager
108
+    ) {
109
+        $this->log = $log;
110
+        $this->dbc = $dbc;
111
+        $this->l = $l;
112
+        $this->config = $config;
113
+        $this->encryptionManager = $encryptionManager;
114
+        $this->userManager = $userManager;
115
+        $this->lockingProvider = $lockingProvider;
116
+        $this->request = $request;
117
+        $this->url = $url;
118
+        $this->accountManager = $accountManager;
119
+        $this->groupManager = $groupManager;
120
+        $this->l10nFactory = $l10nFactory;
121
+        $this->appManager = $appManager;
122
+    }
123
+
124
+    /** @var array */
125
+    protected $sectionClasses = [];
126
+
127
+    /** @var array */
128
+    protected $sections = [];
129
+
130
+    /**
131
+     * @param string $type 'admin' or 'personal'
132
+     * @param string $section Class must implement OCP\Settings\ISection
133
+     * @return void
134
+     */
135
+    public function registerSection(string $type, string $section) {
136
+        $this->sectionClasses[$section] = $type;
137
+    }
138
+
139
+    /**
140
+     * @param string $type 'admin' or 'personal'
141
+     * @return ISection[]
142
+     */
143
+    protected function getSections(string $type): array {
144
+        if (!isset($this->sections[$type])) {
145
+            $this->sections[$type] = [];
146
+        }
147
+
148
+        foreach ($this->sectionClasses as $class => $sectionType) {
149
+            try {
150
+                /** @var ISection $section */
151
+                $section = \OC::$server->query($class);
152
+            } catch (QueryException $e) {
153
+                $this->log->logException($e, ['level' => Util::INFO]);
154
+                continue;
155
+            }
156
+
157
+            if (!$section instanceof ISection) {
158
+                $this->log->logException(new \InvalidArgumentException('Invalid settings section registered'), ['level' => Util::INFO]);
159
+                continue;
160
+            }
161
+
162
+            $this->sections[$sectionType][$section->getID()] = $section;
163
+
164
+            unset($this->sectionClasses[$class]);
165
+        }
166
+
167
+        return $this->sections[$type];
168
+    }
169
+
170
+    /** @var array */
171
+    protected $settingClasses = [];
172
+
173
+    /** @var array */
174
+    protected $settings = [];
175
+
176
+    /**
177
+     * @param string $type 'admin' or 'personal'
178
+     * @param string $setting Class must implement OCP\Settings\ISetting
179
+     * @return void
180
+     */
181
+    public function registerSetting(string $type, string $setting) {
182
+        $this->settingClasses[$setting] = $type;
183
+    }
184
+
185
+    /**
186
+     * @param string $type 'admin' or 'personal'
187
+     * @param string $section
188
+     * @return ISettings[]
189
+     */
190
+    protected function getSettings(string $type, string $section): array {
191
+        if (!isset($this->settings[$type])) {
192
+            $this->settings[$type] = [];
193
+        }
194
+        if (!isset($this->settings[$type][$section])) {
195
+            $this->settings[$type][$section] = [];
196
+        }
197
+
198
+        foreach ($this->settingClasses as $class => $settingsType) {
199
+            try {
200
+                /** @var ISettings $setting */
201
+                $setting = \OC::$server->query($class);
202
+            } catch (QueryException $e) {
203
+                $this->log->logException($e, ['level' => Util::INFO]);
204
+                continue;
205
+            }
206
+
207
+            if (!$setting instanceof ISettings) {
208
+                $this->log->logException(new \InvalidArgumentException('Invalid settings setting registered'), ['level' => Util::INFO]);
209
+                continue;
210
+            }
211
+
212
+            if (!isset($this->settings[$settingsType][$setting->getSection()])) {
213
+                $this->settings[$settingsType][$setting->getSection()] = [];
214
+            }
215
+            $this->settings[$settingsType][$setting->getSection()][] = $setting;
216
+
217
+            unset($this->settingClasses[$class]);
218
+        }
219
+
220
+        return $this->settings[$type][$section];
221
+    }
222
+
223
+    /**
224
+     * @inheritdoc
225
+     */
226
+    public function getAdminSections(): array {
227
+        // built-in sections
228
+        $sections = [
229
+            0 => [new Section('server', $this->l->t('Basic settings'), 0, $this->url->imagePath('settings', 'admin.svg'))],
230
+            5 => [new Section('sharing', $this->l->t('Sharing'), 0, $this->url->imagePath('core', 'actions/share.svg'))],
231
+            10 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
232
+            45 => [new Section('encryption', $this->l->t('Encryption'), 0, $this->url->imagePath('core', 'actions/password.svg'))],
233
+            98 => [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))],
234
+            99 => [new Section('tips-tricks', $this->l->t('Tips & tricks'), 0, $this->url->imagePath('settings', 'help.svg'))],
235
+        ];
236
+
237
+        $appSections = $this->getSections('admin');
238
+
239
+        foreach ($appSections as $section) {
240
+            /** @var ISection $section */
241
+            if (!isset($sections[$section->getPriority()])) {
242
+                $sections[$section->getPriority()] = [];
243
+            }
244
+
245
+            $sections[$section->getPriority()][] = $section;
246
+        }
247
+
248
+        ksort($sections);
249
+
250
+        return $sections;
251
+    }
252
+
253
+    /**
254
+     * @param string $section
255
+     * @return ISection[]
256
+     */
257
+    private function getBuiltInAdminSettings($section): array {
258
+        $forms = [];
259
+
260
+        if ($section === 'server') {
261
+            /** @var ISettings $form */
262
+            $form = new Admin\Server($this->dbc, $this->request, $this->config, $this->lockingProvider, $this->l);
263
+            $forms[$form->getPriority()] = [$form];
264
+            $form = new Admin\ServerDevNotice();
265
+            $forms[$form->getPriority()] = [$form];
266
+        }
267
+        if ($section === 'encryption') {
268
+            /** @var ISettings $form */
269
+            $form = new Admin\Encryption($this->encryptionManager, $this->userManager);
270
+            $forms[$form->getPriority()] = [$form];
271
+        }
272
+        if ($section === 'sharing') {
273
+            /** @var ISettings $form */
274
+            $form = new Admin\Sharing($this->config);
275
+            $forms[$form->getPriority()] = [$form];
276
+        }
277
+        if ($section === 'additional') {
278
+            /** @var ISettings $form */
279
+            $form = new Admin\Additional($this->config);
280
+            $forms[$form->getPriority()] = [$form];
281
+        }
282
+        if ($section === 'tips-tricks') {
283
+            /** @var ISettings $form */
284
+            $form = new Admin\TipsTricks($this->config);
285
+            $forms[$form->getPriority()] = [$form];
286
+        }
287
+
288
+        return $forms;
289
+    }
290
+
291
+    /**
292
+     * @param string $section
293
+     * @return ISection[]
294
+     */
295
+    private function getBuiltInPersonalSettings($section): array {
296
+        $forms = [];
297
+
298
+        if ($section === 'personal-info') {
299
+            /** @var ISettings $form */
300
+            $form = new Personal\PersonalInfo(
301
+                $this->config,
302
+                $this->userManager,
303
+                $this->groupManager,
304
+                $this->accountManager,
305
+                $this->appManager,
306
+                $this->l10nFactory,
307
+                $this->l
308
+            );
309
+            $forms[$form->getPriority()] = [$form];
310
+        }
311
+        if($section === 'security') {
312
+            /** @var ISettings $form */
313
+            $form = new Personal\Security();
314
+            $forms[$form->getPriority()] = [$form];
315
+        }
316
+        if ($section === 'additional') {
317
+            /** @var ISettings $form */
318
+            $form = new Personal\Additional();
319
+            $forms[$form->getPriority()] = [$form];
320
+        }
321
+
322
+        return $forms;
323
+    }
324
+
325
+    /**
326
+     * @inheritdoc
327
+     */
328
+    public function getAdminSettings($section): array {
329
+        $settings = $this->getBuiltInAdminSettings($section);
330
+        $appSettings = $this->getSettings('admin', $section);
331
+
332
+        foreach ($appSettings as $setting) {
333
+            if (!isset($settings[$setting->getPriority()])) {
334
+                $settings[$setting->getPriority()] = [];
335
+            }
336
+            $settings[$setting->getPriority()][] = $setting;
337
+        }
338
+
339
+        ksort($settings);
340
+        return $settings;
341
+    }
342
+
343
+    /**
344
+     * @inheritdoc
345
+     */
346
+    public function getPersonalSections(): array {
347
+        $sections = [
348
+            0 => [new Section('personal-info', $this->l->t('Personal info'), 0, $this->url->imagePath('core', 'actions/info.svg'))],
349
+            5 => [new Section('security', $this->l->t('Security'), 0, $this->url->imagePath('settings', 'password.svg'))],
350
+            15 => [new Section('sync-clients', $this->l->t('Sync clients'), 0, $this->url->imagePath('settings', 'change.svg'))],
351
+        ];
352
+
353
+        $legacyForms = \OC_App::getForms('personal');
354
+        if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355
+            $sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356
+        }
357
+
358
+        $appSections = $this->getSections('personal');
359
+
360
+        foreach ($appSections as $section) {
361
+            /** @var ISection $section */
362
+            if (!isset($sections[$section->getPriority()])) {
363
+                $sections[$section->getPriority()] = [];
364
+            }
365
+
366
+            $sections[$section->getPriority()][] = $section;
367
+        }
368
+
369
+        ksort($sections);
370
+
371
+        return $sections;
372
+    }
373
+
374
+    /**
375
+     * @param string[] $forms
376
+     * @return bool
377
+     */
378
+    private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379
+        foreach ($forms as $form) {
380
+            if(trim($form) !== '') {
381
+                return true;
382
+            }
383
+        }
384
+        return false;
385
+    }
386
+
387
+    /**
388
+     * @inheritdoc
389
+     */
390
+    public function getPersonalSettings($section): array {
391
+        $settings = $this->getBuiltInPersonalSettings($section);
392
+        $appSettings = $this->getSettings('personal', $section);
393
+
394
+        foreach ($appSettings as $setting) {
395
+            if (!isset($settings[$setting->getPriority()])) {
396
+                $settings[$setting->getPriority()] = [];
397
+            }
398
+            $settings[$setting->getPriority()][] = $setting;
399
+        }
400
+
401
+        ksort($settings);
402
+        return $settings;
403
+    }
404 404
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -308,7 +308,7 @@  discard block
 block discarded – undo
308 308
 			);
309 309
 			$forms[$form->getPriority()] = [$form];
310 310
 		}
311
-		if($section === 'security') {
311
+		if ($section === 'security') {
312 312
 			/** @var ISettings $form */
313 313
 			$form = new Personal\Security();
314 314
 			$forms[$form->getPriority()] = [$form];
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
 		];
352 352
 
353 353
 		$legacyForms = \OC_App::getForms('personal');
354
-		if(!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
354
+		if (!empty($legacyForms) && $this->hasLegacyPersonalSettingsToRender($legacyForms)) {
355 355
 			$sections[98] = [new Section('additional', $this->l->t('Additional settings'), 0, $this->url->imagePath('core', 'actions/settings-dark.svg'))];
356 356
 		}
357 357
 
@@ -377,7 +377,7 @@  discard block
 block discarded – undo
377 377
 	 */
378 378
 	private function hasLegacyPersonalSettingsToRender(array $forms): bool {
379 379
 		foreach ($forms as $form) {
380
-			if(trim($form) !== '') {
380
+			if (trim($form) !== '') {
381 381
 				return true;
382 382
 			}
383 383
 		}
Please login to merge, or discard this patch.
lib/public/Settings/IManager.php 2 patches
Indentation   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -28,71 +28,71 @@
 block discarded – undo
28 28
  * @since 9.1
29 29
  */
30 30
 interface IManager {
31
-	/**
32
-	 * @since 9.1.0
33
-	 */
34
-	const KEY_ADMIN_SETTINGS = 'admin';
31
+    /**
32
+     * @since 9.1.0
33
+     */
34
+    const KEY_ADMIN_SETTINGS = 'admin';
35 35
 
36
-	/**
37
-	 * @since 9.1.0
38
-	 */
39
-	const KEY_ADMIN_SECTION  = 'admin-section';
36
+    /**
37
+     * @since 9.1.0
38
+     */
39
+    const KEY_ADMIN_SECTION  = 'admin-section';
40 40
 
41
-	/**
42
-	 * @since 13.0.0
43
-	 */
44
-	const KEY_PERSONAL_SETTINGS = 'personal';
41
+    /**
42
+     * @since 13.0.0
43
+     */
44
+    const KEY_PERSONAL_SETTINGS = 'personal';
45 45
 
46
-	/**
47
-	 * @since 13.0.0
48
-	 */
49
-	const KEY_PERSONAL_SECTION  = 'personal-section';
46
+    /**
47
+     * @since 13.0.0
48
+     */
49
+    const KEY_PERSONAL_SECTION  = 'personal-section';
50 50
 
51
-	/**
52
-	 * @param string $type 'admin' or 'personal'
53
-	 * @param string $section Class must implement OCP\Settings\ISection
54
-	 * @since 14.0.0
55
-	 */
56
-	public function registerSection(string $type, string $section);
51
+    /**
52
+     * @param string $type 'admin' or 'personal'
53
+     * @param string $section Class must implement OCP\Settings\ISection
54
+     * @since 14.0.0
55
+     */
56
+    public function registerSection(string $type, string $section);
57 57
 
58
-	/**
59
-	 * @param string $type 'admin' or 'personal'
60
-	 * @param string $setting Class must implement OCP\Settings\ISetting
61
-	 * @since 14.0.0
62
-	 */
63
-	public function registerSetting(string $type, string $setting);
58
+    /**
59
+     * @param string $type 'admin' or 'personal'
60
+     * @param string $setting Class must implement OCP\Settings\ISetting
61
+     * @since 14.0.0
62
+     */
63
+    public function registerSetting(string $type, string $setting);
64 64
 
65
-	/**
66
-	 * returns a list of the admin sections
67
-	 *
68
-	 * @return array array of ISection[] where key is the priority
69
-	 * @since 9.1.0
70
-	 */
71
-	public function getAdminSections(): array;
65
+    /**
66
+     * returns a list of the admin sections
67
+     *
68
+     * @return array array of ISection[] where key is the priority
69
+     * @since 9.1.0
70
+     */
71
+    public function getAdminSections(): array;
72 72
 
73
-	/**
74
-	 * returns a list of the personal sections
75
-	 *
76
-	 * @return array array of ISection[] where key is the priority
77
-	 * @since 13.0.0
78
-	 */
79
-	public function getPersonalSections(): array;
73
+    /**
74
+     * returns a list of the personal sections
75
+     *
76
+     * @return array array of ISection[] where key is the priority
77
+     * @since 13.0.0
78
+     */
79
+    public function getPersonalSections(): array;
80 80
 
81
-	/**
82
-	 * returns a list of the admin settings
83
-	 *
84
-	 * @param string $section the section id for which to load the settings
85
-	 * @return array array of IAdmin[] where key is the priority
86
-	 * @since 9.1.0
87
-	 */
88
-	public function getAdminSettings($section): array;
81
+    /**
82
+     * returns a list of the admin settings
83
+     *
84
+     * @param string $section the section id for which to load the settings
85
+     * @return array array of IAdmin[] where key is the priority
86
+     * @since 9.1.0
87
+     */
88
+    public function getAdminSettings($section): array;
89 89
 
90
-	/**
91
-	 * returns a list of the personal  settings
92
-	 *
93
-	 * @param string $section the section id for which to load the settings
94
-	 * @return array array of IPersonal[] where key is the priority
95
-	 * @since 13.0.0
96
-	 */
97
-	public function getPersonalSettings($section): array;
90
+    /**
91
+     * returns a list of the personal  settings
92
+     *
93
+     * @param string $section the section id for which to load the settings
94
+     * @return array array of IPersonal[] where key is the priority
95
+     * @since 13.0.0
96
+     */
97
+    public function getPersonalSettings($section): array;
98 98
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -36,7 +36,7 @@  discard block
 block discarded – undo
36 36
 	/**
37 37
 	 * @since 9.1.0
38 38
 	 */
39
-	const KEY_ADMIN_SECTION  = 'admin-section';
39
+	const KEY_ADMIN_SECTION = 'admin-section';
40 40
 
41 41
 	/**
42 42
 	 * @since 13.0.0
@@ -46,7 +46,7 @@  discard block
 block discarded – undo
46 46
 	/**
47 47
 	 * @since 13.0.0
48 48
 	 */
49
-	const KEY_PERSONAL_SECTION  = 'personal-section';
49
+	const KEY_PERSONAL_SECTION = 'personal-section';
50 50
 
51 51
 	/**
52 52
 	 * @param string $type 'admin' or 'personal'
Please login to merge, or discard this patch.
lib/base.php 2 patches
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -122,14 +122,14 @@  discard block
 block discarded – undo
122 122
 	 * the app path list is empty or contains an invalid path
123 123
 	 */
124 124
 	public static function initPaths() {
125
-		if(defined('PHPUNIT_CONFIG_DIR')) {
126
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
127
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
128
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
129
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
-			self::$configDir = rtrim($dir, '/') . '/';
125
+		if (defined('PHPUNIT_CONFIG_DIR')) {
126
+			self::$configDir = OC::$SERVERROOT.'/'.PHPUNIT_CONFIG_DIR.'/';
127
+		} elseif (defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT.'/tests/config/')) {
128
+			self::$configDir = OC::$SERVERROOT.'/tests/config/';
129
+		} elseif ($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
130
+			self::$configDir = rtrim($dir, '/').'/';
131 131
 		} else {
132
-			self::$configDir = OC::$SERVERROOT . '/config/';
132
+			self::$configDir = OC::$SERVERROOT.'/config/';
133 133
 		}
134 134
 		self::$config = new \OC\Config(self::$configDir);
135 135
 
@@ -151,9 +151,9 @@  discard block
 block discarded – undo
151 151
 			//make sure suburi follows the same rules as scriptName
152 152
 			if (substr(OC::$SUBURI, -9) != 'index.php') {
153 153
 				if (substr(OC::$SUBURI, -1) != '/') {
154
-					OC::$SUBURI = OC::$SUBURI . '/';
154
+					OC::$SUBURI = OC::$SUBURI.'/';
155 155
 				}
156
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
156
+				OC::$SUBURI = OC::$SUBURI.'index.php';
157 157
 			}
158 158
 		}
159 159
 
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
 				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
166 166
 
167 167
 				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
168
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
168
+					OC::$WEBROOT = '/'.OC::$WEBROOT;
169 169
 				}
170 170
 			} else {
171 171
 				// The scriptName is not ending with OC::$SUBURI
@@ -194,11 +194,11 @@  discard block
 block discarded – undo
194 194
 					OC::$APPSROOTS[] = $paths;
195 195
 				}
196 196
 			}
197
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
198
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
199
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
197
+		} elseif (file_exists(OC::$SERVERROOT.'/apps')) {
198
+			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT.'/apps', 'url' => '/apps', 'writable' => true);
199
+		} elseif (file_exists(OC::$SERVERROOT.'/../apps')) {
200 200
 			OC::$APPSROOTS[] = array(
201
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
201
+				'path' => rtrim(dirname(OC::$SERVERROOT), '/').'/apps',
202 202
 				'url' => '/apps',
203 203
 				'writable' => true
204 204
 			);
@@ -228,8 +228,8 @@  discard block
 block discarded – undo
228 228
 		$l = \OC::$server->getL10N('lib');
229 229
 
230 230
 		// Create config if it does not already exist
231
-		$configFilePath = self::$configDir .'/config.php';
232
-		if(!file_exists($configFilePath)) {
231
+		$configFilePath = self::$configDir.'/config.php';
232
+		if (!file_exists($configFilePath)) {
233 233
 			@touch($configFilePath);
234 234
 		}
235 235
 
@@ -244,13 +244,13 @@  discard block
 block discarded – undo
244 244
 				echo $l->t('Cannot write into "config" directory!')."\n";
245 245
 				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
246 246
 				echo "\n";
247
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
247
+				echo $l->t('See %s', [$urlGenerator->linkToDocs('admin-dir_permissions')])."\n";
248 248
 				exit;
249 249
 			} else {
250 250
 				OC_Template::printErrorPage(
251 251
 					$l->t('Cannot write into "config" directory!'),
252 252
 					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
253
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
253
+					 [$urlGenerator->linkToDocs('admin-dir_permissions')])
254 254
 				);
255 255
 			}
256 256
 		}
@@ -265,8 +265,8 @@  discard block
 block discarded – undo
265 265
 			if (OC::$CLI) {
266 266
 				throw new Exception('Not installed');
267 267
 			} else {
268
-				$url = OC::$WEBROOT . '/index.php';
269
-				header('Location: ' . $url);
268
+				$url = OC::$WEBROOT.'/index.php';
269
+				header('Location: '.$url);
270 270
 			}
271 271
 			exit();
272 272
 		}
@@ -372,14 +372,14 @@  discard block
 block discarded – undo
372 372
 		$incompatibleShippedApps = [];
373 373
 		foreach ($incompatibleApps as $appInfo) {
374 374
 			if ($appManager->isShipped($appInfo['id'])) {
375
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
375
+				$incompatibleShippedApps[] = $appInfo['name'].' ('.$appInfo['id'].')';
376 376
 			}
377 377
 		}
378 378
 
379 379
 		if (!empty($incompatibleShippedApps)) {
380 380
 			$l = \OC::$server->getL10N('core');
381 381
 			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
382
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
382
+			throw new \OC\HintException('The files of the app '.implode(', ', $incompatibleShippedApps).' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
383 383
 		}
384 384
 
385 385
 		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
@@ -390,7 +390,7 @@  discard block
 block discarded – undo
390 390
 	}
391 391
 
392 392
 	public static function initSession() {
393
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
393
+		if (self::$server->getRequest()->getServerProtocol() === 'https') {
394 394
 			ini_set('session.cookie_secure', true);
395 395
 		}
396 396
 
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 		ini_set('session.cookie_httponly', 'true');
399 399
 
400 400
 		// set the cookie path to the Nextcloud directory
401
-		$cookie_path = OC::$WEBROOT ? : '/';
401
+		$cookie_path = OC::$WEBROOT ?: '/';
402 402
 		ini_set('session.cookie_path', $cookie_path);
403 403
 
404 404
 		// Let the session name be changed in the initSession Hook
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 		// session timeout
433 433
 		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
434 434
 			if (isset($_COOKIE[session_name()])) {
435
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
435
+				setcookie(session_name(), null, -1, self::$WEBROOT ?: '/');
436 436
 			}
437 437
 			\OC::$server->getUserSession()->logout();
438 438
 		}
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
 				continue;
455 455
 			}
456 456
 
457
-			$file = $appPath . '/appinfo/classpath.php';
457
+			$file = $appPath.'/appinfo/classpath.php';
458 458
 			if (file_exists($file)) {
459 459
 				require_once $file;
460 460
 			}
@@ -482,14 +482,14 @@  discard block
 block discarded – undo
482 482
 
483 483
 		// Append __Host to the cookie if it meets the requirements
484 484
 		$cookiePrefix = '';
485
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
485
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
486 486
 			$cookiePrefix = '__Host-';
487 487
 		}
488 488
 
489
-		foreach($policies as $policy) {
489
+		foreach ($policies as $policy) {
490 490
 			header(
491 491
 				sprintf(
492
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
492
+					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;'.$secureCookie.'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
493 493
 					$cookiePrefix,
494 494
 					$policy,
495 495
 					$cookieParams['path'],
@@ -520,31 +520,31 @@  discard block
 block discarded – undo
520 520
 			// OS X Finder
521 521
 			'/^WebDAVFS/',
522 522
 		];
523
-		if($request->isUserAgent($incompatibleUserAgents)) {
523
+		if ($request->isUserAgent($incompatibleUserAgents)) {
524 524
 			return;
525 525
 		}
526 526
 
527
-		if(count($_COOKIE) > 0) {
527
+		if (count($_COOKIE) > 0) {
528 528
 			$requestUri = $request->getScriptName();
529 529
 			$processingScript = explode('/', $requestUri);
530
-			$processingScript = $processingScript[count($processingScript)-1];
530
+			$processingScript = $processingScript[count($processingScript) - 1];
531 531
 
532 532
 			// index.php routes are handled in the middleware
533
-			if($processingScript === 'index.php') {
533
+			if ($processingScript === 'index.php') {
534 534
 				return;
535 535
 			}
536 536
 
537 537
 			// All other endpoints require the lax and the strict cookie
538
-			if(!$request->passesStrictCookieCheck()) {
538
+			if (!$request->passesStrictCookieCheck()) {
539 539
 				self::sendSameSiteCookies();
540 540
 				// Debug mode gets access to the resources without strict cookie
541 541
 				// due to the fact that the SabreDAV browser also lives there.
542
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
542
+				if (!\OC::$server->getConfig()->getSystemValue('debug', false)) {
543 543
 					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
544 544
 					exit();
545 545
 				}
546 546
 			}
547
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
547
+		} elseif (!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
548 548
 			self::sendSameSiteCookies();
549 549
 		}
550 550
 	}
@@ -555,12 +555,12 @@  discard block
 block discarded – undo
555 555
 
556 556
 		// register autoloader
557 557
 		$loaderStart = microtime(true);
558
-		require_once __DIR__ . '/autoloader.php';
558
+		require_once __DIR__.'/autoloader.php';
559 559
 		self::$loader = new \OC\Autoloader([
560
-			OC::$SERVERROOT . '/lib/private/legacy',
560
+			OC::$SERVERROOT.'/lib/private/legacy',
561 561
 		]);
562 562
 		if (defined('PHPUNIT_RUN')) {
563
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
563
+			self::$loader->addValidRoot(OC::$SERVERROOT.'/tests');
564 564
 		}
565 565
 		spl_autoload_register(array(self::$loader, 'load'));
566 566
 		$loaderEnd = microtime(true);
@@ -568,12 +568,12 @@  discard block
 block discarded – undo
568 568
 		self::$CLI = (php_sapi_name() == 'cli');
569 569
 
570 570
 		// Add default composer PSR-4 autoloader
571
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
571
+		self::$composerAutoloader = require_once OC::$SERVERROOT.'/lib/composer/autoload.php';
572 572
 
573 573
 		try {
574 574
 			self::initPaths();
575 575
 			// setup 3rdparty autoloader
576
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
576
+			$vendorAutoLoad = OC::$SERVERROOT.'/3rdparty/autoload.php';
577 577
 			if (!file_exists($vendorAutoLoad)) {
578 578
 				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
579 579
 			}
@@ -583,7 +583,7 @@  discard block
 block discarded – undo
583 583
 			if (!self::$CLI) {
584 584
 				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
585 585
 				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
586
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
586
+				header($protocol.' '.OC_Response::STATUS_SERVICE_UNAVAILABLE);
587 587
 			}
588 588
 			// we can't use the template error page here, because this needs the
589 589
 			// DI container which isn't available yet
@@ -601,7 +601,7 @@  discard block
 block discarded – undo
601 601
 		@ini_set('display_errors', '0');
602 602
 		@ini_set('log_errors', '1');
603 603
 
604
-		if(!date_default_timezone_set('UTC')) {
604
+		if (!date_default_timezone_set('UTC')) {
605 605
 			throw new \RuntimeException('Could not set timezone to UTC');
606 606
 		}
607 607
 
@@ -655,11 +655,11 @@  discard block
 block discarded – undo
655 655
 					// Convert l10n string into regular string for usage in database
656 656
 					$staticErrors = [];
657 657
 					foreach ($errors as $error) {
658
-						echo $error['error'] . "\n";
659
-						echo $error['hint'] . "\n\n";
658
+						echo $error['error']."\n";
659
+						echo $error['hint']."\n\n";
660 660
 						$staticErrors[] = [
661
-							'error' => (string)$error['error'],
662
-							'hint' => (string)$error['hint'],
661
+							'error' => (string) $error['error'],
662
+							'hint' => (string) $error['hint'],
663 663
 						];
664 664
 					}
665 665
 
@@ -681,7 +681,7 @@  discard block
 block discarded – undo
681 681
 		}
682 682
 		//try to set the session lifetime
683 683
 		$sessionLifeTime = self::getSessionLifeTime();
684
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
684
+		@ini_set('gc_maxlifetime', (string) $sessionLifeTime);
685 685
 
686 686
 		$systemConfig = \OC::$server->getSystemConfig();
687 687
 
@@ -726,7 +726,7 @@  discard block
 block discarded – undo
726 726
 		register_shutdown_function(array($lockProvider, 'releaseAll'));
727 727
 
728 728
 		// Check whether the sample configuration has been copied
729
-		if($systemConfig->getValue('copied_sample_config', false)) {
729
+		if ($systemConfig->getValue('copied_sample_config', false)) {
730 730
 			$l = \OC::$server->getL10N('lib');
731 731
 			header('HTTP/1.1 503 Service Temporarily Unavailable');
732 732
 			header('Status: 503 Service Temporarily Unavailable');
@@ -752,11 +752,11 @@  discard block
 block discarded – undo
752 752
 		) {
753 753
 			// Allow access to CSS resources
754 754
 			$isScssRequest = false;
755
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
755
+			if (strpos($request->getPathInfo(), '/css/') === 0) {
756 756
 				$isScssRequest = true;
757 757
 			}
758 758
 
759
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
759
+			if (substr($request->getRequestUri(), -11) === '/status.php') {
760 760
 				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
761 761
 				header('Status: 400 Bad Request');
762 762
 				header('Content-Type: application/json');
@@ -796,7 +796,7 @@  discard block
 block discarded – undo
796 796
 
797 797
 			// NOTE: This will be replaced to use OCP
798 798
 			$userSession = self::$server->getUserSession();
799
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
799
+			$userSession->listen('\OC\User', 'postLogin', function() use ($userSession) {
800 800
 				if (!defined('PHPUNIT_RUN')) {
801 801
 					// reset brute force delay for this IP address and username
802 802
 					$uid = \OC::$server->getUserSession()->getUser()->getUID();
@@ -933,12 +933,12 @@  discard block
 block discarded – undo
933 933
 		// emergency app disabling
934 934
 		if ($requestPath === '/disableapp'
935 935
 			&& $request->getMethod() === 'POST'
936
-			&& ((array)$request->getParam('appid')) !== ''
936
+			&& ((array) $request->getParam('appid')) !== ''
937 937
 		) {
938 938
 			\OCP\JSON::callCheck();
939 939
 			\OCP\JSON::checkAdminUser();
940
-			$appIds = (array)$request->getParam('appid');
941
-			foreach($appIds as $appId) {
940
+			$appIds = (array) $request->getParam('appid');
941
+			foreach ($appIds as $appId) {
942 942
 				$appId = \OC_App::cleanAppId($appId);
943 943
 				\OC_App::disable($appId);
944 944
 			}
@@ -953,7 +953,7 @@  discard block
 block discarded – undo
953 953
 		if (!\OCP\Util::needUpgrade()
954 954
 			&& !$systemConfig->getValue('maintenance', false)) {
955 955
 			// For logged-in users: Load everything
956
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
956
+			if (\OC::$server->getUserSession()->isLoggedIn()) {
957 957
 				OC_App::loadApps();
958 958
 			} else {
959 959
 				// For guests: Load only filesystem and logging
Please login to merge, or discard this patch.
Indentation   +987 added lines, -987 removed lines patch added patch discarded remove patch
@@ -67,993 +67,993 @@
 block discarded – undo
67 67
  * OC_autoload!
68 68
  */
69 69
 class OC {
70
-	/**
71
-	 * Associative array for autoloading. classname => filename
72
-	 */
73
-	public static $CLASSPATH = array();
74
-	/**
75
-	 * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
76
-	 */
77
-	public static $SERVERROOT = '';
78
-	/**
79
-	 * the current request path relative to the Nextcloud root (e.g. files/index.php)
80
-	 */
81
-	private static $SUBURI = '';
82
-	/**
83
-	 * the Nextcloud root path for http requests (e.g. nextcloud/)
84
-	 */
85
-	public static $WEBROOT = '';
86
-	/**
87
-	 * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
88
-	 * web path in 'url'
89
-	 */
90
-	public static $APPSROOTS = array();
91
-
92
-	/**
93
-	 * @var string
94
-	 */
95
-	public static $configDir;
96
-
97
-	/**
98
-	 * requested app
99
-	 */
100
-	public static $REQUESTEDAPP = '';
101
-
102
-	/**
103
-	 * check if Nextcloud runs in cli mode
104
-	 */
105
-	public static $CLI = false;
106
-
107
-	/**
108
-	 * @var \OC\Autoloader $loader
109
-	 */
110
-	public static $loader = null;
111
-
112
-	/** @var \Composer\Autoload\ClassLoader $composerAutoloader */
113
-	public static $composerAutoloader = null;
114
-
115
-	/**
116
-	 * @var \OC\Server
117
-	 */
118
-	public static $server = null;
119
-
120
-	/**
121
-	 * @var \OC\Config
122
-	 */
123
-	private static $config = null;
124
-
125
-	/**
126
-	 * @throws \RuntimeException when the 3rdparty directory is missing or
127
-	 * the app path list is empty or contains an invalid path
128
-	 */
129
-	public static function initPaths() {
130
-		if(defined('PHPUNIT_CONFIG_DIR')) {
131
-			self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
132
-		} elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
133
-			self::$configDir = OC::$SERVERROOT . '/tests/config/';
134
-		} elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
135
-			self::$configDir = rtrim($dir, '/') . '/';
136
-		} else {
137
-			self::$configDir = OC::$SERVERROOT . '/config/';
138
-		}
139
-		self::$config = new \OC\Config(self::$configDir);
140
-
141
-		OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
142
-		/**
143
-		 * FIXME: The following lines are required because we can't yet instantiate
144
-		 *        \OC::$server->getRequest() since \OC::$server does not yet exist.
145
-		 */
146
-		$params = [
147
-			'server' => [
148
-				'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
149
-				'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
150
-			],
151
-		];
152
-		$fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
153
-		$scriptName = $fakeRequest->getScriptName();
154
-		if (substr($scriptName, -1) == '/') {
155
-			$scriptName .= 'index.php';
156
-			//make sure suburi follows the same rules as scriptName
157
-			if (substr(OC::$SUBURI, -9) != 'index.php') {
158
-				if (substr(OC::$SUBURI, -1) != '/') {
159
-					OC::$SUBURI = OC::$SUBURI . '/';
160
-				}
161
-				OC::$SUBURI = OC::$SUBURI . 'index.php';
162
-			}
163
-		}
164
-
165
-
166
-		if (OC::$CLI) {
167
-			OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
168
-		} else {
169
-			if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
170
-				OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
171
-
172
-				if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
173
-					OC::$WEBROOT = '/' . OC::$WEBROOT;
174
-				}
175
-			} else {
176
-				// The scriptName is not ending with OC::$SUBURI
177
-				// This most likely means that we are calling from CLI.
178
-				// However some cron jobs still need to generate
179
-				// a web URL, so we use overwritewebroot as a fallback.
180
-				OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
181
-			}
182
-
183
-			// Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
184
-			// slash which is required by URL generation.
185
-			if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
186
-					substr($_SERVER['REQUEST_URI'], -1) !== '/') {
187
-				header('Location: '.\OC::$WEBROOT.'/');
188
-				exit();
189
-			}
190
-		}
191
-
192
-		// search the apps folder
193
-		$config_paths = self::$config->getValue('apps_paths', array());
194
-		if (!empty($config_paths)) {
195
-			foreach ($config_paths as $paths) {
196
-				if (isset($paths['url']) && isset($paths['path'])) {
197
-					$paths['url'] = rtrim($paths['url'], '/');
198
-					$paths['path'] = rtrim($paths['path'], '/');
199
-					OC::$APPSROOTS[] = $paths;
200
-				}
201
-			}
202
-		} elseif (file_exists(OC::$SERVERROOT . '/apps')) {
203
-			OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
204
-		} elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
205
-			OC::$APPSROOTS[] = array(
206
-				'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
207
-				'url' => '/apps',
208
-				'writable' => true
209
-			);
210
-		}
211
-
212
-		if (empty(OC::$APPSROOTS)) {
213
-			throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
214
-				. ' or the folder above. You can also configure the location in the config.php file.');
215
-		}
216
-		$paths = array();
217
-		foreach (OC::$APPSROOTS as $path) {
218
-			$paths[] = $path['path'];
219
-			if (!is_dir($path['path'])) {
220
-				throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
221
-					. ' Nextcloud folder or the folder above. You can also configure the location in the'
222
-					. ' config.php file.', $path['path']));
223
-			}
224
-		}
225
-
226
-		// set the right include path
227
-		set_include_path(
228
-			implode(PATH_SEPARATOR, $paths)
229
-		);
230
-	}
231
-
232
-	public static function checkConfig() {
233
-		$l = \OC::$server->getL10N('lib');
234
-
235
-		// Create config if it does not already exist
236
-		$configFilePath = self::$configDir .'/config.php';
237
-		if(!file_exists($configFilePath)) {
238
-			@touch($configFilePath);
239
-		}
240
-
241
-		// Check if config is writable
242
-		$configFileWritable = is_writable($configFilePath);
243
-		if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
244
-			|| !$configFileWritable && \OCP\Util::needUpgrade()) {
245
-
246
-			$urlGenerator = \OC::$server->getURLGenerator();
247
-
248
-			if (self::$CLI) {
249
-				echo $l->t('Cannot write into "config" directory!')."\n";
250
-				echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
251
-				echo "\n";
252
-				echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
-				exit;
254
-			} else {
255
-				OC_Template::printErrorPage(
256
-					$l->t('Cannot write into "config" directory!'),
257
-					$l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
258
-					 [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
259
-				);
260
-			}
261
-		}
262
-	}
263
-
264
-	public static function checkInstalled() {
265
-		if (defined('OC_CONSOLE')) {
266
-			return;
267
-		}
268
-		// Redirect to installer if not installed
269
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
270
-			if (OC::$CLI) {
271
-				throw new Exception('Not installed');
272
-			} else {
273
-				$url = OC::$WEBROOT . '/index.php';
274
-				header('Location: ' . $url);
275
-			}
276
-			exit();
277
-		}
278
-	}
279
-
280
-	public static function checkMaintenanceMode() {
281
-		// Allow ajax update script to execute without being stopped
282
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
283
-			// send http status 503
284
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
285
-			header('Status: 503 Service Temporarily Unavailable');
286
-			header('Retry-After: 120');
287
-
288
-			// render error page
289
-			$template = new OC_Template('', 'update.user', 'guest');
290
-			OC_Util::addScript('maintenance-check');
291
-			OC_Util::addStyle('core', 'guest');
292
-			$template->printPage();
293
-			die();
294
-		}
295
-	}
296
-
297
-	/**
298
-	 * Prints the upgrade page
299
-	 *
300
-	 * @param \OC\SystemConfig $systemConfig
301
-	 */
302
-	private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
303
-		$disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
304
-		$tooBig = false;
305
-		if (!$disableWebUpdater) {
306
-			$apps = \OC::$server->getAppManager();
307
-			if ($apps->isInstalled('user_ldap')) {
308
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
309
-
310
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
311
-					->from('ldap_user_mapping')
312
-					->execute();
313
-				$row = $result->fetch();
314
-				$result->closeCursor();
315
-
316
-				$tooBig = ($row['user_count'] > 50);
317
-			}
318
-			if (!$tooBig && $apps->isInstalled('user_saml')) {
319
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
-
321
-				$result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
322
-					->from('user_saml_users')
323
-					->execute();
324
-				$row = $result->fetch();
325
-				$result->closeCursor();
326
-
327
-				$tooBig = ($row['user_count'] > 50);
328
-			}
329
-			if (!$tooBig) {
330
-				// count users
331
-				$stats = \OC::$server->getUserManager()->countUsers();
332
-				$totalUsers = array_sum($stats);
333
-				$tooBig = ($totalUsers > 50);
334
-			}
335
-		}
336
-		$ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
337
-			$_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
338
-
339
-		if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
340
-			// send http status 503
341
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
342
-			header('Status: 503 Service Temporarily Unavailable');
343
-			header('Retry-After: 120');
344
-
345
-			// render error page
346
-			$template = new OC_Template('', 'update.use-cli', 'guest');
347
-			$template->assign('productName', 'nextcloud'); // for now
348
-			$template->assign('version', OC_Util::getVersionString());
349
-			$template->assign('tooBig', $tooBig);
350
-
351
-			$template->printPage();
352
-			die();
353
-		}
354
-
355
-		// check whether this is a core update or apps update
356
-		$installedVersion = $systemConfig->getValue('version', '0.0.0');
357
-		$currentVersion = implode('.', \OCP\Util::getVersion());
358
-
359
-		// if not a core upgrade, then it's apps upgrade
360
-		$isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
361
-
362
-		$oldTheme = $systemConfig->getValue('theme');
363
-		$systemConfig->setValue('theme', '');
364
-		OC_Util::addScript('config'); // needed for web root
365
-		OC_Util::addScript('update');
366
-
367
-		/** @var \OC\App\AppManager $appManager */
368
-		$appManager = \OC::$server->getAppManager();
369
-
370
-		$tmpl = new OC_Template('', 'update.admin', 'guest');
371
-		$tmpl->assign('version', OC_Util::getVersionString());
372
-		$tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
373
-
374
-		// get third party apps
375
-		$ocVersion = \OCP\Util::getVersion();
376
-		$incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
377
-		$incompatibleShippedApps = [];
378
-		foreach ($incompatibleApps as $appInfo) {
379
-			if ($appManager->isShipped($appInfo['id'])) {
380
-				$incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
381
-			}
382
-		}
383
-
384
-		if (!empty($incompatibleShippedApps)) {
385
-			$l = \OC::$server->getL10N('core');
386
-			$hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
387
-			throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
388
-		}
389
-
390
-		$tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
391
-		$tmpl->assign('incompatibleAppsList', $incompatibleApps);
392
-		$tmpl->assign('productName', 'Nextcloud'); // for now
393
-		$tmpl->assign('oldTheme', $oldTheme);
394
-		$tmpl->printPage();
395
-	}
396
-
397
-	public static function initSession() {
398
-		if(self::$server->getRequest()->getServerProtocol() === 'https') {
399
-			ini_set('session.cookie_secure', true);
400
-		}
401
-
402
-		// prevents javascript from accessing php session cookies
403
-		ini_set('session.cookie_httponly', 'true');
404
-
405
-		// set the cookie path to the Nextcloud directory
406
-		$cookie_path = OC::$WEBROOT ? : '/';
407
-		ini_set('session.cookie_path', $cookie_path);
408
-
409
-		// Let the session name be changed in the initSession Hook
410
-		$sessionName = OC_Util::getInstanceId();
411
-
412
-		try {
413
-			// Allow session apps to create a custom session object
414
-			$useCustomSession = false;
415
-			$session = self::$server->getSession();
416
-			OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
417
-			if (!$useCustomSession) {
418
-				// set the session name to the instance id - which is unique
419
-				$session = new \OC\Session\Internal($sessionName);
420
-			}
421
-
422
-			$cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
423
-			$session = $cryptoWrapper->wrapSession($session);
424
-			self::$server->setSession($session);
425
-
426
-			// if session can't be started break with http 500 error
427
-		} catch (Exception $e) {
428
-			\OCP\Util::logException('base', $e);
429
-			//show the user a detailed error page
430
-			OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
431
-			OC_Template::printExceptionErrorPage($e);
432
-			die();
433
-		}
434
-
435
-		$sessionLifeTime = self::getSessionLifeTime();
436
-
437
-		// session timeout
438
-		if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
439
-			if (isset($_COOKIE[session_name()])) {
440
-				setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
441
-			}
442
-			\OC::$server->getUserSession()->logout();
443
-		}
444
-
445
-		$session->set('LAST_ACTIVITY', time());
446
-	}
447
-
448
-	/**
449
-	 * @return string
450
-	 */
451
-	private static function getSessionLifeTime() {
452
-		return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
453
-	}
454
-
455
-	public static function loadAppClassPaths() {
456
-		foreach (OC_App::getEnabledApps() as $app) {
457
-			$appPath = OC_App::getAppPath($app);
458
-			if ($appPath === false) {
459
-				continue;
460
-			}
461
-
462
-			$file = $appPath . '/appinfo/classpath.php';
463
-			if (file_exists($file)) {
464
-				require_once $file;
465
-			}
466
-		}
467
-	}
468
-
469
-	/**
470
-	 * Try to set some values to the required Nextcloud default
471
-	 */
472
-	public static function setRequiredIniValues() {
473
-		@ini_set('default_charset', 'UTF-8');
474
-		@ini_set('gd.jpeg_ignore_warning', '1');
475
-	}
476
-
477
-	/**
478
-	 * Send the same site cookies
479
-	 */
480
-	private static function sendSameSiteCookies() {
481
-		$cookieParams = session_get_cookie_params();
482
-		$secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
483
-		$policies = [
484
-			'lax',
485
-			'strict',
486
-		];
487
-
488
-		// Append __Host to the cookie if it meets the requirements
489
-		$cookiePrefix = '';
490
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
491
-			$cookiePrefix = '__Host-';
492
-		}
493
-
494
-		foreach($policies as $policy) {
495
-			header(
496
-				sprintf(
497
-					'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
498
-					$cookiePrefix,
499
-					$policy,
500
-					$cookieParams['path'],
501
-					$policy
502
-				),
503
-				false
504
-			);
505
-		}
506
-	}
507
-
508
-	/**
509
-	 * Same Site cookie to further mitigate CSRF attacks. This cookie has to
510
-	 * be set in every request if cookies are sent to add a second level of
511
-	 * defense against CSRF.
512
-	 *
513
-	 * If the cookie is not sent this will set the cookie and reload the page.
514
-	 * We use an additional cookie since we want to protect logout CSRF and
515
-	 * also we can't directly interfere with PHP's session mechanism.
516
-	 */
517
-	private static function performSameSiteCookieProtection() {
518
-		$request = \OC::$server->getRequest();
519
-
520
-		// Some user agents are notorious and don't really properly follow HTTP
521
-		// specifications. For those, have an automated opt-out. Since the protection
522
-		// for remote.php is applied in base.php as starting point we need to opt out
523
-		// here.
524
-		$incompatibleUserAgents = [
525
-			// OS X Finder
526
-			'/^WebDAVFS/',
527
-		];
528
-		if($request->isUserAgent($incompatibleUserAgents)) {
529
-			return;
530
-		}
531
-
532
-		if(count($_COOKIE) > 0) {
533
-			$requestUri = $request->getScriptName();
534
-			$processingScript = explode('/', $requestUri);
535
-			$processingScript = $processingScript[count($processingScript)-1];
536
-
537
-			// index.php routes are handled in the middleware
538
-			if($processingScript === 'index.php') {
539
-				return;
540
-			}
541
-
542
-			// All other endpoints require the lax and the strict cookie
543
-			if(!$request->passesStrictCookieCheck()) {
544
-				self::sendSameSiteCookies();
545
-				// Debug mode gets access to the resources without strict cookie
546
-				// due to the fact that the SabreDAV browser also lives there.
547
-				if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
548
-					http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
549
-					exit();
550
-				}
551
-			}
552
-		} elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
553
-			self::sendSameSiteCookies();
554
-		}
555
-	}
556
-
557
-	public static function init() {
558
-		// calculate the root directories
559
-		OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
560
-
561
-		// register autoloader
562
-		$loaderStart = microtime(true);
563
-		require_once __DIR__ . '/autoloader.php';
564
-		self::$loader = new \OC\Autoloader([
565
-			OC::$SERVERROOT . '/lib/private/legacy',
566
-		]);
567
-		if (defined('PHPUNIT_RUN')) {
568
-			self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
569
-		}
570
-		spl_autoload_register(array(self::$loader, 'load'));
571
-		$loaderEnd = microtime(true);
572
-
573
-		self::$CLI = (php_sapi_name() == 'cli');
574
-
575
-		// Add default composer PSR-4 autoloader
576
-		self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
577
-
578
-		try {
579
-			self::initPaths();
580
-			// setup 3rdparty autoloader
581
-			$vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
582
-			if (!file_exists($vendorAutoLoad)) {
583
-				throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
584
-			}
585
-			require_once $vendorAutoLoad;
586
-
587
-		} catch (\RuntimeException $e) {
588
-			if (!self::$CLI) {
589
-				$claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
590
-				$protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
591
-				header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
592
-			}
593
-			// we can't use the template error page here, because this needs the
594
-			// DI container which isn't available yet
595
-			print($e->getMessage());
596
-			exit();
597
-		}
598
-
599
-		// setup the basic server
600
-		self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
601
-		\OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
602
-		\OC::$server->getEventLogger()->start('boot', 'Initialize');
603
-
604
-		// Don't display errors and log them
605
-		error_reporting(E_ALL | E_STRICT);
606
-		@ini_set('display_errors', '0');
607
-		@ini_set('log_errors', '1');
608
-
609
-		if(!date_default_timezone_set('UTC')) {
610
-			throw new \RuntimeException('Could not set timezone to UTC');
611
-		}
612
-
613
-		//try to configure php to enable big file uploads.
614
-		//this doesn´t work always depending on the webserver and php configuration.
615
-		//Let´s try to overwrite some defaults anyway
616
-
617
-		//try to set the maximum execution time to 60min
618
-		if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
619
-			@set_time_limit(3600);
620
-		}
621
-		@ini_set('max_execution_time', '3600');
622
-		@ini_set('max_input_time', '3600');
623
-
624
-		//try to set the maximum filesize to 10G
625
-		@ini_set('upload_max_filesize', '10G');
626
-		@ini_set('post_max_size', '10G');
627
-		@ini_set('file_uploads', '50');
628
-
629
-		self::setRequiredIniValues();
630
-		self::handleAuthHeaders();
631
-		self::registerAutoloaderCache();
632
-
633
-		// initialize intl fallback is necessary
634
-		\Patchwork\Utf8\Bootup::initIntl();
635
-		OC_Util::isSetLocaleWorking();
636
-
637
-		if (!defined('PHPUNIT_RUN')) {
638
-			OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
639
-			$debug = \OC::$server->getConfig()->getSystemValue('debug', false);
640
-			OC\Log\ErrorHandler::register($debug);
641
-		}
642
-
643
-		\OC::$server->getEventLogger()->start('init_session', 'Initialize session');
644
-		OC_App::loadApps(array('session'));
645
-		if (!self::$CLI) {
646
-			self::initSession();
647
-		}
648
-		\OC::$server->getEventLogger()->end('init_session');
649
-		self::checkConfig();
650
-		self::checkInstalled();
651
-
652
-		OC_Response::addSecurityHeaders();
653
-
654
-		self::performSameSiteCookieProtection();
655
-
656
-		if (!defined('OC_CONSOLE')) {
657
-			$errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
658
-			if (count($errors) > 0) {
659
-				if (self::$CLI) {
660
-					// Convert l10n string into regular string for usage in database
661
-					$staticErrors = [];
662
-					foreach ($errors as $error) {
663
-						echo $error['error'] . "\n";
664
-						echo $error['hint'] . "\n\n";
665
-						$staticErrors[] = [
666
-							'error' => (string)$error['error'],
667
-							'hint' => (string)$error['hint'],
668
-						];
669
-					}
670
-
671
-					try {
672
-						\OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
673
-					} catch (\Exception $e) {
674
-						echo('Writing to database failed');
675
-					}
676
-					exit(1);
677
-				} else {
678
-					OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
679
-					OC_Util::addStyle('guest');
680
-					OC_Template::printGuestPage('', 'error', array('errors' => $errors));
681
-					exit;
682
-				}
683
-			} elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
684
-				\OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
685
-			}
686
-		}
687
-		//try to set the session lifetime
688
-		$sessionLifeTime = self::getSessionLifeTime();
689
-		@ini_set('gc_maxlifetime', (string)$sessionLifeTime);
690
-
691
-		$systemConfig = \OC::$server->getSystemConfig();
692
-
693
-		// User and Groups
694
-		if (!$systemConfig->getValue("installed", false)) {
695
-			self::$server->getSession()->set('user_id', '');
696
-		}
697
-
698
-		OC_User::useBackend(new \OC\User\Database());
699
-		\OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
700
-
701
-		// Subscribe to the hook
702
-		\OCP\Util::connectHook(
703
-			'\OCA\Files_Sharing\API\Server2Server',
704
-			'preLoginNameUsedAsUserName',
705
-			'\OC\User\Database',
706
-			'preLoginNameUsedAsUserName'
707
-		);
708
-
709
-		//setup extra user backends
710
-		if (!\OCP\Util::needUpgrade()) {
711
-			OC_User::setupBackends();
712
-		} else {
713
-			// Run upgrades in incognito mode
714
-			OC_User::setIncognitoMode(true);
715
-		}
716
-
717
-		self::registerCleanupHooks();
718
-		self::registerFilesystemHooks();
719
-		self::registerShareHooks();
720
-		self::registerEncryptionWrapper();
721
-		self::registerEncryptionHooks();
722
-		self::registerAccountHooks();
723
-
724
-		$settings = new \OC\Settings\Application();
725
-		$settings->register();
726
-
727
-		//make sure temporary files are cleaned up
728
-		$tmpManager = \OC::$server->getTempManager();
729
-		register_shutdown_function(array($tmpManager, 'clean'));
730
-		$lockProvider = \OC::$server->getLockingProvider();
731
-		register_shutdown_function(array($lockProvider, 'releaseAll'));
732
-
733
-		// Check whether the sample configuration has been copied
734
-		if($systemConfig->getValue('copied_sample_config', false)) {
735
-			$l = \OC::$server->getL10N('lib');
736
-			header('HTTP/1.1 503 Service Temporarily Unavailable');
737
-			header('Status: 503 Service Temporarily Unavailable');
738
-			OC_Template::printErrorPage(
739
-				$l->t('Sample configuration detected'),
740
-				$l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
741
-			);
742
-			return;
743
-		}
744
-
745
-		$request = \OC::$server->getRequest();
746
-		$host = $request->getInsecureServerHost();
747
-		/**
748
-		 * if the host passed in headers isn't trusted
749
-		 * FIXME: Should not be in here at all :see_no_evil:
750
-		 */
751
-		if (!OC::$CLI
752
-			// overwritehost is always trusted, workaround to not have to make
753
-			// \OC\AppFramework\Http\Request::getOverwriteHost public
754
-			&& self::$server->getConfig()->getSystemValue('overwritehost') === ''
755
-			&& !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
756
-			&& self::$server->getConfig()->getSystemValue('installed', false)
757
-		) {
758
-			// Allow access to CSS resources
759
-			$isScssRequest = false;
760
-			if(strpos($request->getPathInfo(), '/css/') === 0) {
761
-				$isScssRequest = true;
762
-			}
763
-
764
-			if(substr($request->getRequestUri(), -11) === '/status.php') {
765
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
766
-				header('Status: 400 Bad Request');
767
-				header('Content-Type: application/json');
768
-				echo '{"error": "Trusted domain error.", "code": 15}';
769
-				exit();
770
-			}
771
-
772
-			if (!$isScssRequest) {
773
-				OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
774
-				header('Status: 400 Bad Request');
775
-
776
-				\OC::$server->getLogger()->warning(
777
-					'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
778
-					[
779
-						'app' => 'core',
780
-						'remoteAddress' => $request->getRemoteAddress(),
781
-						'host' => $host,
782
-					]
783
-				);
784
-
785
-				$tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
786
-				$tmpl->assign('domain', $host);
787
-				$tmpl->printPage();
788
-
789
-				exit();
790
-			}
791
-		}
792
-		\OC::$server->getEventLogger()->end('boot');
793
-	}
794
-
795
-	/**
796
-	 * register hooks for the cleanup of cache and bruteforce protection
797
-	 */
798
-	public static function registerCleanupHooks() {
799
-		//don't try to do this before we are properly setup
800
-		if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
801
-
802
-			// NOTE: This will be replaced to use OCP
803
-			$userSession = self::$server->getUserSession();
804
-			$userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
805
-				if (!defined('PHPUNIT_RUN')) {
806
-					// reset brute force delay for this IP address and username
807
-					$uid = \OC::$server->getUserSession()->getUser()->getUID();
808
-					$request = \OC::$server->getRequest();
809
-					$throttler = \OC::$server->getBruteForceThrottler();
810
-					$throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
811
-				}
812
-
813
-				try {
814
-					$cache = new \OC\Cache\File();
815
-					$cache->gc();
816
-				} catch (\OC\ServerNotAvailableException $e) {
817
-					// not a GC exception, pass it on
818
-					throw $e;
819
-				} catch (\OC\ForbiddenException $e) {
820
-					// filesystem blocked for this request, ignore
821
-				} catch (\Exception $e) {
822
-					// a GC exception should not prevent users from using OC,
823
-					// so log the exception
824
-					\OC::$server->getLogger()->logException($e, [
825
-						'message' => 'Exception when running cache gc.',
826
-						'level' => \OCP\Util::WARN,
827
-						'app' => 'core',
828
-					]);
829
-				}
830
-			});
831
-		}
832
-	}
833
-
834
-	private static function registerEncryptionWrapper() {
835
-		$manager = self::$server->getEncryptionManager();
836
-		\OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
837
-	}
838
-
839
-	private static function registerEncryptionHooks() {
840
-		$enabled = self::$server->getEncryptionManager()->isEnabled();
841
-		if ($enabled) {
842
-			\OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
843
-			\OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
844
-			\OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
845
-			\OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
846
-		}
847
-	}
848
-
849
-	private static function registerAccountHooks() {
850
-		$hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
851
-		\OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
852
-	}
853
-
854
-	/**
855
-	 * register hooks for the filesystem
856
-	 */
857
-	public static function registerFilesystemHooks() {
858
-		// Check for blacklisted files
859
-		OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
860
-		OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
861
-	}
862
-
863
-	/**
864
-	 * register hooks for sharing
865
-	 */
866
-	public static function registerShareHooks() {
867
-		if (\OC::$server->getSystemConfig()->getValue('installed')) {
868
-			OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
869
-			OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
870
-			OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
871
-		}
872
-	}
873
-
874
-	protected static function registerAutoloaderCache() {
875
-		// The class loader takes an optional low-latency cache, which MUST be
876
-		// namespaced. The instanceid is used for namespacing, but might be
877
-		// unavailable at this point. Furthermore, it might not be possible to
878
-		// generate an instanceid via \OC_Util::getInstanceId() because the
879
-		// config file may not be writable. As such, we only register a class
880
-		// loader cache if instanceid is available without trying to create one.
881
-		$instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
882
-		if ($instanceId) {
883
-			try {
884
-				$memcacheFactory = \OC::$server->getMemCacheFactory();
885
-				self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
886
-			} catch (\Exception $ex) {
887
-			}
888
-		}
889
-	}
890
-
891
-	/**
892
-	 * Handle the request
893
-	 */
894
-	public static function handleRequest() {
895
-
896
-		\OC::$server->getEventLogger()->start('handle_request', 'Handle request');
897
-		$systemConfig = \OC::$server->getSystemConfig();
898
-		// load all the classpaths from the enabled apps so they are available
899
-		// in the routing files of each app
900
-		OC::loadAppClassPaths();
901
-
902
-		// Check if Nextcloud is installed or in maintenance (update) mode
903
-		if (!$systemConfig->getValue('installed', false)) {
904
-			\OC::$server->getSession()->clear();
905
-			$setupHelper = new OC\Setup(
906
-				$systemConfig,
907
-				\OC::$server->getIniWrapper(),
908
-				\OC::$server->getL10N('lib'),
909
-				\OC::$server->query(\OCP\Defaults::class),
910
-				\OC::$server->getLogger(),
911
-				\OC::$server->getSecureRandom(),
912
-				\OC::$server->query(\OC\Installer::class)
913
-			);
914
-			$controller = new OC\Core\Controller\SetupController($setupHelper);
915
-			$controller->run($_POST);
916
-			exit();
917
-		}
918
-
919
-		$request = \OC::$server->getRequest();
920
-		$requestPath = $request->getRawPathInfo();
921
-		if ($requestPath === '/heartbeat') {
922
-			return;
923
-		}
924
-		if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
925
-			self::checkMaintenanceMode();
926
-
927
-			if (\OCP\Util::needUpgrade()) {
928
-				if (function_exists('opcache_reset')) {
929
-					opcache_reset();
930
-				}
931
-				if (!$systemConfig->getValue('maintenance', false)) {
932
-					self::printUpgradePage($systemConfig);
933
-					exit();
934
-				}
935
-			}
936
-		}
937
-
938
-		// emergency app disabling
939
-		if ($requestPath === '/disableapp'
940
-			&& $request->getMethod() === 'POST'
941
-			&& ((array)$request->getParam('appid')) !== ''
942
-		) {
943
-			\OCP\JSON::callCheck();
944
-			\OCP\JSON::checkAdminUser();
945
-			$appIds = (array)$request->getParam('appid');
946
-			foreach($appIds as $appId) {
947
-				$appId = \OC_App::cleanAppId($appId);
948
-				\OC_App::disable($appId);
949
-			}
950
-			\OC_JSON::success();
951
-			exit();
952
-		}
953
-
954
-		// Always load authentication apps
955
-		OC_App::loadApps(['authentication']);
956
-
957
-		// Load minimum set of apps
958
-		if (!\OCP\Util::needUpgrade()
959
-			&& !$systemConfig->getValue('maintenance', false)) {
960
-			// For logged-in users: Load everything
961
-			if(\OC::$server->getUserSession()->isLoggedIn()) {
962
-				OC_App::loadApps();
963
-			} else {
964
-				// For guests: Load only filesystem and logging
965
-				OC_App::loadApps(array('filesystem', 'logging'));
966
-				self::handleLogin($request);
967
-			}
968
-		}
969
-
970
-		if (!self::$CLI) {
971
-			try {
972
-				if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
973
-					OC_App::loadApps(array('filesystem', 'logging'));
974
-					OC_App::loadApps();
975
-				}
976
-				OC_Util::setupFS();
977
-				OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
978
-				return;
979
-			} catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
980
-				//header('HTTP/1.0 404 Not Found');
981
-			} catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
982
-				OC_Response::setStatus(405);
983
-				return;
984
-			}
985
-		}
986
-
987
-		// Handle WebDAV
988
-		if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
989
-			// not allowed any more to prevent people
990
-			// mounting this root directly.
991
-			// Users need to mount remote.php/webdav instead.
992
-			header('HTTP/1.1 405 Method Not Allowed');
993
-			header('Status: 405 Method Not Allowed');
994
-			return;
995
-		}
996
-
997
-		// Someone is logged in
998
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
999
-			OC_App::loadApps();
1000
-			OC_User::setupBackends();
1001
-			OC_Util::setupFS();
1002
-			// FIXME
1003
-			// Redirect to default application
1004
-			OC_Util::redirectToDefaultPage();
1005
-		} else {
1006
-			// Not handled and not logged in
1007
-			header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1008
-		}
1009
-	}
1010
-
1011
-	/**
1012
-	 * Check login: apache auth, auth token, basic auth
1013
-	 *
1014
-	 * @param OCP\IRequest $request
1015
-	 * @return boolean
1016
-	 */
1017
-	static function handleLogin(OCP\IRequest $request) {
1018
-		$userSession = self::$server->getUserSession();
1019
-		if (OC_User::handleApacheAuth()) {
1020
-			return true;
1021
-		}
1022
-		if ($userSession->tryTokenLogin($request)) {
1023
-			return true;
1024
-		}
1025
-		if (isset($_COOKIE['nc_username'])
1026
-			&& isset($_COOKIE['nc_token'])
1027
-			&& isset($_COOKIE['nc_session_id'])
1028
-			&& $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1029
-			return true;
1030
-		}
1031
-		if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1032
-			return true;
1033
-		}
1034
-		return false;
1035
-	}
1036
-
1037
-	protected static function handleAuthHeaders() {
1038
-		//copy http auth headers for apache+php-fcgid work around
1039
-		if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1040
-			$_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1041
-		}
1042
-
1043
-		// Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1044
-		$vars = array(
1045
-			'HTTP_AUTHORIZATION', // apache+php-cgi work around
1046
-			'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1047
-		);
1048
-		foreach ($vars as $var) {
1049
-			if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1050
-				list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1051
-				$_SERVER['PHP_AUTH_USER'] = $name;
1052
-				$_SERVER['PHP_AUTH_PW'] = $password;
1053
-				break;
1054
-			}
1055
-		}
1056
-	}
70
+    /**
71
+     * Associative array for autoloading. classname => filename
72
+     */
73
+    public static $CLASSPATH = array();
74
+    /**
75
+     * The installation path for Nextcloud  on the server (e.g. /srv/http/nextcloud)
76
+     */
77
+    public static $SERVERROOT = '';
78
+    /**
79
+     * the current request path relative to the Nextcloud root (e.g. files/index.php)
80
+     */
81
+    private static $SUBURI = '';
82
+    /**
83
+     * the Nextcloud root path for http requests (e.g. nextcloud/)
84
+     */
85
+    public static $WEBROOT = '';
86
+    /**
87
+     * The installation path array of the apps folder on the server (e.g. /srv/http/nextcloud) 'path' and
88
+     * web path in 'url'
89
+     */
90
+    public static $APPSROOTS = array();
91
+
92
+    /**
93
+     * @var string
94
+     */
95
+    public static $configDir;
96
+
97
+    /**
98
+     * requested app
99
+     */
100
+    public static $REQUESTEDAPP = '';
101
+
102
+    /**
103
+     * check if Nextcloud runs in cli mode
104
+     */
105
+    public static $CLI = false;
106
+
107
+    /**
108
+     * @var \OC\Autoloader $loader
109
+     */
110
+    public static $loader = null;
111
+
112
+    /** @var \Composer\Autoload\ClassLoader $composerAutoloader */
113
+    public static $composerAutoloader = null;
114
+
115
+    /**
116
+     * @var \OC\Server
117
+     */
118
+    public static $server = null;
119
+
120
+    /**
121
+     * @var \OC\Config
122
+     */
123
+    private static $config = null;
124
+
125
+    /**
126
+     * @throws \RuntimeException when the 3rdparty directory is missing or
127
+     * the app path list is empty or contains an invalid path
128
+     */
129
+    public static function initPaths() {
130
+        if(defined('PHPUNIT_CONFIG_DIR')) {
131
+            self::$configDir = OC::$SERVERROOT . '/' . PHPUNIT_CONFIG_DIR . '/';
132
+        } elseif(defined('PHPUNIT_RUN') and PHPUNIT_RUN and is_dir(OC::$SERVERROOT . '/tests/config/')) {
133
+            self::$configDir = OC::$SERVERROOT . '/tests/config/';
134
+        } elseif($dir = getenv('NEXTCLOUD_CONFIG_DIR')) {
135
+            self::$configDir = rtrim($dir, '/') . '/';
136
+        } else {
137
+            self::$configDir = OC::$SERVERROOT . '/config/';
138
+        }
139
+        self::$config = new \OC\Config(self::$configDir);
140
+
141
+        OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
142
+        /**
143
+         * FIXME: The following lines are required because we can't yet instantiate
144
+         *        \OC::$server->getRequest() since \OC::$server does not yet exist.
145
+         */
146
+        $params = [
147
+            'server' => [
148
+                'SCRIPT_NAME' => $_SERVER['SCRIPT_NAME'],
149
+                'SCRIPT_FILENAME' => $_SERVER['SCRIPT_FILENAME'],
150
+            ],
151
+        ];
152
+        $fakeRequest = new \OC\AppFramework\Http\Request($params, null, new \OC\AllConfig(new \OC\SystemConfig(self::$config)));
153
+        $scriptName = $fakeRequest->getScriptName();
154
+        if (substr($scriptName, -1) == '/') {
155
+            $scriptName .= 'index.php';
156
+            //make sure suburi follows the same rules as scriptName
157
+            if (substr(OC::$SUBURI, -9) != 'index.php') {
158
+                if (substr(OC::$SUBURI, -1) != '/') {
159
+                    OC::$SUBURI = OC::$SUBURI . '/';
160
+                }
161
+                OC::$SUBURI = OC::$SUBURI . 'index.php';
162
+            }
163
+        }
164
+
165
+
166
+        if (OC::$CLI) {
167
+            OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
168
+        } else {
169
+            if (substr($scriptName, 0 - strlen(OC::$SUBURI)) === OC::$SUBURI) {
170
+                OC::$WEBROOT = substr($scriptName, 0, 0 - strlen(OC::$SUBURI));
171
+
172
+                if (OC::$WEBROOT != '' && OC::$WEBROOT[0] !== '/') {
173
+                    OC::$WEBROOT = '/' . OC::$WEBROOT;
174
+                }
175
+            } else {
176
+                // The scriptName is not ending with OC::$SUBURI
177
+                // This most likely means that we are calling from CLI.
178
+                // However some cron jobs still need to generate
179
+                // a web URL, so we use overwritewebroot as a fallback.
180
+                OC::$WEBROOT = self::$config->getValue('overwritewebroot', '');
181
+            }
182
+
183
+            // Resolve /nextcloud to /nextcloud/ to ensure to always have a trailing
184
+            // slash which is required by URL generation.
185
+            if (isset($_SERVER['REQUEST_URI']) && $_SERVER['REQUEST_URI'] === \OC::$WEBROOT &&
186
+                    substr($_SERVER['REQUEST_URI'], -1) !== '/') {
187
+                header('Location: '.\OC::$WEBROOT.'/');
188
+                exit();
189
+            }
190
+        }
191
+
192
+        // search the apps folder
193
+        $config_paths = self::$config->getValue('apps_paths', array());
194
+        if (!empty($config_paths)) {
195
+            foreach ($config_paths as $paths) {
196
+                if (isset($paths['url']) && isset($paths['path'])) {
197
+                    $paths['url'] = rtrim($paths['url'], '/');
198
+                    $paths['path'] = rtrim($paths['path'], '/');
199
+                    OC::$APPSROOTS[] = $paths;
200
+                }
201
+            }
202
+        } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
203
+            OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
204
+        } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
205
+            OC::$APPSROOTS[] = array(
206
+                'path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps',
207
+                'url' => '/apps',
208
+                'writable' => true
209
+            );
210
+        }
211
+
212
+        if (empty(OC::$APPSROOTS)) {
213
+            throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
214
+                . ' or the folder above. You can also configure the location in the config.php file.');
215
+        }
216
+        $paths = array();
217
+        foreach (OC::$APPSROOTS as $path) {
218
+            $paths[] = $path['path'];
219
+            if (!is_dir($path['path'])) {
220
+                throw new \RuntimeException(sprintf('App directory "%s" not found! Please put the Nextcloud apps folder in the'
221
+                    . ' Nextcloud folder or the folder above. You can also configure the location in the'
222
+                    . ' config.php file.', $path['path']));
223
+            }
224
+        }
225
+
226
+        // set the right include path
227
+        set_include_path(
228
+            implode(PATH_SEPARATOR, $paths)
229
+        );
230
+    }
231
+
232
+    public static function checkConfig() {
233
+        $l = \OC::$server->getL10N('lib');
234
+
235
+        // Create config if it does not already exist
236
+        $configFilePath = self::$configDir .'/config.php';
237
+        if(!file_exists($configFilePath)) {
238
+            @touch($configFilePath);
239
+        }
240
+
241
+        // Check if config is writable
242
+        $configFileWritable = is_writable($configFilePath);
243
+        if (!$configFileWritable && !OC_Helper::isReadOnlyConfigEnabled()
244
+            || !$configFileWritable && \OCP\Util::needUpgrade()) {
245
+
246
+            $urlGenerator = \OC::$server->getURLGenerator();
247
+
248
+            if (self::$CLI) {
249
+                echo $l->t('Cannot write into "config" directory!')."\n";
250
+                echo $l->t('This can usually be fixed by giving the webserver write access to the config directory')."\n";
251
+                echo "\n";
252
+                echo $l->t('See %s', [ $urlGenerator->linkToDocs('admin-dir_permissions') ])."\n";
253
+                exit;
254
+            } else {
255
+                OC_Template::printErrorPage(
256
+                    $l->t('Cannot write into "config" directory!'),
257
+                    $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
258
+                        [ $urlGenerator->linkToDocs('admin-dir_permissions') ])
259
+                );
260
+            }
261
+        }
262
+    }
263
+
264
+    public static function checkInstalled() {
265
+        if (defined('OC_CONSOLE')) {
266
+            return;
267
+        }
268
+        // Redirect to installer if not installed
269
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false) && OC::$SUBURI !== '/index.php' && OC::$SUBURI !== '/status.php') {
270
+            if (OC::$CLI) {
271
+                throw new Exception('Not installed');
272
+            } else {
273
+                $url = OC::$WEBROOT . '/index.php';
274
+                header('Location: ' . $url);
275
+            }
276
+            exit();
277
+        }
278
+    }
279
+
280
+    public static function checkMaintenanceMode() {
281
+        // Allow ajax update script to execute without being stopped
282
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
283
+            // send http status 503
284
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
285
+            header('Status: 503 Service Temporarily Unavailable');
286
+            header('Retry-After: 120');
287
+
288
+            // render error page
289
+            $template = new OC_Template('', 'update.user', 'guest');
290
+            OC_Util::addScript('maintenance-check');
291
+            OC_Util::addStyle('core', 'guest');
292
+            $template->printPage();
293
+            die();
294
+        }
295
+    }
296
+
297
+    /**
298
+     * Prints the upgrade page
299
+     *
300
+     * @param \OC\SystemConfig $systemConfig
301
+     */
302
+    private static function printUpgradePage(\OC\SystemConfig $systemConfig) {
303
+        $disableWebUpdater = $systemConfig->getValue('upgrade.disable-web', false);
304
+        $tooBig = false;
305
+        if (!$disableWebUpdater) {
306
+            $apps = \OC::$server->getAppManager();
307
+            if ($apps->isInstalled('user_ldap')) {
308
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
309
+
310
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
311
+                    ->from('ldap_user_mapping')
312
+                    ->execute();
313
+                $row = $result->fetch();
314
+                $result->closeCursor();
315
+
316
+                $tooBig = ($row['user_count'] > 50);
317
+            }
318
+            if (!$tooBig && $apps->isInstalled('user_saml')) {
319
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
320
+
321
+                $result = $qb->selectAlias($qb->createFunction('COUNT(*)'), 'user_count')
322
+                    ->from('user_saml_users')
323
+                    ->execute();
324
+                $row = $result->fetch();
325
+                $result->closeCursor();
326
+
327
+                $tooBig = ($row['user_count'] > 50);
328
+            }
329
+            if (!$tooBig) {
330
+                // count users
331
+                $stats = \OC::$server->getUserManager()->countUsers();
332
+                $totalUsers = array_sum($stats);
333
+                $tooBig = ($totalUsers > 50);
334
+            }
335
+        }
336
+        $ignoreTooBigWarning = isset($_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup']) &&
337
+            $_GET['IKnowThatThisIsABigInstanceAndTheUpdateRequestCouldRunIntoATimeoutAndHowToRestoreABackup'] === 'IAmSuperSureToDoThis';
338
+
339
+        if ($disableWebUpdater || ($tooBig && !$ignoreTooBigWarning)) {
340
+            // send http status 503
341
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
342
+            header('Status: 503 Service Temporarily Unavailable');
343
+            header('Retry-After: 120');
344
+
345
+            // render error page
346
+            $template = new OC_Template('', 'update.use-cli', 'guest');
347
+            $template->assign('productName', 'nextcloud'); // for now
348
+            $template->assign('version', OC_Util::getVersionString());
349
+            $template->assign('tooBig', $tooBig);
350
+
351
+            $template->printPage();
352
+            die();
353
+        }
354
+
355
+        // check whether this is a core update or apps update
356
+        $installedVersion = $systemConfig->getValue('version', '0.0.0');
357
+        $currentVersion = implode('.', \OCP\Util::getVersion());
358
+
359
+        // if not a core upgrade, then it's apps upgrade
360
+        $isAppsOnlyUpgrade = version_compare($currentVersion, $installedVersion, '=');
361
+
362
+        $oldTheme = $systemConfig->getValue('theme');
363
+        $systemConfig->setValue('theme', '');
364
+        OC_Util::addScript('config'); // needed for web root
365
+        OC_Util::addScript('update');
366
+
367
+        /** @var \OC\App\AppManager $appManager */
368
+        $appManager = \OC::$server->getAppManager();
369
+
370
+        $tmpl = new OC_Template('', 'update.admin', 'guest');
371
+        $tmpl->assign('version', OC_Util::getVersionString());
372
+        $tmpl->assign('isAppsOnlyUpgrade', $isAppsOnlyUpgrade);
373
+
374
+        // get third party apps
375
+        $ocVersion = \OCP\Util::getVersion();
376
+        $incompatibleApps = $appManager->getIncompatibleApps($ocVersion);
377
+        $incompatibleShippedApps = [];
378
+        foreach ($incompatibleApps as $appInfo) {
379
+            if ($appManager->isShipped($appInfo['id'])) {
380
+                $incompatibleShippedApps[] = $appInfo['name'] . ' (' . $appInfo['id'] . ')';
381
+            }
382
+        }
383
+
384
+        if (!empty($incompatibleShippedApps)) {
385
+            $l = \OC::$server->getL10N('core');
386
+            $hint = $l->t('The files of the app %$1s were not replaced correctly. Make sure it is a version compatible with the server.', [implode(', ', $incompatibleShippedApps)]);
387
+            throw new \OC\HintException('The files of the app ' . implode(', ', $incompatibleShippedApps) . ' were not replaced correctly. Make sure it is a version compatible with the server.', $hint);
388
+        }
389
+
390
+        $tmpl->assign('appsToUpgrade', $appManager->getAppsNeedingUpgrade($ocVersion));
391
+        $tmpl->assign('incompatibleAppsList', $incompatibleApps);
392
+        $tmpl->assign('productName', 'Nextcloud'); // for now
393
+        $tmpl->assign('oldTheme', $oldTheme);
394
+        $tmpl->printPage();
395
+    }
396
+
397
+    public static function initSession() {
398
+        if(self::$server->getRequest()->getServerProtocol() === 'https') {
399
+            ini_set('session.cookie_secure', true);
400
+        }
401
+
402
+        // prevents javascript from accessing php session cookies
403
+        ini_set('session.cookie_httponly', 'true');
404
+
405
+        // set the cookie path to the Nextcloud directory
406
+        $cookie_path = OC::$WEBROOT ? : '/';
407
+        ini_set('session.cookie_path', $cookie_path);
408
+
409
+        // Let the session name be changed in the initSession Hook
410
+        $sessionName = OC_Util::getInstanceId();
411
+
412
+        try {
413
+            // Allow session apps to create a custom session object
414
+            $useCustomSession = false;
415
+            $session = self::$server->getSession();
416
+            OC_Hook::emit('OC', 'initSession', array('session' => &$session, 'sessionName' => &$sessionName, 'useCustomSession' => &$useCustomSession));
417
+            if (!$useCustomSession) {
418
+                // set the session name to the instance id - which is unique
419
+                $session = new \OC\Session\Internal($sessionName);
420
+            }
421
+
422
+            $cryptoWrapper = \OC::$server->getSessionCryptoWrapper();
423
+            $session = $cryptoWrapper->wrapSession($session);
424
+            self::$server->setSession($session);
425
+
426
+            // if session can't be started break with http 500 error
427
+        } catch (Exception $e) {
428
+            \OCP\Util::logException('base', $e);
429
+            //show the user a detailed error page
430
+            OC_Response::setStatus(OC_Response::STATUS_INTERNAL_SERVER_ERROR);
431
+            OC_Template::printExceptionErrorPage($e);
432
+            die();
433
+        }
434
+
435
+        $sessionLifeTime = self::getSessionLifeTime();
436
+
437
+        // session timeout
438
+        if ($session->exists('LAST_ACTIVITY') && (time() - $session->get('LAST_ACTIVITY') > $sessionLifeTime)) {
439
+            if (isset($_COOKIE[session_name()])) {
440
+                setcookie(session_name(), null, -1, self::$WEBROOT ? : '/');
441
+            }
442
+            \OC::$server->getUserSession()->logout();
443
+        }
444
+
445
+        $session->set('LAST_ACTIVITY', time());
446
+    }
447
+
448
+    /**
449
+     * @return string
450
+     */
451
+    private static function getSessionLifeTime() {
452
+        return \OC::$server->getConfig()->getSystemValue('session_lifetime', 60 * 60 * 24);
453
+    }
454
+
455
+    public static function loadAppClassPaths() {
456
+        foreach (OC_App::getEnabledApps() as $app) {
457
+            $appPath = OC_App::getAppPath($app);
458
+            if ($appPath === false) {
459
+                continue;
460
+            }
461
+
462
+            $file = $appPath . '/appinfo/classpath.php';
463
+            if (file_exists($file)) {
464
+                require_once $file;
465
+            }
466
+        }
467
+    }
468
+
469
+    /**
470
+     * Try to set some values to the required Nextcloud default
471
+     */
472
+    public static function setRequiredIniValues() {
473
+        @ini_set('default_charset', 'UTF-8');
474
+        @ini_set('gd.jpeg_ignore_warning', '1');
475
+    }
476
+
477
+    /**
478
+     * Send the same site cookies
479
+     */
480
+    private static function sendSameSiteCookies() {
481
+        $cookieParams = session_get_cookie_params();
482
+        $secureCookie = ($cookieParams['secure'] === true) ? 'secure; ' : '';
483
+        $policies = [
484
+            'lax',
485
+            'strict',
486
+        ];
487
+
488
+        // Append __Host to the cookie if it meets the requirements
489
+        $cookiePrefix = '';
490
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
491
+            $cookiePrefix = '__Host-';
492
+        }
493
+
494
+        foreach($policies as $policy) {
495
+            header(
496
+                sprintf(
497
+                    'Set-Cookie: %snc_sameSiteCookie%s=true; path=%s; httponly;' . $secureCookie . 'expires=Fri, 31-Dec-2100 23:59:59 GMT; SameSite=%s',
498
+                    $cookiePrefix,
499
+                    $policy,
500
+                    $cookieParams['path'],
501
+                    $policy
502
+                ),
503
+                false
504
+            );
505
+        }
506
+    }
507
+
508
+    /**
509
+     * Same Site cookie to further mitigate CSRF attacks. This cookie has to
510
+     * be set in every request if cookies are sent to add a second level of
511
+     * defense against CSRF.
512
+     *
513
+     * If the cookie is not sent this will set the cookie and reload the page.
514
+     * We use an additional cookie since we want to protect logout CSRF and
515
+     * also we can't directly interfere with PHP's session mechanism.
516
+     */
517
+    private static function performSameSiteCookieProtection() {
518
+        $request = \OC::$server->getRequest();
519
+
520
+        // Some user agents are notorious and don't really properly follow HTTP
521
+        // specifications. For those, have an automated opt-out. Since the protection
522
+        // for remote.php is applied in base.php as starting point we need to opt out
523
+        // here.
524
+        $incompatibleUserAgents = [
525
+            // OS X Finder
526
+            '/^WebDAVFS/',
527
+        ];
528
+        if($request->isUserAgent($incompatibleUserAgents)) {
529
+            return;
530
+        }
531
+
532
+        if(count($_COOKIE) > 0) {
533
+            $requestUri = $request->getScriptName();
534
+            $processingScript = explode('/', $requestUri);
535
+            $processingScript = $processingScript[count($processingScript)-1];
536
+
537
+            // index.php routes are handled in the middleware
538
+            if($processingScript === 'index.php') {
539
+                return;
540
+            }
541
+
542
+            // All other endpoints require the lax and the strict cookie
543
+            if(!$request->passesStrictCookieCheck()) {
544
+                self::sendSameSiteCookies();
545
+                // Debug mode gets access to the resources without strict cookie
546
+                // due to the fact that the SabreDAV browser also lives there.
547
+                if(!\OC::$server->getConfig()->getSystemValue('debug', false)) {
548
+                    http_response_code(\OCP\AppFramework\Http::STATUS_SERVICE_UNAVAILABLE);
549
+                    exit();
550
+                }
551
+            }
552
+        } elseif(!isset($_COOKIE['nc_sameSiteCookielax']) || !isset($_COOKIE['nc_sameSiteCookiestrict'])) {
553
+            self::sendSameSiteCookies();
554
+        }
555
+    }
556
+
557
+    public static function init() {
558
+        // calculate the root directories
559
+        OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
560
+
561
+        // register autoloader
562
+        $loaderStart = microtime(true);
563
+        require_once __DIR__ . '/autoloader.php';
564
+        self::$loader = new \OC\Autoloader([
565
+            OC::$SERVERROOT . '/lib/private/legacy',
566
+        ]);
567
+        if (defined('PHPUNIT_RUN')) {
568
+            self::$loader->addValidRoot(OC::$SERVERROOT . '/tests');
569
+        }
570
+        spl_autoload_register(array(self::$loader, 'load'));
571
+        $loaderEnd = microtime(true);
572
+
573
+        self::$CLI = (php_sapi_name() == 'cli');
574
+
575
+        // Add default composer PSR-4 autoloader
576
+        self::$composerAutoloader = require_once OC::$SERVERROOT . '/lib/composer/autoload.php';
577
+
578
+        try {
579
+            self::initPaths();
580
+            // setup 3rdparty autoloader
581
+            $vendorAutoLoad = OC::$SERVERROOT. '/3rdparty/autoload.php';
582
+            if (!file_exists($vendorAutoLoad)) {
583
+                throw new \RuntimeException('Composer autoloader not found, unable to continue. Check the folder "3rdparty". Running "git submodule update --init" will initialize the git submodule that handles the subfolder "3rdparty".');
584
+            }
585
+            require_once $vendorAutoLoad;
586
+
587
+        } catch (\RuntimeException $e) {
588
+            if (!self::$CLI) {
589
+                $claimedProtocol = strtoupper($_SERVER['SERVER_PROTOCOL']);
590
+                $protocol = in_array($claimedProtocol, ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2']) ? $claimedProtocol : 'HTTP/1.1';
591
+                header($protocol . ' ' . OC_Response::STATUS_SERVICE_UNAVAILABLE);
592
+            }
593
+            // we can't use the template error page here, because this needs the
594
+            // DI container which isn't available yet
595
+            print($e->getMessage());
596
+            exit();
597
+        }
598
+
599
+        // setup the basic server
600
+        self::$server = new \OC\Server(\OC::$WEBROOT, self::$config);
601
+        \OC::$server->getEventLogger()->log('autoloader', 'Autoloader', $loaderStart, $loaderEnd);
602
+        \OC::$server->getEventLogger()->start('boot', 'Initialize');
603
+
604
+        // Don't display errors and log them
605
+        error_reporting(E_ALL | E_STRICT);
606
+        @ini_set('display_errors', '0');
607
+        @ini_set('log_errors', '1');
608
+
609
+        if(!date_default_timezone_set('UTC')) {
610
+            throw new \RuntimeException('Could not set timezone to UTC');
611
+        }
612
+
613
+        //try to configure php to enable big file uploads.
614
+        //this doesn´t work always depending on the webserver and php configuration.
615
+        //Let´s try to overwrite some defaults anyway
616
+
617
+        //try to set the maximum execution time to 60min
618
+        if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) {
619
+            @set_time_limit(3600);
620
+        }
621
+        @ini_set('max_execution_time', '3600');
622
+        @ini_set('max_input_time', '3600');
623
+
624
+        //try to set the maximum filesize to 10G
625
+        @ini_set('upload_max_filesize', '10G');
626
+        @ini_set('post_max_size', '10G');
627
+        @ini_set('file_uploads', '50');
628
+
629
+        self::setRequiredIniValues();
630
+        self::handleAuthHeaders();
631
+        self::registerAutoloaderCache();
632
+
633
+        // initialize intl fallback is necessary
634
+        \Patchwork\Utf8\Bootup::initIntl();
635
+        OC_Util::isSetLocaleWorking();
636
+
637
+        if (!defined('PHPUNIT_RUN')) {
638
+            OC\Log\ErrorHandler::setLogger(\OC::$server->getLogger());
639
+            $debug = \OC::$server->getConfig()->getSystemValue('debug', false);
640
+            OC\Log\ErrorHandler::register($debug);
641
+        }
642
+
643
+        \OC::$server->getEventLogger()->start('init_session', 'Initialize session');
644
+        OC_App::loadApps(array('session'));
645
+        if (!self::$CLI) {
646
+            self::initSession();
647
+        }
648
+        \OC::$server->getEventLogger()->end('init_session');
649
+        self::checkConfig();
650
+        self::checkInstalled();
651
+
652
+        OC_Response::addSecurityHeaders();
653
+
654
+        self::performSameSiteCookieProtection();
655
+
656
+        if (!defined('OC_CONSOLE')) {
657
+            $errors = OC_Util::checkServer(\OC::$server->getSystemConfig());
658
+            if (count($errors) > 0) {
659
+                if (self::$CLI) {
660
+                    // Convert l10n string into regular string for usage in database
661
+                    $staticErrors = [];
662
+                    foreach ($errors as $error) {
663
+                        echo $error['error'] . "\n";
664
+                        echo $error['hint'] . "\n\n";
665
+                        $staticErrors[] = [
666
+                            'error' => (string)$error['error'],
667
+                            'hint' => (string)$error['hint'],
668
+                        ];
669
+                    }
670
+
671
+                    try {
672
+                        \OC::$server->getConfig()->setAppValue('core', 'cronErrors', json_encode($staticErrors));
673
+                    } catch (\Exception $e) {
674
+                        echo('Writing to database failed');
675
+                    }
676
+                    exit(1);
677
+                } else {
678
+                    OC_Response::setStatus(OC_Response::STATUS_SERVICE_UNAVAILABLE);
679
+                    OC_Util::addStyle('guest');
680
+                    OC_Template::printGuestPage('', 'error', array('errors' => $errors));
681
+                    exit;
682
+                }
683
+            } elseif (self::$CLI && \OC::$server->getConfig()->getSystemValue('installed', false)) {
684
+                \OC::$server->getConfig()->deleteAppValue('core', 'cronErrors');
685
+            }
686
+        }
687
+        //try to set the session lifetime
688
+        $sessionLifeTime = self::getSessionLifeTime();
689
+        @ini_set('gc_maxlifetime', (string)$sessionLifeTime);
690
+
691
+        $systemConfig = \OC::$server->getSystemConfig();
692
+
693
+        // User and Groups
694
+        if (!$systemConfig->getValue("installed", false)) {
695
+            self::$server->getSession()->set('user_id', '');
696
+        }
697
+
698
+        OC_User::useBackend(new \OC\User\Database());
699
+        \OC::$server->getGroupManager()->addBackend(new \OC\Group\Database());
700
+
701
+        // Subscribe to the hook
702
+        \OCP\Util::connectHook(
703
+            '\OCA\Files_Sharing\API\Server2Server',
704
+            'preLoginNameUsedAsUserName',
705
+            '\OC\User\Database',
706
+            'preLoginNameUsedAsUserName'
707
+        );
708
+
709
+        //setup extra user backends
710
+        if (!\OCP\Util::needUpgrade()) {
711
+            OC_User::setupBackends();
712
+        } else {
713
+            // Run upgrades in incognito mode
714
+            OC_User::setIncognitoMode(true);
715
+        }
716
+
717
+        self::registerCleanupHooks();
718
+        self::registerFilesystemHooks();
719
+        self::registerShareHooks();
720
+        self::registerEncryptionWrapper();
721
+        self::registerEncryptionHooks();
722
+        self::registerAccountHooks();
723
+
724
+        $settings = new \OC\Settings\Application();
725
+        $settings->register();
726
+
727
+        //make sure temporary files are cleaned up
728
+        $tmpManager = \OC::$server->getTempManager();
729
+        register_shutdown_function(array($tmpManager, 'clean'));
730
+        $lockProvider = \OC::$server->getLockingProvider();
731
+        register_shutdown_function(array($lockProvider, 'releaseAll'));
732
+
733
+        // Check whether the sample configuration has been copied
734
+        if($systemConfig->getValue('copied_sample_config', false)) {
735
+            $l = \OC::$server->getL10N('lib');
736
+            header('HTTP/1.1 503 Service Temporarily Unavailable');
737
+            header('Status: 503 Service Temporarily Unavailable');
738
+            OC_Template::printErrorPage(
739
+                $l->t('Sample configuration detected'),
740
+                $l->t('It has been detected that the sample configuration has been copied. This can break your installation and is unsupported. Please read the documentation before performing changes on config.php')
741
+            );
742
+            return;
743
+        }
744
+
745
+        $request = \OC::$server->getRequest();
746
+        $host = $request->getInsecureServerHost();
747
+        /**
748
+         * if the host passed in headers isn't trusted
749
+         * FIXME: Should not be in here at all :see_no_evil:
750
+         */
751
+        if (!OC::$CLI
752
+            // overwritehost is always trusted, workaround to not have to make
753
+            // \OC\AppFramework\Http\Request::getOverwriteHost public
754
+            && self::$server->getConfig()->getSystemValue('overwritehost') === ''
755
+            && !\OC::$server->getTrustedDomainHelper()->isTrustedDomain($host)
756
+            && self::$server->getConfig()->getSystemValue('installed', false)
757
+        ) {
758
+            // Allow access to CSS resources
759
+            $isScssRequest = false;
760
+            if(strpos($request->getPathInfo(), '/css/') === 0) {
761
+                $isScssRequest = true;
762
+            }
763
+
764
+            if(substr($request->getRequestUri(), -11) === '/status.php') {
765
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
766
+                header('Status: 400 Bad Request');
767
+                header('Content-Type: application/json');
768
+                echo '{"error": "Trusted domain error.", "code": 15}';
769
+                exit();
770
+            }
771
+
772
+            if (!$isScssRequest) {
773
+                OC_Response::setStatus(\OC_Response::STATUS_BAD_REQUEST);
774
+                header('Status: 400 Bad Request');
775
+
776
+                \OC::$server->getLogger()->warning(
777
+                    'Trusted domain error. "{remoteAddress}" tried to access using "{host}" as host.',
778
+                    [
779
+                        'app' => 'core',
780
+                        'remoteAddress' => $request->getRemoteAddress(),
781
+                        'host' => $host,
782
+                    ]
783
+                );
784
+
785
+                $tmpl = new OCP\Template('core', 'untrustedDomain', 'guest');
786
+                $tmpl->assign('domain', $host);
787
+                $tmpl->printPage();
788
+
789
+                exit();
790
+            }
791
+        }
792
+        \OC::$server->getEventLogger()->end('boot');
793
+    }
794
+
795
+    /**
796
+     * register hooks for the cleanup of cache and bruteforce protection
797
+     */
798
+    public static function registerCleanupHooks() {
799
+        //don't try to do this before we are properly setup
800
+        if (\OC::$server->getSystemConfig()->getValue('installed', false) && !\OCP\Util::needUpgrade()) {
801
+
802
+            // NOTE: This will be replaced to use OCP
803
+            $userSession = self::$server->getUserSession();
804
+            $userSession->listen('\OC\User', 'postLogin', function () use ($userSession) {
805
+                if (!defined('PHPUNIT_RUN')) {
806
+                    // reset brute force delay for this IP address and username
807
+                    $uid = \OC::$server->getUserSession()->getUser()->getUID();
808
+                    $request = \OC::$server->getRequest();
809
+                    $throttler = \OC::$server->getBruteForceThrottler();
810
+                    $throttler->resetDelay($request->getRemoteAddress(), 'login', ['user' => $uid]);
811
+                }
812
+
813
+                try {
814
+                    $cache = new \OC\Cache\File();
815
+                    $cache->gc();
816
+                } catch (\OC\ServerNotAvailableException $e) {
817
+                    // not a GC exception, pass it on
818
+                    throw $e;
819
+                } catch (\OC\ForbiddenException $e) {
820
+                    // filesystem blocked for this request, ignore
821
+                } catch (\Exception $e) {
822
+                    // a GC exception should not prevent users from using OC,
823
+                    // so log the exception
824
+                    \OC::$server->getLogger()->logException($e, [
825
+                        'message' => 'Exception when running cache gc.',
826
+                        'level' => \OCP\Util::WARN,
827
+                        'app' => 'core',
828
+                    ]);
829
+                }
830
+            });
831
+        }
832
+    }
833
+
834
+    private static function registerEncryptionWrapper() {
835
+        $manager = self::$server->getEncryptionManager();
836
+        \OCP\Util::connectHook('OC_Filesystem', 'preSetup', $manager, 'setupStorage');
837
+    }
838
+
839
+    private static function registerEncryptionHooks() {
840
+        $enabled = self::$server->getEncryptionManager()->isEnabled();
841
+        if ($enabled) {
842
+            \OCP\Util::connectHook(Share::class, 'post_shared', HookManager::class, 'postShared');
843
+            \OCP\Util::connectHook(Share::class, 'post_unshare', HookManager::class, 'postUnshared');
844
+            \OCP\Util::connectHook('OC_Filesystem', 'post_rename', HookManager::class, 'postRename');
845
+            \OCP\Util::connectHook('\OCA\Files_Trashbin\Trashbin', 'post_restore', HookManager::class, 'postRestore');
846
+        }
847
+    }
848
+
849
+    private static function registerAccountHooks() {
850
+        $hookHandler = new \OC\Accounts\Hooks(\OC::$server->getLogger());
851
+        \OCP\Util::connectHook('OC_User', 'changeUser', $hookHandler, 'changeUserHook');
852
+    }
853
+
854
+    /**
855
+     * register hooks for the filesystem
856
+     */
857
+    public static function registerFilesystemHooks() {
858
+        // Check for blacklisted files
859
+        OC_Hook::connect('OC_Filesystem', 'write', Filesystem::class, 'isBlacklisted');
860
+        OC_Hook::connect('OC_Filesystem', 'rename', Filesystem::class, 'isBlacklisted');
861
+    }
862
+
863
+    /**
864
+     * register hooks for sharing
865
+     */
866
+    public static function registerShareHooks() {
867
+        if (\OC::$server->getSystemConfig()->getValue('installed')) {
868
+            OC_Hook::connect('OC_User', 'post_deleteUser', Hooks::class, 'post_deleteUser');
869
+            OC_Hook::connect('OC_User', 'post_removeFromGroup', Hooks::class, 'post_removeFromGroup');
870
+            OC_Hook::connect('OC_User', 'post_deleteGroup', Hooks::class, 'post_deleteGroup');
871
+        }
872
+    }
873
+
874
+    protected static function registerAutoloaderCache() {
875
+        // The class loader takes an optional low-latency cache, which MUST be
876
+        // namespaced. The instanceid is used for namespacing, but might be
877
+        // unavailable at this point. Furthermore, it might not be possible to
878
+        // generate an instanceid via \OC_Util::getInstanceId() because the
879
+        // config file may not be writable. As such, we only register a class
880
+        // loader cache if instanceid is available without trying to create one.
881
+        $instanceId = \OC::$server->getSystemConfig()->getValue('instanceid', null);
882
+        if ($instanceId) {
883
+            try {
884
+                $memcacheFactory = \OC::$server->getMemCacheFactory();
885
+                self::$loader->setMemoryCache($memcacheFactory->createLocal('Autoloader'));
886
+            } catch (\Exception $ex) {
887
+            }
888
+        }
889
+    }
890
+
891
+    /**
892
+     * Handle the request
893
+     */
894
+    public static function handleRequest() {
895
+
896
+        \OC::$server->getEventLogger()->start('handle_request', 'Handle request');
897
+        $systemConfig = \OC::$server->getSystemConfig();
898
+        // load all the classpaths from the enabled apps so they are available
899
+        // in the routing files of each app
900
+        OC::loadAppClassPaths();
901
+
902
+        // Check if Nextcloud is installed or in maintenance (update) mode
903
+        if (!$systemConfig->getValue('installed', false)) {
904
+            \OC::$server->getSession()->clear();
905
+            $setupHelper = new OC\Setup(
906
+                $systemConfig,
907
+                \OC::$server->getIniWrapper(),
908
+                \OC::$server->getL10N('lib'),
909
+                \OC::$server->query(\OCP\Defaults::class),
910
+                \OC::$server->getLogger(),
911
+                \OC::$server->getSecureRandom(),
912
+                \OC::$server->query(\OC\Installer::class)
913
+            );
914
+            $controller = new OC\Core\Controller\SetupController($setupHelper);
915
+            $controller->run($_POST);
916
+            exit();
917
+        }
918
+
919
+        $request = \OC::$server->getRequest();
920
+        $requestPath = $request->getRawPathInfo();
921
+        if ($requestPath === '/heartbeat') {
922
+            return;
923
+        }
924
+        if (substr($requestPath, -3) !== '.js') { // we need these files during the upgrade
925
+            self::checkMaintenanceMode();
926
+
927
+            if (\OCP\Util::needUpgrade()) {
928
+                if (function_exists('opcache_reset')) {
929
+                    opcache_reset();
930
+                }
931
+                if (!$systemConfig->getValue('maintenance', false)) {
932
+                    self::printUpgradePage($systemConfig);
933
+                    exit();
934
+                }
935
+            }
936
+        }
937
+
938
+        // emergency app disabling
939
+        if ($requestPath === '/disableapp'
940
+            && $request->getMethod() === 'POST'
941
+            && ((array)$request->getParam('appid')) !== ''
942
+        ) {
943
+            \OCP\JSON::callCheck();
944
+            \OCP\JSON::checkAdminUser();
945
+            $appIds = (array)$request->getParam('appid');
946
+            foreach($appIds as $appId) {
947
+                $appId = \OC_App::cleanAppId($appId);
948
+                \OC_App::disable($appId);
949
+            }
950
+            \OC_JSON::success();
951
+            exit();
952
+        }
953
+
954
+        // Always load authentication apps
955
+        OC_App::loadApps(['authentication']);
956
+
957
+        // Load minimum set of apps
958
+        if (!\OCP\Util::needUpgrade()
959
+            && !$systemConfig->getValue('maintenance', false)) {
960
+            // For logged-in users: Load everything
961
+            if(\OC::$server->getUserSession()->isLoggedIn()) {
962
+                OC_App::loadApps();
963
+            } else {
964
+                // For guests: Load only filesystem and logging
965
+                OC_App::loadApps(array('filesystem', 'logging'));
966
+                self::handleLogin($request);
967
+            }
968
+        }
969
+
970
+        if (!self::$CLI) {
971
+            try {
972
+                if (!$systemConfig->getValue('maintenance', false) && !\OCP\Util::needUpgrade()) {
973
+                    OC_App::loadApps(array('filesystem', 'logging'));
974
+                    OC_App::loadApps();
975
+                }
976
+                OC_Util::setupFS();
977
+                OC::$server->getRouter()->match(\OC::$server->getRequest()->getRawPathInfo());
978
+                return;
979
+            } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
980
+                //header('HTTP/1.0 404 Not Found');
981
+            } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
982
+                OC_Response::setStatus(405);
983
+                return;
984
+            }
985
+        }
986
+
987
+        // Handle WebDAV
988
+        if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') {
989
+            // not allowed any more to prevent people
990
+            // mounting this root directly.
991
+            // Users need to mount remote.php/webdav instead.
992
+            header('HTTP/1.1 405 Method Not Allowed');
993
+            header('Status: 405 Method Not Allowed');
994
+            return;
995
+        }
996
+
997
+        // Someone is logged in
998
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
999
+            OC_App::loadApps();
1000
+            OC_User::setupBackends();
1001
+            OC_Util::setupFS();
1002
+            // FIXME
1003
+            // Redirect to default application
1004
+            OC_Util::redirectToDefaultPage();
1005
+        } else {
1006
+            // Not handled and not logged in
1007
+            header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute('core.login.showLoginForm'));
1008
+        }
1009
+    }
1010
+
1011
+    /**
1012
+     * Check login: apache auth, auth token, basic auth
1013
+     *
1014
+     * @param OCP\IRequest $request
1015
+     * @return boolean
1016
+     */
1017
+    static function handleLogin(OCP\IRequest $request) {
1018
+        $userSession = self::$server->getUserSession();
1019
+        if (OC_User::handleApacheAuth()) {
1020
+            return true;
1021
+        }
1022
+        if ($userSession->tryTokenLogin($request)) {
1023
+            return true;
1024
+        }
1025
+        if (isset($_COOKIE['nc_username'])
1026
+            && isset($_COOKIE['nc_token'])
1027
+            && isset($_COOKIE['nc_session_id'])
1028
+            && $userSession->loginWithCookie($_COOKIE['nc_username'], $_COOKIE['nc_token'], $_COOKIE['nc_session_id'])) {
1029
+            return true;
1030
+        }
1031
+        if ($userSession->tryBasicAuthLogin($request, \OC::$server->getBruteForceThrottler())) {
1032
+            return true;
1033
+        }
1034
+        return false;
1035
+    }
1036
+
1037
+    protected static function handleAuthHeaders() {
1038
+        //copy http auth headers for apache+php-fcgid work around
1039
+        if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
1040
+            $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
1041
+        }
1042
+
1043
+        // Extract PHP_AUTH_USER/PHP_AUTH_PW from other headers if necessary.
1044
+        $vars = array(
1045
+            'HTTP_AUTHORIZATION', // apache+php-cgi work around
1046
+            'REDIRECT_HTTP_AUTHORIZATION', // apache+php-cgi alternative
1047
+        );
1048
+        foreach ($vars as $var) {
1049
+            if (isset($_SERVER[$var]) && preg_match('/Basic\s+(.*)$/i', $_SERVER[$var], $matches)) {
1050
+                list($name, $password) = explode(':', base64_decode($matches[1]), 2);
1051
+                $_SERVER['PHP_AUTH_USER'] = $name;
1052
+                $_SERVER['PHP_AUTH_PW'] = $password;
1053
+                break;
1054
+            }
1055
+        }
1056
+    }
1057 1057
 }
1058 1058
 
1059 1059
 OC::init();
Please login to merge, or discard this patch.
lib/private/legacy/app.php 2 patches
Indentation   +1198 added lines, -1198 removed lines patch added patch discarded remove patch
@@ -63,1202 +63,1202 @@
 block discarded – undo
63 63
  * upgrading and removing apps.
64 64
  */
65 65
 class OC_App {
66
-	static private $appVersion = [];
67
-	static private $adminForms = array();
68
-	static private $personalForms = array();
69
-	static private $appInfo = array();
70
-	static private $appTypes = array();
71
-	static private $loadedApps = array();
72
-	static private $altLogin = array();
73
-	static private $alreadyRegistered = [];
74
-	const officialApp = 200;
75
-
76
-	/**
77
-	 * clean the appId
78
-	 *
79
-	 * @param string|boolean $app AppId that needs to be cleaned
80
-	 * @return string
81
-	 */
82
-	public static function cleanAppId($app) {
83
-		return str_replace(array('\0', '/', '\\', '..'), '', $app);
84
-	}
85
-
86
-	/**
87
-	 * Check if an app is loaded
88
-	 *
89
-	 * @param string $app
90
-	 * @return bool
91
-	 */
92
-	public static function isAppLoaded($app) {
93
-		return in_array($app, self::$loadedApps, true);
94
-	}
95
-
96
-	/**
97
-	 * loads all apps
98
-	 *
99
-	 * @param string[] | string | null $types
100
-	 * @return bool
101
-	 *
102
-	 * This function walks through the ownCloud directory and loads all apps
103
-	 * it can find. A directory contains an app if the file /appinfo/info.xml
104
-	 * exists.
105
-	 *
106
-	 * if $types is set, only apps of those types will be loaded
107
-	 */
108
-	public static function loadApps($types = null) {
109
-		if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
110
-			return false;
111
-		}
112
-		// Load the enabled apps here
113
-		$apps = self::getEnabledApps();
114
-
115
-		// Add each apps' folder as allowed class path
116
-		foreach($apps as $app) {
117
-			$path = self::getAppPath($app);
118
-			if($path !== false) {
119
-				self::registerAutoloading($app, $path);
120
-			}
121
-		}
122
-
123
-		// prevent app.php from printing output
124
-		ob_start();
125
-		foreach ($apps as $app) {
126
-			if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
127
-				self::loadApp($app);
128
-			}
129
-		}
130
-		ob_end_clean();
131
-
132
-		return true;
133
-	}
134
-
135
-	/**
136
-	 * load a single app
137
-	 *
138
-	 * @param string $app
139
-	 */
140
-	public static function loadApp($app) {
141
-		self::$loadedApps[] = $app;
142
-		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
144
-			return;
145
-		}
146
-
147
-		// in case someone calls loadApp() directly
148
-		self::registerAutoloading($app, $appPath);
149
-
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
-			self::requireAppFile($app);
153
-			if (self::isType($app, array('authentication'))) {
154
-				// since authentication apps affect the "is app enabled for group" check,
155
-				// the enabled apps cache needs to be cleared to make sure that the
156
-				// next time getEnableApps() is called it will also include apps that were
157
-				// enabled for groups
158
-				self::$enabledAppsCache = array();
159
-			}
160
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
161
-		}
162
-
163
-		$info = self::getAppInfo($app);
164
-		if (!empty($info['activity']['filters'])) {
165
-			foreach ($info['activity']['filters'] as $filter) {
166
-				\OC::$server->getActivityManager()->registerFilter($filter);
167
-			}
168
-		}
169
-		if (!empty($info['activity']['settings'])) {
170
-			foreach ($info['activity']['settings'] as $setting) {
171
-				\OC::$server->getActivityManager()->registerSetting($setting);
172
-			}
173
-		}
174
-		if (!empty($info['activity']['providers'])) {
175
-			foreach ($info['activity']['providers'] as $provider) {
176
-				\OC::$server->getActivityManager()->registerProvider($provider);
177
-			}
178
-		}
179
-
180
-		if (!empty($info['settings']['admin'])) {
181
-			foreach ($info['settings']['admin'] as $setting) {
182
-				\OC::$server->getSettingsManager()->registerSetting('admin', $setting);
183
-			}
184
-		}
185
-		if (!empty($info['settings']['admin-section'])) {
186
-			foreach ($info['settings']['admin-section'] as $section) {
187
-				\OC::$server->getSettingsManager()->registerSection('admin', $section);
188
-			}
189
-		}
190
-		if (!empty($info['settings']['personal'])) {
191
-			foreach ($info['settings']['personal'] as $setting) {
192
-				\OC::$server->getSettingsManager()->registerSetting('personal', $setting);
193
-			}
194
-		}
195
-		if (!empty($info['settings']['personal-section'])) {
196
-			foreach ($info['settings']['personal-section'] as $section) {
197
-				\OC::$server->getSettingsManager()->registerSection('personal', $section);
198
-			}
199
-		}
200
-
201
-		if (!empty($info['collaboration']['plugins'])) {
202
-			// deal with one or many plugin entries
203
-			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
204
-				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
205
-			foreach ($plugins as $plugin) {
206
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
207
-					$pluginInfo = [
208
-						'shareType' => $plugin['@attributes']['share-type'],
209
-						'class' => $plugin['@value'],
210
-					];
211
-					\OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
212
-				} else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
213
-					\OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
214
-				}
215
-			}
216
-		}
217
-	}
218
-
219
-	/**
220
-	 * @internal
221
-	 * @param string $app
222
-	 * @param string $path
223
-	 */
224
-	public static function registerAutoloading($app, $path) {
225
-		$key = $app . '-' . $path;
226
-		if(isset(self::$alreadyRegistered[$key])) {
227
-			return;
228
-		}
229
-
230
-		self::$alreadyRegistered[$key] = true;
231
-
232
-		// Register on PSR-4 composer autoloader
233
-		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
234
-		\OC::$server->registerNamespace($app, $appNamespace);
235
-
236
-		if (file_exists($path . '/composer/autoload.php')) {
237
-			require_once $path . '/composer/autoload.php';
238
-		} else {
239
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
240
-			// Register on legacy autoloader
241
-			\OC::$loader->addValidRoot($path);
242
-		}
243
-
244
-		// Register Test namespace only when testing
245
-		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
246
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
247
-		}
248
-	}
249
-
250
-	/**
251
-	 * Load app.php from the given app
252
-	 *
253
-	 * @param string $app app name
254
-	 */
255
-	private static function requireAppFile($app) {
256
-		try {
257
-			// encapsulated here to avoid variable scope conflicts
258
-			require_once $app . '/appinfo/app.php';
259
-		} catch (Error $ex) {
260
-			\OC::$server->getLogger()->logException($ex);
261
-			if (!\OC::$server->getAppManager()->isShipped($app)) {
262
-				// Only disable apps which are not shipped
263
-				self::disable($app);
264
-			}
265
-		}
266
-	}
267
-
268
-	/**
269
-	 * check if an app is of a specific type
270
-	 *
271
-	 * @param string $app
272
-	 * @param string|array $types
273
-	 * @return bool
274
-	 */
275
-	public static function isType($app, $types) {
276
-		if (is_string($types)) {
277
-			$types = array($types);
278
-		}
279
-		$appTypes = self::getAppTypes($app);
280
-		foreach ($types as $type) {
281
-			if (array_search($type, $appTypes) !== false) {
282
-				return true;
283
-			}
284
-		}
285
-		return false;
286
-	}
287
-
288
-	/**
289
-	 * get the types of an app
290
-	 *
291
-	 * @param string $app
292
-	 * @return array
293
-	 */
294
-	private static function getAppTypes($app) {
295
-		//load the cache
296
-		if (count(self::$appTypes) == 0) {
297
-			self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
298
-		}
299
-
300
-		if (isset(self::$appTypes[$app])) {
301
-			return explode(',', self::$appTypes[$app]);
302
-		} else {
303
-			return array();
304
-		}
305
-	}
306
-
307
-	/**
308
-	 * read app types from info.xml and cache them in the database
309
-	 */
310
-	public static function setAppTypes($app) {
311
-		$appData = self::getAppInfo($app);
312
-		if(!is_array($appData)) {
313
-			return;
314
-		}
315
-
316
-		if (isset($appData['types'])) {
317
-			$appTypes = implode(',', $appData['types']);
318
-		} else {
319
-			$appTypes = '';
320
-			$appData['types'] = [];
321
-		}
322
-
323
-		\OC::$server->getConfig()->setAppValue($app, 'types', $appTypes);
324
-
325
-		if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
326
-			$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes');
327
-			if ($enabled !== 'yes' && $enabled !== 'no') {
328
-				\OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes');
329
-			}
330
-		}
331
-	}
332
-
333
-	/**
334
-	 * get all enabled apps
335
-	 */
336
-	protected static $enabledAppsCache = array();
337
-
338
-	/**
339
-	 * Returns apps enabled for the current user.
340
-	 *
341
-	 * @param bool $forceRefresh whether to refresh the cache
342
-	 * @param bool $all whether to return apps for all users, not only the
343
-	 * currently logged in one
344
-	 * @return string[]
345
-	 */
346
-	public static function getEnabledApps($forceRefresh = false, $all = false) {
347
-		if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
348
-			return array();
349
-		}
350
-		// in incognito mode or when logged out, $user will be false,
351
-		// which is also the case during an upgrade
352
-		$appManager = \OC::$server->getAppManager();
353
-		if ($all) {
354
-			$user = null;
355
-		} else {
356
-			$user = \OC::$server->getUserSession()->getUser();
357
-		}
358
-
359
-		if (is_null($user)) {
360
-			$apps = $appManager->getInstalledApps();
361
-		} else {
362
-			$apps = $appManager->getEnabledAppsForUser($user);
363
-		}
364
-		$apps = array_filter($apps, function ($app) {
365
-			return $app !== 'files';//we add this manually
366
-		});
367
-		sort($apps);
368
-		array_unshift($apps, 'files');
369
-		return $apps;
370
-	}
371
-
372
-	/**
373
-	 * checks whether or not an app is enabled
374
-	 *
375
-	 * @param string $app app
376
-	 * @return bool
377
-	 * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
378
-	 *
379
-	 * This function checks whether or not an app is enabled.
380
-	 */
381
-	public static function isEnabled($app) {
382
-		return \OC::$server->getAppManager()->isEnabledForUser($app);
383
-	}
384
-
385
-	/**
386
-	 * enables an app
387
-	 *
388
-	 * @param string $appId
389
-	 * @param array $groups (optional) when set, only these groups will have access to the app
390
-	 * @throws \Exception
391
-	 * @return void
392
-	 *
393
-	 * This function set an app as enabled in appconfig.
394
-	 */
395
-	public function enable($appId,
396
-						   $groups = null) {
397
-		self::$enabledAppsCache = []; // flush
398
-
399
-		// Check if app is already downloaded
400
-		$installer = \OC::$server->query(Installer::class);
401
-		$isDownloaded = $installer->isDownloaded($appId);
402
-
403
-		if(!$isDownloaded) {
404
-			$installer->downloadApp($appId);
405
-		}
406
-
407
-		$installer->installApp($appId);
408
-
409
-		$appManager = \OC::$server->getAppManager();
410
-		if (!is_null($groups)) {
411
-			$groupManager = \OC::$server->getGroupManager();
412
-			$groupsList = [];
413
-			foreach ($groups as $group) {
414
-				$groupItem = $groupManager->get($group);
415
-				if ($groupItem instanceof \OCP\IGroup) {
416
-					$groupsList[] = $groupManager->get($group);
417
-				}
418
-			}
419
-			$appManager->enableAppForGroups($appId, $groupsList);
420
-		} else {
421
-			$appManager->enableApp($appId);
422
-		}
423
-	}
424
-
425
-	/**
426
-	 * @param string $app
427
-	 * @return bool
428
-	 */
429
-	public static function removeApp($app) {
430
-		if (\OC::$server->getAppManager()->isShipped($app)) {
431
-			return false;
432
-		}
433
-
434
-		$installer = \OC::$server->query(Installer::class);
435
-		return $installer->removeApp($app);
436
-	}
437
-
438
-	/**
439
-	 * This function set an app as disabled in appconfig.
440
-	 *
441
-	 * @param string $app app
442
-	 * @throws Exception
443
-	 */
444
-	public static function disable($app) {
445
-		// flush
446
-		self::$enabledAppsCache = array();
447
-
448
-		// run uninstall steps
449
-		$appData = OC_App::getAppInfo($app);
450
-		if (!is_null($appData)) {
451
-			OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
452
-		}
453
-
454
-		// emit disable hook - needed anymore ?
455
-		\OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
456
-
457
-		// finally disable it
458
-		$appManager = \OC::$server->getAppManager();
459
-		$appManager->disableApp($app);
460
-	}
461
-
462
-	// This is private as well. It simply works, so don't ask for more details
463
-	private static function proceedNavigation($list) {
464
-		usort($list, function($a, $b) {
465
-			if (isset($a['order']) && isset($b['order'])) {
466
-				return ($a['order'] < $b['order']) ? -1 : 1;
467
-			} else if (isset($a['order']) || isset($b['order'])) {
468
-				return isset($a['order']) ? -1 : 1;
469
-			} else {
470
-				return ($a['name'] < $b['name']) ? -1 : 1;
471
-			}
472
-		});
473
-
474
-		$activeApp = OC::$server->getNavigationManager()->getActiveEntry();
475
-		foreach ($list as $index => &$navEntry) {
476
-			if ($navEntry['id'] == $activeApp) {
477
-				$navEntry['active'] = true;
478
-			} else {
479
-				$navEntry['active'] = false;
480
-			}
481
-		}
482
-		unset($navEntry);
483
-
484
-		return $list;
485
-	}
486
-
487
-	/**
488
-	 * Get the path where to install apps
489
-	 *
490
-	 * @return string|false
491
-	 */
492
-	public static function getInstallPath() {
493
-		if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
494
-			return false;
495
-		}
496
-
497
-		foreach (OC::$APPSROOTS as $dir) {
498
-			if (isset($dir['writable']) && $dir['writable'] === true) {
499
-				return $dir['path'];
500
-			}
501
-		}
502
-
503
-		\OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
504
-		return null;
505
-	}
506
-
507
-
508
-	/**
509
-	 * search for an app in all app-directories
510
-	 *
511
-	 * @param string $appId
512
-	 * @return false|string
513
-	 */
514
-	public static function findAppInDirectories($appId) {
515
-		$sanitizedAppId = self::cleanAppId($appId);
516
-		if($sanitizedAppId !== $appId) {
517
-			return false;
518
-		}
519
-		static $app_dir = array();
520
-
521
-		if (isset($app_dir[$appId])) {
522
-			return $app_dir[$appId];
523
-		}
524
-
525
-		$possibleApps = array();
526
-		foreach (OC::$APPSROOTS as $dir) {
527
-			if (file_exists($dir['path'] . '/' . $appId)) {
528
-				$possibleApps[] = $dir;
529
-			}
530
-		}
531
-
532
-		if (empty($possibleApps)) {
533
-			return false;
534
-		} elseif (count($possibleApps) === 1) {
535
-			$dir = array_shift($possibleApps);
536
-			$app_dir[$appId] = $dir;
537
-			return $dir;
538
-		} else {
539
-			$versionToLoad = array();
540
-			foreach ($possibleApps as $possibleApp) {
541
-				$version = self::getAppVersionByPath($possibleApp['path']);
542
-				if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
543
-					$versionToLoad = array(
544
-						'dir' => $possibleApp,
545
-						'version' => $version,
546
-					);
547
-				}
548
-			}
549
-			$app_dir[$appId] = $versionToLoad['dir'];
550
-			return $versionToLoad['dir'];
551
-			//TODO - write test
552
-		}
553
-	}
554
-
555
-	/**
556
-	 * Get the directory for the given app.
557
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
558
-	 *
559
-	 * @param string $appId
560
-	 * @return string|false
561
-	 */
562
-	public static function getAppPath($appId) {
563
-		if ($appId === null || trim($appId) === '') {
564
-			return false;
565
-		}
566
-
567
-		if (($dir = self::findAppInDirectories($appId)) != false) {
568
-			return $dir['path'] . '/' . $appId;
569
-		}
570
-		return false;
571
-	}
572
-
573
-	/**
574
-	 * Get the path for the given app on the access
575
-	 * If the app is defined in multiple directories, the first one is taken. (false if not found)
576
-	 *
577
-	 * @param string $appId
578
-	 * @return string|false
579
-	 */
580
-	public static function getAppWebPath($appId) {
581
-		if (($dir = self::findAppInDirectories($appId)) != false) {
582
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
583
-		}
584
-		return false;
585
-	}
586
-
587
-	/**
588
-	 * get the last version of the app from appinfo/info.xml
589
-	 *
590
-	 * @param string $appId
591
-	 * @param bool $useCache
592
-	 * @return string
593
-	 */
594
-	public static function getAppVersion($appId, $useCache = true) {
595
-		if($useCache && isset(self::$appVersion[$appId])) {
596
-			return self::$appVersion[$appId];
597
-		}
598
-
599
-		$file = self::getAppPath($appId);
600
-		self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
601
-		return self::$appVersion[$appId];
602
-	}
603
-
604
-	/**
605
-	 * get app's version based on it's path
606
-	 *
607
-	 * @param string $path
608
-	 * @return string
609
-	 */
610
-	public static function getAppVersionByPath($path) {
611
-		$infoFile = $path . '/appinfo/info.xml';
612
-		$appData = self::getAppInfo($infoFile, true);
613
-		return isset($appData['version']) ? $appData['version'] : '';
614
-	}
615
-
616
-
617
-	/**
618
-	 * Read all app metadata from the info.xml file
619
-	 *
620
-	 * @param string $appId id of the app or the path of the info.xml file
621
-	 * @param bool $path
622
-	 * @param string $lang
623
-	 * @return array|null
624
-	 * @note all data is read from info.xml, not just pre-defined fields
625
-	 */
626
-	public static function getAppInfo($appId, $path = false, $lang = null) {
627
-		if ($path) {
628
-			$file = $appId;
629
-		} else {
630
-			if ($lang === null && isset(self::$appInfo[$appId])) {
631
-				return self::$appInfo[$appId];
632
-			}
633
-			$appPath = self::getAppPath($appId);
634
-			if($appPath === false) {
635
-				return null;
636
-			}
637
-			$file = $appPath . '/appinfo/info.xml';
638
-		}
639
-
640
-		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
641
-		$data = $parser->parse($file);
642
-
643
-		if (is_array($data)) {
644
-			$data = OC_App::parseAppInfo($data, $lang);
645
-		}
646
-		if(isset($data['ocsid'])) {
647
-			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
648
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
649
-				$data['ocsid'] = $storedId;
650
-			}
651
-		}
652
-
653
-		if ($lang === null) {
654
-			self::$appInfo[$appId] = $data;
655
-		}
656
-
657
-		return $data;
658
-	}
659
-
660
-	/**
661
-	 * Returns the navigation
662
-	 *
663
-	 * @return array
664
-	 *
665
-	 * This function returns an array containing all entries added. The
666
-	 * entries are sorted by the key 'order' ascending. Additional to the keys
667
-	 * given for each app the following keys exist:
668
-	 *   - active: boolean, signals if the user is on this navigation entry
669
-	 */
670
-	public static function getNavigation() {
671
-		$entries = OC::$server->getNavigationManager()->getAll();
672
-		return self::proceedNavigation($entries);
673
-	}
674
-
675
-	/**
676
-	 * Returns the Settings Navigation
677
-	 *
678
-	 * @return string[]
679
-	 *
680
-	 * This function returns an array containing all settings pages added. The
681
-	 * entries are sorted by the key 'order' ascending.
682
-	 */
683
-	public static function getSettingsNavigation() {
684
-		$entries = OC::$server->getNavigationManager()->getAll('settings');
685
-		return self::proceedNavigation($entries);
686
-	}
687
-
688
-	/**
689
-	 * get the id of loaded app
690
-	 *
691
-	 * @return string
692
-	 */
693
-	public static function getCurrentApp() {
694
-		$request = \OC::$server->getRequest();
695
-		$script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
696
-		$topFolder = substr($script, 0, strpos($script, '/') ?: 0);
697
-		if (empty($topFolder)) {
698
-			$path_info = $request->getPathInfo();
699
-			if ($path_info) {
700
-				$topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
701
-			}
702
-		}
703
-		if ($topFolder == 'apps') {
704
-			$length = strlen($topFolder);
705
-			return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
706
-		} else {
707
-			return $topFolder;
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * @param string $type
713
-	 * @return array
714
-	 */
715
-	public static function getForms($type) {
716
-		$forms = array();
717
-		switch ($type) {
718
-			case 'admin':
719
-				$source = self::$adminForms;
720
-				break;
721
-			case 'personal':
722
-				$source = self::$personalForms;
723
-				break;
724
-			default:
725
-				return array();
726
-		}
727
-		foreach ($source as $form) {
728
-			$forms[] = include $form;
729
-		}
730
-		return $forms;
731
-	}
732
-
733
-	/**
734
-	 * register an admin form to be shown
735
-	 *
736
-	 * @param string $app
737
-	 * @param string $page
738
-	 */
739
-	public static function registerAdmin($app, $page) {
740
-		self::$adminForms[] = $app . '/' . $page . '.php';
741
-	}
742
-
743
-	/**
744
-	 * register a personal form to be shown
745
-	 * @param string $app
746
-	 * @param string $page
747
-	 */
748
-	public static function registerPersonal($app, $page) {
749
-		self::$personalForms[] = $app . '/' . $page . '.php';
750
-	}
751
-
752
-	/**
753
-	 * @param array $entry
754
-	 */
755
-	public static function registerLogIn(array $entry) {
756
-		self::$altLogin[] = $entry;
757
-	}
758
-
759
-	/**
760
-	 * @return array
761
-	 */
762
-	public static function getAlternativeLogIns() {
763
-		return self::$altLogin;
764
-	}
765
-
766
-	/**
767
-	 * get a list of all apps in the apps folder
768
-	 *
769
-	 * @return array an array of app names (string IDs)
770
-	 * @todo: change the name of this method to getInstalledApps, which is more accurate
771
-	 */
772
-	public static function getAllApps() {
773
-
774
-		$apps = array();
775
-
776
-		foreach (OC::$APPSROOTS as $apps_dir) {
777
-			if (!is_readable($apps_dir['path'])) {
778
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
779
-				continue;
780
-			}
781
-			$dh = opendir($apps_dir['path']);
782
-
783
-			if (is_resource($dh)) {
784
-				while (($file = readdir($dh)) !== false) {
785
-
786
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
787
-
788
-						$apps[] = $file;
789
-					}
790
-				}
791
-			}
792
-		}
793
-
794
-		$apps = array_unique($apps);
795
-
796
-		return $apps;
797
-	}
798
-
799
-	/**
800
-	 * List all apps, this is used in apps.php
801
-	 *
802
-	 * @return array
803
-	 */
804
-	public function listAllApps() {
805
-		$installedApps = OC_App::getAllApps();
806
-
807
-		$appManager = \OC::$server->getAppManager();
808
-		//we don't want to show configuration for these
809
-		$blacklist = $appManager->getAlwaysEnabledApps();
810
-		$appList = array();
811
-		$langCode = \OC::$server->getL10N('core')->getLanguageCode();
812
-		$urlGenerator = \OC::$server->getURLGenerator();
813
-
814
-		foreach ($installedApps as $app) {
815
-			if (array_search($app, $blacklist) === false) {
816
-
817
-				$info = OC_App::getAppInfo($app, false, $langCode);
818
-				if (!is_array($info)) {
819
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
820
-					continue;
821
-				}
822
-
823
-				if (!isset($info['name'])) {
824
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
825
-					continue;
826
-				}
827
-
828
-				$enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
829
-				$info['groups'] = null;
830
-				if ($enabled === 'yes') {
831
-					$active = true;
832
-				} else if ($enabled === 'no') {
833
-					$active = false;
834
-				} else {
835
-					$active = true;
836
-					$info['groups'] = $enabled;
837
-				}
838
-
839
-				$info['active'] = $active;
840
-
841
-				if ($appManager->isShipped($app)) {
842
-					$info['internal'] = true;
843
-					$info['level'] = self::officialApp;
844
-					$info['removable'] = false;
845
-				} else {
846
-					$info['internal'] = false;
847
-					$info['removable'] = true;
848
-				}
849
-
850
-				$appPath = self::getAppPath($app);
851
-				if($appPath !== false) {
852
-					$appIcon = $appPath . '/img/' . $app . '.svg';
853
-					if (file_exists($appIcon)) {
854
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
855
-						$info['previewAsIcon'] = true;
856
-					} else {
857
-						$appIcon = $appPath . '/img/app.svg';
858
-						if (file_exists($appIcon)) {
859
-							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
860
-							$info['previewAsIcon'] = true;
861
-						}
862
-					}
863
-				}
864
-				// fix documentation
865
-				if (isset($info['documentation']) && is_array($info['documentation'])) {
866
-					foreach ($info['documentation'] as $key => $url) {
867
-						// If it is not an absolute URL we assume it is a key
868
-						// i.e. admin-ldap will get converted to go.php?to=admin-ldap
869
-						if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
870
-							$url = $urlGenerator->linkToDocs($url);
871
-						}
872
-
873
-						$info['documentation'][$key] = $url;
874
-					}
875
-				}
876
-
877
-				$info['version'] = OC_App::getAppVersion($app);
878
-				$appList[] = $info;
879
-			}
880
-		}
881
-
882
-		return $appList;
883
-	}
884
-
885
-	public static function shouldUpgrade($app) {
886
-		$versions = self::getAppVersions();
887
-		$currentVersion = OC_App::getAppVersion($app);
888
-		if ($currentVersion && isset($versions[$app])) {
889
-			$installedVersion = $versions[$app];
890
-			if (!version_compare($currentVersion, $installedVersion, '=')) {
891
-				return true;
892
-			}
893
-		}
894
-		return false;
895
-	}
896
-
897
-	/**
898
-	 * Adjust the number of version parts of $version1 to match
899
-	 * the number of version parts of $version2.
900
-	 *
901
-	 * @param string $version1 version to adjust
902
-	 * @param string $version2 version to take the number of parts from
903
-	 * @return string shortened $version1
904
-	 */
905
-	private static function adjustVersionParts($version1, $version2) {
906
-		$version1 = explode('.', $version1);
907
-		$version2 = explode('.', $version2);
908
-		// reduce $version1 to match the number of parts in $version2
909
-		while (count($version1) > count($version2)) {
910
-			array_pop($version1);
911
-		}
912
-		// if $version1 does not have enough parts, add some
913
-		while (count($version1) < count($version2)) {
914
-			$version1[] = '0';
915
-		}
916
-		return implode('.', $version1);
917
-	}
918
-
919
-	/**
920
-	 * Check whether the current ownCloud version matches the given
921
-	 * application's version requirements.
922
-	 *
923
-	 * The comparison is made based on the number of parts that the
924
-	 * app info version has. For example for ownCloud 6.0.3 if the
925
-	 * app info version is expecting version 6.0, the comparison is
926
-	 * made on the first two parts of the ownCloud version.
927
-	 * This means that it's possible to specify "requiremin" => 6
928
-	 * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
929
-	 *
930
-	 * @param string $ocVersion ownCloud version to check against
931
-	 * @param array $appInfo app info (from xml)
932
-	 *
933
-	 * @return boolean true if compatible, otherwise false
934
-	 */
935
-	public static function isAppCompatible($ocVersion, $appInfo) {
936
-		$requireMin = '';
937
-		$requireMax = '';
938
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
939
-			$requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
940
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
941
-			$requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
942
-		} else if (isset($appInfo['requiremin'])) {
943
-			$requireMin = $appInfo['requiremin'];
944
-		} else if (isset($appInfo['require'])) {
945
-			$requireMin = $appInfo['require'];
946
-		}
947
-
948
-		if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
949
-			$requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
950
-		} elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
951
-			$requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
952
-		} else if (isset($appInfo['requiremax'])) {
953
-			$requireMax = $appInfo['requiremax'];
954
-		}
955
-
956
-		if (is_array($ocVersion)) {
957
-			$ocVersion = implode('.', $ocVersion);
958
-		}
959
-
960
-		if (!empty($requireMin)
961
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
962
-		) {
963
-
964
-			return false;
965
-		}
966
-
967
-		if (!empty($requireMax)
968
-			&& version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
969
-		) {
970
-			return false;
971
-		}
972
-
973
-		return true;
974
-	}
975
-
976
-	/**
977
-	 * get the installed version of all apps
978
-	 */
979
-	public static function getAppVersions() {
980
-		static $versions;
981
-
982
-		if(!$versions) {
983
-			$appConfig = \OC::$server->getAppConfig();
984
-			$versions = $appConfig->getValues(false, 'installed_version');
985
-		}
986
-		return $versions;
987
-	}
988
-
989
-	/**
990
-	 * @param string $app
991
-	 * @param \OCP\IConfig $config
992
-	 * @param \OCP\IL10N $l
993
-	 * @return bool
994
-	 *
995
-	 * @throws Exception if app is not compatible with this version of ownCloud
996
-	 * @throws Exception if no app-name was specified
997
-	 */
998
-	public function installApp($app,
999
-							   \OCP\IConfig $config,
1000
-							   \OCP\IL10N $l) {
1001
-		if ($app !== false) {
1002
-			// check if the app is compatible with this version of ownCloud
1003
-			$info = self::getAppInfo($app);
1004
-			if(!is_array($info)) {
1005
-				throw new \Exception(
1006
-					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1007
-						[$info['name']]
1008
-					)
1009
-				);
1010
-			}
1011
-
1012
-			$version = \OCP\Util::getVersion();
1013
-			if (!self::isAppCompatible($version, $info)) {
1014
-				throw new \Exception(
1015
-					$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1016
-						array($info['name'])
1017
-					)
1018
-				);
1019
-			}
1020
-
1021
-			// check for required dependencies
1022
-			self::checkAppDependencies($config, $l, $info);
1023
-
1024
-			$config->setAppValue($app, 'enabled', 'yes');
1025
-			if (isset($appData['id'])) {
1026
-				$config->setAppValue($app, 'ocsid', $appData['id']);
1027
-			}
1028
-
1029
-			if(isset($info['settings']) && is_array($info['settings'])) {
1030
-				$appPath = self::getAppPath($app);
1031
-				self::registerAutoloading($app, $appPath);
1032
-			}
1033
-
1034
-			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1035
-		} else {
1036
-			if(empty($appName) ) {
1037
-				throw new \Exception($l->t("No app name specified"));
1038
-			} else {
1039
-				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1040
-			}
1041
-		}
1042
-
1043
-		return $app;
1044
-	}
1045
-
1046
-	/**
1047
-	 * update the database for the app and call the update script
1048
-	 *
1049
-	 * @param string $appId
1050
-	 * @return bool
1051
-	 */
1052
-	public static function updateApp($appId) {
1053
-		$appPath = self::getAppPath($appId);
1054
-		if($appPath === false) {
1055
-			return false;
1056
-		}
1057
-		self::registerAutoloading($appId, $appPath);
1058
-
1059
-		$appData = self::getAppInfo($appId);
1060
-		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1061
-
1062
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1063
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1064
-		} else {
1065
-			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1066
-			$ms->migrate();
1067
-		}
1068
-
1069
-		self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1070
-		self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1071
-		unset(self::$appVersion[$appId]);
1072
-
1073
-		// run upgrade code
1074
-		if (file_exists($appPath . '/appinfo/update.php')) {
1075
-			self::loadApp($appId);
1076
-			include $appPath . '/appinfo/update.php';
1077
-		}
1078
-		self::setupBackgroundJobs($appData['background-jobs']);
1079
-
1080
-		//set remote/public handlers
1081
-		if (array_key_exists('ocsid', $appData)) {
1082
-			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1083
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1084
-			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1085
-		}
1086
-		foreach ($appData['remote'] as $name => $path) {
1087
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1088
-		}
1089
-		foreach ($appData['public'] as $name => $path) {
1090
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1091
-		}
1092
-
1093
-		self::setAppTypes($appId);
1094
-
1095
-		$version = \OC_App::getAppVersion($appId);
1096
-		\OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1097
-
1098
-		\OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1099
-			ManagerEvent::EVENT_APP_UPDATE, $appId
1100
-		));
1101
-
1102
-		return true;
1103
-	}
1104
-
1105
-	/**
1106
-	 * @param string $appId
1107
-	 * @param string[] $steps
1108
-	 * @throws \OC\NeedsUpdateException
1109
-	 */
1110
-	public static function executeRepairSteps($appId, array $steps) {
1111
-		if (empty($steps)) {
1112
-			return;
1113
-		}
1114
-		// load the app
1115
-		self::loadApp($appId);
1116
-
1117
-		$dispatcher = OC::$server->getEventDispatcher();
1118
-
1119
-		// load the steps
1120
-		$r = new Repair([], $dispatcher);
1121
-		foreach ($steps as $step) {
1122
-			try {
1123
-				$r->addStep($step);
1124
-			} catch (Exception $ex) {
1125
-				$r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1126
-				\OC::$server->getLogger()->logException($ex);
1127
-			}
1128
-		}
1129
-		// run the steps
1130
-		$r->run();
1131
-	}
1132
-
1133
-	public static function setupBackgroundJobs(array $jobs) {
1134
-		$queue = \OC::$server->getJobList();
1135
-		foreach ($jobs as $job) {
1136
-			$queue->add($job);
1137
-		}
1138
-	}
1139
-
1140
-	/**
1141
-	 * @param string $appId
1142
-	 * @param string[] $steps
1143
-	 */
1144
-	private static function setupLiveMigrations($appId, array $steps) {
1145
-		$queue = \OC::$server->getJobList();
1146
-		foreach ($steps as $step) {
1147
-			$queue->add('OC\Migration\BackgroundRepair', [
1148
-				'app' => $appId,
1149
-				'step' => $step]);
1150
-		}
1151
-	}
1152
-
1153
-	/**
1154
-	 * @param string $appId
1155
-	 * @return \OC\Files\View|false
1156
-	 */
1157
-	public static function getStorage($appId) {
1158
-		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1159
-			if (\OC::$server->getUserSession()->isLoggedIn()) {
1160
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1161
-				if (!$view->file_exists($appId)) {
1162
-					$view->mkdir($appId);
1163
-				}
1164
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1165
-			} else {
1166
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1167
-				return false;
1168
-			}
1169
-		} else {
1170
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1171
-			return false;
1172
-		}
1173
-	}
1174
-
1175
-	protected static function findBestL10NOption($options, $lang) {
1176
-		$fallback = $similarLangFallback = $englishFallback = false;
1177
-
1178
-		$lang = strtolower($lang);
1179
-		$similarLang = $lang;
1180
-		if (strpos($similarLang, '_')) {
1181
-			// For "de_DE" we want to find "de" and the other way around
1182
-			$similarLang = substr($lang, 0, strpos($lang, '_'));
1183
-		}
1184
-
1185
-		foreach ($options as $option) {
1186
-			if (is_array($option)) {
1187
-				if ($fallback === false) {
1188
-					$fallback = $option['@value'];
1189
-				}
1190
-
1191
-				if (!isset($option['@attributes']['lang'])) {
1192
-					continue;
1193
-				}
1194
-
1195
-				$attributeLang = strtolower($option['@attributes']['lang']);
1196
-				if ($attributeLang === $lang) {
1197
-					return $option['@value'];
1198
-				}
1199
-
1200
-				if ($attributeLang === $similarLang) {
1201
-					$similarLangFallback = $option['@value'];
1202
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1203
-					if ($similarLangFallback === false) {
1204
-						$similarLangFallback =  $option['@value'];
1205
-					}
1206
-				}
1207
-			} else {
1208
-				$englishFallback = $option;
1209
-			}
1210
-		}
1211
-
1212
-		if ($similarLangFallback !== false) {
1213
-			return $similarLangFallback;
1214
-		} else if ($englishFallback !== false) {
1215
-			return $englishFallback;
1216
-		}
1217
-		return (string) $fallback;
1218
-	}
1219
-
1220
-	/**
1221
-	 * parses the app data array and enhanced the 'description' value
1222
-	 *
1223
-	 * @param array $data the app data
1224
-	 * @param string $lang
1225
-	 * @return array improved app data
1226
-	 */
1227
-	public static function parseAppInfo(array $data, $lang = null) {
1228
-
1229
-		if ($lang && isset($data['name']) && is_array($data['name'])) {
1230
-			$data['name'] = self::findBestL10NOption($data['name'], $lang);
1231
-		}
1232
-		if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1233
-			$data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1234
-		}
1235
-		if ($lang && isset($data['description']) && is_array($data['description'])) {
1236
-			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1237
-		} else if (isset($data['description']) && is_string($data['description'])) {
1238
-			$data['description'] = trim($data['description']);
1239
-		} else  {
1240
-			$data['description'] = '';
1241
-		}
1242
-
1243
-		return $data;
1244
-	}
1245
-
1246
-	/**
1247
-	 * @param \OCP\IConfig $config
1248
-	 * @param \OCP\IL10N $l
1249
-	 * @param array $info
1250
-	 * @throws \Exception
1251
-	 */
1252
-	public static function checkAppDependencies($config, $l, $info) {
1253
-		$dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1254
-		$missing = $dependencyAnalyzer->analyze($info);
1255
-		if (!empty($missing)) {
1256
-			$missingMsg = implode(PHP_EOL, $missing);
1257
-			throw new \Exception(
1258
-				$l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1259
-					[$info['name'], $missingMsg]
1260
-				)
1261
-			);
1262
-		}
1263
-	}
66
+    static private $appVersion = [];
67
+    static private $adminForms = array();
68
+    static private $personalForms = array();
69
+    static private $appInfo = array();
70
+    static private $appTypes = array();
71
+    static private $loadedApps = array();
72
+    static private $altLogin = array();
73
+    static private $alreadyRegistered = [];
74
+    const officialApp = 200;
75
+
76
+    /**
77
+     * clean the appId
78
+     *
79
+     * @param string|boolean $app AppId that needs to be cleaned
80
+     * @return string
81
+     */
82
+    public static function cleanAppId($app) {
83
+        return str_replace(array('\0', '/', '\\', '..'), '', $app);
84
+    }
85
+
86
+    /**
87
+     * Check if an app is loaded
88
+     *
89
+     * @param string $app
90
+     * @return bool
91
+     */
92
+    public static function isAppLoaded($app) {
93
+        return in_array($app, self::$loadedApps, true);
94
+    }
95
+
96
+    /**
97
+     * loads all apps
98
+     *
99
+     * @param string[] | string | null $types
100
+     * @return bool
101
+     *
102
+     * This function walks through the ownCloud directory and loads all apps
103
+     * it can find. A directory contains an app if the file /appinfo/info.xml
104
+     * exists.
105
+     *
106
+     * if $types is set, only apps of those types will be loaded
107
+     */
108
+    public static function loadApps($types = null) {
109
+        if (\OC::$server->getSystemConfig()->getValue('maintenance', false)) {
110
+            return false;
111
+        }
112
+        // Load the enabled apps here
113
+        $apps = self::getEnabledApps();
114
+
115
+        // Add each apps' folder as allowed class path
116
+        foreach($apps as $app) {
117
+            $path = self::getAppPath($app);
118
+            if($path !== false) {
119
+                self::registerAutoloading($app, $path);
120
+            }
121
+        }
122
+
123
+        // prevent app.php from printing output
124
+        ob_start();
125
+        foreach ($apps as $app) {
126
+            if ((is_null($types) or self::isType($app, $types)) && !in_array($app, self::$loadedApps)) {
127
+                self::loadApp($app);
128
+            }
129
+        }
130
+        ob_end_clean();
131
+
132
+        return true;
133
+    }
134
+
135
+    /**
136
+     * load a single app
137
+     *
138
+     * @param string $app
139
+     */
140
+    public static function loadApp($app) {
141
+        self::$loadedApps[] = $app;
142
+        $appPath = self::getAppPath($app);
143
+        if($appPath === false) {
144
+            return;
145
+        }
146
+
147
+        // in case someone calls loadApp() directly
148
+        self::registerAutoloading($app, $appPath);
149
+
150
+        if (is_file($appPath . '/appinfo/app.php')) {
151
+            \OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
152
+            self::requireAppFile($app);
153
+            if (self::isType($app, array('authentication'))) {
154
+                // since authentication apps affect the "is app enabled for group" check,
155
+                // the enabled apps cache needs to be cleared to make sure that the
156
+                // next time getEnableApps() is called it will also include apps that were
157
+                // enabled for groups
158
+                self::$enabledAppsCache = array();
159
+            }
160
+            \OC::$server->getEventLogger()->end('load_app_' . $app);
161
+        }
162
+
163
+        $info = self::getAppInfo($app);
164
+        if (!empty($info['activity']['filters'])) {
165
+            foreach ($info['activity']['filters'] as $filter) {
166
+                \OC::$server->getActivityManager()->registerFilter($filter);
167
+            }
168
+        }
169
+        if (!empty($info['activity']['settings'])) {
170
+            foreach ($info['activity']['settings'] as $setting) {
171
+                \OC::$server->getActivityManager()->registerSetting($setting);
172
+            }
173
+        }
174
+        if (!empty($info['activity']['providers'])) {
175
+            foreach ($info['activity']['providers'] as $provider) {
176
+                \OC::$server->getActivityManager()->registerProvider($provider);
177
+            }
178
+        }
179
+
180
+        if (!empty($info['settings']['admin'])) {
181
+            foreach ($info['settings']['admin'] as $setting) {
182
+                \OC::$server->getSettingsManager()->registerSetting('admin', $setting);
183
+            }
184
+        }
185
+        if (!empty($info['settings']['admin-section'])) {
186
+            foreach ($info['settings']['admin-section'] as $section) {
187
+                \OC::$server->getSettingsManager()->registerSection('admin', $section);
188
+            }
189
+        }
190
+        if (!empty($info['settings']['personal'])) {
191
+            foreach ($info['settings']['personal'] as $setting) {
192
+                \OC::$server->getSettingsManager()->registerSetting('personal', $setting);
193
+            }
194
+        }
195
+        if (!empty($info['settings']['personal-section'])) {
196
+            foreach ($info['settings']['personal-section'] as $section) {
197
+                \OC::$server->getSettingsManager()->registerSection('personal', $section);
198
+            }
199
+        }
200
+
201
+        if (!empty($info['collaboration']['plugins'])) {
202
+            // deal with one or many plugin entries
203
+            $plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
204
+                [$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
205
+            foreach ($plugins as $plugin) {
206
+                if($plugin['@attributes']['type'] === 'collaborator-search') {
207
+                    $pluginInfo = [
208
+                        'shareType' => $plugin['@attributes']['share-type'],
209
+                        'class' => $plugin['@value'],
210
+                    ];
211
+                    \OC::$server->getCollaboratorSearch()->registerPlugin($pluginInfo);
212
+                } else if ($plugin['@attributes']['type'] === 'autocomplete-sort') {
213
+                    \OC::$server->getAutoCompleteManager()->registerSorter($plugin['@value']);
214
+                }
215
+            }
216
+        }
217
+    }
218
+
219
+    /**
220
+     * @internal
221
+     * @param string $app
222
+     * @param string $path
223
+     */
224
+    public static function registerAutoloading($app, $path) {
225
+        $key = $app . '-' . $path;
226
+        if(isset(self::$alreadyRegistered[$key])) {
227
+            return;
228
+        }
229
+
230
+        self::$alreadyRegistered[$key] = true;
231
+
232
+        // Register on PSR-4 composer autoloader
233
+        $appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
234
+        \OC::$server->registerNamespace($app, $appNamespace);
235
+
236
+        if (file_exists($path . '/composer/autoload.php')) {
237
+            require_once $path . '/composer/autoload.php';
238
+        } else {
239
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
240
+            // Register on legacy autoloader
241
+            \OC::$loader->addValidRoot($path);
242
+        }
243
+
244
+        // Register Test namespace only when testing
245
+        if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
246
+            \OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
247
+        }
248
+    }
249
+
250
+    /**
251
+     * Load app.php from the given app
252
+     *
253
+     * @param string $app app name
254
+     */
255
+    private static function requireAppFile($app) {
256
+        try {
257
+            // encapsulated here to avoid variable scope conflicts
258
+            require_once $app . '/appinfo/app.php';
259
+        } catch (Error $ex) {
260
+            \OC::$server->getLogger()->logException($ex);
261
+            if (!\OC::$server->getAppManager()->isShipped($app)) {
262
+                // Only disable apps which are not shipped
263
+                self::disable($app);
264
+            }
265
+        }
266
+    }
267
+
268
+    /**
269
+     * check if an app is of a specific type
270
+     *
271
+     * @param string $app
272
+     * @param string|array $types
273
+     * @return bool
274
+     */
275
+    public static function isType($app, $types) {
276
+        if (is_string($types)) {
277
+            $types = array($types);
278
+        }
279
+        $appTypes = self::getAppTypes($app);
280
+        foreach ($types as $type) {
281
+            if (array_search($type, $appTypes) !== false) {
282
+                return true;
283
+            }
284
+        }
285
+        return false;
286
+    }
287
+
288
+    /**
289
+     * get the types of an app
290
+     *
291
+     * @param string $app
292
+     * @return array
293
+     */
294
+    private static function getAppTypes($app) {
295
+        //load the cache
296
+        if (count(self::$appTypes) == 0) {
297
+            self::$appTypes = \OC::$server->getAppConfig()->getValues(false, 'types');
298
+        }
299
+
300
+        if (isset(self::$appTypes[$app])) {
301
+            return explode(',', self::$appTypes[$app]);
302
+        } else {
303
+            return array();
304
+        }
305
+    }
306
+
307
+    /**
308
+     * read app types from info.xml and cache them in the database
309
+     */
310
+    public static function setAppTypes($app) {
311
+        $appData = self::getAppInfo($app);
312
+        if(!is_array($appData)) {
313
+            return;
314
+        }
315
+
316
+        if (isset($appData['types'])) {
317
+            $appTypes = implode(',', $appData['types']);
318
+        } else {
319
+            $appTypes = '';
320
+            $appData['types'] = [];
321
+        }
322
+
323
+        \OC::$server->getConfig()->setAppValue($app, 'types', $appTypes);
324
+
325
+        if (\OC::$server->getAppManager()->hasProtectedAppType($appData['types'])) {
326
+            $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'yes');
327
+            if ($enabled !== 'yes' && $enabled !== 'no') {
328
+                \OC::$server->getConfig()->setAppValue($app, 'enabled', 'yes');
329
+            }
330
+        }
331
+    }
332
+
333
+    /**
334
+     * get all enabled apps
335
+     */
336
+    protected static $enabledAppsCache = array();
337
+
338
+    /**
339
+     * Returns apps enabled for the current user.
340
+     *
341
+     * @param bool $forceRefresh whether to refresh the cache
342
+     * @param bool $all whether to return apps for all users, not only the
343
+     * currently logged in one
344
+     * @return string[]
345
+     */
346
+    public static function getEnabledApps($forceRefresh = false, $all = false) {
347
+        if (!\OC::$server->getSystemConfig()->getValue('installed', false)) {
348
+            return array();
349
+        }
350
+        // in incognito mode or when logged out, $user will be false,
351
+        // which is also the case during an upgrade
352
+        $appManager = \OC::$server->getAppManager();
353
+        if ($all) {
354
+            $user = null;
355
+        } else {
356
+            $user = \OC::$server->getUserSession()->getUser();
357
+        }
358
+
359
+        if (is_null($user)) {
360
+            $apps = $appManager->getInstalledApps();
361
+        } else {
362
+            $apps = $appManager->getEnabledAppsForUser($user);
363
+        }
364
+        $apps = array_filter($apps, function ($app) {
365
+            return $app !== 'files';//we add this manually
366
+        });
367
+        sort($apps);
368
+        array_unshift($apps, 'files');
369
+        return $apps;
370
+    }
371
+
372
+    /**
373
+     * checks whether or not an app is enabled
374
+     *
375
+     * @param string $app app
376
+     * @return bool
377
+     * @deprecated 13.0.0 use \OC::$server->getAppManager()->isEnabledForUser($appId)
378
+     *
379
+     * This function checks whether or not an app is enabled.
380
+     */
381
+    public static function isEnabled($app) {
382
+        return \OC::$server->getAppManager()->isEnabledForUser($app);
383
+    }
384
+
385
+    /**
386
+     * enables an app
387
+     *
388
+     * @param string $appId
389
+     * @param array $groups (optional) when set, only these groups will have access to the app
390
+     * @throws \Exception
391
+     * @return void
392
+     *
393
+     * This function set an app as enabled in appconfig.
394
+     */
395
+    public function enable($appId,
396
+                            $groups = null) {
397
+        self::$enabledAppsCache = []; // flush
398
+
399
+        // Check if app is already downloaded
400
+        $installer = \OC::$server->query(Installer::class);
401
+        $isDownloaded = $installer->isDownloaded($appId);
402
+
403
+        if(!$isDownloaded) {
404
+            $installer->downloadApp($appId);
405
+        }
406
+
407
+        $installer->installApp($appId);
408
+
409
+        $appManager = \OC::$server->getAppManager();
410
+        if (!is_null($groups)) {
411
+            $groupManager = \OC::$server->getGroupManager();
412
+            $groupsList = [];
413
+            foreach ($groups as $group) {
414
+                $groupItem = $groupManager->get($group);
415
+                if ($groupItem instanceof \OCP\IGroup) {
416
+                    $groupsList[] = $groupManager->get($group);
417
+                }
418
+            }
419
+            $appManager->enableAppForGroups($appId, $groupsList);
420
+        } else {
421
+            $appManager->enableApp($appId);
422
+        }
423
+    }
424
+
425
+    /**
426
+     * @param string $app
427
+     * @return bool
428
+     */
429
+    public static function removeApp($app) {
430
+        if (\OC::$server->getAppManager()->isShipped($app)) {
431
+            return false;
432
+        }
433
+
434
+        $installer = \OC::$server->query(Installer::class);
435
+        return $installer->removeApp($app);
436
+    }
437
+
438
+    /**
439
+     * This function set an app as disabled in appconfig.
440
+     *
441
+     * @param string $app app
442
+     * @throws Exception
443
+     */
444
+    public static function disable($app) {
445
+        // flush
446
+        self::$enabledAppsCache = array();
447
+
448
+        // run uninstall steps
449
+        $appData = OC_App::getAppInfo($app);
450
+        if (!is_null($appData)) {
451
+            OC_App::executeRepairSteps($app, $appData['repair-steps']['uninstall']);
452
+        }
453
+
454
+        // emit disable hook - needed anymore ?
455
+        \OC_Hook::emit('OC_App', 'pre_disable', array('app' => $app));
456
+
457
+        // finally disable it
458
+        $appManager = \OC::$server->getAppManager();
459
+        $appManager->disableApp($app);
460
+    }
461
+
462
+    // This is private as well. It simply works, so don't ask for more details
463
+    private static function proceedNavigation($list) {
464
+        usort($list, function($a, $b) {
465
+            if (isset($a['order']) && isset($b['order'])) {
466
+                return ($a['order'] < $b['order']) ? -1 : 1;
467
+            } else if (isset($a['order']) || isset($b['order'])) {
468
+                return isset($a['order']) ? -1 : 1;
469
+            } else {
470
+                return ($a['name'] < $b['name']) ? -1 : 1;
471
+            }
472
+        });
473
+
474
+        $activeApp = OC::$server->getNavigationManager()->getActiveEntry();
475
+        foreach ($list as $index => &$navEntry) {
476
+            if ($navEntry['id'] == $activeApp) {
477
+                $navEntry['active'] = true;
478
+            } else {
479
+                $navEntry['active'] = false;
480
+            }
481
+        }
482
+        unset($navEntry);
483
+
484
+        return $list;
485
+    }
486
+
487
+    /**
488
+     * Get the path where to install apps
489
+     *
490
+     * @return string|false
491
+     */
492
+    public static function getInstallPath() {
493
+        if (\OC::$server->getSystemConfig()->getValue('appstoreenabled', true) == false) {
494
+            return false;
495
+        }
496
+
497
+        foreach (OC::$APPSROOTS as $dir) {
498
+            if (isset($dir['writable']) && $dir['writable'] === true) {
499
+                return $dir['path'];
500
+            }
501
+        }
502
+
503
+        \OCP\Util::writeLog('core', 'No application directories are marked as writable.', \OCP\Util::ERROR);
504
+        return null;
505
+    }
506
+
507
+
508
+    /**
509
+     * search for an app in all app-directories
510
+     *
511
+     * @param string $appId
512
+     * @return false|string
513
+     */
514
+    public static function findAppInDirectories($appId) {
515
+        $sanitizedAppId = self::cleanAppId($appId);
516
+        if($sanitizedAppId !== $appId) {
517
+            return false;
518
+        }
519
+        static $app_dir = array();
520
+
521
+        if (isset($app_dir[$appId])) {
522
+            return $app_dir[$appId];
523
+        }
524
+
525
+        $possibleApps = array();
526
+        foreach (OC::$APPSROOTS as $dir) {
527
+            if (file_exists($dir['path'] . '/' . $appId)) {
528
+                $possibleApps[] = $dir;
529
+            }
530
+        }
531
+
532
+        if (empty($possibleApps)) {
533
+            return false;
534
+        } elseif (count($possibleApps) === 1) {
535
+            $dir = array_shift($possibleApps);
536
+            $app_dir[$appId] = $dir;
537
+            return $dir;
538
+        } else {
539
+            $versionToLoad = array();
540
+            foreach ($possibleApps as $possibleApp) {
541
+                $version = self::getAppVersionByPath($possibleApp['path']);
542
+                if (empty($versionToLoad) || version_compare($version, $versionToLoad['version'], '>')) {
543
+                    $versionToLoad = array(
544
+                        'dir' => $possibleApp,
545
+                        'version' => $version,
546
+                    );
547
+                }
548
+            }
549
+            $app_dir[$appId] = $versionToLoad['dir'];
550
+            return $versionToLoad['dir'];
551
+            //TODO - write test
552
+        }
553
+    }
554
+
555
+    /**
556
+     * Get the directory for the given app.
557
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
558
+     *
559
+     * @param string $appId
560
+     * @return string|false
561
+     */
562
+    public static function getAppPath($appId) {
563
+        if ($appId === null || trim($appId) === '') {
564
+            return false;
565
+        }
566
+
567
+        if (($dir = self::findAppInDirectories($appId)) != false) {
568
+            return $dir['path'] . '/' . $appId;
569
+        }
570
+        return false;
571
+    }
572
+
573
+    /**
574
+     * Get the path for the given app on the access
575
+     * If the app is defined in multiple directories, the first one is taken. (false if not found)
576
+     *
577
+     * @param string $appId
578
+     * @return string|false
579
+     */
580
+    public static function getAppWebPath($appId) {
581
+        if (($dir = self::findAppInDirectories($appId)) != false) {
582
+            return OC::$WEBROOT . $dir['url'] . '/' . $appId;
583
+        }
584
+        return false;
585
+    }
586
+
587
+    /**
588
+     * get the last version of the app from appinfo/info.xml
589
+     *
590
+     * @param string $appId
591
+     * @param bool $useCache
592
+     * @return string
593
+     */
594
+    public static function getAppVersion($appId, $useCache = true) {
595
+        if($useCache && isset(self::$appVersion[$appId])) {
596
+            return self::$appVersion[$appId];
597
+        }
598
+
599
+        $file = self::getAppPath($appId);
600
+        self::$appVersion[$appId] = ($file !== false) ? self::getAppVersionByPath($file) : '0';
601
+        return self::$appVersion[$appId];
602
+    }
603
+
604
+    /**
605
+     * get app's version based on it's path
606
+     *
607
+     * @param string $path
608
+     * @return string
609
+     */
610
+    public static function getAppVersionByPath($path) {
611
+        $infoFile = $path . '/appinfo/info.xml';
612
+        $appData = self::getAppInfo($infoFile, true);
613
+        return isset($appData['version']) ? $appData['version'] : '';
614
+    }
615
+
616
+
617
+    /**
618
+     * Read all app metadata from the info.xml file
619
+     *
620
+     * @param string $appId id of the app or the path of the info.xml file
621
+     * @param bool $path
622
+     * @param string $lang
623
+     * @return array|null
624
+     * @note all data is read from info.xml, not just pre-defined fields
625
+     */
626
+    public static function getAppInfo($appId, $path = false, $lang = null) {
627
+        if ($path) {
628
+            $file = $appId;
629
+        } else {
630
+            if ($lang === null && isset(self::$appInfo[$appId])) {
631
+                return self::$appInfo[$appId];
632
+            }
633
+            $appPath = self::getAppPath($appId);
634
+            if($appPath === false) {
635
+                return null;
636
+            }
637
+            $file = $appPath . '/appinfo/info.xml';
638
+        }
639
+
640
+        $parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
641
+        $data = $parser->parse($file);
642
+
643
+        if (is_array($data)) {
644
+            $data = OC_App::parseAppInfo($data, $lang);
645
+        }
646
+        if(isset($data['ocsid'])) {
647
+            $storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
648
+            if($storedId !== '' && $storedId !== $data['ocsid']) {
649
+                $data['ocsid'] = $storedId;
650
+            }
651
+        }
652
+
653
+        if ($lang === null) {
654
+            self::$appInfo[$appId] = $data;
655
+        }
656
+
657
+        return $data;
658
+    }
659
+
660
+    /**
661
+     * Returns the navigation
662
+     *
663
+     * @return array
664
+     *
665
+     * This function returns an array containing all entries added. The
666
+     * entries are sorted by the key 'order' ascending. Additional to the keys
667
+     * given for each app the following keys exist:
668
+     *   - active: boolean, signals if the user is on this navigation entry
669
+     */
670
+    public static function getNavigation() {
671
+        $entries = OC::$server->getNavigationManager()->getAll();
672
+        return self::proceedNavigation($entries);
673
+    }
674
+
675
+    /**
676
+     * Returns the Settings Navigation
677
+     *
678
+     * @return string[]
679
+     *
680
+     * This function returns an array containing all settings pages added. The
681
+     * entries are sorted by the key 'order' ascending.
682
+     */
683
+    public static function getSettingsNavigation() {
684
+        $entries = OC::$server->getNavigationManager()->getAll('settings');
685
+        return self::proceedNavigation($entries);
686
+    }
687
+
688
+    /**
689
+     * get the id of loaded app
690
+     *
691
+     * @return string
692
+     */
693
+    public static function getCurrentApp() {
694
+        $request = \OC::$server->getRequest();
695
+        $script = substr($request->getScriptName(), strlen(OC::$WEBROOT) + 1);
696
+        $topFolder = substr($script, 0, strpos($script, '/') ?: 0);
697
+        if (empty($topFolder)) {
698
+            $path_info = $request->getPathInfo();
699
+            if ($path_info) {
700
+                $topFolder = substr($path_info, 1, strpos($path_info, '/', 1) - 1);
701
+            }
702
+        }
703
+        if ($topFolder == 'apps') {
704
+            $length = strlen($topFolder);
705
+            return substr($script, $length + 1, strpos($script, '/', $length + 1) - $length - 1);
706
+        } else {
707
+            return $topFolder;
708
+        }
709
+    }
710
+
711
+    /**
712
+     * @param string $type
713
+     * @return array
714
+     */
715
+    public static function getForms($type) {
716
+        $forms = array();
717
+        switch ($type) {
718
+            case 'admin':
719
+                $source = self::$adminForms;
720
+                break;
721
+            case 'personal':
722
+                $source = self::$personalForms;
723
+                break;
724
+            default:
725
+                return array();
726
+        }
727
+        foreach ($source as $form) {
728
+            $forms[] = include $form;
729
+        }
730
+        return $forms;
731
+    }
732
+
733
+    /**
734
+     * register an admin form to be shown
735
+     *
736
+     * @param string $app
737
+     * @param string $page
738
+     */
739
+    public static function registerAdmin($app, $page) {
740
+        self::$adminForms[] = $app . '/' . $page . '.php';
741
+    }
742
+
743
+    /**
744
+     * register a personal form to be shown
745
+     * @param string $app
746
+     * @param string $page
747
+     */
748
+    public static function registerPersonal($app, $page) {
749
+        self::$personalForms[] = $app . '/' . $page . '.php';
750
+    }
751
+
752
+    /**
753
+     * @param array $entry
754
+     */
755
+    public static function registerLogIn(array $entry) {
756
+        self::$altLogin[] = $entry;
757
+    }
758
+
759
+    /**
760
+     * @return array
761
+     */
762
+    public static function getAlternativeLogIns() {
763
+        return self::$altLogin;
764
+    }
765
+
766
+    /**
767
+     * get a list of all apps in the apps folder
768
+     *
769
+     * @return array an array of app names (string IDs)
770
+     * @todo: change the name of this method to getInstalledApps, which is more accurate
771
+     */
772
+    public static function getAllApps() {
773
+
774
+        $apps = array();
775
+
776
+        foreach (OC::$APPSROOTS as $apps_dir) {
777
+            if (!is_readable($apps_dir['path'])) {
778
+                \OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
779
+                continue;
780
+            }
781
+            $dh = opendir($apps_dir['path']);
782
+
783
+            if (is_resource($dh)) {
784
+                while (($file = readdir($dh)) !== false) {
785
+
786
+                    if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
787
+
788
+                        $apps[] = $file;
789
+                    }
790
+                }
791
+            }
792
+        }
793
+
794
+        $apps = array_unique($apps);
795
+
796
+        return $apps;
797
+    }
798
+
799
+    /**
800
+     * List all apps, this is used in apps.php
801
+     *
802
+     * @return array
803
+     */
804
+    public function listAllApps() {
805
+        $installedApps = OC_App::getAllApps();
806
+
807
+        $appManager = \OC::$server->getAppManager();
808
+        //we don't want to show configuration for these
809
+        $blacklist = $appManager->getAlwaysEnabledApps();
810
+        $appList = array();
811
+        $langCode = \OC::$server->getL10N('core')->getLanguageCode();
812
+        $urlGenerator = \OC::$server->getURLGenerator();
813
+
814
+        foreach ($installedApps as $app) {
815
+            if (array_search($app, $blacklist) === false) {
816
+
817
+                $info = OC_App::getAppInfo($app, false, $langCode);
818
+                if (!is_array($info)) {
819
+                    \OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
820
+                    continue;
821
+                }
822
+
823
+                if (!isset($info['name'])) {
824
+                    \OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
825
+                    continue;
826
+                }
827
+
828
+                $enabled = \OC::$server->getConfig()->getAppValue($app, 'enabled', 'no');
829
+                $info['groups'] = null;
830
+                if ($enabled === 'yes') {
831
+                    $active = true;
832
+                } else if ($enabled === 'no') {
833
+                    $active = false;
834
+                } else {
835
+                    $active = true;
836
+                    $info['groups'] = $enabled;
837
+                }
838
+
839
+                $info['active'] = $active;
840
+
841
+                if ($appManager->isShipped($app)) {
842
+                    $info['internal'] = true;
843
+                    $info['level'] = self::officialApp;
844
+                    $info['removable'] = false;
845
+                } else {
846
+                    $info['internal'] = false;
847
+                    $info['removable'] = true;
848
+                }
849
+
850
+                $appPath = self::getAppPath($app);
851
+                if($appPath !== false) {
852
+                    $appIcon = $appPath . '/img/' . $app . '.svg';
853
+                    if (file_exists($appIcon)) {
854
+                        $info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
855
+                        $info['previewAsIcon'] = true;
856
+                    } else {
857
+                        $appIcon = $appPath . '/img/app.svg';
858
+                        if (file_exists($appIcon)) {
859
+                            $info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
860
+                            $info['previewAsIcon'] = true;
861
+                        }
862
+                    }
863
+                }
864
+                // fix documentation
865
+                if (isset($info['documentation']) && is_array($info['documentation'])) {
866
+                    foreach ($info['documentation'] as $key => $url) {
867
+                        // If it is not an absolute URL we assume it is a key
868
+                        // i.e. admin-ldap will get converted to go.php?to=admin-ldap
869
+                        if (stripos($url, 'https://') !== 0 && stripos($url, 'http://') !== 0) {
870
+                            $url = $urlGenerator->linkToDocs($url);
871
+                        }
872
+
873
+                        $info['documentation'][$key] = $url;
874
+                    }
875
+                }
876
+
877
+                $info['version'] = OC_App::getAppVersion($app);
878
+                $appList[] = $info;
879
+            }
880
+        }
881
+
882
+        return $appList;
883
+    }
884
+
885
+    public static function shouldUpgrade($app) {
886
+        $versions = self::getAppVersions();
887
+        $currentVersion = OC_App::getAppVersion($app);
888
+        if ($currentVersion && isset($versions[$app])) {
889
+            $installedVersion = $versions[$app];
890
+            if (!version_compare($currentVersion, $installedVersion, '=')) {
891
+                return true;
892
+            }
893
+        }
894
+        return false;
895
+    }
896
+
897
+    /**
898
+     * Adjust the number of version parts of $version1 to match
899
+     * the number of version parts of $version2.
900
+     *
901
+     * @param string $version1 version to adjust
902
+     * @param string $version2 version to take the number of parts from
903
+     * @return string shortened $version1
904
+     */
905
+    private static function adjustVersionParts($version1, $version2) {
906
+        $version1 = explode('.', $version1);
907
+        $version2 = explode('.', $version2);
908
+        // reduce $version1 to match the number of parts in $version2
909
+        while (count($version1) > count($version2)) {
910
+            array_pop($version1);
911
+        }
912
+        // if $version1 does not have enough parts, add some
913
+        while (count($version1) < count($version2)) {
914
+            $version1[] = '0';
915
+        }
916
+        return implode('.', $version1);
917
+    }
918
+
919
+    /**
920
+     * Check whether the current ownCloud version matches the given
921
+     * application's version requirements.
922
+     *
923
+     * The comparison is made based on the number of parts that the
924
+     * app info version has. For example for ownCloud 6.0.3 if the
925
+     * app info version is expecting version 6.0, the comparison is
926
+     * made on the first two parts of the ownCloud version.
927
+     * This means that it's possible to specify "requiremin" => 6
928
+     * and "requiremax" => 6 and it will still match ownCloud 6.0.3.
929
+     *
930
+     * @param string $ocVersion ownCloud version to check against
931
+     * @param array $appInfo app info (from xml)
932
+     *
933
+     * @return boolean true if compatible, otherwise false
934
+     */
935
+    public static function isAppCompatible($ocVersion, $appInfo) {
936
+        $requireMin = '';
937
+        $requireMax = '';
938
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['min-version'])) {
939
+            $requireMin = $appInfo['dependencies']['nextcloud']['@attributes']['min-version'];
940
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['min-version'])) {
941
+            $requireMin = $appInfo['dependencies']['owncloud']['@attributes']['min-version'];
942
+        } else if (isset($appInfo['requiremin'])) {
943
+            $requireMin = $appInfo['requiremin'];
944
+        } else if (isset($appInfo['require'])) {
945
+            $requireMin = $appInfo['require'];
946
+        }
947
+
948
+        if (isset($appInfo['dependencies']['nextcloud']['@attributes']['max-version'])) {
949
+            $requireMax = $appInfo['dependencies']['nextcloud']['@attributes']['max-version'];
950
+        } elseif (isset($appInfo['dependencies']['owncloud']['@attributes']['max-version'])) {
951
+            $requireMax = $appInfo['dependencies']['owncloud']['@attributes']['max-version'];
952
+        } else if (isset($appInfo['requiremax'])) {
953
+            $requireMax = $appInfo['requiremax'];
954
+        }
955
+
956
+        if (is_array($ocVersion)) {
957
+            $ocVersion = implode('.', $ocVersion);
958
+        }
959
+
960
+        if (!empty($requireMin)
961
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMin), $requireMin, '<')
962
+        ) {
963
+
964
+            return false;
965
+        }
966
+
967
+        if (!empty($requireMax)
968
+            && version_compare(self::adjustVersionParts($ocVersion, $requireMax), $requireMax, '>')
969
+        ) {
970
+            return false;
971
+        }
972
+
973
+        return true;
974
+    }
975
+
976
+    /**
977
+     * get the installed version of all apps
978
+     */
979
+    public static function getAppVersions() {
980
+        static $versions;
981
+
982
+        if(!$versions) {
983
+            $appConfig = \OC::$server->getAppConfig();
984
+            $versions = $appConfig->getValues(false, 'installed_version');
985
+        }
986
+        return $versions;
987
+    }
988
+
989
+    /**
990
+     * @param string $app
991
+     * @param \OCP\IConfig $config
992
+     * @param \OCP\IL10N $l
993
+     * @return bool
994
+     *
995
+     * @throws Exception if app is not compatible with this version of ownCloud
996
+     * @throws Exception if no app-name was specified
997
+     */
998
+    public function installApp($app,
999
+                                \OCP\IConfig $config,
1000
+                                \OCP\IL10N $l) {
1001
+        if ($app !== false) {
1002
+            // check if the app is compatible with this version of ownCloud
1003
+            $info = self::getAppInfo($app);
1004
+            if(!is_array($info)) {
1005
+                throw new \Exception(
1006
+                    $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1007
+                        [$info['name']]
1008
+                    )
1009
+                );
1010
+            }
1011
+
1012
+            $version = \OCP\Util::getVersion();
1013
+            if (!self::isAppCompatible($version, $info)) {
1014
+                throw new \Exception(
1015
+                    $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
1016
+                        array($info['name'])
1017
+                    )
1018
+                );
1019
+            }
1020
+
1021
+            // check for required dependencies
1022
+            self::checkAppDependencies($config, $l, $info);
1023
+
1024
+            $config->setAppValue($app, 'enabled', 'yes');
1025
+            if (isset($appData['id'])) {
1026
+                $config->setAppValue($app, 'ocsid', $appData['id']);
1027
+            }
1028
+
1029
+            if(isset($info['settings']) && is_array($info['settings'])) {
1030
+                $appPath = self::getAppPath($app);
1031
+                self::registerAutoloading($app, $appPath);
1032
+            }
1033
+
1034
+            \OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1035
+        } else {
1036
+            if(empty($appName) ) {
1037
+                throw new \Exception($l->t("No app name specified"));
1038
+            } else {
1039
+                throw new \Exception($l->t("App '%s' could not be installed!", $appName));
1040
+            }
1041
+        }
1042
+
1043
+        return $app;
1044
+    }
1045
+
1046
+    /**
1047
+     * update the database for the app and call the update script
1048
+     *
1049
+     * @param string $appId
1050
+     * @return bool
1051
+     */
1052
+    public static function updateApp($appId) {
1053
+        $appPath = self::getAppPath($appId);
1054
+        if($appPath === false) {
1055
+            return false;
1056
+        }
1057
+        self::registerAutoloading($appId, $appPath);
1058
+
1059
+        $appData = self::getAppInfo($appId);
1060
+        self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1061
+
1062
+        if (file_exists($appPath . '/appinfo/database.xml')) {
1063
+            OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1064
+        } else {
1065
+            $ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1066
+            $ms->migrate();
1067
+        }
1068
+
1069
+        self::executeRepairSteps($appId, $appData['repair-steps']['post-migration']);
1070
+        self::setupLiveMigrations($appId, $appData['repair-steps']['live-migration']);
1071
+        unset(self::$appVersion[$appId]);
1072
+
1073
+        // run upgrade code
1074
+        if (file_exists($appPath . '/appinfo/update.php')) {
1075
+            self::loadApp($appId);
1076
+            include $appPath . '/appinfo/update.php';
1077
+        }
1078
+        self::setupBackgroundJobs($appData['background-jobs']);
1079
+
1080
+        //set remote/public handlers
1081
+        if (array_key_exists('ocsid', $appData)) {
1082
+            \OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1083
+        } elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1084
+            \OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1085
+        }
1086
+        foreach ($appData['remote'] as $name => $path) {
1087
+            \OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1088
+        }
1089
+        foreach ($appData['public'] as $name => $path) {
1090
+            \OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1091
+        }
1092
+
1093
+        self::setAppTypes($appId);
1094
+
1095
+        $version = \OC_App::getAppVersion($appId);
1096
+        \OC::$server->getConfig()->setAppValue($appId, 'installed_version', $version);
1097
+
1098
+        \OC::$server->getEventDispatcher()->dispatch(ManagerEvent::EVENT_APP_UPDATE, new ManagerEvent(
1099
+            ManagerEvent::EVENT_APP_UPDATE, $appId
1100
+        ));
1101
+
1102
+        return true;
1103
+    }
1104
+
1105
+    /**
1106
+     * @param string $appId
1107
+     * @param string[] $steps
1108
+     * @throws \OC\NeedsUpdateException
1109
+     */
1110
+    public static function executeRepairSteps($appId, array $steps) {
1111
+        if (empty($steps)) {
1112
+            return;
1113
+        }
1114
+        // load the app
1115
+        self::loadApp($appId);
1116
+
1117
+        $dispatcher = OC::$server->getEventDispatcher();
1118
+
1119
+        // load the steps
1120
+        $r = new Repair([], $dispatcher);
1121
+        foreach ($steps as $step) {
1122
+            try {
1123
+                $r->addStep($step);
1124
+            } catch (Exception $ex) {
1125
+                $r->emit('\OC\Repair', 'error', [$ex->getMessage()]);
1126
+                \OC::$server->getLogger()->logException($ex);
1127
+            }
1128
+        }
1129
+        // run the steps
1130
+        $r->run();
1131
+    }
1132
+
1133
+    public static function setupBackgroundJobs(array $jobs) {
1134
+        $queue = \OC::$server->getJobList();
1135
+        foreach ($jobs as $job) {
1136
+            $queue->add($job);
1137
+        }
1138
+    }
1139
+
1140
+    /**
1141
+     * @param string $appId
1142
+     * @param string[] $steps
1143
+     */
1144
+    private static function setupLiveMigrations($appId, array $steps) {
1145
+        $queue = \OC::$server->getJobList();
1146
+        foreach ($steps as $step) {
1147
+            $queue->add('OC\Migration\BackgroundRepair', [
1148
+                'app' => $appId,
1149
+                'step' => $step]);
1150
+        }
1151
+    }
1152
+
1153
+    /**
1154
+     * @param string $appId
1155
+     * @return \OC\Files\View|false
1156
+     */
1157
+    public static function getStorage($appId) {
1158
+        if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1159
+            if (\OC::$server->getUserSession()->isLoggedIn()) {
1160
+                $view = new \OC\Files\View('/' . OC_User::getUser());
1161
+                if (!$view->file_exists($appId)) {
1162
+                    $view->mkdir($appId);
1163
+                }
1164
+                return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1165
+            } else {
1166
+                \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1167
+                return false;
1168
+            }
1169
+        } else {
1170
+            \OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1171
+            return false;
1172
+        }
1173
+    }
1174
+
1175
+    protected static function findBestL10NOption($options, $lang) {
1176
+        $fallback = $similarLangFallback = $englishFallback = false;
1177
+
1178
+        $lang = strtolower($lang);
1179
+        $similarLang = $lang;
1180
+        if (strpos($similarLang, '_')) {
1181
+            // For "de_DE" we want to find "de" and the other way around
1182
+            $similarLang = substr($lang, 0, strpos($lang, '_'));
1183
+        }
1184
+
1185
+        foreach ($options as $option) {
1186
+            if (is_array($option)) {
1187
+                if ($fallback === false) {
1188
+                    $fallback = $option['@value'];
1189
+                }
1190
+
1191
+                if (!isset($option['@attributes']['lang'])) {
1192
+                    continue;
1193
+                }
1194
+
1195
+                $attributeLang = strtolower($option['@attributes']['lang']);
1196
+                if ($attributeLang === $lang) {
1197
+                    return $option['@value'];
1198
+                }
1199
+
1200
+                if ($attributeLang === $similarLang) {
1201
+                    $similarLangFallback = $option['@value'];
1202
+                } else if (strpos($attributeLang, $similarLang . '_') === 0) {
1203
+                    if ($similarLangFallback === false) {
1204
+                        $similarLangFallback =  $option['@value'];
1205
+                    }
1206
+                }
1207
+            } else {
1208
+                $englishFallback = $option;
1209
+            }
1210
+        }
1211
+
1212
+        if ($similarLangFallback !== false) {
1213
+            return $similarLangFallback;
1214
+        } else if ($englishFallback !== false) {
1215
+            return $englishFallback;
1216
+        }
1217
+        return (string) $fallback;
1218
+    }
1219
+
1220
+    /**
1221
+     * parses the app data array and enhanced the 'description' value
1222
+     *
1223
+     * @param array $data the app data
1224
+     * @param string $lang
1225
+     * @return array improved app data
1226
+     */
1227
+    public static function parseAppInfo(array $data, $lang = null) {
1228
+
1229
+        if ($lang && isset($data['name']) && is_array($data['name'])) {
1230
+            $data['name'] = self::findBestL10NOption($data['name'], $lang);
1231
+        }
1232
+        if ($lang && isset($data['summary']) && is_array($data['summary'])) {
1233
+            $data['summary'] = self::findBestL10NOption($data['summary'], $lang);
1234
+        }
1235
+        if ($lang && isset($data['description']) && is_array($data['description'])) {
1236
+            $data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1237
+        } else if (isset($data['description']) && is_string($data['description'])) {
1238
+            $data['description'] = trim($data['description']);
1239
+        } else  {
1240
+            $data['description'] = '';
1241
+        }
1242
+
1243
+        return $data;
1244
+    }
1245
+
1246
+    /**
1247
+     * @param \OCP\IConfig $config
1248
+     * @param \OCP\IL10N $l
1249
+     * @param array $info
1250
+     * @throws \Exception
1251
+     */
1252
+    public static function checkAppDependencies($config, $l, $info) {
1253
+        $dependencyAnalyzer = new DependencyAnalyzer(new Platform($config), $l);
1254
+        $missing = $dependencyAnalyzer->analyze($info);
1255
+        if (!empty($missing)) {
1256
+            $missingMsg = implode(PHP_EOL, $missing);
1257
+            throw new \Exception(
1258
+                $l->t('App "%s" cannot be installed because the following dependencies are not fulfilled: %s',
1259
+                    [$info['name'], $missingMsg]
1260
+                )
1261
+            );
1262
+        }
1263
+    }
1264 1264
 }
Please login to merge, or discard this patch.
Spacing   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -113,9 +113,9 @@  discard block
 block discarded – undo
113 113
 		$apps = self::getEnabledApps();
114 114
 
115 115
 		// Add each apps' folder as allowed class path
116
-		foreach($apps as $app) {
116
+		foreach ($apps as $app) {
117 117
 			$path = self::getAppPath($app);
118
-			if($path !== false) {
118
+			if ($path !== false) {
119 119
 				self::registerAutoloading($app, $path);
120 120
 			}
121 121
 		}
@@ -140,15 +140,15 @@  discard block
 block discarded – undo
140 140
 	public static function loadApp($app) {
141 141
 		self::$loadedApps[] = $app;
142 142
 		$appPath = self::getAppPath($app);
143
-		if($appPath === false) {
143
+		if ($appPath === false) {
144 144
 			return;
145 145
 		}
146 146
 
147 147
 		// in case someone calls loadApp() directly
148 148
 		self::registerAutoloading($app, $appPath);
149 149
 
150
-		if (is_file($appPath . '/appinfo/app.php')) {
151
-			\OC::$server->getEventLogger()->start('load_app_' . $app, 'Load app: ' . $app);
150
+		if (is_file($appPath.'/appinfo/app.php')) {
151
+			\OC::$server->getEventLogger()->start('load_app_'.$app, 'Load app: '.$app);
152 152
 			self::requireAppFile($app);
153 153
 			if (self::isType($app, array('authentication'))) {
154 154
 				// since authentication apps affect the "is app enabled for group" check,
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 				// enabled for groups
158 158
 				self::$enabledAppsCache = array();
159 159
 			}
160
-			\OC::$server->getEventLogger()->end('load_app_' . $app);
160
+			\OC::$server->getEventLogger()->end('load_app_'.$app);
161 161
 		}
162 162
 
163 163
 		$info = self::getAppInfo($app);
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 			$plugins = isset($info['collaboration']['plugins']['plugin']['@value']) ?
204 204
 				[$info['collaboration']['plugins']['plugin']] : $info['collaboration']['plugins']['plugin'];
205 205
 			foreach ($plugins as $plugin) {
206
-				if($plugin['@attributes']['type'] === 'collaborator-search') {
206
+				if ($plugin['@attributes']['type'] === 'collaborator-search') {
207 207
 					$pluginInfo = [
208 208
 						'shareType' => $plugin['@attributes']['share-type'],
209 209
 						'class' => $plugin['@value'],
@@ -222,8 +222,8 @@  discard block
 block discarded – undo
222 222
 	 * @param string $path
223 223
 	 */
224 224
 	public static function registerAutoloading($app, $path) {
225
-		$key = $app . '-' . $path;
226
-		if(isset(self::$alreadyRegistered[$key])) {
225
+		$key = $app.'-'.$path;
226
+		if (isset(self::$alreadyRegistered[$key])) {
227 227
 			return;
228 228
 		}
229 229
 
@@ -233,17 +233,17 @@  discard block
 block discarded – undo
233 233
 		$appNamespace = \OC\AppFramework\App::buildAppNamespace($app);
234 234
 		\OC::$server->registerNamespace($app, $appNamespace);
235 235
 
236
-		if (file_exists($path . '/composer/autoload.php')) {
237
-			require_once $path . '/composer/autoload.php';
236
+		if (file_exists($path.'/composer/autoload.php')) {
237
+			require_once $path.'/composer/autoload.php';
238 238
 		} else {
239
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\', $path . '/lib/', true);
239
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\', $path.'/lib/', true);
240 240
 			// Register on legacy autoloader
241 241
 			\OC::$loader->addValidRoot($path);
242 242
 		}
243 243
 
244 244
 		// Register Test namespace only when testing
245 245
 		if (defined('PHPUNIT_RUN') || defined('CLI_TEST_RUN')) {
246
-			\OC::$composerAutoloader->addPsr4($appNamespace . '\\Tests\\', $path . '/tests/', true);
246
+			\OC::$composerAutoloader->addPsr4($appNamespace.'\\Tests\\', $path.'/tests/', true);
247 247
 		}
248 248
 	}
249 249
 
@@ -255,7 +255,7 @@  discard block
 block discarded – undo
255 255
 	private static function requireAppFile($app) {
256 256
 		try {
257 257
 			// encapsulated here to avoid variable scope conflicts
258
-			require_once $app . '/appinfo/app.php';
258
+			require_once $app.'/appinfo/app.php';
259 259
 		} catch (Error $ex) {
260 260
 			\OC::$server->getLogger()->logException($ex);
261 261
 			if (!\OC::$server->getAppManager()->isShipped($app)) {
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 	 */
310 310
 	public static function setAppTypes($app) {
311 311
 		$appData = self::getAppInfo($app);
312
-		if(!is_array($appData)) {
312
+		if (!is_array($appData)) {
313 313
 			return;
314 314
 		}
315 315
 
@@ -361,8 +361,8 @@  discard block
 block discarded – undo
361 361
 		} else {
362 362
 			$apps = $appManager->getEnabledAppsForUser($user);
363 363
 		}
364
-		$apps = array_filter($apps, function ($app) {
365
-			return $app !== 'files';//we add this manually
364
+		$apps = array_filter($apps, function($app) {
365
+			return $app !== 'files'; //we add this manually
366 366
 		});
367 367
 		sort($apps);
368 368
 		array_unshift($apps, 'files');
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 		$installer = \OC::$server->query(Installer::class);
401 401
 		$isDownloaded = $installer->isDownloaded($appId);
402 402
 
403
-		if(!$isDownloaded) {
403
+		if (!$isDownloaded) {
404 404
 			$installer->downloadApp($appId);
405 405
 		}
406 406
 
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 	 */
514 514
 	public static function findAppInDirectories($appId) {
515 515
 		$sanitizedAppId = self::cleanAppId($appId);
516
-		if($sanitizedAppId !== $appId) {
516
+		if ($sanitizedAppId !== $appId) {
517 517
 			return false;
518 518
 		}
519 519
 		static $app_dir = array();
@@ -524,7 +524,7 @@  discard block
 block discarded – undo
524 524
 
525 525
 		$possibleApps = array();
526 526
 		foreach (OC::$APPSROOTS as $dir) {
527
-			if (file_exists($dir['path'] . '/' . $appId)) {
527
+			if (file_exists($dir['path'].'/'.$appId)) {
528 528
 				$possibleApps[] = $dir;
529 529
 			}
530 530
 		}
@@ -565,7 +565,7 @@  discard block
 block discarded – undo
565 565
 		}
566 566
 
567 567
 		if (($dir = self::findAppInDirectories($appId)) != false) {
568
-			return $dir['path'] . '/' . $appId;
568
+			return $dir['path'].'/'.$appId;
569 569
 		}
570 570
 		return false;
571 571
 	}
@@ -579,7 +579,7 @@  discard block
 block discarded – undo
579 579
 	 */
580 580
 	public static function getAppWebPath($appId) {
581 581
 		if (($dir = self::findAppInDirectories($appId)) != false) {
582
-			return OC::$WEBROOT . $dir['url'] . '/' . $appId;
582
+			return OC::$WEBROOT.$dir['url'].'/'.$appId;
583 583
 		}
584 584
 		return false;
585 585
 	}
@@ -592,7 +592,7 @@  discard block
 block discarded – undo
592 592
 	 * @return string
593 593
 	 */
594 594
 	public static function getAppVersion($appId, $useCache = true) {
595
-		if($useCache && isset(self::$appVersion[$appId])) {
595
+		if ($useCache && isset(self::$appVersion[$appId])) {
596 596
 			return self::$appVersion[$appId];
597 597
 		}
598 598
 
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 	 * @return string
609 609
 	 */
610 610
 	public static function getAppVersionByPath($path) {
611
-		$infoFile = $path . '/appinfo/info.xml';
611
+		$infoFile = $path.'/appinfo/info.xml';
612 612
 		$appData = self::getAppInfo($infoFile, true);
613 613
 		return isset($appData['version']) ? $appData['version'] : '';
614 614
 	}
@@ -631,10 +631,10 @@  discard block
 block discarded – undo
631 631
 				return self::$appInfo[$appId];
632 632
 			}
633 633
 			$appPath = self::getAppPath($appId);
634
-			if($appPath === false) {
634
+			if ($appPath === false) {
635 635
 				return null;
636 636
 			}
637
-			$file = $appPath . '/appinfo/info.xml';
637
+			$file = $appPath.'/appinfo/info.xml';
638 638
 		}
639 639
 
640 640
 		$parser = new InfoParser(\OC::$server->getMemCacheFactory()->createLocal('core.appinfo'));
@@ -643,9 +643,9 @@  discard block
 block discarded – undo
643 643
 		if (is_array($data)) {
644 644
 			$data = OC_App::parseAppInfo($data, $lang);
645 645
 		}
646
-		if(isset($data['ocsid'])) {
646
+		if (isset($data['ocsid'])) {
647 647
 			$storedId = \OC::$server->getConfig()->getAppValue($appId, 'ocsid');
648
-			if($storedId !== '' && $storedId !== $data['ocsid']) {
648
+			if ($storedId !== '' && $storedId !== $data['ocsid']) {
649 649
 				$data['ocsid'] = $storedId;
650 650
 			}
651 651
 		}
@@ -737,7 +737,7 @@  discard block
 block discarded – undo
737 737
 	 * @param string $page
738 738
 	 */
739 739
 	public static function registerAdmin($app, $page) {
740
-		self::$adminForms[] = $app . '/' . $page . '.php';
740
+		self::$adminForms[] = $app.'/'.$page.'.php';
741 741
 	}
742 742
 
743 743
 	/**
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
 	 * @param string $page
747 747
 	 */
748 748
 	public static function registerPersonal($app, $page) {
749
-		self::$personalForms[] = $app . '/' . $page . '.php';
749
+		self::$personalForms[] = $app.'/'.$page.'.php';
750 750
 	}
751 751
 
752 752
 	/**
@@ -775,7 +775,7 @@  discard block
 block discarded – undo
775 775
 
776 776
 		foreach (OC::$APPSROOTS as $apps_dir) {
777 777
 			if (!is_readable($apps_dir['path'])) {
778
-				\OCP\Util::writeLog('core', 'unable to read app folder : ' . $apps_dir['path'], \OCP\Util::WARN);
778
+				\OCP\Util::writeLog('core', 'unable to read app folder : '.$apps_dir['path'], \OCP\Util::WARN);
779 779
 				continue;
780 780
 			}
781 781
 			$dh = opendir($apps_dir['path']);
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
 			if (is_resource($dh)) {
784 784
 				while (($file = readdir($dh)) !== false) {
785 785
 
786
-					if ($file[0] != '.' and is_dir($apps_dir['path'] . '/' . $file) and is_file($apps_dir['path'] . '/' . $file . '/appinfo/info.xml')) {
786
+					if ($file[0] != '.' and is_dir($apps_dir['path'].'/'.$file) and is_file($apps_dir['path'].'/'.$file.'/appinfo/info.xml')) {
787 787
 
788 788
 						$apps[] = $file;
789 789
 					}
@@ -816,12 +816,12 @@  discard block
 block discarded – undo
816 816
 
817 817
 				$info = OC_App::getAppInfo($app, false, $langCode);
818 818
 				if (!is_array($info)) {
819
-					\OCP\Util::writeLog('core', 'Could not read app info file for app "' . $app . '"', \OCP\Util::ERROR);
819
+					\OCP\Util::writeLog('core', 'Could not read app info file for app "'.$app.'"', \OCP\Util::ERROR);
820 820
 					continue;
821 821
 				}
822 822
 
823 823
 				if (!isset($info['name'])) {
824
-					\OCP\Util::writeLog('core', 'App id "' . $app . '" has no name in appinfo', \OCP\Util::ERROR);
824
+					\OCP\Util::writeLog('core', 'App id "'.$app.'" has no name in appinfo', \OCP\Util::ERROR);
825 825
 					continue;
826 826
 				}
827 827
 
@@ -848,13 +848,13 @@  discard block
 block discarded – undo
848 848
 				}
849 849
 
850 850
 				$appPath = self::getAppPath($app);
851
-				if($appPath !== false) {
852
-					$appIcon = $appPath . '/img/' . $app . '.svg';
851
+				if ($appPath !== false) {
852
+					$appIcon = $appPath.'/img/'.$app.'.svg';
853 853
 					if (file_exists($appIcon)) {
854
-						$info['preview'] = $urlGenerator->imagePath($app, $app . '.svg');
854
+						$info['preview'] = $urlGenerator->imagePath($app, $app.'.svg');
855 855
 						$info['previewAsIcon'] = true;
856 856
 					} else {
857
-						$appIcon = $appPath . '/img/app.svg';
857
+						$appIcon = $appPath.'/img/app.svg';
858 858
 						if (file_exists($appIcon)) {
859 859
 							$info['preview'] = $urlGenerator->imagePath($app, 'app.svg');
860 860
 							$info['previewAsIcon'] = true;
@@ -979,7 +979,7 @@  discard block
 block discarded – undo
979 979
 	public static function getAppVersions() {
980 980
 		static $versions;
981 981
 
982
-		if(!$versions) {
982
+		if (!$versions) {
983 983
 			$appConfig = \OC::$server->getAppConfig();
984 984
 			$versions = $appConfig->getValues(false, 'installed_version');
985 985
 		}
@@ -1001,7 +1001,7 @@  discard block
 block discarded – undo
1001 1001
 		if ($app !== false) {
1002 1002
 			// check if the app is compatible with this version of ownCloud
1003 1003
 			$info = self::getAppInfo($app);
1004
-			if(!is_array($info)) {
1004
+			if (!is_array($info)) {
1005 1005
 				throw new \Exception(
1006 1006
 					$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
1007 1007
 						[$info['name']]
@@ -1026,14 +1026,14 @@  discard block
 block discarded – undo
1026 1026
 				$config->setAppValue($app, 'ocsid', $appData['id']);
1027 1027
 			}
1028 1028
 
1029
-			if(isset($info['settings']) && is_array($info['settings'])) {
1029
+			if (isset($info['settings']) && is_array($info['settings'])) {
1030 1030
 				$appPath = self::getAppPath($app);
1031 1031
 				self::registerAutoloading($app, $appPath);
1032 1032
 			}
1033 1033
 
1034 1034
 			\OC_Hook::emit('OC_App', 'post_enable', array('app' => $app));
1035 1035
 		} else {
1036
-			if(empty($appName) ) {
1036
+			if (empty($appName)) {
1037 1037
 				throw new \Exception($l->t("No app name specified"));
1038 1038
 			} else {
1039 1039
 				throw new \Exception($l->t("App '%s' could not be installed!", $appName));
@@ -1051,7 +1051,7 @@  discard block
 block discarded – undo
1051 1051
 	 */
1052 1052
 	public static function updateApp($appId) {
1053 1053
 		$appPath = self::getAppPath($appId);
1054
-		if($appPath === false) {
1054
+		if ($appPath === false) {
1055 1055
 			return false;
1056 1056
 		}
1057 1057
 		self::registerAutoloading($appId, $appPath);
@@ -1059,8 +1059,8 @@  discard block
 block discarded – undo
1059 1059
 		$appData = self::getAppInfo($appId);
1060 1060
 		self::executeRepairSteps($appId, $appData['repair-steps']['pre-migration']);
1061 1061
 
1062
-		if (file_exists($appPath . '/appinfo/database.xml')) {
1063
-			OC_DB::updateDbFromStructure($appPath . '/appinfo/database.xml');
1062
+		if (file_exists($appPath.'/appinfo/database.xml')) {
1063
+			OC_DB::updateDbFromStructure($appPath.'/appinfo/database.xml');
1064 1064
 		} else {
1065 1065
 			$ms = new MigrationService($appId, \OC::$server->getDatabaseConnection());
1066 1066
 			$ms->migrate();
@@ -1071,23 +1071,23 @@  discard block
 block discarded – undo
1071 1071
 		unset(self::$appVersion[$appId]);
1072 1072
 
1073 1073
 		// run upgrade code
1074
-		if (file_exists($appPath . '/appinfo/update.php')) {
1074
+		if (file_exists($appPath.'/appinfo/update.php')) {
1075 1075
 			self::loadApp($appId);
1076
-			include $appPath . '/appinfo/update.php';
1076
+			include $appPath.'/appinfo/update.php';
1077 1077
 		}
1078 1078
 		self::setupBackgroundJobs($appData['background-jobs']);
1079 1079
 
1080 1080
 		//set remote/public handlers
1081 1081
 		if (array_key_exists('ocsid', $appData)) {
1082 1082
 			\OC::$server->getConfig()->setAppValue($appId, 'ocsid', $appData['ocsid']);
1083
-		} elseif(\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1083
+		} elseif (\OC::$server->getConfig()->getAppValue($appId, 'ocsid', null) !== null) {
1084 1084
 			\OC::$server->getConfig()->deleteAppValue($appId, 'ocsid');
1085 1085
 		}
1086 1086
 		foreach ($appData['remote'] as $name => $path) {
1087
-			\OC::$server->getConfig()->setAppValue('core', 'remote_' . $name, $appId . '/' . $path);
1087
+			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $appId.'/'.$path);
1088 1088
 		}
1089 1089
 		foreach ($appData['public'] as $name => $path) {
1090
-			\OC::$server->getConfig()->setAppValue('core', 'public_' . $name, $appId . '/' . $path);
1090
+			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $appId.'/'.$path);
1091 1091
 		}
1092 1092
 
1093 1093
 		self::setAppTypes($appId);
@@ -1157,17 +1157,17 @@  discard block
 block discarded – undo
1157 1157
 	public static function getStorage($appId) {
1158 1158
 		if (\OC::$server->getAppManager()->isEnabledForUser($appId)) { //sanity check
1159 1159
 			if (\OC::$server->getUserSession()->isLoggedIn()) {
1160
-				$view = new \OC\Files\View('/' . OC_User::getUser());
1160
+				$view = new \OC\Files\View('/'.OC_User::getUser());
1161 1161
 				if (!$view->file_exists($appId)) {
1162 1162
 					$view->mkdir($appId);
1163 1163
 				}
1164
-				return new \OC\Files\View('/' . OC_User::getUser() . '/' . $appId);
1164
+				return new \OC\Files\View('/'.OC_User::getUser().'/'.$appId);
1165 1165
 			} else {
1166
-				\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ', user not logged in', \OCP\Util::ERROR);
1166
+				\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.', user not logged in', \OCP\Util::ERROR);
1167 1167
 				return false;
1168 1168
 			}
1169 1169
 		} else {
1170
-			\OCP\Util::writeLog('core', 'Can\'t get app storage, app ' . $appId . ' not enabled', \OCP\Util::ERROR);
1170
+			\OCP\Util::writeLog('core', 'Can\'t get app storage, app '.$appId.' not enabled', \OCP\Util::ERROR);
1171 1171
 			return false;
1172 1172
 		}
1173 1173
 	}
@@ -1199,9 +1199,9 @@  discard block
 block discarded – undo
1199 1199
 
1200 1200
 				if ($attributeLang === $similarLang) {
1201 1201
 					$similarLangFallback = $option['@value'];
1202
-				} else if (strpos($attributeLang, $similarLang . '_') === 0) {
1202
+				} else if (strpos($attributeLang, $similarLang.'_') === 0) {
1203 1203
 					if ($similarLangFallback === false) {
1204
-						$similarLangFallback =  $option['@value'];
1204
+						$similarLangFallback = $option['@value'];
1205 1205
 					}
1206 1206
 				}
1207 1207
 			} else {
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 			$data['description'] = trim(self::findBestL10NOption($data['description'], $lang));
1237 1237
 		} else if (isset($data['description']) && is_string($data['description'])) {
1238 1238
 			$data['description'] = trim($data['description']);
1239
-		} else  {
1239
+		} else {
1240 1240
 			$data['description'] = '';
1241 1241
 		}
1242 1242
 
Please login to merge, or discard this patch.
lib/private/Installer.php 2 patches
Indentation   +556 added lines, -556 removed lines patch added patch discarded remove patch
@@ -57,560 +57,560 @@
 block discarded – undo
57 57
  * This class provides the functionality needed to install, update and remove apps
58 58
  */
59 59
 class Installer {
60
-	/** @var AppFetcher */
61
-	private $appFetcher;
62
-	/** @var IClientService */
63
-	private $clientService;
64
-	/** @var ITempManager */
65
-	private $tempManager;
66
-	/** @var ILogger */
67
-	private $logger;
68
-	/** @var IConfig */
69
-	private $config;
70
-	/** @var array - for caching the result of app fetcher */
71
-	private $apps = null;
72
-	/** @var bool|null - for caching the result of the ready status */
73
-	private $isInstanceReadyForUpdates = null;
74
-
75
-	/**
76
-	 * @param AppFetcher $appFetcher
77
-	 * @param IClientService $clientService
78
-	 * @param ITempManager $tempManager
79
-	 * @param ILogger $logger
80
-	 * @param IConfig $config
81
-	 */
82
-	public function __construct(AppFetcher $appFetcher,
83
-								IClientService $clientService,
84
-								ITempManager $tempManager,
85
-								ILogger $logger,
86
-								IConfig $config) {
87
-		$this->appFetcher = $appFetcher;
88
-		$this->clientService = $clientService;
89
-		$this->tempManager = $tempManager;
90
-		$this->logger = $logger;
91
-		$this->config = $config;
92
-	}
93
-
94
-	/**
95
-	 * Installs an app that is located in one of the app folders already
96
-	 *
97
-	 * @param string $appId App to install
98
-	 * @throws \Exception
99
-	 * @return string app ID
100
-	 */
101
-	public function installApp($appId) {
102
-		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
104
-			throw new \Exception('App not found in any app directory');
105
-		}
106
-
107
-		$basedir = $app['path'].'/'.$appId;
108
-		$info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
-
110
-		$l = \OC::$server->getL10N('core');
111
-
112
-		if(!is_array($info)) {
113
-			throw new \Exception(
114
-				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
-					[$info['name']]
116
-				)
117
-			);
118
-		}
119
-
120
-		$version = \OCP\Util::getVersion();
121
-		if (!\OC_App::isAppCompatible($version, $info)) {
122
-			throw new \Exception(
123
-				// TODO $l
124
-				$l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
-					[$info['name']]
126
-				)
127
-			);
128
-		}
129
-
130
-		// check for required dependencies
131
-		\OC_App::checkAppDependencies($this->config, $l, $info);
132
-		\OC_App::registerAutoloading($appId, $basedir);
133
-
134
-		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
136
-			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137
-				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
-			} else {
139
-				OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
-			}
141
-		} else {
142
-			$ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
-			$ms->migrate();
144
-		}
145
-
146
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
147
-
148
-		//run appinfo/install.php
149
-		if(!isset($data['noinstall']) or $data['noinstall']==false) {
150
-			self::includeAppScript($basedir . '/appinfo/install.php');
151
-		}
152
-
153
-		$appData = OC_App::getAppInfo($appId);
154
-		OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
155
-
156
-		//set the installed version
157
-		\OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
158
-		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
159
-
160
-		//set remote/public handlers
161
-		foreach($info['remote'] as $name=>$path) {
162
-			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
163
-		}
164
-		foreach($info['public'] as $name=>$path) {
165
-			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
166
-		}
167
-
168
-		OC_App::setAppTypes($info['id']);
169
-
170
-		return $info['id'];
171
-	}
172
-
173
-	/**
174
-	 * @brief checks whether or not an app is installed
175
-	 * @param string $app app
176
-	 * @returns bool
177
-	 *
178
-	 * Checks whether or not an app is installed, i.e. registered in apps table.
179
-	 */
180
-	public static function isInstalled( $app ) {
181
-		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
182
-	}
183
-
184
-	/**
185
-	 * Updates the specified app from the appstore
186
-	 *
187
-	 * @param string $appId
188
-	 * @return bool
189
-	 */
190
-	public function updateAppstoreApp($appId) {
191
-		if($this->isUpdateAvailable($appId)) {
192
-			try {
193
-				$this->downloadApp($appId);
194
-			} catch (\Exception $e) {
195
-				$this->logger->logException($e, [
196
-					'level' => \OCP\Util::ERROR,
197
-					'app' => 'core',
198
-				]);
199
-				return false;
200
-			}
201
-			return OC_App::updateApp($appId);
202
-		}
203
-
204
-		return false;
205
-	}
206
-
207
-	/**
208
-	 * Downloads an app and puts it into the app directory
209
-	 *
210
-	 * @param string $appId
211
-	 *
212
-	 * @throws \Exception If the installation was not successful
213
-	 */
214
-	public function downloadApp($appId) {
215
-		$appId = strtolower($appId);
216
-
217
-		$apps = $this->appFetcher->get();
218
-		foreach($apps as $app) {
219
-			if($app['id'] === $appId) {
220
-				// Load the certificate
221
-				$certificate = new X509();
222
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
223
-				$loadedCertificate = $certificate->loadX509($app['certificate']);
224
-
225
-				// Verify if the certificate has been revoked
226
-				$crl = new X509();
227
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
-				if($crl->validateSignature() !== true) {
230
-					throw new \Exception('Could not validate CRL signature');
231
-				}
232
-				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
233
-				$revoked = $crl->getRevoked($csn);
234
-				if ($revoked !== false) {
235
-					throw new \Exception(
236
-						sprintf(
237
-							'Certificate "%s" has been revoked',
238
-							$csn
239
-						)
240
-					);
241
-				}
242
-
243
-				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
-				if($certificate->validateSignature() !== true) {
245
-					throw new \Exception(
246
-						sprintf(
247
-							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
248
-							$appId
249
-						)
250
-					);
251
-				}
252
-
253
-				// Verify if the certificate is issued for the requested app id
254
-				$certInfo = openssl_x509_parse($app['certificate']);
255
-				if(!isset($certInfo['subject']['CN'])) {
256
-					throw new \Exception(
257
-						sprintf(
258
-							'App with id %s has a cert with no CN',
259
-							$appId
260
-						)
261
-					);
262
-				}
263
-				if($certInfo['subject']['CN'] !== $appId) {
264
-					throw new \Exception(
265
-						sprintf(
266
-							'App with id %s has a cert issued to %s',
267
-							$appId,
268
-							$certInfo['subject']['CN']
269
-						)
270
-					);
271
-				}
272
-
273
-				// Download the release
274
-				$tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
275
-				$client = $this->clientService->newClient();
276
-				$client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
277
-
278
-				// Check if the signature actually matches the downloaded content
279
-				$certificate = openssl_get_publickey($app['certificate']);
280
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281
-				openssl_free_key($certificate);
282
-
283
-				if($verified === true) {
284
-					// Seems to match, let's proceed
285
-					$extractDir = $this->tempManager->getTemporaryFolder();
286
-					$archive = new TAR($tempFile);
287
-
288
-					if($archive) {
289
-						if (!$archive->extract($extractDir)) {
290
-							throw new \Exception(
291
-								sprintf(
292
-									'Could not extract app %s',
293
-									$appId
294
-								)
295
-							);
296
-						}
297
-						$allFiles = scandir($extractDir);
298
-						$folders = array_diff($allFiles, ['.', '..']);
299
-						$folders = array_values($folders);
300
-
301
-						if(count($folders) > 1) {
302
-							throw new \Exception(
303
-								sprintf(
304
-									'Extracted app %s has more than 1 folder',
305
-									$appId
306
-								)
307
-							);
308
-						}
309
-
310
-						// Check if appinfo/info.xml has the same app ID as well
311
-						$loadEntities = libxml_disable_entity_loader(false);
312
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
313
-						libxml_disable_entity_loader($loadEntities);
314
-						if((string)$xml->id !== $appId) {
315
-							throw new \Exception(
316
-								sprintf(
317
-									'App for id %s has a wrong app ID in info.xml: %s',
318
-									$appId,
319
-									(string)$xml->id
320
-								)
321
-							);
322
-						}
323
-
324
-						// Check if the version is lower than before
325
-						$currentVersion = OC_App::getAppVersion($appId);
326
-						$newVersion = (string)$xml->version;
327
-						if(version_compare($currentVersion, $newVersion) === 1) {
328
-							throw new \Exception(
329
-								sprintf(
330
-									'App for id %s has version %s and tried to update to lower version %s',
331
-									$appId,
332
-									$currentVersion,
333
-									$newVersion
334
-								)
335
-							);
336
-						}
337
-
338
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
339
-						// Remove old app with the ID if existent
340
-						OC_Helper::rmdirr($baseDir);
341
-						// Move to app folder
342
-						if(@mkdir($baseDir)) {
343
-							$extractDir .= '/' . $folders[0];
344
-							OC_Helper::copyr($extractDir, $baseDir);
345
-						}
346
-						OC_Helper::copyr($extractDir, $baseDir);
347
-						OC_Helper::rmdirr($extractDir);
348
-						return;
349
-					} else {
350
-						throw new \Exception(
351
-							sprintf(
352
-								'Could not extract app with ID %s to %s',
353
-								$appId,
354
-								$extractDir
355
-							)
356
-						);
357
-					}
358
-				} else {
359
-					// Signature does not match
360
-					throw new \Exception(
361
-						sprintf(
362
-							'App with id %s has invalid signature',
363
-							$appId
364
-						)
365
-					);
366
-				}
367
-			}
368
-		}
369
-
370
-		throw new \Exception(
371
-			sprintf(
372
-				'Could not download app %s',
373
-				$appId
374
-			)
375
-		);
376
-	}
377
-
378
-	/**
379
-	 * Check if an update for the app is available
380
-	 *
381
-	 * @param string $appId
382
-	 * @return string|false false or the version number of the update
383
-	 */
384
-	public function isUpdateAvailable($appId) {
385
-		if ($this->isInstanceReadyForUpdates === null) {
386
-			$installPath = OC_App::getInstallPath();
387
-			if ($installPath === false || $installPath === null) {
388
-				$this->isInstanceReadyForUpdates = false;
389
-			} else {
390
-				$this->isInstanceReadyForUpdates = true;
391
-			}
392
-		}
393
-
394
-		if ($this->isInstanceReadyForUpdates === false) {
395
-			return false;
396
-		}
397
-
398
-		if ($this->isInstalledFromGit($appId) === true) {
399
-			return false;
400
-		}
401
-
402
-		if ($this->apps === null) {
403
-			$this->apps = $this->appFetcher->get();
404
-		}
405
-
406
-		foreach($this->apps as $app) {
407
-			if($app['id'] === $appId) {
408
-				$currentVersion = OC_App::getAppVersion($appId);
409
-				$newestVersion = $app['releases'][0]['version'];
410
-				if (version_compare($newestVersion, $currentVersion, '>')) {
411
-					return $newestVersion;
412
-				} else {
413
-					return false;
414
-				}
415
-			}
416
-		}
417
-
418
-		return false;
419
-	}
420
-
421
-	/**
422
-	 * Check if app has been installed from git
423
-	 * @param string $name name of the application to remove
424
-	 * @return boolean
425
-	 *
426
-	 * The function will check if the path contains a .git folder
427
-	 */
428
-	private function isInstalledFromGit($appId) {
429
-		$app = \OC_App::findAppInDirectories($appId);
430
-		if($app === false) {
431
-			return false;
432
-		}
433
-		$basedir = $app['path'].'/'.$appId;
434
-		return file_exists($basedir.'/.git/');
435
-	}
436
-
437
-	/**
438
-	 * Check if app is already downloaded
439
-	 * @param string $name name of the application to remove
440
-	 * @return boolean
441
-	 *
442
-	 * The function will check if the app is already downloaded in the apps repository
443
-	 */
444
-	public function isDownloaded($name) {
445
-		foreach(\OC::$APPSROOTS as $dir) {
446
-			$dirToTest  = $dir['path'];
447
-			$dirToTest .= '/';
448
-			$dirToTest .= $name;
449
-			$dirToTest .= '/';
450
-
451
-			if (is_dir($dirToTest)) {
452
-				return true;
453
-			}
454
-		}
455
-
456
-		return false;
457
-	}
458
-
459
-	/**
460
-	 * Removes an app
461
-	 * @param string $appId ID of the application to remove
462
-	 * @return boolean
463
-	 *
464
-	 *
465
-	 * This function works as follows
466
-	 *   -# call uninstall repair steps
467
-	 *   -# removing the files
468
-	 *
469
-	 * The function will not delete preferences, tables and the configuration,
470
-	 * this has to be done by the function oc_app_uninstall().
471
-	 */
472
-	public function removeApp($appId) {
473
-		if($this->isDownloaded( $appId )) {
474
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
475
-			OC_Helper::rmdirr($appDir);
476
-			return true;
477
-		}else{
478
-			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
479
-
480
-			return false;
481
-		}
482
-
483
-	}
484
-
485
-	/**
486
-	 * Installs the app within the bundle and marks the bundle as installed
487
-	 *
488
-	 * @param Bundle $bundle
489
-	 * @throws \Exception If app could not get installed
490
-	 */
491
-	public function installAppBundle(Bundle $bundle) {
492
-		$appIds = $bundle->getAppIdentifiers();
493
-		foreach($appIds as $appId) {
494
-			if(!$this->isDownloaded($appId)) {
495
-				$this->downloadApp($appId);
496
-			}
497
-			$this->installApp($appId);
498
-			$app = new OC_App();
499
-			$app->enable($appId);
500
-		}
501
-		$bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
502
-		$bundles[] = $bundle->getIdentifier();
503
-		$this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
504
-	}
505
-
506
-	/**
507
-	 * Installs shipped apps
508
-	 *
509
-	 * This function installs all apps found in the 'apps' directory that should be enabled by default;
510
-	 * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
511
-	 *                         working ownCloud at the end instead of an aborted update.
512
-	 * @return array Array of error messages (appid => Exception)
513
-	 */
514
-	public static function installShippedApps($softErrors = false) {
515
-		$errors = [];
516
-		foreach(\OC::$APPSROOTS as $app_dir) {
517
-			if($dir = opendir( $app_dir['path'] )) {
518
-				while( false !== ( $filename = readdir( $dir ))) {
519
-					if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
520
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
521
-							if(!Installer::isInstalled($filename)) {
522
-								$info=OC_App::getAppInfo($filename);
523
-								$enabled = isset($info['default_enable']);
524
-								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
525
-									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
526
-									if ($softErrors) {
527
-										try {
528
-											Installer::installShippedApp($filename);
529
-										} catch (HintException $e) {
530
-											if ($e->getPrevious() instanceof TableExistsException) {
531
-												$errors[$filename] = $e;
532
-												continue;
533
-											}
534
-											throw $e;
535
-										}
536
-									} else {
537
-										Installer::installShippedApp($filename);
538
-									}
539
-									\OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
540
-								}
541
-							}
542
-						}
543
-					}
544
-				}
545
-				closedir( $dir );
546
-			}
547
-		}
548
-
549
-		return $errors;
550
-	}
551
-
552
-	/**
553
-	 * install an app already placed in the app folder
554
-	 * @param string $app id of the app to install
555
-	 * @return integer
556
-	 */
557
-	public static function installShippedApp($app) {
558
-		//install the database
559
-		$appPath = OC_App::getAppPath($app);
560
-		\OC_App::registerAutoloading($app, $appPath);
561
-
562
-		if(is_file("$appPath/appinfo/database.xml")) {
563
-			try {
564
-				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
565
-			} catch (TableExistsException $e) {
566
-				throw new HintException(
567
-					'Failed to enable app ' . $app,
568
-					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
569
-					0, $e
570
-				);
571
-			}
572
-		} else {
573
-			$ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
574
-			$ms->migrate();
575
-		}
576
-
577
-		//run appinfo/install.php
578
-		self::includeAppScript("$appPath/appinfo/install.php");
579
-
580
-		$info = OC_App::getAppInfo($app);
581
-		if (is_null($info)) {
582
-			return false;
583
-		}
584
-		\OC_App::setupBackgroundJobs($info['background-jobs']);
585
-
586
-		OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
587
-
588
-		$config = \OC::$server->getConfig();
589
-
590
-		$config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
591
-		if (array_key_exists('ocsid', $info)) {
592
-			$config->setAppValue($app, 'ocsid', $info['ocsid']);
593
-		}
594
-
595
-		//set remote/public handlers
596
-		foreach($info['remote'] as $name=>$path) {
597
-			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
598
-		}
599
-		foreach($info['public'] as $name=>$path) {
600
-			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
601
-		}
602
-
603
-		OC_App::setAppTypes($info['id']);
604
-
605
-		return $info['id'];
606
-	}
607
-
608
-	/**
609
-	 * @param string $script
610
-	 */
611
-	private static function includeAppScript($script) {
612
-		if ( file_exists($script) ){
613
-			include $script;
614
-		}
615
-	}
60
+    /** @var AppFetcher */
61
+    private $appFetcher;
62
+    /** @var IClientService */
63
+    private $clientService;
64
+    /** @var ITempManager */
65
+    private $tempManager;
66
+    /** @var ILogger */
67
+    private $logger;
68
+    /** @var IConfig */
69
+    private $config;
70
+    /** @var array - for caching the result of app fetcher */
71
+    private $apps = null;
72
+    /** @var bool|null - for caching the result of the ready status */
73
+    private $isInstanceReadyForUpdates = null;
74
+
75
+    /**
76
+     * @param AppFetcher $appFetcher
77
+     * @param IClientService $clientService
78
+     * @param ITempManager $tempManager
79
+     * @param ILogger $logger
80
+     * @param IConfig $config
81
+     */
82
+    public function __construct(AppFetcher $appFetcher,
83
+                                IClientService $clientService,
84
+                                ITempManager $tempManager,
85
+                                ILogger $logger,
86
+                                IConfig $config) {
87
+        $this->appFetcher = $appFetcher;
88
+        $this->clientService = $clientService;
89
+        $this->tempManager = $tempManager;
90
+        $this->logger = $logger;
91
+        $this->config = $config;
92
+    }
93
+
94
+    /**
95
+     * Installs an app that is located in one of the app folders already
96
+     *
97
+     * @param string $appId App to install
98
+     * @throws \Exception
99
+     * @return string app ID
100
+     */
101
+    public function installApp($appId) {
102
+        $app = \OC_App::findAppInDirectories($appId);
103
+        if($app === false) {
104
+            throw new \Exception('App not found in any app directory');
105
+        }
106
+
107
+        $basedir = $app['path'].'/'.$appId;
108
+        $info = OC_App::getAppInfo($basedir.'/appinfo/info.xml', true);
109
+
110
+        $l = \OC::$server->getL10N('core');
111
+
112
+        if(!is_array($info)) {
113
+            throw new \Exception(
114
+                $l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115
+                    [$info['name']]
116
+                )
117
+            );
118
+        }
119
+
120
+        $version = \OCP\Util::getVersion();
121
+        if (!\OC_App::isAppCompatible($version, $info)) {
122
+            throw new \Exception(
123
+                // TODO $l
124
+                $l->t('App "%s" cannot be installed because it is not compatible with this version of the server.',
125
+                    [$info['name']]
126
+                )
127
+            );
128
+        }
129
+
130
+        // check for required dependencies
131
+        \OC_App::checkAppDependencies($this->config, $l, $info);
132
+        \OC_App::registerAutoloading($appId, $basedir);
133
+
134
+        //install the database
135
+        if(is_file($basedir.'/appinfo/database.xml')) {
136
+            if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137
+                OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138
+            } else {
139
+                OC_DB::updateDbFromStructure($basedir.'/appinfo/database.xml');
140
+            }
141
+        } else {
142
+            $ms = new \OC\DB\MigrationService($info['id'], \OC::$server->getDatabaseConnection());
143
+            $ms->migrate();
144
+        }
145
+
146
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
147
+
148
+        //run appinfo/install.php
149
+        if(!isset($data['noinstall']) or $data['noinstall']==false) {
150
+            self::includeAppScript($basedir . '/appinfo/install.php');
151
+        }
152
+
153
+        $appData = OC_App::getAppInfo($appId);
154
+        OC_App::executeRepairSteps($appId, $appData['repair-steps']['install']);
155
+
156
+        //set the installed version
157
+        \OC::$server->getConfig()->setAppValue($info['id'], 'installed_version', OC_App::getAppVersion($info['id'], false));
158
+        \OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
159
+
160
+        //set remote/public handlers
161
+        foreach($info['remote'] as $name=>$path) {
162
+            \OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
163
+        }
164
+        foreach($info['public'] as $name=>$path) {
165
+            \OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
166
+        }
167
+
168
+        OC_App::setAppTypes($info['id']);
169
+
170
+        return $info['id'];
171
+    }
172
+
173
+    /**
174
+     * @brief checks whether or not an app is installed
175
+     * @param string $app app
176
+     * @returns bool
177
+     *
178
+     * Checks whether or not an app is installed, i.e. registered in apps table.
179
+     */
180
+    public static function isInstalled( $app ) {
181
+        return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
182
+    }
183
+
184
+    /**
185
+     * Updates the specified app from the appstore
186
+     *
187
+     * @param string $appId
188
+     * @return bool
189
+     */
190
+    public function updateAppstoreApp($appId) {
191
+        if($this->isUpdateAvailable($appId)) {
192
+            try {
193
+                $this->downloadApp($appId);
194
+            } catch (\Exception $e) {
195
+                $this->logger->logException($e, [
196
+                    'level' => \OCP\Util::ERROR,
197
+                    'app' => 'core',
198
+                ]);
199
+                return false;
200
+            }
201
+            return OC_App::updateApp($appId);
202
+        }
203
+
204
+        return false;
205
+    }
206
+
207
+    /**
208
+     * Downloads an app and puts it into the app directory
209
+     *
210
+     * @param string $appId
211
+     *
212
+     * @throws \Exception If the installation was not successful
213
+     */
214
+    public function downloadApp($appId) {
215
+        $appId = strtolower($appId);
216
+
217
+        $apps = $this->appFetcher->get();
218
+        foreach($apps as $app) {
219
+            if($app['id'] === $appId) {
220
+                // Load the certificate
221
+                $certificate = new X509();
222
+                $certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
223
+                $loadedCertificate = $certificate->loadX509($app['certificate']);
224
+
225
+                // Verify if the certificate has been revoked
226
+                $crl = new X509();
227
+                $crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
+                $crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
+                if($crl->validateSignature() !== true) {
230
+                    throw new \Exception('Could not validate CRL signature');
231
+                }
232
+                $csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
233
+                $revoked = $crl->getRevoked($csn);
234
+                if ($revoked !== false) {
235
+                    throw new \Exception(
236
+                        sprintf(
237
+                            'Certificate "%s" has been revoked',
238
+                            $csn
239
+                        )
240
+                    );
241
+                }
242
+
243
+                // Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
+                if($certificate->validateSignature() !== true) {
245
+                    throw new \Exception(
246
+                        sprintf(
247
+                            'App with id %s has a certificate not issued by a trusted Code Signing Authority',
248
+                            $appId
249
+                        )
250
+                    );
251
+                }
252
+
253
+                // Verify if the certificate is issued for the requested app id
254
+                $certInfo = openssl_x509_parse($app['certificate']);
255
+                if(!isset($certInfo['subject']['CN'])) {
256
+                    throw new \Exception(
257
+                        sprintf(
258
+                            'App with id %s has a cert with no CN',
259
+                            $appId
260
+                        )
261
+                    );
262
+                }
263
+                if($certInfo['subject']['CN'] !== $appId) {
264
+                    throw new \Exception(
265
+                        sprintf(
266
+                            'App with id %s has a cert issued to %s',
267
+                            $appId,
268
+                            $certInfo['subject']['CN']
269
+                        )
270
+                    );
271
+                }
272
+
273
+                // Download the release
274
+                $tempFile = $this->tempManager->getTemporaryFile('.tar.gz');
275
+                $client = $this->clientService->newClient();
276
+                $client->get($app['releases'][0]['download'], ['save_to' => $tempFile]);
277
+
278
+                // Check if the signature actually matches the downloaded content
279
+                $certificate = openssl_get_publickey($app['certificate']);
280
+                $verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281
+                openssl_free_key($certificate);
282
+
283
+                if($verified === true) {
284
+                    // Seems to match, let's proceed
285
+                    $extractDir = $this->tempManager->getTemporaryFolder();
286
+                    $archive = new TAR($tempFile);
287
+
288
+                    if($archive) {
289
+                        if (!$archive->extract($extractDir)) {
290
+                            throw new \Exception(
291
+                                sprintf(
292
+                                    'Could not extract app %s',
293
+                                    $appId
294
+                                )
295
+                            );
296
+                        }
297
+                        $allFiles = scandir($extractDir);
298
+                        $folders = array_diff($allFiles, ['.', '..']);
299
+                        $folders = array_values($folders);
300
+
301
+                        if(count($folders) > 1) {
302
+                            throw new \Exception(
303
+                                sprintf(
304
+                                    'Extracted app %s has more than 1 folder',
305
+                                    $appId
306
+                                )
307
+                            );
308
+                        }
309
+
310
+                        // Check if appinfo/info.xml has the same app ID as well
311
+                        $loadEntities = libxml_disable_entity_loader(false);
312
+                        $xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
313
+                        libxml_disable_entity_loader($loadEntities);
314
+                        if((string)$xml->id !== $appId) {
315
+                            throw new \Exception(
316
+                                sprintf(
317
+                                    'App for id %s has a wrong app ID in info.xml: %s',
318
+                                    $appId,
319
+                                    (string)$xml->id
320
+                                )
321
+                            );
322
+                        }
323
+
324
+                        // Check if the version is lower than before
325
+                        $currentVersion = OC_App::getAppVersion($appId);
326
+                        $newVersion = (string)$xml->version;
327
+                        if(version_compare($currentVersion, $newVersion) === 1) {
328
+                            throw new \Exception(
329
+                                sprintf(
330
+                                    'App for id %s has version %s and tried to update to lower version %s',
331
+                                    $appId,
332
+                                    $currentVersion,
333
+                                    $newVersion
334
+                                )
335
+                            );
336
+                        }
337
+
338
+                        $baseDir = OC_App::getInstallPath() . '/' . $appId;
339
+                        // Remove old app with the ID if existent
340
+                        OC_Helper::rmdirr($baseDir);
341
+                        // Move to app folder
342
+                        if(@mkdir($baseDir)) {
343
+                            $extractDir .= '/' . $folders[0];
344
+                            OC_Helper::copyr($extractDir, $baseDir);
345
+                        }
346
+                        OC_Helper::copyr($extractDir, $baseDir);
347
+                        OC_Helper::rmdirr($extractDir);
348
+                        return;
349
+                    } else {
350
+                        throw new \Exception(
351
+                            sprintf(
352
+                                'Could not extract app with ID %s to %s',
353
+                                $appId,
354
+                                $extractDir
355
+                            )
356
+                        );
357
+                    }
358
+                } else {
359
+                    // Signature does not match
360
+                    throw new \Exception(
361
+                        sprintf(
362
+                            'App with id %s has invalid signature',
363
+                            $appId
364
+                        )
365
+                    );
366
+                }
367
+            }
368
+        }
369
+
370
+        throw new \Exception(
371
+            sprintf(
372
+                'Could not download app %s',
373
+                $appId
374
+            )
375
+        );
376
+    }
377
+
378
+    /**
379
+     * Check if an update for the app is available
380
+     *
381
+     * @param string $appId
382
+     * @return string|false false or the version number of the update
383
+     */
384
+    public function isUpdateAvailable($appId) {
385
+        if ($this->isInstanceReadyForUpdates === null) {
386
+            $installPath = OC_App::getInstallPath();
387
+            if ($installPath === false || $installPath === null) {
388
+                $this->isInstanceReadyForUpdates = false;
389
+            } else {
390
+                $this->isInstanceReadyForUpdates = true;
391
+            }
392
+        }
393
+
394
+        if ($this->isInstanceReadyForUpdates === false) {
395
+            return false;
396
+        }
397
+
398
+        if ($this->isInstalledFromGit($appId) === true) {
399
+            return false;
400
+        }
401
+
402
+        if ($this->apps === null) {
403
+            $this->apps = $this->appFetcher->get();
404
+        }
405
+
406
+        foreach($this->apps as $app) {
407
+            if($app['id'] === $appId) {
408
+                $currentVersion = OC_App::getAppVersion($appId);
409
+                $newestVersion = $app['releases'][0]['version'];
410
+                if (version_compare($newestVersion, $currentVersion, '>')) {
411
+                    return $newestVersion;
412
+                } else {
413
+                    return false;
414
+                }
415
+            }
416
+        }
417
+
418
+        return false;
419
+    }
420
+
421
+    /**
422
+     * Check if app has been installed from git
423
+     * @param string $name name of the application to remove
424
+     * @return boolean
425
+     *
426
+     * The function will check if the path contains a .git folder
427
+     */
428
+    private function isInstalledFromGit($appId) {
429
+        $app = \OC_App::findAppInDirectories($appId);
430
+        if($app === false) {
431
+            return false;
432
+        }
433
+        $basedir = $app['path'].'/'.$appId;
434
+        return file_exists($basedir.'/.git/');
435
+    }
436
+
437
+    /**
438
+     * Check if app is already downloaded
439
+     * @param string $name name of the application to remove
440
+     * @return boolean
441
+     *
442
+     * The function will check if the app is already downloaded in the apps repository
443
+     */
444
+    public function isDownloaded($name) {
445
+        foreach(\OC::$APPSROOTS as $dir) {
446
+            $dirToTest  = $dir['path'];
447
+            $dirToTest .= '/';
448
+            $dirToTest .= $name;
449
+            $dirToTest .= '/';
450
+
451
+            if (is_dir($dirToTest)) {
452
+                return true;
453
+            }
454
+        }
455
+
456
+        return false;
457
+    }
458
+
459
+    /**
460
+     * Removes an app
461
+     * @param string $appId ID of the application to remove
462
+     * @return boolean
463
+     *
464
+     *
465
+     * This function works as follows
466
+     *   -# call uninstall repair steps
467
+     *   -# removing the files
468
+     *
469
+     * The function will not delete preferences, tables and the configuration,
470
+     * this has to be done by the function oc_app_uninstall().
471
+     */
472
+    public function removeApp($appId) {
473
+        if($this->isDownloaded( $appId )) {
474
+            $appDir = OC_App::getInstallPath() . '/' . $appId;
475
+            OC_Helper::rmdirr($appDir);
476
+            return true;
477
+        }else{
478
+            \OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
479
+
480
+            return false;
481
+        }
482
+
483
+    }
484
+
485
+    /**
486
+     * Installs the app within the bundle and marks the bundle as installed
487
+     *
488
+     * @param Bundle $bundle
489
+     * @throws \Exception If app could not get installed
490
+     */
491
+    public function installAppBundle(Bundle $bundle) {
492
+        $appIds = $bundle->getAppIdentifiers();
493
+        foreach($appIds as $appId) {
494
+            if(!$this->isDownloaded($appId)) {
495
+                $this->downloadApp($appId);
496
+            }
497
+            $this->installApp($appId);
498
+            $app = new OC_App();
499
+            $app->enable($appId);
500
+        }
501
+        $bundles = json_decode($this->config->getAppValue('core', 'installed.bundles', json_encode([])), true);
502
+        $bundles[] = $bundle->getIdentifier();
503
+        $this->config->setAppValue('core', 'installed.bundles', json_encode($bundles));
504
+    }
505
+
506
+    /**
507
+     * Installs shipped apps
508
+     *
509
+     * This function installs all apps found in the 'apps' directory that should be enabled by default;
510
+     * @param bool $softErrors When updating we ignore errors and simply log them, better to have a
511
+     *                         working ownCloud at the end instead of an aborted update.
512
+     * @return array Array of error messages (appid => Exception)
513
+     */
514
+    public static function installShippedApps($softErrors = false) {
515
+        $errors = [];
516
+        foreach(\OC::$APPSROOTS as $app_dir) {
517
+            if($dir = opendir( $app_dir['path'] )) {
518
+                while( false !== ( $filename = readdir( $dir ))) {
519
+                    if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
520
+                        if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
521
+                            if(!Installer::isInstalled($filename)) {
522
+                                $info=OC_App::getAppInfo($filename);
523
+                                $enabled = isset($info['default_enable']);
524
+                                if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
525
+                                      && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
526
+                                    if ($softErrors) {
527
+                                        try {
528
+                                            Installer::installShippedApp($filename);
529
+                                        } catch (HintException $e) {
530
+                                            if ($e->getPrevious() instanceof TableExistsException) {
531
+                                                $errors[$filename] = $e;
532
+                                                continue;
533
+                                            }
534
+                                            throw $e;
535
+                                        }
536
+                                    } else {
537
+                                        Installer::installShippedApp($filename);
538
+                                    }
539
+                                    \OC::$server->getConfig()->setAppValue($filename, 'enabled', 'yes');
540
+                                }
541
+                            }
542
+                        }
543
+                    }
544
+                }
545
+                closedir( $dir );
546
+            }
547
+        }
548
+
549
+        return $errors;
550
+    }
551
+
552
+    /**
553
+     * install an app already placed in the app folder
554
+     * @param string $app id of the app to install
555
+     * @return integer
556
+     */
557
+    public static function installShippedApp($app) {
558
+        //install the database
559
+        $appPath = OC_App::getAppPath($app);
560
+        \OC_App::registerAutoloading($app, $appPath);
561
+
562
+        if(is_file("$appPath/appinfo/database.xml")) {
563
+            try {
564
+                OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
565
+            } catch (TableExistsException $e) {
566
+                throw new HintException(
567
+                    'Failed to enable app ' . $app,
568
+                    'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
569
+                    0, $e
570
+                );
571
+            }
572
+        } else {
573
+            $ms = new \OC\DB\MigrationService($app, \OC::$server->getDatabaseConnection());
574
+            $ms->migrate();
575
+        }
576
+
577
+        //run appinfo/install.php
578
+        self::includeAppScript("$appPath/appinfo/install.php");
579
+
580
+        $info = OC_App::getAppInfo($app);
581
+        if (is_null($info)) {
582
+            return false;
583
+        }
584
+        \OC_App::setupBackgroundJobs($info['background-jobs']);
585
+
586
+        OC_App::executeRepairSteps($app, $info['repair-steps']['install']);
587
+
588
+        $config = \OC::$server->getConfig();
589
+
590
+        $config->setAppValue($app, 'installed_version', OC_App::getAppVersion($app));
591
+        if (array_key_exists('ocsid', $info)) {
592
+            $config->setAppValue($app, 'ocsid', $info['ocsid']);
593
+        }
594
+
595
+        //set remote/public handlers
596
+        foreach($info['remote'] as $name=>$path) {
597
+            $config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
598
+        }
599
+        foreach($info['public'] as $name=>$path) {
600
+            $config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
601
+        }
602
+
603
+        OC_App::setAppTypes($info['id']);
604
+
605
+        return $info['id'];
606
+    }
607
+
608
+    /**
609
+     * @param string $script
610
+     */
611
+    private static function includeAppScript($script) {
612
+        if ( file_exists($script) ){
613
+            include $script;
614
+        }
615
+    }
616 616
 }
Please login to merge, or discard this patch.
Spacing   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 	 */
101 101
 	public function installApp($appId) {
102 102
 		$app = \OC_App::findAppInDirectories($appId);
103
-		if($app === false) {
103
+		if ($app === false) {
104 104
 			throw new \Exception('App not found in any app directory');
105 105
 		}
106 106
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 
110 110
 		$l = \OC::$server->getL10N('core');
111 111
 
112
-		if(!is_array($info)) {
112
+		if (!is_array($info)) {
113 113
 			throw new \Exception(
114 114
 				$l->t('App "%s" cannot be installed because appinfo file cannot be read.',
115 115
 					[$info['name']]
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 		\OC_App::registerAutoloading($appId, $basedir);
133 133
 
134 134
 		//install the database
135
-		if(is_file($basedir.'/appinfo/database.xml')) {
135
+		if (is_file($basedir.'/appinfo/database.xml')) {
136 136
 			if (\OC::$server->getConfig()->getAppValue($info['id'], 'installed_version') === null) {
137 137
 				OC_DB::createDbFromStructure($basedir.'/appinfo/database.xml');
138 138
 			} else {
@@ -146,8 +146,8 @@  discard block
 block discarded – undo
146 146
 		\OC_App::setupBackgroundJobs($info['background-jobs']);
147 147
 
148 148
 		//run appinfo/install.php
149
-		if(!isset($data['noinstall']) or $data['noinstall']==false) {
150
-			self::includeAppScript($basedir . '/appinfo/install.php');
149
+		if (!isset($data['noinstall']) or $data['noinstall'] == false) {
150
+			self::includeAppScript($basedir.'/appinfo/install.php');
151 151
 		}
152 152
 
153 153
 		$appData = OC_App::getAppInfo($appId);
@@ -158,10 +158,10 @@  discard block
 block discarded – undo
158 158
 		\OC::$server->getConfig()->setAppValue($info['id'], 'enabled', 'no');
159 159
 
160 160
 		//set remote/public handlers
161
-		foreach($info['remote'] as $name=>$path) {
161
+		foreach ($info['remote'] as $name=>$path) {
162 162
 			\OC::$server->getConfig()->setAppValue('core', 'remote_'.$name, $info['id'].'/'.$path);
163 163
 		}
164
-		foreach($info['public'] as $name=>$path) {
164
+		foreach ($info['public'] as $name=>$path) {
165 165
 			\OC::$server->getConfig()->setAppValue('core', 'public_'.$name, $info['id'].'/'.$path);
166 166
 		}
167 167
 
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	 *
178 178
 	 * Checks whether or not an app is installed, i.e. registered in apps table.
179 179
 	 */
180
-	public static function isInstalled( $app ) {
180
+	public static function isInstalled($app) {
181 181
 		return (\OC::$server->getConfig()->getAppValue($app, "installed_version", null) !== null);
182 182
 	}
183 183
 
@@ -188,7 +188,7 @@  discard block
 block discarded – undo
188 188
 	 * @return bool
189 189
 	 */
190 190
 	public function updateAppstoreApp($appId) {
191
-		if($this->isUpdateAvailable($appId)) {
191
+		if ($this->isUpdateAvailable($appId)) {
192 192
 			try {
193 193
 				$this->downloadApp($appId);
194 194
 			} catch (\Exception $e) {
@@ -215,18 +215,18 @@  discard block
 block discarded – undo
215 215
 		$appId = strtolower($appId);
216 216
 
217 217
 		$apps = $this->appFetcher->get();
218
-		foreach($apps as $app) {
219
-			if($app['id'] === $appId) {
218
+		foreach ($apps as $app) {
219
+			if ($app['id'] === $appId) {
220 220
 				// Load the certificate
221 221
 				$certificate = new X509();
222
-				$certificate->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
222
+				$certificate->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
223 223
 				$loadedCertificate = $certificate->loadX509($app['certificate']);
224 224
 
225 225
 				// Verify if the certificate has been revoked
226 226
 				$crl = new X509();
227
-				$crl->loadCA(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crt'));
228
-				$crl->loadCRL(file_get_contents(__DIR__ . '/../../resources/codesigning/root.crl'));
229
-				if($crl->validateSignature() !== true) {
227
+				$crl->loadCA(file_get_contents(__DIR__.'/../../resources/codesigning/root.crt'));
228
+				$crl->loadCRL(file_get_contents(__DIR__.'/../../resources/codesigning/root.crl'));
229
+				if ($crl->validateSignature() !== true) {
230 230
 					throw new \Exception('Could not validate CRL signature');
231 231
 				}
232 232
 				$csn = $loadedCertificate['tbsCertificate']['serialNumber']->toString();
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 				}
242 242
 
243 243
 				// Verify if the certificate has been issued by the Nextcloud Code Authority CA
244
-				if($certificate->validateSignature() !== true) {
244
+				if ($certificate->validateSignature() !== true) {
245 245
 					throw new \Exception(
246 246
 						sprintf(
247 247
 							'App with id %s has a certificate not issued by a trusted Code Signing Authority',
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
 
253 253
 				// Verify if the certificate is issued for the requested app id
254 254
 				$certInfo = openssl_x509_parse($app['certificate']);
255
-				if(!isset($certInfo['subject']['CN'])) {
255
+				if (!isset($certInfo['subject']['CN'])) {
256 256
 					throw new \Exception(
257 257
 						sprintf(
258 258
 							'App with id %s has a cert with no CN',
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 						)
261 261
 					);
262 262
 				}
263
-				if($certInfo['subject']['CN'] !== $appId) {
263
+				if ($certInfo['subject']['CN'] !== $appId) {
264 264
 					throw new \Exception(
265 265
 						sprintf(
266 266
 							'App with id %s has a cert issued to %s',
@@ -277,15 +277,15 @@  discard block
 block discarded – undo
277 277
 
278 278
 				// Check if the signature actually matches the downloaded content
279 279
 				$certificate = openssl_get_publickey($app['certificate']);
280
-				$verified = (bool)openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
280
+				$verified = (bool) openssl_verify(file_get_contents($tempFile), base64_decode($app['releases'][0]['signature']), $certificate, OPENSSL_ALGO_SHA512);
281 281
 				openssl_free_key($certificate);
282 282
 
283
-				if($verified === true) {
283
+				if ($verified === true) {
284 284
 					// Seems to match, let's proceed
285 285
 					$extractDir = $this->tempManager->getTemporaryFolder();
286 286
 					$archive = new TAR($tempFile);
287 287
 
288
-					if($archive) {
288
+					if ($archive) {
289 289
 						if (!$archive->extract($extractDir)) {
290 290
 							throw new \Exception(
291 291
 								sprintf(
@@ -298,7 +298,7 @@  discard block
 block discarded – undo
298 298
 						$folders = array_diff($allFiles, ['.', '..']);
299 299
 						$folders = array_values($folders);
300 300
 
301
-						if(count($folders) > 1) {
301
+						if (count($folders) > 1) {
302 302
 							throw new \Exception(
303 303
 								sprintf(
304 304
 									'Extracted app %s has more than 1 folder',
@@ -309,22 +309,22 @@  discard block
 block discarded – undo
309 309
 
310 310
 						// Check if appinfo/info.xml has the same app ID as well
311 311
 						$loadEntities = libxml_disable_entity_loader(false);
312
-						$xml = simplexml_load_file($extractDir . '/' . $folders[0] . '/appinfo/info.xml');
312
+						$xml = simplexml_load_file($extractDir.'/'.$folders[0].'/appinfo/info.xml');
313 313
 						libxml_disable_entity_loader($loadEntities);
314
-						if((string)$xml->id !== $appId) {
314
+						if ((string) $xml->id !== $appId) {
315 315
 							throw new \Exception(
316 316
 								sprintf(
317 317
 									'App for id %s has a wrong app ID in info.xml: %s',
318 318
 									$appId,
319
-									(string)$xml->id
319
+									(string) $xml->id
320 320
 								)
321 321
 							);
322 322
 						}
323 323
 
324 324
 						// Check if the version is lower than before
325 325
 						$currentVersion = OC_App::getAppVersion($appId);
326
-						$newVersion = (string)$xml->version;
327
-						if(version_compare($currentVersion, $newVersion) === 1) {
326
+						$newVersion = (string) $xml->version;
327
+						if (version_compare($currentVersion, $newVersion) === 1) {
328 328
 							throw new \Exception(
329 329
 								sprintf(
330 330
 									'App for id %s has version %s and tried to update to lower version %s',
@@ -335,12 +335,12 @@  discard block
 block discarded – undo
335 335
 							);
336 336
 						}
337 337
 
338
-						$baseDir = OC_App::getInstallPath() . '/' . $appId;
338
+						$baseDir = OC_App::getInstallPath().'/'.$appId;
339 339
 						// Remove old app with the ID if existent
340 340
 						OC_Helper::rmdirr($baseDir);
341 341
 						// Move to app folder
342
-						if(@mkdir($baseDir)) {
343
-							$extractDir .= '/' . $folders[0];
342
+						if (@mkdir($baseDir)) {
343
+							$extractDir .= '/'.$folders[0];
344 344
 							OC_Helper::copyr($extractDir, $baseDir);
345 345
 						}
346 346
 						OC_Helper::copyr($extractDir, $baseDir);
@@ -403,8 +403,8 @@  discard block
 block discarded – undo
403 403
 			$this->apps = $this->appFetcher->get();
404 404
 		}
405 405
 
406
-		foreach($this->apps as $app) {
407
-			if($app['id'] === $appId) {
406
+		foreach ($this->apps as $app) {
407
+			if ($app['id'] === $appId) {
408 408
 				$currentVersion = OC_App::getAppVersion($appId);
409 409
 				$newestVersion = $app['releases'][0]['version'];
410 410
 				if (version_compare($newestVersion, $currentVersion, '>')) {
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 	 */
428 428
 	private function isInstalledFromGit($appId) {
429 429
 		$app = \OC_App::findAppInDirectories($appId);
430
-		if($app === false) {
430
+		if ($app === false) {
431 431
 			return false;
432 432
 		}
433 433
 		$basedir = $app['path'].'/'.$appId;
@@ -442,7 +442,7 @@  discard block
 block discarded – undo
442 442
 	 * The function will check if the app is already downloaded in the apps repository
443 443
 	 */
444 444
 	public function isDownloaded($name) {
445
-		foreach(\OC::$APPSROOTS as $dir) {
445
+		foreach (\OC::$APPSROOTS as $dir) {
446 446
 			$dirToTest  = $dir['path'];
447 447
 			$dirToTest .= '/';
448 448
 			$dirToTest .= $name;
@@ -470,11 +470,11 @@  discard block
 block discarded – undo
470 470
 	 * this has to be done by the function oc_app_uninstall().
471 471
 	 */
472 472
 	public function removeApp($appId) {
473
-		if($this->isDownloaded( $appId )) {
474
-			$appDir = OC_App::getInstallPath() . '/' . $appId;
473
+		if ($this->isDownloaded($appId)) {
474
+			$appDir = OC_App::getInstallPath().'/'.$appId;
475 475
 			OC_Helper::rmdirr($appDir);
476 476
 			return true;
477
-		}else{
477
+		} else {
478 478
 			\OCP\Util::writeLog('core', 'can\'t remove app '.$appId.'. It is not installed.', \OCP\Util::ERROR);
479 479
 
480 480
 			return false;
@@ -490,8 +490,8 @@  discard block
 block discarded – undo
490 490
 	 */
491 491
 	public function installAppBundle(Bundle $bundle) {
492 492
 		$appIds = $bundle->getAppIdentifiers();
493
-		foreach($appIds as $appId) {
494
-			if(!$this->isDownloaded($appId)) {
493
+		foreach ($appIds as $appId) {
494
+			if (!$this->isDownloaded($appId)) {
495 495
 				$this->downloadApp($appId);
496 496
 			}
497 497
 			$this->installApp($appId);
@@ -513,13 +513,13 @@  discard block
 block discarded – undo
513 513
 	 */
514 514
 	public static function installShippedApps($softErrors = false) {
515 515
 		$errors = [];
516
-		foreach(\OC::$APPSROOTS as $app_dir) {
517
-			if($dir = opendir( $app_dir['path'] )) {
518
-				while( false !== ( $filename = readdir( $dir ))) {
519
-					if( $filename[0] !== '.' and is_dir($app_dir['path']."/$filename") ) {
520
-						if( file_exists( $app_dir['path']."/$filename/appinfo/info.xml" )) {
521
-							if(!Installer::isInstalled($filename)) {
522
-								$info=OC_App::getAppInfo($filename);
516
+		foreach (\OC::$APPSROOTS as $app_dir) {
517
+			if ($dir = opendir($app_dir['path'])) {
518
+				while (false !== ($filename = readdir($dir))) {
519
+					if ($filename[0] !== '.' and is_dir($app_dir['path']."/$filename")) {
520
+						if (file_exists($app_dir['path']."/$filename/appinfo/info.xml")) {
521
+							if (!Installer::isInstalled($filename)) {
522
+								$info = OC_App::getAppInfo($filename);
523 523
 								$enabled = isset($info['default_enable']);
524 524
 								if (($enabled || in_array($filename, \OC::$server->getAppManager()->getAlwaysEnabledApps()))
525 525
 									  && \OC::$server->getConfig()->getAppValue($filename, 'enabled') !== 'no') {
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 						}
543 543
 					}
544 544
 				}
545
-				closedir( $dir );
545
+				closedir($dir);
546 546
 			}
547 547
 		}
548 548
 
@@ -559,12 +559,12 @@  discard block
 block discarded – undo
559 559
 		$appPath = OC_App::getAppPath($app);
560 560
 		\OC_App::registerAutoloading($app, $appPath);
561 561
 
562
-		if(is_file("$appPath/appinfo/database.xml")) {
562
+		if (is_file("$appPath/appinfo/database.xml")) {
563 563
 			try {
564 564
 				OC_DB::createDbFromStructure("$appPath/appinfo/database.xml");
565 565
 			} catch (TableExistsException $e) {
566 566
 				throw new HintException(
567
-					'Failed to enable app ' . $app,
567
+					'Failed to enable app '.$app,
568 568
 					'Please ask for help via one of our <a href="https://nextcloud.com/support/" target="_blank" rel="noreferrer noopener">support channels</a>.',
569 569
 					0, $e
570 570
 				);
@@ -593,10 +593,10 @@  discard block
 block discarded – undo
593 593
 		}
594 594
 
595 595
 		//set remote/public handlers
596
-		foreach($info['remote'] as $name=>$path) {
596
+		foreach ($info['remote'] as $name=>$path) {
597 597
 			$config->setAppValue('core', 'remote_'.$name, $app.'/'.$path);
598 598
 		}
599
-		foreach($info['public'] as $name=>$path) {
599
+		foreach ($info['public'] as $name=>$path) {
600 600
 			$config->setAppValue('core', 'public_'.$name, $app.'/'.$path);
601 601
 		}
602 602
 
@@ -609,7 +609,7 @@  discard block
 block discarded – undo
609 609
 	 * @param string $script
610 610
 	 */
611 611
 	private static function includeAppScript($script) {
612
-		if ( file_exists($script) ){
612
+		if (file_exists($script)) {
613 613
 			include $script;
614 614
 		}
615 615
 	}
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1823 added lines, -1823 removed lines patch added patch discarded remove patch
@@ -149,1832 +149,1832 @@
 block discarded – undo
149 149
  * TODO: hookup all manager classes
150 150
  */
151 151
 class Server extends ServerContainer implements IServerContainer {
152
-	/** @var string */
153
-	private $webRoot;
154
-
155
-	/**
156
-	 * @param string $webRoot
157
-	 * @param \OC\Config $config
158
-	 */
159
-	public function __construct($webRoot, \OC\Config $config) {
160
-		parent::__construct();
161
-		$this->webRoot = $webRoot;
162
-
163
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
164
-			return $c;
165
-		});
166
-
167
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
168
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
169
-
170
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
171
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
172
-
173
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
174
-
175
-
176
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
177
-			return new PreviewManager(
178
-				$c->getConfig(),
179
-				$c->getRootFolder(),
180
-				$c->getAppDataDir('preview'),
181
-				$c->getEventDispatcher(),
182
-				$c->getSession()->get('user_id')
183
-			);
184
-		});
185
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
186
-
187
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
188
-			return new \OC\Preview\Watcher(
189
-				$c->getAppDataDir('preview')
190
-			);
191
-		});
192
-
193
-		$this->registerService('EncryptionManager', function (Server $c) {
194
-			$view = new View();
195
-			$util = new Encryption\Util(
196
-				$view,
197
-				$c->getUserManager(),
198
-				$c->getGroupManager(),
199
-				$c->getConfig()
200
-			);
201
-			return new Encryption\Manager(
202
-				$c->getConfig(),
203
-				$c->getLogger(),
204
-				$c->getL10N('core'),
205
-				new View(),
206
-				$util,
207
-				new ArrayCache()
208
-			);
209
-		});
210
-
211
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
212
-			$util = new Encryption\Util(
213
-				new View(),
214
-				$c->getUserManager(),
215
-				$c->getGroupManager(),
216
-				$c->getConfig()
217
-			);
218
-			return new Encryption\File(
219
-				$util,
220
-				$c->getRootFolder(),
221
-				$c->getShareManager()
222
-			);
223
-		});
224
-
225
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
226
-			$view = new View();
227
-			$util = new Encryption\Util(
228
-				$view,
229
-				$c->getUserManager(),
230
-				$c->getGroupManager(),
231
-				$c->getConfig()
232
-			);
233
-
234
-			return new Encryption\Keys\Storage($view, $util);
235
-		});
236
-		$this->registerService('TagMapper', function (Server $c) {
237
-			return new TagMapper($c->getDatabaseConnection());
238
-		});
239
-
240
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
241
-			$tagMapper = $c->query('TagMapper');
242
-			return new TagManager($tagMapper, $c->getUserSession());
243
-		});
244
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
245
-
246
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
247
-			$config = $c->getConfig();
248
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
249
-			return new $factoryClass($this);
250
-		});
251
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
-			return $c->query('SystemTagManagerFactory')->getManager();
253
-		});
254
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255
-
256
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
258
-		});
259
-		$this->registerService('RootFolder', function (Server $c) {
260
-			$manager = \OC\Files\Filesystem::getMountManager(null);
261
-			$view = new View();
262
-			$root = new Root(
263
-				$manager,
264
-				$view,
265
-				null,
266
-				$c->getUserMountCache(),
267
-				$this->getLogger(),
268
-				$this->getUserManager()
269
-			);
270
-			$connector = new HookConnector($root, $view);
271
-			$connector->viewToNode();
272
-
273
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
274
-			$previewConnector->connectWatcher();
275
-
276
-			return $root;
277
-		});
278
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279
-
280
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
-			return new LazyRoot(function () use ($c) {
282
-				return $c->query('RootFolder');
283
-			});
284
-		});
285
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286
-
287
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
288
-			$config = $c->getConfig();
289
-			return new \OC\User\Manager($config);
290
-		});
291
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
292
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
293
-
294
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298
-			});
299
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301
-			});
302
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304
-			});
305
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307
-			});
308
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310
-			});
311
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
315
-			});
316
-			return $groupManager;
317
-		});
318
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319
-
320
-		$this->registerService(Store::class, function (Server $c) {
321
-			$session = $c->getSession();
322
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
-				$tokenProvider = $c->query(IProvider::class);
324
-			} else {
325
-				$tokenProvider = null;
326
-			}
327
-			$logger = $c->getLogger();
328
-			return new Store($session, $logger, $tokenProvider);
329
-		});
330
-		$this->registerAlias(IStore::class, Store::class);
331
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
332
-			$dbConnection = $c->getDatabaseConnection();
333
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
334
-		});
335
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
336
-			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
337
-			$crypto = $c->getCrypto();
338
-			$config = $c->getConfig();
339
-			$logger = $c->getLogger();
340
-			$timeFactory = new TimeFactory();
341
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
342
-		});
343
-		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
344
-
345
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
-			$manager = $c->getUserManager();
347
-			$session = new \OC\Session\Memory('');
348
-			$timeFactory = new TimeFactory();
349
-			// Token providers might require a working database. This code
350
-			// might however be called when ownCloud is not yet setup.
351
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
352
-				$defaultTokenProvider = $c->query(IProvider::class);
353
-			} else {
354
-				$defaultTokenProvider = null;
355
-			}
356
-
357
-			$dispatcher = $c->getEventDispatcher();
358
-
359
-			$userSession = new \OC\User\Session(
360
-				$manager,
361
-				$session,
362
-				$timeFactory,
363
-				$defaultTokenProvider,
364
-				$c->getConfig(),
365
-				$c->getSecureRandom(),
366
-				$c->getLockdownManager(),
367
-				$c->getLogger()
368
-			);
369
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
370
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
371
-			});
372
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
373
-				/** @var $user \OC\User\User */
374
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
375
-			});
376
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
377
-				/** @var $user \OC\User\User */
378
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
379
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
380
-			});
381
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
382
-				/** @var $user \OC\User\User */
383
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
384
-			});
385
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
386
-				/** @var $user \OC\User\User */
387
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
388
-			});
389
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
390
-				/** @var $user \OC\User\User */
391
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392
-			});
393
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
394
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
395
-			});
396
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
397
-				/** @var $user \OC\User\User */
398
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
399
-			});
400
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
401
-				/** @var $user \OC\User\User */
402
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403
-			});
404
-			$userSession->listen('\OC\User', 'logout', function () {
405
-				\OC_Hook::emit('OC_User', 'logout', array());
406
-			});
407
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
408
-				/** @var $user \OC\User\User */
409
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
410
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
411
-			});
412
-			return $userSession;
413
-		});
414
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
415
-
416
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
417
-			return new \OC\Authentication\TwoFactorAuth\Manager(
418
-				$c->getAppManager(),
419
-				$c->getSession(),
420
-				$c->getConfig(),
421
-				$c->getActivityManager(),
422
-				$c->getLogger(),
423
-				$c->query(IProvider::class),
424
-				$c->query(ITimeFactory::class),
425
-				$c->query(EventDispatcherInterface::class)
426
-			);
427
-		});
428
-
429
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
430
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
431
-
432
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
433
-			return new \OC\AllConfig(
434
-				$c->getSystemConfig()
435
-			);
436
-		});
437
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
438
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
439
-
440
-		$this->registerService('SystemConfig', function ($c) use ($config) {
441
-			return new \OC\SystemConfig($config);
442
-		});
443
-
444
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
445
-			return new \OC\AppConfig($c->getDatabaseConnection());
446
-		});
447
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
448
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
449
-
450
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
451
-			return new \OC\L10N\Factory(
452
-				$c->getConfig(),
453
-				$c->getRequest(),
454
-				$c->getUserSession(),
455
-				\OC::$SERVERROOT
456
-			);
457
-		});
458
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
459
-
460
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
461
-			$config = $c->getConfig();
462
-			$cacheFactory = $c->getMemCacheFactory();
463
-			$request = $c->getRequest();
464
-			return new \OC\URLGenerator(
465
-				$config,
466
-				$cacheFactory,
467
-				$request
468
-			);
469
-		});
470
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
471
-
472
-		$this->registerService('AppHelper', function ($c) {
473
-			return new \OC\AppHelper();
474
-		});
475
-		$this->registerAlias('AppFetcher', AppFetcher::class);
476
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
477
-
478
-		$this->registerService(\OCP\ICache::class, function ($c) {
479
-			return new Cache\File();
480
-		});
481
-		$this->registerAlias('UserCache', \OCP\ICache::class);
482
-
483
-		$this->registerService(Factory::class, function (Server $c) {
484
-
485
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
486
-				ArrayCache::class,
487
-				ArrayCache::class,
488
-				ArrayCache::class
489
-			);
490
-			$config = $c->getConfig();
491
-			$request = $c->getRequest();
492
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
493
-
494
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
495
-				$v = \OC_App::getAppVersions();
496
-				$v['core'] = implode(',', \OC_Util::getVersion());
497
-				$version = implode(',', $v);
498
-				$instanceId = \OC_Util::getInstanceId();
499
-				$path = \OC::$SERVERROOT;
500
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
501
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
502
-					$config->getSystemValue('memcache.local', null),
503
-					$config->getSystemValue('memcache.distributed', null),
504
-					$config->getSystemValue('memcache.locking', null)
505
-				);
506
-			}
507
-			return $arrayCacheFactory;
508
-
509
-		});
510
-		$this->registerAlias('MemCacheFactory', Factory::class);
511
-		$this->registerAlias(ICacheFactory::class, Factory::class);
512
-
513
-		$this->registerService('RedisFactory', function (Server $c) {
514
-			$systemConfig = $c->getSystemConfig();
515
-			return new RedisFactory($systemConfig);
516
-		});
517
-
518
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
519
-			return new \OC\Activity\Manager(
520
-				$c->getRequest(),
521
-				$c->getUserSession(),
522
-				$c->getConfig(),
523
-				$c->query(IValidator::class)
524
-			);
525
-		});
526
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
527
-
528
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
529
-			return new \OC\Activity\EventMerger(
530
-				$c->getL10N('lib')
531
-			);
532
-		});
533
-		$this->registerAlias(IValidator::class, Validator::class);
534
-
535
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
536
-			return new AvatarManager(
537
-				$c->query(\OC\User\Manager::class),
538
-				$c->getAppDataDir('avatar'),
539
-				$c->getL10N('lib'),
540
-				$c->getLogger(),
541
-				$c->getConfig()
542
-			);
543
-		});
544
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
545
-
546
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
547
-
548
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
549
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
550
-			$logger = Log::getLogClass($logType);
551
-			call_user_func(array($logger, 'init'));
552
-			$config = $this->getSystemConfig();
553
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
554
-
555
-			return new Log($logger, $config, null, $registry);
556
-		});
557
-		$this->registerAlias('Logger', \OCP\ILogger::class);
558
-
559
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
560
-			$config = $c->getConfig();
561
-			return new \OC\BackgroundJob\JobList(
562
-				$c->getDatabaseConnection(),
563
-				$config,
564
-				new TimeFactory()
565
-			);
566
-		});
567
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
568
-
569
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
570
-			$cacheFactory = $c->getMemCacheFactory();
571
-			$logger = $c->getLogger();
572
-			if ($cacheFactory->isAvailableLowLatency()) {
573
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
574
-			} else {
575
-				$router = new \OC\Route\Router($logger);
576
-			}
577
-			return $router;
578
-		});
579
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
580
-
581
-		$this->registerService(\OCP\ISearch::class, function ($c) {
582
-			return new Search();
583
-		});
584
-		$this->registerAlias('Search', \OCP\ISearch::class);
585
-
586
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
587
-			return new \OC\Security\RateLimiting\Limiter(
588
-				$this->getUserSession(),
589
-				$this->getRequest(),
590
-				new \OC\AppFramework\Utility\TimeFactory(),
591
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
592
-			);
593
-		});
594
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
595
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
596
-				$this->getMemCacheFactory(),
597
-				new \OC\AppFramework\Utility\TimeFactory()
598
-			);
599
-		});
600
-
601
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
602
-			return new SecureRandom();
603
-		});
604
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
605
-
606
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
607
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
608
-		});
609
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
610
-
611
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
612
-			return new Hasher($c->getConfig());
613
-		});
614
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
615
-
616
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
617
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
618
-		});
619
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
620
-
621
-		$this->registerService(IDBConnection::class, function (Server $c) {
622
-			$systemConfig = $c->getSystemConfig();
623
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
624
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
625
-			if (!$factory->isValidType($type)) {
626
-				throw new \OC\DatabaseException('Invalid database type');
627
-			}
628
-			$connectionParams = $factory->createConnectionParams();
629
-			$connection = $factory->getConnection($type, $connectionParams);
630
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
631
-			return $connection;
632
-		});
633
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
634
-
635
-		$this->registerService('HTTPHelper', function (Server $c) {
636
-			$config = $c->getConfig();
637
-			return new HTTPHelper(
638
-				$config,
639
-				$c->getHTTPClientService()
640
-			);
641
-		});
642
-
643
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
644
-			$user = \OC_User::getUser();
645
-			$uid = $user ? $user : null;
646
-			return new ClientService(
647
-				$c->getConfig(),
648
-				new \OC\Security\CertificateManager(
649
-					$uid,
650
-					new View(),
651
-					$c->getConfig(),
652
-					$c->getLogger(),
653
-					$c->getSecureRandom()
654
-				)
655
-			);
656
-		});
657
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
658
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
659
-			$eventLogger = new EventLogger();
660
-			if ($c->getSystemConfig()->getValue('debug', false)) {
661
-				// In debug mode, module is being activated by default
662
-				$eventLogger->activate();
663
-			}
664
-			return $eventLogger;
665
-		});
666
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
667
-
668
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
669
-			$queryLogger = new QueryLogger();
670
-			if ($c->getSystemConfig()->getValue('debug', false)) {
671
-				// In debug mode, module is being activated by default
672
-				$queryLogger->activate();
673
-			}
674
-			return $queryLogger;
675
-		});
676
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
677
-
678
-		$this->registerService(TempManager::class, function (Server $c) {
679
-			return new TempManager(
680
-				$c->getLogger(),
681
-				$c->getConfig()
682
-			);
683
-		});
684
-		$this->registerAlias('TempManager', TempManager::class);
685
-		$this->registerAlias(ITempManager::class, TempManager::class);
686
-
687
-		$this->registerService(AppManager::class, function (Server $c) {
688
-			return new \OC\App\AppManager(
689
-				$c->getUserSession(),
690
-				$c->query(\OC\AppConfig::class),
691
-				$c->getGroupManager(),
692
-				$c->getMemCacheFactory(),
693
-				$c->getEventDispatcher()
694
-			);
695
-		});
696
-		$this->registerAlias('AppManager', AppManager::class);
697
-		$this->registerAlias(IAppManager::class, AppManager::class);
698
-
699
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
700
-			return new DateTimeZone(
701
-				$c->getConfig(),
702
-				$c->getSession()
703
-			);
704
-		});
705
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
706
-
707
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
708
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
709
-
710
-			return new DateTimeFormatter(
711
-				$c->getDateTimeZone()->getTimeZone(),
712
-				$c->getL10N('lib', $language)
713
-			);
714
-		});
715
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
716
-
717
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
718
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
719
-			$listener = new UserMountCacheListener($mountCache);
720
-			$listener->listen($c->getUserManager());
721
-			return $mountCache;
722
-		});
723
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
724
-
725
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
726
-			$loader = \OC\Files\Filesystem::getLoader();
727
-			$mountCache = $c->query('UserMountCache');
728
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
729
-
730
-			// builtin providers
731
-
732
-			$config = $c->getConfig();
733
-			$manager->registerProvider(new CacheMountProvider($config));
734
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
735
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
736
-
737
-			return $manager;
738
-		});
739
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
740
-
741
-		$this->registerService('IniWrapper', function ($c) {
742
-			return new IniGetWrapper();
743
-		});
744
-		$this->registerService('AsyncCommandBus', function (Server $c) {
745
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
746
-			if ($busClass) {
747
-				list($app, $class) = explode('::', $busClass, 2);
748
-				if ($c->getAppManager()->isInstalled($app)) {
749
-					\OC_App::loadApp($app);
750
-					return $c->query($class);
751
-				} else {
752
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
753
-				}
754
-			} else {
755
-				$jobList = $c->getJobList();
756
-				return new CronBus($jobList);
757
-			}
758
-		});
759
-		$this->registerService('TrustedDomainHelper', function ($c) {
760
-			return new TrustedDomainHelper($this->getConfig());
761
-		});
762
-		$this->registerService('Throttler', function (Server $c) {
763
-			return new Throttler(
764
-				$c->getDatabaseConnection(),
765
-				new TimeFactory(),
766
-				$c->getLogger(),
767
-				$c->getConfig()
768
-			);
769
-		});
770
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
771
-			// IConfig and IAppManager requires a working database. This code
772
-			// might however be called when ownCloud is not yet setup.
773
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
774
-				$config = $c->getConfig();
775
-				$appManager = $c->getAppManager();
776
-			} else {
777
-				$config = null;
778
-				$appManager = null;
779
-			}
780
-
781
-			return new Checker(
782
-				new EnvironmentHelper(),
783
-				new FileAccessHelper(),
784
-				new AppLocator(),
785
-				$config,
786
-				$c->getMemCacheFactory(),
787
-				$appManager,
788
-				$c->getTempManager()
789
-			);
790
-		});
791
-		$this->registerService(\OCP\IRequest::class, function ($c) {
792
-			if (isset($this['urlParams'])) {
793
-				$urlParams = $this['urlParams'];
794
-			} else {
795
-				$urlParams = [];
796
-			}
797
-
798
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
799
-				&& in_array('fakeinput', stream_get_wrappers())
800
-			) {
801
-				$stream = 'fakeinput://data';
802
-			} else {
803
-				$stream = 'php://input';
804
-			}
805
-
806
-			return new Request(
807
-				[
808
-					'get' => $_GET,
809
-					'post' => $_POST,
810
-					'files' => $_FILES,
811
-					'server' => $_SERVER,
812
-					'env' => $_ENV,
813
-					'cookies' => $_COOKIE,
814
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
815
-						? $_SERVER['REQUEST_METHOD']
816
-						: null,
817
-					'urlParams' => $urlParams,
818
-				],
819
-				$this->getSecureRandom(),
820
-				$this->getConfig(),
821
-				$this->getCsrfTokenManager(),
822
-				$stream
823
-			);
824
-		});
825
-		$this->registerAlias('Request', \OCP\IRequest::class);
826
-
827
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
828
-			return new Mailer(
829
-				$c->getConfig(),
830
-				$c->getLogger(),
831
-				$c->query(Defaults::class),
832
-				$c->getURLGenerator(),
833
-				$c->getL10N('lib')
834
-			);
835
-		});
836
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837
-
838
-		$this->registerService('LDAPProvider', function (Server $c) {
839
-			$config = $c->getConfig();
840
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841
-			if (is_null($factoryClass)) {
842
-				throw new \Exception('ldapProviderFactory not set');
843
-			}
844
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
845
-			$factory = new $factoryClass($this);
846
-			return $factory->getLDAPProvider();
847
-		});
848
-		$this->registerService(ILockingProvider::class, function (Server $c) {
849
-			$ini = $c->getIniWrapper();
850
-			$config = $c->getConfig();
851
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
852
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
853
-				/** @var \OC\Memcache\Factory $memcacheFactory */
854
-				$memcacheFactory = $c->getMemCacheFactory();
855
-				$memcache = $memcacheFactory->createLocking('lock');
856
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
857
-					return new MemcacheLockingProvider($memcache, $ttl);
858
-				}
859
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
860
-			}
861
-			return new NoopLockingProvider();
862
-		});
863
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
864
-
865
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
866
-			return new \OC\Files\Mount\Manager();
867
-		});
868
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
869
-
870
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
871
-			return new \OC\Files\Type\Detection(
872
-				$c->getURLGenerator(),
873
-				\OC::$configDir,
874
-				\OC::$SERVERROOT . '/resources/config/'
875
-			);
876
-		});
877
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
878
-
879
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
880
-			return new \OC\Files\Type\Loader(
881
-				$c->getDatabaseConnection()
882
-			);
883
-		});
884
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
885
-		$this->registerService(BundleFetcher::class, function () {
886
-			return new BundleFetcher($this->getL10N('lib'));
887
-		});
888
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
889
-			return new Manager(
890
-				$c->query(IValidator::class)
891
-			);
892
-		});
893
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
894
-
895
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
896
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
897
-			$manager->registerCapability(function () use ($c) {
898
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
899
-			});
900
-			$manager->registerCapability(function () use ($c) {
901
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
902
-			});
903
-			return $manager;
904
-		});
905
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
906
-
907
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
908
-			$config = $c->getConfig();
909
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
910
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
911
-			$factory = new $factoryClass($this);
912
-			$manager = $factory->getManager();
913
-
914
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
915
-				$manager = $c->getUserManager();
916
-				$user = $manager->get($id);
917
-				if(is_null($user)) {
918
-					$l = $c->getL10N('core');
919
-					$displayName = $l->t('Unknown user');
920
-				} else {
921
-					$displayName = $user->getDisplayName();
922
-				}
923
-				return $displayName;
924
-			});
925
-
926
-			return $manager;
927
-		});
928
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
929
-
930
-		$this->registerService('ThemingDefaults', function (Server $c) {
931
-			/*
152
+    /** @var string */
153
+    private $webRoot;
154
+
155
+    /**
156
+     * @param string $webRoot
157
+     * @param \OC\Config $config
158
+     */
159
+    public function __construct($webRoot, \OC\Config $config) {
160
+        parent::__construct();
161
+        $this->webRoot = $webRoot;
162
+
163
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
164
+            return $c;
165
+        });
166
+
167
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
168
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
169
+
170
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
171
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
172
+
173
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
174
+
175
+
176
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
177
+            return new PreviewManager(
178
+                $c->getConfig(),
179
+                $c->getRootFolder(),
180
+                $c->getAppDataDir('preview'),
181
+                $c->getEventDispatcher(),
182
+                $c->getSession()->get('user_id')
183
+            );
184
+        });
185
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
186
+
187
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
188
+            return new \OC\Preview\Watcher(
189
+                $c->getAppDataDir('preview')
190
+            );
191
+        });
192
+
193
+        $this->registerService('EncryptionManager', function (Server $c) {
194
+            $view = new View();
195
+            $util = new Encryption\Util(
196
+                $view,
197
+                $c->getUserManager(),
198
+                $c->getGroupManager(),
199
+                $c->getConfig()
200
+            );
201
+            return new Encryption\Manager(
202
+                $c->getConfig(),
203
+                $c->getLogger(),
204
+                $c->getL10N('core'),
205
+                new View(),
206
+                $util,
207
+                new ArrayCache()
208
+            );
209
+        });
210
+
211
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
212
+            $util = new Encryption\Util(
213
+                new View(),
214
+                $c->getUserManager(),
215
+                $c->getGroupManager(),
216
+                $c->getConfig()
217
+            );
218
+            return new Encryption\File(
219
+                $util,
220
+                $c->getRootFolder(),
221
+                $c->getShareManager()
222
+            );
223
+        });
224
+
225
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
226
+            $view = new View();
227
+            $util = new Encryption\Util(
228
+                $view,
229
+                $c->getUserManager(),
230
+                $c->getGroupManager(),
231
+                $c->getConfig()
232
+            );
233
+
234
+            return new Encryption\Keys\Storage($view, $util);
235
+        });
236
+        $this->registerService('TagMapper', function (Server $c) {
237
+            return new TagMapper($c->getDatabaseConnection());
238
+        });
239
+
240
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
241
+            $tagMapper = $c->query('TagMapper');
242
+            return new TagManager($tagMapper, $c->getUserSession());
243
+        });
244
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
245
+
246
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
247
+            $config = $c->getConfig();
248
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
249
+            return new $factoryClass($this);
250
+        });
251
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
252
+            return $c->query('SystemTagManagerFactory')->getManager();
253
+        });
254
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
255
+
256
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
257
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
258
+        });
259
+        $this->registerService('RootFolder', function (Server $c) {
260
+            $manager = \OC\Files\Filesystem::getMountManager(null);
261
+            $view = new View();
262
+            $root = new Root(
263
+                $manager,
264
+                $view,
265
+                null,
266
+                $c->getUserMountCache(),
267
+                $this->getLogger(),
268
+                $this->getUserManager()
269
+            );
270
+            $connector = new HookConnector($root, $view);
271
+            $connector->viewToNode();
272
+
273
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
274
+            $previewConnector->connectWatcher();
275
+
276
+            return $root;
277
+        });
278
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
279
+
280
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
281
+            return new LazyRoot(function () use ($c) {
282
+                return $c->query('RootFolder');
283
+            });
284
+        });
285
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
286
+
287
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
288
+            $config = $c->getConfig();
289
+            return new \OC\User\Manager($config);
290
+        });
291
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
292
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
293
+
294
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
295
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
296
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
297
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
298
+            });
299
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
300
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
301
+            });
302
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
303
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
304
+            });
305
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
306
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
307
+            });
308
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
309
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
310
+            });
311
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
312
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
313
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
314
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
315
+            });
316
+            return $groupManager;
317
+        });
318
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
319
+
320
+        $this->registerService(Store::class, function (Server $c) {
321
+            $session = $c->getSession();
322
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
323
+                $tokenProvider = $c->query(IProvider::class);
324
+            } else {
325
+                $tokenProvider = null;
326
+            }
327
+            $logger = $c->getLogger();
328
+            return new Store($session, $logger, $tokenProvider);
329
+        });
330
+        $this->registerAlias(IStore::class, Store::class);
331
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
332
+            $dbConnection = $c->getDatabaseConnection();
333
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
334
+        });
335
+        $this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
336
+            $mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
337
+            $crypto = $c->getCrypto();
338
+            $config = $c->getConfig();
339
+            $logger = $c->getLogger();
340
+            $timeFactory = new TimeFactory();
341
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
342
+        });
343
+        $this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
344
+
345
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
346
+            $manager = $c->getUserManager();
347
+            $session = new \OC\Session\Memory('');
348
+            $timeFactory = new TimeFactory();
349
+            // Token providers might require a working database. This code
350
+            // might however be called when ownCloud is not yet setup.
351
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
352
+                $defaultTokenProvider = $c->query(IProvider::class);
353
+            } else {
354
+                $defaultTokenProvider = null;
355
+            }
356
+
357
+            $dispatcher = $c->getEventDispatcher();
358
+
359
+            $userSession = new \OC\User\Session(
360
+                $manager,
361
+                $session,
362
+                $timeFactory,
363
+                $defaultTokenProvider,
364
+                $c->getConfig(),
365
+                $c->getSecureRandom(),
366
+                $c->getLockdownManager(),
367
+                $c->getLogger()
368
+            );
369
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
370
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
371
+            });
372
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
373
+                /** @var $user \OC\User\User */
374
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
375
+            });
376
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
377
+                /** @var $user \OC\User\User */
378
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
379
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
380
+            });
381
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
382
+                /** @var $user \OC\User\User */
383
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
384
+            });
385
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
386
+                /** @var $user \OC\User\User */
387
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
388
+            });
389
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
390
+                /** @var $user \OC\User\User */
391
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392
+            });
393
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
394
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
395
+            });
396
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
397
+                /** @var $user \OC\User\User */
398
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
399
+            });
400
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
401
+                /** @var $user \OC\User\User */
402
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403
+            });
404
+            $userSession->listen('\OC\User', 'logout', function () {
405
+                \OC_Hook::emit('OC_User', 'logout', array());
406
+            });
407
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
408
+                /** @var $user \OC\User\User */
409
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
410
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
411
+            });
412
+            return $userSession;
413
+        });
414
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
415
+
416
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
417
+            return new \OC\Authentication\TwoFactorAuth\Manager(
418
+                $c->getAppManager(),
419
+                $c->getSession(),
420
+                $c->getConfig(),
421
+                $c->getActivityManager(),
422
+                $c->getLogger(),
423
+                $c->query(IProvider::class),
424
+                $c->query(ITimeFactory::class),
425
+                $c->query(EventDispatcherInterface::class)
426
+            );
427
+        });
428
+
429
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
430
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
431
+
432
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
433
+            return new \OC\AllConfig(
434
+                $c->getSystemConfig()
435
+            );
436
+        });
437
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
438
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
439
+
440
+        $this->registerService('SystemConfig', function ($c) use ($config) {
441
+            return new \OC\SystemConfig($config);
442
+        });
443
+
444
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
445
+            return new \OC\AppConfig($c->getDatabaseConnection());
446
+        });
447
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
448
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
449
+
450
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
451
+            return new \OC\L10N\Factory(
452
+                $c->getConfig(),
453
+                $c->getRequest(),
454
+                $c->getUserSession(),
455
+                \OC::$SERVERROOT
456
+            );
457
+        });
458
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
459
+
460
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
461
+            $config = $c->getConfig();
462
+            $cacheFactory = $c->getMemCacheFactory();
463
+            $request = $c->getRequest();
464
+            return new \OC\URLGenerator(
465
+                $config,
466
+                $cacheFactory,
467
+                $request
468
+            );
469
+        });
470
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
471
+
472
+        $this->registerService('AppHelper', function ($c) {
473
+            return new \OC\AppHelper();
474
+        });
475
+        $this->registerAlias('AppFetcher', AppFetcher::class);
476
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
477
+
478
+        $this->registerService(\OCP\ICache::class, function ($c) {
479
+            return new Cache\File();
480
+        });
481
+        $this->registerAlias('UserCache', \OCP\ICache::class);
482
+
483
+        $this->registerService(Factory::class, function (Server $c) {
484
+
485
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
486
+                ArrayCache::class,
487
+                ArrayCache::class,
488
+                ArrayCache::class
489
+            );
490
+            $config = $c->getConfig();
491
+            $request = $c->getRequest();
492
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
493
+
494
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
495
+                $v = \OC_App::getAppVersions();
496
+                $v['core'] = implode(',', \OC_Util::getVersion());
497
+                $version = implode(',', $v);
498
+                $instanceId = \OC_Util::getInstanceId();
499
+                $path = \OC::$SERVERROOT;
500
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
501
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
502
+                    $config->getSystemValue('memcache.local', null),
503
+                    $config->getSystemValue('memcache.distributed', null),
504
+                    $config->getSystemValue('memcache.locking', null)
505
+                );
506
+            }
507
+            return $arrayCacheFactory;
508
+
509
+        });
510
+        $this->registerAlias('MemCacheFactory', Factory::class);
511
+        $this->registerAlias(ICacheFactory::class, Factory::class);
512
+
513
+        $this->registerService('RedisFactory', function (Server $c) {
514
+            $systemConfig = $c->getSystemConfig();
515
+            return new RedisFactory($systemConfig);
516
+        });
517
+
518
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
519
+            return new \OC\Activity\Manager(
520
+                $c->getRequest(),
521
+                $c->getUserSession(),
522
+                $c->getConfig(),
523
+                $c->query(IValidator::class)
524
+            );
525
+        });
526
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
527
+
528
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
529
+            return new \OC\Activity\EventMerger(
530
+                $c->getL10N('lib')
531
+            );
532
+        });
533
+        $this->registerAlias(IValidator::class, Validator::class);
534
+
535
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
536
+            return new AvatarManager(
537
+                $c->query(\OC\User\Manager::class),
538
+                $c->getAppDataDir('avatar'),
539
+                $c->getL10N('lib'),
540
+                $c->getLogger(),
541
+                $c->getConfig()
542
+            );
543
+        });
544
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
545
+
546
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
547
+
548
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
549
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
550
+            $logger = Log::getLogClass($logType);
551
+            call_user_func(array($logger, 'init'));
552
+            $config = $this->getSystemConfig();
553
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
554
+
555
+            return new Log($logger, $config, null, $registry);
556
+        });
557
+        $this->registerAlias('Logger', \OCP\ILogger::class);
558
+
559
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
560
+            $config = $c->getConfig();
561
+            return new \OC\BackgroundJob\JobList(
562
+                $c->getDatabaseConnection(),
563
+                $config,
564
+                new TimeFactory()
565
+            );
566
+        });
567
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
568
+
569
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
570
+            $cacheFactory = $c->getMemCacheFactory();
571
+            $logger = $c->getLogger();
572
+            if ($cacheFactory->isAvailableLowLatency()) {
573
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
574
+            } else {
575
+                $router = new \OC\Route\Router($logger);
576
+            }
577
+            return $router;
578
+        });
579
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
580
+
581
+        $this->registerService(\OCP\ISearch::class, function ($c) {
582
+            return new Search();
583
+        });
584
+        $this->registerAlias('Search', \OCP\ISearch::class);
585
+
586
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
587
+            return new \OC\Security\RateLimiting\Limiter(
588
+                $this->getUserSession(),
589
+                $this->getRequest(),
590
+                new \OC\AppFramework\Utility\TimeFactory(),
591
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
592
+            );
593
+        });
594
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
595
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
596
+                $this->getMemCacheFactory(),
597
+                new \OC\AppFramework\Utility\TimeFactory()
598
+            );
599
+        });
600
+
601
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
602
+            return new SecureRandom();
603
+        });
604
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
605
+
606
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
607
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
608
+        });
609
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
610
+
611
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
612
+            return new Hasher($c->getConfig());
613
+        });
614
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
615
+
616
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
617
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
618
+        });
619
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
620
+
621
+        $this->registerService(IDBConnection::class, function (Server $c) {
622
+            $systemConfig = $c->getSystemConfig();
623
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
624
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
625
+            if (!$factory->isValidType($type)) {
626
+                throw new \OC\DatabaseException('Invalid database type');
627
+            }
628
+            $connectionParams = $factory->createConnectionParams();
629
+            $connection = $factory->getConnection($type, $connectionParams);
630
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
631
+            return $connection;
632
+        });
633
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
634
+
635
+        $this->registerService('HTTPHelper', function (Server $c) {
636
+            $config = $c->getConfig();
637
+            return new HTTPHelper(
638
+                $config,
639
+                $c->getHTTPClientService()
640
+            );
641
+        });
642
+
643
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
644
+            $user = \OC_User::getUser();
645
+            $uid = $user ? $user : null;
646
+            return new ClientService(
647
+                $c->getConfig(),
648
+                new \OC\Security\CertificateManager(
649
+                    $uid,
650
+                    new View(),
651
+                    $c->getConfig(),
652
+                    $c->getLogger(),
653
+                    $c->getSecureRandom()
654
+                )
655
+            );
656
+        });
657
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
658
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
659
+            $eventLogger = new EventLogger();
660
+            if ($c->getSystemConfig()->getValue('debug', false)) {
661
+                // In debug mode, module is being activated by default
662
+                $eventLogger->activate();
663
+            }
664
+            return $eventLogger;
665
+        });
666
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
667
+
668
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
669
+            $queryLogger = new QueryLogger();
670
+            if ($c->getSystemConfig()->getValue('debug', false)) {
671
+                // In debug mode, module is being activated by default
672
+                $queryLogger->activate();
673
+            }
674
+            return $queryLogger;
675
+        });
676
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
677
+
678
+        $this->registerService(TempManager::class, function (Server $c) {
679
+            return new TempManager(
680
+                $c->getLogger(),
681
+                $c->getConfig()
682
+            );
683
+        });
684
+        $this->registerAlias('TempManager', TempManager::class);
685
+        $this->registerAlias(ITempManager::class, TempManager::class);
686
+
687
+        $this->registerService(AppManager::class, function (Server $c) {
688
+            return new \OC\App\AppManager(
689
+                $c->getUserSession(),
690
+                $c->query(\OC\AppConfig::class),
691
+                $c->getGroupManager(),
692
+                $c->getMemCacheFactory(),
693
+                $c->getEventDispatcher()
694
+            );
695
+        });
696
+        $this->registerAlias('AppManager', AppManager::class);
697
+        $this->registerAlias(IAppManager::class, AppManager::class);
698
+
699
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
700
+            return new DateTimeZone(
701
+                $c->getConfig(),
702
+                $c->getSession()
703
+            );
704
+        });
705
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
706
+
707
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
708
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
709
+
710
+            return new DateTimeFormatter(
711
+                $c->getDateTimeZone()->getTimeZone(),
712
+                $c->getL10N('lib', $language)
713
+            );
714
+        });
715
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
716
+
717
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
718
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
719
+            $listener = new UserMountCacheListener($mountCache);
720
+            $listener->listen($c->getUserManager());
721
+            return $mountCache;
722
+        });
723
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
724
+
725
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
726
+            $loader = \OC\Files\Filesystem::getLoader();
727
+            $mountCache = $c->query('UserMountCache');
728
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
729
+
730
+            // builtin providers
731
+
732
+            $config = $c->getConfig();
733
+            $manager->registerProvider(new CacheMountProvider($config));
734
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
735
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
736
+
737
+            return $manager;
738
+        });
739
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
740
+
741
+        $this->registerService('IniWrapper', function ($c) {
742
+            return new IniGetWrapper();
743
+        });
744
+        $this->registerService('AsyncCommandBus', function (Server $c) {
745
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
746
+            if ($busClass) {
747
+                list($app, $class) = explode('::', $busClass, 2);
748
+                if ($c->getAppManager()->isInstalled($app)) {
749
+                    \OC_App::loadApp($app);
750
+                    return $c->query($class);
751
+                } else {
752
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
753
+                }
754
+            } else {
755
+                $jobList = $c->getJobList();
756
+                return new CronBus($jobList);
757
+            }
758
+        });
759
+        $this->registerService('TrustedDomainHelper', function ($c) {
760
+            return new TrustedDomainHelper($this->getConfig());
761
+        });
762
+        $this->registerService('Throttler', function (Server $c) {
763
+            return new Throttler(
764
+                $c->getDatabaseConnection(),
765
+                new TimeFactory(),
766
+                $c->getLogger(),
767
+                $c->getConfig()
768
+            );
769
+        });
770
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
771
+            // IConfig and IAppManager requires a working database. This code
772
+            // might however be called when ownCloud is not yet setup.
773
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
774
+                $config = $c->getConfig();
775
+                $appManager = $c->getAppManager();
776
+            } else {
777
+                $config = null;
778
+                $appManager = null;
779
+            }
780
+
781
+            return new Checker(
782
+                new EnvironmentHelper(),
783
+                new FileAccessHelper(),
784
+                new AppLocator(),
785
+                $config,
786
+                $c->getMemCacheFactory(),
787
+                $appManager,
788
+                $c->getTempManager()
789
+            );
790
+        });
791
+        $this->registerService(\OCP\IRequest::class, function ($c) {
792
+            if (isset($this['urlParams'])) {
793
+                $urlParams = $this['urlParams'];
794
+            } else {
795
+                $urlParams = [];
796
+            }
797
+
798
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
799
+                && in_array('fakeinput', stream_get_wrappers())
800
+            ) {
801
+                $stream = 'fakeinput://data';
802
+            } else {
803
+                $stream = 'php://input';
804
+            }
805
+
806
+            return new Request(
807
+                [
808
+                    'get' => $_GET,
809
+                    'post' => $_POST,
810
+                    'files' => $_FILES,
811
+                    'server' => $_SERVER,
812
+                    'env' => $_ENV,
813
+                    'cookies' => $_COOKIE,
814
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
815
+                        ? $_SERVER['REQUEST_METHOD']
816
+                        : null,
817
+                    'urlParams' => $urlParams,
818
+                ],
819
+                $this->getSecureRandom(),
820
+                $this->getConfig(),
821
+                $this->getCsrfTokenManager(),
822
+                $stream
823
+            );
824
+        });
825
+        $this->registerAlias('Request', \OCP\IRequest::class);
826
+
827
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
828
+            return new Mailer(
829
+                $c->getConfig(),
830
+                $c->getLogger(),
831
+                $c->query(Defaults::class),
832
+                $c->getURLGenerator(),
833
+                $c->getL10N('lib')
834
+            );
835
+        });
836
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
837
+
838
+        $this->registerService('LDAPProvider', function (Server $c) {
839
+            $config = $c->getConfig();
840
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
841
+            if (is_null($factoryClass)) {
842
+                throw new \Exception('ldapProviderFactory not set');
843
+            }
844
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
845
+            $factory = new $factoryClass($this);
846
+            return $factory->getLDAPProvider();
847
+        });
848
+        $this->registerService(ILockingProvider::class, function (Server $c) {
849
+            $ini = $c->getIniWrapper();
850
+            $config = $c->getConfig();
851
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
852
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
853
+                /** @var \OC\Memcache\Factory $memcacheFactory */
854
+                $memcacheFactory = $c->getMemCacheFactory();
855
+                $memcache = $memcacheFactory->createLocking('lock');
856
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
857
+                    return new MemcacheLockingProvider($memcache, $ttl);
858
+                }
859
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
860
+            }
861
+            return new NoopLockingProvider();
862
+        });
863
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
864
+
865
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
866
+            return new \OC\Files\Mount\Manager();
867
+        });
868
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
869
+
870
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
871
+            return new \OC\Files\Type\Detection(
872
+                $c->getURLGenerator(),
873
+                \OC::$configDir,
874
+                \OC::$SERVERROOT . '/resources/config/'
875
+            );
876
+        });
877
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
878
+
879
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
880
+            return new \OC\Files\Type\Loader(
881
+                $c->getDatabaseConnection()
882
+            );
883
+        });
884
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
885
+        $this->registerService(BundleFetcher::class, function () {
886
+            return new BundleFetcher($this->getL10N('lib'));
887
+        });
888
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
889
+            return new Manager(
890
+                $c->query(IValidator::class)
891
+            );
892
+        });
893
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
894
+
895
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
896
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
897
+            $manager->registerCapability(function () use ($c) {
898
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
899
+            });
900
+            $manager->registerCapability(function () use ($c) {
901
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
902
+            });
903
+            return $manager;
904
+        });
905
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
906
+
907
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
908
+            $config = $c->getConfig();
909
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
910
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
911
+            $factory = new $factoryClass($this);
912
+            $manager = $factory->getManager();
913
+
914
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
915
+                $manager = $c->getUserManager();
916
+                $user = $manager->get($id);
917
+                if(is_null($user)) {
918
+                    $l = $c->getL10N('core');
919
+                    $displayName = $l->t('Unknown user');
920
+                } else {
921
+                    $displayName = $user->getDisplayName();
922
+                }
923
+                return $displayName;
924
+            });
925
+
926
+            return $manager;
927
+        });
928
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
929
+
930
+        $this->registerService('ThemingDefaults', function (Server $c) {
931
+            /*
932 932
 			 * Dark magic for autoloader.
933 933
 			 * If we do a class_exists it will try to load the class which will
934 934
 			 * make composer cache the result. Resulting in errors when enabling
935 935
 			 * the theming app.
936 936
 			 */
937
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
938
-			if (isset($prefixes['OCA\\Theming\\'])) {
939
-				$classExists = true;
940
-			} else {
941
-				$classExists = false;
942
-			}
943
-
944
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
945
-				return new ThemingDefaults(
946
-					$c->getConfig(),
947
-					$c->getL10N('theming'),
948
-					$c->getURLGenerator(),
949
-					$c->getAppDataDir('theming'),
950
-					$c->getMemCacheFactory(),
951
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
952
-					$this->getAppManager()
953
-				);
954
-			}
955
-			return new \OC_Defaults();
956
-		});
957
-		$this->registerService(SCSSCacher::class, function (Server $c) {
958
-			/** @var Factory $cacheFactory */
959
-			$cacheFactory = $c->query(Factory::class);
960
-			return new SCSSCacher(
961
-				$c->getLogger(),
962
-				$c->query(\OC\Files\AppData\Factory::class),
963
-				$c->getURLGenerator(),
964
-				$c->getConfig(),
965
-				$c->getThemingDefaults(),
966
-				\OC::$SERVERROOT,
967
-				$cacheFactory->createDistributed('SCSS')
968
-			);
969
-		});
970
-		$this->registerService(EventDispatcher::class, function () {
971
-			return new EventDispatcher();
972
-		});
973
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
974
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
975
-
976
-		$this->registerService('CryptoWrapper', function (Server $c) {
977
-			// FIXME: Instantiiated here due to cyclic dependency
978
-			$request = new Request(
979
-				[
980
-					'get' => $_GET,
981
-					'post' => $_POST,
982
-					'files' => $_FILES,
983
-					'server' => $_SERVER,
984
-					'env' => $_ENV,
985
-					'cookies' => $_COOKIE,
986
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
987
-						? $_SERVER['REQUEST_METHOD']
988
-						: null,
989
-				],
990
-				$c->getSecureRandom(),
991
-				$c->getConfig()
992
-			);
993
-
994
-			return new CryptoWrapper(
995
-				$c->getConfig(),
996
-				$c->getCrypto(),
997
-				$c->getSecureRandom(),
998
-				$request
999
-			);
1000
-		});
1001
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1002
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1003
-
1004
-			return new CsrfTokenManager(
1005
-				$tokenGenerator,
1006
-				$c->query(SessionStorage::class)
1007
-			);
1008
-		});
1009
-		$this->registerService(SessionStorage::class, function (Server $c) {
1010
-			return new SessionStorage($c->getSession());
1011
-		});
1012
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1013
-			return new ContentSecurityPolicyManager();
1014
-		});
1015
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1016
-
1017
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1018
-			return new ContentSecurityPolicyNonceManager(
1019
-				$c->getCsrfTokenManager(),
1020
-				$c->getRequest()
1021
-			);
1022
-		});
1023
-
1024
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1025
-			$config = $c->getConfig();
1026
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1027
-			/** @var \OCP\Share\IProviderFactory $factory */
1028
-			$factory = new $factoryClass($this);
1029
-
1030
-			$manager = new \OC\Share20\Manager(
1031
-				$c->getLogger(),
1032
-				$c->getConfig(),
1033
-				$c->getSecureRandom(),
1034
-				$c->getHasher(),
1035
-				$c->getMountManager(),
1036
-				$c->getGroupManager(),
1037
-				$c->getL10N('lib'),
1038
-				$c->getL10NFactory(),
1039
-				$factory,
1040
-				$c->getUserManager(),
1041
-				$c->getLazyRootFolder(),
1042
-				$c->getEventDispatcher(),
1043
-				$c->getMailer(),
1044
-				$c->getURLGenerator(),
1045
-				$c->getThemingDefaults()
1046
-			);
1047
-
1048
-			return $manager;
1049
-		});
1050
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1051
-
1052
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1053
-			$instance = new Collaboration\Collaborators\Search($c);
1054
-
1055
-			// register default plugins
1056
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1057
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1058
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1059
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1060
-
1061
-			return $instance;
1062
-		});
1063
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1064
-
1065
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1066
-
1067
-		$this->registerService('SettingsManager', function (Server $c) {
1068
-			$manager = new \OC\Settings\Manager(
1069
-				$c->getLogger(),
1070
-				$c->getDatabaseConnection(),
1071
-				$c->getL10N('lib'),
1072
-				$c->getConfig(),
1073
-				$c->getEncryptionManager(),
1074
-				$c->getUserManager(),
1075
-				$c->getLockingProvider(),
1076
-				$c->getRequest(),
1077
-				$c->getURLGenerator(),
1078
-				$c->query(AccountManager::class),
1079
-				$c->getGroupManager(),
1080
-				$c->getL10NFactory(),
1081
-				$c->getAppManager()
1082
-			);
1083
-			return $manager;
1084
-		});
1085
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1086
-			return new \OC\Files\AppData\Factory(
1087
-				$c->getRootFolder(),
1088
-				$c->getSystemConfig()
1089
-			);
1090
-		});
1091
-
1092
-		$this->registerService('LockdownManager', function (Server $c) {
1093
-			return new LockdownManager(function () use ($c) {
1094
-				return $c->getSession();
1095
-			});
1096
-		});
1097
-
1098
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1099
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1100
-		});
1101
-
1102
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1103
-			return new CloudIdManager();
1104
-		});
1105
-
1106
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1107
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1108
-
1109
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1110
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1111
-
1112
-		$this->registerService(Defaults::class, function (Server $c) {
1113
-			return new Defaults(
1114
-				$c->getThemingDefaults()
1115
-			);
1116
-		});
1117
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1118
-
1119
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1120
-			return $c->query(\OCP\IUserSession::class)->getSession();
1121
-		});
1122
-
1123
-		$this->registerService(IShareHelper::class, function (Server $c) {
1124
-			return new ShareHelper(
1125
-				$c->query(\OCP\Share\IManager::class)
1126
-			);
1127
-		});
1128
-
1129
-		$this->registerService(Installer::class, function(Server $c) {
1130
-			return new Installer(
1131
-				$c->getAppFetcher(),
1132
-				$c->getHTTPClientService(),
1133
-				$c->getTempManager(),
1134
-				$c->getLogger(),
1135
-				$c->getConfig()
1136
-			);
1137
-		});
1138
-
1139
-		$this->registerService(IApiFactory::class, function(Server $c) {
1140
-			return new ApiFactory($c->getHTTPClientService());
1141
-		});
1142
-
1143
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1144
-			$memcacheFactory = $c->getMemCacheFactory();
1145
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1146
-		});
1147
-
1148
-		$this->registerService(IContactsStore::class, function(Server $c) {
1149
-			return new ContactsStore(
1150
-				$c->getContactsManager(),
1151
-				$c->getConfig(),
1152
-				$c->getUserManager(),
1153
-				$c->getGroupManager()
1154
-			);
1155
-		});
1156
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1157
-
1158
-		$this->connectDispatcher();
1159
-	}
1160
-
1161
-	/**
1162
-	 * @return \OCP\Calendar\IManager
1163
-	 */
1164
-	public function getCalendarManager() {
1165
-		return $this->query('CalendarManager');
1166
-	}
1167
-
1168
-	private function connectDispatcher() {
1169
-		$dispatcher = $this->getEventDispatcher();
1170
-
1171
-		// Delete avatar on user deletion
1172
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1173
-			$logger = $this->getLogger();
1174
-			$manager = $this->getAvatarManager();
1175
-			/** @var IUser $user */
1176
-			$user = $e->getSubject();
1177
-
1178
-			try {
1179
-				$avatar = $manager->getAvatar($user->getUID());
1180
-				$avatar->remove();
1181
-			} catch (NotFoundException $e) {
1182
-				// no avatar to remove
1183
-			} catch (\Exception $e) {
1184
-				// Ignore exceptions
1185
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1186
-			}
1187
-		});
1188
-
1189
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1190
-			$manager = $this->getAvatarManager();
1191
-			/** @var IUser $user */
1192
-			$user = $e->getSubject();
1193
-			$feature = $e->getArgument('feature');
1194
-			$oldValue = $e->getArgument('oldValue');
1195
-			$value = $e->getArgument('value');
1196
-
1197
-			try {
1198
-				$avatar = $manager->getAvatar($user->getUID());
1199
-				$avatar->userChanged($feature, $oldValue, $value);
1200
-			} catch (NotFoundException $e) {
1201
-				// no avatar to remove
1202
-			}
1203
-		});
1204
-	}
1205
-
1206
-	/**
1207
-	 * @return \OCP\Contacts\IManager
1208
-	 */
1209
-	public function getContactsManager() {
1210
-		return $this->query('ContactsManager');
1211
-	}
1212
-
1213
-	/**
1214
-	 * @return \OC\Encryption\Manager
1215
-	 */
1216
-	public function getEncryptionManager() {
1217
-		return $this->query('EncryptionManager');
1218
-	}
1219
-
1220
-	/**
1221
-	 * @return \OC\Encryption\File
1222
-	 */
1223
-	public function getEncryptionFilesHelper() {
1224
-		return $this->query('EncryptionFileHelper');
1225
-	}
1226
-
1227
-	/**
1228
-	 * @return \OCP\Encryption\Keys\IStorage
1229
-	 */
1230
-	public function getEncryptionKeyStorage() {
1231
-		return $this->query('EncryptionKeyStorage');
1232
-	}
1233
-
1234
-	/**
1235
-	 * The current request object holding all information about the request
1236
-	 * currently being processed is returned from this method.
1237
-	 * In case the current execution was not initiated by a web request null is returned
1238
-	 *
1239
-	 * @return \OCP\IRequest
1240
-	 */
1241
-	public function getRequest() {
1242
-		return $this->query('Request');
1243
-	}
1244
-
1245
-	/**
1246
-	 * Returns the preview manager which can create preview images for a given file
1247
-	 *
1248
-	 * @return \OCP\IPreview
1249
-	 */
1250
-	public function getPreviewManager() {
1251
-		return $this->query('PreviewManager');
1252
-	}
1253
-
1254
-	/**
1255
-	 * Returns the tag manager which can get and set tags for different object types
1256
-	 *
1257
-	 * @see \OCP\ITagManager::load()
1258
-	 * @return \OCP\ITagManager
1259
-	 */
1260
-	public function getTagManager() {
1261
-		return $this->query('TagManager');
1262
-	}
1263
-
1264
-	/**
1265
-	 * Returns the system-tag manager
1266
-	 *
1267
-	 * @return \OCP\SystemTag\ISystemTagManager
1268
-	 *
1269
-	 * @since 9.0.0
1270
-	 */
1271
-	public function getSystemTagManager() {
1272
-		return $this->query('SystemTagManager');
1273
-	}
1274
-
1275
-	/**
1276
-	 * Returns the system-tag object mapper
1277
-	 *
1278
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1279
-	 *
1280
-	 * @since 9.0.0
1281
-	 */
1282
-	public function getSystemTagObjectMapper() {
1283
-		return $this->query('SystemTagObjectMapper');
1284
-	}
1285
-
1286
-	/**
1287
-	 * Returns the avatar manager, used for avatar functionality
1288
-	 *
1289
-	 * @return \OCP\IAvatarManager
1290
-	 */
1291
-	public function getAvatarManager() {
1292
-		return $this->query('AvatarManager');
1293
-	}
1294
-
1295
-	/**
1296
-	 * Returns the root folder of ownCloud's data directory
1297
-	 *
1298
-	 * @return \OCP\Files\IRootFolder
1299
-	 */
1300
-	public function getRootFolder() {
1301
-		return $this->query('LazyRootFolder');
1302
-	}
1303
-
1304
-	/**
1305
-	 * Returns the root folder of ownCloud's data directory
1306
-	 * This is the lazy variant so this gets only initialized once it
1307
-	 * is actually used.
1308
-	 *
1309
-	 * @return \OCP\Files\IRootFolder
1310
-	 */
1311
-	public function getLazyRootFolder() {
1312
-		return $this->query('LazyRootFolder');
1313
-	}
1314
-
1315
-	/**
1316
-	 * Returns a view to ownCloud's files folder
1317
-	 *
1318
-	 * @param string $userId user ID
1319
-	 * @return \OCP\Files\Folder|null
1320
-	 */
1321
-	public function getUserFolder($userId = null) {
1322
-		if ($userId === null) {
1323
-			$user = $this->getUserSession()->getUser();
1324
-			if (!$user) {
1325
-				return null;
1326
-			}
1327
-			$userId = $user->getUID();
1328
-		}
1329
-		$root = $this->getRootFolder();
1330
-		return $root->getUserFolder($userId);
1331
-	}
1332
-
1333
-	/**
1334
-	 * Returns an app-specific view in ownClouds data directory
1335
-	 *
1336
-	 * @return \OCP\Files\Folder
1337
-	 * @deprecated since 9.2.0 use IAppData
1338
-	 */
1339
-	public function getAppFolder() {
1340
-		$dir = '/' . \OC_App::getCurrentApp();
1341
-		$root = $this->getRootFolder();
1342
-		if (!$root->nodeExists($dir)) {
1343
-			$folder = $root->newFolder($dir);
1344
-		} else {
1345
-			$folder = $root->get($dir);
1346
-		}
1347
-		return $folder;
1348
-	}
1349
-
1350
-	/**
1351
-	 * @return \OC\User\Manager
1352
-	 */
1353
-	public function getUserManager() {
1354
-		return $this->query('UserManager');
1355
-	}
1356
-
1357
-	/**
1358
-	 * @return \OC\Group\Manager
1359
-	 */
1360
-	public function getGroupManager() {
1361
-		return $this->query('GroupManager');
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OC\User\Session
1366
-	 */
1367
-	public function getUserSession() {
1368
-		return $this->query('UserSession');
1369
-	}
1370
-
1371
-	/**
1372
-	 * @return \OCP\ISession
1373
-	 */
1374
-	public function getSession() {
1375
-		return $this->query('UserSession')->getSession();
1376
-	}
1377
-
1378
-	/**
1379
-	 * @param \OCP\ISession $session
1380
-	 */
1381
-	public function setSession(\OCP\ISession $session) {
1382
-		$this->query(SessionStorage::class)->setSession($session);
1383
-		$this->query('UserSession')->setSession($session);
1384
-		$this->query(Store::class)->setSession($session);
1385
-	}
1386
-
1387
-	/**
1388
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1389
-	 */
1390
-	public function getTwoFactorAuthManager() {
1391
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1392
-	}
1393
-
1394
-	/**
1395
-	 * @return \OC\NavigationManager
1396
-	 */
1397
-	public function getNavigationManager() {
1398
-		return $this->query('NavigationManager');
1399
-	}
1400
-
1401
-	/**
1402
-	 * @return \OCP\IConfig
1403
-	 */
1404
-	public function getConfig() {
1405
-		return $this->query('AllConfig');
1406
-	}
1407
-
1408
-	/**
1409
-	 * @return \OC\SystemConfig
1410
-	 */
1411
-	public function getSystemConfig() {
1412
-		return $this->query('SystemConfig');
1413
-	}
1414
-
1415
-	/**
1416
-	 * Returns the app config manager
1417
-	 *
1418
-	 * @return \OCP\IAppConfig
1419
-	 */
1420
-	public function getAppConfig() {
1421
-		return $this->query('AppConfig');
1422
-	}
1423
-
1424
-	/**
1425
-	 * @return \OCP\L10N\IFactory
1426
-	 */
1427
-	public function getL10NFactory() {
1428
-		return $this->query('L10NFactory');
1429
-	}
1430
-
1431
-	/**
1432
-	 * get an L10N instance
1433
-	 *
1434
-	 * @param string $app appid
1435
-	 * @param string $lang
1436
-	 * @return IL10N
1437
-	 */
1438
-	public function getL10N($app, $lang = null) {
1439
-		return $this->getL10NFactory()->get($app, $lang);
1440
-	}
1441
-
1442
-	/**
1443
-	 * @return \OCP\IURLGenerator
1444
-	 */
1445
-	public function getURLGenerator() {
1446
-		return $this->query('URLGenerator');
1447
-	}
1448
-
1449
-	/**
1450
-	 * @return \OCP\IHelper
1451
-	 */
1452
-	public function getHelper() {
1453
-		return $this->query('AppHelper');
1454
-	}
1455
-
1456
-	/**
1457
-	 * @return AppFetcher
1458
-	 */
1459
-	public function getAppFetcher() {
1460
-		return $this->query(AppFetcher::class);
1461
-	}
1462
-
1463
-	/**
1464
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1465
-	 * getMemCacheFactory() instead.
1466
-	 *
1467
-	 * @return \OCP\ICache
1468
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1469
-	 */
1470
-	public function getCache() {
1471
-		return $this->query('UserCache');
1472
-	}
1473
-
1474
-	/**
1475
-	 * Returns an \OCP\CacheFactory instance
1476
-	 *
1477
-	 * @return \OCP\ICacheFactory
1478
-	 */
1479
-	public function getMemCacheFactory() {
1480
-		return $this->query('MemCacheFactory');
1481
-	}
1482
-
1483
-	/**
1484
-	 * Returns an \OC\RedisFactory instance
1485
-	 *
1486
-	 * @return \OC\RedisFactory
1487
-	 */
1488
-	public function getGetRedisFactory() {
1489
-		return $this->query('RedisFactory');
1490
-	}
1491
-
1492
-
1493
-	/**
1494
-	 * Returns the current session
1495
-	 *
1496
-	 * @return \OCP\IDBConnection
1497
-	 */
1498
-	public function getDatabaseConnection() {
1499
-		return $this->query('DatabaseConnection');
1500
-	}
1501
-
1502
-	/**
1503
-	 * Returns the activity manager
1504
-	 *
1505
-	 * @return \OCP\Activity\IManager
1506
-	 */
1507
-	public function getActivityManager() {
1508
-		return $this->query('ActivityManager');
1509
-	}
1510
-
1511
-	/**
1512
-	 * Returns an job list for controlling background jobs
1513
-	 *
1514
-	 * @return \OCP\BackgroundJob\IJobList
1515
-	 */
1516
-	public function getJobList() {
1517
-		return $this->query('JobList');
1518
-	}
1519
-
1520
-	/**
1521
-	 * Returns a logger instance
1522
-	 *
1523
-	 * @return \OCP\ILogger
1524
-	 */
1525
-	public function getLogger() {
1526
-		return $this->query('Logger');
1527
-	}
1528
-
1529
-	/**
1530
-	 * Returns a router for generating and matching urls
1531
-	 *
1532
-	 * @return \OCP\Route\IRouter
1533
-	 */
1534
-	public function getRouter() {
1535
-		return $this->query('Router');
1536
-	}
1537
-
1538
-	/**
1539
-	 * Returns a search instance
1540
-	 *
1541
-	 * @return \OCP\ISearch
1542
-	 */
1543
-	public function getSearch() {
1544
-		return $this->query('Search');
1545
-	}
1546
-
1547
-	/**
1548
-	 * Returns a SecureRandom instance
1549
-	 *
1550
-	 * @return \OCP\Security\ISecureRandom
1551
-	 */
1552
-	public function getSecureRandom() {
1553
-		return $this->query('SecureRandom');
1554
-	}
1555
-
1556
-	/**
1557
-	 * Returns a Crypto instance
1558
-	 *
1559
-	 * @return \OCP\Security\ICrypto
1560
-	 */
1561
-	public function getCrypto() {
1562
-		return $this->query('Crypto');
1563
-	}
1564
-
1565
-	/**
1566
-	 * Returns a Hasher instance
1567
-	 *
1568
-	 * @return \OCP\Security\IHasher
1569
-	 */
1570
-	public function getHasher() {
1571
-		return $this->query('Hasher');
1572
-	}
1573
-
1574
-	/**
1575
-	 * Returns a CredentialsManager instance
1576
-	 *
1577
-	 * @return \OCP\Security\ICredentialsManager
1578
-	 */
1579
-	public function getCredentialsManager() {
1580
-		return $this->query('CredentialsManager');
1581
-	}
1582
-
1583
-	/**
1584
-	 * Returns an instance of the HTTP helper class
1585
-	 *
1586
-	 * @deprecated Use getHTTPClientService()
1587
-	 * @return \OC\HTTPHelper
1588
-	 */
1589
-	public function getHTTPHelper() {
1590
-		return $this->query('HTTPHelper');
1591
-	}
1592
-
1593
-	/**
1594
-	 * Get the certificate manager for the user
1595
-	 *
1596
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1597
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1598
-	 */
1599
-	public function getCertificateManager($userId = '') {
1600
-		if ($userId === '') {
1601
-			$userSession = $this->getUserSession();
1602
-			$user = $userSession->getUser();
1603
-			if (is_null($user)) {
1604
-				return null;
1605
-			}
1606
-			$userId = $user->getUID();
1607
-		}
1608
-		return new CertificateManager(
1609
-			$userId,
1610
-			new View(),
1611
-			$this->getConfig(),
1612
-			$this->getLogger(),
1613
-			$this->getSecureRandom()
1614
-		);
1615
-	}
1616
-
1617
-	/**
1618
-	 * Returns an instance of the HTTP client service
1619
-	 *
1620
-	 * @return \OCP\Http\Client\IClientService
1621
-	 */
1622
-	public function getHTTPClientService() {
1623
-		return $this->query('HttpClientService');
1624
-	}
1625
-
1626
-	/**
1627
-	 * Create a new event source
1628
-	 *
1629
-	 * @return \OCP\IEventSource
1630
-	 */
1631
-	public function createEventSource() {
1632
-		return new \OC_EventSource();
1633
-	}
1634
-
1635
-	/**
1636
-	 * Get the active event logger
1637
-	 *
1638
-	 * The returned logger only logs data when debug mode is enabled
1639
-	 *
1640
-	 * @return \OCP\Diagnostics\IEventLogger
1641
-	 */
1642
-	public function getEventLogger() {
1643
-		return $this->query('EventLogger');
1644
-	}
1645
-
1646
-	/**
1647
-	 * Get the active query logger
1648
-	 *
1649
-	 * The returned logger only logs data when debug mode is enabled
1650
-	 *
1651
-	 * @return \OCP\Diagnostics\IQueryLogger
1652
-	 */
1653
-	public function getQueryLogger() {
1654
-		return $this->query('QueryLogger');
1655
-	}
1656
-
1657
-	/**
1658
-	 * Get the manager for temporary files and folders
1659
-	 *
1660
-	 * @return \OCP\ITempManager
1661
-	 */
1662
-	public function getTempManager() {
1663
-		return $this->query('TempManager');
1664
-	}
1665
-
1666
-	/**
1667
-	 * Get the app manager
1668
-	 *
1669
-	 * @return \OCP\App\IAppManager
1670
-	 */
1671
-	public function getAppManager() {
1672
-		return $this->query('AppManager');
1673
-	}
1674
-
1675
-	/**
1676
-	 * Creates a new mailer
1677
-	 *
1678
-	 * @return \OCP\Mail\IMailer
1679
-	 */
1680
-	public function getMailer() {
1681
-		return $this->query('Mailer');
1682
-	}
1683
-
1684
-	/**
1685
-	 * Get the webroot
1686
-	 *
1687
-	 * @return string
1688
-	 */
1689
-	public function getWebRoot() {
1690
-		return $this->webRoot;
1691
-	}
1692
-
1693
-	/**
1694
-	 * @return \OC\OCSClient
1695
-	 */
1696
-	public function getOcsClient() {
1697
-		return $this->query('OcsClient');
1698
-	}
1699
-
1700
-	/**
1701
-	 * @return \OCP\IDateTimeZone
1702
-	 */
1703
-	public function getDateTimeZone() {
1704
-		return $this->query('DateTimeZone');
1705
-	}
1706
-
1707
-	/**
1708
-	 * @return \OCP\IDateTimeFormatter
1709
-	 */
1710
-	public function getDateTimeFormatter() {
1711
-		return $this->query('DateTimeFormatter');
1712
-	}
1713
-
1714
-	/**
1715
-	 * @return \OCP\Files\Config\IMountProviderCollection
1716
-	 */
1717
-	public function getMountProviderCollection() {
1718
-		return $this->query('MountConfigManager');
1719
-	}
1720
-
1721
-	/**
1722
-	 * Get the IniWrapper
1723
-	 *
1724
-	 * @return IniGetWrapper
1725
-	 */
1726
-	public function getIniWrapper() {
1727
-		return $this->query('IniWrapper');
1728
-	}
1729
-
1730
-	/**
1731
-	 * @return \OCP\Command\IBus
1732
-	 */
1733
-	public function getCommandBus() {
1734
-		return $this->query('AsyncCommandBus');
1735
-	}
1736
-
1737
-	/**
1738
-	 * Get the trusted domain helper
1739
-	 *
1740
-	 * @return TrustedDomainHelper
1741
-	 */
1742
-	public function getTrustedDomainHelper() {
1743
-		return $this->query('TrustedDomainHelper');
1744
-	}
1745
-
1746
-	/**
1747
-	 * Get the locking provider
1748
-	 *
1749
-	 * @return \OCP\Lock\ILockingProvider
1750
-	 * @since 8.1.0
1751
-	 */
1752
-	public function getLockingProvider() {
1753
-		return $this->query('LockingProvider');
1754
-	}
1755
-
1756
-	/**
1757
-	 * @return \OCP\Files\Mount\IMountManager
1758
-	 **/
1759
-	function getMountManager() {
1760
-		return $this->query('MountManager');
1761
-	}
1762
-
1763
-	/** @return \OCP\Files\Config\IUserMountCache */
1764
-	function getUserMountCache() {
1765
-		return $this->query('UserMountCache');
1766
-	}
1767
-
1768
-	/**
1769
-	 * Get the MimeTypeDetector
1770
-	 *
1771
-	 * @return \OCP\Files\IMimeTypeDetector
1772
-	 */
1773
-	public function getMimeTypeDetector() {
1774
-		return $this->query('MimeTypeDetector');
1775
-	}
1776
-
1777
-	/**
1778
-	 * Get the MimeTypeLoader
1779
-	 *
1780
-	 * @return \OCP\Files\IMimeTypeLoader
1781
-	 */
1782
-	public function getMimeTypeLoader() {
1783
-		return $this->query('MimeTypeLoader');
1784
-	}
1785
-
1786
-	/**
1787
-	 * Get the manager of all the capabilities
1788
-	 *
1789
-	 * @return \OC\CapabilitiesManager
1790
-	 */
1791
-	public function getCapabilitiesManager() {
1792
-		return $this->query('CapabilitiesManager');
1793
-	}
1794
-
1795
-	/**
1796
-	 * Get the EventDispatcher
1797
-	 *
1798
-	 * @return EventDispatcherInterface
1799
-	 * @since 8.2.0
1800
-	 */
1801
-	public function getEventDispatcher() {
1802
-		return $this->query('EventDispatcher');
1803
-	}
1804
-
1805
-	/**
1806
-	 * Get the Notification Manager
1807
-	 *
1808
-	 * @return \OCP\Notification\IManager
1809
-	 * @since 8.2.0
1810
-	 */
1811
-	public function getNotificationManager() {
1812
-		return $this->query('NotificationManager');
1813
-	}
1814
-
1815
-	/**
1816
-	 * @return \OCP\Comments\ICommentsManager
1817
-	 */
1818
-	public function getCommentsManager() {
1819
-		return $this->query('CommentsManager');
1820
-	}
1821
-
1822
-	/**
1823
-	 * @return \OCA\Theming\ThemingDefaults
1824
-	 */
1825
-	public function getThemingDefaults() {
1826
-		return $this->query('ThemingDefaults');
1827
-	}
1828
-
1829
-	/**
1830
-	 * @return \OC\IntegrityCheck\Checker
1831
-	 */
1832
-	public function getIntegrityCodeChecker() {
1833
-		return $this->query('IntegrityCodeChecker');
1834
-	}
1835
-
1836
-	/**
1837
-	 * @return \OC\Session\CryptoWrapper
1838
-	 */
1839
-	public function getSessionCryptoWrapper() {
1840
-		return $this->query('CryptoWrapper');
1841
-	}
1842
-
1843
-	/**
1844
-	 * @return CsrfTokenManager
1845
-	 */
1846
-	public function getCsrfTokenManager() {
1847
-		return $this->query('CsrfTokenManager');
1848
-	}
1849
-
1850
-	/**
1851
-	 * @return Throttler
1852
-	 */
1853
-	public function getBruteForceThrottler() {
1854
-		return $this->query('Throttler');
1855
-	}
1856
-
1857
-	/**
1858
-	 * @return IContentSecurityPolicyManager
1859
-	 */
1860
-	public function getContentSecurityPolicyManager() {
1861
-		return $this->query('ContentSecurityPolicyManager');
1862
-	}
1863
-
1864
-	/**
1865
-	 * @return ContentSecurityPolicyNonceManager
1866
-	 */
1867
-	public function getContentSecurityPolicyNonceManager() {
1868
-		return $this->query('ContentSecurityPolicyNonceManager');
1869
-	}
1870
-
1871
-	/**
1872
-	 * Not a public API as of 8.2, wait for 9.0
1873
-	 *
1874
-	 * @return \OCA\Files_External\Service\BackendService
1875
-	 */
1876
-	public function getStoragesBackendService() {
1877
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1878
-	}
1879
-
1880
-	/**
1881
-	 * Not a public API as of 8.2, wait for 9.0
1882
-	 *
1883
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1884
-	 */
1885
-	public function getGlobalStoragesService() {
1886
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1887
-	}
1888
-
1889
-	/**
1890
-	 * Not a public API as of 8.2, wait for 9.0
1891
-	 *
1892
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1893
-	 */
1894
-	public function getUserGlobalStoragesService() {
1895
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1896
-	}
1897
-
1898
-	/**
1899
-	 * Not a public API as of 8.2, wait for 9.0
1900
-	 *
1901
-	 * @return \OCA\Files_External\Service\UserStoragesService
1902
-	 */
1903
-	public function getUserStoragesService() {
1904
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1905
-	}
1906
-
1907
-	/**
1908
-	 * @return \OCP\Share\IManager
1909
-	 */
1910
-	public function getShareManager() {
1911
-		return $this->query('ShareManager');
1912
-	}
1913
-
1914
-	/**
1915
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1916
-	 */
1917
-	public function getCollaboratorSearch() {
1918
-		return $this->query('CollaboratorSearch');
1919
-	}
1920
-
1921
-	/**
1922
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1923
-	 */
1924
-	public function getAutoCompleteManager(){
1925
-		return $this->query(IManager::class);
1926
-	}
1927
-
1928
-	/**
1929
-	 * Returns the LDAP Provider
1930
-	 *
1931
-	 * @return \OCP\LDAP\ILDAPProvider
1932
-	 */
1933
-	public function getLDAPProvider() {
1934
-		return $this->query('LDAPProvider');
1935
-	}
1936
-
1937
-	/**
1938
-	 * @return \OCP\Settings\IManager
1939
-	 */
1940
-	public function getSettingsManager() {
1941
-		return $this->query('SettingsManager');
1942
-	}
1943
-
1944
-	/**
1945
-	 * @return \OCP\Files\IAppData
1946
-	 */
1947
-	public function getAppDataDir($app) {
1948
-		/** @var \OC\Files\AppData\Factory $factory */
1949
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1950
-		return $factory->get($app);
1951
-	}
1952
-
1953
-	/**
1954
-	 * @return \OCP\Lockdown\ILockdownManager
1955
-	 */
1956
-	public function getLockdownManager() {
1957
-		return $this->query('LockdownManager');
1958
-	}
1959
-
1960
-	/**
1961
-	 * @return \OCP\Federation\ICloudIdManager
1962
-	 */
1963
-	public function getCloudIdManager() {
1964
-		return $this->query(ICloudIdManager::class);
1965
-	}
1966
-
1967
-	/**
1968
-	 * @return \OCP\Remote\Api\IApiFactory
1969
-	 */
1970
-	public function getRemoteApiFactory() {
1971
-		return $this->query(IApiFactory::class);
1972
-	}
1973
-
1974
-	/**
1975
-	 * @return \OCP\Remote\IInstanceFactory
1976
-	 */
1977
-	public function getRemoteInstanceFactory() {
1978
-		return $this->query(IInstanceFactory::class);
1979
-	}
937
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
938
+            if (isset($prefixes['OCA\\Theming\\'])) {
939
+                $classExists = true;
940
+            } else {
941
+                $classExists = false;
942
+            }
943
+
944
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
945
+                return new ThemingDefaults(
946
+                    $c->getConfig(),
947
+                    $c->getL10N('theming'),
948
+                    $c->getURLGenerator(),
949
+                    $c->getAppDataDir('theming'),
950
+                    $c->getMemCacheFactory(),
951
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
952
+                    $this->getAppManager()
953
+                );
954
+            }
955
+            return new \OC_Defaults();
956
+        });
957
+        $this->registerService(SCSSCacher::class, function (Server $c) {
958
+            /** @var Factory $cacheFactory */
959
+            $cacheFactory = $c->query(Factory::class);
960
+            return new SCSSCacher(
961
+                $c->getLogger(),
962
+                $c->query(\OC\Files\AppData\Factory::class),
963
+                $c->getURLGenerator(),
964
+                $c->getConfig(),
965
+                $c->getThemingDefaults(),
966
+                \OC::$SERVERROOT,
967
+                $cacheFactory->createDistributed('SCSS')
968
+            );
969
+        });
970
+        $this->registerService(EventDispatcher::class, function () {
971
+            return new EventDispatcher();
972
+        });
973
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
974
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
975
+
976
+        $this->registerService('CryptoWrapper', function (Server $c) {
977
+            // FIXME: Instantiiated here due to cyclic dependency
978
+            $request = new Request(
979
+                [
980
+                    'get' => $_GET,
981
+                    'post' => $_POST,
982
+                    'files' => $_FILES,
983
+                    'server' => $_SERVER,
984
+                    'env' => $_ENV,
985
+                    'cookies' => $_COOKIE,
986
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
987
+                        ? $_SERVER['REQUEST_METHOD']
988
+                        : null,
989
+                ],
990
+                $c->getSecureRandom(),
991
+                $c->getConfig()
992
+            );
993
+
994
+            return new CryptoWrapper(
995
+                $c->getConfig(),
996
+                $c->getCrypto(),
997
+                $c->getSecureRandom(),
998
+                $request
999
+            );
1000
+        });
1001
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1002
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1003
+
1004
+            return new CsrfTokenManager(
1005
+                $tokenGenerator,
1006
+                $c->query(SessionStorage::class)
1007
+            );
1008
+        });
1009
+        $this->registerService(SessionStorage::class, function (Server $c) {
1010
+            return new SessionStorage($c->getSession());
1011
+        });
1012
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1013
+            return new ContentSecurityPolicyManager();
1014
+        });
1015
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1016
+
1017
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1018
+            return new ContentSecurityPolicyNonceManager(
1019
+                $c->getCsrfTokenManager(),
1020
+                $c->getRequest()
1021
+            );
1022
+        });
1023
+
1024
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1025
+            $config = $c->getConfig();
1026
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1027
+            /** @var \OCP\Share\IProviderFactory $factory */
1028
+            $factory = new $factoryClass($this);
1029
+
1030
+            $manager = new \OC\Share20\Manager(
1031
+                $c->getLogger(),
1032
+                $c->getConfig(),
1033
+                $c->getSecureRandom(),
1034
+                $c->getHasher(),
1035
+                $c->getMountManager(),
1036
+                $c->getGroupManager(),
1037
+                $c->getL10N('lib'),
1038
+                $c->getL10NFactory(),
1039
+                $factory,
1040
+                $c->getUserManager(),
1041
+                $c->getLazyRootFolder(),
1042
+                $c->getEventDispatcher(),
1043
+                $c->getMailer(),
1044
+                $c->getURLGenerator(),
1045
+                $c->getThemingDefaults()
1046
+            );
1047
+
1048
+            return $manager;
1049
+        });
1050
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1051
+
1052
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1053
+            $instance = new Collaboration\Collaborators\Search($c);
1054
+
1055
+            // register default plugins
1056
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1057
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1058
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1059
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1060
+
1061
+            return $instance;
1062
+        });
1063
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1064
+
1065
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1066
+
1067
+        $this->registerService('SettingsManager', function (Server $c) {
1068
+            $manager = new \OC\Settings\Manager(
1069
+                $c->getLogger(),
1070
+                $c->getDatabaseConnection(),
1071
+                $c->getL10N('lib'),
1072
+                $c->getConfig(),
1073
+                $c->getEncryptionManager(),
1074
+                $c->getUserManager(),
1075
+                $c->getLockingProvider(),
1076
+                $c->getRequest(),
1077
+                $c->getURLGenerator(),
1078
+                $c->query(AccountManager::class),
1079
+                $c->getGroupManager(),
1080
+                $c->getL10NFactory(),
1081
+                $c->getAppManager()
1082
+            );
1083
+            return $manager;
1084
+        });
1085
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1086
+            return new \OC\Files\AppData\Factory(
1087
+                $c->getRootFolder(),
1088
+                $c->getSystemConfig()
1089
+            );
1090
+        });
1091
+
1092
+        $this->registerService('LockdownManager', function (Server $c) {
1093
+            return new LockdownManager(function () use ($c) {
1094
+                return $c->getSession();
1095
+            });
1096
+        });
1097
+
1098
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1099
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1100
+        });
1101
+
1102
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1103
+            return new CloudIdManager();
1104
+        });
1105
+
1106
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1107
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1108
+
1109
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1110
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1111
+
1112
+        $this->registerService(Defaults::class, function (Server $c) {
1113
+            return new Defaults(
1114
+                $c->getThemingDefaults()
1115
+            );
1116
+        });
1117
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1118
+
1119
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1120
+            return $c->query(\OCP\IUserSession::class)->getSession();
1121
+        });
1122
+
1123
+        $this->registerService(IShareHelper::class, function (Server $c) {
1124
+            return new ShareHelper(
1125
+                $c->query(\OCP\Share\IManager::class)
1126
+            );
1127
+        });
1128
+
1129
+        $this->registerService(Installer::class, function(Server $c) {
1130
+            return new Installer(
1131
+                $c->getAppFetcher(),
1132
+                $c->getHTTPClientService(),
1133
+                $c->getTempManager(),
1134
+                $c->getLogger(),
1135
+                $c->getConfig()
1136
+            );
1137
+        });
1138
+
1139
+        $this->registerService(IApiFactory::class, function(Server $c) {
1140
+            return new ApiFactory($c->getHTTPClientService());
1141
+        });
1142
+
1143
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1144
+            $memcacheFactory = $c->getMemCacheFactory();
1145
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1146
+        });
1147
+
1148
+        $this->registerService(IContactsStore::class, function(Server $c) {
1149
+            return new ContactsStore(
1150
+                $c->getContactsManager(),
1151
+                $c->getConfig(),
1152
+                $c->getUserManager(),
1153
+                $c->getGroupManager()
1154
+            );
1155
+        });
1156
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1157
+
1158
+        $this->connectDispatcher();
1159
+    }
1160
+
1161
+    /**
1162
+     * @return \OCP\Calendar\IManager
1163
+     */
1164
+    public function getCalendarManager() {
1165
+        return $this->query('CalendarManager');
1166
+    }
1167
+
1168
+    private function connectDispatcher() {
1169
+        $dispatcher = $this->getEventDispatcher();
1170
+
1171
+        // Delete avatar on user deletion
1172
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1173
+            $logger = $this->getLogger();
1174
+            $manager = $this->getAvatarManager();
1175
+            /** @var IUser $user */
1176
+            $user = $e->getSubject();
1177
+
1178
+            try {
1179
+                $avatar = $manager->getAvatar($user->getUID());
1180
+                $avatar->remove();
1181
+            } catch (NotFoundException $e) {
1182
+                // no avatar to remove
1183
+            } catch (\Exception $e) {
1184
+                // Ignore exceptions
1185
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1186
+            }
1187
+        });
1188
+
1189
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1190
+            $manager = $this->getAvatarManager();
1191
+            /** @var IUser $user */
1192
+            $user = $e->getSubject();
1193
+            $feature = $e->getArgument('feature');
1194
+            $oldValue = $e->getArgument('oldValue');
1195
+            $value = $e->getArgument('value');
1196
+
1197
+            try {
1198
+                $avatar = $manager->getAvatar($user->getUID());
1199
+                $avatar->userChanged($feature, $oldValue, $value);
1200
+            } catch (NotFoundException $e) {
1201
+                // no avatar to remove
1202
+            }
1203
+        });
1204
+    }
1205
+
1206
+    /**
1207
+     * @return \OCP\Contacts\IManager
1208
+     */
1209
+    public function getContactsManager() {
1210
+        return $this->query('ContactsManager');
1211
+    }
1212
+
1213
+    /**
1214
+     * @return \OC\Encryption\Manager
1215
+     */
1216
+    public function getEncryptionManager() {
1217
+        return $this->query('EncryptionManager');
1218
+    }
1219
+
1220
+    /**
1221
+     * @return \OC\Encryption\File
1222
+     */
1223
+    public function getEncryptionFilesHelper() {
1224
+        return $this->query('EncryptionFileHelper');
1225
+    }
1226
+
1227
+    /**
1228
+     * @return \OCP\Encryption\Keys\IStorage
1229
+     */
1230
+    public function getEncryptionKeyStorage() {
1231
+        return $this->query('EncryptionKeyStorage');
1232
+    }
1233
+
1234
+    /**
1235
+     * The current request object holding all information about the request
1236
+     * currently being processed is returned from this method.
1237
+     * In case the current execution was not initiated by a web request null is returned
1238
+     *
1239
+     * @return \OCP\IRequest
1240
+     */
1241
+    public function getRequest() {
1242
+        return $this->query('Request');
1243
+    }
1244
+
1245
+    /**
1246
+     * Returns the preview manager which can create preview images for a given file
1247
+     *
1248
+     * @return \OCP\IPreview
1249
+     */
1250
+    public function getPreviewManager() {
1251
+        return $this->query('PreviewManager');
1252
+    }
1253
+
1254
+    /**
1255
+     * Returns the tag manager which can get and set tags for different object types
1256
+     *
1257
+     * @see \OCP\ITagManager::load()
1258
+     * @return \OCP\ITagManager
1259
+     */
1260
+    public function getTagManager() {
1261
+        return $this->query('TagManager');
1262
+    }
1263
+
1264
+    /**
1265
+     * Returns the system-tag manager
1266
+     *
1267
+     * @return \OCP\SystemTag\ISystemTagManager
1268
+     *
1269
+     * @since 9.0.0
1270
+     */
1271
+    public function getSystemTagManager() {
1272
+        return $this->query('SystemTagManager');
1273
+    }
1274
+
1275
+    /**
1276
+     * Returns the system-tag object mapper
1277
+     *
1278
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1279
+     *
1280
+     * @since 9.0.0
1281
+     */
1282
+    public function getSystemTagObjectMapper() {
1283
+        return $this->query('SystemTagObjectMapper');
1284
+    }
1285
+
1286
+    /**
1287
+     * Returns the avatar manager, used for avatar functionality
1288
+     *
1289
+     * @return \OCP\IAvatarManager
1290
+     */
1291
+    public function getAvatarManager() {
1292
+        return $this->query('AvatarManager');
1293
+    }
1294
+
1295
+    /**
1296
+     * Returns the root folder of ownCloud's data directory
1297
+     *
1298
+     * @return \OCP\Files\IRootFolder
1299
+     */
1300
+    public function getRootFolder() {
1301
+        return $this->query('LazyRootFolder');
1302
+    }
1303
+
1304
+    /**
1305
+     * Returns the root folder of ownCloud's data directory
1306
+     * This is the lazy variant so this gets only initialized once it
1307
+     * is actually used.
1308
+     *
1309
+     * @return \OCP\Files\IRootFolder
1310
+     */
1311
+    public function getLazyRootFolder() {
1312
+        return $this->query('LazyRootFolder');
1313
+    }
1314
+
1315
+    /**
1316
+     * Returns a view to ownCloud's files folder
1317
+     *
1318
+     * @param string $userId user ID
1319
+     * @return \OCP\Files\Folder|null
1320
+     */
1321
+    public function getUserFolder($userId = null) {
1322
+        if ($userId === null) {
1323
+            $user = $this->getUserSession()->getUser();
1324
+            if (!$user) {
1325
+                return null;
1326
+            }
1327
+            $userId = $user->getUID();
1328
+        }
1329
+        $root = $this->getRootFolder();
1330
+        return $root->getUserFolder($userId);
1331
+    }
1332
+
1333
+    /**
1334
+     * Returns an app-specific view in ownClouds data directory
1335
+     *
1336
+     * @return \OCP\Files\Folder
1337
+     * @deprecated since 9.2.0 use IAppData
1338
+     */
1339
+    public function getAppFolder() {
1340
+        $dir = '/' . \OC_App::getCurrentApp();
1341
+        $root = $this->getRootFolder();
1342
+        if (!$root->nodeExists($dir)) {
1343
+            $folder = $root->newFolder($dir);
1344
+        } else {
1345
+            $folder = $root->get($dir);
1346
+        }
1347
+        return $folder;
1348
+    }
1349
+
1350
+    /**
1351
+     * @return \OC\User\Manager
1352
+     */
1353
+    public function getUserManager() {
1354
+        return $this->query('UserManager');
1355
+    }
1356
+
1357
+    /**
1358
+     * @return \OC\Group\Manager
1359
+     */
1360
+    public function getGroupManager() {
1361
+        return $this->query('GroupManager');
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OC\User\Session
1366
+     */
1367
+    public function getUserSession() {
1368
+        return $this->query('UserSession');
1369
+    }
1370
+
1371
+    /**
1372
+     * @return \OCP\ISession
1373
+     */
1374
+    public function getSession() {
1375
+        return $this->query('UserSession')->getSession();
1376
+    }
1377
+
1378
+    /**
1379
+     * @param \OCP\ISession $session
1380
+     */
1381
+    public function setSession(\OCP\ISession $session) {
1382
+        $this->query(SessionStorage::class)->setSession($session);
1383
+        $this->query('UserSession')->setSession($session);
1384
+        $this->query(Store::class)->setSession($session);
1385
+    }
1386
+
1387
+    /**
1388
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1389
+     */
1390
+    public function getTwoFactorAuthManager() {
1391
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1392
+    }
1393
+
1394
+    /**
1395
+     * @return \OC\NavigationManager
1396
+     */
1397
+    public function getNavigationManager() {
1398
+        return $this->query('NavigationManager');
1399
+    }
1400
+
1401
+    /**
1402
+     * @return \OCP\IConfig
1403
+     */
1404
+    public function getConfig() {
1405
+        return $this->query('AllConfig');
1406
+    }
1407
+
1408
+    /**
1409
+     * @return \OC\SystemConfig
1410
+     */
1411
+    public function getSystemConfig() {
1412
+        return $this->query('SystemConfig');
1413
+    }
1414
+
1415
+    /**
1416
+     * Returns the app config manager
1417
+     *
1418
+     * @return \OCP\IAppConfig
1419
+     */
1420
+    public function getAppConfig() {
1421
+        return $this->query('AppConfig');
1422
+    }
1423
+
1424
+    /**
1425
+     * @return \OCP\L10N\IFactory
1426
+     */
1427
+    public function getL10NFactory() {
1428
+        return $this->query('L10NFactory');
1429
+    }
1430
+
1431
+    /**
1432
+     * get an L10N instance
1433
+     *
1434
+     * @param string $app appid
1435
+     * @param string $lang
1436
+     * @return IL10N
1437
+     */
1438
+    public function getL10N($app, $lang = null) {
1439
+        return $this->getL10NFactory()->get($app, $lang);
1440
+    }
1441
+
1442
+    /**
1443
+     * @return \OCP\IURLGenerator
1444
+     */
1445
+    public function getURLGenerator() {
1446
+        return $this->query('URLGenerator');
1447
+    }
1448
+
1449
+    /**
1450
+     * @return \OCP\IHelper
1451
+     */
1452
+    public function getHelper() {
1453
+        return $this->query('AppHelper');
1454
+    }
1455
+
1456
+    /**
1457
+     * @return AppFetcher
1458
+     */
1459
+    public function getAppFetcher() {
1460
+        return $this->query(AppFetcher::class);
1461
+    }
1462
+
1463
+    /**
1464
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1465
+     * getMemCacheFactory() instead.
1466
+     *
1467
+     * @return \OCP\ICache
1468
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1469
+     */
1470
+    public function getCache() {
1471
+        return $this->query('UserCache');
1472
+    }
1473
+
1474
+    /**
1475
+     * Returns an \OCP\CacheFactory instance
1476
+     *
1477
+     * @return \OCP\ICacheFactory
1478
+     */
1479
+    public function getMemCacheFactory() {
1480
+        return $this->query('MemCacheFactory');
1481
+    }
1482
+
1483
+    /**
1484
+     * Returns an \OC\RedisFactory instance
1485
+     *
1486
+     * @return \OC\RedisFactory
1487
+     */
1488
+    public function getGetRedisFactory() {
1489
+        return $this->query('RedisFactory');
1490
+    }
1491
+
1492
+
1493
+    /**
1494
+     * Returns the current session
1495
+     *
1496
+     * @return \OCP\IDBConnection
1497
+     */
1498
+    public function getDatabaseConnection() {
1499
+        return $this->query('DatabaseConnection');
1500
+    }
1501
+
1502
+    /**
1503
+     * Returns the activity manager
1504
+     *
1505
+     * @return \OCP\Activity\IManager
1506
+     */
1507
+    public function getActivityManager() {
1508
+        return $this->query('ActivityManager');
1509
+    }
1510
+
1511
+    /**
1512
+     * Returns an job list for controlling background jobs
1513
+     *
1514
+     * @return \OCP\BackgroundJob\IJobList
1515
+     */
1516
+    public function getJobList() {
1517
+        return $this->query('JobList');
1518
+    }
1519
+
1520
+    /**
1521
+     * Returns a logger instance
1522
+     *
1523
+     * @return \OCP\ILogger
1524
+     */
1525
+    public function getLogger() {
1526
+        return $this->query('Logger');
1527
+    }
1528
+
1529
+    /**
1530
+     * Returns a router for generating and matching urls
1531
+     *
1532
+     * @return \OCP\Route\IRouter
1533
+     */
1534
+    public function getRouter() {
1535
+        return $this->query('Router');
1536
+    }
1537
+
1538
+    /**
1539
+     * Returns a search instance
1540
+     *
1541
+     * @return \OCP\ISearch
1542
+     */
1543
+    public function getSearch() {
1544
+        return $this->query('Search');
1545
+    }
1546
+
1547
+    /**
1548
+     * Returns a SecureRandom instance
1549
+     *
1550
+     * @return \OCP\Security\ISecureRandom
1551
+     */
1552
+    public function getSecureRandom() {
1553
+        return $this->query('SecureRandom');
1554
+    }
1555
+
1556
+    /**
1557
+     * Returns a Crypto instance
1558
+     *
1559
+     * @return \OCP\Security\ICrypto
1560
+     */
1561
+    public function getCrypto() {
1562
+        return $this->query('Crypto');
1563
+    }
1564
+
1565
+    /**
1566
+     * Returns a Hasher instance
1567
+     *
1568
+     * @return \OCP\Security\IHasher
1569
+     */
1570
+    public function getHasher() {
1571
+        return $this->query('Hasher');
1572
+    }
1573
+
1574
+    /**
1575
+     * Returns a CredentialsManager instance
1576
+     *
1577
+     * @return \OCP\Security\ICredentialsManager
1578
+     */
1579
+    public function getCredentialsManager() {
1580
+        return $this->query('CredentialsManager');
1581
+    }
1582
+
1583
+    /**
1584
+     * Returns an instance of the HTTP helper class
1585
+     *
1586
+     * @deprecated Use getHTTPClientService()
1587
+     * @return \OC\HTTPHelper
1588
+     */
1589
+    public function getHTTPHelper() {
1590
+        return $this->query('HTTPHelper');
1591
+    }
1592
+
1593
+    /**
1594
+     * Get the certificate manager for the user
1595
+     *
1596
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1597
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1598
+     */
1599
+    public function getCertificateManager($userId = '') {
1600
+        if ($userId === '') {
1601
+            $userSession = $this->getUserSession();
1602
+            $user = $userSession->getUser();
1603
+            if (is_null($user)) {
1604
+                return null;
1605
+            }
1606
+            $userId = $user->getUID();
1607
+        }
1608
+        return new CertificateManager(
1609
+            $userId,
1610
+            new View(),
1611
+            $this->getConfig(),
1612
+            $this->getLogger(),
1613
+            $this->getSecureRandom()
1614
+        );
1615
+    }
1616
+
1617
+    /**
1618
+     * Returns an instance of the HTTP client service
1619
+     *
1620
+     * @return \OCP\Http\Client\IClientService
1621
+     */
1622
+    public function getHTTPClientService() {
1623
+        return $this->query('HttpClientService');
1624
+    }
1625
+
1626
+    /**
1627
+     * Create a new event source
1628
+     *
1629
+     * @return \OCP\IEventSource
1630
+     */
1631
+    public function createEventSource() {
1632
+        return new \OC_EventSource();
1633
+    }
1634
+
1635
+    /**
1636
+     * Get the active event logger
1637
+     *
1638
+     * The returned logger only logs data when debug mode is enabled
1639
+     *
1640
+     * @return \OCP\Diagnostics\IEventLogger
1641
+     */
1642
+    public function getEventLogger() {
1643
+        return $this->query('EventLogger');
1644
+    }
1645
+
1646
+    /**
1647
+     * Get the active query logger
1648
+     *
1649
+     * The returned logger only logs data when debug mode is enabled
1650
+     *
1651
+     * @return \OCP\Diagnostics\IQueryLogger
1652
+     */
1653
+    public function getQueryLogger() {
1654
+        return $this->query('QueryLogger');
1655
+    }
1656
+
1657
+    /**
1658
+     * Get the manager for temporary files and folders
1659
+     *
1660
+     * @return \OCP\ITempManager
1661
+     */
1662
+    public function getTempManager() {
1663
+        return $this->query('TempManager');
1664
+    }
1665
+
1666
+    /**
1667
+     * Get the app manager
1668
+     *
1669
+     * @return \OCP\App\IAppManager
1670
+     */
1671
+    public function getAppManager() {
1672
+        return $this->query('AppManager');
1673
+    }
1674
+
1675
+    /**
1676
+     * Creates a new mailer
1677
+     *
1678
+     * @return \OCP\Mail\IMailer
1679
+     */
1680
+    public function getMailer() {
1681
+        return $this->query('Mailer');
1682
+    }
1683
+
1684
+    /**
1685
+     * Get the webroot
1686
+     *
1687
+     * @return string
1688
+     */
1689
+    public function getWebRoot() {
1690
+        return $this->webRoot;
1691
+    }
1692
+
1693
+    /**
1694
+     * @return \OC\OCSClient
1695
+     */
1696
+    public function getOcsClient() {
1697
+        return $this->query('OcsClient');
1698
+    }
1699
+
1700
+    /**
1701
+     * @return \OCP\IDateTimeZone
1702
+     */
1703
+    public function getDateTimeZone() {
1704
+        return $this->query('DateTimeZone');
1705
+    }
1706
+
1707
+    /**
1708
+     * @return \OCP\IDateTimeFormatter
1709
+     */
1710
+    public function getDateTimeFormatter() {
1711
+        return $this->query('DateTimeFormatter');
1712
+    }
1713
+
1714
+    /**
1715
+     * @return \OCP\Files\Config\IMountProviderCollection
1716
+     */
1717
+    public function getMountProviderCollection() {
1718
+        return $this->query('MountConfigManager');
1719
+    }
1720
+
1721
+    /**
1722
+     * Get the IniWrapper
1723
+     *
1724
+     * @return IniGetWrapper
1725
+     */
1726
+    public function getIniWrapper() {
1727
+        return $this->query('IniWrapper');
1728
+    }
1729
+
1730
+    /**
1731
+     * @return \OCP\Command\IBus
1732
+     */
1733
+    public function getCommandBus() {
1734
+        return $this->query('AsyncCommandBus');
1735
+    }
1736
+
1737
+    /**
1738
+     * Get the trusted domain helper
1739
+     *
1740
+     * @return TrustedDomainHelper
1741
+     */
1742
+    public function getTrustedDomainHelper() {
1743
+        return $this->query('TrustedDomainHelper');
1744
+    }
1745
+
1746
+    /**
1747
+     * Get the locking provider
1748
+     *
1749
+     * @return \OCP\Lock\ILockingProvider
1750
+     * @since 8.1.0
1751
+     */
1752
+    public function getLockingProvider() {
1753
+        return $this->query('LockingProvider');
1754
+    }
1755
+
1756
+    /**
1757
+     * @return \OCP\Files\Mount\IMountManager
1758
+     **/
1759
+    function getMountManager() {
1760
+        return $this->query('MountManager');
1761
+    }
1762
+
1763
+    /** @return \OCP\Files\Config\IUserMountCache */
1764
+    function getUserMountCache() {
1765
+        return $this->query('UserMountCache');
1766
+    }
1767
+
1768
+    /**
1769
+     * Get the MimeTypeDetector
1770
+     *
1771
+     * @return \OCP\Files\IMimeTypeDetector
1772
+     */
1773
+    public function getMimeTypeDetector() {
1774
+        return $this->query('MimeTypeDetector');
1775
+    }
1776
+
1777
+    /**
1778
+     * Get the MimeTypeLoader
1779
+     *
1780
+     * @return \OCP\Files\IMimeTypeLoader
1781
+     */
1782
+    public function getMimeTypeLoader() {
1783
+        return $this->query('MimeTypeLoader');
1784
+    }
1785
+
1786
+    /**
1787
+     * Get the manager of all the capabilities
1788
+     *
1789
+     * @return \OC\CapabilitiesManager
1790
+     */
1791
+    public function getCapabilitiesManager() {
1792
+        return $this->query('CapabilitiesManager');
1793
+    }
1794
+
1795
+    /**
1796
+     * Get the EventDispatcher
1797
+     *
1798
+     * @return EventDispatcherInterface
1799
+     * @since 8.2.0
1800
+     */
1801
+    public function getEventDispatcher() {
1802
+        return $this->query('EventDispatcher');
1803
+    }
1804
+
1805
+    /**
1806
+     * Get the Notification Manager
1807
+     *
1808
+     * @return \OCP\Notification\IManager
1809
+     * @since 8.2.0
1810
+     */
1811
+    public function getNotificationManager() {
1812
+        return $this->query('NotificationManager');
1813
+    }
1814
+
1815
+    /**
1816
+     * @return \OCP\Comments\ICommentsManager
1817
+     */
1818
+    public function getCommentsManager() {
1819
+        return $this->query('CommentsManager');
1820
+    }
1821
+
1822
+    /**
1823
+     * @return \OCA\Theming\ThemingDefaults
1824
+     */
1825
+    public function getThemingDefaults() {
1826
+        return $this->query('ThemingDefaults');
1827
+    }
1828
+
1829
+    /**
1830
+     * @return \OC\IntegrityCheck\Checker
1831
+     */
1832
+    public function getIntegrityCodeChecker() {
1833
+        return $this->query('IntegrityCodeChecker');
1834
+    }
1835
+
1836
+    /**
1837
+     * @return \OC\Session\CryptoWrapper
1838
+     */
1839
+    public function getSessionCryptoWrapper() {
1840
+        return $this->query('CryptoWrapper');
1841
+    }
1842
+
1843
+    /**
1844
+     * @return CsrfTokenManager
1845
+     */
1846
+    public function getCsrfTokenManager() {
1847
+        return $this->query('CsrfTokenManager');
1848
+    }
1849
+
1850
+    /**
1851
+     * @return Throttler
1852
+     */
1853
+    public function getBruteForceThrottler() {
1854
+        return $this->query('Throttler');
1855
+    }
1856
+
1857
+    /**
1858
+     * @return IContentSecurityPolicyManager
1859
+     */
1860
+    public function getContentSecurityPolicyManager() {
1861
+        return $this->query('ContentSecurityPolicyManager');
1862
+    }
1863
+
1864
+    /**
1865
+     * @return ContentSecurityPolicyNonceManager
1866
+     */
1867
+    public function getContentSecurityPolicyNonceManager() {
1868
+        return $this->query('ContentSecurityPolicyNonceManager');
1869
+    }
1870
+
1871
+    /**
1872
+     * Not a public API as of 8.2, wait for 9.0
1873
+     *
1874
+     * @return \OCA\Files_External\Service\BackendService
1875
+     */
1876
+    public function getStoragesBackendService() {
1877
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1878
+    }
1879
+
1880
+    /**
1881
+     * Not a public API as of 8.2, wait for 9.0
1882
+     *
1883
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1884
+     */
1885
+    public function getGlobalStoragesService() {
1886
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1887
+    }
1888
+
1889
+    /**
1890
+     * Not a public API as of 8.2, wait for 9.0
1891
+     *
1892
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1893
+     */
1894
+    public function getUserGlobalStoragesService() {
1895
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1896
+    }
1897
+
1898
+    /**
1899
+     * Not a public API as of 8.2, wait for 9.0
1900
+     *
1901
+     * @return \OCA\Files_External\Service\UserStoragesService
1902
+     */
1903
+    public function getUserStoragesService() {
1904
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1905
+    }
1906
+
1907
+    /**
1908
+     * @return \OCP\Share\IManager
1909
+     */
1910
+    public function getShareManager() {
1911
+        return $this->query('ShareManager');
1912
+    }
1913
+
1914
+    /**
1915
+     * @return \OCP\Collaboration\Collaborators\ISearch
1916
+     */
1917
+    public function getCollaboratorSearch() {
1918
+        return $this->query('CollaboratorSearch');
1919
+    }
1920
+
1921
+    /**
1922
+     * @return \OCP\Collaboration\AutoComplete\IManager
1923
+     */
1924
+    public function getAutoCompleteManager(){
1925
+        return $this->query(IManager::class);
1926
+    }
1927
+
1928
+    /**
1929
+     * Returns the LDAP Provider
1930
+     *
1931
+     * @return \OCP\LDAP\ILDAPProvider
1932
+     */
1933
+    public function getLDAPProvider() {
1934
+        return $this->query('LDAPProvider');
1935
+    }
1936
+
1937
+    /**
1938
+     * @return \OCP\Settings\IManager
1939
+     */
1940
+    public function getSettingsManager() {
1941
+        return $this->query('SettingsManager');
1942
+    }
1943
+
1944
+    /**
1945
+     * @return \OCP\Files\IAppData
1946
+     */
1947
+    public function getAppDataDir($app) {
1948
+        /** @var \OC\Files\AppData\Factory $factory */
1949
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1950
+        return $factory->get($app);
1951
+    }
1952
+
1953
+    /**
1954
+     * @return \OCP\Lockdown\ILockdownManager
1955
+     */
1956
+    public function getLockdownManager() {
1957
+        return $this->query('LockdownManager');
1958
+    }
1959
+
1960
+    /**
1961
+     * @return \OCP\Federation\ICloudIdManager
1962
+     */
1963
+    public function getCloudIdManager() {
1964
+        return $this->query(ICloudIdManager::class);
1965
+    }
1966
+
1967
+    /**
1968
+     * @return \OCP\Remote\Api\IApiFactory
1969
+     */
1970
+    public function getRemoteApiFactory() {
1971
+        return $this->query(IApiFactory::class);
1972
+    }
1973
+
1974
+    /**
1975
+     * @return \OCP\Remote\IInstanceFactory
1976
+     */
1977
+    public function getRemoteInstanceFactory() {
1978
+        return $this->query(IInstanceFactory::class);
1979
+    }
1980 1980
 }
Please login to merge, or discard this patch.