Completed
Push — master ( 2f1209...695e32 )
by Joas
19:11 queued 10s
created
lib/public/IRequest.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@
 block discarded – undo
1 1
 <?php
2
-declare(strict_types=1);
2
+declare(strict_types = 1);
3 3
 /**
4 4
  * @copyright Copyright (c) 2016, ownCloud, Inc.
5 5
  *
Please login to merge, or discard this patch.
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -65,227 +65,227 @@
 block discarded – undo
65 65
  * @since 6.0.0
66 66
  */
67 67
 interface IRequest {
68
-	/**
69
-	 * @since 9.1.0
70
-	 */
71
-	const USER_AGENT_CLIENT_ANDROID = '/^Mozilla\/5\.0 \(Android\) (ownCloud|Nextcloud)\-android.*$/';
72
-
73
-	/**
74
-	 * @since 13.0.0
75
-	 */
76
-	const USER_AGENT_TALK_ANDROID = '/^Mozilla\/5\.0 \(Android\) Nextcloud\-Talk v.*$/';
77
-
78
-	/**
79
-	 * @since 9.1.0
80
-	 */
81
-	const USER_AGENT_CLIENT_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
82
-
83
-	/**
84
-	 * @since 9.1.0
85
-	 */
86
-	const USER_AGENT_CLIENT_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
87
-
88
-	/**
89
-	 * @since 13.0.0
90
-	 */
91
-	const USER_AGENT_TALK_IOS = '/^Mozilla\/5\.0 \(iOS\) Nextcloud\-Talk v.*$/';
92
-
93
-	/**
94
-	 * @param string $name
95
-	 *
96
-	 * @return string
97
-	 * @since 6.0.0
98
-	 */
99
-	public function getHeader(string $name): string;
100
-
101
-	/**
102
-	 * Lets you access post and get parameters by the index
103
-	 * In case of json requests the encoded json body is accessed
104
-	 *
105
-	 * @param string $key the key which you want to access in the URL Parameter
106
-	 *                     placeholder, $_POST or $_GET array.
107
-	 *                     The priority how they're returned is the following:
108
-	 *                     1. URL parameters
109
-	 *                     2. POST parameters
110
-	 *                     3. GET parameters
111
-	 * @param mixed $default If the key is not found, this value will be returned
112
-	 * @return mixed the content of the array
113
-	 * @since 6.0.0
114
-	 */
115
-	public function getParam(string $key, $default = null);
116
-
117
-
118
-	/**
119
-	 * Returns all params that were received, be it from the request
120
-	 *
121
-	 * (as GET or POST) or through the URL by the route
122
-	 *
123
-	 * @return array the array with all parameters
124
-	 * @since 6.0.0
125
-	 */
126
-	public function getParams(): array;
127
-
128
-	/**
129
-	 * Returns the method of the request
130
-	 *
131
-	 * @return string the method of the request (POST, GET, etc)
132
-	 * @since 6.0.0
133
-	 */
134
-	public function getMethod(): string;
135
-
136
-	/**
137
-	 * Shortcut for accessing an uploaded file through the $_FILES array
138
-	 *
139
-	 * @param string $key the key that will be taken from the $_FILES array
140
-	 * @return array the file in the $_FILES element
141
-	 * @since 6.0.0
142
-	 */
143
-	public function getUploadedFile(string $key);
144
-
145
-
146
-	/**
147
-	 * Shortcut for getting env variables
148
-	 *
149
-	 * @param string $key the key that will be taken from the $_ENV array
150
-	 * @return array the value in the $_ENV element
151
-	 * @since 6.0.0
152
-	 */
153
-	public function getEnv(string $key);
154
-
155
-
156
-	/**
157
-	 * Shortcut for getting cookie variables
158
-	 *
159
-	 * @param string $key the key that will be taken from the $_COOKIE array
160
-	 * @return string|null the value in the $_COOKIE element
161
-	 * @since 6.0.0
162
-	 */
163
-	public function getCookie(string $key);
164
-
165
-
166
-	/**
167
-	 * Checks if the CSRF check was correct
168
-	 *
169
-	 * @return bool true if CSRF check passed
170
-	 * @since 6.0.0
171
-	 */
172
-	public function passesCSRFCheck(): bool;
173
-
174
-	/**
175
-	 * Checks if the strict cookie has been sent with the request if the request
176
-	 * is including any cookies.
177
-	 *
178
-	 * @return bool
179
-	 * @since 9.0.0
180
-	 */
181
-	public function passesStrictCookieCheck(): bool;
182
-
183
-	/**
184
-	 * Checks if the lax cookie has been sent with the request if the request
185
-	 * is including any cookies.
186
-	 *
187
-	 * @return bool
188
-	 * @since 9.0.0
189
-	 */
190
-	public function passesLaxCookieCheck(): bool;
191
-
192
-	/**
193
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
194
-	 * If `mod_unique_id` is installed this value will be taken.
195
-	 *
196
-	 * @return string
197
-	 * @since 8.1.0
198
-	 */
199
-	public function getId(): string;
200
-
201
-	/**
202
-	 * Returns the remote address, if the connection came from a trusted proxy
203
-	 * and `forwarded_for_headers` has been configured then the IP address
204
-	 * specified in this header will be returned instead.
205
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
206
-	 *
207
-	 * @return string IP address
208
-	 * @since 8.1.0
209
-	 */
210
-	public function getRemoteAddress(): string;
211
-
212
-	/**
213
-	 * Returns the server protocol. It respects reverse proxy servers and load
214
-	 * balancers.
215
-	 *
216
-	 * @return string Server protocol (http or https)
217
-	 * @since 8.1.0
218
-	 */
219
-	public function getServerProtocol(): string;
220
-
221
-	/**
222
-	 * Returns the used HTTP protocol.
223
-	 *
224
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
225
-	 * @since 8.2.0
226
-	 */
227
-	public function getHttpProtocol(): string;
228
-
229
-	/**
230
-	 * Returns the request uri, even if the website uses one or more
231
-	 * reverse proxies
232
-	 *
233
-	 * @return string
234
-	 * @since 8.1.0
235
-	 */
236
-	public function getRequestUri(): string;
237
-
238
-	/**
239
-	 * Get raw PathInfo from request (not urldecoded)
240
-	 *
241
-	 * @throws \Exception
242
-	 * @return string Path info
243
-	 * @since 8.1.0
244
-	 */
245
-	public function getRawPathInfo(): string;
246
-
247
-	/**
248
-	 * Get PathInfo from request
249
-	 *
250
-	 * @throws \Exception
251
-	 * @return string|false Path info or false when not found
252
-	 * @since 8.1.0
253
-	 */
254
-	public function getPathInfo();
255
-
256
-	/**
257
-	 * Returns the script name, even if the website uses one or more
258
-	 * reverse proxies
259
-	 *
260
-	 * @return string the script name
261
-	 * @since 8.1.0
262
-	 */
263
-	public function getScriptName(): string;
264
-
265
-	/**
266
-	 * Checks whether the user agent matches a given regex
267
-	 *
268
-	 * @param array $agent array of agent names
269
-	 * @return bool true if at least one of the given agent matches, false otherwise
270
-	 * @since 8.1.0
271
-	 */
272
-	public function isUserAgent(array $agent): bool;
273
-
274
-	/**
275
-	 * Returns the unverified server host from the headers without checking
276
-	 * whether it is a trusted domain
277
-	 *
278
-	 * @return string Server host
279
-	 * @since 8.1.0
280
-	 */
281
-	public function getInsecureServerHost(): string;
282
-
283
-	/**
284
-	 * Returns the server host from the headers, or the first configured
285
-	 * trusted domain if the host isn't in the trusted list
286
-	 *
287
-	 * @return string Server host
288
-	 * @since 8.1.0
289
-	 */
290
-	public function getServerHost(): string;
68
+    /**
69
+     * @since 9.1.0
70
+     */
71
+    const USER_AGENT_CLIENT_ANDROID = '/^Mozilla\/5\.0 \(Android\) (ownCloud|Nextcloud)\-android.*$/';
72
+
73
+    /**
74
+     * @since 13.0.0
75
+     */
76
+    const USER_AGENT_TALK_ANDROID = '/^Mozilla\/5\.0 \(Android\) Nextcloud\-Talk v.*$/';
77
+
78
+    /**
79
+     * @since 9.1.0
80
+     */
81
+    const USER_AGENT_CLIENT_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
82
+
83
+    /**
84
+     * @since 9.1.0
85
+     */
86
+    const USER_AGENT_CLIENT_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
87
+
88
+    /**
89
+     * @since 13.0.0
90
+     */
91
+    const USER_AGENT_TALK_IOS = '/^Mozilla\/5\.0 \(iOS\) Nextcloud\-Talk v.*$/';
92
+
93
+    /**
94
+     * @param string $name
95
+     *
96
+     * @return string
97
+     * @since 6.0.0
98
+     */
99
+    public function getHeader(string $name): string;
100
+
101
+    /**
102
+     * Lets you access post and get parameters by the index
103
+     * In case of json requests the encoded json body is accessed
104
+     *
105
+     * @param string $key the key which you want to access in the URL Parameter
106
+     *                     placeholder, $_POST or $_GET array.
107
+     *                     The priority how they're returned is the following:
108
+     *                     1. URL parameters
109
+     *                     2. POST parameters
110
+     *                     3. GET parameters
111
+     * @param mixed $default If the key is not found, this value will be returned
112
+     * @return mixed the content of the array
113
+     * @since 6.0.0
114
+     */
115
+    public function getParam(string $key, $default = null);
116
+
117
+
118
+    /**
119
+     * Returns all params that were received, be it from the request
120
+     *
121
+     * (as GET or POST) or through the URL by the route
122
+     *
123
+     * @return array the array with all parameters
124
+     * @since 6.0.0
125
+     */
126
+    public function getParams(): array;
127
+
128
+    /**
129
+     * Returns the method of the request
130
+     *
131
+     * @return string the method of the request (POST, GET, etc)
132
+     * @since 6.0.0
133
+     */
134
+    public function getMethod(): string;
135
+
136
+    /**
137
+     * Shortcut for accessing an uploaded file through the $_FILES array
138
+     *
139
+     * @param string $key the key that will be taken from the $_FILES array
140
+     * @return array the file in the $_FILES element
141
+     * @since 6.0.0
142
+     */
143
+    public function getUploadedFile(string $key);
144
+
145
+
146
+    /**
147
+     * Shortcut for getting env variables
148
+     *
149
+     * @param string $key the key that will be taken from the $_ENV array
150
+     * @return array the value in the $_ENV element
151
+     * @since 6.0.0
152
+     */
153
+    public function getEnv(string $key);
154
+
155
+
156
+    /**
157
+     * Shortcut for getting cookie variables
158
+     *
159
+     * @param string $key the key that will be taken from the $_COOKIE array
160
+     * @return string|null the value in the $_COOKIE element
161
+     * @since 6.0.0
162
+     */
163
+    public function getCookie(string $key);
164
+
165
+
166
+    /**
167
+     * Checks if the CSRF check was correct
168
+     *
169
+     * @return bool true if CSRF check passed
170
+     * @since 6.0.0
171
+     */
172
+    public function passesCSRFCheck(): bool;
173
+
174
+    /**
175
+     * Checks if the strict cookie has been sent with the request if the request
176
+     * is including any cookies.
177
+     *
178
+     * @return bool
179
+     * @since 9.0.0
180
+     */
181
+    public function passesStrictCookieCheck(): bool;
182
+
183
+    /**
184
+     * Checks if the lax cookie has been sent with the request if the request
185
+     * is including any cookies.
186
+     *
187
+     * @return bool
188
+     * @since 9.0.0
189
+     */
190
+    public function passesLaxCookieCheck(): bool;
191
+
192
+    /**
193
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
194
+     * If `mod_unique_id` is installed this value will be taken.
195
+     *
196
+     * @return string
197
+     * @since 8.1.0
198
+     */
199
+    public function getId(): string;
200
+
201
+    /**
202
+     * Returns the remote address, if the connection came from a trusted proxy
203
+     * and `forwarded_for_headers` has been configured then the IP address
204
+     * specified in this header will be returned instead.
205
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
206
+     *
207
+     * @return string IP address
208
+     * @since 8.1.0
209
+     */
210
+    public function getRemoteAddress(): string;
211
+
212
+    /**
213
+     * Returns the server protocol. It respects reverse proxy servers and load
214
+     * balancers.
215
+     *
216
+     * @return string Server protocol (http or https)
217
+     * @since 8.1.0
218
+     */
219
+    public function getServerProtocol(): string;
220
+
221
+    /**
222
+     * Returns the used HTTP protocol.
223
+     *
224
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
225
+     * @since 8.2.0
226
+     */
227
+    public function getHttpProtocol(): string;
228
+
229
+    /**
230
+     * Returns the request uri, even if the website uses one or more
231
+     * reverse proxies
232
+     *
233
+     * @return string
234
+     * @since 8.1.0
235
+     */
236
+    public function getRequestUri(): string;
237
+
238
+    /**
239
+     * Get raw PathInfo from request (not urldecoded)
240
+     *
241
+     * @throws \Exception
242
+     * @return string Path info
243
+     * @since 8.1.0
244
+     */
245
+    public function getRawPathInfo(): string;
246
+
247
+    /**
248
+     * Get PathInfo from request
249
+     *
250
+     * @throws \Exception
251
+     * @return string|false Path info or false when not found
252
+     * @since 8.1.0
253
+     */
254
+    public function getPathInfo();
255
+
256
+    /**
257
+     * Returns the script name, even if the website uses one or more
258
+     * reverse proxies
259
+     *
260
+     * @return string the script name
261
+     * @since 8.1.0
262
+     */
263
+    public function getScriptName(): string;
264
+
265
+    /**
266
+     * Checks whether the user agent matches a given regex
267
+     *
268
+     * @param array $agent array of agent names
269
+     * @return bool true if at least one of the given agent matches, false otherwise
270
+     * @since 8.1.0
271
+     */
272
+    public function isUserAgent(array $agent): bool;
273
+
274
+    /**
275
+     * Returns the unverified server host from the headers without checking
276
+     * whether it is a trusted domain
277
+     *
278
+     * @return string Server host
279
+     * @since 8.1.0
280
+     */
281
+    public function getInsecureServerHost(): string;
282
+
283
+    /**
284
+     * Returns the server host from the headers, or the first configured
285
+     * trusted domain if the host isn't in the trusted list
286
+     *
287
+     * @return string Server host
288
+     * @since 8.1.0
289
+     */
290
+    public function getServerHost(): string;
291 291
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1834 added lines, -1834 removed lines patch added patch discarded remove patch
@@ -150,1843 +150,1843 @@
 block discarded – undo
150 150
  * TODO: hookup all manager classes
151 151
  */
152 152
 class Server extends ServerContainer implements IServerContainer {
153
-	/** @var string */
154
-	private $webRoot;
155
-
156
-	/**
157
-	 * @param string $webRoot
158
-	 * @param \OC\Config $config
159
-	 */
160
-	public function __construct($webRoot, \OC\Config $config) {
161
-		parent::__construct();
162
-		$this->webRoot = $webRoot;
163
-
164
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
165
-			return $c;
166
-		});
167
-
168
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
169
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
170
-
171
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
172
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
173
-
174
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
175
-
176
-
177
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
178
-			return new PreviewManager(
179
-				$c->getConfig(),
180
-				$c->getRootFolder(),
181
-				$c->getAppDataDir('preview'),
182
-				$c->getEventDispatcher(),
183
-				$c->getSession()->get('user_id')
184
-			);
185
-		});
186
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
187
-
188
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
189
-			return new \OC\Preview\Watcher(
190
-				$c->getAppDataDir('preview')
191
-			);
192
-		});
193
-
194
-		$this->registerService('EncryptionManager', function (Server $c) {
195
-			$view = new View();
196
-			$util = new Encryption\Util(
197
-				$view,
198
-				$c->getUserManager(),
199
-				$c->getGroupManager(),
200
-				$c->getConfig()
201
-			);
202
-			return new Encryption\Manager(
203
-				$c->getConfig(),
204
-				$c->getLogger(),
205
-				$c->getL10N('core'),
206
-				new View(),
207
-				$util,
208
-				new ArrayCache()
209
-			);
210
-		});
211
-
212
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
213
-			$util = new Encryption\Util(
214
-				new View(),
215
-				$c->getUserManager(),
216
-				$c->getGroupManager(),
217
-				$c->getConfig()
218
-			);
219
-			return new Encryption\File(
220
-				$util,
221
-				$c->getRootFolder(),
222
-				$c->getShareManager()
223
-			);
224
-		});
225
-
226
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
227
-			$view = new View();
228
-			$util = new Encryption\Util(
229
-				$view,
230
-				$c->getUserManager(),
231
-				$c->getGroupManager(),
232
-				$c->getConfig()
233
-			);
234
-
235
-			return new Encryption\Keys\Storage($view, $util);
236
-		});
237
-		$this->registerService('TagMapper', function (Server $c) {
238
-			return new TagMapper($c->getDatabaseConnection());
239
-		});
240
-
241
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
242
-			$tagMapper = $c->query('TagMapper');
243
-			return new TagManager($tagMapper, $c->getUserSession());
244
-		});
245
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
246
-
247
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
248
-			$config = $c->getConfig();
249
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250
-			return new $factoryClass($this);
251
-		});
252
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
-			return $c->query('SystemTagManagerFactory')->getManager();
254
-		});
255
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
-
257
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
-		});
260
-		$this->registerService('RootFolder', function (Server $c) {
261
-			$manager = \OC\Files\Filesystem::getMountManager(null);
262
-			$view = new View();
263
-			$root = new Root(
264
-				$manager,
265
-				$view,
266
-				null,
267
-				$c->getUserMountCache(),
268
-				$this->getLogger(),
269
-				$this->getUserManager()
270
-			);
271
-			$connector = new HookConnector($root, $view);
272
-			$connector->viewToNode();
273
-
274
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
-			$previewConnector->connectWatcher();
276
-
277
-			return $root;
278
-		});
279
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
-
281
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
-			return new LazyRoot(function () use ($c) {
283
-				return $c->query('RootFolder');
284
-			});
285
-		});
286
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
-
288
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
289
-			$config = $c->getConfig();
290
-			return new \OC\User\Manager($config);
291
-		});
292
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
293
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294
-
295
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
296
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
298
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299
-			});
300
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
301
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302
-			});
303
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
304
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305
-			});
306
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
307
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308
-			});
309
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311
-			});
312
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
316
-			});
317
-			return $groupManager;
318
-		});
319
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320
-
321
-		$this->registerService(Store::class, function (Server $c) {
322
-			$session = $c->getSession();
323
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
-				$tokenProvider = $c->query(IProvider::class);
325
-			} else {
326
-				$tokenProvider = null;
327
-			}
328
-			$logger = $c->getLogger();
329
-			return new Store($session, $logger, $tokenProvider);
330
-		});
331
-		$this->registerAlias(IStore::class, Store::class);
332
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
333
-			$dbConnection = $c->getDatabaseConnection();
334
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
335
-		});
336
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
337
-			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338
-			$crypto = $c->getCrypto();
339
-			$config = $c->getConfig();
340
-			$logger = $c->getLogger();
341
-			$timeFactory = new TimeFactory();
342
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
343
-		});
344
-		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345
-
346
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
347
-			$manager = $c->getUserManager();
348
-			$session = new \OC\Session\Memory('');
349
-			$timeFactory = new TimeFactory();
350
-			// Token providers might require a working database. This code
351
-			// might however be called when ownCloud is not yet setup.
352
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
353
-				$defaultTokenProvider = $c->query(IProvider::class);
354
-			} else {
355
-				$defaultTokenProvider = null;
356
-			}
357
-
358
-			$dispatcher = $c->getEventDispatcher();
359
-
360
-			$userSession = new \OC\User\Session(
361
-				$manager,
362
-				$session,
363
-				$timeFactory,
364
-				$defaultTokenProvider,
365
-				$c->getConfig(),
366
-				$c->getSecureRandom(),
367
-				$c->getLockdownManager(),
368
-				$c->getLogger()
369
-			);
370
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
371
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372
-			});
373
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
374
-				/** @var $user \OC\User\User */
375
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376
-			});
377
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
378
-				/** @var $user \OC\User\User */
379
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381
-			});
382
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
383
-				/** @var $user \OC\User\User */
384
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385
-			});
386
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
-			});
390
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
391
-				/** @var $user \OC\User\User */
392
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393
-			});
394
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
395
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396
-			});
397
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
398
-				/** @var $user \OC\User\User */
399
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
-			});
401
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
402
-				/** @var $user \OC\User\User */
403
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404
-			});
405
-			$userSession->listen('\OC\User', 'logout', function () {
406
-				\OC_Hook::emit('OC_User', 'logout', array());
407
-			});
408
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
409
-				/** @var $user \OC\User\User */
410
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
412
-			});
413
-			return $userSession;
414
-		});
415
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
416
-
417
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
418
-			return new \OC\Authentication\TwoFactorAuth\Manager(
419
-				$c->getAppManager(),
420
-				$c->getSession(),
421
-				$c->getConfig(),
422
-				$c->getActivityManager(),
423
-				$c->getLogger(),
424
-				$c->query(IProvider::class),
425
-				$c->query(ITimeFactory::class),
426
-				$c->query(EventDispatcherInterface::class)
427
-			);
428
-		});
429
-
430
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432
-
433
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
434
-			return new \OC\AllConfig(
435
-				$c->getSystemConfig()
436
-			);
437
-		});
438
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
439
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440
-
441
-		$this->registerService('SystemConfig', function ($c) use ($config) {
442
-			return new \OC\SystemConfig($config);
443
-		});
444
-
445
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
446
-			return new \OC\AppConfig($c->getDatabaseConnection());
447
-		});
448
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
449
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450
-
451
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
452
-			return new \OC\L10N\Factory(
453
-				$c->getConfig(),
454
-				$c->getRequest(),
455
-				$c->getUserSession(),
456
-				\OC::$SERVERROOT
457
-			);
458
-		});
459
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460
-
461
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
462
-			$config = $c->getConfig();
463
-			$cacheFactory = $c->getMemCacheFactory();
464
-			$request = $c->getRequest();
465
-			return new \OC\URLGenerator(
466
-				$config,
467
-				$cacheFactory,
468
-				$request
469
-			);
470
-		});
471
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
472
-
473
-		$this->registerService('AppHelper', function ($c) {
474
-			return new \OC\AppHelper();
475
-		});
476
-		$this->registerAlias('AppFetcher', AppFetcher::class);
477
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
478
-
479
-		$this->registerService(\OCP\ICache::class, function ($c) {
480
-			return new Cache\File();
481
-		});
482
-		$this->registerAlias('UserCache', \OCP\ICache::class);
483
-
484
-		$this->registerService(Factory::class, function (Server $c) {
485
-
486
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
487
-				ArrayCache::class,
488
-				ArrayCache::class,
489
-				ArrayCache::class
490
-			);
491
-			$config = $c->getConfig();
492
-			$request = $c->getRequest();
493
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
494
-
495
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
496
-				$v = \OC_App::getAppVersions();
497
-				$v['core'] = implode(',', \OC_Util::getVersion());
498
-				$version = implode(',', $v);
499
-				$instanceId = \OC_Util::getInstanceId();
500
-				$path = \OC::$SERVERROOT;
501
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
502
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
503
-					$config->getSystemValue('memcache.local', null),
504
-					$config->getSystemValue('memcache.distributed', null),
505
-					$config->getSystemValue('memcache.locking', null)
506
-				);
507
-			}
508
-			return $arrayCacheFactory;
509
-
510
-		});
511
-		$this->registerAlias('MemCacheFactory', Factory::class);
512
-		$this->registerAlias(ICacheFactory::class, Factory::class);
513
-
514
-		$this->registerService('RedisFactory', function (Server $c) {
515
-			$systemConfig = $c->getSystemConfig();
516
-			return new RedisFactory($systemConfig);
517
-		});
518
-
519
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
520
-			return new \OC\Activity\Manager(
521
-				$c->getRequest(),
522
-				$c->getUserSession(),
523
-				$c->getConfig(),
524
-				$c->query(IValidator::class)
525
-			);
526
-		});
527
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
528
-
529
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
530
-			return new \OC\Activity\EventMerger(
531
-				$c->getL10N('lib')
532
-			);
533
-		});
534
-		$this->registerAlias(IValidator::class, Validator::class);
535
-
536
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
537
-			return new AvatarManager(
538
-				$c->query(\OC\User\Manager::class),
539
-				$c->getAppDataDir('avatar'),
540
-				$c->getL10N('lib'),
541
-				$c->getLogger(),
542
-				$c->getConfig()
543
-			);
544
-		});
545
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
546
-
547
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
548
-
549
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
550
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
551
-			$logger = Log::getLogClass($logType);
552
-			call_user_func(array($logger, 'init'));
553
-			$config = $this->getSystemConfig();
554
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
555
-
556
-			return new Log($logger, $config, null, $registry);
557
-		});
558
-		$this->registerAlias('Logger', \OCP\ILogger::class);
559
-
560
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
561
-			$config = $c->getConfig();
562
-			return new \OC\BackgroundJob\JobList(
563
-				$c->getDatabaseConnection(),
564
-				$config,
565
-				new TimeFactory()
566
-			);
567
-		});
568
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
569
-
570
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
571
-			$cacheFactory = $c->getMemCacheFactory();
572
-			$logger = $c->getLogger();
573
-			if ($cacheFactory->isAvailableLowLatency()) {
574
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
575
-			} else {
576
-				$router = new \OC\Route\Router($logger);
577
-			}
578
-			return $router;
579
-		});
580
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
581
-
582
-		$this->registerService(\OCP\ISearch::class, function ($c) {
583
-			return new Search();
584
-		});
585
-		$this->registerAlias('Search', \OCP\ISearch::class);
586
-
587
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
588
-			return new \OC\Security\RateLimiting\Limiter(
589
-				$this->getUserSession(),
590
-				$this->getRequest(),
591
-				new \OC\AppFramework\Utility\TimeFactory(),
592
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
593
-			);
594
-		});
595
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
596
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
597
-				$this->getMemCacheFactory(),
598
-				new \OC\AppFramework\Utility\TimeFactory()
599
-			);
600
-		});
601
-
602
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
603
-			return new SecureRandom();
604
-		});
605
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
606
-
607
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
608
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
609
-		});
610
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
611
-
612
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
613
-			return new Hasher($c->getConfig());
614
-		});
615
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
616
-
617
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
618
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
619
-		});
620
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
621
-
622
-		$this->registerService(IDBConnection::class, function (Server $c) {
623
-			$systemConfig = $c->getSystemConfig();
624
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
625
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
626
-			if (!$factory->isValidType($type)) {
627
-				throw new \OC\DatabaseException('Invalid database type');
628
-			}
629
-			$connectionParams = $factory->createConnectionParams();
630
-			$connection = $factory->getConnection($type, $connectionParams);
631
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
632
-			return $connection;
633
-		});
634
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
635
-
636
-		$this->registerService('HTTPHelper', function (Server $c) {
637
-			$config = $c->getConfig();
638
-			return new HTTPHelper(
639
-				$config,
640
-				$c->getHTTPClientService()
641
-			);
642
-		});
643
-
644
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
645
-			$user = \OC_User::getUser();
646
-			$uid = $user ? $user : null;
647
-			return new ClientService(
648
-				$c->getConfig(),
649
-				new \OC\Security\CertificateManager(
650
-					$uid,
651
-					new View(),
652
-					$c->getConfig(),
653
-					$c->getLogger(),
654
-					$c->getSecureRandom()
655
-				)
656
-			);
657
-		});
658
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
659
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
660
-			$eventLogger = new EventLogger();
661
-			if ($c->getSystemConfig()->getValue('debug', false)) {
662
-				// In debug mode, module is being activated by default
663
-				$eventLogger->activate();
664
-			}
665
-			return $eventLogger;
666
-		});
667
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
668
-
669
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
670
-			$queryLogger = new QueryLogger();
671
-			if ($c->getSystemConfig()->getValue('debug', false)) {
672
-				// In debug mode, module is being activated by default
673
-				$queryLogger->activate();
674
-			}
675
-			return $queryLogger;
676
-		});
677
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
678
-
679
-		$this->registerService(TempManager::class, function (Server $c) {
680
-			return new TempManager(
681
-				$c->getLogger(),
682
-				$c->getConfig()
683
-			);
684
-		});
685
-		$this->registerAlias('TempManager', TempManager::class);
686
-		$this->registerAlias(ITempManager::class, TempManager::class);
687
-
688
-		$this->registerService(AppManager::class, function (Server $c) {
689
-			return new \OC\App\AppManager(
690
-				$c->getUserSession(),
691
-				$c->query(\OC\AppConfig::class),
692
-				$c->getGroupManager(),
693
-				$c->getMemCacheFactory(),
694
-				$c->getEventDispatcher()
695
-			);
696
-		});
697
-		$this->registerAlias('AppManager', AppManager::class);
698
-		$this->registerAlias(IAppManager::class, AppManager::class);
699
-
700
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
701
-			return new DateTimeZone(
702
-				$c->getConfig(),
703
-				$c->getSession()
704
-			);
705
-		});
706
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
707
-
708
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
709
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
710
-
711
-			return new DateTimeFormatter(
712
-				$c->getDateTimeZone()->getTimeZone(),
713
-				$c->getL10N('lib', $language)
714
-			);
715
-		});
716
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
717
-
718
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
719
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
720
-			$listener = new UserMountCacheListener($mountCache);
721
-			$listener->listen($c->getUserManager());
722
-			return $mountCache;
723
-		});
724
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
725
-
726
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
727
-			$loader = \OC\Files\Filesystem::getLoader();
728
-			$mountCache = $c->query('UserMountCache');
729
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
730
-
731
-			// builtin providers
732
-
733
-			$config = $c->getConfig();
734
-			$manager->registerProvider(new CacheMountProvider($config));
735
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
736
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
737
-
738
-			return $manager;
739
-		});
740
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
741
-
742
-		$this->registerService('IniWrapper', function ($c) {
743
-			return new IniGetWrapper();
744
-		});
745
-		$this->registerService('AsyncCommandBus', function (Server $c) {
746
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
747
-			if ($busClass) {
748
-				list($app, $class) = explode('::', $busClass, 2);
749
-				if ($c->getAppManager()->isInstalled($app)) {
750
-					\OC_App::loadApp($app);
751
-					return $c->query($class);
752
-				} else {
753
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
754
-				}
755
-			} else {
756
-				$jobList = $c->getJobList();
757
-				return new CronBus($jobList);
758
-			}
759
-		});
760
-		$this->registerService('TrustedDomainHelper', function ($c) {
761
-			return new TrustedDomainHelper($this->getConfig());
762
-		});
763
-		$this->registerService('Throttler', function (Server $c) {
764
-			return new Throttler(
765
-				$c->getDatabaseConnection(),
766
-				new TimeFactory(),
767
-				$c->getLogger(),
768
-				$c->getConfig()
769
-			);
770
-		});
771
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
772
-			// IConfig and IAppManager requires a working database. This code
773
-			// might however be called when ownCloud is not yet setup.
774
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
775
-				$config = $c->getConfig();
776
-				$appManager = $c->getAppManager();
777
-			} else {
778
-				$config = null;
779
-				$appManager = null;
780
-			}
781
-
782
-			return new Checker(
783
-				new EnvironmentHelper(),
784
-				new FileAccessHelper(),
785
-				new AppLocator(),
786
-				$config,
787
-				$c->getMemCacheFactory(),
788
-				$appManager,
789
-				$c->getTempManager()
790
-			);
791
-		});
792
-		$this->registerService(\OCP\IRequest::class, function ($c) {
793
-			if (isset($this['urlParams'])) {
794
-				$urlParams = $this['urlParams'];
795
-			} else {
796
-				$urlParams = [];
797
-			}
798
-
799
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
800
-				&& in_array('fakeinput', stream_get_wrappers())
801
-			) {
802
-				$stream = 'fakeinput://data';
803
-			} else {
804
-				$stream = 'php://input';
805
-			}
806
-
807
-			return new Request(
808
-				[
809
-					'get' => $_GET,
810
-					'post' => $_POST,
811
-					'files' => $_FILES,
812
-					'server' => $_SERVER,
813
-					'env' => $_ENV,
814
-					'cookies' => $_COOKIE,
815
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
816
-						? $_SERVER['REQUEST_METHOD']
817
-						: '',
818
-					'urlParams' => $urlParams,
819
-				],
820
-				$this->getSecureRandom(),
821
-				$this->getConfig(),
822
-				$this->getCsrfTokenManager(),
823
-				$stream
824
-			);
825
-		});
826
-		$this->registerAlias('Request', \OCP\IRequest::class);
827
-
828
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
829
-			return new Mailer(
830
-				$c->getConfig(),
831
-				$c->getLogger(),
832
-				$c->query(Defaults::class),
833
-				$c->getURLGenerator(),
834
-				$c->getL10N('lib')
835
-			);
836
-		});
837
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
838
-
839
-		$this->registerService('LDAPProvider', function (Server $c) {
840
-			$config = $c->getConfig();
841
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
842
-			if (is_null($factoryClass)) {
843
-				throw new \Exception('ldapProviderFactory not set');
844
-			}
845
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
846
-			$factory = new $factoryClass($this);
847
-			return $factory->getLDAPProvider();
848
-		});
849
-		$this->registerService(ILockingProvider::class, function (Server $c) {
850
-			$ini = $c->getIniWrapper();
851
-			$config = $c->getConfig();
852
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
853
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
854
-				/** @var \OC\Memcache\Factory $memcacheFactory */
855
-				$memcacheFactory = $c->getMemCacheFactory();
856
-				$memcache = $memcacheFactory->createLocking('lock');
857
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
858
-					return new MemcacheLockingProvider($memcache, $ttl);
859
-				}
860
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
861
-			}
862
-			return new NoopLockingProvider();
863
-		});
864
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
865
-
866
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
867
-			return new \OC\Files\Mount\Manager();
868
-		});
869
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
870
-
871
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
872
-			return new \OC\Files\Type\Detection(
873
-				$c->getURLGenerator(),
874
-				\OC::$configDir,
875
-				\OC::$SERVERROOT . '/resources/config/'
876
-			);
877
-		});
878
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
879
-
880
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
881
-			return new \OC\Files\Type\Loader(
882
-				$c->getDatabaseConnection()
883
-			);
884
-		});
885
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
886
-		$this->registerService(BundleFetcher::class, function () {
887
-			return new BundleFetcher($this->getL10N('lib'));
888
-		});
889
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
890
-			return new Manager(
891
-				$c->query(IValidator::class)
892
-			);
893
-		});
894
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
895
-
896
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
897
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
898
-			$manager->registerCapability(function () use ($c) {
899
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
900
-			});
901
-			$manager->registerCapability(function () use ($c) {
902
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
903
-			});
904
-			return $manager;
905
-		});
906
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
907
-
908
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
909
-			$config = $c->getConfig();
910
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
911
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
912
-			$factory = new $factoryClass($this);
913
-			$manager = $factory->getManager();
914
-
915
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
916
-				$manager = $c->getUserManager();
917
-				$user = $manager->get($id);
918
-				if(is_null($user)) {
919
-					$l = $c->getL10N('core');
920
-					$displayName = $l->t('Unknown user');
921
-				} else {
922
-					$displayName = $user->getDisplayName();
923
-				}
924
-				return $displayName;
925
-			});
926
-
927
-			return $manager;
928
-		});
929
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
930
-
931
-		$this->registerService('ThemingDefaults', function (Server $c) {
932
-			/*
153
+    /** @var string */
154
+    private $webRoot;
155
+
156
+    /**
157
+     * @param string $webRoot
158
+     * @param \OC\Config $config
159
+     */
160
+    public function __construct($webRoot, \OC\Config $config) {
161
+        parent::__construct();
162
+        $this->webRoot = $webRoot;
163
+
164
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
165
+            return $c;
166
+        });
167
+
168
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
169
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
170
+
171
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
172
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
173
+
174
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
175
+
176
+
177
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
178
+            return new PreviewManager(
179
+                $c->getConfig(),
180
+                $c->getRootFolder(),
181
+                $c->getAppDataDir('preview'),
182
+                $c->getEventDispatcher(),
183
+                $c->getSession()->get('user_id')
184
+            );
185
+        });
186
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
187
+
188
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
189
+            return new \OC\Preview\Watcher(
190
+                $c->getAppDataDir('preview')
191
+            );
192
+        });
193
+
194
+        $this->registerService('EncryptionManager', function (Server $c) {
195
+            $view = new View();
196
+            $util = new Encryption\Util(
197
+                $view,
198
+                $c->getUserManager(),
199
+                $c->getGroupManager(),
200
+                $c->getConfig()
201
+            );
202
+            return new Encryption\Manager(
203
+                $c->getConfig(),
204
+                $c->getLogger(),
205
+                $c->getL10N('core'),
206
+                new View(),
207
+                $util,
208
+                new ArrayCache()
209
+            );
210
+        });
211
+
212
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
213
+            $util = new Encryption\Util(
214
+                new View(),
215
+                $c->getUserManager(),
216
+                $c->getGroupManager(),
217
+                $c->getConfig()
218
+            );
219
+            return new Encryption\File(
220
+                $util,
221
+                $c->getRootFolder(),
222
+                $c->getShareManager()
223
+            );
224
+        });
225
+
226
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
227
+            $view = new View();
228
+            $util = new Encryption\Util(
229
+                $view,
230
+                $c->getUserManager(),
231
+                $c->getGroupManager(),
232
+                $c->getConfig()
233
+            );
234
+
235
+            return new Encryption\Keys\Storage($view, $util);
236
+        });
237
+        $this->registerService('TagMapper', function (Server $c) {
238
+            return new TagMapper($c->getDatabaseConnection());
239
+        });
240
+
241
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
242
+            $tagMapper = $c->query('TagMapper');
243
+            return new TagManager($tagMapper, $c->getUserSession());
244
+        });
245
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
246
+
247
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
248
+            $config = $c->getConfig();
249
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
250
+            return new $factoryClass($this);
251
+        });
252
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
253
+            return $c->query('SystemTagManagerFactory')->getManager();
254
+        });
255
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
256
+
257
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
258
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
259
+        });
260
+        $this->registerService('RootFolder', function (Server $c) {
261
+            $manager = \OC\Files\Filesystem::getMountManager(null);
262
+            $view = new View();
263
+            $root = new Root(
264
+                $manager,
265
+                $view,
266
+                null,
267
+                $c->getUserMountCache(),
268
+                $this->getLogger(),
269
+                $this->getUserManager()
270
+            );
271
+            $connector = new HookConnector($root, $view);
272
+            $connector->viewToNode();
273
+
274
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
275
+            $previewConnector->connectWatcher();
276
+
277
+            return $root;
278
+        });
279
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
280
+
281
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
282
+            return new LazyRoot(function () use ($c) {
283
+                return $c->query('RootFolder');
284
+            });
285
+        });
286
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
287
+
288
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
289
+            $config = $c->getConfig();
290
+            return new \OC\User\Manager($config);
291
+        });
292
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
293
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
294
+
295
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
296
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
297
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
298
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
299
+            });
300
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
301
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
302
+            });
303
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
304
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
305
+            });
306
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
307
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
308
+            });
309
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
310
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
311
+            });
312
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
314
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
315
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
316
+            });
317
+            return $groupManager;
318
+        });
319
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
320
+
321
+        $this->registerService(Store::class, function (Server $c) {
322
+            $session = $c->getSession();
323
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
324
+                $tokenProvider = $c->query(IProvider::class);
325
+            } else {
326
+                $tokenProvider = null;
327
+            }
328
+            $logger = $c->getLogger();
329
+            return new Store($session, $logger, $tokenProvider);
330
+        });
331
+        $this->registerAlias(IStore::class, Store::class);
332
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
333
+            $dbConnection = $c->getDatabaseConnection();
334
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
335
+        });
336
+        $this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
337
+            $mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
338
+            $crypto = $c->getCrypto();
339
+            $config = $c->getConfig();
340
+            $logger = $c->getLogger();
341
+            $timeFactory = new TimeFactory();
342
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
343
+        });
344
+        $this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
345
+
346
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
347
+            $manager = $c->getUserManager();
348
+            $session = new \OC\Session\Memory('');
349
+            $timeFactory = new TimeFactory();
350
+            // Token providers might require a working database. This code
351
+            // might however be called when ownCloud is not yet setup.
352
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
353
+                $defaultTokenProvider = $c->query(IProvider::class);
354
+            } else {
355
+                $defaultTokenProvider = null;
356
+            }
357
+
358
+            $dispatcher = $c->getEventDispatcher();
359
+
360
+            $userSession = new \OC\User\Session(
361
+                $manager,
362
+                $session,
363
+                $timeFactory,
364
+                $defaultTokenProvider,
365
+                $c->getConfig(),
366
+                $c->getSecureRandom(),
367
+                $c->getLockdownManager(),
368
+                $c->getLogger()
369
+            );
370
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
371
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
372
+            });
373
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
374
+                /** @var $user \OC\User\User */
375
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
376
+            });
377
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
378
+                /** @var $user \OC\User\User */
379
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
380
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
381
+            });
382
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
383
+                /** @var $user \OC\User\User */
384
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
385
+            });
386
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
389
+            });
390
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
391
+                /** @var $user \OC\User\User */
392
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
393
+            });
394
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
395
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
396
+            });
397
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
398
+                /** @var $user \OC\User\User */
399
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
400
+            });
401
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
402
+                /** @var $user \OC\User\User */
403
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
404
+            });
405
+            $userSession->listen('\OC\User', 'logout', function () {
406
+                \OC_Hook::emit('OC_User', 'logout', array());
407
+            });
408
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
409
+                /** @var $user \OC\User\User */
410
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
411
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
412
+            });
413
+            return $userSession;
414
+        });
415
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
416
+
417
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
418
+            return new \OC\Authentication\TwoFactorAuth\Manager(
419
+                $c->getAppManager(),
420
+                $c->getSession(),
421
+                $c->getConfig(),
422
+                $c->getActivityManager(),
423
+                $c->getLogger(),
424
+                $c->query(IProvider::class),
425
+                $c->query(ITimeFactory::class),
426
+                $c->query(EventDispatcherInterface::class)
427
+            );
428
+        });
429
+
430
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
431
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
432
+
433
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
434
+            return new \OC\AllConfig(
435
+                $c->getSystemConfig()
436
+            );
437
+        });
438
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
439
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
440
+
441
+        $this->registerService('SystemConfig', function ($c) use ($config) {
442
+            return new \OC\SystemConfig($config);
443
+        });
444
+
445
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
446
+            return new \OC\AppConfig($c->getDatabaseConnection());
447
+        });
448
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
449
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
450
+
451
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
452
+            return new \OC\L10N\Factory(
453
+                $c->getConfig(),
454
+                $c->getRequest(),
455
+                $c->getUserSession(),
456
+                \OC::$SERVERROOT
457
+            );
458
+        });
459
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
460
+
461
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
462
+            $config = $c->getConfig();
463
+            $cacheFactory = $c->getMemCacheFactory();
464
+            $request = $c->getRequest();
465
+            return new \OC\URLGenerator(
466
+                $config,
467
+                $cacheFactory,
468
+                $request
469
+            );
470
+        });
471
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
472
+
473
+        $this->registerService('AppHelper', function ($c) {
474
+            return new \OC\AppHelper();
475
+        });
476
+        $this->registerAlias('AppFetcher', AppFetcher::class);
477
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
478
+
479
+        $this->registerService(\OCP\ICache::class, function ($c) {
480
+            return new Cache\File();
481
+        });
482
+        $this->registerAlias('UserCache', \OCP\ICache::class);
483
+
484
+        $this->registerService(Factory::class, function (Server $c) {
485
+
486
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
487
+                ArrayCache::class,
488
+                ArrayCache::class,
489
+                ArrayCache::class
490
+            );
491
+            $config = $c->getConfig();
492
+            $request = $c->getRequest();
493
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
494
+
495
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
496
+                $v = \OC_App::getAppVersions();
497
+                $v['core'] = implode(',', \OC_Util::getVersion());
498
+                $version = implode(',', $v);
499
+                $instanceId = \OC_Util::getInstanceId();
500
+                $path = \OC::$SERVERROOT;
501
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . $urlGenerator->getBaseUrl());
502
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
503
+                    $config->getSystemValue('memcache.local', null),
504
+                    $config->getSystemValue('memcache.distributed', null),
505
+                    $config->getSystemValue('memcache.locking', null)
506
+                );
507
+            }
508
+            return $arrayCacheFactory;
509
+
510
+        });
511
+        $this->registerAlias('MemCacheFactory', Factory::class);
512
+        $this->registerAlias(ICacheFactory::class, Factory::class);
513
+
514
+        $this->registerService('RedisFactory', function (Server $c) {
515
+            $systemConfig = $c->getSystemConfig();
516
+            return new RedisFactory($systemConfig);
517
+        });
518
+
519
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
520
+            return new \OC\Activity\Manager(
521
+                $c->getRequest(),
522
+                $c->getUserSession(),
523
+                $c->getConfig(),
524
+                $c->query(IValidator::class)
525
+            );
526
+        });
527
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
528
+
529
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
530
+            return new \OC\Activity\EventMerger(
531
+                $c->getL10N('lib')
532
+            );
533
+        });
534
+        $this->registerAlias(IValidator::class, Validator::class);
535
+
536
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
537
+            return new AvatarManager(
538
+                $c->query(\OC\User\Manager::class),
539
+                $c->getAppDataDir('avatar'),
540
+                $c->getL10N('lib'),
541
+                $c->getLogger(),
542
+                $c->getConfig()
543
+            );
544
+        });
545
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
546
+
547
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
548
+
549
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
550
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
551
+            $logger = Log::getLogClass($logType);
552
+            call_user_func(array($logger, 'init'));
553
+            $config = $this->getSystemConfig();
554
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
555
+
556
+            return new Log($logger, $config, null, $registry);
557
+        });
558
+        $this->registerAlias('Logger', \OCP\ILogger::class);
559
+
560
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
561
+            $config = $c->getConfig();
562
+            return new \OC\BackgroundJob\JobList(
563
+                $c->getDatabaseConnection(),
564
+                $config,
565
+                new TimeFactory()
566
+            );
567
+        });
568
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
569
+
570
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
571
+            $cacheFactory = $c->getMemCacheFactory();
572
+            $logger = $c->getLogger();
573
+            if ($cacheFactory->isAvailableLowLatency()) {
574
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
575
+            } else {
576
+                $router = new \OC\Route\Router($logger);
577
+            }
578
+            return $router;
579
+        });
580
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
581
+
582
+        $this->registerService(\OCP\ISearch::class, function ($c) {
583
+            return new Search();
584
+        });
585
+        $this->registerAlias('Search', \OCP\ISearch::class);
586
+
587
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function ($c) {
588
+            return new \OC\Security\RateLimiting\Limiter(
589
+                $this->getUserSession(),
590
+                $this->getRequest(),
591
+                new \OC\AppFramework\Utility\TimeFactory(),
592
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
593
+            );
594
+        });
595
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
596
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
597
+                $this->getMemCacheFactory(),
598
+                new \OC\AppFramework\Utility\TimeFactory()
599
+            );
600
+        });
601
+
602
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
603
+            return new SecureRandom();
604
+        });
605
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
606
+
607
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
608
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
609
+        });
610
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
611
+
612
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
613
+            return new Hasher($c->getConfig());
614
+        });
615
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
616
+
617
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
618
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
619
+        });
620
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
621
+
622
+        $this->registerService(IDBConnection::class, function (Server $c) {
623
+            $systemConfig = $c->getSystemConfig();
624
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
625
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
626
+            if (!$factory->isValidType($type)) {
627
+                throw new \OC\DatabaseException('Invalid database type');
628
+            }
629
+            $connectionParams = $factory->createConnectionParams();
630
+            $connection = $factory->getConnection($type, $connectionParams);
631
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
632
+            return $connection;
633
+        });
634
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
635
+
636
+        $this->registerService('HTTPHelper', function (Server $c) {
637
+            $config = $c->getConfig();
638
+            return new HTTPHelper(
639
+                $config,
640
+                $c->getHTTPClientService()
641
+            );
642
+        });
643
+
644
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
645
+            $user = \OC_User::getUser();
646
+            $uid = $user ? $user : null;
647
+            return new ClientService(
648
+                $c->getConfig(),
649
+                new \OC\Security\CertificateManager(
650
+                    $uid,
651
+                    new View(),
652
+                    $c->getConfig(),
653
+                    $c->getLogger(),
654
+                    $c->getSecureRandom()
655
+                )
656
+            );
657
+        });
658
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
659
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
660
+            $eventLogger = new EventLogger();
661
+            if ($c->getSystemConfig()->getValue('debug', false)) {
662
+                // In debug mode, module is being activated by default
663
+                $eventLogger->activate();
664
+            }
665
+            return $eventLogger;
666
+        });
667
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
668
+
669
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
670
+            $queryLogger = new QueryLogger();
671
+            if ($c->getSystemConfig()->getValue('debug', false)) {
672
+                // In debug mode, module is being activated by default
673
+                $queryLogger->activate();
674
+            }
675
+            return $queryLogger;
676
+        });
677
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
678
+
679
+        $this->registerService(TempManager::class, function (Server $c) {
680
+            return new TempManager(
681
+                $c->getLogger(),
682
+                $c->getConfig()
683
+            );
684
+        });
685
+        $this->registerAlias('TempManager', TempManager::class);
686
+        $this->registerAlias(ITempManager::class, TempManager::class);
687
+
688
+        $this->registerService(AppManager::class, function (Server $c) {
689
+            return new \OC\App\AppManager(
690
+                $c->getUserSession(),
691
+                $c->query(\OC\AppConfig::class),
692
+                $c->getGroupManager(),
693
+                $c->getMemCacheFactory(),
694
+                $c->getEventDispatcher()
695
+            );
696
+        });
697
+        $this->registerAlias('AppManager', AppManager::class);
698
+        $this->registerAlias(IAppManager::class, AppManager::class);
699
+
700
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
701
+            return new DateTimeZone(
702
+                $c->getConfig(),
703
+                $c->getSession()
704
+            );
705
+        });
706
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
707
+
708
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
709
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
710
+
711
+            return new DateTimeFormatter(
712
+                $c->getDateTimeZone()->getTimeZone(),
713
+                $c->getL10N('lib', $language)
714
+            );
715
+        });
716
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
717
+
718
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
719
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
720
+            $listener = new UserMountCacheListener($mountCache);
721
+            $listener->listen($c->getUserManager());
722
+            return $mountCache;
723
+        });
724
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
725
+
726
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
727
+            $loader = \OC\Files\Filesystem::getLoader();
728
+            $mountCache = $c->query('UserMountCache');
729
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
730
+
731
+            // builtin providers
732
+
733
+            $config = $c->getConfig();
734
+            $manager->registerProvider(new CacheMountProvider($config));
735
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
736
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
737
+
738
+            return $manager;
739
+        });
740
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
741
+
742
+        $this->registerService('IniWrapper', function ($c) {
743
+            return new IniGetWrapper();
744
+        });
745
+        $this->registerService('AsyncCommandBus', function (Server $c) {
746
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
747
+            if ($busClass) {
748
+                list($app, $class) = explode('::', $busClass, 2);
749
+                if ($c->getAppManager()->isInstalled($app)) {
750
+                    \OC_App::loadApp($app);
751
+                    return $c->query($class);
752
+                } else {
753
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
754
+                }
755
+            } else {
756
+                $jobList = $c->getJobList();
757
+                return new CronBus($jobList);
758
+            }
759
+        });
760
+        $this->registerService('TrustedDomainHelper', function ($c) {
761
+            return new TrustedDomainHelper($this->getConfig());
762
+        });
763
+        $this->registerService('Throttler', function (Server $c) {
764
+            return new Throttler(
765
+                $c->getDatabaseConnection(),
766
+                new TimeFactory(),
767
+                $c->getLogger(),
768
+                $c->getConfig()
769
+            );
770
+        });
771
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
772
+            // IConfig and IAppManager requires a working database. This code
773
+            // might however be called when ownCloud is not yet setup.
774
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
775
+                $config = $c->getConfig();
776
+                $appManager = $c->getAppManager();
777
+            } else {
778
+                $config = null;
779
+                $appManager = null;
780
+            }
781
+
782
+            return new Checker(
783
+                new EnvironmentHelper(),
784
+                new FileAccessHelper(),
785
+                new AppLocator(),
786
+                $config,
787
+                $c->getMemCacheFactory(),
788
+                $appManager,
789
+                $c->getTempManager()
790
+            );
791
+        });
792
+        $this->registerService(\OCP\IRequest::class, function ($c) {
793
+            if (isset($this['urlParams'])) {
794
+                $urlParams = $this['urlParams'];
795
+            } else {
796
+                $urlParams = [];
797
+            }
798
+
799
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
800
+                && in_array('fakeinput', stream_get_wrappers())
801
+            ) {
802
+                $stream = 'fakeinput://data';
803
+            } else {
804
+                $stream = 'php://input';
805
+            }
806
+
807
+            return new Request(
808
+                [
809
+                    'get' => $_GET,
810
+                    'post' => $_POST,
811
+                    'files' => $_FILES,
812
+                    'server' => $_SERVER,
813
+                    'env' => $_ENV,
814
+                    'cookies' => $_COOKIE,
815
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
816
+                        ? $_SERVER['REQUEST_METHOD']
817
+                        : '',
818
+                    'urlParams' => $urlParams,
819
+                ],
820
+                $this->getSecureRandom(),
821
+                $this->getConfig(),
822
+                $this->getCsrfTokenManager(),
823
+                $stream
824
+            );
825
+        });
826
+        $this->registerAlias('Request', \OCP\IRequest::class);
827
+
828
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
829
+            return new Mailer(
830
+                $c->getConfig(),
831
+                $c->getLogger(),
832
+                $c->query(Defaults::class),
833
+                $c->getURLGenerator(),
834
+                $c->getL10N('lib')
835
+            );
836
+        });
837
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
838
+
839
+        $this->registerService('LDAPProvider', function (Server $c) {
840
+            $config = $c->getConfig();
841
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
842
+            if (is_null($factoryClass)) {
843
+                throw new \Exception('ldapProviderFactory not set');
844
+            }
845
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
846
+            $factory = new $factoryClass($this);
847
+            return $factory->getLDAPProvider();
848
+        });
849
+        $this->registerService(ILockingProvider::class, function (Server $c) {
850
+            $ini = $c->getIniWrapper();
851
+            $config = $c->getConfig();
852
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
853
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
854
+                /** @var \OC\Memcache\Factory $memcacheFactory */
855
+                $memcacheFactory = $c->getMemCacheFactory();
856
+                $memcache = $memcacheFactory->createLocking('lock');
857
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
858
+                    return new MemcacheLockingProvider($memcache, $ttl);
859
+                }
860
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
861
+            }
862
+            return new NoopLockingProvider();
863
+        });
864
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
865
+
866
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
867
+            return new \OC\Files\Mount\Manager();
868
+        });
869
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
870
+
871
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
872
+            return new \OC\Files\Type\Detection(
873
+                $c->getURLGenerator(),
874
+                \OC::$configDir,
875
+                \OC::$SERVERROOT . '/resources/config/'
876
+            );
877
+        });
878
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
879
+
880
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
881
+            return new \OC\Files\Type\Loader(
882
+                $c->getDatabaseConnection()
883
+            );
884
+        });
885
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
886
+        $this->registerService(BundleFetcher::class, function () {
887
+            return new BundleFetcher($this->getL10N('lib'));
888
+        });
889
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
890
+            return new Manager(
891
+                $c->query(IValidator::class)
892
+            );
893
+        });
894
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
895
+
896
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
897
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
898
+            $manager->registerCapability(function () use ($c) {
899
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
900
+            });
901
+            $manager->registerCapability(function () use ($c) {
902
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
903
+            });
904
+            return $manager;
905
+        });
906
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
907
+
908
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
909
+            $config = $c->getConfig();
910
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
911
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
912
+            $factory = new $factoryClass($this);
913
+            $manager = $factory->getManager();
914
+
915
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
916
+                $manager = $c->getUserManager();
917
+                $user = $manager->get($id);
918
+                if(is_null($user)) {
919
+                    $l = $c->getL10N('core');
920
+                    $displayName = $l->t('Unknown user');
921
+                } else {
922
+                    $displayName = $user->getDisplayName();
923
+                }
924
+                return $displayName;
925
+            });
926
+
927
+            return $manager;
928
+        });
929
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
930
+
931
+        $this->registerService('ThemingDefaults', function (Server $c) {
932
+            /*
933 933
 			 * Dark magic for autoloader.
934 934
 			 * If we do a class_exists it will try to load the class which will
935 935
 			 * make composer cache the result. Resulting in errors when enabling
936 936
 			 * the theming app.
937 937
 			 */
938
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
939
-			if (isset($prefixes['OCA\\Theming\\'])) {
940
-				$classExists = true;
941
-			} else {
942
-				$classExists = false;
943
-			}
944
-
945
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
946
-				return new ThemingDefaults(
947
-					$c->getConfig(),
948
-					$c->getL10N('theming'),
949
-					$c->getURLGenerator(),
950
-					$c->getAppDataDir('theming'),
951
-					$c->getMemCacheFactory(),
952
-					new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
953
-					$this->getAppManager()
954
-				);
955
-			}
956
-			return new \OC_Defaults();
957
-		});
958
-		$this->registerService(SCSSCacher::class, function (Server $c) {
959
-			/** @var Factory $cacheFactory */
960
-			$cacheFactory = $c->query(Factory::class);
961
-			return new SCSSCacher(
962
-				$c->getLogger(),
963
-				$c->query(\OC\Files\AppData\Factory::class),
964
-				$c->getURLGenerator(),
965
-				$c->getConfig(),
966
-				$c->getThemingDefaults(),
967
-				\OC::$SERVERROOT,
968
-				$cacheFactory->createDistributed('SCSS')
969
-			);
970
-		});
971
-		$this->registerService(JSCombiner::class, function (Server $c) {
972
-			/** @var Factory $cacheFactory */
973
-			$cacheFactory = $c->query(Factory::class);
974
-			return new JSCombiner(
975
-				$c->getAppDataDir('js'),
976
-				$c->getURLGenerator(),
977
-				$cacheFactory->createDistributed('JS'),
978
-				$c->getSystemConfig(),
979
-				$c->getLogger()
980
-			);
981
-		});
982
-		$this->registerService(EventDispatcher::class, function () {
983
-			return new EventDispatcher();
984
-		});
985
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
986
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
987
-
988
-		$this->registerService('CryptoWrapper', function (Server $c) {
989
-			// FIXME: Instantiiated here due to cyclic dependency
990
-			$request = new Request(
991
-				[
992
-					'get' => $_GET,
993
-					'post' => $_POST,
994
-					'files' => $_FILES,
995
-					'server' => $_SERVER,
996
-					'env' => $_ENV,
997
-					'cookies' => $_COOKIE,
998
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
999
-						? $_SERVER['REQUEST_METHOD']
1000
-						: null,
1001
-				],
1002
-				$c->getSecureRandom(),
1003
-				$c->getConfig()
1004
-			);
1005
-
1006
-			return new CryptoWrapper(
1007
-				$c->getConfig(),
1008
-				$c->getCrypto(),
1009
-				$c->getSecureRandom(),
1010
-				$request
1011
-			);
1012
-		});
1013
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1014
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1015
-
1016
-			return new CsrfTokenManager(
1017
-				$tokenGenerator,
1018
-				$c->query(SessionStorage::class)
1019
-			);
1020
-		});
1021
-		$this->registerService(SessionStorage::class, function (Server $c) {
1022
-			return new SessionStorage($c->getSession());
1023
-		});
1024
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1025
-			return new ContentSecurityPolicyManager();
1026
-		});
1027
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1028
-
1029
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1030
-			return new ContentSecurityPolicyNonceManager(
1031
-				$c->getCsrfTokenManager(),
1032
-				$c->getRequest()
1033
-			);
1034
-		});
1035
-
1036
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1037
-			$config = $c->getConfig();
1038
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1039
-			/** @var \OCP\Share\IProviderFactory $factory */
1040
-			$factory = new $factoryClass($this);
1041
-
1042
-			$manager = new \OC\Share20\Manager(
1043
-				$c->getLogger(),
1044
-				$c->getConfig(),
1045
-				$c->getSecureRandom(),
1046
-				$c->getHasher(),
1047
-				$c->getMountManager(),
1048
-				$c->getGroupManager(),
1049
-				$c->getL10N('lib'),
1050
-				$c->getL10NFactory(),
1051
-				$factory,
1052
-				$c->getUserManager(),
1053
-				$c->getLazyRootFolder(),
1054
-				$c->getEventDispatcher(),
1055
-				$c->getMailer(),
1056
-				$c->getURLGenerator(),
1057
-				$c->getThemingDefaults()
1058
-			);
1059
-
1060
-			return $manager;
1061
-		});
1062
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1063
-
1064
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1065
-			$instance = new Collaboration\Collaborators\Search($c);
1066
-
1067
-			// register default plugins
1068
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1069
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1070
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1071
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1072
-
1073
-			return $instance;
1074
-		});
1075
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1076
-
1077
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1078
-
1079
-		$this->registerService('SettingsManager', function (Server $c) {
1080
-			$manager = new \OC\Settings\Manager(
1081
-				$c->getLogger(),
1082
-				$c->getDatabaseConnection(),
1083
-				$c->getL10N('lib'),
1084
-				$c->getConfig(),
1085
-				$c->getEncryptionManager(),
1086
-				$c->getUserManager(),
1087
-				$c->getLockingProvider(),
1088
-				$c->getRequest(),
1089
-				$c->getURLGenerator(),
1090
-				$c->query(AccountManager::class),
1091
-				$c->getGroupManager(),
1092
-				$c->getL10NFactory(),
1093
-				$c->getAppManager()
1094
-			);
1095
-			return $manager;
1096
-		});
1097
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1098
-			return new \OC\Files\AppData\Factory(
1099
-				$c->getRootFolder(),
1100
-				$c->getSystemConfig()
1101
-			);
1102
-		});
1103
-
1104
-		$this->registerService('LockdownManager', function (Server $c) {
1105
-			return new LockdownManager(function () use ($c) {
1106
-				return $c->getSession();
1107
-			});
1108
-		});
1109
-
1110
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1111
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1112
-		});
1113
-
1114
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1115
-			return new CloudIdManager();
1116
-		});
1117
-
1118
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1119
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1120
-
1121
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1122
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1123
-
1124
-		$this->registerService(Defaults::class, function (Server $c) {
1125
-			return new Defaults(
1126
-				$c->getThemingDefaults()
1127
-			);
1128
-		});
1129
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1130
-
1131
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1132
-			return $c->query(\OCP\IUserSession::class)->getSession();
1133
-		});
1134
-
1135
-		$this->registerService(IShareHelper::class, function (Server $c) {
1136
-			return new ShareHelper(
1137
-				$c->query(\OCP\Share\IManager::class)
1138
-			);
1139
-		});
1140
-
1141
-		$this->registerService(Installer::class, function(Server $c) {
1142
-			return new Installer(
1143
-				$c->getAppFetcher(),
1144
-				$c->getHTTPClientService(),
1145
-				$c->getTempManager(),
1146
-				$c->getLogger(),
1147
-				$c->getConfig()
1148
-			);
1149
-		});
1150
-
1151
-		$this->registerService(IApiFactory::class, function(Server $c) {
1152
-			return new ApiFactory($c->getHTTPClientService());
1153
-		});
1154
-
1155
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1156
-			$memcacheFactory = $c->getMemCacheFactory();
1157
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1158
-		});
1159
-
1160
-		$this->registerService(IContactsStore::class, function(Server $c) {
1161
-			return new ContactsStore(
1162
-				$c->getContactsManager(),
1163
-				$c->getConfig(),
1164
-				$c->getUserManager(),
1165
-				$c->getGroupManager()
1166
-			);
1167
-		});
1168
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1169
-
1170
-		$this->connectDispatcher();
1171
-	}
1172
-
1173
-	/**
1174
-	 * @return \OCP\Calendar\IManager
1175
-	 */
1176
-	public function getCalendarManager() {
1177
-		return $this->query('CalendarManager');
1178
-	}
1179
-
1180
-	private function connectDispatcher() {
1181
-		$dispatcher = $this->getEventDispatcher();
1182
-
1183
-		// Delete avatar on user deletion
1184
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1185
-			$logger = $this->getLogger();
1186
-			$manager = $this->getAvatarManager();
1187
-			/** @var IUser $user */
1188
-			$user = $e->getSubject();
1189
-
1190
-			try {
1191
-				$avatar = $manager->getAvatar($user->getUID());
1192
-				$avatar->remove();
1193
-			} catch (NotFoundException $e) {
1194
-				// no avatar to remove
1195
-			} catch (\Exception $e) {
1196
-				// Ignore exceptions
1197
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1198
-			}
1199
-		});
1200
-
1201
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1202
-			$manager = $this->getAvatarManager();
1203
-			/** @var IUser $user */
1204
-			$user = $e->getSubject();
1205
-			$feature = $e->getArgument('feature');
1206
-			$oldValue = $e->getArgument('oldValue');
1207
-			$value = $e->getArgument('value');
1208
-
1209
-			try {
1210
-				$avatar = $manager->getAvatar($user->getUID());
1211
-				$avatar->userChanged($feature, $oldValue, $value);
1212
-			} catch (NotFoundException $e) {
1213
-				// no avatar to remove
1214
-			}
1215
-		});
1216
-	}
1217
-
1218
-	/**
1219
-	 * @return \OCP\Contacts\IManager
1220
-	 */
1221
-	public function getContactsManager() {
1222
-		return $this->query('ContactsManager');
1223
-	}
1224
-
1225
-	/**
1226
-	 * @return \OC\Encryption\Manager
1227
-	 */
1228
-	public function getEncryptionManager() {
1229
-		return $this->query('EncryptionManager');
1230
-	}
1231
-
1232
-	/**
1233
-	 * @return \OC\Encryption\File
1234
-	 */
1235
-	public function getEncryptionFilesHelper() {
1236
-		return $this->query('EncryptionFileHelper');
1237
-	}
1238
-
1239
-	/**
1240
-	 * @return \OCP\Encryption\Keys\IStorage
1241
-	 */
1242
-	public function getEncryptionKeyStorage() {
1243
-		return $this->query('EncryptionKeyStorage');
1244
-	}
1245
-
1246
-	/**
1247
-	 * The current request object holding all information about the request
1248
-	 * currently being processed is returned from this method.
1249
-	 * In case the current execution was not initiated by a web request null is returned
1250
-	 *
1251
-	 * @return \OCP\IRequest
1252
-	 */
1253
-	public function getRequest() {
1254
-		return $this->query('Request');
1255
-	}
1256
-
1257
-	/**
1258
-	 * Returns the preview manager which can create preview images for a given file
1259
-	 *
1260
-	 * @return \OCP\IPreview
1261
-	 */
1262
-	public function getPreviewManager() {
1263
-		return $this->query('PreviewManager');
1264
-	}
1265
-
1266
-	/**
1267
-	 * Returns the tag manager which can get and set tags for different object types
1268
-	 *
1269
-	 * @see \OCP\ITagManager::load()
1270
-	 * @return \OCP\ITagManager
1271
-	 */
1272
-	public function getTagManager() {
1273
-		return $this->query('TagManager');
1274
-	}
1275
-
1276
-	/**
1277
-	 * Returns the system-tag manager
1278
-	 *
1279
-	 * @return \OCP\SystemTag\ISystemTagManager
1280
-	 *
1281
-	 * @since 9.0.0
1282
-	 */
1283
-	public function getSystemTagManager() {
1284
-		return $this->query('SystemTagManager');
1285
-	}
1286
-
1287
-	/**
1288
-	 * Returns the system-tag object mapper
1289
-	 *
1290
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1291
-	 *
1292
-	 * @since 9.0.0
1293
-	 */
1294
-	public function getSystemTagObjectMapper() {
1295
-		return $this->query('SystemTagObjectMapper');
1296
-	}
1297
-
1298
-	/**
1299
-	 * Returns the avatar manager, used for avatar functionality
1300
-	 *
1301
-	 * @return \OCP\IAvatarManager
1302
-	 */
1303
-	public function getAvatarManager() {
1304
-		return $this->query('AvatarManager');
1305
-	}
1306
-
1307
-	/**
1308
-	 * Returns the root folder of ownCloud's data directory
1309
-	 *
1310
-	 * @return \OCP\Files\IRootFolder
1311
-	 */
1312
-	public function getRootFolder() {
1313
-		return $this->query('LazyRootFolder');
1314
-	}
1315
-
1316
-	/**
1317
-	 * Returns the root folder of ownCloud's data directory
1318
-	 * This is the lazy variant so this gets only initialized once it
1319
-	 * is actually used.
1320
-	 *
1321
-	 * @return \OCP\Files\IRootFolder
1322
-	 */
1323
-	public function getLazyRootFolder() {
1324
-		return $this->query('LazyRootFolder');
1325
-	}
1326
-
1327
-	/**
1328
-	 * Returns a view to ownCloud's files folder
1329
-	 *
1330
-	 * @param string $userId user ID
1331
-	 * @return \OCP\Files\Folder|null
1332
-	 */
1333
-	public function getUserFolder($userId = null) {
1334
-		if ($userId === null) {
1335
-			$user = $this->getUserSession()->getUser();
1336
-			if (!$user) {
1337
-				return null;
1338
-			}
1339
-			$userId = $user->getUID();
1340
-		}
1341
-		$root = $this->getRootFolder();
1342
-		return $root->getUserFolder($userId);
1343
-	}
1344
-
1345
-	/**
1346
-	 * Returns an app-specific view in ownClouds data directory
1347
-	 *
1348
-	 * @return \OCP\Files\Folder
1349
-	 * @deprecated since 9.2.0 use IAppData
1350
-	 */
1351
-	public function getAppFolder() {
1352
-		$dir = '/' . \OC_App::getCurrentApp();
1353
-		$root = $this->getRootFolder();
1354
-		if (!$root->nodeExists($dir)) {
1355
-			$folder = $root->newFolder($dir);
1356
-		} else {
1357
-			$folder = $root->get($dir);
1358
-		}
1359
-		return $folder;
1360
-	}
1361
-
1362
-	/**
1363
-	 * @return \OC\User\Manager
1364
-	 */
1365
-	public function getUserManager() {
1366
-		return $this->query('UserManager');
1367
-	}
1368
-
1369
-	/**
1370
-	 * @return \OC\Group\Manager
1371
-	 */
1372
-	public function getGroupManager() {
1373
-		return $this->query('GroupManager');
1374
-	}
1375
-
1376
-	/**
1377
-	 * @return \OC\User\Session
1378
-	 */
1379
-	public function getUserSession() {
1380
-		return $this->query('UserSession');
1381
-	}
1382
-
1383
-	/**
1384
-	 * @return \OCP\ISession
1385
-	 */
1386
-	public function getSession() {
1387
-		return $this->query('UserSession')->getSession();
1388
-	}
1389
-
1390
-	/**
1391
-	 * @param \OCP\ISession $session
1392
-	 */
1393
-	public function setSession(\OCP\ISession $session) {
1394
-		$this->query(SessionStorage::class)->setSession($session);
1395
-		$this->query('UserSession')->setSession($session);
1396
-		$this->query(Store::class)->setSession($session);
1397
-	}
1398
-
1399
-	/**
1400
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1401
-	 */
1402
-	public function getTwoFactorAuthManager() {
1403
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1404
-	}
1405
-
1406
-	/**
1407
-	 * @return \OC\NavigationManager
1408
-	 */
1409
-	public function getNavigationManager() {
1410
-		return $this->query('NavigationManager');
1411
-	}
1412
-
1413
-	/**
1414
-	 * @return \OCP\IConfig
1415
-	 */
1416
-	public function getConfig() {
1417
-		return $this->query('AllConfig');
1418
-	}
1419
-
1420
-	/**
1421
-	 * @return \OC\SystemConfig
1422
-	 */
1423
-	public function getSystemConfig() {
1424
-		return $this->query('SystemConfig');
1425
-	}
1426
-
1427
-	/**
1428
-	 * Returns the app config manager
1429
-	 *
1430
-	 * @return \OCP\IAppConfig
1431
-	 */
1432
-	public function getAppConfig() {
1433
-		return $this->query('AppConfig');
1434
-	}
1435
-
1436
-	/**
1437
-	 * @return \OCP\L10N\IFactory
1438
-	 */
1439
-	public function getL10NFactory() {
1440
-		return $this->query('L10NFactory');
1441
-	}
1442
-
1443
-	/**
1444
-	 * get an L10N instance
1445
-	 *
1446
-	 * @param string $app appid
1447
-	 * @param string $lang
1448
-	 * @return IL10N
1449
-	 */
1450
-	public function getL10N($app, $lang = null) {
1451
-		return $this->getL10NFactory()->get($app, $lang);
1452
-	}
1453
-
1454
-	/**
1455
-	 * @return \OCP\IURLGenerator
1456
-	 */
1457
-	public function getURLGenerator() {
1458
-		return $this->query('URLGenerator');
1459
-	}
1460
-
1461
-	/**
1462
-	 * @return \OCP\IHelper
1463
-	 */
1464
-	public function getHelper() {
1465
-		return $this->query('AppHelper');
1466
-	}
1467
-
1468
-	/**
1469
-	 * @return AppFetcher
1470
-	 */
1471
-	public function getAppFetcher() {
1472
-		return $this->query(AppFetcher::class);
1473
-	}
1474
-
1475
-	/**
1476
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1477
-	 * getMemCacheFactory() instead.
1478
-	 *
1479
-	 * @return \OCP\ICache
1480
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1481
-	 */
1482
-	public function getCache() {
1483
-		return $this->query('UserCache');
1484
-	}
1485
-
1486
-	/**
1487
-	 * Returns an \OCP\CacheFactory instance
1488
-	 *
1489
-	 * @return \OCP\ICacheFactory
1490
-	 */
1491
-	public function getMemCacheFactory() {
1492
-		return $this->query('MemCacheFactory');
1493
-	}
1494
-
1495
-	/**
1496
-	 * Returns an \OC\RedisFactory instance
1497
-	 *
1498
-	 * @return \OC\RedisFactory
1499
-	 */
1500
-	public function getGetRedisFactory() {
1501
-		return $this->query('RedisFactory');
1502
-	}
1503
-
1504
-
1505
-	/**
1506
-	 * Returns the current session
1507
-	 *
1508
-	 * @return \OCP\IDBConnection
1509
-	 */
1510
-	public function getDatabaseConnection() {
1511
-		return $this->query('DatabaseConnection');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Returns the activity manager
1516
-	 *
1517
-	 * @return \OCP\Activity\IManager
1518
-	 */
1519
-	public function getActivityManager() {
1520
-		return $this->query('ActivityManager');
1521
-	}
1522
-
1523
-	/**
1524
-	 * Returns an job list for controlling background jobs
1525
-	 *
1526
-	 * @return \OCP\BackgroundJob\IJobList
1527
-	 */
1528
-	public function getJobList() {
1529
-		return $this->query('JobList');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Returns a logger instance
1534
-	 *
1535
-	 * @return \OCP\ILogger
1536
-	 */
1537
-	public function getLogger() {
1538
-		return $this->query('Logger');
1539
-	}
1540
-
1541
-	/**
1542
-	 * Returns a router for generating and matching urls
1543
-	 *
1544
-	 * @return \OCP\Route\IRouter
1545
-	 */
1546
-	public function getRouter() {
1547
-		return $this->query('Router');
1548
-	}
1549
-
1550
-	/**
1551
-	 * Returns a search instance
1552
-	 *
1553
-	 * @return \OCP\ISearch
1554
-	 */
1555
-	public function getSearch() {
1556
-		return $this->query('Search');
1557
-	}
1558
-
1559
-	/**
1560
-	 * Returns a SecureRandom instance
1561
-	 *
1562
-	 * @return \OCP\Security\ISecureRandom
1563
-	 */
1564
-	public function getSecureRandom() {
1565
-		return $this->query('SecureRandom');
1566
-	}
1567
-
1568
-	/**
1569
-	 * Returns a Crypto instance
1570
-	 *
1571
-	 * @return \OCP\Security\ICrypto
1572
-	 */
1573
-	public function getCrypto() {
1574
-		return $this->query('Crypto');
1575
-	}
1576
-
1577
-	/**
1578
-	 * Returns a Hasher instance
1579
-	 *
1580
-	 * @return \OCP\Security\IHasher
1581
-	 */
1582
-	public function getHasher() {
1583
-		return $this->query('Hasher');
1584
-	}
1585
-
1586
-	/**
1587
-	 * Returns a CredentialsManager instance
1588
-	 *
1589
-	 * @return \OCP\Security\ICredentialsManager
1590
-	 */
1591
-	public function getCredentialsManager() {
1592
-		return $this->query('CredentialsManager');
1593
-	}
1594
-
1595
-	/**
1596
-	 * Returns an instance of the HTTP helper class
1597
-	 *
1598
-	 * @deprecated Use getHTTPClientService()
1599
-	 * @return \OC\HTTPHelper
1600
-	 */
1601
-	public function getHTTPHelper() {
1602
-		return $this->query('HTTPHelper');
1603
-	}
1604
-
1605
-	/**
1606
-	 * Get the certificate manager for the user
1607
-	 *
1608
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1609
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1610
-	 */
1611
-	public function getCertificateManager($userId = '') {
1612
-		if ($userId === '') {
1613
-			$userSession = $this->getUserSession();
1614
-			$user = $userSession->getUser();
1615
-			if (is_null($user)) {
1616
-				return null;
1617
-			}
1618
-			$userId = $user->getUID();
1619
-		}
1620
-		return new CertificateManager(
1621
-			$userId,
1622
-			new View(),
1623
-			$this->getConfig(),
1624
-			$this->getLogger(),
1625
-			$this->getSecureRandom()
1626
-		);
1627
-	}
1628
-
1629
-	/**
1630
-	 * Returns an instance of the HTTP client service
1631
-	 *
1632
-	 * @return \OCP\Http\Client\IClientService
1633
-	 */
1634
-	public function getHTTPClientService() {
1635
-		return $this->query('HttpClientService');
1636
-	}
1637
-
1638
-	/**
1639
-	 * Create a new event source
1640
-	 *
1641
-	 * @return \OCP\IEventSource
1642
-	 */
1643
-	public function createEventSource() {
1644
-		return new \OC_EventSource();
1645
-	}
1646
-
1647
-	/**
1648
-	 * Get the active event logger
1649
-	 *
1650
-	 * The returned logger only logs data when debug mode is enabled
1651
-	 *
1652
-	 * @return \OCP\Diagnostics\IEventLogger
1653
-	 */
1654
-	public function getEventLogger() {
1655
-		return $this->query('EventLogger');
1656
-	}
1657
-
1658
-	/**
1659
-	 * Get the active query logger
1660
-	 *
1661
-	 * The returned logger only logs data when debug mode is enabled
1662
-	 *
1663
-	 * @return \OCP\Diagnostics\IQueryLogger
1664
-	 */
1665
-	public function getQueryLogger() {
1666
-		return $this->query('QueryLogger');
1667
-	}
1668
-
1669
-	/**
1670
-	 * Get the manager for temporary files and folders
1671
-	 *
1672
-	 * @return \OCP\ITempManager
1673
-	 */
1674
-	public function getTempManager() {
1675
-		return $this->query('TempManager');
1676
-	}
1677
-
1678
-	/**
1679
-	 * Get the app manager
1680
-	 *
1681
-	 * @return \OCP\App\IAppManager
1682
-	 */
1683
-	public function getAppManager() {
1684
-		return $this->query('AppManager');
1685
-	}
1686
-
1687
-	/**
1688
-	 * Creates a new mailer
1689
-	 *
1690
-	 * @return \OCP\Mail\IMailer
1691
-	 */
1692
-	public function getMailer() {
1693
-		return $this->query('Mailer');
1694
-	}
1695
-
1696
-	/**
1697
-	 * Get the webroot
1698
-	 *
1699
-	 * @return string
1700
-	 */
1701
-	public function getWebRoot() {
1702
-		return $this->webRoot;
1703
-	}
1704
-
1705
-	/**
1706
-	 * @return \OC\OCSClient
1707
-	 */
1708
-	public function getOcsClient() {
1709
-		return $this->query('OcsClient');
1710
-	}
1711
-
1712
-	/**
1713
-	 * @return \OCP\IDateTimeZone
1714
-	 */
1715
-	public function getDateTimeZone() {
1716
-		return $this->query('DateTimeZone');
1717
-	}
1718
-
1719
-	/**
1720
-	 * @return \OCP\IDateTimeFormatter
1721
-	 */
1722
-	public function getDateTimeFormatter() {
1723
-		return $this->query('DateTimeFormatter');
1724
-	}
1725
-
1726
-	/**
1727
-	 * @return \OCP\Files\Config\IMountProviderCollection
1728
-	 */
1729
-	public function getMountProviderCollection() {
1730
-		return $this->query('MountConfigManager');
1731
-	}
1732
-
1733
-	/**
1734
-	 * Get the IniWrapper
1735
-	 *
1736
-	 * @return IniGetWrapper
1737
-	 */
1738
-	public function getIniWrapper() {
1739
-		return $this->query('IniWrapper');
1740
-	}
1741
-
1742
-	/**
1743
-	 * @return \OCP\Command\IBus
1744
-	 */
1745
-	public function getCommandBus() {
1746
-		return $this->query('AsyncCommandBus');
1747
-	}
1748
-
1749
-	/**
1750
-	 * Get the trusted domain helper
1751
-	 *
1752
-	 * @return TrustedDomainHelper
1753
-	 */
1754
-	public function getTrustedDomainHelper() {
1755
-		return $this->query('TrustedDomainHelper');
1756
-	}
1757
-
1758
-	/**
1759
-	 * Get the locking provider
1760
-	 *
1761
-	 * @return \OCP\Lock\ILockingProvider
1762
-	 * @since 8.1.0
1763
-	 */
1764
-	public function getLockingProvider() {
1765
-		return $this->query('LockingProvider');
1766
-	}
1767
-
1768
-	/**
1769
-	 * @return \OCP\Files\Mount\IMountManager
1770
-	 **/
1771
-	function getMountManager() {
1772
-		return $this->query('MountManager');
1773
-	}
1774
-
1775
-	/** @return \OCP\Files\Config\IUserMountCache */
1776
-	function getUserMountCache() {
1777
-		return $this->query('UserMountCache');
1778
-	}
1779
-
1780
-	/**
1781
-	 * Get the MimeTypeDetector
1782
-	 *
1783
-	 * @return \OCP\Files\IMimeTypeDetector
1784
-	 */
1785
-	public function getMimeTypeDetector() {
1786
-		return $this->query('MimeTypeDetector');
1787
-	}
1788
-
1789
-	/**
1790
-	 * Get the MimeTypeLoader
1791
-	 *
1792
-	 * @return \OCP\Files\IMimeTypeLoader
1793
-	 */
1794
-	public function getMimeTypeLoader() {
1795
-		return $this->query('MimeTypeLoader');
1796
-	}
1797
-
1798
-	/**
1799
-	 * Get the manager of all the capabilities
1800
-	 *
1801
-	 * @return \OC\CapabilitiesManager
1802
-	 */
1803
-	public function getCapabilitiesManager() {
1804
-		return $this->query('CapabilitiesManager');
1805
-	}
1806
-
1807
-	/**
1808
-	 * Get the EventDispatcher
1809
-	 *
1810
-	 * @return EventDispatcherInterface
1811
-	 * @since 8.2.0
1812
-	 */
1813
-	public function getEventDispatcher() {
1814
-		return $this->query('EventDispatcher');
1815
-	}
1816
-
1817
-	/**
1818
-	 * Get the Notification Manager
1819
-	 *
1820
-	 * @return \OCP\Notification\IManager
1821
-	 * @since 8.2.0
1822
-	 */
1823
-	public function getNotificationManager() {
1824
-		return $this->query('NotificationManager');
1825
-	}
1826
-
1827
-	/**
1828
-	 * @return \OCP\Comments\ICommentsManager
1829
-	 */
1830
-	public function getCommentsManager() {
1831
-		return $this->query('CommentsManager');
1832
-	}
1833
-
1834
-	/**
1835
-	 * @return \OCA\Theming\ThemingDefaults
1836
-	 */
1837
-	public function getThemingDefaults() {
1838
-		return $this->query('ThemingDefaults');
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return \OC\IntegrityCheck\Checker
1843
-	 */
1844
-	public function getIntegrityCodeChecker() {
1845
-		return $this->query('IntegrityCodeChecker');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return \OC\Session\CryptoWrapper
1850
-	 */
1851
-	public function getSessionCryptoWrapper() {
1852
-		return $this->query('CryptoWrapper');
1853
-	}
1854
-
1855
-	/**
1856
-	 * @return CsrfTokenManager
1857
-	 */
1858
-	public function getCsrfTokenManager() {
1859
-		return $this->query('CsrfTokenManager');
1860
-	}
1861
-
1862
-	/**
1863
-	 * @return Throttler
1864
-	 */
1865
-	public function getBruteForceThrottler() {
1866
-		return $this->query('Throttler');
1867
-	}
1868
-
1869
-	/**
1870
-	 * @return IContentSecurityPolicyManager
1871
-	 */
1872
-	public function getContentSecurityPolicyManager() {
1873
-		return $this->query('ContentSecurityPolicyManager');
1874
-	}
1875
-
1876
-	/**
1877
-	 * @return ContentSecurityPolicyNonceManager
1878
-	 */
1879
-	public function getContentSecurityPolicyNonceManager() {
1880
-		return $this->query('ContentSecurityPolicyNonceManager');
1881
-	}
1882
-
1883
-	/**
1884
-	 * Not a public API as of 8.2, wait for 9.0
1885
-	 *
1886
-	 * @return \OCA\Files_External\Service\BackendService
1887
-	 */
1888
-	public function getStoragesBackendService() {
1889
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1890
-	}
1891
-
1892
-	/**
1893
-	 * Not a public API as of 8.2, wait for 9.0
1894
-	 *
1895
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1896
-	 */
1897
-	public function getGlobalStoragesService() {
1898
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1899
-	}
1900
-
1901
-	/**
1902
-	 * Not a public API as of 8.2, wait for 9.0
1903
-	 *
1904
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1905
-	 */
1906
-	public function getUserGlobalStoragesService() {
1907
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1908
-	}
1909
-
1910
-	/**
1911
-	 * Not a public API as of 8.2, wait for 9.0
1912
-	 *
1913
-	 * @return \OCA\Files_External\Service\UserStoragesService
1914
-	 */
1915
-	public function getUserStoragesService() {
1916
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1917
-	}
1918
-
1919
-	/**
1920
-	 * @return \OCP\Share\IManager
1921
-	 */
1922
-	public function getShareManager() {
1923
-		return $this->query('ShareManager');
1924
-	}
1925
-
1926
-	/**
1927
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1928
-	 */
1929
-	public function getCollaboratorSearch() {
1930
-		return $this->query('CollaboratorSearch');
1931
-	}
1932
-
1933
-	/**
1934
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1935
-	 */
1936
-	public function getAutoCompleteManager(){
1937
-		return $this->query(IManager::class);
1938
-	}
1939
-
1940
-	/**
1941
-	 * Returns the LDAP Provider
1942
-	 *
1943
-	 * @return \OCP\LDAP\ILDAPProvider
1944
-	 */
1945
-	public function getLDAPProvider() {
1946
-		return $this->query('LDAPProvider');
1947
-	}
1948
-
1949
-	/**
1950
-	 * @return \OCP\Settings\IManager
1951
-	 */
1952
-	public function getSettingsManager() {
1953
-		return $this->query('SettingsManager');
1954
-	}
1955
-
1956
-	/**
1957
-	 * @return \OCP\Files\IAppData
1958
-	 */
1959
-	public function getAppDataDir($app) {
1960
-		/** @var \OC\Files\AppData\Factory $factory */
1961
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1962
-		return $factory->get($app);
1963
-	}
1964
-
1965
-	/**
1966
-	 * @return \OCP\Lockdown\ILockdownManager
1967
-	 */
1968
-	public function getLockdownManager() {
1969
-		return $this->query('LockdownManager');
1970
-	}
1971
-
1972
-	/**
1973
-	 * @return \OCP\Federation\ICloudIdManager
1974
-	 */
1975
-	public function getCloudIdManager() {
1976
-		return $this->query(ICloudIdManager::class);
1977
-	}
1978
-
1979
-	/**
1980
-	 * @return \OCP\Remote\Api\IApiFactory
1981
-	 */
1982
-	public function getRemoteApiFactory() {
1983
-		return $this->query(IApiFactory::class);
1984
-	}
1985
-
1986
-	/**
1987
-	 * @return \OCP\Remote\IInstanceFactory
1988
-	 */
1989
-	public function getRemoteInstanceFactory() {
1990
-		return $this->query(IInstanceFactory::class);
1991
-	}
938
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
939
+            if (isset($prefixes['OCA\\Theming\\'])) {
940
+                $classExists = true;
941
+            } else {
942
+                $classExists = false;
943
+            }
944
+
945
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
946
+                return new ThemingDefaults(
947
+                    $c->getConfig(),
948
+                    $c->getL10N('theming'),
949
+                    $c->getURLGenerator(),
950
+                    $c->getAppDataDir('theming'),
951
+                    $c->getMemCacheFactory(),
952
+                    new Util($c->getConfig(), $this->getAppManager(), $this->getAppDataDir('theming')),
953
+                    $this->getAppManager()
954
+                );
955
+            }
956
+            return new \OC_Defaults();
957
+        });
958
+        $this->registerService(SCSSCacher::class, function (Server $c) {
959
+            /** @var Factory $cacheFactory */
960
+            $cacheFactory = $c->query(Factory::class);
961
+            return new SCSSCacher(
962
+                $c->getLogger(),
963
+                $c->query(\OC\Files\AppData\Factory::class),
964
+                $c->getURLGenerator(),
965
+                $c->getConfig(),
966
+                $c->getThemingDefaults(),
967
+                \OC::$SERVERROOT,
968
+                $cacheFactory->createDistributed('SCSS')
969
+            );
970
+        });
971
+        $this->registerService(JSCombiner::class, function (Server $c) {
972
+            /** @var Factory $cacheFactory */
973
+            $cacheFactory = $c->query(Factory::class);
974
+            return new JSCombiner(
975
+                $c->getAppDataDir('js'),
976
+                $c->getURLGenerator(),
977
+                $cacheFactory->createDistributed('JS'),
978
+                $c->getSystemConfig(),
979
+                $c->getLogger()
980
+            );
981
+        });
982
+        $this->registerService(EventDispatcher::class, function () {
983
+            return new EventDispatcher();
984
+        });
985
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
986
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
987
+
988
+        $this->registerService('CryptoWrapper', function (Server $c) {
989
+            // FIXME: Instantiiated here due to cyclic dependency
990
+            $request = new Request(
991
+                [
992
+                    'get' => $_GET,
993
+                    'post' => $_POST,
994
+                    'files' => $_FILES,
995
+                    'server' => $_SERVER,
996
+                    'env' => $_ENV,
997
+                    'cookies' => $_COOKIE,
998
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
999
+                        ? $_SERVER['REQUEST_METHOD']
1000
+                        : null,
1001
+                ],
1002
+                $c->getSecureRandom(),
1003
+                $c->getConfig()
1004
+            );
1005
+
1006
+            return new CryptoWrapper(
1007
+                $c->getConfig(),
1008
+                $c->getCrypto(),
1009
+                $c->getSecureRandom(),
1010
+                $request
1011
+            );
1012
+        });
1013
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1014
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1015
+
1016
+            return new CsrfTokenManager(
1017
+                $tokenGenerator,
1018
+                $c->query(SessionStorage::class)
1019
+            );
1020
+        });
1021
+        $this->registerService(SessionStorage::class, function (Server $c) {
1022
+            return new SessionStorage($c->getSession());
1023
+        });
1024
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1025
+            return new ContentSecurityPolicyManager();
1026
+        });
1027
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1028
+
1029
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1030
+            return new ContentSecurityPolicyNonceManager(
1031
+                $c->getCsrfTokenManager(),
1032
+                $c->getRequest()
1033
+            );
1034
+        });
1035
+
1036
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1037
+            $config = $c->getConfig();
1038
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1039
+            /** @var \OCP\Share\IProviderFactory $factory */
1040
+            $factory = new $factoryClass($this);
1041
+
1042
+            $manager = new \OC\Share20\Manager(
1043
+                $c->getLogger(),
1044
+                $c->getConfig(),
1045
+                $c->getSecureRandom(),
1046
+                $c->getHasher(),
1047
+                $c->getMountManager(),
1048
+                $c->getGroupManager(),
1049
+                $c->getL10N('lib'),
1050
+                $c->getL10NFactory(),
1051
+                $factory,
1052
+                $c->getUserManager(),
1053
+                $c->getLazyRootFolder(),
1054
+                $c->getEventDispatcher(),
1055
+                $c->getMailer(),
1056
+                $c->getURLGenerator(),
1057
+                $c->getThemingDefaults()
1058
+            );
1059
+
1060
+            return $manager;
1061
+        });
1062
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1063
+
1064
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1065
+            $instance = new Collaboration\Collaborators\Search($c);
1066
+
1067
+            // register default plugins
1068
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1069
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1070
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1071
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1072
+
1073
+            return $instance;
1074
+        });
1075
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1076
+
1077
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1078
+
1079
+        $this->registerService('SettingsManager', function (Server $c) {
1080
+            $manager = new \OC\Settings\Manager(
1081
+                $c->getLogger(),
1082
+                $c->getDatabaseConnection(),
1083
+                $c->getL10N('lib'),
1084
+                $c->getConfig(),
1085
+                $c->getEncryptionManager(),
1086
+                $c->getUserManager(),
1087
+                $c->getLockingProvider(),
1088
+                $c->getRequest(),
1089
+                $c->getURLGenerator(),
1090
+                $c->query(AccountManager::class),
1091
+                $c->getGroupManager(),
1092
+                $c->getL10NFactory(),
1093
+                $c->getAppManager()
1094
+            );
1095
+            return $manager;
1096
+        });
1097
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1098
+            return new \OC\Files\AppData\Factory(
1099
+                $c->getRootFolder(),
1100
+                $c->getSystemConfig()
1101
+            );
1102
+        });
1103
+
1104
+        $this->registerService('LockdownManager', function (Server $c) {
1105
+            return new LockdownManager(function () use ($c) {
1106
+                return $c->getSession();
1107
+            });
1108
+        });
1109
+
1110
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1111
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1112
+        });
1113
+
1114
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1115
+            return new CloudIdManager();
1116
+        });
1117
+
1118
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1119
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1120
+
1121
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1122
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1123
+
1124
+        $this->registerService(Defaults::class, function (Server $c) {
1125
+            return new Defaults(
1126
+                $c->getThemingDefaults()
1127
+            );
1128
+        });
1129
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1130
+
1131
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1132
+            return $c->query(\OCP\IUserSession::class)->getSession();
1133
+        });
1134
+
1135
+        $this->registerService(IShareHelper::class, function (Server $c) {
1136
+            return new ShareHelper(
1137
+                $c->query(\OCP\Share\IManager::class)
1138
+            );
1139
+        });
1140
+
1141
+        $this->registerService(Installer::class, function(Server $c) {
1142
+            return new Installer(
1143
+                $c->getAppFetcher(),
1144
+                $c->getHTTPClientService(),
1145
+                $c->getTempManager(),
1146
+                $c->getLogger(),
1147
+                $c->getConfig()
1148
+            );
1149
+        });
1150
+
1151
+        $this->registerService(IApiFactory::class, function(Server $c) {
1152
+            return new ApiFactory($c->getHTTPClientService());
1153
+        });
1154
+
1155
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1156
+            $memcacheFactory = $c->getMemCacheFactory();
1157
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1158
+        });
1159
+
1160
+        $this->registerService(IContactsStore::class, function(Server $c) {
1161
+            return new ContactsStore(
1162
+                $c->getContactsManager(),
1163
+                $c->getConfig(),
1164
+                $c->getUserManager(),
1165
+                $c->getGroupManager()
1166
+            );
1167
+        });
1168
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1169
+
1170
+        $this->connectDispatcher();
1171
+    }
1172
+
1173
+    /**
1174
+     * @return \OCP\Calendar\IManager
1175
+     */
1176
+    public function getCalendarManager() {
1177
+        return $this->query('CalendarManager');
1178
+    }
1179
+
1180
+    private function connectDispatcher() {
1181
+        $dispatcher = $this->getEventDispatcher();
1182
+
1183
+        // Delete avatar on user deletion
1184
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1185
+            $logger = $this->getLogger();
1186
+            $manager = $this->getAvatarManager();
1187
+            /** @var IUser $user */
1188
+            $user = $e->getSubject();
1189
+
1190
+            try {
1191
+                $avatar = $manager->getAvatar($user->getUID());
1192
+                $avatar->remove();
1193
+            } catch (NotFoundException $e) {
1194
+                // no avatar to remove
1195
+            } catch (\Exception $e) {
1196
+                // Ignore exceptions
1197
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1198
+            }
1199
+        });
1200
+
1201
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1202
+            $manager = $this->getAvatarManager();
1203
+            /** @var IUser $user */
1204
+            $user = $e->getSubject();
1205
+            $feature = $e->getArgument('feature');
1206
+            $oldValue = $e->getArgument('oldValue');
1207
+            $value = $e->getArgument('value');
1208
+
1209
+            try {
1210
+                $avatar = $manager->getAvatar($user->getUID());
1211
+                $avatar->userChanged($feature, $oldValue, $value);
1212
+            } catch (NotFoundException $e) {
1213
+                // no avatar to remove
1214
+            }
1215
+        });
1216
+    }
1217
+
1218
+    /**
1219
+     * @return \OCP\Contacts\IManager
1220
+     */
1221
+    public function getContactsManager() {
1222
+        return $this->query('ContactsManager');
1223
+    }
1224
+
1225
+    /**
1226
+     * @return \OC\Encryption\Manager
1227
+     */
1228
+    public function getEncryptionManager() {
1229
+        return $this->query('EncryptionManager');
1230
+    }
1231
+
1232
+    /**
1233
+     * @return \OC\Encryption\File
1234
+     */
1235
+    public function getEncryptionFilesHelper() {
1236
+        return $this->query('EncryptionFileHelper');
1237
+    }
1238
+
1239
+    /**
1240
+     * @return \OCP\Encryption\Keys\IStorage
1241
+     */
1242
+    public function getEncryptionKeyStorage() {
1243
+        return $this->query('EncryptionKeyStorage');
1244
+    }
1245
+
1246
+    /**
1247
+     * The current request object holding all information about the request
1248
+     * currently being processed is returned from this method.
1249
+     * In case the current execution was not initiated by a web request null is returned
1250
+     *
1251
+     * @return \OCP\IRequest
1252
+     */
1253
+    public function getRequest() {
1254
+        return $this->query('Request');
1255
+    }
1256
+
1257
+    /**
1258
+     * Returns the preview manager which can create preview images for a given file
1259
+     *
1260
+     * @return \OCP\IPreview
1261
+     */
1262
+    public function getPreviewManager() {
1263
+        return $this->query('PreviewManager');
1264
+    }
1265
+
1266
+    /**
1267
+     * Returns the tag manager which can get and set tags for different object types
1268
+     *
1269
+     * @see \OCP\ITagManager::load()
1270
+     * @return \OCP\ITagManager
1271
+     */
1272
+    public function getTagManager() {
1273
+        return $this->query('TagManager');
1274
+    }
1275
+
1276
+    /**
1277
+     * Returns the system-tag manager
1278
+     *
1279
+     * @return \OCP\SystemTag\ISystemTagManager
1280
+     *
1281
+     * @since 9.0.0
1282
+     */
1283
+    public function getSystemTagManager() {
1284
+        return $this->query('SystemTagManager');
1285
+    }
1286
+
1287
+    /**
1288
+     * Returns the system-tag object mapper
1289
+     *
1290
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1291
+     *
1292
+     * @since 9.0.0
1293
+     */
1294
+    public function getSystemTagObjectMapper() {
1295
+        return $this->query('SystemTagObjectMapper');
1296
+    }
1297
+
1298
+    /**
1299
+     * Returns the avatar manager, used for avatar functionality
1300
+     *
1301
+     * @return \OCP\IAvatarManager
1302
+     */
1303
+    public function getAvatarManager() {
1304
+        return $this->query('AvatarManager');
1305
+    }
1306
+
1307
+    /**
1308
+     * Returns the root folder of ownCloud's data directory
1309
+     *
1310
+     * @return \OCP\Files\IRootFolder
1311
+     */
1312
+    public function getRootFolder() {
1313
+        return $this->query('LazyRootFolder');
1314
+    }
1315
+
1316
+    /**
1317
+     * Returns the root folder of ownCloud's data directory
1318
+     * This is the lazy variant so this gets only initialized once it
1319
+     * is actually used.
1320
+     *
1321
+     * @return \OCP\Files\IRootFolder
1322
+     */
1323
+    public function getLazyRootFolder() {
1324
+        return $this->query('LazyRootFolder');
1325
+    }
1326
+
1327
+    /**
1328
+     * Returns a view to ownCloud's files folder
1329
+     *
1330
+     * @param string $userId user ID
1331
+     * @return \OCP\Files\Folder|null
1332
+     */
1333
+    public function getUserFolder($userId = null) {
1334
+        if ($userId === null) {
1335
+            $user = $this->getUserSession()->getUser();
1336
+            if (!$user) {
1337
+                return null;
1338
+            }
1339
+            $userId = $user->getUID();
1340
+        }
1341
+        $root = $this->getRootFolder();
1342
+        return $root->getUserFolder($userId);
1343
+    }
1344
+
1345
+    /**
1346
+     * Returns an app-specific view in ownClouds data directory
1347
+     *
1348
+     * @return \OCP\Files\Folder
1349
+     * @deprecated since 9.2.0 use IAppData
1350
+     */
1351
+    public function getAppFolder() {
1352
+        $dir = '/' . \OC_App::getCurrentApp();
1353
+        $root = $this->getRootFolder();
1354
+        if (!$root->nodeExists($dir)) {
1355
+            $folder = $root->newFolder($dir);
1356
+        } else {
1357
+            $folder = $root->get($dir);
1358
+        }
1359
+        return $folder;
1360
+    }
1361
+
1362
+    /**
1363
+     * @return \OC\User\Manager
1364
+     */
1365
+    public function getUserManager() {
1366
+        return $this->query('UserManager');
1367
+    }
1368
+
1369
+    /**
1370
+     * @return \OC\Group\Manager
1371
+     */
1372
+    public function getGroupManager() {
1373
+        return $this->query('GroupManager');
1374
+    }
1375
+
1376
+    /**
1377
+     * @return \OC\User\Session
1378
+     */
1379
+    public function getUserSession() {
1380
+        return $this->query('UserSession');
1381
+    }
1382
+
1383
+    /**
1384
+     * @return \OCP\ISession
1385
+     */
1386
+    public function getSession() {
1387
+        return $this->query('UserSession')->getSession();
1388
+    }
1389
+
1390
+    /**
1391
+     * @param \OCP\ISession $session
1392
+     */
1393
+    public function setSession(\OCP\ISession $session) {
1394
+        $this->query(SessionStorage::class)->setSession($session);
1395
+        $this->query('UserSession')->setSession($session);
1396
+        $this->query(Store::class)->setSession($session);
1397
+    }
1398
+
1399
+    /**
1400
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1401
+     */
1402
+    public function getTwoFactorAuthManager() {
1403
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1404
+    }
1405
+
1406
+    /**
1407
+     * @return \OC\NavigationManager
1408
+     */
1409
+    public function getNavigationManager() {
1410
+        return $this->query('NavigationManager');
1411
+    }
1412
+
1413
+    /**
1414
+     * @return \OCP\IConfig
1415
+     */
1416
+    public function getConfig() {
1417
+        return $this->query('AllConfig');
1418
+    }
1419
+
1420
+    /**
1421
+     * @return \OC\SystemConfig
1422
+     */
1423
+    public function getSystemConfig() {
1424
+        return $this->query('SystemConfig');
1425
+    }
1426
+
1427
+    /**
1428
+     * Returns the app config manager
1429
+     *
1430
+     * @return \OCP\IAppConfig
1431
+     */
1432
+    public function getAppConfig() {
1433
+        return $this->query('AppConfig');
1434
+    }
1435
+
1436
+    /**
1437
+     * @return \OCP\L10N\IFactory
1438
+     */
1439
+    public function getL10NFactory() {
1440
+        return $this->query('L10NFactory');
1441
+    }
1442
+
1443
+    /**
1444
+     * get an L10N instance
1445
+     *
1446
+     * @param string $app appid
1447
+     * @param string $lang
1448
+     * @return IL10N
1449
+     */
1450
+    public function getL10N($app, $lang = null) {
1451
+        return $this->getL10NFactory()->get($app, $lang);
1452
+    }
1453
+
1454
+    /**
1455
+     * @return \OCP\IURLGenerator
1456
+     */
1457
+    public function getURLGenerator() {
1458
+        return $this->query('URLGenerator');
1459
+    }
1460
+
1461
+    /**
1462
+     * @return \OCP\IHelper
1463
+     */
1464
+    public function getHelper() {
1465
+        return $this->query('AppHelper');
1466
+    }
1467
+
1468
+    /**
1469
+     * @return AppFetcher
1470
+     */
1471
+    public function getAppFetcher() {
1472
+        return $this->query(AppFetcher::class);
1473
+    }
1474
+
1475
+    /**
1476
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1477
+     * getMemCacheFactory() instead.
1478
+     *
1479
+     * @return \OCP\ICache
1480
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1481
+     */
1482
+    public function getCache() {
1483
+        return $this->query('UserCache');
1484
+    }
1485
+
1486
+    /**
1487
+     * Returns an \OCP\CacheFactory instance
1488
+     *
1489
+     * @return \OCP\ICacheFactory
1490
+     */
1491
+    public function getMemCacheFactory() {
1492
+        return $this->query('MemCacheFactory');
1493
+    }
1494
+
1495
+    /**
1496
+     * Returns an \OC\RedisFactory instance
1497
+     *
1498
+     * @return \OC\RedisFactory
1499
+     */
1500
+    public function getGetRedisFactory() {
1501
+        return $this->query('RedisFactory');
1502
+    }
1503
+
1504
+
1505
+    /**
1506
+     * Returns the current session
1507
+     *
1508
+     * @return \OCP\IDBConnection
1509
+     */
1510
+    public function getDatabaseConnection() {
1511
+        return $this->query('DatabaseConnection');
1512
+    }
1513
+
1514
+    /**
1515
+     * Returns the activity manager
1516
+     *
1517
+     * @return \OCP\Activity\IManager
1518
+     */
1519
+    public function getActivityManager() {
1520
+        return $this->query('ActivityManager');
1521
+    }
1522
+
1523
+    /**
1524
+     * Returns an job list for controlling background jobs
1525
+     *
1526
+     * @return \OCP\BackgroundJob\IJobList
1527
+     */
1528
+    public function getJobList() {
1529
+        return $this->query('JobList');
1530
+    }
1531
+
1532
+    /**
1533
+     * Returns a logger instance
1534
+     *
1535
+     * @return \OCP\ILogger
1536
+     */
1537
+    public function getLogger() {
1538
+        return $this->query('Logger');
1539
+    }
1540
+
1541
+    /**
1542
+     * Returns a router for generating and matching urls
1543
+     *
1544
+     * @return \OCP\Route\IRouter
1545
+     */
1546
+    public function getRouter() {
1547
+        return $this->query('Router');
1548
+    }
1549
+
1550
+    /**
1551
+     * Returns a search instance
1552
+     *
1553
+     * @return \OCP\ISearch
1554
+     */
1555
+    public function getSearch() {
1556
+        return $this->query('Search');
1557
+    }
1558
+
1559
+    /**
1560
+     * Returns a SecureRandom instance
1561
+     *
1562
+     * @return \OCP\Security\ISecureRandom
1563
+     */
1564
+    public function getSecureRandom() {
1565
+        return $this->query('SecureRandom');
1566
+    }
1567
+
1568
+    /**
1569
+     * Returns a Crypto instance
1570
+     *
1571
+     * @return \OCP\Security\ICrypto
1572
+     */
1573
+    public function getCrypto() {
1574
+        return $this->query('Crypto');
1575
+    }
1576
+
1577
+    /**
1578
+     * Returns a Hasher instance
1579
+     *
1580
+     * @return \OCP\Security\IHasher
1581
+     */
1582
+    public function getHasher() {
1583
+        return $this->query('Hasher');
1584
+    }
1585
+
1586
+    /**
1587
+     * Returns a CredentialsManager instance
1588
+     *
1589
+     * @return \OCP\Security\ICredentialsManager
1590
+     */
1591
+    public function getCredentialsManager() {
1592
+        return $this->query('CredentialsManager');
1593
+    }
1594
+
1595
+    /**
1596
+     * Returns an instance of the HTTP helper class
1597
+     *
1598
+     * @deprecated Use getHTTPClientService()
1599
+     * @return \OC\HTTPHelper
1600
+     */
1601
+    public function getHTTPHelper() {
1602
+        return $this->query('HTTPHelper');
1603
+    }
1604
+
1605
+    /**
1606
+     * Get the certificate manager for the user
1607
+     *
1608
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1609
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1610
+     */
1611
+    public function getCertificateManager($userId = '') {
1612
+        if ($userId === '') {
1613
+            $userSession = $this->getUserSession();
1614
+            $user = $userSession->getUser();
1615
+            if (is_null($user)) {
1616
+                return null;
1617
+            }
1618
+            $userId = $user->getUID();
1619
+        }
1620
+        return new CertificateManager(
1621
+            $userId,
1622
+            new View(),
1623
+            $this->getConfig(),
1624
+            $this->getLogger(),
1625
+            $this->getSecureRandom()
1626
+        );
1627
+    }
1628
+
1629
+    /**
1630
+     * Returns an instance of the HTTP client service
1631
+     *
1632
+     * @return \OCP\Http\Client\IClientService
1633
+     */
1634
+    public function getHTTPClientService() {
1635
+        return $this->query('HttpClientService');
1636
+    }
1637
+
1638
+    /**
1639
+     * Create a new event source
1640
+     *
1641
+     * @return \OCP\IEventSource
1642
+     */
1643
+    public function createEventSource() {
1644
+        return new \OC_EventSource();
1645
+    }
1646
+
1647
+    /**
1648
+     * Get the active event logger
1649
+     *
1650
+     * The returned logger only logs data when debug mode is enabled
1651
+     *
1652
+     * @return \OCP\Diagnostics\IEventLogger
1653
+     */
1654
+    public function getEventLogger() {
1655
+        return $this->query('EventLogger');
1656
+    }
1657
+
1658
+    /**
1659
+     * Get the active query logger
1660
+     *
1661
+     * The returned logger only logs data when debug mode is enabled
1662
+     *
1663
+     * @return \OCP\Diagnostics\IQueryLogger
1664
+     */
1665
+    public function getQueryLogger() {
1666
+        return $this->query('QueryLogger');
1667
+    }
1668
+
1669
+    /**
1670
+     * Get the manager for temporary files and folders
1671
+     *
1672
+     * @return \OCP\ITempManager
1673
+     */
1674
+    public function getTempManager() {
1675
+        return $this->query('TempManager');
1676
+    }
1677
+
1678
+    /**
1679
+     * Get the app manager
1680
+     *
1681
+     * @return \OCP\App\IAppManager
1682
+     */
1683
+    public function getAppManager() {
1684
+        return $this->query('AppManager');
1685
+    }
1686
+
1687
+    /**
1688
+     * Creates a new mailer
1689
+     *
1690
+     * @return \OCP\Mail\IMailer
1691
+     */
1692
+    public function getMailer() {
1693
+        return $this->query('Mailer');
1694
+    }
1695
+
1696
+    /**
1697
+     * Get the webroot
1698
+     *
1699
+     * @return string
1700
+     */
1701
+    public function getWebRoot() {
1702
+        return $this->webRoot;
1703
+    }
1704
+
1705
+    /**
1706
+     * @return \OC\OCSClient
1707
+     */
1708
+    public function getOcsClient() {
1709
+        return $this->query('OcsClient');
1710
+    }
1711
+
1712
+    /**
1713
+     * @return \OCP\IDateTimeZone
1714
+     */
1715
+    public function getDateTimeZone() {
1716
+        return $this->query('DateTimeZone');
1717
+    }
1718
+
1719
+    /**
1720
+     * @return \OCP\IDateTimeFormatter
1721
+     */
1722
+    public function getDateTimeFormatter() {
1723
+        return $this->query('DateTimeFormatter');
1724
+    }
1725
+
1726
+    /**
1727
+     * @return \OCP\Files\Config\IMountProviderCollection
1728
+     */
1729
+    public function getMountProviderCollection() {
1730
+        return $this->query('MountConfigManager');
1731
+    }
1732
+
1733
+    /**
1734
+     * Get the IniWrapper
1735
+     *
1736
+     * @return IniGetWrapper
1737
+     */
1738
+    public function getIniWrapper() {
1739
+        return $this->query('IniWrapper');
1740
+    }
1741
+
1742
+    /**
1743
+     * @return \OCP\Command\IBus
1744
+     */
1745
+    public function getCommandBus() {
1746
+        return $this->query('AsyncCommandBus');
1747
+    }
1748
+
1749
+    /**
1750
+     * Get the trusted domain helper
1751
+     *
1752
+     * @return TrustedDomainHelper
1753
+     */
1754
+    public function getTrustedDomainHelper() {
1755
+        return $this->query('TrustedDomainHelper');
1756
+    }
1757
+
1758
+    /**
1759
+     * Get the locking provider
1760
+     *
1761
+     * @return \OCP\Lock\ILockingProvider
1762
+     * @since 8.1.0
1763
+     */
1764
+    public function getLockingProvider() {
1765
+        return $this->query('LockingProvider');
1766
+    }
1767
+
1768
+    /**
1769
+     * @return \OCP\Files\Mount\IMountManager
1770
+     **/
1771
+    function getMountManager() {
1772
+        return $this->query('MountManager');
1773
+    }
1774
+
1775
+    /** @return \OCP\Files\Config\IUserMountCache */
1776
+    function getUserMountCache() {
1777
+        return $this->query('UserMountCache');
1778
+    }
1779
+
1780
+    /**
1781
+     * Get the MimeTypeDetector
1782
+     *
1783
+     * @return \OCP\Files\IMimeTypeDetector
1784
+     */
1785
+    public function getMimeTypeDetector() {
1786
+        return $this->query('MimeTypeDetector');
1787
+    }
1788
+
1789
+    /**
1790
+     * Get the MimeTypeLoader
1791
+     *
1792
+     * @return \OCP\Files\IMimeTypeLoader
1793
+     */
1794
+    public function getMimeTypeLoader() {
1795
+        return $this->query('MimeTypeLoader');
1796
+    }
1797
+
1798
+    /**
1799
+     * Get the manager of all the capabilities
1800
+     *
1801
+     * @return \OC\CapabilitiesManager
1802
+     */
1803
+    public function getCapabilitiesManager() {
1804
+        return $this->query('CapabilitiesManager');
1805
+    }
1806
+
1807
+    /**
1808
+     * Get the EventDispatcher
1809
+     *
1810
+     * @return EventDispatcherInterface
1811
+     * @since 8.2.0
1812
+     */
1813
+    public function getEventDispatcher() {
1814
+        return $this->query('EventDispatcher');
1815
+    }
1816
+
1817
+    /**
1818
+     * Get the Notification Manager
1819
+     *
1820
+     * @return \OCP\Notification\IManager
1821
+     * @since 8.2.0
1822
+     */
1823
+    public function getNotificationManager() {
1824
+        return $this->query('NotificationManager');
1825
+    }
1826
+
1827
+    /**
1828
+     * @return \OCP\Comments\ICommentsManager
1829
+     */
1830
+    public function getCommentsManager() {
1831
+        return $this->query('CommentsManager');
1832
+    }
1833
+
1834
+    /**
1835
+     * @return \OCA\Theming\ThemingDefaults
1836
+     */
1837
+    public function getThemingDefaults() {
1838
+        return $this->query('ThemingDefaults');
1839
+    }
1840
+
1841
+    /**
1842
+     * @return \OC\IntegrityCheck\Checker
1843
+     */
1844
+    public function getIntegrityCodeChecker() {
1845
+        return $this->query('IntegrityCodeChecker');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return \OC\Session\CryptoWrapper
1850
+     */
1851
+    public function getSessionCryptoWrapper() {
1852
+        return $this->query('CryptoWrapper');
1853
+    }
1854
+
1855
+    /**
1856
+     * @return CsrfTokenManager
1857
+     */
1858
+    public function getCsrfTokenManager() {
1859
+        return $this->query('CsrfTokenManager');
1860
+    }
1861
+
1862
+    /**
1863
+     * @return Throttler
1864
+     */
1865
+    public function getBruteForceThrottler() {
1866
+        return $this->query('Throttler');
1867
+    }
1868
+
1869
+    /**
1870
+     * @return IContentSecurityPolicyManager
1871
+     */
1872
+    public function getContentSecurityPolicyManager() {
1873
+        return $this->query('ContentSecurityPolicyManager');
1874
+    }
1875
+
1876
+    /**
1877
+     * @return ContentSecurityPolicyNonceManager
1878
+     */
1879
+    public function getContentSecurityPolicyNonceManager() {
1880
+        return $this->query('ContentSecurityPolicyNonceManager');
1881
+    }
1882
+
1883
+    /**
1884
+     * Not a public API as of 8.2, wait for 9.0
1885
+     *
1886
+     * @return \OCA\Files_External\Service\BackendService
1887
+     */
1888
+    public function getStoragesBackendService() {
1889
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1890
+    }
1891
+
1892
+    /**
1893
+     * Not a public API as of 8.2, wait for 9.0
1894
+     *
1895
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1896
+     */
1897
+    public function getGlobalStoragesService() {
1898
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1899
+    }
1900
+
1901
+    /**
1902
+     * Not a public API as of 8.2, wait for 9.0
1903
+     *
1904
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1905
+     */
1906
+    public function getUserGlobalStoragesService() {
1907
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1908
+    }
1909
+
1910
+    /**
1911
+     * Not a public API as of 8.2, wait for 9.0
1912
+     *
1913
+     * @return \OCA\Files_External\Service\UserStoragesService
1914
+     */
1915
+    public function getUserStoragesService() {
1916
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1917
+    }
1918
+
1919
+    /**
1920
+     * @return \OCP\Share\IManager
1921
+     */
1922
+    public function getShareManager() {
1923
+        return $this->query('ShareManager');
1924
+    }
1925
+
1926
+    /**
1927
+     * @return \OCP\Collaboration\Collaborators\ISearch
1928
+     */
1929
+    public function getCollaboratorSearch() {
1930
+        return $this->query('CollaboratorSearch');
1931
+    }
1932
+
1933
+    /**
1934
+     * @return \OCP\Collaboration\AutoComplete\IManager
1935
+     */
1936
+    public function getAutoCompleteManager(){
1937
+        return $this->query(IManager::class);
1938
+    }
1939
+
1940
+    /**
1941
+     * Returns the LDAP Provider
1942
+     *
1943
+     * @return \OCP\LDAP\ILDAPProvider
1944
+     */
1945
+    public function getLDAPProvider() {
1946
+        return $this->query('LDAPProvider');
1947
+    }
1948
+
1949
+    /**
1950
+     * @return \OCP\Settings\IManager
1951
+     */
1952
+    public function getSettingsManager() {
1953
+        return $this->query('SettingsManager');
1954
+    }
1955
+
1956
+    /**
1957
+     * @return \OCP\Files\IAppData
1958
+     */
1959
+    public function getAppDataDir($app) {
1960
+        /** @var \OC\Files\AppData\Factory $factory */
1961
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1962
+        return $factory->get($app);
1963
+    }
1964
+
1965
+    /**
1966
+     * @return \OCP\Lockdown\ILockdownManager
1967
+     */
1968
+    public function getLockdownManager() {
1969
+        return $this->query('LockdownManager');
1970
+    }
1971
+
1972
+    /**
1973
+     * @return \OCP\Federation\ICloudIdManager
1974
+     */
1975
+    public function getCloudIdManager() {
1976
+        return $this->query(ICloudIdManager::class);
1977
+    }
1978
+
1979
+    /**
1980
+     * @return \OCP\Remote\Api\IApiFactory
1981
+     */
1982
+    public function getRemoteApiFactory() {
1983
+        return $this->query(IApiFactory::class);
1984
+    }
1985
+
1986
+    /**
1987
+     * @return \OCP\Remote\IInstanceFactory
1988
+     */
1989
+    public function getRemoteInstanceFactory() {
1990
+        return $this->query(IInstanceFactory::class);
1991
+    }
1992 1992
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http/Request.php 2 patches
Indentation   +822 added lines, -822 removed lines patch added patch discarded remove patch
@@ -59,827 +59,827 @@
 block discarded – undo
59 59
  */
60 60
 class Request implements \ArrayAccess, \Countable, IRequest {
61 61
 
62
-	const USER_AGENT_IE = '/(MSIE)|(Trident)/';
63
-	// Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
64
-	const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
65
-	// Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
66
-	const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
67
-	// Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
68
-	const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/';
69
-	// Safari User Agent from http://www.useragentstring.com/pages/Safari/
70
-	const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
71
-	// Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
72
-	const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
73
-	const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
74
-	const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
75
-
76
-	/**
77
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
78
-	 */
79
-	const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
80
-	/**
81
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
82
-	 */
83
-	const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
84
-	/**
85
-	 * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
86
-	 */
87
-	const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
88
-
89
-	protected $inputStream;
90
-	protected $content;
91
-	protected $items = [];
92
-	protected $allowedKeys = [
93
-		'get',
94
-		'post',
95
-		'files',
96
-		'server',
97
-		'env',
98
-		'cookies',
99
-		'urlParams',
100
-		'parameters',
101
-		'method',
102
-		'requesttoken',
103
-	];
104
-	/** @var ISecureRandom */
105
-	protected $secureRandom;
106
-	/** @var IConfig */
107
-	protected $config;
108
-	/** @var string */
109
-	protected $requestId = '';
110
-	/** @var ICrypto */
111
-	protected $crypto;
112
-	/** @var CsrfTokenManager|null */
113
-	protected $csrfTokenManager;
114
-
115
-	/** @var bool */
116
-	protected $contentDecoded = false;
117
-
118
-	/**
119
-	 * @param array $vars An associative array with the following optional values:
120
-	 *        - array 'urlParams' the parameters which were matched from the URL
121
-	 *        - array 'get' the $_GET array
122
-	 *        - array|string 'post' the $_POST array or JSON string
123
-	 *        - array 'files' the $_FILES array
124
-	 *        - array 'server' the $_SERVER array
125
-	 *        - array 'env' the $_ENV array
126
-	 *        - array 'cookies' the $_COOKIE array
127
-	 *        - string 'method' the request method (GET, POST etc)
128
-	 *        - string|false 'requesttoken' the requesttoken or false when not available
129
-	 * @param ISecureRandom $secureRandom
130
-	 * @param IConfig $config
131
-	 * @param CsrfTokenManager|null $csrfTokenManager
132
-	 * @param string $stream
133
-	 * @see http://www.php.net/manual/en/reserved.variables.php
134
-	 */
135
-	public function __construct(array $vars= [],
136
-								ISecureRandom $secureRandom = null,
137
-								IConfig $config,
138
-								CsrfTokenManager $csrfTokenManager = null,
139
-								string $stream = 'php://input') {
140
-		$this->inputStream = $stream;
141
-		$this->items['params'] = [];
142
-		$this->secureRandom = $secureRandom;
143
-		$this->config = $config;
144
-		$this->csrfTokenManager = $csrfTokenManager;
145
-
146
-		if(!array_key_exists('method', $vars)) {
147
-			$vars['method'] = 'GET';
148
-		}
149
-
150
-		foreach($this->allowedKeys as $name) {
151
-			$this->items[$name] = isset($vars[$name])
152
-				? $vars[$name]
153
-				: [];
154
-		}
155
-
156
-		$this->items['parameters'] = array_merge(
157
-			$this->items['get'],
158
-			$this->items['post'],
159
-			$this->items['urlParams'],
160
-			$this->items['params']
161
-		);
162
-
163
-	}
164
-	/**
165
-	 * @param array $parameters
166
-	 */
167
-	public function setUrlParameters(array $parameters) {
168
-		$this->items['urlParams'] = $parameters;
169
-		$this->items['parameters'] = array_merge(
170
-			$this->items['parameters'],
171
-			$this->items['urlParams']
172
-		);
173
-	}
174
-
175
-	/**
176
-	 * Countable method
177
-	 * @return int
178
-	 */
179
-	public function count(): int {
180
-		return \count($this->items['parameters']);
181
-	}
182
-
183
-	/**
184
-	* ArrayAccess methods
185
-	*
186
-	* Gives access to the combined GET, POST and urlParams arrays
187
-	*
188
-	* Examples:
189
-	*
190
-	* $var = $request['myvar'];
191
-	*
192
-	* or
193
-	*
194
-	* if(!isset($request['myvar']) {
195
-	* 	// Do something
196
-	* }
197
-	*
198
-	* $request['myvar'] = 'something'; // This throws an exception.
199
-	*
200
-	* @param string $offset The key to lookup
201
-	* @return boolean
202
-	*/
203
-	public function offsetExists($offset): bool {
204
-		return isset($this->items['parameters'][$offset]);
205
-	}
206
-
207
-	/**
208
-	 * @see offsetExists
209
-	 * @param string $offset
210
-	 * @return mixed
211
-	 */
212
-	public function offsetGet($offset) {
213
-		return isset($this->items['parameters'][$offset])
214
-			? $this->items['parameters'][$offset]
215
-			: null;
216
-	}
217
-
218
-	/**
219
-	 * @see offsetExists
220
-	 * @param string $offset
221
-	 * @param mixed $value
222
-	 */
223
-	public function offsetSet($offset, $value) {
224
-		throw new \RuntimeException('You cannot change the contents of the request object');
225
-	}
226
-
227
-	/**
228
-	 * @see offsetExists
229
-	 * @param string $offset
230
-	 */
231
-	public function offsetUnset($offset) {
232
-		throw new \RuntimeException('You cannot change the contents of the request object');
233
-	}
234
-
235
-	/**
236
-	 * Magic property accessors
237
-	 * @param string $name
238
-	 * @param mixed $value
239
-	 */
240
-	public function __set($name, $value) {
241
-		throw new \RuntimeException('You cannot change the contents of the request object');
242
-	}
243
-
244
-	/**
245
-	* Access request variables by method and name.
246
-	* Examples:
247
-	*
248
-	* $request->post['myvar']; // Only look for POST variables
249
-	* $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
250
-	* Looks in the combined GET, POST and urlParams array.
251
-	*
252
-	* If you access e.g. ->post but the current HTTP request method
253
-	* is GET a \LogicException will be thrown.
254
-	*
255
-	* @param string $name The key to look for.
256
-	* @throws \LogicException
257
-	* @return mixed|null
258
-	*/
259
-	public function __get($name) {
260
-		switch($name) {
261
-			case 'put':
262
-			case 'patch':
263
-			case 'get':
264
-			case 'post':
265
-				if($this->method !== strtoupper($name)) {
266
-					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
267
-				}
268
-				return $this->getContent();
269
-			case 'files':
270
-			case 'server':
271
-			case 'env':
272
-			case 'cookies':
273
-			case 'urlParams':
274
-			case 'method':
275
-				return isset($this->items[$name])
276
-					? $this->items[$name]
277
-					: null;
278
-			case 'parameters':
279
-			case 'params':
280
-				return $this->getContent();
281
-			default;
282
-				return isset($this[$name])
283
-					? $this[$name]
284
-					: null;
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * @param string $name
290
-	 * @return bool
291
-	 */
292
-	public function __isset($name) {
293
-		if (\in_array($name, $this->allowedKeys, true)) {
294
-			return true;
295
-		}
296
-		return isset($this->items['parameters'][$name]);
297
-	}
298
-
299
-	/**
300
-	 * @param string $id
301
-	 */
302
-	public function __unset($id) {
303
-		throw new \RuntimeException('You cannot change the contents of the request object');
304
-	}
305
-
306
-	/**
307
-	 * Returns the value for a specific http header.
308
-	 *
309
-	 * This method returns null if the header did not exist.
310
-	 *
311
-	 * @param string $name
312
-	 * @return string
313
-	 */
314
-	public function getHeader(string $name): string {
315
-
316
-		$name = strtoupper(str_replace('-', '_',$name));
317
-		if (isset($this->server['HTTP_' . $name])) {
318
-			return $this->server['HTTP_' . $name];
319
-		}
320
-
321
-		// There's a few headers that seem to end up in the top-level
322
-		// server array.
323
-		switch($name) {
324
-			case 'CONTENT_TYPE' :
325
-			case 'CONTENT_LENGTH' :
326
-				if (isset($this->server[$name])) {
327
-					return $this->server[$name];
328
-				}
329
-				break;
330
-
331
-		}
332
-
333
-		return '';
334
-	}
335
-
336
-	/**
337
-	 * Lets you access post and get parameters by the index
338
-	 * In case of json requests the encoded json body is accessed
339
-	 *
340
-	 * @param string $key the key which you want to access in the URL Parameter
341
-	 *                     placeholder, $_POST or $_GET array.
342
-	 *                     The priority how they're returned is the following:
343
-	 *                     1. URL parameters
344
-	 *                     2. POST parameters
345
-	 *                     3. GET parameters
346
-	 * @param mixed $default If the key is not found, this value will be returned
347
-	 * @return mixed the content of the array
348
-	 */
349
-	public function getParam(string $key, $default = null) {
350
-		return isset($this->parameters[$key])
351
-			? $this->parameters[$key]
352
-			: $default;
353
-	}
354
-
355
-	/**
356
-	 * Returns all params that were received, be it from the request
357
-	 * (as GET or POST) or throuh the URL by the route
358
-	 * @return array the array with all parameters
359
-	 */
360
-	public function getParams(): array {
361
-		return $this->parameters;
362
-	}
363
-
364
-	/**
365
-	 * Returns the method of the request
366
-	 * @return string the method of the request (POST, GET, etc)
367
-	 */
368
-	public function getMethod(): string {
369
-		return $this->method;
370
-	}
371
-
372
-	/**
373
-	 * Shortcut for accessing an uploaded file through the $_FILES array
374
-	 * @param string $key the key that will be taken from the $_FILES array
375
-	 * @return array the file in the $_FILES element
376
-	 */
377
-	public function getUploadedFile(string $key) {
378
-		return isset($this->files[$key]) ? $this->files[$key] : null;
379
-	}
380
-
381
-	/**
382
-	 * Shortcut for getting env variables
383
-	 * @param string $key the key that will be taken from the $_ENV array
384
-	 * @return array the value in the $_ENV element
385
-	 */
386
-	public function getEnv(string $key) {
387
-		return isset($this->env[$key]) ? $this->env[$key] : null;
388
-	}
389
-
390
-	/**
391
-	 * Shortcut for getting cookie variables
392
-	 * @param string $key the key that will be taken from the $_COOKIE array
393
-	 * @return string the value in the $_COOKIE element
394
-	 */
395
-	public function getCookie(string $key) {
396
-		return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
397
-	}
398
-
399
-	/**
400
-	 * Returns the request body content.
401
-	 *
402
-	 * If the HTTP request method is PUT and the body
403
-	 * not application/x-www-form-urlencoded or application/json a stream
404
-	 * resource is returned, otherwise an array.
405
-	 *
406
-	 * @return array|string|resource The request body content or a resource to read the body stream.
407
-	 *
408
-	 * @throws \LogicException
409
-	 */
410
-	protected function getContent() {
411
-		// If the content can't be parsed into an array then return a stream resource.
412
-		if ($this->method === 'PUT'
413
-			&& $this->getHeader('Content-Length') !== '0'
414
-			&& $this->getHeader('Content-Length') !== ''
415
-			&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
416
-			&& strpos($this->getHeader('Content-Type'), 'application/json') === false
417
-		) {
418
-			if ($this->content === false) {
419
-				throw new \LogicException(
420
-					'"put" can only be accessed once if not '
421
-					. 'application/x-www-form-urlencoded or application/json.'
422
-				);
423
-			}
424
-			$this->content = false;
425
-			return fopen($this->inputStream, 'rb');
426
-		} else {
427
-			$this->decodeContent();
428
-			return $this->items['parameters'];
429
-		}
430
-	}
431
-
432
-	/**
433
-	 * Attempt to decode the content and populate parameters
434
-	 */
435
-	protected function decodeContent() {
436
-		if ($this->contentDecoded) {
437
-			return;
438
-		}
439
-		$params = [];
440
-
441
-		// 'application/json' must be decoded manually.
442
-		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
443
-			$params = json_decode(file_get_contents($this->inputStream), true);
444
-			if($params !== null && \count($params) > 0) {
445
-				$this->items['params'] = $params;
446
-				if($this->method === 'POST') {
447
-					$this->items['post'] = $params;
448
-				}
449
-			}
450
-
451
-		// Handle application/x-www-form-urlencoded for methods other than GET
452
-		// or post correctly
453
-		} elseif($this->method !== 'GET'
454
-				&& $this->method !== 'POST'
455
-				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
456
-
457
-			parse_str(file_get_contents($this->inputStream), $params);
458
-			if(\is_array($params)) {
459
-				$this->items['params'] = $params;
460
-			}
461
-		}
462
-
463
-		if (\is_array($params)) {
464
-			$this->items['parameters'] = array_merge($this->items['parameters'], $params);
465
-		}
466
-		$this->contentDecoded = true;
467
-	}
468
-
469
-
470
-	/**
471
-	 * Checks if the CSRF check was correct
472
-	 * @return bool true if CSRF check passed
473
-	 */
474
-	public function passesCSRFCheck(): bool {
475
-		if($this->csrfTokenManager === null) {
476
-			return false;
477
-		}
478
-
479
-		if(!$this->passesStrictCookieCheck()) {
480
-			return false;
481
-		}
482
-
483
-		if (isset($this->items['get']['requesttoken'])) {
484
-			$token = $this->items['get']['requesttoken'];
485
-		} elseif (isset($this->items['post']['requesttoken'])) {
486
-			$token = $this->items['post']['requesttoken'];
487
-		} elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
488
-			$token = $this->items['server']['HTTP_REQUESTTOKEN'];
489
-		} else {
490
-			//no token found.
491
-			return false;
492
-		}
493
-		$token = new CsrfToken($token);
494
-
495
-		return $this->csrfTokenManager->isTokenValid($token);
496
-	}
497
-
498
-	/**
499
-	 * Whether the cookie checks are required
500
-	 *
501
-	 * @return bool
502
-	 */
503
-	private function cookieCheckRequired(): bool {
504
-		if ($this->getHeader('OCS-APIREQUEST')) {
505
-			return false;
506
-		}
507
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
508
-			return false;
509
-		}
510
-
511
-		return true;
512
-	}
513
-
514
-	/**
515
-	 * Wrapper around session_get_cookie_params
516
-	 *
517
-	 * @return array
518
-	 */
519
-	public function getCookieParams(): array {
520
-		return session_get_cookie_params();
521
-	}
522
-
523
-	/**
524
-	 * Appends the __Host- prefix to the cookie if applicable
525
-	 *
526
-	 * @param string $name
527
-	 * @return string
528
-	 */
529
-	protected function getProtectedCookieName(string $name): string {
530
-		$cookieParams = $this->getCookieParams();
531
-		$prefix = '';
532
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
533
-			$prefix = '__Host-';
534
-		}
535
-
536
-		return $prefix.$name;
537
-	}
538
-
539
-	/**
540
-	 * Checks if the strict cookie has been sent with the request if the request
541
-	 * is including any cookies.
542
-	 *
543
-	 * @return bool
544
-	 * @since 9.1.0
545
-	 */
546
-	public function passesStrictCookieCheck(): bool {
547
-		if(!$this->cookieCheckRequired()) {
548
-			return true;
549
-		}
550
-
551
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
552
-		if($this->getCookie($cookieName) === 'true'
553
-			&& $this->passesLaxCookieCheck()) {
554
-			return true;
555
-		}
556
-		return false;
557
-	}
558
-
559
-	/**
560
-	 * Checks if the lax cookie has been sent with the request if the request
561
-	 * is including any cookies.
562
-	 *
563
-	 * @return bool
564
-	 * @since 9.1.0
565
-	 */
566
-	public function passesLaxCookieCheck(): bool {
567
-		if(!$this->cookieCheckRequired()) {
568
-			return true;
569
-		}
570
-
571
-		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
572
-		if($this->getCookie($cookieName) === 'true') {
573
-			return true;
574
-		}
575
-		return false;
576
-	}
577
-
578
-
579
-	/**
580
-	 * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
581
-	 * If `mod_unique_id` is installed this value will be taken.
582
-	 * @return string
583
-	 */
584
-	public function getId(): string {
585
-		if(isset($this->server['UNIQUE_ID'])) {
586
-			return $this->server['UNIQUE_ID'];
587
-		}
588
-
589
-		if(empty($this->requestId)) {
590
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
591
-			$this->requestId = $this->secureRandom->generate(20, $validChars);
592
-		}
593
-
594
-		return $this->requestId;
595
-	}
596
-
597
-	/**
598
-	 * Returns the remote address, if the connection came from a trusted proxy
599
-	 * and `forwarded_for_headers` has been configured then the IP address
600
-	 * specified in this header will be returned instead.
601
-	 * Do always use this instead of $_SERVER['REMOTE_ADDR']
602
-	 * @return string IP address
603
-	 */
604
-	public function getRemoteAddress(): string {
605
-		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
606
-		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
607
-
608
-		if(\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
609
-			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
610
-				'HTTP_X_FORWARDED_FOR'
611
-				// only have one default, so we cannot ship an insecure product out of the box
612
-			]);
613
-
614
-			foreach($forwardedForHeaders as $header) {
615
-				if(isset($this->server[$header])) {
616
-					foreach(explode(',', $this->server[$header]) as $IP) {
617
-						$IP = trim($IP);
618
-						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
619
-							return $IP;
620
-						}
621
-					}
622
-				}
623
-			}
624
-		}
625
-
626
-		return $remoteAddress;
627
-	}
628
-
629
-	/**
630
-	 * Check overwrite condition
631
-	 * @param string $type
632
-	 * @return bool
633
-	 */
634
-	private function isOverwriteCondition(string $type = ''): bool {
635
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
636
-		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
637
-		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
638
-		|| $type !== 'protocol';
639
-	}
640
-
641
-	/**
642
-	 * Returns the server protocol. It respects one or more reverse proxies servers
643
-	 * and load balancers
644
-	 * @return string Server protocol (http or https)
645
-	 */
646
-	public function getServerProtocol(): string {
647
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
648
-			&& $this->isOverwriteCondition('protocol')) {
649
-			return $this->config->getSystemValue('overwriteprotocol');
650
-		}
651
-
652
-		if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
653
-			if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
654
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
655
-				$proto = strtolower(trim($parts[0]));
656
-			} else {
657
-				$proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
658
-			}
659
-
660
-			// Verify that the protocol is always HTTP or HTTPS
661
-			// default to http if an invalid value is provided
662
-			return $proto === 'https' ? 'https' : 'http';
663
-		}
664
-
665
-		if (isset($this->server['HTTPS'])
666
-			&& $this->server['HTTPS'] !== null
667
-			&& $this->server['HTTPS'] !== 'off'
668
-			&& $this->server['HTTPS'] !== '') {
669
-			return 'https';
670
-		}
671
-
672
-		return 'http';
673
-	}
674
-
675
-	/**
676
-	 * Returns the used HTTP protocol.
677
-	 *
678
-	 * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
679
-	 */
680
-	public function getHttpProtocol(): string {
681
-		$claimedProtocol = $this->server['SERVER_PROTOCOL'];
682
-
683
-		if (\is_string($claimedProtocol)) {
684
-			$claimedProtocol = strtoupper($claimedProtocol);
685
-		}
686
-
687
-		$validProtocols = [
688
-			'HTTP/1.0',
689
-			'HTTP/1.1',
690
-			'HTTP/2',
691
-		];
692
-
693
-		if(\in_array($claimedProtocol, $validProtocols, true)) {
694
-			return $claimedProtocol;
695
-		}
696
-
697
-		return 'HTTP/1.1';
698
-	}
699
-
700
-	/**
701
-	 * Returns the request uri, even if the website uses one or more
702
-	 * reverse proxies
703
-	 * @return string
704
-	 */
705
-	public function getRequestUri(): string {
706
-		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
707
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
708
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
709
-		}
710
-		return $uri;
711
-	}
712
-
713
-	/**
714
-	 * Get raw PathInfo from request (not urldecoded)
715
-	 * @throws \Exception
716
-	 * @return string Path info
717
-	 */
718
-	public function getRawPathInfo(): string {
719
-		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
720
-		// remove too many leading slashes - can be caused by reverse proxy configuration
721
-		if (strpos($requestUri, '/') === 0) {
722
-			$requestUri = '/' . ltrim($requestUri, '/');
723
-		}
724
-
725
-		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
726
-
727
-		// Remove the query string from REQUEST_URI
728
-		if ($pos = strpos($requestUri, '?')) {
729
-			$requestUri = substr($requestUri, 0, $pos);
730
-		}
731
-
732
-		$scriptName = $this->server['SCRIPT_NAME'];
733
-		$pathInfo = $requestUri;
734
-
735
-		// strip off the script name's dir and file name
736
-		// FIXME: Sabre does not really belong here
737
-		list($path, $name) = \Sabre\Uri\split($scriptName);
738
-		if (!empty($path)) {
739
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
740
-				$pathInfo = substr($pathInfo, \strlen($path));
741
-			} else {
742
-				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
743
-			}
744
-		}
745
-		if ($name === null) {
746
-			$name = '';
747
-		}
748
-
749
-		if (strpos($pathInfo, '/'.$name) === 0) {
750
-			$pathInfo = substr($pathInfo, \strlen($name) + 1);
751
-		}
752
-		if ($name !== '' && strpos($pathInfo, $name) === 0) {
753
-			$pathInfo = substr($pathInfo, \strlen($name));
754
-		}
755
-		if($pathInfo === false || $pathInfo === '/'){
756
-			return '';
757
-		} else {
758
-			return $pathInfo;
759
-		}
760
-	}
761
-
762
-	/**
763
-	 * Get PathInfo from request
764
-	 * @throws \Exception
765
-	 * @return string|false Path info or false when not found
766
-	 */
767
-	public function getPathInfo() {
768
-		$pathInfo = $this->getRawPathInfo();
769
-		// following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
770
-		$pathInfo = rawurldecode($pathInfo);
771
-		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
772
-
773
-		switch($encoding) {
774
-			case 'ISO-8859-1' :
775
-				$pathInfo = utf8_encode($pathInfo);
776
-		}
777
-		// end copy
778
-
779
-		return $pathInfo;
780
-	}
781
-
782
-	/**
783
-	 * Returns the script name, even if the website uses one or more
784
-	 * reverse proxies
785
-	 * @return string the script name
786
-	 */
787
-	public function getScriptName(): string {
788
-		$name = $this->server['SCRIPT_NAME'];
789
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
790
-		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
791
-			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
792
-			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
793
-			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
794
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
795
-		}
796
-		return $name;
797
-	}
798
-
799
-	/**
800
-	 * Checks whether the user agent matches a given regex
801
-	 * @param array $agent array of agent names
802
-	 * @return bool true if at least one of the given agent matches, false otherwise
803
-	 */
804
-	public function isUserAgent(array $agent): bool {
805
-		if (!isset($this->server['HTTP_USER_AGENT'])) {
806
-			return false;
807
-		}
808
-		foreach ($agent as $regex) {
809
-			if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
810
-				return true;
811
-			}
812
-		}
813
-		return false;
814
-	}
815
-
816
-	/**
817
-	 * Returns the unverified server host from the headers without checking
818
-	 * whether it is a trusted domain
819
-	 * @return string Server host
820
-	 */
821
-	public function getInsecureServerHost(): string {
822
-		$host = 'localhost';
823
-		if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
824
-			if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
825
-				$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
826
-				$host = trim(current($parts));
827
-			} else {
828
-				$host = $this->server['HTTP_X_FORWARDED_HOST'];
829
-			}
830
-		} else {
831
-			if (isset($this->server['HTTP_HOST'])) {
832
-				$host = $this->server['HTTP_HOST'];
833
-			} else if (isset($this->server['SERVER_NAME'])) {
834
-				$host = $this->server['SERVER_NAME'];
835
-			}
836
-		}
837
-		return $host;
838
-	}
839
-
840
-
841
-	/**
842
-	 * Returns the server host from the headers, or the first configured
843
-	 * trusted domain if the host isn't in the trusted list
844
-	 * @return string Server host
845
-	 */
846
-	public function getServerHost(): string {
847
-		// overwritehost is always trusted
848
-		$host = $this->getOverwriteHost();
849
-		if ($host !== null) {
850
-			return $host;
851
-		}
852
-
853
-		// get the host from the headers
854
-		$host = $this->getInsecureServerHost();
855
-
856
-		// Verify that the host is a trusted domain if the trusted domains
857
-		// are defined
858
-		// If no trusted domain is provided the first trusted domain is returned
859
-		$trustedDomainHelper = new TrustedDomainHelper($this->config);
860
-		if ($trustedDomainHelper->isTrustedDomain($host)) {
861
-			return $host;
862
-		} else {
863
-			$trustedList = $this->config->getSystemValue('trusted_domains', []);
864
-			if(!empty($trustedList)) {
865
-				return $trustedList[0];
866
-			} else {
867
-				return '';
868
-			}
869
-		}
870
-	}
871
-
872
-	/**
873
-	 * Returns the overwritehost setting from the config if set and
874
-	 * if the overwrite condition is met
875
-	 * @return string|null overwritehost value or null if not defined or the defined condition
876
-	 * isn't met
877
-	 */
878
-	private function getOverwriteHost() {
879
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
880
-			return $this->config->getSystemValue('overwritehost');
881
-		}
882
-		return null;
883
-	}
62
+    const USER_AGENT_IE = '/(MSIE)|(Trident)/';
63
+    // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
64
+    const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/';
65
+    // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
66
+    const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
67
+    // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
68
+    const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/';
69
+    // Safari User Agent from http://www.useragentstring.com/pages/Safari/
70
+    const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
71
+    // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
72
+    const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
73
+    const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
74
+    const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
75
+
76
+    /**
77
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
78
+     */
79
+    const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
80
+    /**
81
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
82
+     */
83
+    const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
84
+    /**
85
+     * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
86
+     */
87
+    const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
88
+
89
+    protected $inputStream;
90
+    protected $content;
91
+    protected $items = [];
92
+    protected $allowedKeys = [
93
+        'get',
94
+        'post',
95
+        'files',
96
+        'server',
97
+        'env',
98
+        'cookies',
99
+        'urlParams',
100
+        'parameters',
101
+        'method',
102
+        'requesttoken',
103
+    ];
104
+    /** @var ISecureRandom */
105
+    protected $secureRandom;
106
+    /** @var IConfig */
107
+    protected $config;
108
+    /** @var string */
109
+    protected $requestId = '';
110
+    /** @var ICrypto */
111
+    protected $crypto;
112
+    /** @var CsrfTokenManager|null */
113
+    protected $csrfTokenManager;
114
+
115
+    /** @var bool */
116
+    protected $contentDecoded = false;
117
+
118
+    /**
119
+     * @param array $vars An associative array with the following optional values:
120
+     *        - array 'urlParams' the parameters which were matched from the URL
121
+     *        - array 'get' the $_GET array
122
+     *        - array|string 'post' the $_POST array or JSON string
123
+     *        - array 'files' the $_FILES array
124
+     *        - array 'server' the $_SERVER array
125
+     *        - array 'env' the $_ENV array
126
+     *        - array 'cookies' the $_COOKIE array
127
+     *        - string 'method' the request method (GET, POST etc)
128
+     *        - string|false 'requesttoken' the requesttoken or false when not available
129
+     * @param ISecureRandom $secureRandom
130
+     * @param IConfig $config
131
+     * @param CsrfTokenManager|null $csrfTokenManager
132
+     * @param string $stream
133
+     * @see http://www.php.net/manual/en/reserved.variables.php
134
+     */
135
+    public function __construct(array $vars= [],
136
+                                ISecureRandom $secureRandom = null,
137
+                                IConfig $config,
138
+                                CsrfTokenManager $csrfTokenManager = null,
139
+                                string $stream = 'php://input') {
140
+        $this->inputStream = $stream;
141
+        $this->items['params'] = [];
142
+        $this->secureRandom = $secureRandom;
143
+        $this->config = $config;
144
+        $this->csrfTokenManager = $csrfTokenManager;
145
+
146
+        if(!array_key_exists('method', $vars)) {
147
+            $vars['method'] = 'GET';
148
+        }
149
+
150
+        foreach($this->allowedKeys as $name) {
151
+            $this->items[$name] = isset($vars[$name])
152
+                ? $vars[$name]
153
+                : [];
154
+        }
155
+
156
+        $this->items['parameters'] = array_merge(
157
+            $this->items['get'],
158
+            $this->items['post'],
159
+            $this->items['urlParams'],
160
+            $this->items['params']
161
+        );
162
+
163
+    }
164
+    /**
165
+     * @param array $parameters
166
+     */
167
+    public function setUrlParameters(array $parameters) {
168
+        $this->items['urlParams'] = $parameters;
169
+        $this->items['parameters'] = array_merge(
170
+            $this->items['parameters'],
171
+            $this->items['urlParams']
172
+        );
173
+    }
174
+
175
+    /**
176
+     * Countable method
177
+     * @return int
178
+     */
179
+    public function count(): int {
180
+        return \count($this->items['parameters']);
181
+    }
182
+
183
+    /**
184
+     * ArrayAccess methods
185
+     *
186
+     * Gives access to the combined GET, POST and urlParams arrays
187
+     *
188
+     * Examples:
189
+     *
190
+     * $var = $request['myvar'];
191
+     *
192
+     * or
193
+     *
194
+     * if(!isset($request['myvar']) {
195
+     * 	// Do something
196
+     * }
197
+     *
198
+     * $request['myvar'] = 'something'; // This throws an exception.
199
+     *
200
+     * @param string $offset The key to lookup
201
+     * @return boolean
202
+     */
203
+    public function offsetExists($offset): bool {
204
+        return isset($this->items['parameters'][$offset]);
205
+    }
206
+
207
+    /**
208
+     * @see offsetExists
209
+     * @param string $offset
210
+     * @return mixed
211
+     */
212
+    public function offsetGet($offset) {
213
+        return isset($this->items['parameters'][$offset])
214
+            ? $this->items['parameters'][$offset]
215
+            : null;
216
+    }
217
+
218
+    /**
219
+     * @see offsetExists
220
+     * @param string $offset
221
+     * @param mixed $value
222
+     */
223
+    public function offsetSet($offset, $value) {
224
+        throw new \RuntimeException('You cannot change the contents of the request object');
225
+    }
226
+
227
+    /**
228
+     * @see offsetExists
229
+     * @param string $offset
230
+     */
231
+    public function offsetUnset($offset) {
232
+        throw new \RuntimeException('You cannot change the contents of the request object');
233
+    }
234
+
235
+    /**
236
+     * Magic property accessors
237
+     * @param string $name
238
+     * @param mixed $value
239
+     */
240
+    public function __set($name, $value) {
241
+        throw new \RuntimeException('You cannot change the contents of the request object');
242
+    }
243
+
244
+    /**
245
+     * Access request variables by method and name.
246
+     * Examples:
247
+     *
248
+     * $request->post['myvar']; // Only look for POST variables
249
+     * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
250
+     * Looks in the combined GET, POST and urlParams array.
251
+     *
252
+     * If you access e.g. ->post but the current HTTP request method
253
+     * is GET a \LogicException will be thrown.
254
+     *
255
+     * @param string $name The key to look for.
256
+     * @throws \LogicException
257
+     * @return mixed|null
258
+     */
259
+    public function __get($name) {
260
+        switch($name) {
261
+            case 'put':
262
+            case 'patch':
263
+            case 'get':
264
+            case 'post':
265
+                if($this->method !== strtoupper($name)) {
266
+                    throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
267
+                }
268
+                return $this->getContent();
269
+            case 'files':
270
+            case 'server':
271
+            case 'env':
272
+            case 'cookies':
273
+            case 'urlParams':
274
+            case 'method':
275
+                return isset($this->items[$name])
276
+                    ? $this->items[$name]
277
+                    : null;
278
+            case 'parameters':
279
+            case 'params':
280
+                return $this->getContent();
281
+            default;
282
+                return isset($this[$name])
283
+                    ? $this[$name]
284
+                    : null;
285
+        }
286
+    }
287
+
288
+    /**
289
+     * @param string $name
290
+     * @return bool
291
+     */
292
+    public function __isset($name) {
293
+        if (\in_array($name, $this->allowedKeys, true)) {
294
+            return true;
295
+        }
296
+        return isset($this->items['parameters'][$name]);
297
+    }
298
+
299
+    /**
300
+     * @param string $id
301
+     */
302
+    public function __unset($id) {
303
+        throw new \RuntimeException('You cannot change the contents of the request object');
304
+    }
305
+
306
+    /**
307
+     * Returns the value for a specific http header.
308
+     *
309
+     * This method returns null if the header did not exist.
310
+     *
311
+     * @param string $name
312
+     * @return string
313
+     */
314
+    public function getHeader(string $name): string {
315
+
316
+        $name = strtoupper(str_replace('-', '_',$name));
317
+        if (isset($this->server['HTTP_' . $name])) {
318
+            return $this->server['HTTP_' . $name];
319
+        }
320
+
321
+        // There's a few headers that seem to end up in the top-level
322
+        // server array.
323
+        switch($name) {
324
+            case 'CONTENT_TYPE' :
325
+            case 'CONTENT_LENGTH' :
326
+                if (isset($this->server[$name])) {
327
+                    return $this->server[$name];
328
+                }
329
+                break;
330
+
331
+        }
332
+
333
+        return '';
334
+    }
335
+
336
+    /**
337
+     * Lets you access post and get parameters by the index
338
+     * In case of json requests the encoded json body is accessed
339
+     *
340
+     * @param string $key the key which you want to access in the URL Parameter
341
+     *                     placeholder, $_POST or $_GET array.
342
+     *                     The priority how they're returned is the following:
343
+     *                     1. URL parameters
344
+     *                     2. POST parameters
345
+     *                     3. GET parameters
346
+     * @param mixed $default If the key is not found, this value will be returned
347
+     * @return mixed the content of the array
348
+     */
349
+    public function getParam(string $key, $default = null) {
350
+        return isset($this->parameters[$key])
351
+            ? $this->parameters[$key]
352
+            : $default;
353
+    }
354
+
355
+    /**
356
+     * Returns all params that were received, be it from the request
357
+     * (as GET or POST) or throuh the URL by the route
358
+     * @return array the array with all parameters
359
+     */
360
+    public function getParams(): array {
361
+        return $this->parameters;
362
+    }
363
+
364
+    /**
365
+     * Returns the method of the request
366
+     * @return string the method of the request (POST, GET, etc)
367
+     */
368
+    public function getMethod(): string {
369
+        return $this->method;
370
+    }
371
+
372
+    /**
373
+     * Shortcut for accessing an uploaded file through the $_FILES array
374
+     * @param string $key the key that will be taken from the $_FILES array
375
+     * @return array the file in the $_FILES element
376
+     */
377
+    public function getUploadedFile(string $key) {
378
+        return isset($this->files[$key]) ? $this->files[$key] : null;
379
+    }
380
+
381
+    /**
382
+     * Shortcut for getting env variables
383
+     * @param string $key the key that will be taken from the $_ENV array
384
+     * @return array the value in the $_ENV element
385
+     */
386
+    public function getEnv(string $key) {
387
+        return isset($this->env[$key]) ? $this->env[$key] : null;
388
+    }
389
+
390
+    /**
391
+     * Shortcut for getting cookie variables
392
+     * @param string $key the key that will be taken from the $_COOKIE array
393
+     * @return string the value in the $_COOKIE element
394
+     */
395
+    public function getCookie(string $key) {
396
+        return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
397
+    }
398
+
399
+    /**
400
+     * Returns the request body content.
401
+     *
402
+     * If the HTTP request method is PUT and the body
403
+     * not application/x-www-form-urlencoded or application/json a stream
404
+     * resource is returned, otherwise an array.
405
+     *
406
+     * @return array|string|resource The request body content or a resource to read the body stream.
407
+     *
408
+     * @throws \LogicException
409
+     */
410
+    protected function getContent() {
411
+        // If the content can't be parsed into an array then return a stream resource.
412
+        if ($this->method === 'PUT'
413
+            && $this->getHeader('Content-Length') !== '0'
414
+            && $this->getHeader('Content-Length') !== ''
415
+            && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
416
+            && strpos($this->getHeader('Content-Type'), 'application/json') === false
417
+        ) {
418
+            if ($this->content === false) {
419
+                throw new \LogicException(
420
+                    '"put" can only be accessed once if not '
421
+                    . 'application/x-www-form-urlencoded or application/json.'
422
+                );
423
+            }
424
+            $this->content = false;
425
+            return fopen($this->inputStream, 'rb');
426
+        } else {
427
+            $this->decodeContent();
428
+            return $this->items['parameters'];
429
+        }
430
+    }
431
+
432
+    /**
433
+     * Attempt to decode the content and populate parameters
434
+     */
435
+    protected function decodeContent() {
436
+        if ($this->contentDecoded) {
437
+            return;
438
+        }
439
+        $params = [];
440
+
441
+        // 'application/json' must be decoded manually.
442
+        if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
443
+            $params = json_decode(file_get_contents($this->inputStream), true);
444
+            if($params !== null && \count($params) > 0) {
445
+                $this->items['params'] = $params;
446
+                if($this->method === 'POST') {
447
+                    $this->items['post'] = $params;
448
+                }
449
+            }
450
+
451
+        // Handle application/x-www-form-urlencoded for methods other than GET
452
+        // or post correctly
453
+        } elseif($this->method !== 'GET'
454
+                && $this->method !== 'POST'
455
+                && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
456
+
457
+            parse_str(file_get_contents($this->inputStream), $params);
458
+            if(\is_array($params)) {
459
+                $this->items['params'] = $params;
460
+            }
461
+        }
462
+
463
+        if (\is_array($params)) {
464
+            $this->items['parameters'] = array_merge($this->items['parameters'], $params);
465
+        }
466
+        $this->contentDecoded = true;
467
+    }
468
+
469
+
470
+    /**
471
+     * Checks if the CSRF check was correct
472
+     * @return bool true if CSRF check passed
473
+     */
474
+    public function passesCSRFCheck(): bool {
475
+        if($this->csrfTokenManager === null) {
476
+            return false;
477
+        }
478
+
479
+        if(!$this->passesStrictCookieCheck()) {
480
+            return false;
481
+        }
482
+
483
+        if (isset($this->items['get']['requesttoken'])) {
484
+            $token = $this->items['get']['requesttoken'];
485
+        } elseif (isset($this->items['post']['requesttoken'])) {
486
+            $token = $this->items['post']['requesttoken'];
487
+        } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
488
+            $token = $this->items['server']['HTTP_REQUESTTOKEN'];
489
+        } else {
490
+            //no token found.
491
+            return false;
492
+        }
493
+        $token = new CsrfToken($token);
494
+
495
+        return $this->csrfTokenManager->isTokenValid($token);
496
+    }
497
+
498
+    /**
499
+     * Whether the cookie checks are required
500
+     *
501
+     * @return bool
502
+     */
503
+    private function cookieCheckRequired(): bool {
504
+        if ($this->getHeader('OCS-APIREQUEST')) {
505
+            return false;
506
+        }
507
+        if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
508
+            return false;
509
+        }
510
+
511
+        return true;
512
+    }
513
+
514
+    /**
515
+     * Wrapper around session_get_cookie_params
516
+     *
517
+     * @return array
518
+     */
519
+    public function getCookieParams(): array {
520
+        return session_get_cookie_params();
521
+    }
522
+
523
+    /**
524
+     * Appends the __Host- prefix to the cookie if applicable
525
+     *
526
+     * @param string $name
527
+     * @return string
528
+     */
529
+    protected function getProtectedCookieName(string $name): string {
530
+        $cookieParams = $this->getCookieParams();
531
+        $prefix = '';
532
+        if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
533
+            $prefix = '__Host-';
534
+        }
535
+
536
+        return $prefix.$name;
537
+    }
538
+
539
+    /**
540
+     * Checks if the strict cookie has been sent with the request if the request
541
+     * is including any cookies.
542
+     *
543
+     * @return bool
544
+     * @since 9.1.0
545
+     */
546
+    public function passesStrictCookieCheck(): bool {
547
+        if(!$this->cookieCheckRequired()) {
548
+            return true;
549
+        }
550
+
551
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
552
+        if($this->getCookie($cookieName) === 'true'
553
+            && $this->passesLaxCookieCheck()) {
554
+            return true;
555
+        }
556
+        return false;
557
+    }
558
+
559
+    /**
560
+     * Checks if the lax cookie has been sent with the request if the request
561
+     * is including any cookies.
562
+     *
563
+     * @return bool
564
+     * @since 9.1.0
565
+     */
566
+    public function passesLaxCookieCheck(): bool {
567
+        if(!$this->cookieCheckRequired()) {
568
+            return true;
569
+        }
570
+
571
+        $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
572
+        if($this->getCookie($cookieName) === 'true') {
573
+            return true;
574
+        }
575
+        return false;
576
+    }
577
+
578
+
579
+    /**
580
+     * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
581
+     * If `mod_unique_id` is installed this value will be taken.
582
+     * @return string
583
+     */
584
+    public function getId(): string {
585
+        if(isset($this->server['UNIQUE_ID'])) {
586
+            return $this->server['UNIQUE_ID'];
587
+        }
588
+
589
+        if(empty($this->requestId)) {
590
+            $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
591
+            $this->requestId = $this->secureRandom->generate(20, $validChars);
592
+        }
593
+
594
+        return $this->requestId;
595
+    }
596
+
597
+    /**
598
+     * Returns the remote address, if the connection came from a trusted proxy
599
+     * and `forwarded_for_headers` has been configured then the IP address
600
+     * specified in this header will be returned instead.
601
+     * Do always use this instead of $_SERVER['REMOTE_ADDR']
602
+     * @return string IP address
603
+     */
604
+    public function getRemoteAddress(): string {
605
+        $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
606
+        $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
607
+
608
+        if(\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
609
+            $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
610
+                'HTTP_X_FORWARDED_FOR'
611
+                // only have one default, so we cannot ship an insecure product out of the box
612
+            ]);
613
+
614
+            foreach($forwardedForHeaders as $header) {
615
+                if(isset($this->server[$header])) {
616
+                    foreach(explode(',', $this->server[$header]) as $IP) {
617
+                        $IP = trim($IP);
618
+                        if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
619
+                            return $IP;
620
+                        }
621
+                    }
622
+                }
623
+            }
624
+        }
625
+
626
+        return $remoteAddress;
627
+    }
628
+
629
+    /**
630
+     * Check overwrite condition
631
+     * @param string $type
632
+     * @return bool
633
+     */
634
+    private function isOverwriteCondition(string $type = ''): bool {
635
+        $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
636
+        $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
637
+        return $regex === '//' || preg_match($regex, $remoteAddr) === 1
638
+        || $type !== 'protocol';
639
+    }
640
+
641
+    /**
642
+     * Returns the server protocol. It respects one or more reverse proxies servers
643
+     * and load balancers
644
+     * @return string Server protocol (http or https)
645
+     */
646
+    public function getServerProtocol(): string {
647
+        if($this->config->getSystemValue('overwriteprotocol') !== ''
648
+            && $this->isOverwriteCondition('protocol')) {
649
+            return $this->config->getSystemValue('overwriteprotocol');
650
+        }
651
+
652
+        if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
653
+            if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
654
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
655
+                $proto = strtolower(trim($parts[0]));
656
+            } else {
657
+                $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
658
+            }
659
+
660
+            // Verify that the protocol is always HTTP or HTTPS
661
+            // default to http if an invalid value is provided
662
+            return $proto === 'https' ? 'https' : 'http';
663
+        }
664
+
665
+        if (isset($this->server['HTTPS'])
666
+            && $this->server['HTTPS'] !== null
667
+            && $this->server['HTTPS'] !== 'off'
668
+            && $this->server['HTTPS'] !== '') {
669
+            return 'https';
670
+        }
671
+
672
+        return 'http';
673
+    }
674
+
675
+    /**
676
+     * Returns the used HTTP protocol.
677
+     *
678
+     * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
679
+     */
680
+    public function getHttpProtocol(): string {
681
+        $claimedProtocol = $this->server['SERVER_PROTOCOL'];
682
+
683
+        if (\is_string($claimedProtocol)) {
684
+            $claimedProtocol = strtoupper($claimedProtocol);
685
+        }
686
+
687
+        $validProtocols = [
688
+            'HTTP/1.0',
689
+            'HTTP/1.1',
690
+            'HTTP/2',
691
+        ];
692
+
693
+        if(\in_array($claimedProtocol, $validProtocols, true)) {
694
+            return $claimedProtocol;
695
+        }
696
+
697
+        return 'HTTP/1.1';
698
+    }
699
+
700
+    /**
701
+     * Returns the request uri, even if the website uses one or more
702
+     * reverse proxies
703
+     * @return string
704
+     */
705
+    public function getRequestUri(): string {
706
+        $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
707
+        if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
708
+            $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
709
+        }
710
+        return $uri;
711
+    }
712
+
713
+    /**
714
+     * Get raw PathInfo from request (not urldecoded)
715
+     * @throws \Exception
716
+     * @return string Path info
717
+     */
718
+    public function getRawPathInfo(): string {
719
+        $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
720
+        // remove too many leading slashes - can be caused by reverse proxy configuration
721
+        if (strpos($requestUri, '/') === 0) {
722
+            $requestUri = '/' . ltrim($requestUri, '/');
723
+        }
724
+
725
+        $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
726
+
727
+        // Remove the query string from REQUEST_URI
728
+        if ($pos = strpos($requestUri, '?')) {
729
+            $requestUri = substr($requestUri, 0, $pos);
730
+        }
731
+
732
+        $scriptName = $this->server['SCRIPT_NAME'];
733
+        $pathInfo = $requestUri;
734
+
735
+        // strip off the script name's dir and file name
736
+        // FIXME: Sabre does not really belong here
737
+        list($path, $name) = \Sabre\Uri\split($scriptName);
738
+        if (!empty($path)) {
739
+            if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
740
+                $pathInfo = substr($pathInfo, \strlen($path));
741
+            } else {
742
+                throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
743
+            }
744
+        }
745
+        if ($name === null) {
746
+            $name = '';
747
+        }
748
+
749
+        if (strpos($pathInfo, '/'.$name) === 0) {
750
+            $pathInfo = substr($pathInfo, \strlen($name) + 1);
751
+        }
752
+        if ($name !== '' && strpos($pathInfo, $name) === 0) {
753
+            $pathInfo = substr($pathInfo, \strlen($name));
754
+        }
755
+        if($pathInfo === false || $pathInfo === '/'){
756
+            return '';
757
+        } else {
758
+            return $pathInfo;
759
+        }
760
+    }
761
+
762
+    /**
763
+     * Get PathInfo from request
764
+     * @throws \Exception
765
+     * @return string|false Path info or false when not found
766
+     */
767
+    public function getPathInfo() {
768
+        $pathInfo = $this->getRawPathInfo();
769
+        // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment
770
+        $pathInfo = rawurldecode($pathInfo);
771
+        $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
772
+
773
+        switch($encoding) {
774
+            case 'ISO-8859-1' :
775
+                $pathInfo = utf8_encode($pathInfo);
776
+        }
777
+        // end copy
778
+
779
+        return $pathInfo;
780
+    }
781
+
782
+    /**
783
+     * Returns the script name, even if the website uses one or more
784
+     * reverse proxies
785
+     * @return string the script name
786
+     */
787
+    public function getScriptName(): string {
788
+        $name = $this->server['SCRIPT_NAME'];
789
+        $overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
790
+        if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
791
+            // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
792
+            $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
793
+            $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
794
+            $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
795
+        }
796
+        return $name;
797
+    }
798
+
799
+    /**
800
+     * Checks whether the user agent matches a given regex
801
+     * @param array $agent array of agent names
802
+     * @return bool true if at least one of the given agent matches, false otherwise
803
+     */
804
+    public function isUserAgent(array $agent): bool {
805
+        if (!isset($this->server['HTTP_USER_AGENT'])) {
806
+            return false;
807
+        }
808
+        foreach ($agent as $regex) {
809
+            if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
810
+                return true;
811
+            }
812
+        }
813
+        return false;
814
+    }
815
+
816
+    /**
817
+     * Returns the unverified server host from the headers without checking
818
+     * whether it is a trusted domain
819
+     * @return string Server host
820
+     */
821
+    public function getInsecureServerHost(): string {
822
+        $host = 'localhost';
823
+        if (isset($this->server['HTTP_X_FORWARDED_HOST'])) {
824
+            if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
825
+                $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
826
+                $host = trim(current($parts));
827
+            } else {
828
+                $host = $this->server['HTTP_X_FORWARDED_HOST'];
829
+            }
830
+        } else {
831
+            if (isset($this->server['HTTP_HOST'])) {
832
+                $host = $this->server['HTTP_HOST'];
833
+            } else if (isset($this->server['SERVER_NAME'])) {
834
+                $host = $this->server['SERVER_NAME'];
835
+            }
836
+        }
837
+        return $host;
838
+    }
839
+
840
+
841
+    /**
842
+     * Returns the server host from the headers, or the first configured
843
+     * trusted domain if the host isn't in the trusted list
844
+     * @return string Server host
845
+     */
846
+    public function getServerHost(): string {
847
+        // overwritehost is always trusted
848
+        $host = $this->getOverwriteHost();
849
+        if ($host !== null) {
850
+            return $host;
851
+        }
852
+
853
+        // get the host from the headers
854
+        $host = $this->getInsecureServerHost();
855
+
856
+        // Verify that the host is a trusted domain if the trusted domains
857
+        // are defined
858
+        // If no trusted domain is provided the first trusted domain is returned
859
+        $trustedDomainHelper = new TrustedDomainHelper($this->config);
860
+        if ($trustedDomainHelper->isTrustedDomain($host)) {
861
+            return $host;
862
+        } else {
863
+            $trustedList = $this->config->getSystemValue('trusted_domains', []);
864
+            if(!empty($trustedList)) {
865
+                return $trustedList[0];
866
+            } else {
867
+                return '';
868
+            }
869
+        }
870
+    }
871
+
872
+    /**
873
+     * Returns the overwritehost setting from the config if set and
874
+     * if the overwrite condition is met
875
+     * @return string|null overwritehost value or null if not defined or the defined condition
876
+     * isn't met
877
+     */
878
+    private function getOverwriteHost() {
879
+        if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
880
+            return $this->config->getSystemValue('overwritehost');
881
+        }
882
+        return null;
883
+    }
884 884
 
885 885
 }
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -1,5 +1,5 @@  discard block
 block discarded – undo
1 1
 <?php
2
-declare(strict_types=1);
2
+declare(strict_types = 1);
3 3
 /**
4 4
  * @copyright Copyright (c) 2016, ownCloud, Inc.
5 5
  *
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 	 * @param string $stream
133 133
 	 * @see http://www.php.net/manual/en/reserved.variables.php
134 134
 	 */
135
-	public function __construct(array $vars= [],
135
+	public function __construct(array $vars = [],
136 136
 								ISecureRandom $secureRandom = null,
137 137
 								IConfig $config,
138 138
 								CsrfTokenManager $csrfTokenManager = null,
@@ -143,11 +143,11 @@  discard block
 block discarded – undo
143 143
 		$this->config = $config;
144 144
 		$this->csrfTokenManager = $csrfTokenManager;
145 145
 
146
-		if(!array_key_exists('method', $vars)) {
146
+		if (!array_key_exists('method', $vars)) {
147 147
 			$vars['method'] = 'GET';
148 148
 		}
149 149
 
150
-		foreach($this->allowedKeys as $name) {
150
+		foreach ($this->allowedKeys as $name) {
151 151
 			$this->items[$name] = isset($vars[$name])
152 152
 				? $vars[$name]
153 153
 				: [];
@@ -257,12 +257,12 @@  discard block
 block discarded – undo
257 257
 	* @return mixed|null
258 258
 	*/
259 259
 	public function __get($name) {
260
-		switch($name) {
260
+		switch ($name) {
261 261
 			case 'put':
262 262
 			case 'patch':
263 263
 			case 'get':
264 264
 			case 'post':
265
-				if($this->method !== strtoupper($name)) {
265
+				if ($this->method !== strtoupper($name)) {
266 266
 					throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
267 267
 				}
268 268
 				return $this->getContent();
@@ -313,14 +313,14 @@  discard block
 block discarded – undo
313 313
 	 */
314 314
 	public function getHeader(string $name): string {
315 315
 
316
-		$name = strtoupper(str_replace('-', '_',$name));
317
-		if (isset($this->server['HTTP_' . $name])) {
318
-			return $this->server['HTTP_' . $name];
316
+		$name = strtoupper(str_replace('-', '_', $name));
317
+		if (isset($this->server['HTTP_'.$name])) {
318
+			return $this->server['HTTP_'.$name];
319 319
 		}
320 320
 
321 321
 		// There's a few headers that seem to end up in the top-level
322 322
 		// server array.
323
-		switch($name) {
323
+		switch ($name) {
324 324
 			case 'CONTENT_TYPE' :
325 325
 			case 'CONTENT_LENGTH' :
326 326
 				if (isset($this->server[$name])) {
@@ -441,21 +441,21 @@  discard block
 block discarded – undo
441 441
 		// 'application/json' must be decoded manually.
442 442
 		if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) {
443 443
 			$params = json_decode(file_get_contents($this->inputStream), true);
444
-			if($params !== null && \count($params) > 0) {
444
+			if ($params !== null && \count($params) > 0) {
445 445
 				$this->items['params'] = $params;
446
-				if($this->method === 'POST') {
446
+				if ($this->method === 'POST') {
447 447
 					$this->items['post'] = $params;
448 448
 				}
449 449
 			}
450 450
 
451 451
 		// Handle application/x-www-form-urlencoded for methods other than GET
452 452
 		// or post correctly
453
-		} elseif($this->method !== 'GET'
453
+		} elseif ($this->method !== 'GET'
454 454
 				&& $this->method !== 'POST'
455 455
 				&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
456 456
 
457 457
 			parse_str(file_get_contents($this->inputStream), $params);
458
-			if(\is_array($params)) {
458
+			if (\is_array($params)) {
459 459
 				$this->items['params'] = $params;
460 460
 			}
461 461
 		}
@@ -472,11 +472,11 @@  discard block
 block discarded – undo
472 472
 	 * @return bool true if CSRF check passed
473 473
 	 */
474 474
 	public function passesCSRFCheck(): bool {
475
-		if($this->csrfTokenManager === null) {
475
+		if ($this->csrfTokenManager === null) {
476 476
 			return false;
477 477
 		}
478 478
 
479
-		if(!$this->passesStrictCookieCheck()) {
479
+		if (!$this->passesStrictCookieCheck()) {
480 480
 			return false;
481 481
 		}
482 482
 
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 		if ($this->getHeader('OCS-APIREQUEST')) {
505 505
 			return false;
506 506
 		}
507
-		if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
507
+		if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
508 508
 			return false;
509 509
 		}
510 510
 
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 	protected function getProtectedCookieName(string $name): string {
530 530
 		$cookieParams = $this->getCookieParams();
531 531
 		$prefix = '';
532
-		if($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
532
+		if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
533 533
 			$prefix = '__Host-';
534 534
 		}
535 535
 
@@ -544,12 +544,12 @@  discard block
 block discarded – undo
544 544
 	 * @since 9.1.0
545 545
 	 */
546 546
 	public function passesStrictCookieCheck(): bool {
547
-		if(!$this->cookieCheckRequired()) {
547
+		if (!$this->cookieCheckRequired()) {
548 548
 			return true;
549 549
 		}
550 550
 
551 551
 		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
552
-		if($this->getCookie($cookieName) === 'true'
552
+		if ($this->getCookie($cookieName) === 'true'
553 553
 			&& $this->passesLaxCookieCheck()) {
554 554
 			return true;
555 555
 		}
@@ -564,12 +564,12 @@  discard block
 block discarded – undo
564 564
 	 * @since 9.1.0
565 565
 	 */
566 566
 	public function passesLaxCookieCheck(): bool {
567
-		if(!$this->cookieCheckRequired()) {
567
+		if (!$this->cookieCheckRequired()) {
568 568
 			return true;
569 569
 		}
570 570
 
571 571
 		$cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
572
-		if($this->getCookie($cookieName) === 'true') {
572
+		if ($this->getCookie($cookieName) === 'true') {
573 573
 			return true;
574 574
 		}
575 575
 		return false;
@@ -582,12 +582,12 @@  discard block
 block discarded – undo
582 582
 	 * @return string
583 583
 	 */
584 584
 	public function getId(): string {
585
-		if(isset($this->server['UNIQUE_ID'])) {
585
+		if (isset($this->server['UNIQUE_ID'])) {
586 586
 			return $this->server['UNIQUE_ID'];
587 587
 		}
588 588
 
589
-		if(empty($this->requestId)) {
590
-			$validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS;
589
+		if (empty($this->requestId)) {
590
+			$validChars = ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_DIGITS;
591 591
 			$this->requestId = $this->secureRandom->generate(20, $validChars);
592 592
 		}
593 593
 
@@ -605,15 +605,15 @@  discard block
 block discarded – undo
605 605
 		$remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
606 606
 		$trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
607 607
 
608
-		if(\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
608
+		if (\is_array($trustedProxies) && \in_array($remoteAddress, $trustedProxies)) {
609 609
 			$forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
610 610
 				'HTTP_X_FORWARDED_FOR'
611 611
 				// only have one default, so we cannot ship an insecure product out of the box
612 612
 			]);
613 613
 
614
-			foreach($forwardedForHeaders as $header) {
615
-				if(isset($this->server[$header])) {
616
-					foreach(explode(',', $this->server[$header]) as $IP) {
614
+			foreach ($forwardedForHeaders as $header) {
615
+				if (isset($this->server[$header])) {
616
+					foreach (explode(',', $this->server[$header]) as $IP) {
617 617
 						$IP = trim($IP);
618 618
 						if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
619 619
 							return $IP;
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
 	 * @return bool
633 633
 	 */
634 634
 	private function isOverwriteCondition(string $type = ''): bool {
635
-		$regex = '/' . $this->config->getSystemValue('overwritecondaddr', '')  . '/';
635
+		$regex = '/'.$this->config->getSystemValue('overwritecondaddr', '').'/';
636 636
 		$remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
637 637
 		return $regex === '//' || preg_match($regex, $remoteAddr) === 1
638 638
 		|| $type !== 'protocol';
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
 	 * @return string Server protocol (http or https)
645 645
 	 */
646 646
 	public function getServerProtocol(): string {
647
-		if($this->config->getSystemValue('overwriteprotocol') !== ''
647
+		if ($this->config->getSystemValue('overwriteprotocol') !== ''
648 648
 			&& $this->isOverwriteCondition('protocol')) {
649 649
 			return $this->config->getSystemValue('overwriteprotocol');
650 650
 		}
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 			'HTTP/2',
691 691
 		];
692 692
 
693
-		if(\in_array($claimedProtocol, $validProtocols, true)) {
693
+		if (\in_array($claimedProtocol, $validProtocols, true)) {
694 694
 			return $claimedProtocol;
695 695
 		}
696 696
 
@@ -704,8 +704,8 @@  discard block
 block discarded – undo
704 704
 	 */
705 705
 	public function getRequestUri(): string {
706 706
 		$uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
707
-		if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
708
-			$uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
707
+		if ($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
708
+			$uri = $this->getScriptName().substr($uri, \strlen($this->server['SCRIPT_NAME']));
709 709
 		}
710 710
 		return $uri;
711 711
 	}
@@ -719,7 +719,7 @@  discard block
 block discarded – undo
719 719
 		$requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
720 720
 		// remove too many leading slashes - can be caused by reverse proxy configuration
721 721
 		if (strpos($requestUri, '/') === 0) {
722
-			$requestUri = '/' . ltrim($requestUri, '/');
722
+			$requestUri = '/'.ltrim($requestUri, '/');
723 723
 		}
724 724
 
725 725
 		$requestUri = preg_replace('%/{2,}%', '/', $requestUri);
@@ -736,7 +736,7 @@  discard block
 block discarded – undo
736 736
 		// FIXME: Sabre does not really belong here
737 737
 		list($path, $name) = \Sabre\Uri\split($scriptName);
738 738
 		if (!empty($path)) {
739
-			if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
739
+			if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
740 740
 				$pathInfo = substr($pathInfo, \strlen($path));
741 741
 			} else {
742 742
 				throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
@@ -752,7 +752,7 @@  discard block
 block discarded – undo
752 752
 		if ($name !== '' && strpos($pathInfo, $name) === 0) {
753 753
 			$pathInfo = substr($pathInfo, \strlen($name));
754 754
 		}
755
-		if($pathInfo === false || $pathInfo === '/'){
755
+		if ($pathInfo === false || $pathInfo === '/') {
756 756
 			return '';
757 757
 		} else {
758 758
 			return $pathInfo;
@@ -770,7 +770,7 @@  discard block
 block discarded – undo
770 770
 		$pathInfo = rawurldecode($pathInfo);
771 771
 		$encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']);
772 772
 
773
-		switch($encoding) {
773
+		switch ($encoding) {
774 774
 			case 'ISO-8859-1' :
775 775
 				$pathInfo = utf8_encode($pathInfo);
776 776
 		}
@@ -786,12 +786,12 @@  discard block
 block discarded – undo
786 786
 	 */
787 787
 	public function getScriptName(): string {
788 788
 		$name = $this->server['SCRIPT_NAME'];
789
-		$overwriteWebRoot =  $this->config->getSystemValue('overwritewebroot');
789
+		$overwriteWebRoot = $this->config->getSystemValue('overwritewebroot');
790 790
 		if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
791 791
 			// FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
792 792
 			$serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
793 793
 			$suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
794
-			$name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
794
+			$name = '/'.ltrim($overwriteWebRoot.$suburi, '/');
795 795
 		}
796 796
 		return $name;
797 797
 	}
@@ -861,7 +861,7 @@  discard block
 block discarded – undo
861 861
 			return $host;
862 862
 		} else {
863 863
 			$trustedList = $this->config->getSystemValue('trusted_domains', []);
864
-			if(!empty($trustedList)) {
864
+			if (!empty($trustedList)) {
865 865
 				return $trustedList[0];
866 866
 			} else {
867 867
 				return '';
@@ -876,7 +876,7 @@  discard block
 block discarded – undo
876 876
 	 * isn't met
877 877
 	 */
878 878
 	private function getOverwriteHost() {
879
-		if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
879
+		if ($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
880 880
 			return $this->config->getSystemValue('overwritehost');
881 881
 		}
882 882
 		return null;
Please login to merge, or discard this patch.