Completed
Pull Request — master (#9895)
by Björn
107:05 queued 87:50
created
lib/private/Share/Constants.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -29,27 +29,27 @@
 block discarded – undo
29 29
 
30 30
 class Constants {
31 31
 
32
-	const SHARE_TYPE_USER = 0;
33
-	const SHARE_TYPE_GROUP = 1;
34
-	const SHARE_TYPE_LINK = 3;
35
-	const SHARE_TYPE_EMAIL = 4;
36
-	const SHARE_TYPE_CONTACT = 5; // ToDo Check if it is still in use otherwise remove it
37
-	const SHARE_TYPE_REMOTE = 6;
38
-	const SHARE_TYPE_CIRCLE = 7;
39
-	const SHARE_TYPE_GUEST = 8;
40
-	const SHARE_TYPE_REMOTE_GROUP = 9;
32
+    const SHARE_TYPE_USER = 0;
33
+    const SHARE_TYPE_GROUP = 1;
34
+    const SHARE_TYPE_LINK = 3;
35
+    const SHARE_TYPE_EMAIL = 4;
36
+    const SHARE_TYPE_CONTACT = 5; // ToDo Check if it is still in use otherwise remove it
37
+    const SHARE_TYPE_REMOTE = 6;
38
+    const SHARE_TYPE_CIRCLE = 7;
39
+    const SHARE_TYPE_GUEST = 8;
40
+    const SHARE_TYPE_REMOTE_GROUP = 9;
41 41
 
42
-	const FORMAT_NONE = -1;
43
-	const FORMAT_STATUSES = -2;
44
-	const FORMAT_SOURCES = -3;  // ToDo Check if it is still in use otherwise remove it
42
+    const FORMAT_NONE = -1;
43
+    const FORMAT_STATUSES = -2;
44
+    const FORMAT_SOURCES = -3;  // ToDo Check if it is still in use otherwise remove it
45 45
 
46
-	const RESPONSE_FORMAT = 'json'; // default resonse format for ocs calls
46
+    const RESPONSE_FORMAT = 'json'; // default resonse format for ocs calls
47 47
 
48
-	const TOKEN_LENGTH = 15; // old (oc7) length is 32, keep token length in db at least that for compatibility
48
+    const TOKEN_LENGTH = 15; // old (oc7) length is 32, keep token length in db at least that for compatibility
49 49
 
50
-	protected static $shareTypeUserAndGroups = -1;
51
-	protected static $shareTypeGroupUserUnique = 2;
52
-	protected static $backends = array();
53
-	protected static $backendTypes = array();
54
-	protected static $isResharingAllowed;
50
+    protected static $shareTypeUserAndGroups = -1;
51
+    protected static $shareTypeGroupUserUnique = 2;
52
+    protected static $backends = array();
53
+    protected static $backendTypes = array();
54
+    protected static $isResharingAllowed;
55 55
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Manager.php 1 patch
Indentation   +476 added lines, -476 removed lines patch added patch discarded remove patch
@@ -44,520 +44,520 @@
 block discarded – undo
44 44
 use OCP\Share;
45 45
 
46 46
 class Manager {
47
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
-
49
-	/**
50
-	 * @var string
51
-	 */
52
-	private $uid;
53
-
54
-	/**
55
-	 * @var IDBConnection
56
-	 */
57
-	private $connection;
58
-
59
-	/**
60
-	 * @var \OC\Files\Mount\Manager
61
-	 */
62
-	private $mountManager;
63
-
64
-	/**
65
-	 * @var IStorageFactory
66
-	 */
67
-	private $storageLoader;
68
-
69
-	/**
70
-	 * @var IClientService
71
-	 */
72
-	private $clientService;
73
-
74
-	/**
75
-	 * @var IManager
76
-	 */
77
-	private $notificationManager;
78
-
79
-	/**
80
-	 * @var IDiscoveryService
81
-	 */
82
-	private $discoveryService;
83
-
84
-	/** @var ICloudFederationProviderManager */
85
-	private $cloudFederationProviderManager;
86
-
87
-	/** @var ICloudFederationFactory */
88
-	private $cloudFederationFactory;
89
-
90
-	/**
91
-	 * @param IDBConnection $connection
92
-	 * @param \OC\Files\Mount\Manager $mountManager
93
-	 * @param IStorageFactory $storageLoader
94
-	 * @param IClientService $clientService
95
-	 * @param IManager $notificationManager
96
-	 * @param IDiscoveryService $discoveryService
97
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
-	 * @param ICloudFederationFactory $cloudFederationFactory
99
-	 * @param string $uid
100
-	 */
101
-	public function __construct(IDBConnection $connection,
102
-								\OC\Files\Mount\Manager $mountManager,
103
-								IStorageFactory $storageLoader,
104
-								IClientService $clientService,
105
-								IManager $notificationManager,
106
-								IDiscoveryService $discoveryService,
107
-								ICloudFederationProviderManager $cloudFederationProviderManager,
108
-								ICloudFederationFactory $cloudFederationFactory,
109
-								$uid) {
110
-		$this->connection = $connection;
111
-		$this->mountManager = $mountManager;
112
-		$this->storageLoader = $storageLoader;
113
-		$this->clientService = $clientService;
114
-		$this->uid = $uid;
115
-		$this->notificationManager = $notificationManager;
116
-		$this->discoveryService = $discoveryService;
117
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
-		$this->cloudFederationFactory = $cloudFederationFactory;
119
-	}
120
-
121
-	/**
122
-	 * add new server-to-server share
123
-	 *
124
-	 * @param string $remote
125
-	 * @param string $token
126
-	 * @param string $password
127
-	 * @param string $name
128
-	 * @param string $owner
129
-	 * @param int $shareType
130
-	 * @param boolean $accepted
131
-	 * @param string $user
132
-	 * @param int $remoteId
133
-	 * @param int $parent
134
-	 * @return Mount|null
135
-	 * @throws \Doctrine\DBAL\DBALException
136
-	 */
137
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
138
-
139
-		$user = $user ? $user : $this->uid;
140
-		$accepted = $accepted ? 1 : 0;
141
-		$name = Filesystem::normalizePath('/' . $name);
142
-
143
-		if (!$accepted) {
144
-			// To avoid conflicts with the mount point generation later,
145
-			// we only use a temporary mount point name here. The real
146
-			// mount point name will be generated when accepting the share,
147
-			// using the original share item name.
148
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
149
-			$mountPoint = $tmpMountPointName;
150
-			$hash = md5($tmpMountPointName);
151
-			$data = [
152
-				'remote'		=> $remote,
153
-				'share_token'	=> $token,
154
-				'password'		=> $password,
155
-				'name'			=> $name,
156
-				'owner'			=> $owner,
157
-				'user'			=> $user,
158
-				'mountpoint'	=> $mountPoint,
159
-				'mountpoint_hash'	=> $hash,
160
-				'accepted'		=> $accepted,
161
-				'remote_id'		=> $remoteId,
162
-				'share_type'    => $shareType,
163
-			];
164
-
165
-			$i = 1;
166
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
167
-				// The external share already exists for the user
168
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
169
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
170
-				$i++;
171
-			}
172
-			return null;
173
-		}
174
-
175
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
176
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
177
-		$hash = md5($mountPoint);
178
-
179
-		$query = $this->connection->prepare('
47
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
48
+
49
+    /**
50
+     * @var string
51
+     */
52
+    private $uid;
53
+
54
+    /**
55
+     * @var IDBConnection
56
+     */
57
+    private $connection;
58
+
59
+    /**
60
+     * @var \OC\Files\Mount\Manager
61
+     */
62
+    private $mountManager;
63
+
64
+    /**
65
+     * @var IStorageFactory
66
+     */
67
+    private $storageLoader;
68
+
69
+    /**
70
+     * @var IClientService
71
+     */
72
+    private $clientService;
73
+
74
+    /**
75
+     * @var IManager
76
+     */
77
+    private $notificationManager;
78
+
79
+    /**
80
+     * @var IDiscoveryService
81
+     */
82
+    private $discoveryService;
83
+
84
+    /** @var ICloudFederationProviderManager */
85
+    private $cloudFederationProviderManager;
86
+
87
+    /** @var ICloudFederationFactory */
88
+    private $cloudFederationFactory;
89
+
90
+    /**
91
+     * @param IDBConnection $connection
92
+     * @param \OC\Files\Mount\Manager $mountManager
93
+     * @param IStorageFactory $storageLoader
94
+     * @param IClientService $clientService
95
+     * @param IManager $notificationManager
96
+     * @param IDiscoveryService $discoveryService
97
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
98
+     * @param ICloudFederationFactory $cloudFederationFactory
99
+     * @param string $uid
100
+     */
101
+    public function __construct(IDBConnection $connection,
102
+                                \OC\Files\Mount\Manager $mountManager,
103
+                                IStorageFactory $storageLoader,
104
+                                IClientService $clientService,
105
+                                IManager $notificationManager,
106
+                                IDiscoveryService $discoveryService,
107
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
108
+                                ICloudFederationFactory $cloudFederationFactory,
109
+                                $uid) {
110
+        $this->connection = $connection;
111
+        $this->mountManager = $mountManager;
112
+        $this->storageLoader = $storageLoader;
113
+        $this->clientService = $clientService;
114
+        $this->uid = $uid;
115
+        $this->notificationManager = $notificationManager;
116
+        $this->discoveryService = $discoveryService;
117
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
118
+        $this->cloudFederationFactory = $cloudFederationFactory;
119
+    }
120
+
121
+    /**
122
+     * add new server-to-server share
123
+     *
124
+     * @param string $remote
125
+     * @param string $token
126
+     * @param string $password
127
+     * @param string $name
128
+     * @param string $owner
129
+     * @param int $shareType
130
+     * @param boolean $accepted
131
+     * @param string $user
132
+     * @param int $remoteId
133
+     * @param int $parent
134
+     * @return Mount|null
135
+     * @throws \Doctrine\DBAL\DBALException
136
+     */
137
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
138
+
139
+        $user = $user ? $user : $this->uid;
140
+        $accepted = $accepted ? 1 : 0;
141
+        $name = Filesystem::normalizePath('/' . $name);
142
+
143
+        if (!$accepted) {
144
+            // To avoid conflicts with the mount point generation later,
145
+            // we only use a temporary mount point name here. The real
146
+            // mount point name will be generated when accepting the share,
147
+            // using the original share item name.
148
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
149
+            $mountPoint = $tmpMountPointName;
150
+            $hash = md5($tmpMountPointName);
151
+            $data = [
152
+                'remote'		=> $remote,
153
+                'share_token'	=> $token,
154
+                'password'		=> $password,
155
+                'name'			=> $name,
156
+                'owner'			=> $owner,
157
+                'user'			=> $user,
158
+                'mountpoint'	=> $mountPoint,
159
+                'mountpoint_hash'	=> $hash,
160
+                'accepted'		=> $accepted,
161
+                'remote_id'		=> $remoteId,
162
+                'share_type'    => $shareType,
163
+            ];
164
+
165
+            $i = 1;
166
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
167
+                // The external share already exists for the user
168
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
169
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
170
+                $i++;
171
+            }
172
+            return null;
173
+        }
174
+
175
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
176
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
177
+        $hash = md5($mountPoint);
178
+
179
+        $query = $this->connection->prepare('
180 180
 				INSERT INTO `*PREFIX*share_external`
181 181
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
182 182
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
183 183
 			');
184
-		$query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
185
-
186
-		$options = array(
187
-			'remote'	=> $remote,
188
-			'token'		=> $token,
189
-			'password'	=> $password,
190
-			'mountpoint'	=> $mountPoint,
191
-			'owner'		=> $owner
192
-		);
193
-		return $this->mountShare($options);
194
-	}
195
-
196
-	/**
197
-	 * get share
198
-	 *
199
-	 * @param int $id share id
200
-	 * @return mixed share of false
201
-	 */
202
-	public function getShare($id) {
203
-		$getShare = $this->connection->prepare('
184
+        $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
185
+
186
+        $options = array(
187
+            'remote'	=> $remote,
188
+            'token'		=> $token,
189
+            'password'	=> $password,
190
+            'mountpoint'	=> $mountPoint,
191
+            'owner'		=> $owner
192
+        );
193
+        return $this->mountShare($options);
194
+    }
195
+
196
+    /**
197
+     * get share
198
+     *
199
+     * @param int $id share id
200
+     * @return mixed share of false
201
+     */
202
+    public function getShare($id) {
203
+        $getShare = $this->connection->prepare('
204 204
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
205 205
 			FROM  `*PREFIX*share_external`
206 206
 			WHERE `id` = ? AND `user` = ?');
207
-		$result = $getShare->execute(array($id, $this->uid));
208
-
209
-		return $result ? $getShare->fetch() : false;
210
-	}
211
-
212
-	/**
213
-	 * accept server-to-server share
214
-	 *
215
-	 * @param int $id
216
-	 * @return bool True if the share could be accepted, false otherwise
217
-	 */
218
-	public function acceptShare($id) {
219
-
220
-		$share = $this->getShare($id);
221
-		$result = false;
222
-
223
-		if ($share) {
224
-			\OC_Util::setupFS($this->uid);
225
-			$shareFolder = Helper::getShareFolder();
226
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
227
-			$mountPoint = Filesystem::normalizePath($mountPoint);
228
-			$hash = md5($mountPoint);
229
-
230
-			if($share['share_type'] === \OCP\Share::SHARE_TYPE_USER) {
231
-				$acceptShare = $this->connection->prepare('
207
+        $result = $getShare->execute(array($id, $this->uid));
208
+
209
+        return $result ? $getShare->fetch() : false;
210
+    }
211
+
212
+    /**
213
+     * accept server-to-server share
214
+     *
215
+     * @param int $id
216
+     * @return bool True if the share could be accepted, false otherwise
217
+     */
218
+    public function acceptShare($id) {
219
+
220
+        $share = $this->getShare($id);
221
+        $result = false;
222
+
223
+        if ($share) {
224
+            \OC_Util::setupFS($this->uid);
225
+            $shareFolder = Helper::getShareFolder();
226
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
227
+            $mountPoint = Filesystem::normalizePath($mountPoint);
228
+            $hash = md5($mountPoint);
229
+
230
+            if($share['share_type'] === \OCP\Share::SHARE_TYPE_USER) {
231
+                $acceptShare = $this->connection->prepare('
232 232
 				UPDATE `*PREFIX*share_external`
233 233
 				SET `accepted` = ?,
234 234
 					`mountpoint` = ?,
235 235
 					`mountpoint_hash` = ?
236 236
 				WHERE `id` = ? AND `user` = ?');
237
-				$updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
238
-			} else {
239
-				// TODO group share, add additional row for the user who accepted it
240
-			}
241
-			if ($updated === true) {
242
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
243
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
244
-				$result = true;
245
-			}
246
-		}
247
-
248
-		// Make sure the user has no notification for something that does not exist anymore.
249
-		$this->processNotification($id);
250
-
251
-		return $result;
252
-	}
253
-
254
-	/**
255
-	 * decline server-to-server share
256
-	 *
257
-	 * @param int $id
258
-	 * @return bool True if the share could be declined, false otherwise
259
-	 */
260
-	public function declineShare($id) {
261
-
262
-		$share = $this->getShare($id);
263
-
264
-		if ($share) {
265
-			$removeShare = $this->connection->prepare('
237
+                $updated = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
238
+            } else {
239
+                // TODO group share, add additional row for the user who accepted it
240
+            }
241
+            if ($updated === true) {
242
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
243
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
244
+                $result = true;
245
+            }
246
+        }
247
+
248
+        // Make sure the user has no notification for something that does not exist anymore.
249
+        $this->processNotification($id);
250
+
251
+        return $result;
252
+    }
253
+
254
+    /**
255
+     * decline server-to-server share
256
+     *
257
+     * @param int $id
258
+     * @return bool True if the share could be declined, false otherwise
259
+     */
260
+    public function declineShare($id) {
261
+
262
+        $share = $this->getShare($id);
263
+
264
+        if ($share) {
265
+            $removeShare = $this->connection->prepare('
266 266
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
267
-			$removeShare->execute(array($id, $this->uid));
268
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
269
-
270
-			$this->processNotification($id);
271
-			return true;
272
-		}
273
-
274
-		return false;
275
-	}
276
-
277
-	/**
278
-	 * @param int $remoteShare
279
-	 */
280
-	public function processNotification($remoteShare) {
281
-		$filter = $this->notificationManager->createNotification();
282
-		$filter->setApp('files_sharing')
283
-			->setUser($this->uid)
284
-			->setObject('remote_share', (int) $remoteShare);
285
-		$this->notificationManager->markProcessed($filter);
286
-	}
287
-
288
-	/**
289
-	 * inform remote server whether server-to-server share was accepted/declined
290
-	 *
291
-	 * @param string $remote
292
-	 * @param string $token
293
-	 * @param int $remoteId Share id on the remote host
294
-	 * @param string $feedback
295
-	 * @return boolean
296
-	 */
297
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
298
-
299
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
300
-
301
-		if($result === true) {
302
-			return true;
303
-		}
304
-
305
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
306
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
307
-
308
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
309
-		$fields = array('token' => $token);
310
-
311
-		$client = $this->clientService->newClient();
312
-
313
-		try {
314
-			$response = $client->post(
315
-				$url,
316
-				[
317
-					'body' => $fields,
318
-					'connect_timeout' => 10,
319
-				]
320
-			);
321
-		} catch (\Exception $e) {
322
-			return false;
323
-		}
324
-
325
-		$status = json_decode($response->getBody(), true);
326
-
327
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
328
-	}
329
-
330
-	/**
331
-	 * try send accept message to ocm end-point
332
-	 *
333
-	 * @param string $remoteDomain
334
-	 * @param string $token
335
-	 * @param $remoteId id of the share
336
-	 * @param string $feedback
337
-	 * @return bool
338
-	 */
339
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
340
-		switch ($feedback) {
341
-			case 'accept':
342
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
343
-				$notification->setMessage(
344
-					'SHARE_ACCEPTED',
345
-					'file',
346
-					$remoteId,
347
-					[
348
-						'sharedSecret' => $token,
349
-						'message' => 'Recipient accept the share'
350
-					]
351
-
352
-				);
353
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
354
-			case 'decline':
355
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
356
-				$notification->setMessage(
357
-					'SHARE_DECLINED',
358
-					'file',
359
-					$remoteId,
360
-					[
361
-						'sharedSecret' => $token,
362
-						'message' => 'Recipient declined the share'
363
-					]
364
-
365
-				);
366
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
367
-		}
368
-
369
-		return false;
370
-
371
-	}
372
-
373
-
374
-	/**
375
-	 * remove '/user/files' from the path and trailing slashes
376
-	 *
377
-	 * @param string $path
378
-	 * @return string
379
-	 */
380
-	protected function stripPath($path) {
381
-		$prefix = '/' . $this->uid . '/files';
382
-		return rtrim(substr($path, strlen($prefix)), '/');
383
-	}
384
-
385
-	public function getMount($data) {
386
-		$data['manager'] = $this;
387
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
388
-		$data['mountpoint'] = $mountPoint;
389
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
390
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
391
-	}
392
-
393
-	/**
394
-	 * @param array $data
395
-	 * @return Mount
396
-	 */
397
-	protected function mountShare($data) {
398
-		$mount = $this->getMount($data);
399
-		$this->mountManager->addMount($mount);
400
-		return $mount;
401
-	}
402
-
403
-	/**
404
-	 * @return \OC\Files\Mount\Manager
405
-	 */
406
-	public function getMountManager() {
407
-		return $this->mountManager;
408
-	}
409
-
410
-	/**
411
-	 * @param string $source
412
-	 * @param string $target
413
-	 * @return bool
414
-	 */
415
-	public function setMountPoint($source, $target) {
416
-		$source = $this->stripPath($source);
417
-		$target = $this->stripPath($target);
418
-		$sourceHash = md5($source);
419
-		$targetHash = md5($target);
420
-
421
-		$query = $this->connection->prepare('
267
+            $removeShare->execute(array($id, $this->uid));
268
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
269
+
270
+            $this->processNotification($id);
271
+            return true;
272
+        }
273
+
274
+        return false;
275
+    }
276
+
277
+    /**
278
+     * @param int $remoteShare
279
+     */
280
+    public function processNotification($remoteShare) {
281
+        $filter = $this->notificationManager->createNotification();
282
+        $filter->setApp('files_sharing')
283
+            ->setUser($this->uid)
284
+            ->setObject('remote_share', (int) $remoteShare);
285
+        $this->notificationManager->markProcessed($filter);
286
+    }
287
+
288
+    /**
289
+     * inform remote server whether server-to-server share was accepted/declined
290
+     *
291
+     * @param string $remote
292
+     * @param string $token
293
+     * @param int $remoteId Share id on the remote host
294
+     * @param string $feedback
295
+     * @return boolean
296
+     */
297
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
298
+
299
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
300
+
301
+        if($result === true) {
302
+            return true;
303
+        }
304
+
305
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
306
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
307
+
308
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . \OCP\Share::RESPONSE_FORMAT;
309
+        $fields = array('token' => $token);
310
+
311
+        $client = $this->clientService->newClient();
312
+
313
+        try {
314
+            $response = $client->post(
315
+                $url,
316
+                [
317
+                    'body' => $fields,
318
+                    'connect_timeout' => 10,
319
+                ]
320
+            );
321
+        } catch (\Exception $e) {
322
+            return false;
323
+        }
324
+
325
+        $status = json_decode($response->getBody(), true);
326
+
327
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
328
+    }
329
+
330
+    /**
331
+     * try send accept message to ocm end-point
332
+     *
333
+     * @param string $remoteDomain
334
+     * @param string $token
335
+     * @param $remoteId id of the share
336
+     * @param string $feedback
337
+     * @return bool
338
+     */
339
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
340
+        switch ($feedback) {
341
+            case 'accept':
342
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
343
+                $notification->setMessage(
344
+                    'SHARE_ACCEPTED',
345
+                    'file',
346
+                    $remoteId,
347
+                    [
348
+                        'sharedSecret' => $token,
349
+                        'message' => 'Recipient accept the share'
350
+                    ]
351
+
352
+                );
353
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
354
+            case 'decline':
355
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
356
+                $notification->setMessage(
357
+                    'SHARE_DECLINED',
358
+                    'file',
359
+                    $remoteId,
360
+                    [
361
+                        'sharedSecret' => $token,
362
+                        'message' => 'Recipient declined the share'
363
+                    ]
364
+
365
+                );
366
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
367
+        }
368
+
369
+        return false;
370
+
371
+    }
372
+
373
+
374
+    /**
375
+     * remove '/user/files' from the path and trailing slashes
376
+     *
377
+     * @param string $path
378
+     * @return string
379
+     */
380
+    protected function stripPath($path) {
381
+        $prefix = '/' . $this->uid . '/files';
382
+        return rtrim(substr($path, strlen($prefix)), '/');
383
+    }
384
+
385
+    public function getMount($data) {
386
+        $data['manager'] = $this;
387
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
388
+        $data['mountpoint'] = $mountPoint;
389
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
390
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
391
+    }
392
+
393
+    /**
394
+     * @param array $data
395
+     * @return Mount
396
+     */
397
+    protected function mountShare($data) {
398
+        $mount = $this->getMount($data);
399
+        $this->mountManager->addMount($mount);
400
+        return $mount;
401
+    }
402
+
403
+    /**
404
+     * @return \OC\Files\Mount\Manager
405
+     */
406
+    public function getMountManager() {
407
+        return $this->mountManager;
408
+    }
409
+
410
+    /**
411
+     * @param string $source
412
+     * @param string $target
413
+     * @return bool
414
+     */
415
+    public function setMountPoint($source, $target) {
416
+        $source = $this->stripPath($source);
417
+        $target = $this->stripPath($target);
418
+        $sourceHash = md5($source);
419
+        $targetHash = md5($target);
420
+
421
+        $query = $this->connection->prepare('
422 422
 			UPDATE `*PREFIX*share_external`
423 423
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
424 424
 			WHERE `mountpoint_hash` = ?
425 425
 			AND `user` = ?
426 426
 		');
427
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
427
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
428 428
 
429
-		return $result;
430
-	}
429
+        return $result;
430
+    }
431 431
 
432
-	public function removeShare($mountPoint) {
432
+    public function removeShare($mountPoint) {
433 433
 
434
-		$mountPointObj = $this->mountManager->find($mountPoint);
435
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
434
+        $mountPointObj = $this->mountManager->find($mountPoint);
435
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
436 436
 
437
-		$mountPoint = $this->stripPath($mountPoint);
438
-		$hash = md5($mountPoint);
437
+        $mountPoint = $this->stripPath($mountPoint);
438
+        $hash = md5($mountPoint);
439 439
 
440
-		$getShare = $this->connection->prepare('
440
+        $getShare = $this->connection->prepare('
441 441
 			SELECT `remote`, `share_token`, `remote_id`
442 442
 			FROM  `*PREFIX*share_external`
443 443
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
444
-		$result = $getShare->execute(array($hash, $this->uid));
445
-
446
-		if ($result) {
447
-			try {
448
-				$share = $getShare->fetch();
449
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
450
-			} catch (\Exception $e) {
451
-				// if we fail to notify the remote (probably cause the remote is down)
452
-				// we still want the share to be gone to prevent undeletable remotes
453
-			}
454
-		}
455
-		$getShare->closeCursor();
456
-
457
-		$query = $this->connection->prepare('
444
+        $result = $getShare->execute(array($hash, $this->uid));
445
+
446
+        if ($result) {
447
+            try {
448
+                $share = $getShare->fetch();
449
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
450
+            } catch (\Exception $e) {
451
+                // if we fail to notify the remote (probably cause the remote is down)
452
+                // we still want the share to be gone to prevent undeletable remotes
453
+            }
454
+        }
455
+        $getShare->closeCursor();
456
+
457
+        $query = $this->connection->prepare('
458 458
 			DELETE FROM `*PREFIX*share_external`
459 459
 			WHERE `mountpoint_hash` = ?
460 460
 			AND `user` = ?
461 461
 		');
462
-		$result = (bool)$query->execute(array($hash, $this->uid));
463
-
464
-		if($result) {
465
-			$this->removeReShares($id);
466
-		}
467
-
468
-		return $result;
469
-	}
470
-
471
-	/**
472
-	 * remove re-shares from share table and mapping in the federated_reshares table
473
-	 *
474
-	 * @param $mountPointId
475
-	 */
476
-	protected function removeReShares($mountPointId) {
477
-		$selectQuery = $this->connection->getQueryBuilder();
478
-		$query = $this->connection->getQueryBuilder();
479
-		$selectQuery->select('id')->from('share')
480
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
481
-		$select = $selectQuery->getSQL();
482
-
483
-
484
-		$query->delete('federated_reshares')
485
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
486
-		$query->execute();
487
-
488
-		$deleteReShares = $this->connection->getQueryBuilder();
489
-		$deleteReShares->delete('share')
490
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
491
-		$deleteReShares->execute();
492
-	}
493
-
494
-	/**
495
-	 * remove all shares for user $uid if the user was deleted
496
-	 *
497
-	 * @param string $uid
498
-	 * @return bool
499
-	 */
500
-	public function removeUserShares($uid) {
501
-		$getShare = $this->connection->prepare('
462
+        $result = (bool)$query->execute(array($hash, $this->uid));
463
+
464
+        if($result) {
465
+            $this->removeReShares($id);
466
+        }
467
+
468
+        return $result;
469
+    }
470
+
471
+    /**
472
+     * remove re-shares from share table and mapping in the federated_reshares table
473
+     *
474
+     * @param $mountPointId
475
+     */
476
+    protected function removeReShares($mountPointId) {
477
+        $selectQuery = $this->connection->getQueryBuilder();
478
+        $query = $this->connection->getQueryBuilder();
479
+        $selectQuery->select('id')->from('share')
480
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
481
+        $select = $selectQuery->getSQL();
482
+
483
+
484
+        $query->delete('federated_reshares')
485
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
486
+        $query->execute();
487
+
488
+        $deleteReShares = $this->connection->getQueryBuilder();
489
+        $deleteReShares->delete('share')
490
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
491
+        $deleteReShares->execute();
492
+    }
493
+
494
+    /**
495
+     * remove all shares for user $uid if the user was deleted
496
+     *
497
+     * @param string $uid
498
+     * @return bool
499
+     */
500
+    public function removeUserShares($uid) {
501
+        $getShare = $this->connection->prepare('
502 502
 			SELECT `remote`, `share_token`, `remote_id`
503 503
 			FROM  `*PREFIX*share_external`
504 504
 			WHERE `user` = ?');
505
-		$result = $getShare->execute(array($uid));
505
+        $result = $getShare->execute(array($uid));
506 506
 
507
-		if ($result) {
508
-			$shares = $getShare->fetchAll();
509
-			foreach($shares as $share) {
510
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
511
-			}
512
-		}
507
+        if ($result) {
508
+            $shares = $getShare->fetchAll();
509
+            foreach($shares as $share) {
510
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
511
+            }
512
+        }
513 513
 
514
-		$query = $this->connection->prepare('
514
+        $query = $this->connection->prepare('
515 515
 			DELETE FROM `*PREFIX*share_external`
516 516
 			WHERE `user` = ?
517 517
 		');
518
-		return (bool)$query->execute(array($uid));
519
-	}
520
-
521
-	/**
522
-	 * return a list of shares which are not yet accepted by the user
523
-	 *
524
-	 * @return array list of open server-to-server shares
525
-	 */
526
-	public function getOpenShares() {
527
-		return $this->getShares(false);
528
-	}
529
-
530
-	/**
531
-	 * return a list of shares which are accepted by the user
532
-	 *
533
-	 * @return array list of accepted server-to-server shares
534
-	 */
535
-	public function getAcceptedShares() {
536
-		return $this->getShares(true);
537
-	}
538
-
539
-	/**
540
-	 * return a list of shares for the user
541
-	 *
542
-	 * @param bool|null $accepted True for accepted only,
543
-	 *                            false for not accepted,
544
-	 *                            null for all shares of the user
545
-	 * @return array list of open server-to-server shares
546
-	 */
547
-	private function getShares($accepted) {
548
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
518
+        return (bool)$query->execute(array($uid));
519
+    }
520
+
521
+    /**
522
+     * return a list of shares which are not yet accepted by the user
523
+     *
524
+     * @return array list of open server-to-server shares
525
+     */
526
+    public function getOpenShares() {
527
+        return $this->getShares(false);
528
+    }
529
+
530
+    /**
531
+     * return a list of shares which are accepted by the user
532
+     *
533
+     * @return array list of accepted server-to-server shares
534
+     */
535
+    public function getAcceptedShares() {
536
+        return $this->getShares(true);
537
+    }
538
+
539
+    /**
540
+     * return a list of shares for the user
541
+     *
542
+     * @param bool|null $accepted True for accepted only,
543
+     *                            false for not accepted,
544
+     *                            null for all shares of the user
545
+     * @return array list of open server-to-server shares
546
+     */
547
+    private function getShares($accepted) {
548
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
549 549
 		          FROM `*PREFIX*share_external` 
550 550
 				  WHERE `user` = ?';
551
-		$parameters = [$this->uid];
552
-		if (!is_null($accepted)) {
553
-			$query .= ' AND `accepted` = ?';
554
-			$parameters[] = (int) $accepted;
555
-		}
556
-		$query .= ' ORDER BY `id` ASC';
557
-
558
-		$shares = $this->connection->prepare($query);
559
-		$result = $shares->execute($parameters);
560
-
561
-		return $result ? $shares->fetchAll() : [];
562
-	}
551
+        $parameters = [$this->uid];
552
+        if (!is_null($accepted)) {
553
+            $query .= ' AND `accepted` = ?';
554
+            $parameters[] = (int) $accepted;
555
+        }
556
+        $query .= ' ORDER BY `id` ASC';
557
+
558
+        $shares = $this->connection->prepare($query);
559
+        $result = $shares->execute($parameters);
560
+
561
+        return $result ? $shares->fetchAll() : [];
562
+    }
563 563
 }
Please login to merge, or discard this patch.
apps/cloud_federation_api/lib/Config.php 1 patch
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -35,26 +35,26 @@
 block discarded – undo
35 35
  */
36 36
 class Config {
37 37
 
38
-	/** @var ICloudFederationProviderManager */
39
-	private $cloudFederationProviderManager;
40
-
41
-	public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager) {
42
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
43
-	}
44
-
45
-	/**
46
-	 * get a list of supported share types
47
-	 *
48
-	 * @param string $resourceType
49
-	 * @return array
50
-	 */
51
-	public function getSupportedShareTypes($resourceType) {
52
-		try {
53
-			$provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
54
-			return $provider->getSupportedShareTypes();
55
-		} catch (\Exception $e) {
56
-			return [];
57
-		}
58
-	}
38
+    /** @var ICloudFederationProviderManager */
39
+    private $cloudFederationProviderManager;
40
+
41
+    public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager) {
42
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
43
+    }
44
+
45
+    /**
46
+     * get a list of supported share types
47
+     *
48
+     * @param string $resourceType
49
+     * @return array
50
+     */
51
+    public function getSupportedShareTypes($resourceType) {
52
+        try {
53
+            $provider = $this->cloudFederationProviderManager->getCloudFederationProvider($resourceType);
54
+            return $provider->getSupportedShareTypes();
55
+        } catch (\Exception $e) {
56
+            return [];
57
+        }
58
+    }
59 59
 
60 60
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 1 patch
Indentation   +433 added lines, -433 removed lines patch added patch discarded remove patch
@@ -33,437 +33,437 @@
 block discarded – undo
33 33
 use OCP\OCS\IDiscoveryService;
34 34
 
35 35
 class Notifications {
36
-	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
-
38
-	/** @var AddressHandler */
39
-	private $addressHandler;
40
-
41
-	/** @var IClientService */
42
-	private $httpClientService;
43
-
44
-	/** @var IDiscoveryService */
45
-	private $discoveryService;
46
-
47
-	/** @var IJobList  */
48
-	private $jobList;
49
-
50
-	/** @var ICloudFederationProviderManager */
51
-	private $federationProviderManager;
52
-
53
-	/** @var ICloudFederationFactory */
54
-	private $cloudFederationFactory;
55
-
56
-	/**
57
-	 * @param AddressHandler $addressHandler
58
-	 * @param IClientService $httpClientService
59
-	 * @param IDiscoveryService $discoveryService
60
-	 * @param IJobList $jobList
61
-	 * @param ICloudFederationProviderManager $federationProviderManager
62
-	 * @param ICloudFederationFactory $cloudFederationFactory
63
-	 */
64
-	public function __construct(
65
-		AddressHandler $addressHandler,
66
-		IClientService $httpClientService,
67
-		IDiscoveryService $discoveryService,
68
-		IJobList $jobList,
69
-		ICloudFederationProviderManager $federationProviderManager,
70
-		ICloudFederationFactory $cloudFederationFactory
71
-	) {
72
-		$this->addressHandler = $addressHandler;
73
-		$this->httpClientService = $httpClientService;
74
-		$this->discoveryService = $discoveryService;
75
-		$this->jobList = $jobList;
76
-		$this->federationProviderManager = $federationProviderManager;
77
-		$this->cloudFederationFactory = $cloudFederationFactory;
78
-	}
79
-
80
-	/**
81
-	 * send server-to-server share to remote server
82
-	 *
83
-	 * @param string $token
84
-	 * @param string $shareWith
85
-	 * @param string $name
86
-	 * @param int $remote_id
87
-	 * @param string $owner
88
-	 * @param string $ownerFederatedId
89
-	 * @param string $sharedBy
90
-	 * @param string $sharedByFederatedId
91
-	 * @param int $shareType (can be a remote user or group share)
92
-	 * @return bool
93
-	 * @throws \OC\HintException
94
-	 * @throws \OC\ServerNotAvailableException
95
-	 */
96
-	public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
97
-
98
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
99
-
100
-		if ($user && $remote) {
101
-			$local = $this->addressHandler->generateRemoteURL();
102
-
103
-			$fields = array(
104
-				'shareWith' => $user,
105
-				'token' => $token,
106
-				'name' => $name,
107
-				'remoteId' => $remote_id,
108
-				'owner' => $owner,
109
-				'ownerFederatedId' => $ownerFederatedId,
110
-				'sharedBy' => $sharedBy,
111
-				'sharedByFederatedId' => $sharedByFederatedId,
112
-				'remote' => $local,
113
-				'shareType' => $shareType
114
-			);
115
-
116
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
117
-			$status = json_decode($result['result'], true);
118
-
119
-			$ocsStatus = isset($status['ocs']);
120
-			$ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
121
-
122
-			if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
123
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
124
-				return true;
125
-			}
126
-
127
-		}
128
-
129
-		return false;
130
-	}
131
-
132
-	/**
133
-	 * ask owner to re-share the file with the given user
134
-	 *
135
-	 * @param string $token
136
-	 * @param int $id remote Id
137
-	 * @param int $shareId internal share Id
138
-	 * @param string $remote remote address of the owner
139
-	 * @param string $shareWith
140
-	 * @param int $permission
141
-	 * @param string $filename
142
-	 * @return bool
143
-	 * @throws \OC\HintException
144
-	 * @throws \OC\ServerNotAvailableException
145
-	 */
146
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
147
-
148
-		$fields = array(
149
-			'shareWith' => $shareWith,
150
-			'token' => $token,
151
-			'permission' => $permission,
152
-			'remoteId' => $shareId,
153
-		);
154
-
155
-		$ocmFields = $fields;
156
-		$ocmFields['remoteId'] = $id;
157
-		$ocmFields['localId'] = $shareId;
158
-		$ocmFields['name'] = $filename;
159
-
160
-		$ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
161
-		if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
162
-			return [$ocmResult['token'], $ocmResult['providerId']];
163
-		}
164
-
165
-		$result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
166
-		$status = json_decode($result['result'], true);
167
-
168
-		$httpRequestSuccessful = $result['success'];
169
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
170
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
171
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
172
-
173
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
174
-			return [
175
-				$status['ocs']['data']['token'],
176
-				(int)$status['ocs']['data']['remoteId']
177
-			];
178
-		}
179
-
180
-		return false;
181
-	}
182
-
183
-	/**
184
-	 * send server-to-server unshare to remote server
185
-	 *
186
-	 * @param string $remote url
187
-	 * @param int $id share id
188
-	 * @param string $token
189
-	 * @return bool
190
-	 */
191
-	public function sendRemoteUnShare($remote, $id, $token) {
192
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
193
-	}
194
-
195
-	/**
196
-	 * send server-to-server unshare to remote server
197
-	 *
198
-	 * @param string $remote url
199
-	 * @param int $id share id
200
-	 * @param string $token
201
-	 * @return bool
202
-	 */
203
-	public function sendRevokeShare($remote, $id, $token) {
204
-		$this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
205
-	}
206
-
207
-	/**
208
-	 * send notification to remote server if the permissions was changed
209
-	 *
210
-	 * @param string $remote
211
-	 * @param int $remoteId
212
-	 * @param string $token
213
-	 * @param int $permissions
214
-	 * @return bool
215
-	 */
216
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
217
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
218
-	}
219
-
220
-	/**
221
-	 * forward accept reShare to remote server
222
-	 *
223
-	 * @param string $remote
224
-	 * @param int $remoteId
225
-	 * @param string $token
226
-	 */
227
-	public function sendAcceptShare($remote, $remoteId, $token) {
228
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
229
-	}
230
-
231
-	/**
232
-	 * forward decline reShare to remote server
233
-	 *
234
-	 * @param string $remote
235
-	 * @param int $remoteId
236
-	 * @param string $token
237
-	 */
238
-	public function sendDeclineShare($remote, $remoteId, $token) {
239
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
240
-	}
241
-
242
-	/**
243
-	 * inform remote server whether server-to-server share was accepted/declined
244
-	 *
245
-	 * @param string $remote
246
-	 * @param string $token
247
-	 * @param int $remoteId Share id on the remote host
248
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
249
-	 * @param array $data
250
-	 * @param int $try
251
-	 * @return boolean
252
-	 */
253
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
254
-
255
-		$fields = [
256
-			'token' => $token,
257
-			'remoteId' => $remoteId
258
-			];
259
-		foreach ($data as $key => $value) {
260
-			$fields[$key] = $value;
261
-		}
262
-
263
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
264
-		$status = json_decode($result['result'], true);
265
-
266
-		if ($result['success'] &&
267
-			($status['ocs']['meta']['statuscode'] === 100 ||
268
-				$status['ocs']['meta']['statuscode'] === 200
269
-			)
270
-		) {
271
-			return true;
272
-		} elseif ($try === 0) {
273
-			// only add new job on first try
274
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
275
-				[
276
-					'remote' => $remote,
277
-					'remoteId' => $remoteId,
278
-					'token' => $token,
279
-					'action' => $action,
280
-					'data' => json_encode($data),
281
-					'try' => $try,
282
-					'lastRun' => $this->getTimestamp()
283
-				]
284
-			);
285
-		}
286
-
287
-		return false;
288
-	}
289
-
290
-
291
-	/**
292
-	 * return current timestamp
293
-	 *
294
-	 * @return int
295
-	 */
296
-	protected function getTimestamp() {
297
-		return time();
298
-	}
299
-
300
-	/**
301
-	 * try http post with the given protocol, if no protocol is given we pick
302
-	 * the secure one (https)
303
-	 *
304
-	 * @param string $remoteDomain
305
-	 * @param string $urlSuffix
306
-	 * @param array $fields post parameters
307
-	 * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
308
-	 * @return array
309
-	 * @throws \Exception
310
-	 */
311
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
312
-
313
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
314
-			$remoteDomain = 'https://' . $remoteDomain;
315
-		}
316
-
317
-		$result = [
318
-			'success' => false,
319
-			'result' => '',
320
-		];
321
-
322
-		// if possible we use the new OCM API
323
-		$ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
324
-		if (is_array($ocmResult)) {
325
-			$result['success'] = true;
326
-			$result['result'] = json_encode([
327
-				'ocs' => ['meta' => ['statuscode' => 200]]]);
328
-			return $result;
329
-		}
330
-
331
-		return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
332
-	}
333
-
334
-	/**
335
-	 * try old federated sharing API if the OCM api doesn't work
336
-	 *
337
-	 * @param $remoteDomain
338
-	 * @param $urlSuffix
339
-	 * @param array $fields
340
-	 * @return mixed
341
-	 * @throws \Exception
342
-	 */
343
-	protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
344
-
345
-		$result = [
346
-			'success' => false,
347
-			'result' => '',
348
-		];
349
-
350
-		// Fall back to old API
351
-		$client = $this->httpClientService->newClient();
352
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
353
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
354
-		try {
355
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
356
-				'body' => $fields,
357
-				'timeout' => 10,
358
-				'connect_timeout' => 10,
359
-			]);
360
-			$result['result'] = $response->getBody();
361
-			$result['success'] = true;
362
-		} catch (\Exception $e) {
363
-			// if flat re-sharing is not supported by the remote server
364
-			// we re-throw the exception and fall back to the old behaviour.
365
-			// (flat re-shares has been introduced in Nextcloud 9.1)
366
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
367
-				throw $e;
368
-			}
369
-		}
370
-
371
-		return $result;
372
-
373
-	}
374
-
375
-	/**
376
-	 * check if server supports the new OCM api and ask for the correct end-point
377
-	 *
378
-	 * @param string $url
379
-	 * @return string
380
-	 */
381
-	protected function getOCMEndPoint($url) {
382
-		$client = $this->httpClientService->newClient();
383
-		try {
384
-			$response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 10]);
385
-		} catch (\Exception $e) {
386
-			return '';
387
-		}
388
-
389
-		$result = $response->getBody();
390
-		$result = json_decode($result, true);
391
-
392
-		if (isset($result['end-point'])) {
393
-			return $result['end-point'];
394
-		}
395
-
396
-		return '';
397
-	}
398
-
399
-	/**
400
-	 * send action regarding federated sharing to the remote server using the OCM API
401
-	 *
402
-	 * @param $remoteDomain
403
-	 * @param $fields
404
-	 * @param $action
405
-	 *
406
-	 * @return bool
407
-	 */
408
-	protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
409
-		switch ($action) {
410
-			case 'share':
411
-				$share = $this->cloudFederationFactory->getCloudFederationShare(
412
-					$fields['shareWith'] . '@' . $remoteDomain,
413
-					$fields['name'],
414
-					'',
415
-					$fields['remoteId'],
416
-					$fields['ownerFederatedId'],
417
-					$fields['owner'],
418
-					$fields['sharedByFederatedId'],
419
-					$fields['sharedBy'],
420
-					$fields['token'],
421
-					$fields['shareType'],
422
-					'file'
423
-				);
424
-				return $this->federationProviderManager->sendShare($share);
425
-			case 'reshare':
426
-				// ask owner to reshare a file
427
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
428
-				$notification->setMessage('REQUEST_RESHARE',
429
-					'file',
430
-					$fields['remoteId'],
431
-					[
432
-						'sharedSecret' => $fields['token'],
433
-						'shareWith' => $fields['shareWith'],
434
-						'senderId' => $fields['localId'],
435
-						'shareType' => $fields['shareType'],
436
-						'message' => 'Ask owner to reshare the file'
437
-					]
438
-				);
439
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
440
-			case 'unshare':
441
-				//owner unshares the file from the recipient again
442
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
443
-				$notification->setMessage('SHARE_UNSHARED',
444
-					'file',
445
-					$fields['remoteId'],
446
-					[
447
-						'sharedSecret' => $fields['token'],
448
-						'messgage' => 'file is no longer shared with you'
449
-					]
450
-				);
451
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
452
-			case 'reshare_undo':
453
-				// if a reshare was unshared we send the information to the initiator/owner
454
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
455
-				$notification->setMessage('RESHARE_UNDO',
456
-					'file',
457
-					$fields['remoteId'],
458
-					[
459
-						'sharedSecret' => $fields['token'],
460
-						'message' => 'reshare was revoked'
461
-					]
462
-				);
463
-				return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
464
-		}
465
-
466
-		return false;
467
-
468
-	}
36
+    const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
+
38
+    /** @var AddressHandler */
39
+    private $addressHandler;
40
+
41
+    /** @var IClientService */
42
+    private $httpClientService;
43
+
44
+    /** @var IDiscoveryService */
45
+    private $discoveryService;
46
+
47
+    /** @var IJobList  */
48
+    private $jobList;
49
+
50
+    /** @var ICloudFederationProviderManager */
51
+    private $federationProviderManager;
52
+
53
+    /** @var ICloudFederationFactory */
54
+    private $cloudFederationFactory;
55
+
56
+    /**
57
+     * @param AddressHandler $addressHandler
58
+     * @param IClientService $httpClientService
59
+     * @param IDiscoveryService $discoveryService
60
+     * @param IJobList $jobList
61
+     * @param ICloudFederationProviderManager $federationProviderManager
62
+     * @param ICloudFederationFactory $cloudFederationFactory
63
+     */
64
+    public function __construct(
65
+        AddressHandler $addressHandler,
66
+        IClientService $httpClientService,
67
+        IDiscoveryService $discoveryService,
68
+        IJobList $jobList,
69
+        ICloudFederationProviderManager $federationProviderManager,
70
+        ICloudFederationFactory $cloudFederationFactory
71
+    ) {
72
+        $this->addressHandler = $addressHandler;
73
+        $this->httpClientService = $httpClientService;
74
+        $this->discoveryService = $discoveryService;
75
+        $this->jobList = $jobList;
76
+        $this->federationProviderManager = $federationProviderManager;
77
+        $this->cloudFederationFactory = $cloudFederationFactory;
78
+    }
79
+
80
+    /**
81
+     * send server-to-server share to remote server
82
+     *
83
+     * @param string $token
84
+     * @param string $shareWith
85
+     * @param string $name
86
+     * @param int $remote_id
87
+     * @param string $owner
88
+     * @param string $ownerFederatedId
89
+     * @param string $sharedBy
90
+     * @param string $sharedByFederatedId
91
+     * @param int $shareType (can be a remote user or group share)
92
+     * @return bool
93
+     * @throws \OC\HintException
94
+     * @throws \OC\ServerNotAvailableException
95
+     */
96
+    public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId, $shareType) {
97
+
98
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
99
+
100
+        if ($user && $remote) {
101
+            $local = $this->addressHandler->generateRemoteURL();
102
+
103
+            $fields = array(
104
+                'shareWith' => $user,
105
+                'token' => $token,
106
+                'name' => $name,
107
+                'remoteId' => $remote_id,
108
+                'owner' => $owner,
109
+                'ownerFederatedId' => $ownerFederatedId,
110
+                'sharedBy' => $sharedBy,
111
+                'sharedByFederatedId' => $sharedByFederatedId,
112
+                'remote' => $local,
113
+                'shareType' => $shareType
114
+            );
115
+
116
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
117
+            $status = json_decode($result['result'], true);
118
+
119
+            $ocsStatus = isset($status['ocs']);
120
+            $ocsSuccess = $ocsStatus && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
121
+
122
+            if ($result['success'] && (!$ocsStatus ||$ocsSuccess)) {
123
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
124
+                return true;
125
+            }
126
+
127
+        }
128
+
129
+        return false;
130
+    }
131
+
132
+    /**
133
+     * ask owner to re-share the file with the given user
134
+     *
135
+     * @param string $token
136
+     * @param int $id remote Id
137
+     * @param int $shareId internal share Id
138
+     * @param string $remote remote address of the owner
139
+     * @param string $shareWith
140
+     * @param int $permission
141
+     * @param string $filename
142
+     * @return bool
143
+     * @throws \OC\HintException
144
+     * @throws \OC\ServerNotAvailableException
145
+     */
146
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission, $filename) {
147
+
148
+        $fields = array(
149
+            'shareWith' => $shareWith,
150
+            'token' => $token,
151
+            'permission' => $permission,
152
+            'remoteId' => $shareId,
153
+        );
154
+
155
+        $ocmFields = $fields;
156
+        $ocmFields['remoteId'] = $id;
157
+        $ocmFields['localId'] = $shareId;
158
+        $ocmFields['name'] = $filename;
159
+
160
+        $ocmResult = $this->tryOCMEndPoint($remote, $ocmFields, 'reshare');
161
+        if (is_array($ocmResult) && isset($ocmResult['token']) && isset($ocmResult['providerId'])) {
162
+            return [$ocmResult['token'], $ocmResult['providerId']];
163
+        }
164
+
165
+        $result = $this->tryLegacyEndPoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
166
+        $status = json_decode($result['result'], true);
167
+
168
+        $httpRequestSuccessful = $result['success'];
169
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
170
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
171
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
172
+
173
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
174
+            return [
175
+                $status['ocs']['data']['token'],
176
+                (int)$status['ocs']['data']['remoteId']
177
+            ];
178
+        }
179
+
180
+        return false;
181
+    }
182
+
183
+    /**
184
+     * send server-to-server unshare to remote server
185
+     *
186
+     * @param string $remote url
187
+     * @param int $id share id
188
+     * @param string $token
189
+     * @return bool
190
+     */
191
+    public function sendRemoteUnShare($remote, $id, $token) {
192
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
193
+    }
194
+
195
+    /**
196
+     * send server-to-server unshare to remote server
197
+     *
198
+     * @param string $remote url
199
+     * @param int $id share id
200
+     * @param string $token
201
+     * @return bool
202
+     */
203
+    public function sendRevokeShare($remote, $id, $token) {
204
+        $this->sendUpdateToRemote($remote, $id, $token, 'reshare_undo');
205
+    }
206
+
207
+    /**
208
+     * send notification to remote server if the permissions was changed
209
+     *
210
+     * @param string $remote
211
+     * @param int $remoteId
212
+     * @param string $token
213
+     * @param int $permissions
214
+     * @return bool
215
+     */
216
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
217
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
218
+    }
219
+
220
+    /**
221
+     * forward accept reShare to remote server
222
+     *
223
+     * @param string $remote
224
+     * @param int $remoteId
225
+     * @param string $token
226
+     */
227
+    public function sendAcceptShare($remote, $remoteId, $token) {
228
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
229
+    }
230
+
231
+    /**
232
+     * forward decline reShare to remote server
233
+     *
234
+     * @param string $remote
235
+     * @param int $remoteId
236
+     * @param string $token
237
+     */
238
+    public function sendDeclineShare($remote, $remoteId, $token) {
239
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
240
+    }
241
+
242
+    /**
243
+     * inform remote server whether server-to-server share was accepted/declined
244
+     *
245
+     * @param string $remote
246
+     * @param string $token
247
+     * @param int $remoteId Share id on the remote host
248
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
249
+     * @param array $data
250
+     * @param int $try
251
+     * @return boolean
252
+     */
253
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
254
+
255
+        $fields = [
256
+            'token' => $token,
257
+            'remoteId' => $remoteId
258
+            ];
259
+        foreach ($data as $key => $value) {
260
+            $fields[$key] = $value;
261
+        }
262
+
263
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields, $action);
264
+        $status = json_decode($result['result'], true);
265
+
266
+        if ($result['success'] &&
267
+            ($status['ocs']['meta']['statuscode'] === 100 ||
268
+                $status['ocs']['meta']['statuscode'] === 200
269
+            )
270
+        ) {
271
+            return true;
272
+        } elseif ($try === 0) {
273
+            // only add new job on first try
274
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
275
+                [
276
+                    'remote' => $remote,
277
+                    'remoteId' => $remoteId,
278
+                    'token' => $token,
279
+                    'action' => $action,
280
+                    'data' => json_encode($data),
281
+                    'try' => $try,
282
+                    'lastRun' => $this->getTimestamp()
283
+                ]
284
+            );
285
+        }
286
+
287
+        return false;
288
+    }
289
+
290
+
291
+    /**
292
+     * return current timestamp
293
+     *
294
+     * @return int
295
+     */
296
+    protected function getTimestamp() {
297
+        return time();
298
+    }
299
+
300
+    /**
301
+     * try http post with the given protocol, if no protocol is given we pick
302
+     * the secure one (https)
303
+     *
304
+     * @param string $remoteDomain
305
+     * @param string $urlSuffix
306
+     * @param array $fields post parameters
307
+     * @param string $action define the action (possible values: share, reshare, accept, decline, unshare, revoke, permissions)
308
+     * @return array
309
+     * @throws \Exception
310
+     */
311
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields, $action="share") {
312
+
313
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
314
+            $remoteDomain = 'https://' . $remoteDomain;
315
+        }
316
+
317
+        $result = [
318
+            'success' => false,
319
+            'result' => '',
320
+        ];
321
+
322
+        // if possible we use the new OCM API
323
+        $ocmResult = $this->tryOCMEndPoint($remoteDomain, $fields, $action);
324
+        if (is_array($ocmResult)) {
325
+            $result['success'] = true;
326
+            $result['result'] = json_encode([
327
+                'ocs' => ['meta' => ['statuscode' => 200]]]);
328
+            return $result;
329
+        }
330
+
331
+        return $this->tryLegacyEndPoint($remoteDomain, $urlSuffix, $fields);
332
+    }
333
+
334
+    /**
335
+     * try old federated sharing API if the OCM api doesn't work
336
+     *
337
+     * @param $remoteDomain
338
+     * @param $urlSuffix
339
+     * @param array $fields
340
+     * @return mixed
341
+     * @throws \Exception
342
+     */
343
+    protected function tryLegacyEndPoint($remoteDomain, $urlSuffix, array $fields) {
344
+
345
+        $result = [
346
+            'success' => false,
347
+            'result' => '',
348
+        ];
349
+
350
+        // Fall back to old API
351
+        $client = $this->httpClientService->newClient();
352
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
353
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
354
+        try {
355
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
356
+                'body' => $fields,
357
+                'timeout' => 10,
358
+                'connect_timeout' => 10,
359
+            ]);
360
+            $result['result'] = $response->getBody();
361
+            $result['success'] = true;
362
+        } catch (\Exception $e) {
363
+            // if flat re-sharing is not supported by the remote server
364
+            // we re-throw the exception and fall back to the old behaviour.
365
+            // (flat re-shares has been introduced in Nextcloud 9.1)
366
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
367
+                throw $e;
368
+            }
369
+        }
370
+
371
+        return $result;
372
+
373
+    }
374
+
375
+    /**
376
+     * check if server supports the new OCM api and ask for the correct end-point
377
+     *
378
+     * @param string $url
379
+     * @return string
380
+     */
381
+    protected function getOCMEndPoint($url) {
382
+        $client = $this->httpClientService->newClient();
383
+        try {
384
+            $response = $client->get($url, ['timeout' => 10, 'connect_timeout' => 10]);
385
+        } catch (\Exception $e) {
386
+            return '';
387
+        }
388
+
389
+        $result = $response->getBody();
390
+        $result = json_decode($result, true);
391
+
392
+        if (isset($result['end-point'])) {
393
+            return $result['end-point'];
394
+        }
395
+
396
+        return '';
397
+    }
398
+
399
+    /**
400
+     * send action regarding federated sharing to the remote server using the OCM API
401
+     *
402
+     * @param $remoteDomain
403
+     * @param $fields
404
+     * @param $action
405
+     *
406
+     * @return bool
407
+     */
408
+    protected function tryOCMEndPoint($remoteDomain, $fields, $action) {
409
+        switch ($action) {
410
+            case 'share':
411
+                $share = $this->cloudFederationFactory->getCloudFederationShare(
412
+                    $fields['shareWith'] . '@' . $remoteDomain,
413
+                    $fields['name'],
414
+                    '',
415
+                    $fields['remoteId'],
416
+                    $fields['ownerFederatedId'],
417
+                    $fields['owner'],
418
+                    $fields['sharedByFederatedId'],
419
+                    $fields['sharedBy'],
420
+                    $fields['token'],
421
+                    $fields['shareType'],
422
+                    'file'
423
+                );
424
+                return $this->federationProviderManager->sendShare($share);
425
+            case 'reshare':
426
+                // ask owner to reshare a file
427
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
428
+                $notification->setMessage('REQUEST_RESHARE',
429
+                    'file',
430
+                    $fields['remoteId'],
431
+                    [
432
+                        'sharedSecret' => $fields['token'],
433
+                        'shareWith' => $fields['shareWith'],
434
+                        'senderId' => $fields['localId'],
435
+                        'shareType' => $fields['shareType'],
436
+                        'message' => 'Ask owner to reshare the file'
437
+                    ]
438
+                );
439
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
440
+            case 'unshare':
441
+                //owner unshares the file from the recipient again
442
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
443
+                $notification->setMessage('SHARE_UNSHARED',
444
+                    'file',
445
+                    $fields['remoteId'],
446
+                    [
447
+                        'sharedSecret' => $fields['token'],
448
+                        'messgage' => 'file is no longer shared with you'
449
+                    ]
450
+                );
451
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
452
+            case 'reshare_undo':
453
+                // if a reshare was unshared we send the information to the initiator/owner
454
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
455
+                $notification->setMessage('RESHARE_UNDO',
456
+                    'file',
457
+                    $fields['remoteId'],
458
+                    [
459
+                        'sharedSecret' => $fields['token'],
460
+                        'message' => 'reshare was revoked'
461
+                    ]
462
+                );
463
+                return $this->federationProviderManager->sendNotification($remoteDomain, $notification);
464
+        }
465
+
466
+        return false;
467
+
468
+    }
469 469
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/External/Storage.php 1 patch
Indentation   +376 added lines, -376 removed lines patch added patch discarded remove patch
@@ -43,380 +43,380 @@
 block discarded – undo
43 43
 use OCP\Files\StorageNotAvailableException;
44 44
 
45 45
 class Storage extends DAV implements ISharedStorage {
46
-	/** @var ICloudId */
47
-	private $cloudId;
48
-	/** @var string */
49
-	private $mountPoint;
50
-	/** @var string */
51
-	private $token;
52
-	/** @var \OCP\ICacheFactory */
53
-	private $memcacheFactory;
54
-	/** @var \OCP\Http\Client\IClientService */
55
-	private $httpClient;
56
-	/** @var bool */
57
-	private $updateChecked = false;
58
-
59
-	/**
60
-	 * @var \OCA\Files_Sharing\External\Manager
61
-	 */
62
-	private $manager;
63
-
64
-	public function __construct($options) {
65
-		$this->memcacheFactory = \OC::$server->getMemCacheFactory();
66
-		$this->httpClient = $options['HttpClientService'];
67
-
68
-		$this->manager = $options['manager'];
69
-		$this->cloudId = $options['cloudId'];
70
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
71
-
72
-		list($protocol, $remote) = explode('://', $this->cloudId->getRemote());
73
-		if (strpos($remote, '/')) {
74
-			list($host, $root) = explode('/', $remote, 2);
75
-		} else {
76
-			$host = $remote;
77
-			$root = '';
78
-		}
79
-		$secure = $protocol === 'https';
80
-		$federatedSharingEndpoints = $discoveryService->discover($this->cloudId->getRemote(), 'FEDERATED_SHARING');
81
-		$webDavEndpoint = isset($federatedSharingEndpoints['webdav']) ? $federatedSharingEndpoints['webdav'] : '/public.php/webdav';
82
-		$root = rtrim($root, '/') . $webDavEndpoint;
83
-		$this->mountPoint = $options['mountpoint'];
84
-		$this->token = $options['token'];
85
-
86
-		parent::__construct(array(
87
-			'secure' => $secure,
88
-			'host' => $host,
89
-			'root' => $root,
90
-			'user' => $options['token'],
91
-			'password' => (string)$options['password']
92
-		));
93
-	}
94
-
95
-	public function getWatcher($path = '', $storage = null) {
96
-		if (!$storage) {
97
-			$storage = $this;
98
-		}
99
-		if (!isset($this->watcher)) {
100
-			$this->watcher = new Watcher($storage);
101
-			$this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
102
-		}
103
-		return $this->watcher;
104
-	}
105
-
106
-	public function getRemoteUser() {
107
-		return $this->cloudId->getUser();
108
-	}
109
-
110
-	public function getRemote() {
111
-		return $this->cloudId->getRemote();
112
-	}
113
-
114
-	public function getMountPoint() {
115
-		return $this->mountPoint;
116
-	}
117
-
118
-	public function getToken() {
119
-		return $this->token;
120
-	}
121
-
122
-	public function getPassword() {
123
-		return $this->password;
124
-	}
125
-
126
-	/**
127
-	 * @brief get id of the mount point
128
-	 * @return string
129
-	 */
130
-	public function getId() {
131
-		return 'shared::' . md5($this->token . '@' . $this->getRemote());
132
-	}
133
-
134
-	public function getCache($path = '', $storage = null) {
135
-		if (is_null($this->cache)) {
136
-			$this->cache = new Cache($this, $this->cloudId);
137
-		}
138
-		return $this->cache;
139
-	}
140
-
141
-	/**
142
-	 * @param string $path
143
-	 * @param \OC\Files\Storage\Storage $storage
144
-	 * @return \OCA\Files_Sharing\External\Scanner
145
-	 */
146
-	public function getScanner($path = '', $storage = null) {
147
-		if (!$storage) {
148
-			$storage = $this;
149
-		}
150
-		if (!isset($this->scanner)) {
151
-			$this->scanner = new Scanner($storage);
152
-		}
153
-		return $this->scanner;
154
-	}
155
-
156
-	/**
157
-	 * check if a file or folder has been updated since $time
158
-	 *
159
-	 * @param string $path
160
-	 * @param int $time
161
-	 * @throws \OCP\Files\StorageNotAvailableException
162
-	 * @throws \OCP\Files\StorageInvalidException
163
-	 * @return bool
164
-	 */
165
-	public function hasUpdated($path, $time) {
166
-		// since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
167
-		// because of that we only do one check for the entire storage per request
168
-		if ($this->updateChecked) {
169
-			return false;
170
-		}
171
-		$this->updateChecked = true;
172
-		try {
173
-			return parent::hasUpdated('', $time);
174
-		} catch (StorageInvalidException $e) {
175
-			// check if it needs to be removed
176
-			$this->checkStorageAvailability();
177
-			throw $e;
178
-		} catch (StorageNotAvailableException $e) {
179
-			// check if it needs to be removed or just temp unavailable
180
-			$this->checkStorageAvailability();
181
-			throw $e;
182
-		}
183
-	}
184
-
185
-	public function test() {
186
-		try {
187
-			return parent::test();
188
-		} catch (StorageInvalidException $e) {
189
-			// check if it needs to be removed
190
-			$this->checkStorageAvailability();
191
-			throw $e;
192
-		} catch (StorageNotAvailableException $e) {
193
-			// check if it needs to be removed or just temp unavailable
194
-			$this->checkStorageAvailability();
195
-			throw $e;
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * Check whether this storage is permanently or temporarily
201
-	 * unavailable
202
-	 *
203
-	 * @throws \OCP\Files\StorageNotAvailableException
204
-	 * @throws \OCP\Files\StorageInvalidException
205
-	 */
206
-	public function checkStorageAvailability() {
207
-		// see if we can find out why the share is unavailable
208
-		try {
209
-			$this->getShareInfo();
210
-		} catch (NotFoundException $e) {
211
-			// a 404 can either mean that the share no longer exists or there is no Nextcloud on the remote
212
-			if ($this->testRemote()) {
213
-				// valid Nextcloud instance means that the public share no longer exists
214
-				// since this is permanent (re-sharing the file will create a new token)
215
-				// we remove the invalid storage
216
-				$this->manager->removeShare($this->mountPoint);
217
-				$this->manager->getMountManager()->removeMount($this->mountPoint);
218
-				throw new StorageInvalidException();
219
-			} else {
220
-				// Nextcloud instance is gone, likely to be a temporary server configuration error
221
-				throw new StorageNotAvailableException();
222
-			}
223
-		} catch (ForbiddenException $e) {
224
-			// auth error, remove share for now (provide a dialog in the future)
225
-			$this->manager->removeShare($this->mountPoint);
226
-			$this->manager->getMountManager()->removeMount($this->mountPoint);
227
-			throw new StorageInvalidException();
228
-		} catch (\GuzzleHttp\Exception\ConnectException $e) {
229
-			throw new StorageNotAvailableException();
230
-		} catch (\GuzzleHttp\Exception\RequestException $e) {
231
-			throw new StorageNotAvailableException();
232
-		} catch (\Exception $e) {
233
-			throw $e;
234
-		}
235
-	}
236
-
237
-	public function file_exists($path) {
238
-		if ($path === '') {
239
-			return true;
240
-		} else {
241
-			return parent::file_exists($path);
242
-		}
243
-	}
244
-
245
-	/**
246
-	 * check if the configured remote is a valid federated share provider
247
-	 *
248
-	 * @return bool
249
-	 */
250
-	protected function testRemote() {
251
-		try {
252
-			return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
253
-				|| $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
254
-				|| $this->testRemoteUrl($this->getRemote() . '/status.php');
255
-		} catch (\Exception $e) {
256
-			return false;
257
-		}
258
-	}
259
-
260
-	/**
261
-	 * @param string $url
262
-	 * @return bool
263
-	 */
264
-	private function testRemoteUrl($url) {
265
-		$cache = $this->memcacheFactory->createDistributed('files_sharing_remote_url');
266
-		if($cache->hasKey($url)) {
267
-			return (bool)$cache->get($url);
268
-		}
269
-
270
-		$client = $this->httpClient->newClient();
271
-		try {
272
-			$result = $client->get($url, [
273
-				'timeout' => 10,
274
-				'connect_timeout' => 10,
275
-			])->getBody();
276
-			$data = json_decode($result);
277
-			$returnValue = (is_object($data) && !empty($data->version));
278
-		} catch (ConnectException $e) {
279
-			$returnValue = false;
280
-		} catch (ClientException $e) {
281
-			$returnValue = false;
282
-		}
283
-
284
-		$cache->set($url, $returnValue, 60*60*24);
285
-		return $returnValue;
286
-	}
287
-
288
-	/**
289
-	 * Whether the remote is an ownCloud/Nextcloud, used since some sharing features are not
290
-	 * standardized. Let's use this to detect whether to use it.
291
-	 *
292
-	 * @return bool
293
-	 */
294
-	public function remoteIsOwnCloud() {
295
-		if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
296
-			return false;
297
-		}
298
-		return true;
299
-	}
300
-
301
-	/**
302
-	 * @return mixed
303
-	 * @throws ForbiddenException
304
-	 * @throws NotFoundException
305
-	 * @throws \Exception
306
-	 */
307
-	public function getShareInfo() {
308
-		$remote = $this->getRemote();
309
-		$token = $this->getToken();
310
-		$password = $this->getPassword();
311
-
312
-		// If remote is not an ownCloud do not try to get any share info
313
-		if(!$this->remoteIsOwnCloud()) {
314
-			return ['status' => 'unsupported'];
315
-		}
316
-
317
-		$url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
318
-
319
-		// TODO: DI
320
-		$client = \OC::$server->getHTTPClientService()->newClient();
321
-		try {
322
-			$response = $client->post($url, [
323
-				'body' => ['password' => $password],
324
-				'timeout' => 10,
325
-				'connect_timeout' => 10,
326
-			]);
327
-		} catch (\GuzzleHttp\Exception\RequestException $e) {
328
-			if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
329
-				throw new ForbiddenException();
330
-			}
331
-			if ($e->getCode() === Http::STATUS_NOT_FOUND) {
332
-				throw new NotFoundException();
333
-			}
334
-			// throw this to be on the safe side: the share will still be visible
335
-			// in the UI in case the failure is intermittent, and the user will
336
-			// be able to decide whether to remove it if it's really gone
337
-			throw new StorageNotAvailableException();
338
-		}
339
-
340
-		return json_decode($response->getBody(), true);
341
-	}
342
-
343
-	public function getOwner($path) {
344
-		return $this->cloudId->getDisplayId();
345
-	}
346
-
347
-	public function isSharable($path) {
348
-		if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
349
-			return false;
350
-		}
351
-		return ($this->getPermissions($path) & Constants::PERMISSION_SHARE);
352
-	}
353
-
354
-	public function getPermissions($path) {
355
-		$response = $this->propfind($path);
356
-		// old federated sharing permissions
357
-		if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
358
-			$permissions = $response['{http://open-collaboration-services.org/ns}share-permissions'];
359
-		} else if (isset($response['{http://open-cloud-mesh.org/ns}share-permissions'])) {
360
-			// permissions provided by the OCM API
361
-			$permissions = $this->ocmPermissions2ncPermissions($response['{http://open-collaboration-services.org/ns}share-permissions']);
362
-		} else {
363
-			// use default permission if remote server doesn't provide the share permissions
364
-			$permissions = $this->getDefaultPermissions($path);
365
-		}
366
-
367
-		return $permissions;
368
-	}
369
-
370
-	public function needsPartFile() {
371
-		return false;
372
-	}
373
-
374
-	/**
375
-	 * translate OCM Permissions to Nextcloud permissions
376
-	 *
377
-	 * @param string $ocmPermissions json encoded OCM permissions
378
-	 * @param string $path path to file
379
-	 * @return int
380
-	 */
381
-	protected function ocmPermissions2ncPermissions($ocmPermissions, $path) {
382
-		try {
383
-			$ocmPermissions = json_decode($ocmPermissions);
384
-			$ncPermissions = 0;
385
-			foreach($ocmPermissions as $permission) {
386
-				switch (strtolower($permission)) {
387
-					case 'read':
388
-						$ncPermissions += Constants::PERMISSION_READ;
389
-						break;
390
-					case 'write':
391
-						$ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
392
-						break;
393
-					case 'share':
394
-						$ncPermissions += Constants::PERMISSION_SHARE;
395
-						break;
396
-					default:
397
-						throw new \Exception();
398
-				}
399
-			}
400
-		} catch (\Exception $e) {
401
-			$ncPermissions = $this->getDefaultPermissions($path);
402
-		}
403
-
404
-		return $ncPermissions;
405
-	}
406
-
407
-	/**
408
-	 * calculate default permissions in case no permissions are provided
409
-	 *
410
-	 * @param $path
411
-	 * @return int
412
-	 */
413
-	protected function getDefaultPermissions($path) {
414
-		if ($this->is_dir($path)) {
415
-			$permissions = Constants::PERMISSION_ALL;
416
-		} else {
417
-			$permissions = Constants::PERMISSION_ALL & ~Constants::PERMISSION_CREATE;
418
-		}
419
-
420
-		return $permissions;
421
-	}
46
+    /** @var ICloudId */
47
+    private $cloudId;
48
+    /** @var string */
49
+    private $mountPoint;
50
+    /** @var string */
51
+    private $token;
52
+    /** @var \OCP\ICacheFactory */
53
+    private $memcacheFactory;
54
+    /** @var \OCP\Http\Client\IClientService */
55
+    private $httpClient;
56
+    /** @var bool */
57
+    private $updateChecked = false;
58
+
59
+    /**
60
+     * @var \OCA\Files_Sharing\External\Manager
61
+     */
62
+    private $manager;
63
+
64
+    public function __construct($options) {
65
+        $this->memcacheFactory = \OC::$server->getMemCacheFactory();
66
+        $this->httpClient = $options['HttpClientService'];
67
+
68
+        $this->manager = $options['manager'];
69
+        $this->cloudId = $options['cloudId'];
70
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
71
+
72
+        list($protocol, $remote) = explode('://', $this->cloudId->getRemote());
73
+        if (strpos($remote, '/')) {
74
+            list($host, $root) = explode('/', $remote, 2);
75
+        } else {
76
+            $host = $remote;
77
+            $root = '';
78
+        }
79
+        $secure = $protocol === 'https';
80
+        $federatedSharingEndpoints = $discoveryService->discover($this->cloudId->getRemote(), 'FEDERATED_SHARING');
81
+        $webDavEndpoint = isset($federatedSharingEndpoints['webdav']) ? $federatedSharingEndpoints['webdav'] : '/public.php/webdav';
82
+        $root = rtrim($root, '/') . $webDavEndpoint;
83
+        $this->mountPoint = $options['mountpoint'];
84
+        $this->token = $options['token'];
85
+
86
+        parent::__construct(array(
87
+            'secure' => $secure,
88
+            'host' => $host,
89
+            'root' => $root,
90
+            'user' => $options['token'],
91
+            'password' => (string)$options['password']
92
+        ));
93
+    }
94
+
95
+    public function getWatcher($path = '', $storage = null) {
96
+        if (!$storage) {
97
+            $storage = $this;
98
+        }
99
+        if (!isset($this->watcher)) {
100
+            $this->watcher = new Watcher($storage);
101
+            $this->watcher->setPolicy(\OC\Files\Cache\Watcher::CHECK_ONCE);
102
+        }
103
+        return $this->watcher;
104
+    }
105
+
106
+    public function getRemoteUser() {
107
+        return $this->cloudId->getUser();
108
+    }
109
+
110
+    public function getRemote() {
111
+        return $this->cloudId->getRemote();
112
+    }
113
+
114
+    public function getMountPoint() {
115
+        return $this->mountPoint;
116
+    }
117
+
118
+    public function getToken() {
119
+        return $this->token;
120
+    }
121
+
122
+    public function getPassword() {
123
+        return $this->password;
124
+    }
125
+
126
+    /**
127
+     * @brief get id of the mount point
128
+     * @return string
129
+     */
130
+    public function getId() {
131
+        return 'shared::' . md5($this->token . '@' . $this->getRemote());
132
+    }
133
+
134
+    public function getCache($path = '', $storage = null) {
135
+        if (is_null($this->cache)) {
136
+            $this->cache = new Cache($this, $this->cloudId);
137
+        }
138
+        return $this->cache;
139
+    }
140
+
141
+    /**
142
+     * @param string $path
143
+     * @param \OC\Files\Storage\Storage $storage
144
+     * @return \OCA\Files_Sharing\External\Scanner
145
+     */
146
+    public function getScanner($path = '', $storage = null) {
147
+        if (!$storage) {
148
+            $storage = $this;
149
+        }
150
+        if (!isset($this->scanner)) {
151
+            $this->scanner = new Scanner($storage);
152
+        }
153
+        return $this->scanner;
154
+    }
155
+
156
+    /**
157
+     * check if a file or folder has been updated since $time
158
+     *
159
+     * @param string $path
160
+     * @param int $time
161
+     * @throws \OCP\Files\StorageNotAvailableException
162
+     * @throws \OCP\Files\StorageInvalidException
163
+     * @return bool
164
+     */
165
+    public function hasUpdated($path, $time) {
166
+        // since for owncloud webdav servers we can rely on etag propagation we only need to check the root of the storage
167
+        // because of that we only do one check for the entire storage per request
168
+        if ($this->updateChecked) {
169
+            return false;
170
+        }
171
+        $this->updateChecked = true;
172
+        try {
173
+            return parent::hasUpdated('', $time);
174
+        } catch (StorageInvalidException $e) {
175
+            // check if it needs to be removed
176
+            $this->checkStorageAvailability();
177
+            throw $e;
178
+        } catch (StorageNotAvailableException $e) {
179
+            // check if it needs to be removed or just temp unavailable
180
+            $this->checkStorageAvailability();
181
+            throw $e;
182
+        }
183
+    }
184
+
185
+    public function test() {
186
+        try {
187
+            return parent::test();
188
+        } catch (StorageInvalidException $e) {
189
+            // check if it needs to be removed
190
+            $this->checkStorageAvailability();
191
+            throw $e;
192
+        } catch (StorageNotAvailableException $e) {
193
+            // check if it needs to be removed or just temp unavailable
194
+            $this->checkStorageAvailability();
195
+            throw $e;
196
+        }
197
+    }
198
+
199
+    /**
200
+     * Check whether this storage is permanently or temporarily
201
+     * unavailable
202
+     *
203
+     * @throws \OCP\Files\StorageNotAvailableException
204
+     * @throws \OCP\Files\StorageInvalidException
205
+     */
206
+    public function checkStorageAvailability() {
207
+        // see if we can find out why the share is unavailable
208
+        try {
209
+            $this->getShareInfo();
210
+        } catch (NotFoundException $e) {
211
+            // a 404 can either mean that the share no longer exists or there is no Nextcloud on the remote
212
+            if ($this->testRemote()) {
213
+                // valid Nextcloud instance means that the public share no longer exists
214
+                // since this is permanent (re-sharing the file will create a new token)
215
+                // we remove the invalid storage
216
+                $this->manager->removeShare($this->mountPoint);
217
+                $this->manager->getMountManager()->removeMount($this->mountPoint);
218
+                throw new StorageInvalidException();
219
+            } else {
220
+                // Nextcloud instance is gone, likely to be a temporary server configuration error
221
+                throw new StorageNotAvailableException();
222
+            }
223
+        } catch (ForbiddenException $e) {
224
+            // auth error, remove share for now (provide a dialog in the future)
225
+            $this->manager->removeShare($this->mountPoint);
226
+            $this->manager->getMountManager()->removeMount($this->mountPoint);
227
+            throw new StorageInvalidException();
228
+        } catch (\GuzzleHttp\Exception\ConnectException $e) {
229
+            throw new StorageNotAvailableException();
230
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
231
+            throw new StorageNotAvailableException();
232
+        } catch (\Exception $e) {
233
+            throw $e;
234
+        }
235
+    }
236
+
237
+    public function file_exists($path) {
238
+        if ($path === '') {
239
+            return true;
240
+        } else {
241
+            return parent::file_exists($path);
242
+        }
243
+    }
244
+
245
+    /**
246
+     * check if the configured remote is a valid federated share provider
247
+     *
248
+     * @return bool
249
+     */
250
+    protected function testRemote() {
251
+        try {
252
+            return $this->testRemoteUrl($this->getRemote() . '/ocs-provider/index.php')
253
+                || $this->testRemoteUrl($this->getRemote() . '/ocs-provider/')
254
+                || $this->testRemoteUrl($this->getRemote() . '/status.php');
255
+        } catch (\Exception $e) {
256
+            return false;
257
+        }
258
+    }
259
+
260
+    /**
261
+     * @param string $url
262
+     * @return bool
263
+     */
264
+    private function testRemoteUrl($url) {
265
+        $cache = $this->memcacheFactory->createDistributed('files_sharing_remote_url');
266
+        if($cache->hasKey($url)) {
267
+            return (bool)$cache->get($url);
268
+        }
269
+
270
+        $client = $this->httpClient->newClient();
271
+        try {
272
+            $result = $client->get($url, [
273
+                'timeout' => 10,
274
+                'connect_timeout' => 10,
275
+            ])->getBody();
276
+            $data = json_decode($result);
277
+            $returnValue = (is_object($data) && !empty($data->version));
278
+        } catch (ConnectException $e) {
279
+            $returnValue = false;
280
+        } catch (ClientException $e) {
281
+            $returnValue = false;
282
+        }
283
+
284
+        $cache->set($url, $returnValue, 60*60*24);
285
+        return $returnValue;
286
+    }
287
+
288
+    /**
289
+     * Whether the remote is an ownCloud/Nextcloud, used since some sharing features are not
290
+     * standardized. Let's use this to detect whether to use it.
291
+     *
292
+     * @return bool
293
+     */
294
+    public function remoteIsOwnCloud() {
295
+        if(defined('PHPUNIT_RUN') || !$this->testRemoteUrl($this->getRemote() . '/status.php')) {
296
+            return false;
297
+        }
298
+        return true;
299
+    }
300
+
301
+    /**
302
+     * @return mixed
303
+     * @throws ForbiddenException
304
+     * @throws NotFoundException
305
+     * @throws \Exception
306
+     */
307
+    public function getShareInfo() {
308
+        $remote = $this->getRemote();
309
+        $token = $this->getToken();
310
+        $password = $this->getPassword();
311
+
312
+        // If remote is not an ownCloud do not try to get any share info
313
+        if(!$this->remoteIsOwnCloud()) {
314
+            return ['status' => 'unsupported'];
315
+        }
316
+
317
+        $url = rtrim($remote, '/') . '/index.php/apps/files_sharing/shareinfo?t=' . $token;
318
+
319
+        // TODO: DI
320
+        $client = \OC::$server->getHTTPClientService()->newClient();
321
+        try {
322
+            $response = $client->post($url, [
323
+                'body' => ['password' => $password],
324
+                'timeout' => 10,
325
+                'connect_timeout' => 10,
326
+            ]);
327
+        } catch (\GuzzleHttp\Exception\RequestException $e) {
328
+            if ($e->getCode() === Http::STATUS_UNAUTHORIZED || $e->getCode() === Http::STATUS_FORBIDDEN) {
329
+                throw new ForbiddenException();
330
+            }
331
+            if ($e->getCode() === Http::STATUS_NOT_FOUND) {
332
+                throw new NotFoundException();
333
+            }
334
+            // throw this to be on the safe side: the share will still be visible
335
+            // in the UI in case the failure is intermittent, and the user will
336
+            // be able to decide whether to remove it if it's really gone
337
+            throw new StorageNotAvailableException();
338
+        }
339
+
340
+        return json_decode($response->getBody(), true);
341
+    }
342
+
343
+    public function getOwner($path) {
344
+        return $this->cloudId->getDisplayId();
345
+    }
346
+
347
+    public function isSharable($path) {
348
+        if (\OCP\Util::isSharingDisabledForUser() || !\OC\Share\Share::isResharingAllowed()) {
349
+            return false;
350
+        }
351
+        return ($this->getPermissions($path) & Constants::PERMISSION_SHARE);
352
+    }
353
+
354
+    public function getPermissions($path) {
355
+        $response = $this->propfind($path);
356
+        // old federated sharing permissions
357
+        if (isset($response['{http://open-collaboration-services.org/ns}share-permissions'])) {
358
+            $permissions = $response['{http://open-collaboration-services.org/ns}share-permissions'];
359
+        } else if (isset($response['{http://open-cloud-mesh.org/ns}share-permissions'])) {
360
+            // permissions provided by the OCM API
361
+            $permissions = $this->ocmPermissions2ncPermissions($response['{http://open-collaboration-services.org/ns}share-permissions']);
362
+        } else {
363
+            // use default permission if remote server doesn't provide the share permissions
364
+            $permissions = $this->getDefaultPermissions($path);
365
+        }
366
+
367
+        return $permissions;
368
+    }
369
+
370
+    public function needsPartFile() {
371
+        return false;
372
+    }
373
+
374
+    /**
375
+     * translate OCM Permissions to Nextcloud permissions
376
+     *
377
+     * @param string $ocmPermissions json encoded OCM permissions
378
+     * @param string $path path to file
379
+     * @return int
380
+     */
381
+    protected function ocmPermissions2ncPermissions($ocmPermissions, $path) {
382
+        try {
383
+            $ocmPermissions = json_decode($ocmPermissions);
384
+            $ncPermissions = 0;
385
+            foreach($ocmPermissions as $permission) {
386
+                switch (strtolower($permission)) {
387
+                    case 'read':
388
+                        $ncPermissions += Constants::PERMISSION_READ;
389
+                        break;
390
+                    case 'write':
391
+                        $ncPermissions += Constants::PERMISSION_CREATE + Constants::PERMISSION_UPDATE;
392
+                        break;
393
+                    case 'share':
394
+                        $ncPermissions += Constants::PERMISSION_SHARE;
395
+                        break;
396
+                    default:
397
+                        throw new \Exception();
398
+                }
399
+            }
400
+        } catch (\Exception $e) {
401
+            $ncPermissions = $this->getDefaultPermissions($path);
402
+        }
403
+
404
+        return $ncPermissions;
405
+    }
406
+
407
+    /**
408
+     * calculate default permissions in case no permissions are provided
409
+     *
410
+     * @param $path
411
+     * @return int
412
+     */
413
+    protected function getDefaultPermissions($path) {
414
+        if ($this->is_dir($path)) {
415
+            $permissions = Constants::PERMISSION_ALL;
416
+        } else {
417
+            $permissions = Constants::PERMISSION_ALL & ~Constants::PERMISSION_CREATE;
418
+        }
419
+
420
+        return $permissions;
421
+    }
422 422
 }
Please login to merge, or discard this patch.
apps/dav/lib/Connector/Sabre/FilesPlugin.php 1 patch
Indentation   +436 added lines, -436 removed lines patch added patch discarded remove patch
@@ -50,444 +50,444 @@
 block discarded – undo
50 50
 
51 51
 class FilesPlugin extends ServerPlugin {
52 52
 
53
-	// namespace
54
-	const NS_OWNCLOUD = 'http://owncloud.org/ns';
55
-	const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
56
-	const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
57
-	const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
58
-	const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
59
-	const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
60
-	const OCM_SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-cloud-mesh.org/ns}share-permissions';
61
-	const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
62
-	const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
63
-	const GETETAG_PROPERTYNAME = '{DAV:}getetag';
64
-	const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
65
-	const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
66
-	const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
67
-	const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
68
-	const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
69
-	const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
70
-	const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
71
-	const IS_ENCRYPTED_PROPERTYNAME = '{http://nextcloud.org/ns}is-encrypted';
72
-
73
-	/**
74
-	 * Reference to main server object
75
-	 *
76
-	 * @var \Sabre\DAV\Server
77
-	 */
78
-	private $server;
79
-
80
-	/**
81
-	 * @var Tree
82
-	 */
83
-	private $tree;
84
-
85
-	/**
86
-	 * Whether this is public webdav.
87
-	 * If true, some returned information will be stripped off.
88
-	 *
89
-	 * @var bool
90
-	 */
91
-	private $isPublic;
92
-
93
-	/**
94
-	 * @var bool
95
-	 */
96
-	private $downloadAttachment;
97
-
98
-	/**
99
-	 * @var IConfig
100
-	 */
101
-	private $config;
102
-
103
-	/**
104
-	 * @var IRequest
105
-	 */
106
-	private $request;
107
-
108
-	/**
109
-	 * @var IPreview
110
-	 */
111
-	private $previewManager;
112
-
113
-	/**
114
-	 * @param Tree $tree
115
-	 * @param IConfig $config
116
-	 * @param IRequest $request
117
-	 * @param IPreview $previewManager
118
-	 * @param bool $isPublic
119
-	 * @param bool $downloadAttachment
120
-	 */
121
-	public function __construct(Tree $tree,
122
-								IConfig $config,
123
-								IRequest $request,
124
-								IPreview $previewManager,
125
-								$isPublic = false,
126
-								$downloadAttachment = true) {
127
-		$this->tree = $tree;
128
-		$this->config = $config;
129
-		$this->request = $request;
130
-		$this->isPublic = $isPublic;
131
-		$this->downloadAttachment = $downloadAttachment;
132
-		$this->previewManager = $previewManager;
133
-	}
134
-
135
-	/**
136
-	 * This initializes the plugin.
137
-	 *
138
-	 * This function is called by \Sabre\DAV\Server, after
139
-	 * addPlugin is called.
140
-	 *
141
-	 * This method should set up the required event subscriptions.
142
-	 *
143
-	 * @param \Sabre\DAV\Server $server
144
-	 * @return void
145
-	 */
146
-	public function initialize(\Sabre\DAV\Server $server) {
147
-		$server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
148
-		$server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
149
-		$server->protectedProperties[] = self::FILEID_PROPERTYNAME;
150
-		$server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
151
-		$server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
152
-		$server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
153
-		$server->protectedProperties[] = self::OCM_SHARE_PERMISSIONS_PROPERTYNAME;
154
-		$server->protectedProperties[] = self::SIZE_PROPERTYNAME;
155
-		$server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
156
-		$server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
157
-		$server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
158
-		$server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
159
-		$server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
160
-		$server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
161
-		$server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
162
-		$server->protectedProperties[] = self::IS_ENCRYPTED_PROPERTYNAME;
163
-
164
-		// normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
165
-		$allowedProperties = ['{DAV:}getetag'];
166
-		$server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
167
-
168
-		$this->server = $server;
169
-		$this->server->on('propFind', array($this, 'handleGetProperties'));
170
-		$this->server->on('propPatch', array($this, 'handleUpdateProperties'));
171
-		$this->server->on('afterBind', array($this, 'sendFileIdHeader'));
172
-		$this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
173
-		$this->server->on('afterMethod:GET', [$this,'httpGet']);
174
-		$this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
175
-		$this->server->on('afterResponse', function($request, ResponseInterface $response) {
176
-			$body = $response->getBody();
177
-			if (is_resource($body)) {
178
-				fclose($body);
179
-			}
180
-		});
181
-		$this->server->on('beforeMove', [$this, 'checkMove']);
182
-	}
183
-
184
-	/**
185
-	 * Plugin that checks if a move can actually be performed.
186
-	 *
187
-	 * @param string $source source path
188
-	 * @param string $destination destination path
189
-	 * @throws Forbidden
190
-	 * @throws NotFound
191
-	 */
192
-	function checkMove($source, $destination) {
193
-		$sourceNode = $this->tree->getNodeForPath($source);
194
-		if (!$sourceNode instanceof Node) {
195
-			return;
196
-		}
197
-		list($sourceDir,) = \Sabre\Uri\split($source);
198
-		list($destinationDir,) = \Sabre\Uri\split($destination);
199
-
200
-		if ($sourceDir !== $destinationDir) {
201
-			$sourceNodeFileInfo = $sourceNode->getFileInfo();
202
-			if ($sourceNodeFileInfo === null) {
203
-				throw new NotFound($source . ' does not exist');
204
- 			}
205
-
206
-			if (!$sourceNodeFileInfo->isDeletable()) {
207
-				throw new Forbidden($source . " cannot be deleted");
208
-			}
209
-		}
210
-	}
211
-
212
-	/**
213
-	 * This sets a cookie to be able to recognize the start of the download
214
-	 * the content must not be longer than 32 characters and must only contain
215
-	 * alphanumeric characters
216
-	 *
217
-	 * @param RequestInterface $request
218
-	 * @param ResponseInterface $response
219
-	 */
220
-	function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
221
-		$queryParams = $request->getQueryParameters();
222
-
223
-		/**
224
-		 * this sets a cookie to be able to recognize the start of the download
225
-		 * the content must not be longer than 32 characters and must only contain
226
-		 * alphanumeric characters
227
-		 */
228
-		if (isset($queryParams['downloadStartSecret'])) {
229
-			$token = $queryParams['downloadStartSecret'];
230
-			if (!isset($token[32])
231
-				&& preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
232
-				// FIXME: use $response->setHeader() instead
233
-				setcookie('ocDownloadStarted', $token, time() + 20, '/');
234
-			}
235
-		}
236
-	}
237
-
238
-	/**
239
-	 * Add headers to file download
240
-	 *
241
-	 * @param RequestInterface $request
242
-	 * @param ResponseInterface $response
243
-	 */
244
-	function httpGet(RequestInterface $request, ResponseInterface $response) {
245
-		// Only handle valid files
246
-		$node = $this->tree->getNodeForPath($request->getPath());
247
-		if (!($node instanceof IFile)) return;
248
-
249
-		// adds a 'Content-Disposition: attachment' header in case no disposition
250
-		// header has been set before
251
-		if ($this->downloadAttachment &&
252
-			$response->getHeader('Content-Disposition') === null) {
253
-			$filename = $node->getName();
254
-			if ($this->request->isUserAgent(
255
-				[
256
-					Request::USER_AGENT_IE,
257
-					Request::USER_AGENT_ANDROID_MOBILE_CHROME,
258
-					Request::USER_AGENT_FREEBOX,
259
-				])) {
260
-				$response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
261
-			} else {
262
-				$response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
263
-													 . '; filename="' . rawurlencode($filename) . '"');
264
-			}
265
-		}
266
-
267
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
268
-			//Add OC-Checksum header
269
-			/** @var $node File */
270
-			$checksum = $node->getChecksum();
271
-			if ($checksum !== null && $checksum !== '') {
272
-				$response->addHeader('OC-Checksum', $checksum);
273
-			}
274
-		}
275
-	}
276
-
277
-	/**
278
-	 * Adds all ownCloud-specific properties
279
-	 *
280
-	 * @param PropFind $propFind
281
-	 * @param \Sabre\DAV\INode $node
282
-	 * @return void
283
-	 */
284
-	public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
285
-
286
-		$httpRequest = $this->server->httpRequest;
287
-
288
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
289
-			/**
290
-			 * This was disabled, because it made dir listing throw an exception,
291
-			 * so users were unable to navigate into folders where one subitem
292
-			 * is blocked by the files_accesscontrol app, see:
293
-			 * https://github.com/nextcloud/files_accesscontrol/issues/65
53
+    // namespace
54
+    const NS_OWNCLOUD = 'http://owncloud.org/ns';
55
+    const NS_NEXTCLOUD = 'http://nextcloud.org/ns';
56
+    const FILEID_PROPERTYNAME = '{http://owncloud.org/ns}id';
57
+    const INTERNAL_FILEID_PROPERTYNAME = '{http://owncloud.org/ns}fileid';
58
+    const PERMISSIONS_PROPERTYNAME = '{http://owncloud.org/ns}permissions';
59
+    const SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-collaboration-services.org/ns}share-permissions';
60
+    const OCM_SHARE_PERMISSIONS_PROPERTYNAME = '{http://open-cloud-mesh.org/ns}share-permissions';
61
+    const DOWNLOADURL_PROPERTYNAME = '{http://owncloud.org/ns}downloadURL';
62
+    const SIZE_PROPERTYNAME = '{http://owncloud.org/ns}size';
63
+    const GETETAG_PROPERTYNAME = '{DAV:}getetag';
64
+    const LASTMODIFIED_PROPERTYNAME = '{DAV:}lastmodified';
65
+    const OWNER_ID_PROPERTYNAME = '{http://owncloud.org/ns}owner-id';
66
+    const OWNER_DISPLAY_NAME_PROPERTYNAME = '{http://owncloud.org/ns}owner-display-name';
67
+    const CHECKSUMS_PROPERTYNAME = '{http://owncloud.org/ns}checksums';
68
+    const DATA_FINGERPRINT_PROPERTYNAME = '{http://owncloud.org/ns}data-fingerprint';
69
+    const HAS_PREVIEW_PROPERTYNAME = '{http://nextcloud.org/ns}has-preview';
70
+    const MOUNT_TYPE_PROPERTYNAME = '{http://nextcloud.org/ns}mount-type';
71
+    const IS_ENCRYPTED_PROPERTYNAME = '{http://nextcloud.org/ns}is-encrypted';
72
+
73
+    /**
74
+     * Reference to main server object
75
+     *
76
+     * @var \Sabre\DAV\Server
77
+     */
78
+    private $server;
79
+
80
+    /**
81
+     * @var Tree
82
+     */
83
+    private $tree;
84
+
85
+    /**
86
+     * Whether this is public webdav.
87
+     * If true, some returned information will be stripped off.
88
+     *
89
+     * @var bool
90
+     */
91
+    private $isPublic;
92
+
93
+    /**
94
+     * @var bool
95
+     */
96
+    private $downloadAttachment;
97
+
98
+    /**
99
+     * @var IConfig
100
+     */
101
+    private $config;
102
+
103
+    /**
104
+     * @var IRequest
105
+     */
106
+    private $request;
107
+
108
+    /**
109
+     * @var IPreview
110
+     */
111
+    private $previewManager;
112
+
113
+    /**
114
+     * @param Tree $tree
115
+     * @param IConfig $config
116
+     * @param IRequest $request
117
+     * @param IPreview $previewManager
118
+     * @param bool $isPublic
119
+     * @param bool $downloadAttachment
120
+     */
121
+    public function __construct(Tree $tree,
122
+                                IConfig $config,
123
+                                IRequest $request,
124
+                                IPreview $previewManager,
125
+                                $isPublic = false,
126
+                                $downloadAttachment = true) {
127
+        $this->tree = $tree;
128
+        $this->config = $config;
129
+        $this->request = $request;
130
+        $this->isPublic = $isPublic;
131
+        $this->downloadAttachment = $downloadAttachment;
132
+        $this->previewManager = $previewManager;
133
+    }
134
+
135
+    /**
136
+     * This initializes the plugin.
137
+     *
138
+     * This function is called by \Sabre\DAV\Server, after
139
+     * addPlugin is called.
140
+     *
141
+     * This method should set up the required event subscriptions.
142
+     *
143
+     * @param \Sabre\DAV\Server $server
144
+     * @return void
145
+     */
146
+    public function initialize(\Sabre\DAV\Server $server) {
147
+        $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc';
148
+        $server->xml->namespaceMap[self::NS_NEXTCLOUD] = 'nc';
149
+        $server->protectedProperties[] = self::FILEID_PROPERTYNAME;
150
+        $server->protectedProperties[] = self::INTERNAL_FILEID_PROPERTYNAME;
151
+        $server->protectedProperties[] = self::PERMISSIONS_PROPERTYNAME;
152
+        $server->protectedProperties[] = self::SHARE_PERMISSIONS_PROPERTYNAME;
153
+        $server->protectedProperties[] = self::OCM_SHARE_PERMISSIONS_PROPERTYNAME;
154
+        $server->protectedProperties[] = self::SIZE_PROPERTYNAME;
155
+        $server->protectedProperties[] = self::DOWNLOADURL_PROPERTYNAME;
156
+        $server->protectedProperties[] = self::OWNER_ID_PROPERTYNAME;
157
+        $server->protectedProperties[] = self::OWNER_DISPLAY_NAME_PROPERTYNAME;
158
+        $server->protectedProperties[] = self::CHECKSUMS_PROPERTYNAME;
159
+        $server->protectedProperties[] = self::DATA_FINGERPRINT_PROPERTYNAME;
160
+        $server->protectedProperties[] = self::HAS_PREVIEW_PROPERTYNAME;
161
+        $server->protectedProperties[] = self::MOUNT_TYPE_PROPERTYNAME;
162
+        $server->protectedProperties[] = self::IS_ENCRYPTED_PROPERTYNAME;
163
+
164
+        // normally these cannot be changed (RFC4918), but we want them modifiable through PROPPATCH
165
+        $allowedProperties = ['{DAV:}getetag'];
166
+        $server->protectedProperties = array_diff($server->protectedProperties, $allowedProperties);
167
+
168
+        $this->server = $server;
169
+        $this->server->on('propFind', array($this, 'handleGetProperties'));
170
+        $this->server->on('propPatch', array($this, 'handleUpdateProperties'));
171
+        $this->server->on('afterBind', array($this, 'sendFileIdHeader'));
172
+        $this->server->on('afterWriteContent', array($this, 'sendFileIdHeader'));
173
+        $this->server->on('afterMethod:GET', [$this,'httpGet']);
174
+        $this->server->on('afterMethod:GET', array($this, 'handleDownloadToken'));
175
+        $this->server->on('afterResponse', function($request, ResponseInterface $response) {
176
+            $body = $response->getBody();
177
+            if (is_resource($body)) {
178
+                fclose($body);
179
+            }
180
+        });
181
+        $this->server->on('beforeMove', [$this, 'checkMove']);
182
+    }
183
+
184
+    /**
185
+     * Plugin that checks if a move can actually be performed.
186
+     *
187
+     * @param string $source source path
188
+     * @param string $destination destination path
189
+     * @throws Forbidden
190
+     * @throws NotFound
191
+     */
192
+    function checkMove($source, $destination) {
193
+        $sourceNode = $this->tree->getNodeForPath($source);
194
+        if (!$sourceNode instanceof Node) {
195
+            return;
196
+        }
197
+        list($sourceDir,) = \Sabre\Uri\split($source);
198
+        list($destinationDir,) = \Sabre\Uri\split($destination);
199
+
200
+        if ($sourceDir !== $destinationDir) {
201
+            $sourceNodeFileInfo = $sourceNode->getFileInfo();
202
+            if ($sourceNodeFileInfo === null) {
203
+                throw new NotFound($source . ' does not exist');
204
+                }
205
+
206
+            if (!$sourceNodeFileInfo->isDeletable()) {
207
+                throw new Forbidden($source . " cannot be deleted");
208
+            }
209
+        }
210
+    }
211
+
212
+    /**
213
+     * This sets a cookie to be able to recognize the start of the download
214
+     * the content must not be longer than 32 characters and must only contain
215
+     * alphanumeric characters
216
+     *
217
+     * @param RequestInterface $request
218
+     * @param ResponseInterface $response
219
+     */
220
+    function handleDownloadToken(RequestInterface $request, ResponseInterface $response) {
221
+        $queryParams = $request->getQueryParameters();
222
+
223
+        /**
224
+         * this sets a cookie to be able to recognize the start of the download
225
+         * the content must not be longer than 32 characters and must only contain
226
+         * alphanumeric characters
227
+         */
228
+        if (isset($queryParams['downloadStartSecret'])) {
229
+            $token = $queryParams['downloadStartSecret'];
230
+            if (!isset($token[32])
231
+                && preg_match('!^[a-zA-Z0-9]+$!', $token) === 1) {
232
+                // FIXME: use $response->setHeader() instead
233
+                setcookie('ocDownloadStarted', $token, time() + 20, '/');
234
+            }
235
+        }
236
+    }
237
+
238
+    /**
239
+     * Add headers to file download
240
+     *
241
+     * @param RequestInterface $request
242
+     * @param ResponseInterface $response
243
+     */
244
+    function httpGet(RequestInterface $request, ResponseInterface $response) {
245
+        // Only handle valid files
246
+        $node = $this->tree->getNodeForPath($request->getPath());
247
+        if (!($node instanceof IFile)) return;
248
+
249
+        // adds a 'Content-Disposition: attachment' header in case no disposition
250
+        // header has been set before
251
+        if ($this->downloadAttachment &&
252
+            $response->getHeader('Content-Disposition') === null) {
253
+            $filename = $node->getName();
254
+            if ($this->request->isUserAgent(
255
+                [
256
+                    Request::USER_AGENT_IE,
257
+                    Request::USER_AGENT_ANDROID_MOBILE_CHROME,
258
+                    Request::USER_AGENT_FREEBOX,
259
+                ])) {
260
+                $response->addHeader('Content-Disposition', 'attachment; filename="' . rawurlencode($filename) . '"');
261
+            } else {
262
+                $response->addHeader('Content-Disposition', 'attachment; filename*=UTF-8\'\'' . rawurlencode($filename)
263
+                                                        . '; filename="' . rawurlencode($filename) . '"');
264
+            }
265
+        }
266
+
267
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
268
+            //Add OC-Checksum header
269
+            /** @var $node File */
270
+            $checksum = $node->getChecksum();
271
+            if ($checksum !== null && $checksum !== '') {
272
+                $response->addHeader('OC-Checksum', $checksum);
273
+            }
274
+        }
275
+    }
276
+
277
+    /**
278
+     * Adds all ownCloud-specific properties
279
+     *
280
+     * @param PropFind $propFind
281
+     * @param \Sabre\DAV\INode $node
282
+     * @return void
283
+     */
284
+    public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) {
285
+
286
+        $httpRequest = $this->server->httpRequest;
287
+
288
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
289
+            /**
290
+             * This was disabled, because it made dir listing throw an exception,
291
+             * so users were unable to navigate into folders where one subitem
292
+             * is blocked by the files_accesscontrol app, see:
293
+             * https://github.com/nextcloud/files_accesscontrol/issues/65
294 294
 			if (!$node->getFileInfo()->isReadable()) {
295 295
 				// avoid detecting files through this means
296 296
 				throw new NotFound();
297 297
 			}
298
-			 */
299
-
300
-			$propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
301
-				return $node->getFileId();
302
-			});
303
-
304
-			$propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
305
-				return $node->getInternalFileId();
306
-			});
307
-
308
-			$propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
309
-				$perms = $node->getDavPermissions();
310
-				if ($this->isPublic) {
311
-					// remove mount information
312
-					$perms = str_replace(['S', 'M'], '', $perms);
313
-				}
314
-				return $perms;
315
-			});
316
-
317
-			$propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
318
-				return $node->getSharePermissions(
319
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
320
-				);
321
-			});
322
-
323
-			$propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
324
-				$ncPermissions = $node->getSharePermissions(
325
-					$httpRequest->getRawServerValue('PHP_AUTH_USER')
326
-				);
327
-				$ocmPermissions = $this->ncPermissions2ocmPermissions($ncPermissions);
328
-				return json_encode($ocmPermissions);
329
-			});
330
-
331
-			$propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
332
-				return $node->getETag();
333
-			});
334
-
335
-			$propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
336
-				$owner = $node->getOwner();
337
-				if (!$owner) {
338
-					return null;
339
-				} else {
340
-					return $owner->getUID();
341
-				}
342
-			});
343
-			$propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
344
-				$owner = $node->getOwner();
345
-				if (!$owner) {
346
-					return null;
347
-				} else {
348
-					return $owner->getDisplayName();
349
-				}
350
-			});
351
-
352
-			$propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
353
-				return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
354
-			});
355
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
356
-				return $node->getSize();
357
-			});
358
-			$propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
359
-				return $node->getFileInfo()->getMountPoint()->getMountType();
360
-			});
361
-		}
362
-
363
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
364
-			$propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
365
-				return $this->config->getSystemValue('data-fingerprint', '');
366
-			});
367
-		}
368
-
369
-		if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
370
-			$propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
371
-				/** @var $node \OCA\DAV\Connector\Sabre\File */
372
-				try {
373
-					$directDownloadUrl = $node->getDirectDownload();
374
-					if (isset($directDownloadUrl['url'])) {
375
-						return $directDownloadUrl['url'];
376
-					}
377
-				} catch (StorageNotAvailableException $e) {
378
-					return false;
379
-				} catch (ForbiddenException $e) {
380
-					return false;
381
-				}
382
-				return false;
383
-			});
384
-
385
-			$propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
386
-				$checksum = $node->getChecksum();
387
-				if ($checksum === NULL || $checksum === '') {
388
-					return null;
389
-				}
390
-
391
-				return new ChecksumList($checksum);
392
-			});
393
-
394
-		}
395
-
396
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
397
-			$propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
398
-				return $node->getSize();
399
-			});
400
-
401
-			$propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function() use ($node) {
402
-				return $node->getFileInfo()->isEncrypted() ? '1' : '0';
403
-			});
404
-		}
405
-	}
406
-
407
-	/**
408
-	 * translate Nextcloud permissions to OCM Permissions
409
-	 *
410
-	 * @param $ncPermissions
411
-	 * @return array
412
-	 */
413
-	protected function ncPermissions2ocmPermissions($ncPermissions) {
414
-
415
-		$ocmPermissions = [];
416
-
417
-		if ($ncPermissions & Constants::PERMISSION_SHARE) {
418
-			$ocmPermissions[] = 'share';
419
-		}
420
-
421
-		if ($ncPermissions & Constants::PERMISSION_READ) {
422
-			$ocmPermissions[] = 'read';
423
-		}
424
-
425
-		if (($ncPermissions & Constants::PERMISSION_CREATE) ||
426
-			($ncPermissions & Constants::PERMISSION_UPDATE)) {
427
-			$ocmPermissions[] = 'write';
428
-		}
429
-
430
-		return $ocmPermissions;
431
-
432
-	}
433
-
434
-	/**
435
-	 * Update ownCloud-specific properties
436
-	 *
437
-	 * @param string $path
438
-	 * @param PropPatch $propPatch
439
-	 *
440
-	 * @return void
441
-	 */
442
-	public function handleUpdateProperties($path, PropPatch $propPatch) {
443
-		$node = $this->tree->getNodeForPath($path);
444
-		if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
445
-			return;
446
-		}
447
-
448
-		$propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
449
-			if (empty($time)) {
450
-				return false;
451
-			}
452
-			$node->touch($time);
453
-			return true;
454
-		});
455
-		$propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
456
-			if (empty($etag)) {
457
-				return false;
458
-			}
459
-			if ($node->setEtag($etag) !== -1) {
460
-				return true;
461
-			}
462
-			return false;
463
-		});
464
-	}
465
-
466
-	/**
467
-	 * @param string $filePath
468
-	 * @param \Sabre\DAV\INode $node
469
-	 * @throws \Sabre\DAV\Exception\BadRequest
470
-	 */
471
-	public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
472
-		// chunked upload handling
473
-		if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
474
-			list($path, $name) = \Sabre\Uri\split($filePath);
475
-			$info = \OC_FileChunking::decodeName($name);
476
-			if (!empty($info)) {
477
-				$filePath = $path . '/' . $info['name'];
478
-			}
479
-		}
480
-
481
-		// we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
482
-		if (!$this->server->tree->nodeExists($filePath)) {
483
-			return;
484
-		}
485
-		$node = $this->server->tree->getNodeForPath($filePath);
486
-		if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
487
-			$fileId = $node->getFileId();
488
-			if (!is_null($fileId)) {
489
-				$this->server->httpResponse->setHeader('OC-FileId', $fileId);
490
-			}
491
-		}
492
-	}
298
+             */
299
+
300
+            $propFind->handle(self::FILEID_PROPERTYNAME, function() use ($node) {
301
+                return $node->getFileId();
302
+            });
303
+
304
+            $propFind->handle(self::INTERNAL_FILEID_PROPERTYNAME, function() use ($node) {
305
+                return $node->getInternalFileId();
306
+            });
307
+
308
+            $propFind->handle(self::PERMISSIONS_PROPERTYNAME, function() use ($node) {
309
+                $perms = $node->getDavPermissions();
310
+                if ($this->isPublic) {
311
+                    // remove mount information
312
+                    $perms = str_replace(['S', 'M'], '', $perms);
313
+                }
314
+                return $perms;
315
+            });
316
+
317
+            $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
318
+                return $node->getSharePermissions(
319
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
320
+                );
321
+            });
322
+
323
+            $propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function() use ($node, $httpRequest) {
324
+                $ncPermissions = $node->getSharePermissions(
325
+                    $httpRequest->getRawServerValue('PHP_AUTH_USER')
326
+                );
327
+                $ocmPermissions = $this->ncPermissions2ocmPermissions($ncPermissions);
328
+                return json_encode($ocmPermissions);
329
+            });
330
+
331
+            $propFind->handle(self::GETETAG_PROPERTYNAME, function() use ($node) {
332
+                return $node->getETag();
333
+            });
334
+
335
+            $propFind->handle(self::OWNER_ID_PROPERTYNAME, function() use ($node) {
336
+                $owner = $node->getOwner();
337
+                if (!$owner) {
338
+                    return null;
339
+                } else {
340
+                    return $owner->getUID();
341
+                }
342
+            });
343
+            $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function() use ($node) {
344
+                $owner = $node->getOwner();
345
+                if (!$owner) {
346
+                    return null;
347
+                } else {
348
+                    return $owner->getDisplayName();
349
+                }
350
+            });
351
+
352
+            $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) {
353
+                return json_encode($this->previewManager->isAvailable($node->getFileInfo()));
354
+            });
355
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
356
+                return $node->getSize();
357
+            });
358
+            $propFind->handle(self::MOUNT_TYPE_PROPERTYNAME, function () use ($node) {
359
+                return $node->getFileInfo()->getMountPoint()->getMountType();
360
+            });
361
+        }
362
+
363
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
364
+            $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function() use ($node) {
365
+                return $this->config->getSystemValue('data-fingerprint', '');
366
+            });
367
+        }
368
+
369
+        if ($node instanceof \OCA\DAV\Connector\Sabre\File) {
370
+            $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function() use ($node) {
371
+                /** @var $node \OCA\DAV\Connector\Sabre\File */
372
+                try {
373
+                    $directDownloadUrl = $node->getDirectDownload();
374
+                    if (isset($directDownloadUrl['url'])) {
375
+                        return $directDownloadUrl['url'];
376
+                    }
377
+                } catch (StorageNotAvailableException $e) {
378
+                    return false;
379
+                } catch (ForbiddenException $e) {
380
+                    return false;
381
+                }
382
+                return false;
383
+            });
384
+
385
+            $propFind->handle(self::CHECKSUMS_PROPERTYNAME, function() use ($node) {
386
+                $checksum = $node->getChecksum();
387
+                if ($checksum === NULL || $checksum === '') {
388
+                    return null;
389
+                }
390
+
391
+                return new ChecksumList($checksum);
392
+            });
393
+
394
+        }
395
+
396
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Directory) {
397
+            $propFind->handle(self::SIZE_PROPERTYNAME, function() use ($node) {
398
+                return $node->getSize();
399
+            });
400
+
401
+            $propFind->handle(self::IS_ENCRYPTED_PROPERTYNAME, function() use ($node) {
402
+                return $node->getFileInfo()->isEncrypted() ? '1' : '0';
403
+            });
404
+        }
405
+    }
406
+
407
+    /**
408
+     * translate Nextcloud permissions to OCM Permissions
409
+     *
410
+     * @param $ncPermissions
411
+     * @return array
412
+     */
413
+    protected function ncPermissions2ocmPermissions($ncPermissions) {
414
+
415
+        $ocmPermissions = [];
416
+
417
+        if ($ncPermissions & Constants::PERMISSION_SHARE) {
418
+            $ocmPermissions[] = 'share';
419
+        }
420
+
421
+        if ($ncPermissions & Constants::PERMISSION_READ) {
422
+            $ocmPermissions[] = 'read';
423
+        }
424
+
425
+        if (($ncPermissions & Constants::PERMISSION_CREATE) ||
426
+            ($ncPermissions & Constants::PERMISSION_UPDATE)) {
427
+            $ocmPermissions[] = 'write';
428
+        }
429
+
430
+        return $ocmPermissions;
431
+
432
+    }
433
+
434
+    /**
435
+     * Update ownCloud-specific properties
436
+     *
437
+     * @param string $path
438
+     * @param PropPatch $propPatch
439
+     *
440
+     * @return void
441
+     */
442
+    public function handleUpdateProperties($path, PropPatch $propPatch) {
443
+        $node = $this->tree->getNodeForPath($path);
444
+        if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) {
445
+            return;
446
+        }
447
+
448
+        $propPatch->handle(self::LASTMODIFIED_PROPERTYNAME, function($time) use ($node) {
449
+            if (empty($time)) {
450
+                return false;
451
+            }
452
+            $node->touch($time);
453
+            return true;
454
+        });
455
+        $propPatch->handle(self::GETETAG_PROPERTYNAME, function($etag) use ($node) {
456
+            if (empty($etag)) {
457
+                return false;
458
+            }
459
+            if ($node->setEtag($etag) !== -1) {
460
+                return true;
461
+            }
462
+            return false;
463
+        });
464
+    }
465
+
466
+    /**
467
+     * @param string $filePath
468
+     * @param \Sabre\DAV\INode $node
469
+     * @throws \Sabre\DAV\Exception\BadRequest
470
+     */
471
+    public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) {
472
+        // chunked upload handling
473
+        if (isset($_SERVER['HTTP_OC_CHUNKED'])) {
474
+            list($path, $name) = \Sabre\Uri\split($filePath);
475
+            $info = \OC_FileChunking::decodeName($name);
476
+            if (!empty($info)) {
477
+                $filePath = $path . '/' . $info['name'];
478
+            }
479
+        }
480
+
481
+        // we get the node for the given $filePath here because in case of afterCreateFile $node is the parent folder
482
+        if (!$this->server->tree->nodeExists($filePath)) {
483
+            return;
484
+        }
485
+        $node = $this->server->tree->getNodeForPath($filePath);
486
+        if ($node instanceof \OCA\DAV\Connector\Sabre\Node) {
487
+            $fileId = $node->getFileId();
488
+            if (!is_null($fileId)) {
489
+                $this->server->httpResponse->setHeader('OC-FileId', $fileId);
490
+            }
491
+        }
492
+    }
493 493
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Settings/Admin.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -32,58 +32,58 @@
 block discarded – undo
32 32
 
33 33
 class Admin implements ISettings {
34 34
 
35
-	/** @var FederatedShareProvider */
36
-	private $fedShareProvider;
35
+    /** @var FederatedShareProvider */
36
+    private $fedShareProvider;
37 37
 
38
-	/** @var IConfig */
39
-	private $gsConfig;
38
+    /** @var IConfig */
39
+    private $gsConfig;
40 40
 
41
-	/**
42
-	 * Admin constructor.
43
-	 *
44
-	 * @param FederatedShareProvider $fedShareProvider
45
-	 * @param IConfig $globalScaleConfig
46
-	 */
47
-	public function __construct(FederatedShareProvider $fedShareProvider, IConfig $globalScaleConfig) {
48
-		$this->fedShareProvider = $fedShareProvider;
49
-		$this->gsConfig = $globalScaleConfig;
50
-	}
41
+    /**
42
+     * Admin constructor.
43
+     *
44
+     * @param FederatedShareProvider $fedShareProvider
45
+     * @param IConfig $globalScaleConfig
46
+     */
47
+    public function __construct(FederatedShareProvider $fedShareProvider, IConfig $globalScaleConfig) {
48
+        $this->fedShareProvider = $fedShareProvider;
49
+        $this->gsConfig = $globalScaleConfig;
50
+    }
51 51
 
52
-	/**
53
-	 * @return TemplateResponse
54
-	 */
55
-	public function getForm() {
52
+    /**
53
+     * @return TemplateResponse
54
+     */
55
+    public function getForm() {
56 56
 
57
-		$parameters = [
58
-			'internalOnly' => $this->gsConfig->onlyInternalFederation(),
59
-			'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(),
60
-			'incomingServer2serverShareEnabled' => $this->fedShareProvider->isIncomingServer2serverShareEnabled(),
61
-			'federatedGroupSharingSupported' => $this->fedShareProvider->isFederatedGroupSharingSupported(),
62
-			'outgoingServer2serverGroupShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverGroupShareEnabled(),
63
-			'incomingServer2serverGroupShareEnabled' => $this->fedShareProvider->isIncomingServer2serverGroupShareEnabled(),
64
-			'lookupServerEnabled' => $this->fedShareProvider->isLookupServerQueriesEnabled(),
65
-			'lookupServerUploadEnabled' => $this->fedShareProvider->isLookupServerUploadEnabled(),
66
-		];
57
+        $parameters = [
58
+            'internalOnly' => $this->gsConfig->onlyInternalFederation(),
59
+            'outgoingServer2serverShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverShareEnabled(),
60
+            'incomingServer2serverShareEnabled' => $this->fedShareProvider->isIncomingServer2serverShareEnabled(),
61
+            'federatedGroupSharingSupported' => $this->fedShareProvider->isFederatedGroupSharingSupported(),
62
+            'outgoingServer2serverGroupShareEnabled' => $this->fedShareProvider->isOutgoingServer2serverGroupShareEnabled(),
63
+            'incomingServer2serverGroupShareEnabled' => $this->fedShareProvider->isIncomingServer2serverGroupShareEnabled(),
64
+            'lookupServerEnabled' => $this->fedShareProvider->isLookupServerQueriesEnabled(),
65
+            'lookupServerUploadEnabled' => $this->fedShareProvider->isLookupServerUploadEnabled(),
66
+        ];
67 67
 
68
-		return new TemplateResponse('federatedfilesharing', 'settings-admin', $parameters, '');
69
-	}
68
+        return new TemplateResponse('federatedfilesharing', 'settings-admin', $parameters, '');
69
+    }
70 70
 
71
-	/**
72
-	 * @return string the section ID, e.g. 'sharing'
73
-	 */
74
-	public function getSection() {
75
-		return 'sharing';
76
-	}
71
+    /**
72
+     * @return string the section ID, e.g. 'sharing'
73
+     */
74
+    public function getSection() {
75
+        return 'sharing';
76
+    }
77 77
 
78
-	/**
79
-	 * @return int whether the form should be rather on the top or bottom of
80
-	 * the admin section. The forms are arranged in ascending order of the
81
-	 * priority values. It is required to return a value between 0 and 100.
82
-	 *
83
-	 * E.g.: 70
84
-	 */
85
-	public function getPriority() {
86
-		return 20;
87
-	}
78
+    /**
79
+     * @return int whether the form should be rather on the top or bottom of
80
+     * the admin section. The forms are arranged in ascending order of the
81
+     * priority values. It is required to return a value between 0 and 100.
82
+     *
83
+     * E.g.: 70
84
+     */
85
+    public function getPriority() {
86
+        return 20;
87
+    }
88 88
 
89 89
 }
Please login to merge, or discard this patch.
lib/public/Federation/ICloudFederationProvider.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -39,51 +39,51 @@
 block discarded – undo
39 39
 
40 40
 interface ICloudFederationProvider {
41 41
 
42
-	/**
43
-	 * get the name of the share type, handled by this provider
44
-	 *
45
-	 * @return string
46
-	 *
47
-	 * @since 14.0.0
48
-	 */
49
-	public function getShareType();
42
+    /**
43
+     * get the name of the share type, handled by this provider
44
+     *
45
+     * @return string
46
+     *
47
+     * @since 14.0.0
48
+     */
49
+    public function getShareType();
50 50
 
51
-	/**
52
-	 * share received from another server
53
-	 *
54
-	 * @param ICloudFederationShare $share
55
-	 * @return string provider specific unique ID of the share
56
-	 *
57
-	 * @throws ProviderCouldNotAddShareException
58
-	 *
59
-	 * @since 14.0.0
60
-	 */
61
-	public function shareReceived(ICloudFederationShare $share);
51
+    /**
52
+     * share received from another server
53
+     *
54
+     * @param ICloudFederationShare $share
55
+     * @return string provider specific unique ID of the share
56
+     *
57
+     * @throws ProviderCouldNotAddShareException
58
+     *
59
+     * @since 14.0.0
60
+     */
61
+    public function shareReceived(ICloudFederationShare $share);
62 62
 
63
-	/**
64
-	 * notification received from another server
65
-	 *
66
-	 * @param string $notificationType (e.g SHARE_ACCEPTED)
67
-	 * @param string $providerId share ID
68
-	 * @param array $notification provider specific notification
69
-	 * @return array $data send back to sender
70
-	 *
71
-	 * @throws ShareNotFound
72
-	 * @throws ActionNotSupportedException
73
-	 * @throws BadRequestException
74
-	 * @throws AuthenticationFailedException
75
-	 *
76
-	 * @since 14.0.0
77
-	 */
78
-	public function notificationReceived($notificationType, $providerId, array $notification);
63
+    /**
64
+     * notification received from another server
65
+     *
66
+     * @param string $notificationType (e.g SHARE_ACCEPTED)
67
+     * @param string $providerId share ID
68
+     * @param array $notification provider specific notification
69
+     * @return array $data send back to sender
70
+     *
71
+     * @throws ShareNotFound
72
+     * @throws ActionNotSupportedException
73
+     * @throws BadRequestException
74
+     * @throws AuthenticationFailedException
75
+     *
76
+     * @since 14.0.0
77
+     */
78
+    public function notificationReceived($notificationType, $providerId, array $notification);
79 79
 
80
-	/**
81
-	 * get the supported share types, e.g. "user", "group", etc.
82
-	 *
83
-	 * @return array
84
-	 *
85
-	 * @since 14.0.0
86
-	 */
87
-	public function getSupportedShareTypes();
80
+    /**
81
+     * get the supported share types, e.g. "user", "group", etc.
82
+     *
83
+     * @return array
84
+     *
85
+     * @since 14.0.0
86
+     */
87
+    public function getSupportedShareTypes();
88 88
 
89 89
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1861 added lines, -1861 removed lines patch added patch discarded remove patch
@@ -158,1870 +158,1870 @@
 block discarded – undo
158 158
  * TODO: hookup all manager classes
159 159
  */
160 160
 class Server extends ServerContainer implements IServerContainer {
161
-	/** @var string */
162
-	private $webRoot;
163
-
164
-	/**
165
-	 * @param string $webRoot
166
-	 * @param \OC\Config $config
167
-	 */
168
-	public function __construct($webRoot, \OC\Config $config) {
169
-		parent::__construct();
170
-		$this->webRoot = $webRoot;
171
-
172
-		// To find out if we are running from CLI or not
173
-		$this->registerParameter('isCLI', \OC::$CLI);
174
-
175
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
176
-			return $c;
177
-		});
178
-
179
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
180
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
181
-
182
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
183
-		$this->registerAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
184
-
185
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
186
-		$this->registerAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
187
-
188
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
189
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
190
-
191
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
192
-
193
-
194
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
195
-			return new PreviewManager(
196
-				$c->getConfig(),
197
-				$c->getRootFolder(),
198
-				$c->getAppDataDir('preview'),
199
-				$c->getEventDispatcher(),
200
-				$c->getSession()->get('user_id')
201
-			);
202
-		});
203
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
204
-
205
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
206
-			return new \OC\Preview\Watcher(
207
-				$c->getAppDataDir('preview')
208
-			);
209
-		});
210
-
211
-		$this->registerService('EncryptionManager', function (Server $c) {
212
-			$view = new View();
213
-			$util = new Encryption\Util(
214
-				$view,
215
-				$c->getUserManager(),
216
-				$c->getGroupManager(),
217
-				$c->getConfig()
218
-			);
219
-			return new Encryption\Manager(
220
-				$c->getConfig(),
221
-				$c->getLogger(),
222
-				$c->getL10N('core'),
223
-				new View(),
224
-				$util,
225
-				new ArrayCache()
226
-			);
227
-		});
228
-
229
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
230
-			$util = new Encryption\Util(
231
-				new View(),
232
-				$c->getUserManager(),
233
-				$c->getGroupManager(),
234
-				$c->getConfig()
235
-			);
236
-			return new Encryption\File(
237
-				$util,
238
-				$c->getRootFolder(),
239
-				$c->getShareManager()
240
-			);
241
-		});
242
-
243
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
244
-			$view = new View();
245
-			$util = new Encryption\Util(
246
-				$view,
247
-				$c->getUserManager(),
248
-				$c->getGroupManager(),
249
-				$c->getConfig()
250
-			);
251
-
252
-			return new Encryption\Keys\Storage($view, $util);
253
-		});
254
-		$this->registerService('TagMapper', function (Server $c) {
255
-			return new TagMapper($c->getDatabaseConnection());
256
-		});
257
-
258
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
259
-			$tagMapper = $c->query('TagMapper');
260
-			return new TagManager($tagMapper, $c->getUserSession());
261
-		});
262
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
263
-
264
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
265
-			$config = $c->getConfig();
266
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
267
-			return new $factoryClass($this);
268
-		});
269
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
270
-			return $c->query('SystemTagManagerFactory')->getManager();
271
-		});
272
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
273
-
274
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
275
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
276
-		});
277
-		$this->registerService('RootFolder', function (Server $c) {
278
-			$manager = \OC\Files\Filesystem::getMountManager(null);
279
-			$view = new View();
280
-			$root = new Root(
281
-				$manager,
282
-				$view,
283
-				null,
284
-				$c->getUserMountCache(),
285
-				$this->getLogger(),
286
-				$this->getUserManager()
287
-			);
288
-			$connector = new HookConnector($root, $view);
289
-			$connector->viewToNode();
290
-
291
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
292
-			$previewConnector->connectWatcher();
293
-
294
-			return $root;
295
-		});
296
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
297
-
298
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
299
-			return new LazyRoot(function () use ($c) {
300
-				return $c->query('RootFolder');
301
-			});
302
-		});
303
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
304
-
305
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
306
-			$config = $c->getConfig();
307
-			return new \OC\User\Manager($config);
308
-		});
309
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
310
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
311
-
312
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
313
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
314
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
315
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
316
-			});
317
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
318
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
319
-			});
320
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
321
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
322
-			});
323
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
324
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
325
-			});
326
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
327
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
328
-			});
329
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
330
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
331
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
332
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
333
-			});
334
-			return $groupManager;
335
-		});
336
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
337
-
338
-		$this->registerService(Store::class, function (Server $c) {
339
-			$session = $c->getSession();
340
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
341
-				$tokenProvider = $c->query(IProvider::class);
342
-			} else {
343
-				$tokenProvider = null;
344
-			}
345
-			$logger = $c->getLogger();
346
-			return new Store($session, $logger, $tokenProvider);
347
-		});
348
-		$this->registerAlias(IStore::class, Store::class);
349
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
350
-			$dbConnection = $c->getDatabaseConnection();
351
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
352
-		});
353
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
354
-
355
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
356
-			$manager = $c->getUserManager();
357
-			$session = new \OC\Session\Memory('');
358
-			$timeFactory = new TimeFactory();
359
-			// Token providers might require a working database. This code
360
-			// might however be called when ownCloud is not yet setup.
361
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
362
-				$defaultTokenProvider = $c->query(IProvider::class);
363
-			} else {
364
-				$defaultTokenProvider = null;
365
-			}
366
-
367
-			$dispatcher = $c->getEventDispatcher();
368
-
369
-			$userSession = new \OC\User\Session(
370
-				$manager,
371
-				$session,
372
-				$timeFactory,
373
-				$defaultTokenProvider,
374
-				$c->getConfig(),
375
-				$c->getSecureRandom(),
376
-				$c->getLockdownManager(),
377
-				$c->getLogger()
378
-			);
379
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
380
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
381
-			});
382
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
383
-				/** @var $user \OC\User\User */
384
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
385
-			});
386
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
387
-				/** @var $user \OC\User\User */
388
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
389
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
390
-			});
391
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
392
-				/** @var $user \OC\User\User */
393
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
394
-			});
395
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
396
-				/** @var $user \OC\User\User */
397
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
398
-			});
399
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
400
-				/** @var $user \OC\User\User */
401
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
402
-			});
403
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
404
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
405
-			});
406
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
407
-				/** @var $user \OC\User\User */
408
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
409
-			});
410
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
411
-				/** @var $user \OC\User\User */
412
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
413
-			});
414
-			$userSession->listen('\OC\User', 'logout', function () {
415
-				\OC_Hook::emit('OC_User', 'logout', array());
416
-			});
417
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
418
-				/** @var $user \OC\User\User */
419
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
420
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
421
-			});
422
-			return $userSession;
423
-		});
424
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
425
-
426
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
427
-
428
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
429
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
430
-
431
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
432
-			return new \OC\AllConfig(
433
-				$c->getSystemConfig()
434
-			);
435
-		});
436
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
437
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
438
-
439
-		$this->registerService('SystemConfig', function ($c) use ($config) {
440
-			return new \OC\SystemConfig($config);
441
-		});
442
-
443
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
444
-			return new \OC\AppConfig($c->getDatabaseConnection());
445
-		});
446
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
447
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
448
-
449
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
450
-			return new \OC\L10N\Factory(
451
-				$c->getConfig(),
452
-				$c->getRequest(),
453
-				$c->getUserSession(),
454
-				\OC::$SERVERROOT
455
-			);
456
-		});
457
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
458
-
459
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
460
-			$config = $c->getConfig();
461
-			$cacheFactory = $c->getMemCacheFactory();
462
-			$request = $c->getRequest();
463
-			return new \OC\URLGenerator(
464
-				$config,
465
-				$cacheFactory,
466
-				$request
467
-			);
468
-		});
469
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
470
-
471
-		$this->registerAlias('AppFetcher', AppFetcher::class);
472
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
473
-
474
-		$this->registerService(\OCP\ICache::class, function ($c) {
475
-			return new Cache\File();
476
-		});
477
-		$this->registerAlias('UserCache', \OCP\ICache::class);
478
-
479
-		$this->registerService(Factory::class, function (Server $c) {
480
-
481
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
482
-				ArrayCache::class,
483
-				ArrayCache::class,
484
-				ArrayCache::class
485
-			);
486
-			$config = $c->getConfig();
487
-			$request = $c->getRequest();
488
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
489
-
490
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
491
-				$v = \OC_App::getAppVersions();
492
-				$v['core'] = implode(',', \OC_Util::getVersion());
493
-				$version = implode(',', $v);
494
-				$instanceId = \OC_Util::getInstanceId();
495
-				$path = \OC::$SERVERROOT;
496
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
497
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
498
-					$config->getSystemValue('memcache.local', null),
499
-					$config->getSystemValue('memcache.distributed', null),
500
-					$config->getSystemValue('memcache.locking', null)
501
-				);
502
-			}
503
-			return $arrayCacheFactory;
504
-
505
-		});
506
-		$this->registerAlias('MemCacheFactory', Factory::class);
507
-		$this->registerAlias(ICacheFactory::class, Factory::class);
508
-
509
-		$this->registerService('RedisFactory', function (Server $c) {
510
-			$systemConfig = $c->getSystemConfig();
511
-			return new RedisFactory($systemConfig);
512
-		});
513
-
514
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
515
-			return new \OC\Activity\Manager(
516
-				$c->getRequest(),
517
-				$c->getUserSession(),
518
-				$c->getConfig(),
519
-				$c->query(IValidator::class)
520
-			);
521
-		});
522
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
523
-
524
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
525
-			return new \OC\Activity\EventMerger(
526
-				$c->getL10N('lib')
527
-			);
528
-		});
529
-		$this->registerAlias(IValidator::class, Validator::class);
530
-
531
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
532
-			return new AvatarManager(
533
-				$c->query(\OC\User\Manager::class),
534
-				$c->getAppDataDir('avatar'),
535
-				$c->getL10N('lib'),
536
-				$c->getLogger(),
537
-				$c->getConfig()
538
-			);
539
-		});
540
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
541
-
542
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
543
-
544
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
545
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
546
-			$factory = new LogFactory($c, $this->getSystemConfig());
547
-			$logger = $factory->get($logType);
548
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
549
-
550
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
551
-		});
552
-		$this->registerAlias('Logger', \OCP\ILogger::class);
553
-
554
-		$this->registerService(ILogFactory::class, function (Server $c) {
555
-			return new LogFactory($c, $this->getSystemConfig());
556
-		});
557
-
558
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
559
-			$config = $c->getConfig();
560
-			return new \OC\BackgroundJob\JobList(
561
-				$c->getDatabaseConnection(),
562
-				$config,
563
-				new TimeFactory()
564
-			);
565
-		});
566
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
567
-
568
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
569
-			$cacheFactory = $c->getMemCacheFactory();
570
-			$logger = $c->getLogger();
571
-			if ($cacheFactory->isLocalCacheAvailable()) {
572
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
573
-			} else {
574
-				$router = new \OC\Route\Router($logger);
575
-			}
576
-			return $router;
577
-		});
578
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
579
-
580
-		$this->registerService(\OCP\ISearch::class, function ($c) {
581
-			return new Search();
582
-		});
583
-		$this->registerAlias('Search', \OCP\ISearch::class);
584
-
585
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
586
-			return new \OC\Security\RateLimiting\Limiter(
587
-				$this->getUserSession(),
588
-				$this->getRequest(),
589
-				new \OC\AppFramework\Utility\TimeFactory(),
590
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
591
-			);
592
-		});
593
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
594
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
595
-				$this->getMemCacheFactory(),
596
-				new \OC\AppFramework\Utility\TimeFactory()
597
-			);
598
-		});
599
-
600
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
601
-			return new SecureRandom();
602
-		});
603
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
604
-
605
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
606
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
607
-		});
608
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
609
-
610
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
611
-			return new Hasher($c->getConfig());
612
-		});
613
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
614
-
615
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
616
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
617
-		});
618
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
619
-
620
-		$this->registerService(IDBConnection::class, function (Server $c) {
621
-			$systemConfig = $c->getSystemConfig();
622
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
623
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
624
-			if (!$factory->isValidType($type)) {
625
-				throw new \OC\DatabaseException('Invalid database type');
626
-			}
627
-			$connectionParams = $factory->createConnectionParams();
628
-			$connection = $factory->getConnection($type, $connectionParams);
629
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
630
-			return $connection;
631
-		});
632
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
633
-
634
-
635
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
636
-			$user = \OC_User::getUser();
637
-			$uid = $user ? $user : null;
638
-			return new ClientService(
639
-				$c->getConfig(),
640
-				new \OC\Security\CertificateManager(
641
-					$uid,
642
-					new View(),
643
-					$c->getConfig(),
644
-					$c->getLogger(),
645
-					$c->getSecureRandom()
646
-				)
647
-			);
648
-		});
649
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
650
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
651
-			$eventLogger = new EventLogger();
652
-			if ($c->getSystemConfig()->getValue('debug', false)) {
653
-				// In debug mode, module is being activated by default
654
-				$eventLogger->activate();
655
-			}
656
-			return $eventLogger;
657
-		});
658
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
659
-
660
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
661
-			$queryLogger = new QueryLogger();
662
-			if ($c->getSystemConfig()->getValue('debug', false)) {
663
-				// In debug mode, module is being activated by default
664
-				$queryLogger->activate();
665
-			}
666
-			return $queryLogger;
667
-		});
668
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
669
-
670
-		$this->registerService(TempManager::class, function (Server $c) {
671
-			return new TempManager(
672
-				$c->getLogger(),
673
-				$c->getConfig()
674
-			);
675
-		});
676
-		$this->registerAlias('TempManager', TempManager::class);
677
-		$this->registerAlias(ITempManager::class, TempManager::class);
678
-
679
-		$this->registerService(AppManager::class, function (Server $c) {
680
-			return new \OC\App\AppManager(
681
-				$c->getUserSession(),
682
-				$c->query(\OC\AppConfig::class),
683
-				$c->getGroupManager(),
684
-				$c->getMemCacheFactory(),
685
-				$c->getEventDispatcher()
686
-			);
687
-		});
688
-		$this->registerAlias('AppManager', AppManager::class);
689
-		$this->registerAlias(IAppManager::class, AppManager::class);
690
-
691
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
692
-			return new DateTimeZone(
693
-				$c->getConfig(),
694
-				$c->getSession()
695
-			);
696
-		});
697
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
698
-
699
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
700
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
701
-
702
-			return new DateTimeFormatter(
703
-				$c->getDateTimeZone()->getTimeZone(),
704
-				$c->getL10N('lib', $language)
705
-			);
706
-		});
707
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
708
-
709
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
710
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
711
-			$listener = new UserMountCacheListener($mountCache);
712
-			$listener->listen($c->getUserManager());
713
-			return $mountCache;
714
-		});
715
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
716
-
717
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
718
-			$loader = \OC\Files\Filesystem::getLoader();
719
-			$mountCache = $c->query('UserMountCache');
720
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
721
-
722
-			// builtin providers
723
-
724
-			$config = $c->getConfig();
725
-			$manager->registerProvider(new CacheMountProvider($config));
726
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
727
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
728
-
729
-			return $manager;
730
-		});
731
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
732
-
733
-		$this->registerService('IniWrapper', function ($c) {
734
-			return new IniGetWrapper();
735
-		});
736
-		$this->registerService('AsyncCommandBus', function (Server $c) {
737
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
738
-			if ($busClass) {
739
-				list($app, $class) = explode('::', $busClass, 2);
740
-				if ($c->getAppManager()->isInstalled($app)) {
741
-					\OC_App::loadApp($app);
742
-					return $c->query($class);
743
-				} else {
744
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
745
-				}
746
-			} else {
747
-				$jobList = $c->getJobList();
748
-				return new CronBus($jobList);
749
-			}
750
-		});
751
-		$this->registerService('TrustedDomainHelper', function ($c) {
752
-			return new TrustedDomainHelper($this->getConfig());
753
-		});
754
-		$this->registerService('Throttler', function (Server $c) {
755
-			return new Throttler(
756
-				$c->getDatabaseConnection(),
757
-				new TimeFactory(),
758
-				$c->getLogger(),
759
-				$c->getConfig()
760
-			);
761
-		});
762
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
763
-			// IConfig and IAppManager requires a working database. This code
764
-			// might however be called when ownCloud is not yet setup.
765
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
766
-				$config = $c->getConfig();
767
-				$appManager = $c->getAppManager();
768
-			} else {
769
-				$config = null;
770
-				$appManager = null;
771
-			}
772
-
773
-			return new Checker(
774
-				new EnvironmentHelper(),
775
-				new FileAccessHelper(),
776
-				new AppLocator(),
777
-				$config,
778
-				$c->getMemCacheFactory(),
779
-				$appManager,
780
-				$c->getTempManager()
781
-			);
782
-		});
783
-		$this->registerService(\OCP\IRequest::class, function ($c) {
784
-			if (isset($this['urlParams'])) {
785
-				$urlParams = $this['urlParams'];
786
-			} else {
787
-				$urlParams = [];
788
-			}
789
-
790
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
791
-				&& in_array('fakeinput', stream_get_wrappers())
792
-			) {
793
-				$stream = 'fakeinput://data';
794
-			} else {
795
-				$stream = 'php://input';
796
-			}
797
-
798
-			return new Request(
799
-				[
800
-					'get' => $_GET,
801
-					'post' => $_POST,
802
-					'files' => $_FILES,
803
-					'server' => $_SERVER,
804
-					'env' => $_ENV,
805
-					'cookies' => $_COOKIE,
806
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
807
-						? $_SERVER['REQUEST_METHOD']
808
-						: '',
809
-					'urlParams' => $urlParams,
810
-				],
811
-				$this->getSecureRandom(),
812
-				$this->getConfig(),
813
-				$this->getCsrfTokenManager(),
814
-				$stream
815
-			);
816
-		});
817
-		$this->registerAlias('Request', \OCP\IRequest::class);
818
-
819
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
820
-			return new Mailer(
821
-				$c->getConfig(),
822
-				$c->getLogger(),
823
-				$c->query(Defaults::class),
824
-				$c->getURLGenerator(),
825
-				$c->getL10N('lib')
826
-			);
827
-		});
828
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
829
-
830
-		$this->registerService('LDAPProvider', function (Server $c) {
831
-			$config = $c->getConfig();
832
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
833
-			if (is_null($factoryClass)) {
834
-				throw new \Exception('ldapProviderFactory not set');
835
-			}
836
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
837
-			$factory = new $factoryClass($this);
838
-			return $factory->getLDAPProvider();
839
-		});
840
-		$this->registerService(ILockingProvider::class, function (Server $c) {
841
-			$ini = $c->getIniWrapper();
842
-			$config = $c->getConfig();
843
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
844
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
845
-				/** @var \OC\Memcache\Factory $memcacheFactory */
846
-				$memcacheFactory = $c->getMemCacheFactory();
847
-				$memcache = $memcacheFactory->createLocking('lock');
848
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
849
-					return new MemcacheLockingProvider($memcache, $ttl);
850
-				}
851
-				return new DBLockingProvider(
852
-					$c->getDatabaseConnection(),
853
-					$c->getLogger(),
854
-					new TimeFactory(),
855
-					$ttl,
856
-					!\OC::$CLI
857
-				);
858
-			}
859
-			return new NoopLockingProvider();
860
-		});
861
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
862
-
863
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
864
-			return new \OC\Files\Mount\Manager();
865
-		});
866
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
867
-
868
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
869
-			return new \OC\Files\Type\Detection(
870
-				$c->getURLGenerator(),
871
-				\OC::$configDir,
872
-				\OC::$SERVERROOT . '/resources/config/'
873
-			);
874
-		});
875
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
876
-
877
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
878
-			return new \OC\Files\Type\Loader(
879
-				$c->getDatabaseConnection()
880
-			);
881
-		});
882
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
883
-		$this->registerService(BundleFetcher::class, function () {
884
-			return new BundleFetcher($this->getL10N('lib'));
885
-		});
886
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
887
-			return new Manager(
888
-				$c->query(IValidator::class)
889
-			);
890
-		});
891
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
892
-
893
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
894
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
895
-			$manager->registerCapability(function () use ($c) {
896
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
897
-			});
898
-			$manager->registerCapability(function () use ($c) {
899
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
900
-			});
901
-			return $manager;
902
-		});
903
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
904
-
905
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
906
-			$config = $c->getConfig();
907
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
908
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
909
-			$factory = new $factoryClass($this);
910
-			$manager = $factory->getManager();
911
-
912
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
913
-				$manager = $c->getUserManager();
914
-				$user = $manager->get($id);
915
-				if(is_null($user)) {
916
-					$l = $c->getL10N('core');
917
-					$displayName = $l->t('Unknown user');
918
-				} else {
919
-					$displayName = $user->getDisplayName();
920
-				}
921
-				return $displayName;
922
-			});
923
-
924
-			return $manager;
925
-		});
926
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
927
-
928
-		$this->registerService('ThemingDefaults', function (Server $c) {
929
-			/*
161
+    /** @var string */
162
+    private $webRoot;
163
+
164
+    /**
165
+     * @param string $webRoot
166
+     * @param \OC\Config $config
167
+     */
168
+    public function __construct($webRoot, \OC\Config $config) {
169
+        parent::__construct();
170
+        $this->webRoot = $webRoot;
171
+
172
+        // To find out if we are running from CLI or not
173
+        $this->registerParameter('isCLI', \OC::$CLI);
174
+
175
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
176
+            return $c;
177
+        });
178
+
179
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
180
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
181
+
182
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
183
+        $this->registerAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
184
+
185
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
186
+        $this->registerAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
187
+
188
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
189
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
190
+
191
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
192
+
193
+
194
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
195
+            return new PreviewManager(
196
+                $c->getConfig(),
197
+                $c->getRootFolder(),
198
+                $c->getAppDataDir('preview'),
199
+                $c->getEventDispatcher(),
200
+                $c->getSession()->get('user_id')
201
+            );
202
+        });
203
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
204
+
205
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
206
+            return new \OC\Preview\Watcher(
207
+                $c->getAppDataDir('preview')
208
+            );
209
+        });
210
+
211
+        $this->registerService('EncryptionManager', function (Server $c) {
212
+            $view = new View();
213
+            $util = new Encryption\Util(
214
+                $view,
215
+                $c->getUserManager(),
216
+                $c->getGroupManager(),
217
+                $c->getConfig()
218
+            );
219
+            return new Encryption\Manager(
220
+                $c->getConfig(),
221
+                $c->getLogger(),
222
+                $c->getL10N('core'),
223
+                new View(),
224
+                $util,
225
+                new ArrayCache()
226
+            );
227
+        });
228
+
229
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
230
+            $util = new Encryption\Util(
231
+                new View(),
232
+                $c->getUserManager(),
233
+                $c->getGroupManager(),
234
+                $c->getConfig()
235
+            );
236
+            return new Encryption\File(
237
+                $util,
238
+                $c->getRootFolder(),
239
+                $c->getShareManager()
240
+            );
241
+        });
242
+
243
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
244
+            $view = new View();
245
+            $util = new Encryption\Util(
246
+                $view,
247
+                $c->getUserManager(),
248
+                $c->getGroupManager(),
249
+                $c->getConfig()
250
+            );
251
+
252
+            return new Encryption\Keys\Storage($view, $util);
253
+        });
254
+        $this->registerService('TagMapper', function (Server $c) {
255
+            return new TagMapper($c->getDatabaseConnection());
256
+        });
257
+
258
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
259
+            $tagMapper = $c->query('TagMapper');
260
+            return new TagManager($tagMapper, $c->getUserSession());
261
+        });
262
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
263
+
264
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
265
+            $config = $c->getConfig();
266
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
267
+            return new $factoryClass($this);
268
+        });
269
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
270
+            return $c->query('SystemTagManagerFactory')->getManager();
271
+        });
272
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
273
+
274
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
275
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
276
+        });
277
+        $this->registerService('RootFolder', function (Server $c) {
278
+            $manager = \OC\Files\Filesystem::getMountManager(null);
279
+            $view = new View();
280
+            $root = new Root(
281
+                $manager,
282
+                $view,
283
+                null,
284
+                $c->getUserMountCache(),
285
+                $this->getLogger(),
286
+                $this->getUserManager()
287
+            );
288
+            $connector = new HookConnector($root, $view);
289
+            $connector->viewToNode();
290
+
291
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
292
+            $previewConnector->connectWatcher();
293
+
294
+            return $root;
295
+        });
296
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
297
+
298
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
299
+            return new LazyRoot(function () use ($c) {
300
+                return $c->query('RootFolder');
301
+            });
302
+        });
303
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
304
+
305
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
306
+            $config = $c->getConfig();
307
+            return new \OC\User\Manager($config);
308
+        });
309
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
310
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
311
+
312
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
313
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
314
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
315
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
316
+            });
317
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
318
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
319
+            });
320
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
321
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
322
+            });
323
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
324
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
325
+            });
326
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
327
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
328
+            });
329
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
330
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
331
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
332
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
333
+            });
334
+            return $groupManager;
335
+        });
336
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
337
+
338
+        $this->registerService(Store::class, function (Server $c) {
339
+            $session = $c->getSession();
340
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
341
+                $tokenProvider = $c->query(IProvider::class);
342
+            } else {
343
+                $tokenProvider = null;
344
+            }
345
+            $logger = $c->getLogger();
346
+            return new Store($session, $logger, $tokenProvider);
347
+        });
348
+        $this->registerAlias(IStore::class, Store::class);
349
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
350
+            $dbConnection = $c->getDatabaseConnection();
351
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
352
+        });
353
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
354
+
355
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
356
+            $manager = $c->getUserManager();
357
+            $session = new \OC\Session\Memory('');
358
+            $timeFactory = new TimeFactory();
359
+            // Token providers might require a working database. This code
360
+            // might however be called when ownCloud is not yet setup.
361
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
362
+                $defaultTokenProvider = $c->query(IProvider::class);
363
+            } else {
364
+                $defaultTokenProvider = null;
365
+            }
366
+
367
+            $dispatcher = $c->getEventDispatcher();
368
+
369
+            $userSession = new \OC\User\Session(
370
+                $manager,
371
+                $session,
372
+                $timeFactory,
373
+                $defaultTokenProvider,
374
+                $c->getConfig(),
375
+                $c->getSecureRandom(),
376
+                $c->getLockdownManager(),
377
+                $c->getLogger()
378
+            );
379
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
380
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
381
+            });
382
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
383
+                /** @var $user \OC\User\User */
384
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
385
+            });
386
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
387
+                /** @var $user \OC\User\User */
388
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
389
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
390
+            });
391
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
392
+                /** @var $user \OC\User\User */
393
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
394
+            });
395
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
396
+                /** @var $user \OC\User\User */
397
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
398
+            });
399
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
400
+                /** @var $user \OC\User\User */
401
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
402
+            });
403
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
404
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
405
+            });
406
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
407
+                /** @var $user \OC\User\User */
408
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
409
+            });
410
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
411
+                /** @var $user \OC\User\User */
412
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
413
+            });
414
+            $userSession->listen('\OC\User', 'logout', function () {
415
+                \OC_Hook::emit('OC_User', 'logout', array());
416
+            });
417
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
418
+                /** @var $user \OC\User\User */
419
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
420
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
421
+            });
422
+            return $userSession;
423
+        });
424
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
425
+
426
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
427
+
428
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
429
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
430
+
431
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
432
+            return new \OC\AllConfig(
433
+                $c->getSystemConfig()
434
+            );
435
+        });
436
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
437
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
438
+
439
+        $this->registerService('SystemConfig', function ($c) use ($config) {
440
+            return new \OC\SystemConfig($config);
441
+        });
442
+
443
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
444
+            return new \OC\AppConfig($c->getDatabaseConnection());
445
+        });
446
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
447
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
448
+
449
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
450
+            return new \OC\L10N\Factory(
451
+                $c->getConfig(),
452
+                $c->getRequest(),
453
+                $c->getUserSession(),
454
+                \OC::$SERVERROOT
455
+            );
456
+        });
457
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
458
+
459
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
460
+            $config = $c->getConfig();
461
+            $cacheFactory = $c->getMemCacheFactory();
462
+            $request = $c->getRequest();
463
+            return new \OC\URLGenerator(
464
+                $config,
465
+                $cacheFactory,
466
+                $request
467
+            );
468
+        });
469
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
470
+
471
+        $this->registerAlias('AppFetcher', AppFetcher::class);
472
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
473
+
474
+        $this->registerService(\OCP\ICache::class, function ($c) {
475
+            return new Cache\File();
476
+        });
477
+        $this->registerAlias('UserCache', \OCP\ICache::class);
478
+
479
+        $this->registerService(Factory::class, function (Server $c) {
480
+
481
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
482
+                ArrayCache::class,
483
+                ArrayCache::class,
484
+                ArrayCache::class
485
+            );
486
+            $config = $c->getConfig();
487
+            $request = $c->getRequest();
488
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
489
+
490
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
491
+                $v = \OC_App::getAppVersions();
492
+                $v['core'] = implode(',', \OC_Util::getVersion());
493
+                $version = implode(',', $v);
494
+                $instanceId = \OC_Util::getInstanceId();
495
+                $path = \OC::$SERVERROOT;
496
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
497
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
498
+                    $config->getSystemValue('memcache.local', null),
499
+                    $config->getSystemValue('memcache.distributed', null),
500
+                    $config->getSystemValue('memcache.locking', null)
501
+                );
502
+            }
503
+            return $arrayCacheFactory;
504
+
505
+        });
506
+        $this->registerAlias('MemCacheFactory', Factory::class);
507
+        $this->registerAlias(ICacheFactory::class, Factory::class);
508
+
509
+        $this->registerService('RedisFactory', function (Server $c) {
510
+            $systemConfig = $c->getSystemConfig();
511
+            return new RedisFactory($systemConfig);
512
+        });
513
+
514
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
515
+            return new \OC\Activity\Manager(
516
+                $c->getRequest(),
517
+                $c->getUserSession(),
518
+                $c->getConfig(),
519
+                $c->query(IValidator::class)
520
+            );
521
+        });
522
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
523
+
524
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
525
+            return new \OC\Activity\EventMerger(
526
+                $c->getL10N('lib')
527
+            );
528
+        });
529
+        $this->registerAlias(IValidator::class, Validator::class);
530
+
531
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
532
+            return new AvatarManager(
533
+                $c->query(\OC\User\Manager::class),
534
+                $c->getAppDataDir('avatar'),
535
+                $c->getL10N('lib'),
536
+                $c->getLogger(),
537
+                $c->getConfig()
538
+            );
539
+        });
540
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
541
+
542
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
543
+
544
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
545
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
546
+            $factory = new LogFactory($c, $this->getSystemConfig());
547
+            $logger = $factory->get($logType);
548
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
549
+
550
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
551
+        });
552
+        $this->registerAlias('Logger', \OCP\ILogger::class);
553
+
554
+        $this->registerService(ILogFactory::class, function (Server $c) {
555
+            return new LogFactory($c, $this->getSystemConfig());
556
+        });
557
+
558
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
559
+            $config = $c->getConfig();
560
+            return new \OC\BackgroundJob\JobList(
561
+                $c->getDatabaseConnection(),
562
+                $config,
563
+                new TimeFactory()
564
+            );
565
+        });
566
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
567
+
568
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
569
+            $cacheFactory = $c->getMemCacheFactory();
570
+            $logger = $c->getLogger();
571
+            if ($cacheFactory->isLocalCacheAvailable()) {
572
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
573
+            } else {
574
+                $router = new \OC\Route\Router($logger);
575
+            }
576
+            return $router;
577
+        });
578
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
579
+
580
+        $this->registerService(\OCP\ISearch::class, function ($c) {
581
+            return new Search();
582
+        });
583
+        $this->registerAlias('Search', \OCP\ISearch::class);
584
+
585
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
586
+            return new \OC\Security\RateLimiting\Limiter(
587
+                $this->getUserSession(),
588
+                $this->getRequest(),
589
+                new \OC\AppFramework\Utility\TimeFactory(),
590
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
591
+            );
592
+        });
593
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
594
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
595
+                $this->getMemCacheFactory(),
596
+                new \OC\AppFramework\Utility\TimeFactory()
597
+            );
598
+        });
599
+
600
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
601
+            return new SecureRandom();
602
+        });
603
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
604
+
605
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
606
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
607
+        });
608
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
609
+
610
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
611
+            return new Hasher($c->getConfig());
612
+        });
613
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
614
+
615
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
616
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
617
+        });
618
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
619
+
620
+        $this->registerService(IDBConnection::class, function (Server $c) {
621
+            $systemConfig = $c->getSystemConfig();
622
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
623
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
624
+            if (!$factory->isValidType($type)) {
625
+                throw new \OC\DatabaseException('Invalid database type');
626
+            }
627
+            $connectionParams = $factory->createConnectionParams();
628
+            $connection = $factory->getConnection($type, $connectionParams);
629
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
630
+            return $connection;
631
+        });
632
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
633
+
634
+
635
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
636
+            $user = \OC_User::getUser();
637
+            $uid = $user ? $user : null;
638
+            return new ClientService(
639
+                $c->getConfig(),
640
+                new \OC\Security\CertificateManager(
641
+                    $uid,
642
+                    new View(),
643
+                    $c->getConfig(),
644
+                    $c->getLogger(),
645
+                    $c->getSecureRandom()
646
+                )
647
+            );
648
+        });
649
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
650
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
651
+            $eventLogger = new EventLogger();
652
+            if ($c->getSystemConfig()->getValue('debug', false)) {
653
+                // In debug mode, module is being activated by default
654
+                $eventLogger->activate();
655
+            }
656
+            return $eventLogger;
657
+        });
658
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
659
+
660
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
661
+            $queryLogger = new QueryLogger();
662
+            if ($c->getSystemConfig()->getValue('debug', false)) {
663
+                // In debug mode, module is being activated by default
664
+                $queryLogger->activate();
665
+            }
666
+            return $queryLogger;
667
+        });
668
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
669
+
670
+        $this->registerService(TempManager::class, function (Server $c) {
671
+            return new TempManager(
672
+                $c->getLogger(),
673
+                $c->getConfig()
674
+            );
675
+        });
676
+        $this->registerAlias('TempManager', TempManager::class);
677
+        $this->registerAlias(ITempManager::class, TempManager::class);
678
+
679
+        $this->registerService(AppManager::class, function (Server $c) {
680
+            return new \OC\App\AppManager(
681
+                $c->getUserSession(),
682
+                $c->query(\OC\AppConfig::class),
683
+                $c->getGroupManager(),
684
+                $c->getMemCacheFactory(),
685
+                $c->getEventDispatcher()
686
+            );
687
+        });
688
+        $this->registerAlias('AppManager', AppManager::class);
689
+        $this->registerAlias(IAppManager::class, AppManager::class);
690
+
691
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
692
+            return new DateTimeZone(
693
+                $c->getConfig(),
694
+                $c->getSession()
695
+            );
696
+        });
697
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
698
+
699
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
700
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
701
+
702
+            return new DateTimeFormatter(
703
+                $c->getDateTimeZone()->getTimeZone(),
704
+                $c->getL10N('lib', $language)
705
+            );
706
+        });
707
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
708
+
709
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
710
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
711
+            $listener = new UserMountCacheListener($mountCache);
712
+            $listener->listen($c->getUserManager());
713
+            return $mountCache;
714
+        });
715
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
716
+
717
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
718
+            $loader = \OC\Files\Filesystem::getLoader();
719
+            $mountCache = $c->query('UserMountCache');
720
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
721
+
722
+            // builtin providers
723
+
724
+            $config = $c->getConfig();
725
+            $manager->registerProvider(new CacheMountProvider($config));
726
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
727
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
728
+
729
+            return $manager;
730
+        });
731
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
732
+
733
+        $this->registerService('IniWrapper', function ($c) {
734
+            return new IniGetWrapper();
735
+        });
736
+        $this->registerService('AsyncCommandBus', function (Server $c) {
737
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
738
+            if ($busClass) {
739
+                list($app, $class) = explode('::', $busClass, 2);
740
+                if ($c->getAppManager()->isInstalled($app)) {
741
+                    \OC_App::loadApp($app);
742
+                    return $c->query($class);
743
+                } else {
744
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
745
+                }
746
+            } else {
747
+                $jobList = $c->getJobList();
748
+                return new CronBus($jobList);
749
+            }
750
+        });
751
+        $this->registerService('TrustedDomainHelper', function ($c) {
752
+            return new TrustedDomainHelper($this->getConfig());
753
+        });
754
+        $this->registerService('Throttler', function (Server $c) {
755
+            return new Throttler(
756
+                $c->getDatabaseConnection(),
757
+                new TimeFactory(),
758
+                $c->getLogger(),
759
+                $c->getConfig()
760
+            );
761
+        });
762
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
763
+            // IConfig and IAppManager requires a working database. This code
764
+            // might however be called when ownCloud is not yet setup.
765
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
766
+                $config = $c->getConfig();
767
+                $appManager = $c->getAppManager();
768
+            } else {
769
+                $config = null;
770
+                $appManager = null;
771
+            }
772
+
773
+            return new Checker(
774
+                new EnvironmentHelper(),
775
+                new FileAccessHelper(),
776
+                new AppLocator(),
777
+                $config,
778
+                $c->getMemCacheFactory(),
779
+                $appManager,
780
+                $c->getTempManager()
781
+            );
782
+        });
783
+        $this->registerService(\OCP\IRequest::class, function ($c) {
784
+            if (isset($this['urlParams'])) {
785
+                $urlParams = $this['urlParams'];
786
+            } else {
787
+                $urlParams = [];
788
+            }
789
+
790
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
791
+                && in_array('fakeinput', stream_get_wrappers())
792
+            ) {
793
+                $stream = 'fakeinput://data';
794
+            } else {
795
+                $stream = 'php://input';
796
+            }
797
+
798
+            return new Request(
799
+                [
800
+                    'get' => $_GET,
801
+                    'post' => $_POST,
802
+                    'files' => $_FILES,
803
+                    'server' => $_SERVER,
804
+                    'env' => $_ENV,
805
+                    'cookies' => $_COOKIE,
806
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
807
+                        ? $_SERVER['REQUEST_METHOD']
808
+                        : '',
809
+                    'urlParams' => $urlParams,
810
+                ],
811
+                $this->getSecureRandom(),
812
+                $this->getConfig(),
813
+                $this->getCsrfTokenManager(),
814
+                $stream
815
+            );
816
+        });
817
+        $this->registerAlias('Request', \OCP\IRequest::class);
818
+
819
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
820
+            return new Mailer(
821
+                $c->getConfig(),
822
+                $c->getLogger(),
823
+                $c->query(Defaults::class),
824
+                $c->getURLGenerator(),
825
+                $c->getL10N('lib')
826
+            );
827
+        });
828
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
829
+
830
+        $this->registerService('LDAPProvider', function (Server $c) {
831
+            $config = $c->getConfig();
832
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
833
+            if (is_null($factoryClass)) {
834
+                throw new \Exception('ldapProviderFactory not set');
835
+            }
836
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
837
+            $factory = new $factoryClass($this);
838
+            return $factory->getLDAPProvider();
839
+        });
840
+        $this->registerService(ILockingProvider::class, function (Server $c) {
841
+            $ini = $c->getIniWrapper();
842
+            $config = $c->getConfig();
843
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
844
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
845
+                /** @var \OC\Memcache\Factory $memcacheFactory */
846
+                $memcacheFactory = $c->getMemCacheFactory();
847
+                $memcache = $memcacheFactory->createLocking('lock');
848
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
849
+                    return new MemcacheLockingProvider($memcache, $ttl);
850
+                }
851
+                return new DBLockingProvider(
852
+                    $c->getDatabaseConnection(),
853
+                    $c->getLogger(),
854
+                    new TimeFactory(),
855
+                    $ttl,
856
+                    !\OC::$CLI
857
+                );
858
+            }
859
+            return new NoopLockingProvider();
860
+        });
861
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
862
+
863
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
864
+            return new \OC\Files\Mount\Manager();
865
+        });
866
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
867
+
868
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
869
+            return new \OC\Files\Type\Detection(
870
+                $c->getURLGenerator(),
871
+                \OC::$configDir,
872
+                \OC::$SERVERROOT . '/resources/config/'
873
+            );
874
+        });
875
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
876
+
877
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
878
+            return new \OC\Files\Type\Loader(
879
+                $c->getDatabaseConnection()
880
+            );
881
+        });
882
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
883
+        $this->registerService(BundleFetcher::class, function () {
884
+            return new BundleFetcher($this->getL10N('lib'));
885
+        });
886
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
887
+            return new Manager(
888
+                $c->query(IValidator::class)
889
+            );
890
+        });
891
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
892
+
893
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
894
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
895
+            $manager->registerCapability(function () use ($c) {
896
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
897
+            });
898
+            $manager->registerCapability(function () use ($c) {
899
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
900
+            });
901
+            return $manager;
902
+        });
903
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
904
+
905
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
906
+            $config = $c->getConfig();
907
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
908
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
909
+            $factory = new $factoryClass($this);
910
+            $manager = $factory->getManager();
911
+
912
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
913
+                $manager = $c->getUserManager();
914
+                $user = $manager->get($id);
915
+                if(is_null($user)) {
916
+                    $l = $c->getL10N('core');
917
+                    $displayName = $l->t('Unknown user');
918
+                } else {
919
+                    $displayName = $user->getDisplayName();
920
+                }
921
+                return $displayName;
922
+            });
923
+
924
+            return $manager;
925
+        });
926
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
927
+
928
+        $this->registerService('ThemingDefaults', function (Server $c) {
929
+            /*
930 930
 			 * Dark magic for autoloader.
931 931
 			 * If we do a class_exists it will try to load the class which will
932 932
 			 * make composer cache the result. Resulting in errors when enabling
933 933
 			 * the theming app.
934 934
 			 */
935
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
936
-			if (isset($prefixes['OCA\\Theming\\'])) {
937
-				$classExists = true;
938
-			} else {
939
-				$classExists = false;
940
-			}
941
-
942
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
943
-				return new ThemingDefaults(
944
-					$c->getConfig(),
945
-					$c->getL10N('theming'),
946
-					$c->getURLGenerator(),
947
-					$c->getMemCacheFactory(),
948
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
949
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
950
-					$c->getAppManager()
951
-				);
952
-			}
953
-			return new \OC_Defaults();
954
-		});
955
-		$this->registerService(SCSSCacher::class, function (Server $c) {
956
-			/** @var Factory $cacheFactory */
957
-			$cacheFactory = $c->query(Factory::class);
958
-			return new SCSSCacher(
959
-				$c->getLogger(),
960
-				$c->query(\OC\Files\AppData\Factory::class),
961
-				$c->getURLGenerator(),
962
-				$c->getConfig(),
963
-				$c->getThemingDefaults(),
964
-				\OC::$SERVERROOT,
965
-				$this->getMemCacheFactory()
966
-			);
967
-		});
968
-		$this->registerService(JSCombiner::class, function (Server $c) {
969
-			/** @var Factory $cacheFactory */
970
-			$cacheFactory = $c->query(Factory::class);
971
-			return new JSCombiner(
972
-				$c->getAppDataDir('js'),
973
-				$c->getURLGenerator(),
974
-				$this->getMemCacheFactory(),
975
-				$c->getSystemConfig(),
976
-				$c->getLogger()
977
-			);
978
-		});
979
-		$this->registerService(EventDispatcher::class, function () {
980
-			return new EventDispatcher();
981
-		});
982
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
983
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
984
-
985
-		$this->registerService('CryptoWrapper', function (Server $c) {
986
-			// FIXME: Instantiiated here due to cyclic dependency
987
-			$request = new Request(
988
-				[
989
-					'get' => $_GET,
990
-					'post' => $_POST,
991
-					'files' => $_FILES,
992
-					'server' => $_SERVER,
993
-					'env' => $_ENV,
994
-					'cookies' => $_COOKIE,
995
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
996
-						? $_SERVER['REQUEST_METHOD']
997
-						: null,
998
-				],
999
-				$c->getSecureRandom(),
1000
-				$c->getConfig()
1001
-			);
1002
-
1003
-			return new CryptoWrapper(
1004
-				$c->getConfig(),
1005
-				$c->getCrypto(),
1006
-				$c->getSecureRandom(),
1007
-				$request
1008
-			);
1009
-		});
1010
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1011
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1012
-
1013
-			return new CsrfTokenManager(
1014
-				$tokenGenerator,
1015
-				$c->query(SessionStorage::class)
1016
-			);
1017
-		});
1018
-		$this->registerService(SessionStorage::class, function (Server $c) {
1019
-			return new SessionStorage($c->getSession());
1020
-		});
1021
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1022
-			return new ContentSecurityPolicyManager();
1023
-		});
1024
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1025
-
1026
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1027
-			return new ContentSecurityPolicyNonceManager(
1028
-				$c->getCsrfTokenManager(),
1029
-				$c->getRequest()
1030
-			);
1031
-		});
1032
-
1033
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1034
-			$config = $c->getConfig();
1035
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1036
-			/** @var \OCP\Share\IProviderFactory $factory */
1037
-			$factory = new $factoryClass($this);
1038
-
1039
-			$manager = new \OC\Share20\Manager(
1040
-				$c->getLogger(),
1041
-				$c->getConfig(),
1042
-				$c->getSecureRandom(),
1043
-				$c->getHasher(),
1044
-				$c->getMountManager(),
1045
-				$c->getGroupManager(),
1046
-				$c->getL10N('lib'),
1047
-				$c->getL10NFactory(),
1048
-				$factory,
1049
-				$c->getUserManager(),
1050
-				$c->getLazyRootFolder(),
1051
-				$c->getEventDispatcher(),
1052
-				$c->getMailer(),
1053
-				$c->getURLGenerator(),
1054
-				$c->getThemingDefaults()
1055
-			);
1056
-
1057
-			return $manager;
1058
-		});
1059
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1060
-
1061
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1062
-			$instance = new Collaboration\Collaborators\Search($c);
1063
-
1064
-			// register default plugins
1065
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1066
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1067
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1068
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1069
-
1070
-			return $instance;
1071
-		});
1072
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1073
-
1074
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1075
-
1076
-		$this->registerService('SettingsManager', function (Server $c) {
1077
-			$manager = new \OC\Settings\Manager(
1078
-				$c->getLogger(),
1079
-				$c->getDatabaseConnection(),
1080
-				$c->getL10N('lib'),
1081
-				$c->getConfig(),
1082
-				$c->getEncryptionManager(),
1083
-				$c->getUserManager(),
1084
-				$c->getLockingProvider(),
1085
-				$c->getRequest(),
1086
-				$c->getURLGenerator(),
1087
-				$c->query(AccountManager::class),
1088
-				$c->getGroupManager(),
1089
-				$c->getL10NFactory(),
1090
-				$c->getAppManager()
1091
-			);
1092
-			return $manager;
1093
-		});
1094
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1095
-			return new \OC\Files\AppData\Factory(
1096
-				$c->getRootFolder(),
1097
-				$c->getSystemConfig()
1098
-			);
1099
-		});
1100
-
1101
-		$this->registerService('LockdownManager', function (Server $c) {
1102
-			return new LockdownManager(function () use ($c) {
1103
-				return $c->getSession();
1104
-			});
1105
-		});
1106
-
1107
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1108
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1109
-		});
1110
-
1111
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1112
-			return new CloudIdManager();
1113
-		});
1114
-
1115
-		$this->registerService(IConfig::class, function (Server $c) {
1116
-			return new GlobalScale\Config($c->getConfig());
1117
-		});
1118
-
1119
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1120
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1121
-		});
1122
-
1123
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1124
-			return new CloudFederationFactory();
1125
-		});
1126
-
1127
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1128
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1129
-
1130
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1131
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1132
-
1133
-		$this->registerService(Defaults::class, function (Server $c) {
1134
-			return new Defaults(
1135
-				$c->getThemingDefaults()
1136
-			);
1137
-		});
1138
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1139
-
1140
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1141
-			return $c->query(\OCP\IUserSession::class)->getSession();
1142
-		});
1143
-
1144
-		$this->registerService(IShareHelper::class, function (Server $c) {
1145
-			return new ShareHelper(
1146
-				$c->query(\OCP\Share\IManager::class)
1147
-			);
1148
-		});
1149
-
1150
-		$this->registerService(Installer::class, function(Server $c) {
1151
-			return new Installer(
1152
-				$c->getAppFetcher(),
1153
-				$c->getHTTPClientService(),
1154
-				$c->getTempManager(),
1155
-				$c->getLogger(),
1156
-				$c->getConfig()
1157
-			);
1158
-		});
1159
-
1160
-		$this->registerService(IApiFactory::class, function(Server $c) {
1161
-			return new ApiFactory($c->getHTTPClientService());
1162
-		});
1163
-
1164
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1165
-			$memcacheFactory = $c->getMemCacheFactory();
1166
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1167
-		});
1168
-
1169
-		$this->registerService(IContactsStore::class, function(Server $c) {
1170
-			return new ContactsStore(
1171
-				$c->getContactsManager(),
1172
-				$c->getConfig(),
1173
-				$c->getUserManager(),
1174
-				$c->getGroupManager()
1175
-			);
1176
-		});
1177
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1178
-
1179
-		$this->connectDispatcher();
1180
-	}
1181
-
1182
-	/**
1183
-	 * @return \OCP\Calendar\IManager
1184
-	 */
1185
-	public function getCalendarManager() {
1186
-		return $this->query('CalendarManager');
1187
-	}
1188
-
1189
-	/**
1190
-	 * @return \OCP\Calendar\Resource\IManager
1191
-	 */
1192
-	public function getCalendarResourceBackendManager() {
1193
-		return $this->query('CalendarResourceBackendManager');
1194
-	}
1195
-
1196
-	/**
1197
-	 * @return \OCP\Calendar\Room\IManager
1198
-	 */
1199
-	public function getCalendarRoomBackendManager() {
1200
-		return $this->query('CalendarRoomBackendManager');
1201
-	}
1202
-
1203
-	private function connectDispatcher() {
1204
-		$dispatcher = $this->getEventDispatcher();
1205
-
1206
-		// Delete avatar on user deletion
1207
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1208
-			$logger = $this->getLogger();
1209
-			$manager = $this->getAvatarManager();
1210
-			/** @var IUser $user */
1211
-			$user = $e->getSubject();
1212
-
1213
-			try {
1214
-				$avatar = $manager->getAvatar($user->getUID());
1215
-				$avatar->remove();
1216
-			} catch (NotFoundException $e) {
1217
-				// no avatar to remove
1218
-			} catch (\Exception $e) {
1219
-				// Ignore exceptions
1220
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1221
-			}
1222
-		});
1223
-
1224
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1225
-			$manager = $this->getAvatarManager();
1226
-			/** @var IUser $user */
1227
-			$user = $e->getSubject();
1228
-			$feature = $e->getArgument('feature');
1229
-			$oldValue = $e->getArgument('oldValue');
1230
-			$value = $e->getArgument('value');
1231
-
1232
-			try {
1233
-				$avatar = $manager->getAvatar($user->getUID());
1234
-				$avatar->userChanged($feature, $oldValue, $value);
1235
-			} catch (NotFoundException $e) {
1236
-				// no avatar to remove
1237
-			}
1238
-		});
1239
-	}
1240
-
1241
-	/**
1242
-	 * @return \OCP\Contacts\IManager
1243
-	 */
1244
-	public function getContactsManager() {
1245
-		return $this->query('ContactsManager');
1246
-	}
1247
-
1248
-	/**
1249
-	 * @return \OC\Encryption\Manager
1250
-	 */
1251
-	public function getEncryptionManager() {
1252
-		return $this->query('EncryptionManager');
1253
-	}
1254
-
1255
-	/**
1256
-	 * @return \OC\Encryption\File
1257
-	 */
1258
-	public function getEncryptionFilesHelper() {
1259
-		return $this->query('EncryptionFileHelper');
1260
-	}
1261
-
1262
-	/**
1263
-	 * @return \OCP\Encryption\Keys\IStorage
1264
-	 */
1265
-	public function getEncryptionKeyStorage() {
1266
-		return $this->query('EncryptionKeyStorage');
1267
-	}
1268
-
1269
-	/**
1270
-	 * The current request object holding all information about the request
1271
-	 * currently being processed is returned from this method.
1272
-	 * In case the current execution was not initiated by a web request null is returned
1273
-	 *
1274
-	 * @return \OCP\IRequest
1275
-	 */
1276
-	public function getRequest() {
1277
-		return $this->query('Request');
1278
-	}
1279
-
1280
-	/**
1281
-	 * Returns the preview manager which can create preview images for a given file
1282
-	 *
1283
-	 * @return \OCP\IPreview
1284
-	 */
1285
-	public function getPreviewManager() {
1286
-		return $this->query('PreviewManager');
1287
-	}
1288
-
1289
-	/**
1290
-	 * Returns the tag manager which can get and set tags for different object types
1291
-	 *
1292
-	 * @see \OCP\ITagManager::load()
1293
-	 * @return \OCP\ITagManager
1294
-	 */
1295
-	public function getTagManager() {
1296
-		return $this->query('TagManager');
1297
-	}
1298
-
1299
-	/**
1300
-	 * Returns the system-tag manager
1301
-	 *
1302
-	 * @return \OCP\SystemTag\ISystemTagManager
1303
-	 *
1304
-	 * @since 9.0.0
1305
-	 */
1306
-	public function getSystemTagManager() {
1307
-		return $this->query('SystemTagManager');
1308
-	}
1309
-
1310
-	/**
1311
-	 * Returns the system-tag object mapper
1312
-	 *
1313
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1314
-	 *
1315
-	 * @since 9.0.0
1316
-	 */
1317
-	public function getSystemTagObjectMapper() {
1318
-		return $this->query('SystemTagObjectMapper');
1319
-	}
1320
-
1321
-	/**
1322
-	 * Returns the avatar manager, used for avatar functionality
1323
-	 *
1324
-	 * @return \OCP\IAvatarManager
1325
-	 */
1326
-	public function getAvatarManager() {
1327
-		return $this->query('AvatarManager');
1328
-	}
1329
-
1330
-	/**
1331
-	 * Returns the root folder of ownCloud's data directory
1332
-	 *
1333
-	 * @return \OCP\Files\IRootFolder
1334
-	 */
1335
-	public function getRootFolder() {
1336
-		return $this->query('LazyRootFolder');
1337
-	}
1338
-
1339
-	/**
1340
-	 * Returns the root folder of ownCloud's data directory
1341
-	 * This is the lazy variant so this gets only initialized once it
1342
-	 * is actually used.
1343
-	 *
1344
-	 * @return \OCP\Files\IRootFolder
1345
-	 */
1346
-	public function getLazyRootFolder() {
1347
-		return $this->query('LazyRootFolder');
1348
-	}
1349
-
1350
-	/**
1351
-	 * Returns a view to ownCloud's files folder
1352
-	 *
1353
-	 * @param string $userId user ID
1354
-	 * @return \OCP\Files\Folder|null
1355
-	 */
1356
-	public function getUserFolder($userId = null) {
1357
-		if ($userId === null) {
1358
-			$user = $this->getUserSession()->getUser();
1359
-			if (!$user) {
1360
-				return null;
1361
-			}
1362
-			$userId = $user->getUID();
1363
-		}
1364
-		$root = $this->getRootFolder();
1365
-		return $root->getUserFolder($userId);
1366
-	}
1367
-
1368
-	/**
1369
-	 * Returns an app-specific view in ownClouds data directory
1370
-	 *
1371
-	 * @return \OCP\Files\Folder
1372
-	 * @deprecated since 9.2.0 use IAppData
1373
-	 */
1374
-	public function getAppFolder() {
1375
-		$dir = '/' . \OC_App::getCurrentApp();
1376
-		$root = $this->getRootFolder();
1377
-		if (!$root->nodeExists($dir)) {
1378
-			$folder = $root->newFolder($dir);
1379
-		} else {
1380
-			$folder = $root->get($dir);
1381
-		}
1382
-		return $folder;
1383
-	}
1384
-
1385
-	/**
1386
-	 * @return \OC\User\Manager
1387
-	 */
1388
-	public function getUserManager() {
1389
-		return $this->query('UserManager');
1390
-	}
1391
-
1392
-	/**
1393
-	 * @return \OC\Group\Manager
1394
-	 */
1395
-	public function getGroupManager() {
1396
-		return $this->query('GroupManager');
1397
-	}
1398
-
1399
-	/**
1400
-	 * @return \OC\User\Session
1401
-	 */
1402
-	public function getUserSession() {
1403
-		return $this->query('UserSession');
1404
-	}
1405
-
1406
-	/**
1407
-	 * @return \OCP\ISession
1408
-	 */
1409
-	public function getSession() {
1410
-		return $this->query('UserSession')->getSession();
1411
-	}
1412
-
1413
-	/**
1414
-	 * @param \OCP\ISession $session
1415
-	 */
1416
-	public function setSession(\OCP\ISession $session) {
1417
-		$this->query(SessionStorage::class)->setSession($session);
1418
-		$this->query('UserSession')->setSession($session);
1419
-		$this->query(Store::class)->setSession($session);
1420
-	}
1421
-
1422
-	/**
1423
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1424
-	 */
1425
-	public function getTwoFactorAuthManager() {
1426
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1427
-	}
1428
-
1429
-	/**
1430
-	 * @return \OC\NavigationManager
1431
-	 */
1432
-	public function getNavigationManager() {
1433
-		return $this->query('NavigationManager');
1434
-	}
1435
-
1436
-	/**
1437
-	 * @return \OCP\IConfig
1438
-	 */
1439
-	public function getConfig() {
1440
-		return $this->query('AllConfig');
1441
-	}
1442
-
1443
-	/**
1444
-	 * @return \OC\SystemConfig
1445
-	 */
1446
-	public function getSystemConfig() {
1447
-		return $this->query('SystemConfig');
1448
-	}
1449
-
1450
-	/**
1451
-	 * Returns the app config manager
1452
-	 *
1453
-	 * @return \OCP\IAppConfig
1454
-	 */
1455
-	public function getAppConfig() {
1456
-		return $this->query('AppConfig');
1457
-	}
1458
-
1459
-	/**
1460
-	 * @return \OCP\L10N\IFactory
1461
-	 */
1462
-	public function getL10NFactory() {
1463
-		return $this->query('L10NFactory');
1464
-	}
1465
-
1466
-	/**
1467
-	 * get an L10N instance
1468
-	 *
1469
-	 * @param string $app appid
1470
-	 * @param string $lang
1471
-	 * @return IL10N
1472
-	 */
1473
-	public function getL10N($app, $lang = null) {
1474
-		return $this->getL10NFactory()->get($app, $lang);
1475
-	}
1476
-
1477
-	/**
1478
-	 * @return \OCP\IURLGenerator
1479
-	 */
1480
-	public function getURLGenerator() {
1481
-		return $this->query('URLGenerator');
1482
-	}
1483
-
1484
-	/**
1485
-	 * @return AppFetcher
1486
-	 */
1487
-	public function getAppFetcher() {
1488
-		return $this->query(AppFetcher::class);
1489
-	}
1490
-
1491
-	/**
1492
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1493
-	 * getMemCacheFactory() instead.
1494
-	 *
1495
-	 * @return \OCP\ICache
1496
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1497
-	 */
1498
-	public function getCache() {
1499
-		return $this->query('UserCache');
1500
-	}
1501
-
1502
-	/**
1503
-	 * Returns an \OCP\CacheFactory instance
1504
-	 *
1505
-	 * @return \OCP\ICacheFactory
1506
-	 */
1507
-	public function getMemCacheFactory() {
1508
-		return $this->query('MemCacheFactory');
1509
-	}
1510
-
1511
-	/**
1512
-	 * Returns an \OC\RedisFactory instance
1513
-	 *
1514
-	 * @return \OC\RedisFactory
1515
-	 */
1516
-	public function getGetRedisFactory() {
1517
-		return $this->query('RedisFactory');
1518
-	}
1519
-
1520
-
1521
-	/**
1522
-	 * Returns the current session
1523
-	 *
1524
-	 * @return \OCP\IDBConnection
1525
-	 */
1526
-	public function getDatabaseConnection() {
1527
-		return $this->query('DatabaseConnection');
1528
-	}
1529
-
1530
-	/**
1531
-	 * Returns the activity manager
1532
-	 *
1533
-	 * @return \OCP\Activity\IManager
1534
-	 */
1535
-	public function getActivityManager() {
1536
-		return $this->query('ActivityManager');
1537
-	}
1538
-
1539
-	/**
1540
-	 * Returns an job list for controlling background jobs
1541
-	 *
1542
-	 * @return \OCP\BackgroundJob\IJobList
1543
-	 */
1544
-	public function getJobList() {
1545
-		return $this->query('JobList');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Returns a logger instance
1550
-	 *
1551
-	 * @return \OCP\ILogger
1552
-	 */
1553
-	public function getLogger() {
1554
-		return $this->query('Logger');
1555
-	}
1556
-
1557
-	/**
1558
-	 * @return ILogFactory
1559
-	 * @throws \OCP\AppFramework\QueryException
1560
-	 */
1561
-	public function getLogFactory() {
1562
-		return $this->query(ILogFactory::class);
1563
-	}
1564
-
1565
-	/**
1566
-	 * Returns a router for generating and matching urls
1567
-	 *
1568
-	 * @return \OCP\Route\IRouter
1569
-	 */
1570
-	public function getRouter() {
1571
-		return $this->query('Router');
1572
-	}
1573
-
1574
-	/**
1575
-	 * Returns a search instance
1576
-	 *
1577
-	 * @return \OCP\ISearch
1578
-	 */
1579
-	public function getSearch() {
1580
-		return $this->query('Search');
1581
-	}
1582
-
1583
-	/**
1584
-	 * Returns a SecureRandom instance
1585
-	 *
1586
-	 * @return \OCP\Security\ISecureRandom
1587
-	 */
1588
-	public function getSecureRandom() {
1589
-		return $this->query('SecureRandom');
1590
-	}
1591
-
1592
-	/**
1593
-	 * Returns a Crypto instance
1594
-	 *
1595
-	 * @return \OCP\Security\ICrypto
1596
-	 */
1597
-	public function getCrypto() {
1598
-		return $this->query('Crypto');
1599
-	}
1600
-
1601
-	/**
1602
-	 * Returns a Hasher instance
1603
-	 *
1604
-	 * @return \OCP\Security\IHasher
1605
-	 */
1606
-	public function getHasher() {
1607
-		return $this->query('Hasher');
1608
-	}
1609
-
1610
-	/**
1611
-	 * Returns a CredentialsManager instance
1612
-	 *
1613
-	 * @return \OCP\Security\ICredentialsManager
1614
-	 */
1615
-	public function getCredentialsManager() {
1616
-		return $this->query('CredentialsManager');
1617
-	}
1618
-
1619
-	/**
1620
-	 * Get the certificate manager for the user
1621
-	 *
1622
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1623
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1624
-	 */
1625
-	public function getCertificateManager($userId = '') {
1626
-		if ($userId === '') {
1627
-			$userSession = $this->getUserSession();
1628
-			$user = $userSession->getUser();
1629
-			if (is_null($user)) {
1630
-				return null;
1631
-			}
1632
-			$userId = $user->getUID();
1633
-		}
1634
-		return new CertificateManager(
1635
-			$userId,
1636
-			new View(),
1637
-			$this->getConfig(),
1638
-			$this->getLogger(),
1639
-			$this->getSecureRandom()
1640
-		);
1641
-	}
1642
-
1643
-	/**
1644
-	 * Returns an instance of the HTTP client service
1645
-	 *
1646
-	 * @return \OCP\Http\Client\IClientService
1647
-	 */
1648
-	public function getHTTPClientService() {
1649
-		return $this->query('HttpClientService');
1650
-	}
1651
-
1652
-	/**
1653
-	 * Create a new event source
1654
-	 *
1655
-	 * @return \OCP\IEventSource
1656
-	 */
1657
-	public function createEventSource() {
1658
-		return new \OC_EventSource();
1659
-	}
1660
-
1661
-	/**
1662
-	 * Get the active event logger
1663
-	 *
1664
-	 * The returned logger only logs data when debug mode is enabled
1665
-	 *
1666
-	 * @return \OCP\Diagnostics\IEventLogger
1667
-	 */
1668
-	public function getEventLogger() {
1669
-		return $this->query('EventLogger');
1670
-	}
1671
-
1672
-	/**
1673
-	 * Get the active query logger
1674
-	 *
1675
-	 * The returned logger only logs data when debug mode is enabled
1676
-	 *
1677
-	 * @return \OCP\Diagnostics\IQueryLogger
1678
-	 */
1679
-	public function getQueryLogger() {
1680
-		return $this->query('QueryLogger');
1681
-	}
1682
-
1683
-	/**
1684
-	 * Get the manager for temporary files and folders
1685
-	 *
1686
-	 * @return \OCP\ITempManager
1687
-	 */
1688
-	public function getTempManager() {
1689
-		return $this->query('TempManager');
1690
-	}
1691
-
1692
-	/**
1693
-	 * Get the app manager
1694
-	 *
1695
-	 * @return \OCP\App\IAppManager
1696
-	 */
1697
-	public function getAppManager() {
1698
-		return $this->query('AppManager');
1699
-	}
1700
-
1701
-	/**
1702
-	 * Creates a new mailer
1703
-	 *
1704
-	 * @return \OCP\Mail\IMailer
1705
-	 */
1706
-	public function getMailer() {
1707
-		return $this->query('Mailer');
1708
-	}
1709
-
1710
-	/**
1711
-	 * Get the webroot
1712
-	 *
1713
-	 * @return string
1714
-	 */
1715
-	public function getWebRoot() {
1716
-		return $this->webRoot;
1717
-	}
1718
-
1719
-	/**
1720
-	 * @return \OC\OCSClient
1721
-	 */
1722
-	public function getOcsClient() {
1723
-		return $this->query('OcsClient');
1724
-	}
1725
-
1726
-	/**
1727
-	 * @return \OCP\IDateTimeZone
1728
-	 */
1729
-	public function getDateTimeZone() {
1730
-		return $this->query('DateTimeZone');
1731
-	}
1732
-
1733
-	/**
1734
-	 * @return \OCP\IDateTimeFormatter
1735
-	 */
1736
-	public function getDateTimeFormatter() {
1737
-		return $this->query('DateTimeFormatter');
1738
-	}
1739
-
1740
-	/**
1741
-	 * @return \OCP\Files\Config\IMountProviderCollection
1742
-	 */
1743
-	public function getMountProviderCollection() {
1744
-		return $this->query('MountConfigManager');
1745
-	}
1746
-
1747
-	/**
1748
-	 * Get the IniWrapper
1749
-	 *
1750
-	 * @return IniGetWrapper
1751
-	 */
1752
-	public function getIniWrapper() {
1753
-		return $this->query('IniWrapper');
1754
-	}
1755
-
1756
-	/**
1757
-	 * @return \OCP\Command\IBus
1758
-	 */
1759
-	public function getCommandBus() {
1760
-		return $this->query('AsyncCommandBus');
1761
-	}
1762
-
1763
-	/**
1764
-	 * Get the trusted domain helper
1765
-	 *
1766
-	 * @return TrustedDomainHelper
1767
-	 */
1768
-	public function getTrustedDomainHelper() {
1769
-		return $this->query('TrustedDomainHelper');
1770
-	}
1771
-
1772
-	/**
1773
-	 * Get the locking provider
1774
-	 *
1775
-	 * @return \OCP\Lock\ILockingProvider
1776
-	 * @since 8.1.0
1777
-	 */
1778
-	public function getLockingProvider() {
1779
-		return $this->query('LockingProvider');
1780
-	}
1781
-
1782
-	/**
1783
-	 * @return \OCP\Files\Mount\IMountManager
1784
-	 **/
1785
-	function getMountManager() {
1786
-		return $this->query('MountManager');
1787
-	}
1788
-
1789
-	/** @return \OCP\Files\Config\IUserMountCache */
1790
-	function getUserMountCache() {
1791
-		return $this->query('UserMountCache');
1792
-	}
1793
-
1794
-	/**
1795
-	 * Get the MimeTypeDetector
1796
-	 *
1797
-	 * @return \OCP\Files\IMimeTypeDetector
1798
-	 */
1799
-	public function getMimeTypeDetector() {
1800
-		return $this->query('MimeTypeDetector');
1801
-	}
1802
-
1803
-	/**
1804
-	 * Get the MimeTypeLoader
1805
-	 *
1806
-	 * @return \OCP\Files\IMimeTypeLoader
1807
-	 */
1808
-	public function getMimeTypeLoader() {
1809
-		return $this->query('MimeTypeLoader');
1810
-	}
1811
-
1812
-	/**
1813
-	 * Get the manager of all the capabilities
1814
-	 *
1815
-	 * @return \OC\CapabilitiesManager
1816
-	 */
1817
-	public function getCapabilitiesManager() {
1818
-		return $this->query('CapabilitiesManager');
1819
-	}
1820
-
1821
-	/**
1822
-	 * Get the EventDispatcher
1823
-	 *
1824
-	 * @return EventDispatcherInterface
1825
-	 * @since 8.2.0
1826
-	 */
1827
-	public function getEventDispatcher() {
1828
-		return $this->query('EventDispatcher');
1829
-	}
1830
-
1831
-	/**
1832
-	 * Get the Notification Manager
1833
-	 *
1834
-	 * @return \OCP\Notification\IManager
1835
-	 * @since 8.2.0
1836
-	 */
1837
-	public function getNotificationManager() {
1838
-		return $this->query('NotificationManager');
1839
-	}
1840
-
1841
-	/**
1842
-	 * @return \OCP\Comments\ICommentsManager
1843
-	 */
1844
-	public function getCommentsManager() {
1845
-		return $this->query('CommentsManager');
1846
-	}
1847
-
1848
-	/**
1849
-	 * @return \OCA\Theming\ThemingDefaults
1850
-	 */
1851
-	public function getThemingDefaults() {
1852
-		return $this->query('ThemingDefaults');
1853
-	}
1854
-
1855
-	/**
1856
-	 * @return \OC\IntegrityCheck\Checker
1857
-	 */
1858
-	public function getIntegrityCodeChecker() {
1859
-		return $this->query('IntegrityCodeChecker');
1860
-	}
1861
-
1862
-	/**
1863
-	 * @return \OC\Session\CryptoWrapper
1864
-	 */
1865
-	public function getSessionCryptoWrapper() {
1866
-		return $this->query('CryptoWrapper');
1867
-	}
1868
-
1869
-	/**
1870
-	 * @return CsrfTokenManager
1871
-	 */
1872
-	public function getCsrfTokenManager() {
1873
-		return $this->query('CsrfTokenManager');
1874
-	}
1875
-
1876
-	/**
1877
-	 * @return Throttler
1878
-	 */
1879
-	public function getBruteForceThrottler() {
1880
-		return $this->query('Throttler');
1881
-	}
1882
-
1883
-	/**
1884
-	 * @return IContentSecurityPolicyManager
1885
-	 */
1886
-	public function getContentSecurityPolicyManager() {
1887
-		return $this->query('ContentSecurityPolicyManager');
1888
-	}
1889
-
1890
-	/**
1891
-	 * @return ContentSecurityPolicyNonceManager
1892
-	 */
1893
-	public function getContentSecurityPolicyNonceManager() {
1894
-		return $this->query('ContentSecurityPolicyNonceManager');
1895
-	}
1896
-
1897
-	/**
1898
-	 * Not a public API as of 8.2, wait for 9.0
1899
-	 *
1900
-	 * @return \OCA\Files_External\Service\BackendService
1901
-	 */
1902
-	public function getStoragesBackendService() {
1903
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1904
-	}
1905
-
1906
-	/**
1907
-	 * Not a public API as of 8.2, wait for 9.0
1908
-	 *
1909
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1910
-	 */
1911
-	public function getGlobalStoragesService() {
1912
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1913
-	}
1914
-
1915
-	/**
1916
-	 * Not a public API as of 8.2, wait for 9.0
1917
-	 *
1918
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1919
-	 */
1920
-	public function getUserGlobalStoragesService() {
1921
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1922
-	}
1923
-
1924
-	/**
1925
-	 * Not a public API as of 8.2, wait for 9.0
1926
-	 *
1927
-	 * @return \OCA\Files_External\Service\UserStoragesService
1928
-	 */
1929
-	public function getUserStoragesService() {
1930
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1931
-	}
1932
-
1933
-	/**
1934
-	 * @return \OCP\Share\IManager
1935
-	 */
1936
-	public function getShareManager() {
1937
-		return $this->query('ShareManager');
1938
-	}
1939
-
1940
-	/**
1941
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1942
-	 */
1943
-	public function getCollaboratorSearch() {
1944
-		return $this->query('CollaboratorSearch');
1945
-	}
1946
-
1947
-	/**
1948
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1949
-	 */
1950
-	public function getAutoCompleteManager(){
1951
-		return $this->query(IManager::class);
1952
-	}
1953
-
1954
-	/**
1955
-	 * Returns the LDAP Provider
1956
-	 *
1957
-	 * @return \OCP\LDAP\ILDAPProvider
1958
-	 */
1959
-	public function getLDAPProvider() {
1960
-		return $this->query('LDAPProvider');
1961
-	}
1962
-
1963
-	/**
1964
-	 * @return \OCP\Settings\IManager
1965
-	 */
1966
-	public function getSettingsManager() {
1967
-		return $this->query('SettingsManager');
1968
-	}
1969
-
1970
-	/**
1971
-	 * @return \OCP\Files\IAppData
1972
-	 */
1973
-	public function getAppDataDir($app) {
1974
-		/** @var \OC\Files\AppData\Factory $factory */
1975
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1976
-		return $factory->get($app);
1977
-	}
1978
-
1979
-	/**
1980
-	 * @return \OCP\Lockdown\ILockdownManager
1981
-	 */
1982
-	public function getLockdownManager() {
1983
-		return $this->query('LockdownManager');
1984
-	}
1985
-
1986
-	/**
1987
-	 * @return \OCP\Federation\ICloudIdManager
1988
-	 */
1989
-	public function getCloudIdManager() {
1990
-		return $this->query(ICloudIdManager::class);
1991
-	}
1992
-
1993
-	/**
1994
-	 * @return \OCP\GlobalScale\IConfig
1995
-	 */
1996
-	public function getGlobalScaleConfig() {
1997
-		return $this->query(IConfig::class);
1998
-	}
1999
-
2000
-	/**
2001
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2002
-	 */
2003
-	public function getCloudFederationProviderManager() {
2004
-		return $this->query(ICloudFederationProviderManager::class);
2005
-	}
2006
-
2007
-	/**
2008
-	 * @return \OCP\Remote\Api\IApiFactory
2009
-	 */
2010
-	public function getRemoteApiFactory() {
2011
-		return $this->query(IApiFactory::class);
2012
-	}
2013
-
2014
-	/**
2015
-	 * @return \OCP\Federation\ICloudFederationFactory
2016
-	 */
2017
-	public function getCloudFederationFactory() {
2018
-		return $this->query(ICloudFederationFactory::class);
2019
-	}
2020
-
2021
-	/**
2022
-	 * @return \OCP\Remote\IInstanceFactory
2023
-	 */
2024
-	public function getRemoteInstanceFactory() {
2025
-		return $this->query(IInstanceFactory::class);
2026
-	}
935
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
936
+            if (isset($prefixes['OCA\\Theming\\'])) {
937
+                $classExists = true;
938
+            } else {
939
+                $classExists = false;
940
+            }
941
+
942
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
943
+                return new ThemingDefaults(
944
+                    $c->getConfig(),
945
+                    $c->getL10N('theming'),
946
+                    $c->getURLGenerator(),
947
+                    $c->getMemCacheFactory(),
948
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
949
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
950
+                    $c->getAppManager()
951
+                );
952
+            }
953
+            return new \OC_Defaults();
954
+        });
955
+        $this->registerService(SCSSCacher::class, function (Server $c) {
956
+            /** @var Factory $cacheFactory */
957
+            $cacheFactory = $c->query(Factory::class);
958
+            return new SCSSCacher(
959
+                $c->getLogger(),
960
+                $c->query(\OC\Files\AppData\Factory::class),
961
+                $c->getURLGenerator(),
962
+                $c->getConfig(),
963
+                $c->getThemingDefaults(),
964
+                \OC::$SERVERROOT,
965
+                $this->getMemCacheFactory()
966
+            );
967
+        });
968
+        $this->registerService(JSCombiner::class, function (Server $c) {
969
+            /** @var Factory $cacheFactory */
970
+            $cacheFactory = $c->query(Factory::class);
971
+            return new JSCombiner(
972
+                $c->getAppDataDir('js'),
973
+                $c->getURLGenerator(),
974
+                $this->getMemCacheFactory(),
975
+                $c->getSystemConfig(),
976
+                $c->getLogger()
977
+            );
978
+        });
979
+        $this->registerService(EventDispatcher::class, function () {
980
+            return new EventDispatcher();
981
+        });
982
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
983
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
984
+
985
+        $this->registerService('CryptoWrapper', function (Server $c) {
986
+            // FIXME: Instantiiated here due to cyclic dependency
987
+            $request = new Request(
988
+                [
989
+                    'get' => $_GET,
990
+                    'post' => $_POST,
991
+                    'files' => $_FILES,
992
+                    'server' => $_SERVER,
993
+                    'env' => $_ENV,
994
+                    'cookies' => $_COOKIE,
995
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
996
+                        ? $_SERVER['REQUEST_METHOD']
997
+                        : null,
998
+                ],
999
+                $c->getSecureRandom(),
1000
+                $c->getConfig()
1001
+            );
1002
+
1003
+            return new CryptoWrapper(
1004
+                $c->getConfig(),
1005
+                $c->getCrypto(),
1006
+                $c->getSecureRandom(),
1007
+                $request
1008
+            );
1009
+        });
1010
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1011
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1012
+
1013
+            return new CsrfTokenManager(
1014
+                $tokenGenerator,
1015
+                $c->query(SessionStorage::class)
1016
+            );
1017
+        });
1018
+        $this->registerService(SessionStorage::class, function (Server $c) {
1019
+            return new SessionStorage($c->getSession());
1020
+        });
1021
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1022
+            return new ContentSecurityPolicyManager();
1023
+        });
1024
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1025
+
1026
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1027
+            return new ContentSecurityPolicyNonceManager(
1028
+                $c->getCsrfTokenManager(),
1029
+                $c->getRequest()
1030
+            );
1031
+        });
1032
+
1033
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1034
+            $config = $c->getConfig();
1035
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1036
+            /** @var \OCP\Share\IProviderFactory $factory */
1037
+            $factory = new $factoryClass($this);
1038
+
1039
+            $manager = new \OC\Share20\Manager(
1040
+                $c->getLogger(),
1041
+                $c->getConfig(),
1042
+                $c->getSecureRandom(),
1043
+                $c->getHasher(),
1044
+                $c->getMountManager(),
1045
+                $c->getGroupManager(),
1046
+                $c->getL10N('lib'),
1047
+                $c->getL10NFactory(),
1048
+                $factory,
1049
+                $c->getUserManager(),
1050
+                $c->getLazyRootFolder(),
1051
+                $c->getEventDispatcher(),
1052
+                $c->getMailer(),
1053
+                $c->getURLGenerator(),
1054
+                $c->getThemingDefaults()
1055
+            );
1056
+
1057
+            return $manager;
1058
+        });
1059
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1060
+
1061
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1062
+            $instance = new Collaboration\Collaborators\Search($c);
1063
+
1064
+            // register default plugins
1065
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1066
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1067
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1068
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1069
+
1070
+            return $instance;
1071
+        });
1072
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1073
+
1074
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1075
+
1076
+        $this->registerService('SettingsManager', function (Server $c) {
1077
+            $manager = new \OC\Settings\Manager(
1078
+                $c->getLogger(),
1079
+                $c->getDatabaseConnection(),
1080
+                $c->getL10N('lib'),
1081
+                $c->getConfig(),
1082
+                $c->getEncryptionManager(),
1083
+                $c->getUserManager(),
1084
+                $c->getLockingProvider(),
1085
+                $c->getRequest(),
1086
+                $c->getURLGenerator(),
1087
+                $c->query(AccountManager::class),
1088
+                $c->getGroupManager(),
1089
+                $c->getL10NFactory(),
1090
+                $c->getAppManager()
1091
+            );
1092
+            return $manager;
1093
+        });
1094
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1095
+            return new \OC\Files\AppData\Factory(
1096
+                $c->getRootFolder(),
1097
+                $c->getSystemConfig()
1098
+            );
1099
+        });
1100
+
1101
+        $this->registerService('LockdownManager', function (Server $c) {
1102
+            return new LockdownManager(function () use ($c) {
1103
+                return $c->getSession();
1104
+            });
1105
+        });
1106
+
1107
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1108
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1109
+        });
1110
+
1111
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1112
+            return new CloudIdManager();
1113
+        });
1114
+
1115
+        $this->registerService(IConfig::class, function (Server $c) {
1116
+            return new GlobalScale\Config($c->getConfig());
1117
+        });
1118
+
1119
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1120
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1121
+        });
1122
+
1123
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1124
+            return new CloudFederationFactory();
1125
+        });
1126
+
1127
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1128
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1129
+
1130
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1131
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1132
+
1133
+        $this->registerService(Defaults::class, function (Server $c) {
1134
+            return new Defaults(
1135
+                $c->getThemingDefaults()
1136
+            );
1137
+        });
1138
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1139
+
1140
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1141
+            return $c->query(\OCP\IUserSession::class)->getSession();
1142
+        });
1143
+
1144
+        $this->registerService(IShareHelper::class, function (Server $c) {
1145
+            return new ShareHelper(
1146
+                $c->query(\OCP\Share\IManager::class)
1147
+            );
1148
+        });
1149
+
1150
+        $this->registerService(Installer::class, function(Server $c) {
1151
+            return new Installer(
1152
+                $c->getAppFetcher(),
1153
+                $c->getHTTPClientService(),
1154
+                $c->getTempManager(),
1155
+                $c->getLogger(),
1156
+                $c->getConfig()
1157
+            );
1158
+        });
1159
+
1160
+        $this->registerService(IApiFactory::class, function(Server $c) {
1161
+            return new ApiFactory($c->getHTTPClientService());
1162
+        });
1163
+
1164
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1165
+            $memcacheFactory = $c->getMemCacheFactory();
1166
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1167
+        });
1168
+
1169
+        $this->registerService(IContactsStore::class, function(Server $c) {
1170
+            return new ContactsStore(
1171
+                $c->getContactsManager(),
1172
+                $c->getConfig(),
1173
+                $c->getUserManager(),
1174
+                $c->getGroupManager()
1175
+            );
1176
+        });
1177
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1178
+
1179
+        $this->connectDispatcher();
1180
+    }
1181
+
1182
+    /**
1183
+     * @return \OCP\Calendar\IManager
1184
+     */
1185
+    public function getCalendarManager() {
1186
+        return $this->query('CalendarManager');
1187
+    }
1188
+
1189
+    /**
1190
+     * @return \OCP\Calendar\Resource\IManager
1191
+     */
1192
+    public function getCalendarResourceBackendManager() {
1193
+        return $this->query('CalendarResourceBackendManager');
1194
+    }
1195
+
1196
+    /**
1197
+     * @return \OCP\Calendar\Room\IManager
1198
+     */
1199
+    public function getCalendarRoomBackendManager() {
1200
+        return $this->query('CalendarRoomBackendManager');
1201
+    }
1202
+
1203
+    private function connectDispatcher() {
1204
+        $dispatcher = $this->getEventDispatcher();
1205
+
1206
+        // Delete avatar on user deletion
1207
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1208
+            $logger = $this->getLogger();
1209
+            $manager = $this->getAvatarManager();
1210
+            /** @var IUser $user */
1211
+            $user = $e->getSubject();
1212
+
1213
+            try {
1214
+                $avatar = $manager->getAvatar($user->getUID());
1215
+                $avatar->remove();
1216
+            } catch (NotFoundException $e) {
1217
+                // no avatar to remove
1218
+            } catch (\Exception $e) {
1219
+                // Ignore exceptions
1220
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1221
+            }
1222
+        });
1223
+
1224
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1225
+            $manager = $this->getAvatarManager();
1226
+            /** @var IUser $user */
1227
+            $user = $e->getSubject();
1228
+            $feature = $e->getArgument('feature');
1229
+            $oldValue = $e->getArgument('oldValue');
1230
+            $value = $e->getArgument('value');
1231
+
1232
+            try {
1233
+                $avatar = $manager->getAvatar($user->getUID());
1234
+                $avatar->userChanged($feature, $oldValue, $value);
1235
+            } catch (NotFoundException $e) {
1236
+                // no avatar to remove
1237
+            }
1238
+        });
1239
+    }
1240
+
1241
+    /**
1242
+     * @return \OCP\Contacts\IManager
1243
+     */
1244
+    public function getContactsManager() {
1245
+        return $this->query('ContactsManager');
1246
+    }
1247
+
1248
+    /**
1249
+     * @return \OC\Encryption\Manager
1250
+     */
1251
+    public function getEncryptionManager() {
1252
+        return $this->query('EncryptionManager');
1253
+    }
1254
+
1255
+    /**
1256
+     * @return \OC\Encryption\File
1257
+     */
1258
+    public function getEncryptionFilesHelper() {
1259
+        return $this->query('EncryptionFileHelper');
1260
+    }
1261
+
1262
+    /**
1263
+     * @return \OCP\Encryption\Keys\IStorage
1264
+     */
1265
+    public function getEncryptionKeyStorage() {
1266
+        return $this->query('EncryptionKeyStorage');
1267
+    }
1268
+
1269
+    /**
1270
+     * The current request object holding all information about the request
1271
+     * currently being processed is returned from this method.
1272
+     * In case the current execution was not initiated by a web request null is returned
1273
+     *
1274
+     * @return \OCP\IRequest
1275
+     */
1276
+    public function getRequest() {
1277
+        return $this->query('Request');
1278
+    }
1279
+
1280
+    /**
1281
+     * Returns the preview manager which can create preview images for a given file
1282
+     *
1283
+     * @return \OCP\IPreview
1284
+     */
1285
+    public function getPreviewManager() {
1286
+        return $this->query('PreviewManager');
1287
+    }
1288
+
1289
+    /**
1290
+     * Returns the tag manager which can get and set tags for different object types
1291
+     *
1292
+     * @see \OCP\ITagManager::load()
1293
+     * @return \OCP\ITagManager
1294
+     */
1295
+    public function getTagManager() {
1296
+        return $this->query('TagManager');
1297
+    }
1298
+
1299
+    /**
1300
+     * Returns the system-tag manager
1301
+     *
1302
+     * @return \OCP\SystemTag\ISystemTagManager
1303
+     *
1304
+     * @since 9.0.0
1305
+     */
1306
+    public function getSystemTagManager() {
1307
+        return $this->query('SystemTagManager');
1308
+    }
1309
+
1310
+    /**
1311
+     * Returns the system-tag object mapper
1312
+     *
1313
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1314
+     *
1315
+     * @since 9.0.0
1316
+     */
1317
+    public function getSystemTagObjectMapper() {
1318
+        return $this->query('SystemTagObjectMapper');
1319
+    }
1320
+
1321
+    /**
1322
+     * Returns the avatar manager, used for avatar functionality
1323
+     *
1324
+     * @return \OCP\IAvatarManager
1325
+     */
1326
+    public function getAvatarManager() {
1327
+        return $this->query('AvatarManager');
1328
+    }
1329
+
1330
+    /**
1331
+     * Returns the root folder of ownCloud's data directory
1332
+     *
1333
+     * @return \OCP\Files\IRootFolder
1334
+     */
1335
+    public function getRootFolder() {
1336
+        return $this->query('LazyRootFolder');
1337
+    }
1338
+
1339
+    /**
1340
+     * Returns the root folder of ownCloud's data directory
1341
+     * This is the lazy variant so this gets only initialized once it
1342
+     * is actually used.
1343
+     *
1344
+     * @return \OCP\Files\IRootFolder
1345
+     */
1346
+    public function getLazyRootFolder() {
1347
+        return $this->query('LazyRootFolder');
1348
+    }
1349
+
1350
+    /**
1351
+     * Returns a view to ownCloud's files folder
1352
+     *
1353
+     * @param string $userId user ID
1354
+     * @return \OCP\Files\Folder|null
1355
+     */
1356
+    public function getUserFolder($userId = null) {
1357
+        if ($userId === null) {
1358
+            $user = $this->getUserSession()->getUser();
1359
+            if (!$user) {
1360
+                return null;
1361
+            }
1362
+            $userId = $user->getUID();
1363
+        }
1364
+        $root = $this->getRootFolder();
1365
+        return $root->getUserFolder($userId);
1366
+    }
1367
+
1368
+    /**
1369
+     * Returns an app-specific view in ownClouds data directory
1370
+     *
1371
+     * @return \OCP\Files\Folder
1372
+     * @deprecated since 9.2.0 use IAppData
1373
+     */
1374
+    public function getAppFolder() {
1375
+        $dir = '/' . \OC_App::getCurrentApp();
1376
+        $root = $this->getRootFolder();
1377
+        if (!$root->nodeExists($dir)) {
1378
+            $folder = $root->newFolder($dir);
1379
+        } else {
1380
+            $folder = $root->get($dir);
1381
+        }
1382
+        return $folder;
1383
+    }
1384
+
1385
+    /**
1386
+     * @return \OC\User\Manager
1387
+     */
1388
+    public function getUserManager() {
1389
+        return $this->query('UserManager');
1390
+    }
1391
+
1392
+    /**
1393
+     * @return \OC\Group\Manager
1394
+     */
1395
+    public function getGroupManager() {
1396
+        return $this->query('GroupManager');
1397
+    }
1398
+
1399
+    /**
1400
+     * @return \OC\User\Session
1401
+     */
1402
+    public function getUserSession() {
1403
+        return $this->query('UserSession');
1404
+    }
1405
+
1406
+    /**
1407
+     * @return \OCP\ISession
1408
+     */
1409
+    public function getSession() {
1410
+        return $this->query('UserSession')->getSession();
1411
+    }
1412
+
1413
+    /**
1414
+     * @param \OCP\ISession $session
1415
+     */
1416
+    public function setSession(\OCP\ISession $session) {
1417
+        $this->query(SessionStorage::class)->setSession($session);
1418
+        $this->query('UserSession')->setSession($session);
1419
+        $this->query(Store::class)->setSession($session);
1420
+    }
1421
+
1422
+    /**
1423
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1424
+     */
1425
+    public function getTwoFactorAuthManager() {
1426
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1427
+    }
1428
+
1429
+    /**
1430
+     * @return \OC\NavigationManager
1431
+     */
1432
+    public function getNavigationManager() {
1433
+        return $this->query('NavigationManager');
1434
+    }
1435
+
1436
+    /**
1437
+     * @return \OCP\IConfig
1438
+     */
1439
+    public function getConfig() {
1440
+        return $this->query('AllConfig');
1441
+    }
1442
+
1443
+    /**
1444
+     * @return \OC\SystemConfig
1445
+     */
1446
+    public function getSystemConfig() {
1447
+        return $this->query('SystemConfig');
1448
+    }
1449
+
1450
+    /**
1451
+     * Returns the app config manager
1452
+     *
1453
+     * @return \OCP\IAppConfig
1454
+     */
1455
+    public function getAppConfig() {
1456
+        return $this->query('AppConfig');
1457
+    }
1458
+
1459
+    /**
1460
+     * @return \OCP\L10N\IFactory
1461
+     */
1462
+    public function getL10NFactory() {
1463
+        return $this->query('L10NFactory');
1464
+    }
1465
+
1466
+    /**
1467
+     * get an L10N instance
1468
+     *
1469
+     * @param string $app appid
1470
+     * @param string $lang
1471
+     * @return IL10N
1472
+     */
1473
+    public function getL10N($app, $lang = null) {
1474
+        return $this->getL10NFactory()->get($app, $lang);
1475
+    }
1476
+
1477
+    /**
1478
+     * @return \OCP\IURLGenerator
1479
+     */
1480
+    public function getURLGenerator() {
1481
+        return $this->query('URLGenerator');
1482
+    }
1483
+
1484
+    /**
1485
+     * @return AppFetcher
1486
+     */
1487
+    public function getAppFetcher() {
1488
+        return $this->query(AppFetcher::class);
1489
+    }
1490
+
1491
+    /**
1492
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1493
+     * getMemCacheFactory() instead.
1494
+     *
1495
+     * @return \OCP\ICache
1496
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1497
+     */
1498
+    public function getCache() {
1499
+        return $this->query('UserCache');
1500
+    }
1501
+
1502
+    /**
1503
+     * Returns an \OCP\CacheFactory instance
1504
+     *
1505
+     * @return \OCP\ICacheFactory
1506
+     */
1507
+    public function getMemCacheFactory() {
1508
+        return $this->query('MemCacheFactory');
1509
+    }
1510
+
1511
+    /**
1512
+     * Returns an \OC\RedisFactory instance
1513
+     *
1514
+     * @return \OC\RedisFactory
1515
+     */
1516
+    public function getGetRedisFactory() {
1517
+        return $this->query('RedisFactory');
1518
+    }
1519
+
1520
+
1521
+    /**
1522
+     * Returns the current session
1523
+     *
1524
+     * @return \OCP\IDBConnection
1525
+     */
1526
+    public function getDatabaseConnection() {
1527
+        return $this->query('DatabaseConnection');
1528
+    }
1529
+
1530
+    /**
1531
+     * Returns the activity manager
1532
+     *
1533
+     * @return \OCP\Activity\IManager
1534
+     */
1535
+    public function getActivityManager() {
1536
+        return $this->query('ActivityManager');
1537
+    }
1538
+
1539
+    /**
1540
+     * Returns an job list for controlling background jobs
1541
+     *
1542
+     * @return \OCP\BackgroundJob\IJobList
1543
+     */
1544
+    public function getJobList() {
1545
+        return $this->query('JobList');
1546
+    }
1547
+
1548
+    /**
1549
+     * Returns a logger instance
1550
+     *
1551
+     * @return \OCP\ILogger
1552
+     */
1553
+    public function getLogger() {
1554
+        return $this->query('Logger');
1555
+    }
1556
+
1557
+    /**
1558
+     * @return ILogFactory
1559
+     * @throws \OCP\AppFramework\QueryException
1560
+     */
1561
+    public function getLogFactory() {
1562
+        return $this->query(ILogFactory::class);
1563
+    }
1564
+
1565
+    /**
1566
+     * Returns a router for generating and matching urls
1567
+     *
1568
+     * @return \OCP\Route\IRouter
1569
+     */
1570
+    public function getRouter() {
1571
+        return $this->query('Router');
1572
+    }
1573
+
1574
+    /**
1575
+     * Returns a search instance
1576
+     *
1577
+     * @return \OCP\ISearch
1578
+     */
1579
+    public function getSearch() {
1580
+        return $this->query('Search');
1581
+    }
1582
+
1583
+    /**
1584
+     * Returns a SecureRandom instance
1585
+     *
1586
+     * @return \OCP\Security\ISecureRandom
1587
+     */
1588
+    public function getSecureRandom() {
1589
+        return $this->query('SecureRandom');
1590
+    }
1591
+
1592
+    /**
1593
+     * Returns a Crypto instance
1594
+     *
1595
+     * @return \OCP\Security\ICrypto
1596
+     */
1597
+    public function getCrypto() {
1598
+        return $this->query('Crypto');
1599
+    }
1600
+
1601
+    /**
1602
+     * Returns a Hasher instance
1603
+     *
1604
+     * @return \OCP\Security\IHasher
1605
+     */
1606
+    public function getHasher() {
1607
+        return $this->query('Hasher');
1608
+    }
1609
+
1610
+    /**
1611
+     * Returns a CredentialsManager instance
1612
+     *
1613
+     * @return \OCP\Security\ICredentialsManager
1614
+     */
1615
+    public function getCredentialsManager() {
1616
+        return $this->query('CredentialsManager');
1617
+    }
1618
+
1619
+    /**
1620
+     * Get the certificate manager for the user
1621
+     *
1622
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1623
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1624
+     */
1625
+    public function getCertificateManager($userId = '') {
1626
+        if ($userId === '') {
1627
+            $userSession = $this->getUserSession();
1628
+            $user = $userSession->getUser();
1629
+            if (is_null($user)) {
1630
+                return null;
1631
+            }
1632
+            $userId = $user->getUID();
1633
+        }
1634
+        return new CertificateManager(
1635
+            $userId,
1636
+            new View(),
1637
+            $this->getConfig(),
1638
+            $this->getLogger(),
1639
+            $this->getSecureRandom()
1640
+        );
1641
+    }
1642
+
1643
+    /**
1644
+     * Returns an instance of the HTTP client service
1645
+     *
1646
+     * @return \OCP\Http\Client\IClientService
1647
+     */
1648
+    public function getHTTPClientService() {
1649
+        return $this->query('HttpClientService');
1650
+    }
1651
+
1652
+    /**
1653
+     * Create a new event source
1654
+     *
1655
+     * @return \OCP\IEventSource
1656
+     */
1657
+    public function createEventSource() {
1658
+        return new \OC_EventSource();
1659
+    }
1660
+
1661
+    /**
1662
+     * Get the active event logger
1663
+     *
1664
+     * The returned logger only logs data when debug mode is enabled
1665
+     *
1666
+     * @return \OCP\Diagnostics\IEventLogger
1667
+     */
1668
+    public function getEventLogger() {
1669
+        return $this->query('EventLogger');
1670
+    }
1671
+
1672
+    /**
1673
+     * Get the active query logger
1674
+     *
1675
+     * The returned logger only logs data when debug mode is enabled
1676
+     *
1677
+     * @return \OCP\Diagnostics\IQueryLogger
1678
+     */
1679
+    public function getQueryLogger() {
1680
+        return $this->query('QueryLogger');
1681
+    }
1682
+
1683
+    /**
1684
+     * Get the manager for temporary files and folders
1685
+     *
1686
+     * @return \OCP\ITempManager
1687
+     */
1688
+    public function getTempManager() {
1689
+        return $this->query('TempManager');
1690
+    }
1691
+
1692
+    /**
1693
+     * Get the app manager
1694
+     *
1695
+     * @return \OCP\App\IAppManager
1696
+     */
1697
+    public function getAppManager() {
1698
+        return $this->query('AppManager');
1699
+    }
1700
+
1701
+    /**
1702
+     * Creates a new mailer
1703
+     *
1704
+     * @return \OCP\Mail\IMailer
1705
+     */
1706
+    public function getMailer() {
1707
+        return $this->query('Mailer');
1708
+    }
1709
+
1710
+    /**
1711
+     * Get the webroot
1712
+     *
1713
+     * @return string
1714
+     */
1715
+    public function getWebRoot() {
1716
+        return $this->webRoot;
1717
+    }
1718
+
1719
+    /**
1720
+     * @return \OC\OCSClient
1721
+     */
1722
+    public function getOcsClient() {
1723
+        return $this->query('OcsClient');
1724
+    }
1725
+
1726
+    /**
1727
+     * @return \OCP\IDateTimeZone
1728
+     */
1729
+    public function getDateTimeZone() {
1730
+        return $this->query('DateTimeZone');
1731
+    }
1732
+
1733
+    /**
1734
+     * @return \OCP\IDateTimeFormatter
1735
+     */
1736
+    public function getDateTimeFormatter() {
1737
+        return $this->query('DateTimeFormatter');
1738
+    }
1739
+
1740
+    /**
1741
+     * @return \OCP\Files\Config\IMountProviderCollection
1742
+     */
1743
+    public function getMountProviderCollection() {
1744
+        return $this->query('MountConfigManager');
1745
+    }
1746
+
1747
+    /**
1748
+     * Get the IniWrapper
1749
+     *
1750
+     * @return IniGetWrapper
1751
+     */
1752
+    public function getIniWrapper() {
1753
+        return $this->query('IniWrapper');
1754
+    }
1755
+
1756
+    /**
1757
+     * @return \OCP\Command\IBus
1758
+     */
1759
+    public function getCommandBus() {
1760
+        return $this->query('AsyncCommandBus');
1761
+    }
1762
+
1763
+    /**
1764
+     * Get the trusted domain helper
1765
+     *
1766
+     * @return TrustedDomainHelper
1767
+     */
1768
+    public function getTrustedDomainHelper() {
1769
+        return $this->query('TrustedDomainHelper');
1770
+    }
1771
+
1772
+    /**
1773
+     * Get the locking provider
1774
+     *
1775
+     * @return \OCP\Lock\ILockingProvider
1776
+     * @since 8.1.0
1777
+     */
1778
+    public function getLockingProvider() {
1779
+        return $this->query('LockingProvider');
1780
+    }
1781
+
1782
+    /**
1783
+     * @return \OCP\Files\Mount\IMountManager
1784
+     **/
1785
+    function getMountManager() {
1786
+        return $this->query('MountManager');
1787
+    }
1788
+
1789
+    /** @return \OCP\Files\Config\IUserMountCache */
1790
+    function getUserMountCache() {
1791
+        return $this->query('UserMountCache');
1792
+    }
1793
+
1794
+    /**
1795
+     * Get the MimeTypeDetector
1796
+     *
1797
+     * @return \OCP\Files\IMimeTypeDetector
1798
+     */
1799
+    public function getMimeTypeDetector() {
1800
+        return $this->query('MimeTypeDetector');
1801
+    }
1802
+
1803
+    /**
1804
+     * Get the MimeTypeLoader
1805
+     *
1806
+     * @return \OCP\Files\IMimeTypeLoader
1807
+     */
1808
+    public function getMimeTypeLoader() {
1809
+        return $this->query('MimeTypeLoader');
1810
+    }
1811
+
1812
+    /**
1813
+     * Get the manager of all the capabilities
1814
+     *
1815
+     * @return \OC\CapabilitiesManager
1816
+     */
1817
+    public function getCapabilitiesManager() {
1818
+        return $this->query('CapabilitiesManager');
1819
+    }
1820
+
1821
+    /**
1822
+     * Get the EventDispatcher
1823
+     *
1824
+     * @return EventDispatcherInterface
1825
+     * @since 8.2.0
1826
+     */
1827
+    public function getEventDispatcher() {
1828
+        return $this->query('EventDispatcher');
1829
+    }
1830
+
1831
+    /**
1832
+     * Get the Notification Manager
1833
+     *
1834
+     * @return \OCP\Notification\IManager
1835
+     * @since 8.2.0
1836
+     */
1837
+    public function getNotificationManager() {
1838
+        return $this->query('NotificationManager');
1839
+    }
1840
+
1841
+    /**
1842
+     * @return \OCP\Comments\ICommentsManager
1843
+     */
1844
+    public function getCommentsManager() {
1845
+        return $this->query('CommentsManager');
1846
+    }
1847
+
1848
+    /**
1849
+     * @return \OCA\Theming\ThemingDefaults
1850
+     */
1851
+    public function getThemingDefaults() {
1852
+        return $this->query('ThemingDefaults');
1853
+    }
1854
+
1855
+    /**
1856
+     * @return \OC\IntegrityCheck\Checker
1857
+     */
1858
+    public function getIntegrityCodeChecker() {
1859
+        return $this->query('IntegrityCodeChecker');
1860
+    }
1861
+
1862
+    /**
1863
+     * @return \OC\Session\CryptoWrapper
1864
+     */
1865
+    public function getSessionCryptoWrapper() {
1866
+        return $this->query('CryptoWrapper');
1867
+    }
1868
+
1869
+    /**
1870
+     * @return CsrfTokenManager
1871
+     */
1872
+    public function getCsrfTokenManager() {
1873
+        return $this->query('CsrfTokenManager');
1874
+    }
1875
+
1876
+    /**
1877
+     * @return Throttler
1878
+     */
1879
+    public function getBruteForceThrottler() {
1880
+        return $this->query('Throttler');
1881
+    }
1882
+
1883
+    /**
1884
+     * @return IContentSecurityPolicyManager
1885
+     */
1886
+    public function getContentSecurityPolicyManager() {
1887
+        return $this->query('ContentSecurityPolicyManager');
1888
+    }
1889
+
1890
+    /**
1891
+     * @return ContentSecurityPolicyNonceManager
1892
+     */
1893
+    public function getContentSecurityPolicyNonceManager() {
1894
+        return $this->query('ContentSecurityPolicyNonceManager');
1895
+    }
1896
+
1897
+    /**
1898
+     * Not a public API as of 8.2, wait for 9.0
1899
+     *
1900
+     * @return \OCA\Files_External\Service\BackendService
1901
+     */
1902
+    public function getStoragesBackendService() {
1903
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1904
+    }
1905
+
1906
+    /**
1907
+     * Not a public API as of 8.2, wait for 9.0
1908
+     *
1909
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1910
+     */
1911
+    public function getGlobalStoragesService() {
1912
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1913
+    }
1914
+
1915
+    /**
1916
+     * Not a public API as of 8.2, wait for 9.0
1917
+     *
1918
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1919
+     */
1920
+    public function getUserGlobalStoragesService() {
1921
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1922
+    }
1923
+
1924
+    /**
1925
+     * Not a public API as of 8.2, wait for 9.0
1926
+     *
1927
+     * @return \OCA\Files_External\Service\UserStoragesService
1928
+     */
1929
+    public function getUserStoragesService() {
1930
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1931
+    }
1932
+
1933
+    /**
1934
+     * @return \OCP\Share\IManager
1935
+     */
1936
+    public function getShareManager() {
1937
+        return $this->query('ShareManager');
1938
+    }
1939
+
1940
+    /**
1941
+     * @return \OCP\Collaboration\Collaborators\ISearch
1942
+     */
1943
+    public function getCollaboratorSearch() {
1944
+        return $this->query('CollaboratorSearch');
1945
+    }
1946
+
1947
+    /**
1948
+     * @return \OCP\Collaboration\AutoComplete\IManager
1949
+     */
1950
+    public function getAutoCompleteManager(){
1951
+        return $this->query(IManager::class);
1952
+    }
1953
+
1954
+    /**
1955
+     * Returns the LDAP Provider
1956
+     *
1957
+     * @return \OCP\LDAP\ILDAPProvider
1958
+     */
1959
+    public function getLDAPProvider() {
1960
+        return $this->query('LDAPProvider');
1961
+    }
1962
+
1963
+    /**
1964
+     * @return \OCP\Settings\IManager
1965
+     */
1966
+    public function getSettingsManager() {
1967
+        return $this->query('SettingsManager');
1968
+    }
1969
+
1970
+    /**
1971
+     * @return \OCP\Files\IAppData
1972
+     */
1973
+    public function getAppDataDir($app) {
1974
+        /** @var \OC\Files\AppData\Factory $factory */
1975
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1976
+        return $factory->get($app);
1977
+    }
1978
+
1979
+    /**
1980
+     * @return \OCP\Lockdown\ILockdownManager
1981
+     */
1982
+    public function getLockdownManager() {
1983
+        return $this->query('LockdownManager');
1984
+    }
1985
+
1986
+    /**
1987
+     * @return \OCP\Federation\ICloudIdManager
1988
+     */
1989
+    public function getCloudIdManager() {
1990
+        return $this->query(ICloudIdManager::class);
1991
+    }
1992
+
1993
+    /**
1994
+     * @return \OCP\GlobalScale\IConfig
1995
+     */
1996
+    public function getGlobalScaleConfig() {
1997
+        return $this->query(IConfig::class);
1998
+    }
1999
+
2000
+    /**
2001
+     * @return \OCP\Federation\ICloudFederationProviderManager
2002
+     */
2003
+    public function getCloudFederationProviderManager() {
2004
+        return $this->query(ICloudFederationProviderManager::class);
2005
+    }
2006
+
2007
+    /**
2008
+     * @return \OCP\Remote\Api\IApiFactory
2009
+     */
2010
+    public function getRemoteApiFactory() {
2011
+        return $this->query(IApiFactory::class);
2012
+    }
2013
+
2014
+    /**
2015
+     * @return \OCP\Federation\ICloudFederationFactory
2016
+     */
2017
+    public function getCloudFederationFactory() {
2018
+        return $this->query(ICloudFederationFactory::class);
2019
+    }
2020
+
2021
+    /**
2022
+     * @return \OCP\Remote\IInstanceFactory
2023
+     */
2024
+    public function getRemoteInstanceFactory() {
2025
+        return $this->query(IInstanceFactory::class);
2026
+    }
2027 2027
 }
Please login to merge, or discard this patch.