Completed
Push — master ( a89f9a...3036b1 )
by Morris
29:19 queued 12:13
created
apps/files_sharing/lib/External/Manager.php 3 patches
Doc Comments   +7 added lines, -4 removed lines patch added patch discarded remove patch
@@ -210,12 +210,12 @@  discard block
 block discarded – undo
210 210
 	 * @param $password
211 211
 	 * @param $name
212 212
 	 * @param $owner
213
-	 * @param $user
213
+	 * @param string $user
214 214
 	 * @param $mountPoint
215 215
 	 * @param $hash
216
-	 * @param $accepted
216
+	 * @param integer $accepted
217 217
 	 * @param $remoteId
218
-	 * @param $parent
218
+	 * @param integer $parent
219 219
 	 * @param $shareType
220 220
 	 * @return bool
221 221
 	 */
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 	 *
410 410
 	 * @param string $remoteDomain
411 411
 	 * @param string $token
412
-	 * @param $remoteId id of the share
412
+	 * @param integer $remoteId id of the share
413 413
 	 * @param string $feedback
414 414
 	 * @return bool
415 415
 	 */
@@ -506,6 +506,9 @@  discard block
 block discarded – undo
506 506
 		return $result;
507 507
 	}
508 508
 
509
+	/**
510
+	 * @param string $mountPoint
511
+	 */
509 512
 	public function removeShare($mountPoint) {
510 513
 
511 514
 		$mountPointObj = $this->mountManager->find($mountPoint);
Please login to merge, or discard this patch.
Indentation   +561 added lines, -561 removed lines patch added patch discarded remove patch
@@ -46,607 +46,607 @@
 block discarded – undo
46 46
 use OCP\Share;
47 47
 
48 48
 class Manager {
49
-	const STORAGE = '\OCA\Files_Sharing\External\Storage';
50
-
51
-	/**
52
-	 * @var string
53
-	 */
54
-	private $uid;
55
-
56
-	/**
57
-	 * @var IDBConnection
58
-	 */
59
-	private $connection;
60
-
61
-	/**
62
-	 * @var \OC\Files\Mount\Manager
63
-	 */
64
-	private $mountManager;
65
-
66
-	/**
67
-	 * @var IStorageFactory
68
-	 */
69
-	private $storageLoader;
70
-
71
-	/**
72
-	 * @var IClientService
73
-	 */
74
-	private $clientService;
75
-
76
-	/**
77
-	 * @var IManager
78
-	 */
79
-	private $notificationManager;
80
-
81
-	/**
82
-	 * @var IDiscoveryService
83
-	 */
84
-	private $discoveryService;
85
-
86
-	/** @var ICloudFederationProviderManager */
87
-	private $cloudFederationProviderManager;
88
-
89
-	/** @var ICloudFederationFactory */
90
-	private $cloudFederationFactory;
91
-
92
-	/** @var IGroupManager  */
93
-	private $groupManager;
94
-
95
-	/** @var IUserManager */
96
-	private $userManager;
97
-
98
-	/**
99
-	 * @param IDBConnection $connection
100
-	 * @param \OC\Files\Mount\Manager $mountManager
101
-	 * @param IStorageFactory $storageLoader
102
-	 * @param IClientService $clientService
103
-	 * @param IManager $notificationManager
104
-	 * @param IDiscoveryService $discoveryService
105
-	 * @param ICloudFederationProviderManager $cloudFederationProviderManager
106
-	 * @param ICloudFederationFactory $cloudFederationFactory
107
-	 * @param IGroupManager $groupManager
108
-	 * @param IUserManager $userManager
109
-	 * @param string $uid
110
-	 */
111
-	public function __construct(IDBConnection $connection,
112
-								\OC\Files\Mount\Manager $mountManager,
113
-								IStorageFactory $storageLoader,
114
-								IClientService $clientService,
115
-								IManager $notificationManager,
116
-								IDiscoveryService $discoveryService,
117
-								ICloudFederationProviderManager $cloudFederationProviderManager,
118
-								ICloudFederationFactory $cloudFederationFactory,
119
-								IGroupManager $groupManager,
120
-								IUserManager $userManager,
121
-								$uid) {
122
-		$this->connection = $connection;
123
-		$this->mountManager = $mountManager;
124
-		$this->storageLoader = $storageLoader;
125
-		$this->clientService = $clientService;
126
-		$this->uid = $uid;
127
-		$this->notificationManager = $notificationManager;
128
-		$this->discoveryService = $discoveryService;
129
-		$this->cloudFederationProviderManager = $cloudFederationProviderManager;
130
-		$this->cloudFederationFactory = $cloudFederationFactory;
131
-		$this->groupManager = $groupManager;
132
-		$this->userManager = $userManager;
133
-	}
134
-
135
-	/**
136
-	 * add new server-to-server share
137
-	 *
138
-	 * @param string $remote
139
-	 * @param string $token
140
-	 * @param string $password
141
-	 * @param string $name
142
-	 * @param string $owner
143
-	 * @param int $shareType
144
-	 * @param boolean $accepted
145
-	 * @param string $user
146
-	 * @param int $remoteId
147
-	 * @param int $parent
148
-	 * @return Mount|null
149
-	 * @throws \Doctrine\DBAL\DBALException
150
-	 */
151
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
152
-
153
-		$user = $user ? $user : $this->uid;
154
-		$accepted = $accepted ? 1 : 0;
155
-		$name = Filesystem::normalizePath('/' . $name);
156
-
157
-		if (!$accepted) {
158
-			// To avoid conflicts with the mount point generation later,
159
-			// we only use a temporary mount point name here. The real
160
-			// mount point name will be generated when accepting the share,
161
-			// using the original share item name.
162
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
163
-			$mountPoint = $tmpMountPointName;
164
-			$hash = md5($tmpMountPointName);
165
-			$data = [
166
-				'remote'		=> $remote,
167
-				'share_token'	=> $token,
168
-				'password'		=> $password,
169
-				'name'			=> $name,
170
-				'owner'			=> $owner,
171
-				'user'			=> $user,
172
-				'mountpoint'	=> $mountPoint,
173
-				'mountpoint_hash'	=> $hash,
174
-				'accepted'		=> $accepted,
175
-				'remote_id'		=> $remoteId,
176
-				'share_type'    => $shareType,
177
-			];
178
-
179
-			$i = 1;
180
-			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
181
-				// The external share already exists for the user
182
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
183
-				$data['mountpoint_hash'] = md5($data['mountpoint']);
184
-				$i++;
185
-			}
186
-			return null;
187
-		}
188
-
189
-		$mountPoint = Files::buildNotExistingFileName('/', $name);
190
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
191
-		$hash = md5($mountPoint);
192
-
193
-		$this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
194
-
195
-		$options = array(
196
-			'remote'	=> $remote,
197
-			'token'		=> $token,
198
-			'password'	=> $password,
199
-			'mountpoint'	=> $mountPoint,
200
-			'owner'		=> $owner
201
-		);
202
-		return $this->mountShare($options);
203
-	}
204
-
205
-	/**
206
-	 * write remote share to the database
207
-	 *
208
-	 * @param $remote
209
-	 * @param $token
210
-	 * @param $password
211
-	 * @param $name
212
-	 * @param $owner
213
-	 * @param $user
214
-	 * @param $mountPoint
215
-	 * @param $hash
216
-	 * @param $accepted
217
-	 * @param $remoteId
218
-	 * @param $parent
219
-	 * @param $shareType
220
-	 * @return bool
221
-	 */
222
-	private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType) {
223
-		$query = $this->connection->prepare('
49
+    const STORAGE = '\OCA\Files_Sharing\External\Storage';
50
+
51
+    /**
52
+     * @var string
53
+     */
54
+    private $uid;
55
+
56
+    /**
57
+     * @var IDBConnection
58
+     */
59
+    private $connection;
60
+
61
+    /**
62
+     * @var \OC\Files\Mount\Manager
63
+     */
64
+    private $mountManager;
65
+
66
+    /**
67
+     * @var IStorageFactory
68
+     */
69
+    private $storageLoader;
70
+
71
+    /**
72
+     * @var IClientService
73
+     */
74
+    private $clientService;
75
+
76
+    /**
77
+     * @var IManager
78
+     */
79
+    private $notificationManager;
80
+
81
+    /**
82
+     * @var IDiscoveryService
83
+     */
84
+    private $discoveryService;
85
+
86
+    /** @var ICloudFederationProviderManager */
87
+    private $cloudFederationProviderManager;
88
+
89
+    /** @var ICloudFederationFactory */
90
+    private $cloudFederationFactory;
91
+
92
+    /** @var IGroupManager  */
93
+    private $groupManager;
94
+
95
+    /** @var IUserManager */
96
+    private $userManager;
97
+
98
+    /**
99
+     * @param IDBConnection $connection
100
+     * @param \OC\Files\Mount\Manager $mountManager
101
+     * @param IStorageFactory $storageLoader
102
+     * @param IClientService $clientService
103
+     * @param IManager $notificationManager
104
+     * @param IDiscoveryService $discoveryService
105
+     * @param ICloudFederationProviderManager $cloudFederationProviderManager
106
+     * @param ICloudFederationFactory $cloudFederationFactory
107
+     * @param IGroupManager $groupManager
108
+     * @param IUserManager $userManager
109
+     * @param string $uid
110
+     */
111
+    public function __construct(IDBConnection $connection,
112
+                                \OC\Files\Mount\Manager $mountManager,
113
+                                IStorageFactory $storageLoader,
114
+                                IClientService $clientService,
115
+                                IManager $notificationManager,
116
+                                IDiscoveryService $discoveryService,
117
+                                ICloudFederationProviderManager $cloudFederationProviderManager,
118
+                                ICloudFederationFactory $cloudFederationFactory,
119
+                                IGroupManager $groupManager,
120
+                                IUserManager $userManager,
121
+                                $uid) {
122
+        $this->connection = $connection;
123
+        $this->mountManager = $mountManager;
124
+        $this->storageLoader = $storageLoader;
125
+        $this->clientService = $clientService;
126
+        $this->uid = $uid;
127
+        $this->notificationManager = $notificationManager;
128
+        $this->discoveryService = $discoveryService;
129
+        $this->cloudFederationProviderManager = $cloudFederationProviderManager;
130
+        $this->cloudFederationFactory = $cloudFederationFactory;
131
+        $this->groupManager = $groupManager;
132
+        $this->userManager = $userManager;
133
+    }
134
+
135
+    /**
136
+     * add new server-to-server share
137
+     *
138
+     * @param string $remote
139
+     * @param string $token
140
+     * @param string $password
141
+     * @param string $name
142
+     * @param string $owner
143
+     * @param int $shareType
144
+     * @param boolean $accepted
145
+     * @param string $user
146
+     * @param int $remoteId
147
+     * @param int $parent
148
+     * @return Mount|null
149
+     * @throws \Doctrine\DBAL\DBALException
150
+     */
151
+    public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
152
+
153
+        $user = $user ? $user : $this->uid;
154
+        $accepted = $accepted ? 1 : 0;
155
+        $name = Filesystem::normalizePath('/' . $name);
156
+
157
+        if (!$accepted) {
158
+            // To avoid conflicts with the mount point generation later,
159
+            // we only use a temporary mount point name here. The real
160
+            // mount point name will be generated when accepting the share,
161
+            // using the original share item name.
162
+            $tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
163
+            $mountPoint = $tmpMountPointName;
164
+            $hash = md5($tmpMountPointName);
165
+            $data = [
166
+                'remote'		=> $remote,
167
+                'share_token'	=> $token,
168
+                'password'		=> $password,
169
+                'name'			=> $name,
170
+                'owner'			=> $owner,
171
+                'user'			=> $user,
172
+                'mountpoint'	=> $mountPoint,
173
+                'mountpoint_hash'	=> $hash,
174
+                'accepted'		=> $accepted,
175
+                'remote_id'		=> $remoteId,
176
+                'share_type'    => $shareType,
177
+            ];
178
+
179
+            $i = 1;
180
+            while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
181
+                // The external share already exists for the user
182
+                $data['mountpoint'] = $tmpMountPointName . '-' . $i;
183
+                $data['mountpoint_hash'] = md5($data['mountpoint']);
184
+                $i++;
185
+            }
186
+            return null;
187
+        }
188
+
189
+        $mountPoint = Files::buildNotExistingFileName('/', $name);
190
+        $mountPoint = Filesystem::normalizePath('/' . $mountPoint);
191
+        $hash = md5($mountPoint);
192
+
193
+        $this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
194
+
195
+        $options = array(
196
+            'remote'	=> $remote,
197
+            'token'		=> $token,
198
+            'password'	=> $password,
199
+            'mountpoint'	=> $mountPoint,
200
+            'owner'		=> $owner
201
+        );
202
+        return $this->mountShare($options);
203
+    }
204
+
205
+    /**
206
+     * write remote share to the database
207
+     *
208
+     * @param $remote
209
+     * @param $token
210
+     * @param $password
211
+     * @param $name
212
+     * @param $owner
213
+     * @param $user
214
+     * @param $mountPoint
215
+     * @param $hash
216
+     * @param $accepted
217
+     * @param $remoteId
218
+     * @param $parent
219
+     * @param $shareType
220
+     * @return bool
221
+     */
222
+    private function writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType) {
223
+        $query = $this->connection->prepare('
224 224
 				INSERT INTO `*PREFIX*share_external`
225 225
 					(`remote`, `share_token`, `password`, `name`, `owner`, `user`, `mountpoint`, `mountpoint_hash`, `accepted`, `remote_id`, `parent`, `share_type`)
226 226
 				VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
227 227
 			');
228
-		return $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
229
-	}
230
-
231
-	/**
232
-	 * get share
233
-	 *
234
-	 * @param int $id share id
235
-	 * @return mixed share of false
236
-	 */
237
-	public function getShare($id) {
238
-		$getShare = $this->connection->prepare('
228
+        return $query->execute(array($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType));
229
+    }
230
+
231
+    /**
232
+     * get share
233
+     *
234
+     * @param int $id share id
235
+     * @return mixed share of false
236
+     */
237
+    public function getShare($id) {
238
+        $getShare = $this->connection->prepare('
239 239
 			SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`, `parent`, `share_type`, `password`, `mountpoint_hash`
240 240
 			FROM  `*PREFIX*share_external`
241 241
 			WHERE `id` = ?');
242
-		$result = $getShare->execute(array($id));
243
-
244
-		$share = $result ? $getShare->fetch() : [];
245
-
246
-		$validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
247
-
248
-		// check if the user is allowed to access it
249
-		if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_USER && $share['user'] === $this->uid) {
250
-			return $share;
251
-		} else if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
252
-			$user = $this->userManager->get($this->uid);
253
-			if ($this->groupManager->get($share['user'])->inGroup($user)) {
254
-				return $share;
255
-			}
256
-		}
257
-
258
-		return false;
259
-
260
-	}
261
-
262
-	/**
263
-	 * accept server-to-server share
264
-	 *
265
-	 * @param int $id
266
-	 * @return bool True if the share could be accepted, false otherwise
267
-	 */
268
-	public function acceptShare($id) {
269
-
270
-		$share = $this->getShare($id);
271
-		$result = false;
272
-
273
-		if ($share) {
274
-			\OC_Util::setupFS($this->uid);
275
-			$shareFolder = Helper::getShareFolder();
276
-			$mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
277
-			$mountPoint = Filesystem::normalizePath($mountPoint);
278
-			$hash = md5($mountPoint);
279
-			$userShareAccepted = false;
280
-
281
-			if((int)$share['share_type'] === Share::SHARE_TYPE_USER) {
282
-				$acceptShare = $this->connection->prepare('
242
+        $result = $getShare->execute(array($id));
243
+
244
+        $share = $result ? $getShare->fetch() : [];
245
+
246
+        $validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
247
+
248
+        // check if the user is allowed to access it
249
+        if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_USER && $share['user'] === $this->uid) {
250
+            return $share;
251
+        } else if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
252
+            $user = $this->userManager->get($this->uid);
253
+            if ($this->groupManager->get($share['user'])->inGroup($user)) {
254
+                return $share;
255
+            }
256
+        }
257
+
258
+        return false;
259
+
260
+    }
261
+
262
+    /**
263
+     * accept server-to-server share
264
+     *
265
+     * @param int $id
266
+     * @return bool True if the share could be accepted, false otherwise
267
+     */
268
+    public function acceptShare($id) {
269
+
270
+        $share = $this->getShare($id);
271
+        $result = false;
272
+
273
+        if ($share) {
274
+            \OC_Util::setupFS($this->uid);
275
+            $shareFolder = Helper::getShareFolder();
276
+            $mountPoint = Files::buildNotExistingFileName($shareFolder, $share['name']);
277
+            $mountPoint = Filesystem::normalizePath($mountPoint);
278
+            $hash = md5($mountPoint);
279
+            $userShareAccepted = false;
280
+
281
+            if((int)$share['share_type'] === Share::SHARE_TYPE_USER) {
282
+                $acceptShare = $this->connection->prepare('
283 283
 				UPDATE `*PREFIX*share_external`
284 284
 				SET `accepted` = ?,
285 285
 					`mountpoint` = ?,
286 286
 					`mountpoint_hash` = ?
287 287
 				WHERE `id` = ? AND `user` = ?');
288
-				$userShareAccepted = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
289
-			} else {
290
-				$result = $this->writeShareToDb(
291
-					$share['remote'],
292
-					$share['share_token'],
293
-					$share['password'],
294
-					$share['name'],
295
-					$share['owner'],
296
-					$this->uid,
297
-					$mountPoint, $hash, 1,
298
-					$share['remote_id'],
299
-					$id,
300
-					$share['share_type']);
301
-			}
302
-			if ($userShareAccepted === true) {
303
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
304
-				\OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
305
-				$result = true;
306
-			}
307
-		}
308
-
309
-		// Make sure the user has no notification for something that does not exist anymore.
310
-		$this->processNotification($id);
311
-
312
-		return $result;
313
-	}
314
-
315
-	/**
316
-	 * decline server-to-server share
317
-	 *
318
-	 * @param int $id
319
-	 * @return bool True if the share could be declined, false otherwise
320
-	 */
321
-	public function declineShare($id) {
322
-
323
-		$share = $this->getShare($id);
324
-		$result = false;
325
-
326
-		if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
327
-			$removeShare = $this->connection->prepare('
288
+                $userShareAccepted = $acceptShare->execute(array(1, $mountPoint, $hash, $id, $this->uid));
289
+            } else {
290
+                $result = $this->writeShareToDb(
291
+                    $share['remote'],
292
+                    $share['share_token'],
293
+                    $share['password'],
294
+                    $share['name'],
295
+                    $share['owner'],
296
+                    $this->uid,
297
+                    $mountPoint, $hash, 1,
298
+                    $share['remote_id'],
299
+                    $id,
300
+                    $share['share_type']);
301
+            }
302
+            if ($userShareAccepted === true) {
303
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'accept');
304
+                \OC_Hook::emit(Share::class, 'federated_share_added', ['server' => $share['remote']]);
305
+                $result = true;
306
+            }
307
+        }
308
+
309
+        // Make sure the user has no notification for something that does not exist anymore.
310
+        $this->processNotification($id);
311
+
312
+        return $result;
313
+    }
314
+
315
+    /**
316
+     * decline server-to-server share
317
+     *
318
+     * @param int $id
319
+     * @return bool True if the share could be declined, false otherwise
320
+     */
321
+    public function declineShare($id) {
322
+
323
+        $share = $this->getShare($id);
324
+        $result = false;
325
+
326
+        if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
327
+            $removeShare = $this->connection->prepare('
328 328
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
329
-			$removeShare->execute(array($id, $this->uid));
330
-			$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
331
-
332
-			$this->processNotification($id);
333
-			$result = true;
334
-		} else if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
335
-			$result = $this->writeShareToDb(
336
-				$share['remote'],
337
-				$share['share_token'],
338
-				$share['password'],
339
-				$share['name'],
340
-				$share['owner'],
341
-				$this->uid,
342
-				$share['mountpoint'],
343
-				$share['mountpoint_hash'],
344
-				0,
345
-				$share['remote_id'],
346
-				$id,
347
-				$share['share_type']);
348
-			$this->processNotification($id);
349
-		}
350
-
351
-		return $result;
352
-	}
353
-
354
-	/**
355
-	 * @param int $remoteShare
356
-	 */
357
-	public function processNotification($remoteShare) {
358
-		$filter = $this->notificationManager->createNotification();
359
-		$filter->setApp('files_sharing')
360
-			->setUser($this->uid)
361
-			->setObject('remote_share', (int) $remoteShare);
362
-		$this->notificationManager->markProcessed($filter);
363
-	}
364
-
365
-	/**
366
-	 * inform remote server whether server-to-server share was accepted/declined
367
-	 *
368
-	 * @param string $remote
369
-	 * @param string $token
370
-	 * @param int $remoteId Share id on the remote host
371
-	 * @param string $feedback
372
-	 * @return boolean
373
-	 */
374
-	private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
375
-
376
-		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
377
-
378
-		if($result === true) {
379
-			return true;
380
-		}
381
-
382
-		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
383
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
384
-
385
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
386
-		$fields = array('token' => $token);
387
-
388
-		$client = $this->clientService->newClient();
389
-
390
-		try {
391
-			$response = $client->post(
392
-				$url,
393
-				[
394
-					'body' => $fields,
395
-					'connect_timeout' => 10,
396
-				]
397
-			);
398
-		} catch (\Exception $e) {
399
-			return false;
400
-		}
401
-
402
-		$status = json_decode($response->getBody(), true);
403
-
404
-		return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
405
-	}
406
-
407
-	/**
408
-	 * try send accept message to ocm end-point
409
-	 *
410
-	 * @param string $remoteDomain
411
-	 * @param string $token
412
-	 * @param $remoteId id of the share
413
-	 * @param string $feedback
414
-	 * @return bool
415
-	 */
416
-	protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
417
-		switch ($feedback) {
418
-			case 'accept':
419
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
420
-				$notification->setMessage(
421
-					'SHARE_ACCEPTED',
422
-					'file',
423
-					$remoteId,
424
-					[
425
-						'sharedSecret' => $token,
426
-						'message' => 'Recipient accept the share'
427
-					]
428
-
429
-				);
430
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
431
-			case 'decline':
432
-				$notification = $this->cloudFederationFactory->getCloudFederationNotification();
433
-				$notification->setMessage(
434
-					'SHARE_DECLINED',
435
-					'file',
436
-					$remoteId,
437
-					[
438
-						'sharedSecret' => $token,
439
-						'message' => 'Recipient declined the share'
440
-					]
441
-
442
-				);
443
-				return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
444
-		}
445
-
446
-		return false;
447
-
448
-	}
449
-
450
-
451
-	/**
452
-	 * remove '/user/files' from the path and trailing slashes
453
-	 *
454
-	 * @param string $path
455
-	 * @return string
456
-	 */
457
-	protected function stripPath($path) {
458
-		$prefix = '/' . $this->uid . '/files';
459
-		return rtrim(substr($path, strlen($prefix)), '/');
460
-	}
461
-
462
-	public function getMount($data) {
463
-		$data['manager'] = $this;
464
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
465
-		$data['mountpoint'] = $mountPoint;
466
-		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
467
-		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
468
-	}
469
-
470
-	/**
471
-	 * @param array $data
472
-	 * @return Mount
473
-	 */
474
-	protected function mountShare($data) {
475
-		$mount = $this->getMount($data);
476
-		$this->mountManager->addMount($mount);
477
-		return $mount;
478
-	}
479
-
480
-	/**
481
-	 * @return \OC\Files\Mount\Manager
482
-	 */
483
-	public function getMountManager() {
484
-		return $this->mountManager;
485
-	}
486
-
487
-	/**
488
-	 * @param string $source
489
-	 * @param string $target
490
-	 * @return bool
491
-	 */
492
-	public function setMountPoint($source, $target) {
493
-		$source = $this->stripPath($source);
494
-		$target = $this->stripPath($target);
495
-		$sourceHash = md5($source);
496
-		$targetHash = md5($target);
497
-
498
-		$query = $this->connection->prepare('
329
+            $removeShare->execute(array($id, $this->uid));
330
+            $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
331
+
332
+            $this->processNotification($id);
333
+            $result = true;
334
+        } else if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
335
+            $result = $this->writeShareToDb(
336
+                $share['remote'],
337
+                $share['share_token'],
338
+                $share['password'],
339
+                $share['name'],
340
+                $share['owner'],
341
+                $this->uid,
342
+                $share['mountpoint'],
343
+                $share['mountpoint_hash'],
344
+                0,
345
+                $share['remote_id'],
346
+                $id,
347
+                $share['share_type']);
348
+            $this->processNotification($id);
349
+        }
350
+
351
+        return $result;
352
+    }
353
+
354
+    /**
355
+     * @param int $remoteShare
356
+     */
357
+    public function processNotification($remoteShare) {
358
+        $filter = $this->notificationManager->createNotification();
359
+        $filter->setApp('files_sharing')
360
+            ->setUser($this->uid)
361
+            ->setObject('remote_share', (int) $remoteShare);
362
+        $this->notificationManager->markProcessed($filter);
363
+    }
364
+
365
+    /**
366
+     * inform remote server whether server-to-server share was accepted/declined
367
+     *
368
+     * @param string $remote
369
+     * @param string $token
370
+     * @param int $remoteId Share id on the remote host
371
+     * @param string $feedback
372
+     * @return boolean
373
+     */
374
+    private function sendFeedbackToRemote($remote, $token, $remoteId, $feedback) {
375
+
376
+        $result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
377
+
378
+        if($result === true) {
379
+            return true;
380
+        }
381
+
382
+        $federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
383
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
384
+
385
+        $url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
386
+        $fields = array('token' => $token);
387
+
388
+        $client = $this->clientService->newClient();
389
+
390
+        try {
391
+            $response = $client->post(
392
+                $url,
393
+                [
394
+                    'body' => $fields,
395
+                    'connect_timeout' => 10,
396
+                ]
397
+            );
398
+        } catch (\Exception $e) {
399
+            return false;
400
+        }
401
+
402
+        $status = json_decode($response->getBody(), true);
403
+
404
+        return ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200);
405
+    }
406
+
407
+    /**
408
+     * try send accept message to ocm end-point
409
+     *
410
+     * @param string $remoteDomain
411
+     * @param string $token
412
+     * @param $remoteId id of the share
413
+     * @param string $feedback
414
+     * @return bool
415
+     */
416
+    protected function tryOCMEndPoint($remoteDomain, $token, $remoteId, $feedback) {
417
+        switch ($feedback) {
418
+            case 'accept':
419
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
420
+                $notification->setMessage(
421
+                    'SHARE_ACCEPTED',
422
+                    'file',
423
+                    $remoteId,
424
+                    [
425
+                        'sharedSecret' => $token,
426
+                        'message' => 'Recipient accept the share'
427
+                    ]
428
+
429
+                );
430
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
431
+            case 'decline':
432
+                $notification = $this->cloudFederationFactory->getCloudFederationNotification();
433
+                $notification->setMessage(
434
+                    'SHARE_DECLINED',
435
+                    'file',
436
+                    $remoteId,
437
+                    [
438
+                        'sharedSecret' => $token,
439
+                        'message' => 'Recipient declined the share'
440
+                    ]
441
+
442
+                );
443
+                return $this->cloudFederationProviderManager->sendNotification($remoteDomain, $notification);
444
+        }
445
+
446
+        return false;
447
+
448
+    }
449
+
450
+
451
+    /**
452
+     * remove '/user/files' from the path and trailing slashes
453
+     *
454
+     * @param string $path
455
+     * @return string
456
+     */
457
+    protected function stripPath($path) {
458
+        $prefix = '/' . $this->uid . '/files';
459
+        return rtrim(substr($path, strlen($prefix)), '/');
460
+    }
461
+
462
+    public function getMount($data) {
463
+        $data['manager'] = $this;
464
+        $mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
465
+        $data['mountpoint'] = $mountPoint;
466
+        $data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
467
+        return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
468
+    }
469
+
470
+    /**
471
+     * @param array $data
472
+     * @return Mount
473
+     */
474
+    protected function mountShare($data) {
475
+        $mount = $this->getMount($data);
476
+        $this->mountManager->addMount($mount);
477
+        return $mount;
478
+    }
479
+
480
+    /**
481
+     * @return \OC\Files\Mount\Manager
482
+     */
483
+    public function getMountManager() {
484
+        return $this->mountManager;
485
+    }
486
+
487
+    /**
488
+     * @param string $source
489
+     * @param string $target
490
+     * @return bool
491
+     */
492
+    public function setMountPoint($source, $target) {
493
+        $source = $this->stripPath($source);
494
+        $target = $this->stripPath($target);
495
+        $sourceHash = md5($source);
496
+        $targetHash = md5($target);
497
+
498
+        $query = $this->connection->prepare('
499 499
 			UPDATE `*PREFIX*share_external`
500 500
 			SET `mountpoint` = ?, `mountpoint_hash` = ?
501 501
 			WHERE `mountpoint_hash` = ?
502 502
 			AND `user` = ?
503 503
 		');
504
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
504
+        $result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
505 505
 
506
-		return $result;
507
-	}
506
+        return $result;
507
+    }
508 508
 
509
-	public function removeShare($mountPoint) {
509
+    public function removeShare($mountPoint) {
510 510
 
511
-		$mountPointObj = $this->mountManager->find($mountPoint);
512
-		$id = $mountPointObj->getStorage()->getCache()->getId('');
511
+        $mountPointObj = $this->mountManager->find($mountPoint);
512
+        $id = $mountPointObj->getStorage()->getCache()->getId('');
513 513
 
514
-		$mountPoint = $this->stripPath($mountPoint);
515
-		$hash = md5($mountPoint);
514
+        $mountPoint = $this->stripPath($mountPoint);
515
+        $hash = md5($mountPoint);
516 516
 
517
-		$getShare = $this->connection->prepare('
517
+        $getShare = $this->connection->prepare('
518 518
 			SELECT `remote`, `share_token`, `remote_id`, `share_type`, `id`
519 519
 			FROM  `*PREFIX*share_external`
520 520
 			WHERE `mountpoint_hash` = ? AND `user` = ?');
521
-		$result = $getShare->execute(array($hash, $this->uid));
522
-
523
-		$share = $getShare->fetch();
524
-		$getShare->closeCursor();
525
-		if ($result && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
526
-			try {
527
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
528
-			} catch (\Exception $e) {
529
-				// if we fail to notify the remote (probably cause the remote is down)
530
-				// we still want the share to be gone to prevent undeletable remotes
531
-			}
532
-
533
-			$query = $this->connection->prepare('
521
+        $result = $getShare->execute(array($hash, $this->uid));
522
+
523
+        $share = $getShare->fetch();
524
+        $getShare->closeCursor();
525
+        if ($result && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
526
+            try {
527
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
528
+            } catch (\Exception $e) {
529
+                // if we fail to notify the remote (probably cause the remote is down)
530
+                // we still want the share to be gone to prevent undeletable remotes
531
+            }
532
+
533
+            $query = $this->connection->prepare('
534 534
 			DELETE FROM `*PREFIX*share_external`
535 535
 			WHERE `id` = ?
536 536
 			');
537
-			$result = (bool)$query->execute(array((int)$share['id']));
538
-		} else if ($result && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
539
-			$query = $this->connection->prepare('
537
+            $result = (bool)$query->execute(array((int)$share['id']));
538
+        } else if ($result && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
539
+            $query = $this->connection->prepare('
540 540
 				UPDATE `*PREFIX*share_external`
541 541
 				SET `accepted` = ?
542 542
 				WHERE `id` = ?');
543
-			$result = (bool)$query->execute(array(0, (int)$share['id']));
544
-		}
545
-
546
-		if($result) {
547
-			$this->removeReShares($id);
548
-		}
549
-
550
-		return $result;
551
-	}
552
-
553
-	/**
554
-	 * remove re-shares from share table and mapping in the federated_reshares table
555
-	 *
556
-	 * @param $mountPointId
557
-	 */
558
-	protected function removeReShares($mountPointId) {
559
-		$selectQuery = $this->connection->getQueryBuilder();
560
-		$query = $this->connection->getQueryBuilder();
561
-		$selectQuery->select('id')->from('share')
562
-			->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
563
-		$select = $selectQuery->getSQL();
564
-
565
-
566
-		$query->delete('federated_reshares')
567
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
568
-		$query->execute();
569
-
570
-		$deleteReShares = $this->connection->getQueryBuilder();
571
-		$deleteReShares->delete('share')
572
-			->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
573
-		$deleteReShares->execute();
574
-	}
575
-
576
-	/**
577
-	 * remove all shares for user $uid if the user was deleted
578
-	 *
579
-	 * @param string $uid
580
-	 * @return bool
581
-	 */
582
-	public function removeUserShares($uid) {
583
-		$getShare = $this->connection->prepare('
543
+            $result = (bool)$query->execute(array(0, (int)$share['id']));
544
+        }
545
+
546
+        if($result) {
547
+            $this->removeReShares($id);
548
+        }
549
+
550
+        return $result;
551
+    }
552
+
553
+    /**
554
+     * remove re-shares from share table and mapping in the federated_reshares table
555
+     *
556
+     * @param $mountPointId
557
+     */
558
+    protected function removeReShares($mountPointId) {
559
+        $selectQuery = $this->connection->getQueryBuilder();
560
+        $query = $this->connection->getQueryBuilder();
561
+        $selectQuery->select('id')->from('share')
562
+            ->where($selectQuery->expr()->eq('file_source', $query->createNamedParameter($mountPointId)));
563
+        $select = $selectQuery->getSQL();
564
+
565
+
566
+        $query->delete('federated_reshares')
567
+            ->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
568
+        $query->execute();
569
+
570
+        $deleteReShares = $this->connection->getQueryBuilder();
571
+        $deleteReShares->delete('share')
572
+            ->where($deleteReShares->expr()->eq('file_source', $deleteReShares->createNamedParameter($mountPointId)));
573
+        $deleteReShares->execute();
574
+    }
575
+
576
+    /**
577
+     * remove all shares for user $uid if the user was deleted
578
+     *
579
+     * @param string $uid
580
+     * @return bool
581
+     */
582
+    public function removeUserShares($uid) {
583
+        $getShare = $this->connection->prepare('
584 584
 			SELECT `remote`, `share_token`, `remote_id`
585 585
 			FROM  `*PREFIX*share_external`
586 586
 			WHERE `user` = ?');
587
-		$result = $getShare->execute(array($uid));
587
+        $result = $getShare->execute(array($uid));
588 588
 
589
-		if ($result) {
590
-			$shares = $getShare->fetchAll();
591
-			foreach($shares as $share) {
592
-				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
593
-			}
594
-		}
589
+        if ($result) {
590
+            $shares = $getShare->fetchAll();
591
+            foreach($shares as $share) {
592
+                $this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
593
+            }
594
+        }
595 595
 
596
-		$query = $this->connection->prepare('
596
+        $query = $this->connection->prepare('
597 597
 			DELETE FROM `*PREFIX*share_external`
598 598
 			WHERE `user` = ?
599 599
 		');
600
-		return (bool)$query->execute(array($uid));
601
-	}
602
-
603
-	/**
604
-	 * return a list of shares which are not yet accepted by the user
605
-	 *
606
-	 * @return array list of open server-to-server shares
607
-	 */
608
-	public function getOpenShares() {
609
-		return $this->getShares(false);
610
-	}
611
-
612
-	/**
613
-	 * return a list of shares which are accepted by the user
614
-	 *
615
-	 * @return array list of accepted server-to-server shares
616
-	 */
617
-	public function getAcceptedShares() {
618
-		return $this->getShares(true);
619
-	}
620
-
621
-	/**
622
-	 * return a list of shares for the user
623
-	 *
624
-	 * @param bool|null $accepted True for accepted only,
625
-	 *                            false for not accepted,
626
-	 *                            null for all shares of the user
627
-	 * @return array list of open server-to-server shares
628
-	 */
629
-	private function getShares($accepted) {
630
-		$user = $this->userManager->get($this->uid);
631
-		$groups = $this->groupManager->getUserGroups($user);
632
-		$userGroups = [];
633
-		foreach ($groups as $group) {
634
-			$userGroups[] = $group->getGID();
635
-		}
636
-
637
-		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
600
+        return (bool)$query->execute(array($uid));
601
+    }
602
+
603
+    /**
604
+     * return a list of shares which are not yet accepted by the user
605
+     *
606
+     * @return array list of open server-to-server shares
607
+     */
608
+    public function getOpenShares() {
609
+        return $this->getShares(false);
610
+    }
611
+
612
+    /**
613
+     * return a list of shares which are accepted by the user
614
+     *
615
+     * @return array list of accepted server-to-server shares
616
+     */
617
+    public function getAcceptedShares() {
618
+        return $this->getShares(true);
619
+    }
620
+
621
+    /**
622
+     * return a list of shares for the user
623
+     *
624
+     * @param bool|null $accepted True for accepted only,
625
+     *                            false for not accepted,
626
+     *                            null for all shares of the user
627
+     * @return array list of open server-to-server shares
628
+     */
629
+    private function getShares($accepted) {
630
+        $user = $this->userManager->get($this->uid);
631
+        $groups = $this->groupManager->getUserGroups($user);
632
+        $userGroups = [];
633
+        foreach ($groups as $group) {
634
+            $userGroups[] = $group->getGID();
635
+        }
636
+
637
+        $query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
638 638
 		          FROM `*PREFIX*share_external` 
639 639
 				  WHERE (`user` = ? OR `user` IN (?))';
640
-		$parameters = [$this->uid, implode(',',$userGroups)];
641
-		if (!is_null($accepted)) {
642
-			$query .= ' AND `accepted` = ?';
643
-			$parameters[] = (int) $accepted;
644
-		}
645
-		$query .= ' ORDER BY `id` ASC';
646
-
647
-		$shares = $this->connection->prepare($query);
648
-		$result = $shares->execute($parameters);
649
-
650
-		return $result ? $shares->fetchAll() : [];
651
-	}
640
+        $parameters = [$this->uid, implode(',',$userGroups)];
641
+        if (!is_null($accepted)) {
642
+            $query .= ' AND `accepted` = ?';
643
+            $parameters[] = (int) $accepted;
644
+        }
645
+        $query .= ' ORDER BY `id` ASC';
646
+
647
+        $shares = $this->connection->prepare($query);
648
+        $result = $shares->execute($parameters);
649
+
650
+        return $result ? $shares->fetchAll() : [];
651
+    }
652 652
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -148,18 +148,18 @@  discard block
 block discarded – undo
148 148
 	 * @return Mount|null
149 149
 	 * @throws \Doctrine\DBAL\DBALException
150 150
 	 */
151
-	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted=false, $user = null, $remoteId = -1, $parent = -1) {
151
+	public function addShare($remote, $token, $password, $name, $owner, $shareType, $accepted = false, $user = null, $remoteId = -1, $parent = -1) {
152 152
 
153 153
 		$user = $user ? $user : $this->uid;
154 154
 		$accepted = $accepted ? 1 : 0;
155
-		$name = Filesystem::normalizePath('/' . $name);
155
+		$name = Filesystem::normalizePath('/'.$name);
156 156
 
157 157
 		if (!$accepted) {
158 158
 			// To avoid conflicts with the mount point generation later,
159 159
 			// we only use a temporary mount point name here. The real
160 160
 			// mount point name will be generated when accepting the share,
161 161
 			// using the original share item name.
162
-			$tmpMountPointName = '{{TemporaryMountPointName#' . $name . '}}';
162
+			$tmpMountPointName = '{{TemporaryMountPointName#'.$name.'}}';
163 163
 			$mountPoint = $tmpMountPointName;
164 164
 			$hash = md5($tmpMountPointName);
165 165
 			$data = [
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 			$i = 1;
180 180
 			while (!$this->connection->insertIfNotExist('*PREFIX*share_external', $data, ['user', 'mountpoint_hash'])) {
181 181
 				// The external share already exists for the user
182
-				$data['mountpoint'] = $tmpMountPointName . '-' . $i;
182
+				$data['mountpoint'] = $tmpMountPointName.'-'.$i;
183 183
 				$data['mountpoint_hash'] = md5($data['mountpoint']);
184 184
 				$i++;
185 185
 			}
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 		}
188 188
 
189 189
 		$mountPoint = Files::buildNotExistingFileName('/', $name);
190
-		$mountPoint = Filesystem::normalizePath('/' . $mountPoint);
190
+		$mountPoint = Filesystem::normalizePath('/'.$mountPoint);
191 191
 		$hash = md5($mountPoint);
192 192
 
193 193
 		$this->writeShareToDb($remote, $token, $password, $name, $owner, $user, $mountPoint, $hash, $accepted, $remoteId, $parent, $shareType);
@@ -246,9 +246,9 @@  discard block
 block discarded – undo
246 246
 		$validShare = is_array($share) && isset($share['share_type']) && isset($share['user']);
247 247
 
248 248
 		// check if the user is allowed to access it
249
-		if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_USER && $share['user'] === $this->uid) {
249
+		if ($validShare && (int) $share['share_type'] === Share::SHARE_TYPE_USER && $share['user'] === $this->uid) {
250 250
 			return $share;
251
-		} else if ($validShare && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
251
+		} else if ($validShare && (int) $share['share_type'] === Share::SHARE_TYPE_GROUP) {
252 252
 			$user = $this->userManager->get($this->uid);
253 253
 			if ($this->groupManager->get($share['user'])->inGroup($user)) {
254 254
 				return $share;
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 			$hash = md5($mountPoint);
279 279
 			$userShareAccepted = false;
280 280
 
281
-			if((int)$share['share_type'] === Share::SHARE_TYPE_USER) {
281
+			if ((int) $share['share_type'] === Share::SHARE_TYPE_USER) {
282 282
 				$acceptShare = $this->connection->prepare('
283 283
 				UPDATE `*PREFIX*share_external`
284 284
 				SET `accepted` = ?,
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 		$share = $this->getShare($id);
324 324
 		$result = false;
325 325
 
326
-		if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
326
+		if ($share && (int) $share['share_type'] === Share::SHARE_TYPE_USER) {
327 327
 			$removeShare = $this->connection->prepare('
328 328
 				DELETE FROM `*PREFIX*share_external` WHERE `id` = ? AND `user` = ?');
329 329
 			$removeShare->execute(array($id, $this->uid));
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 
332 332
 			$this->processNotification($id);
333 333
 			$result = true;
334
-		} else if ($share && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
334
+		} else if ($share && (int) $share['share_type'] === Share::SHARE_TYPE_GROUP) {
335 335
 			$result = $this->writeShareToDb(
336 336
 				$share['remote'],
337 337
 				$share['share_token'],
@@ -375,14 +375,14 @@  discard block
 block discarded – undo
375 375
 
376 376
 		$result = $this->tryOCMEndPoint($remote, $token, $remoteId, $feedback);
377 377
 
378
-		if($result === true) {
378
+		if ($result === true) {
379 379
 			return true;
380 380
 		}
381 381
 
382 382
 		$federationEndpoints = $this->discoveryService->discover($remote, 'FEDERATED_SHARING');
383 383
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
384 384
 
385
-		$url = rtrim($remote, '/') . $endpoint . '/' . $remoteId . '/' . $feedback . '?format=' . Share::RESPONSE_FORMAT;
385
+		$url = rtrim($remote, '/').$endpoint.'/'.$remoteId.'/'.$feedback.'?format='.Share::RESPONSE_FORMAT;
386 386
 		$fields = array('token' => $token);
387 387
 
388 388
 		$client = $this->clientService->newClient();
@@ -455,13 +455,13 @@  discard block
 block discarded – undo
455 455
 	 * @return string
456 456
 	 */
457 457
 	protected function stripPath($path) {
458
-		$prefix = '/' . $this->uid . '/files';
458
+		$prefix = '/'.$this->uid.'/files';
459 459
 		return rtrim(substr($path, strlen($prefix)), '/');
460 460
 	}
461 461
 
462 462
 	public function getMount($data) {
463 463
 		$data['manager'] = $this;
464
-		$mountPoint = '/' . $this->uid . '/files' . $data['mountpoint'];
464
+		$mountPoint = '/'.$this->uid.'/files'.$data['mountpoint'];
465 465
 		$data['mountpoint'] = $mountPoint;
466 466
 		$data['certificateManager'] = \OC::$server->getCertificateManager($this->uid);
467 467
 		return new Mount(self::STORAGE, $mountPoint, $data, $this, $this->storageLoader);
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 			WHERE `mountpoint_hash` = ?
502 502
 			AND `user` = ?
503 503
 		');
504
-		$result = (bool)$query->execute(array($target, $targetHash, $sourceHash, $this->uid));
504
+		$result = (bool) $query->execute(array($target, $targetHash, $sourceHash, $this->uid));
505 505
 
506 506
 		return $result;
507 507
 	}
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 
523 523
 		$share = $getShare->fetch();
524 524
 		$getShare->closeCursor();
525
-		if ($result && (int)$share['share_type'] === Share::SHARE_TYPE_USER) {
525
+		if ($result && (int) $share['share_type'] === Share::SHARE_TYPE_USER) {
526 526
 			try {
527 527
 				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
528 528
 			} catch (\Exception $e) {
@@ -534,16 +534,16 @@  discard block
 block discarded – undo
534 534
 			DELETE FROM `*PREFIX*share_external`
535 535
 			WHERE `id` = ?
536 536
 			');
537
-			$result = (bool)$query->execute(array((int)$share['id']));
538
-		} else if ($result && (int)$share['share_type'] === Share::SHARE_TYPE_GROUP) {
537
+			$result = (bool) $query->execute(array((int) $share['id']));
538
+		} else if ($result && (int) $share['share_type'] === Share::SHARE_TYPE_GROUP) {
539 539
 			$query = $this->connection->prepare('
540 540
 				UPDATE `*PREFIX*share_external`
541 541
 				SET `accepted` = ?
542 542
 				WHERE `id` = ?');
543
-			$result = (bool)$query->execute(array(0, (int)$share['id']));
543
+			$result = (bool) $query->execute(array(0, (int) $share['id']));
544 544
 		}
545 545
 
546
-		if($result) {
546
+		if ($result) {
547 547
 			$this->removeReShares($id);
548 548
 		}
549 549
 
@@ -564,7 +564,7 @@  discard block
 block discarded – undo
564 564
 
565 565
 
566 566
 		$query->delete('federated_reshares')
567
-			->where($query->expr()->in('share_id', $query->createFunction('(' . $select . ')')));
567
+			->where($query->expr()->in('share_id', $query->createFunction('('.$select.')')));
568 568
 		$query->execute();
569 569
 
570 570
 		$deleteReShares = $this->connection->getQueryBuilder();
@@ -588,7 +588,7 @@  discard block
 block discarded – undo
588 588
 
589 589
 		if ($result) {
590 590
 			$shares = $getShare->fetchAll();
591
-			foreach($shares as $share) {
591
+			foreach ($shares as $share) {
592 592
 				$this->sendFeedbackToRemote($share['remote'], $share['share_token'], $share['remote_id'], 'decline');
593 593
 			}
594 594
 		}
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
 			DELETE FROM `*PREFIX*share_external`
598 598
 			WHERE `user` = ?
599 599
 		');
600
-		return (bool)$query->execute(array($uid));
600
+		return (bool) $query->execute(array($uid));
601 601
 	}
602 602
 
603 603
 	/**
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 		$query = 'SELECT `id`, `remote`, `remote_id`, `share_token`, `name`, `owner`, `user`, `mountpoint`, `accepted`
638 638
 		          FROM `*PREFIX*share_external` 
639 639
 				  WHERE (`user` = ? OR `user` IN (?))';
640
-		$parameters = [$this->uid, implode(',',$userGroups)];
640
+		$parameters = [$this->uid, implode(',', $userGroups)];
641 641
 		if (!is_null($accepted)) {
642 642
 			$query .= ' AND `accepted` = ?';
643 643
 			$parameters[] = (int) $accepted;
Please login to merge, or discard this patch.
lib/private/Federation/CloudFederationProviderManager.php 1 patch
Indentation   +196 added lines, -196 removed lines patch added patch discarded remove patch
@@ -42,202 +42,202 @@
 block discarded – undo
42 42
  */
43 43
 class CloudFederationProviderManager implements ICloudFederationProviderManager {
44 44
 
45
-	/** @var array list of available cloud federation providers */
46
-	private $cloudFederationProvider;
47
-
48
-	/** @var IAppManager */
49
-	private $appManager;
50
-
51
-	/** @var IClientService */
52
-	private $httpClientService;
53
-
54
-	/** @var ICloudIdManager */
55
-	private $cloudIdManager;
56
-
57
-	/** @var ILogger */
58
-	private $logger;
59
-
60
-	/** @var array cache OCM end-points */
61
-	private $ocmEndPoints = [];
62
-
63
-	private $supportedAPIVersion = '1.0-proposal1';
64
-
65
-	/**
66
-	 * CloudFederationProviderManager constructor.
67
-	 *
68
-	 * @param IAppManager $appManager
69
-	 * @param IClientService $httpClientService
70
-	 * @param ICloudIdManager $cloudIdManager
71
-	 * @param ILogger $logger
72
-	 */
73
-	public function __construct(IAppManager $appManager,
74
-								IClientService $httpClientService,
75
-								ICloudIdManager $cloudIdManager,
76
-								ILogger $logger) {
77
-		$this->cloudFederationProvider= [];
78
-		$this->appManager = $appManager;
79
-		$this->httpClientService = $httpClientService;
80
-		$this->cloudIdManager = $cloudIdManager;
81
-		$this->logger = $logger;
82
-	}
83
-
84
-
85
-	/**
86
-	 * Registers an callback function which must return an cloud federation provider
87
-	 *
88
-	 * @param string $resourceType which resource type does the provider handles
89
-	 * @param string $displayName user facing name of the federated share provider
90
-	 * @param callable $callback
91
-	 */
92
-	public function addCloudFederationProvider($resourceType, $displayName, callable $callback) {
93
-		$this->cloudFederationProvider[$resourceType] = [
94
-			'resourceType' => $resourceType,
95
-			'displayName' => $displayName,
96
-			'callback' => $callback,
97
-		];
98
-
99
-	}
100
-
101
-	/**
102
-	 * remove cloud federation provider
103
-	 *
104
-	 * @param string $providerId
105
-	 */
106
-	public function removeCloudFederationProvider($providerId) {
107
-		unset($this->cloudFederationProvider[$providerId]);
108
-	}
109
-
110
-	/**
111
-	 * get a list of all cloudFederationProviders
112
-	 *
113
-	 * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
114
-	 */
115
-	public function getAllCloudFederationProviders() {
116
-		return $this->cloudFederationProvider;
117
-	}
118
-
119
-	/**
120
-	 * get a specific cloud federation provider
121
-	 *
122
-	 * @param string $resourceType
123
-	 * @return ICloudFederationProvider
124
-	 * @throws ProviderDoesNotExistsException
125
-	 */
126
-	public function getCloudFederationProvider($resourceType) {
127
-		if (isset($this->cloudFederationProvider[$resourceType])) {
128
-			return call_user_func($this->cloudFederationProvider[$resourceType]['callback']);
129
-		} else {
130
-			throw new ProviderDoesNotExistsException($resourceType);
131
-		}
132
-	}
133
-
134
-	public function sendShare(ICloudFederationShare $share) {
135
-		$cloudID = $this->cloudIdManager->resolveCloudId($share->getShareWith());
136
-		$ocmEndPoint = $this->getOCMEndPoint($cloudID->getRemote());
137
-
138
-		if (empty($ocmEndPoint)) {
139
-			return false;
140
-		}
141
-
142
-		$client = $this->httpClientService->newClient();
143
-		try {
144
-			$response = $client->post($ocmEndPoint . '/shares', [
145
-				'body' => $share->getShare(),
146
-				'timeout' => 10,
147
-				'connect_timeout' => 10,
148
-			]);
149
-
150
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
151
-				$result = json_decode($response->getBody(), true);
152
-				return (is_array($result)) ? $result : [];
153
-			}
154
-
155
-		} catch (\Exception $e) {
156
-			// if flat re-sharing is not supported by the remote server
157
-			// we re-throw the exception and fall back to the old behaviour.
158
-			// (flat re-shares has been introduced in Nextcloud 9.1)
159
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
160
-				$this->logger->debug($e->getMessage());
161
-				throw $e;
162
-			}
163
-		}
164
-
165
-		return false;
166
-
167
-	}
168
-
169
-	/**
170
-	 * @param string $url
171
-	 * @param ICloudFederationNotification $notification
172
-	 * @return mixed
173
-	 */
174
-	public function sendNotification($url, ICloudFederationNotification $notification) {
175
-		$ocmEndPoint = $this->getOCMEndPoint($url);
176
-
177
-		if (empty($ocmEndPoint)) {
178
-			return false;
179
-		}
180
-
181
-		$client = $this->httpClientService->newClient();
182
-		try {
183
-			$response = $client->post($ocmEndPoint . '/notifications', [
184
-				'body' => $notification->getMessage(),
185
-				'timeout' => 10,
186
-				'connect_timeout' => 10,
187
-			]);
188
-			if ($response->getStatusCode() === Http::STATUS_CREATED) {
189
-				$result = json_decode($response->getBody(), true);
190
-				return (is_array($result)) ? $result : [];
191
-			}
192
-		} catch (\Exception $e) {
193
-			// log the error and return false
194
-			$this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
195
-		}
196
-
197
-		return false;
198
-	}
199
-
200
-	/**
201
-	 * check if the new cloud federation API is ready to be used
202
-	 *
203
-	 * @return bool
204
-	 */
205
-	public function isReady() {
206
-		return $this->appManager->isEnabledForUser('cloud_federation_api');
207
-	}
208
-	/**
209
-	 * check if server supports the new OCM api and ask for the correct end-point
210
-	 *
211
-	 * @param string $url full base URL of the cloud server
212
-	 * @return string
213
-	 */
214
-	protected function getOCMEndPoint($url) {
215
-
216
-		if (isset($this->ocmEndPoints[$url])) {
217
-			return $this->ocmEndPoints[$url];
218
-		}
219
-
220
-		$client = $this->httpClientService->newClient();
221
-		try {
222
-			$response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
223
-		} catch (\Exception $e) {
224
-			$this->ocmEndPoints[$url] = '';
225
-			return '';
226
-		}
227
-
228
-		$result = $response->getBody();
229
-		$result = json_decode($result, true);
230
-
231
-		$supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
232
-
233
-		if (isset($result['endPoint']) && $supportedVersion) {
234
-			$this->ocmEndPoints[$url] = $result['endPoint'];
235
-			return $result['endPoint'];
236
-		}
237
-
238
-		$this->ocmEndPoints[$url] = '';
239
-		return '';
240
-	}
45
+    /** @var array list of available cloud federation providers */
46
+    private $cloudFederationProvider;
47
+
48
+    /** @var IAppManager */
49
+    private $appManager;
50
+
51
+    /** @var IClientService */
52
+    private $httpClientService;
53
+
54
+    /** @var ICloudIdManager */
55
+    private $cloudIdManager;
56
+
57
+    /** @var ILogger */
58
+    private $logger;
59
+
60
+    /** @var array cache OCM end-points */
61
+    private $ocmEndPoints = [];
62
+
63
+    private $supportedAPIVersion = '1.0-proposal1';
64
+
65
+    /**
66
+     * CloudFederationProviderManager constructor.
67
+     *
68
+     * @param IAppManager $appManager
69
+     * @param IClientService $httpClientService
70
+     * @param ICloudIdManager $cloudIdManager
71
+     * @param ILogger $logger
72
+     */
73
+    public function __construct(IAppManager $appManager,
74
+                                IClientService $httpClientService,
75
+                                ICloudIdManager $cloudIdManager,
76
+                                ILogger $logger) {
77
+        $this->cloudFederationProvider= [];
78
+        $this->appManager = $appManager;
79
+        $this->httpClientService = $httpClientService;
80
+        $this->cloudIdManager = $cloudIdManager;
81
+        $this->logger = $logger;
82
+    }
83
+
84
+
85
+    /**
86
+     * Registers an callback function which must return an cloud federation provider
87
+     *
88
+     * @param string $resourceType which resource type does the provider handles
89
+     * @param string $displayName user facing name of the federated share provider
90
+     * @param callable $callback
91
+     */
92
+    public function addCloudFederationProvider($resourceType, $displayName, callable $callback) {
93
+        $this->cloudFederationProvider[$resourceType] = [
94
+            'resourceType' => $resourceType,
95
+            'displayName' => $displayName,
96
+            'callback' => $callback,
97
+        ];
98
+
99
+    }
100
+
101
+    /**
102
+     * remove cloud federation provider
103
+     *
104
+     * @param string $providerId
105
+     */
106
+    public function removeCloudFederationProvider($providerId) {
107
+        unset($this->cloudFederationProvider[$providerId]);
108
+    }
109
+
110
+    /**
111
+     * get a list of all cloudFederationProviders
112
+     *
113
+     * @return array [resourceType => ['resourceType' => $resourceType, 'displayName' => $displayName, 'callback' => callback]]
114
+     */
115
+    public function getAllCloudFederationProviders() {
116
+        return $this->cloudFederationProvider;
117
+    }
118
+
119
+    /**
120
+     * get a specific cloud federation provider
121
+     *
122
+     * @param string $resourceType
123
+     * @return ICloudFederationProvider
124
+     * @throws ProviderDoesNotExistsException
125
+     */
126
+    public function getCloudFederationProvider($resourceType) {
127
+        if (isset($this->cloudFederationProvider[$resourceType])) {
128
+            return call_user_func($this->cloudFederationProvider[$resourceType]['callback']);
129
+        } else {
130
+            throw new ProviderDoesNotExistsException($resourceType);
131
+        }
132
+    }
133
+
134
+    public function sendShare(ICloudFederationShare $share) {
135
+        $cloudID = $this->cloudIdManager->resolveCloudId($share->getShareWith());
136
+        $ocmEndPoint = $this->getOCMEndPoint($cloudID->getRemote());
137
+
138
+        if (empty($ocmEndPoint)) {
139
+            return false;
140
+        }
141
+
142
+        $client = $this->httpClientService->newClient();
143
+        try {
144
+            $response = $client->post($ocmEndPoint . '/shares', [
145
+                'body' => $share->getShare(),
146
+                'timeout' => 10,
147
+                'connect_timeout' => 10,
148
+            ]);
149
+
150
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
151
+                $result = json_decode($response->getBody(), true);
152
+                return (is_array($result)) ? $result : [];
153
+            }
154
+
155
+        } catch (\Exception $e) {
156
+            // if flat re-sharing is not supported by the remote server
157
+            // we re-throw the exception and fall back to the old behaviour.
158
+            // (flat re-shares has been introduced in Nextcloud 9.1)
159
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
160
+                $this->logger->debug($e->getMessage());
161
+                throw $e;
162
+            }
163
+        }
164
+
165
+        return false;
166
+
167
+    }
168
+
169
+    /**
170
+     * @param string $url
171
+     * @param ICloudFederationNotification $notification
172
+     * @return mixed
173
+     */
174
+    public function sendNotification($url, ICloudFederationNotification $notification) {
175
+        $ocmEndPoint = $this->getOCMEndPoint($url);
176
+
177
+        if (empty($ocmEndPoint)) {
178
+            return false;
179
+        }
180
+
181
+        $client = $this->httpClientService->newClient();
182
+        try {
183
+            $response = $client->post($ocmEndPoint . '/notifications', [
184
+                'body' => $notification->getMessage(),
185
+                'timeout' => 10,
186
+                'connect_timeout' => 10,
187
+            ]);
188
+            if ($response->getStatusCode() === Http::STATUS_CREATED) {
189
+                $result = json_decode($response->getBody(), true);
190
+                return (is_array($result)) ? $result : [];
191
+            }
192
+        } catch (\Exception $e) {
193
+            // log the error and return false
194
+            $this->logger->error('error while sending notification for federated share: ' . $e->getMessage());
195
+        }
196
+
197
+        return false;
198
+    }
199
+
200
+    /**
201
+     * check if the new cloud federation API is ready to be used
202
+     *
203
+     * @return bool
204
+     */
205
+    public function isReady() {
206
+        return $this->appManager->isEnabledForUser('cloud_federation_api');
207
+    }
208
+    /**
209
+     * check if server supports the new OCM api and ask for the correct end-point
210
+     *
211
+     * @param string $url full base URL of the cloud server
212
+     * @return string
213
+     */
214
+    protected function getOCMEndPoint($url) {
215
+
216
+        if (isset($this->ocmEndPoints[$url])) {
217
+            return $this->ocmEndPoints[$url];
218
+        }
219
+
220
+        $client = $this->httpClientService->newClient();
221
+        try {
222
+            $response = $client->get($url . '/ocm-provider/', ['timeout' => 10, 'connect_timeout' => 10]);
223
+        } catch (\Exception $e) {
224
+            $this->ocmEndPoints[$url] = '';
225
+            return '';
226
+        }
227
+
228
+        $result = $response->getBody();
229
+        $result = json_decode($result, true);
230
+
231
+        $supportedVersion = isset($result['apiVersion']) && $result['apiVersion'] === $this->supportedAPIVersion;
232
+
233
+        if (isset($result['endPoint']) && $supportedVersion) {
234
+            $this->ocmEndPoints[$url] = $result['endPoint'];
235
+            return $result['endPoint'];
236
+        }
237
+
238
+        $this->ocmEndPoints[$url] = '';
239
+        return '';
240
+    }
241 241
 
242 242
 
243 243
 }
Please login to merge, or discard this patch.
lib/private/Collaboration/Collaborators/RemoteGroupPlugin.php 1 patch
Indentation   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -34,45 +34,45 @@
 block discarded – undo
34 34
 use OCP\Share;
35 35
 
36 36
 class RemoteGroupPlugin implements ISearchPlugin {
37
-	protected $shareeEnumeration;
37
+    protected $shareeEnumeration;
38 38
 
39
-	/** @var ICloudIdManager */
40
-	private $cloudIdManager;
41
-	/** @var IConfig */
42
-	private $config;
43
-	/** @var bool */
44
-	private $enabled = false;
39
+    /** @var ICloudIdManager */
40
+    private $cloudIdManager;
41
+    /** @var IConfig */
42
+    private $config;
43
+    /** @var bool */
44
+    private $enabled = false;
45 45
 
46
-	public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager, ICloudIdManager $cloudIdManager) {
47
-		try {
48
-			$fileSharingProvider = $cloudFederationProviderManager->getCloudFederationProvider('file');
49
-			$supportedShareTypes = $fileSharingProvider->getSupportedShareTypes();
50
-			if (in_array('group', $supportedShareTypes)) {
51
-				$this->enabled = true;
52
-			}
53
-		} catch (\Exception $e) {
54
-			// do nothing, just don't enable federated group shares
55
-		}
56
-		$this->cloudIdManager = $cloudIdManager;
57
-	}
46
+    public function __construct(ICloudFederationProviderManager $cloudFederationProviderManager, ICloudIdManager $cloudIdManager) {
47
+        try {
48
+            $fileSharingProvider = $cloudFederationProviderManager->getCloudFederationProvider('file');
49
+            $supportedShareTypes = $fileSharingProvider->getSupportedShareTypes();
50
+            if (in_array('group', $supportedShareTypes)) {
51
+                $this->enabled = true;
52
+            }
53
+        } catch (\Exception $e) {
54
+            // do nothing, just don't enable federated group shares
55
+        }
56
+        $this->cloudIdManager = $cloudIdManager;
57
+    }
58 58
 
59
-	public function search($search, $limit, $offset, ISearchResult $searchResult) {
60
-		$result = ['wide' => [], 'exact' => []];
61
-		$resultType = new SearchResultType('remote_groups');
59
+    public function search($search, $limit, $offset, ISearchResult $searchResult) {
60
+        $result = ['wide' => [], 'exact' => []];
61
+        $resultType = new SearchResultType('remote_groups');
62 62
 
63
-		if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
64
-			$result['exact'][] = [
65
-				'label' => $search,
66
-				'value' => [
67
-					'shareType' => Share::SHARE_TYPE_REMOTE_GROUP,
68
-					'shareWith' => $search,
69
-				],
70
-			];
71
-		}
63
+        if ($this->enabled && $this->cloudIdManager->isValidCloudId($search) && $offset === 0) {
64
+            $result['exact'][] = [
65
+                'label' => $search,
66
+                'value' => [
67
+                    'shareType' => Share::SHARE_TYPE_REMOTE_GROUP,
68
+                    'shareWith' => $search,
69
+                ],
70
+            ];
71
+        }
72 72
 
73
-		$searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
73
+        $searchResult->addResultSet($resultType, $result['wide'], $result['exact']);
74 74
 
75
-		return true;
76
-	}
75
+        return true;
76
+    }
77 77
 
78 78
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1862 added lines, -1862 removed lines patch added patch discarded remove patch
@@ -159,1871 +159,1871 @@
 block discarded – undo
159 159
  * TODO: hookup all manager classes
160 160
  */
161 161
 class Server extends ServerContainer implements IServerContainer {
162
-	/** @var string */
163
-	private $webRoot;
164
-
165
-	/**
166
-	 * @param string $webRoot
167
-	 * @param \OC\Config $config
168
-	 */
169
-	public function __construct($webRoot, \OC\Config $config) {
170
-		parent::__construct();
171
-		$this->webRoot = $webRoot;
172
-
173
-		// To find out if we are running from CLI or not
174
-		$this->registerParameter('isCLI', \OC::$CLI);
175
-
176
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
177
-			return $c;
178
-		});
179
-
180
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
181
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
182
-
183
-		$this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
184
-		$this->registerAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
185
-
186
-		$this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
187
-		$this->registerAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
188
-
189
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
190
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
191
-
192
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
193
-
194
-
195
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
196
-			return new PreviewManager(
197
-				$c->getConfig(),
198
-				$c->getRootFolder(),
199
-				$c->getAppDataDir('preview'),
200
-				$c->getEventDispatcher(),
201
-				$c->getSession()->get('user_id')
202
-			);
203
-		});
204
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
205
-
206
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
207
-			return new \OC\Preview\Watcher(
208
-				$c->getAppDataDir('preview')
209
-			);
210
-		});
211
-
212
-		$this->registerService('EncryptionManager', function (Server $c) {
213
-			$view = new View();
214
-			$util = new Encryption\Util(
215
-				$view,
216
-				$c->getUserManager(),
217
-				$c->getGroupManager(),
218
-				$c->getConfig()
219
-			);
220
-			return new Encryption\Manager(
221
-				$c->getConfig(),
222
-				$c->getLogger(),
223
-				$c->getL10N('core'),
224
-				new View(),
225
-				$util,
226
-				new ArrayCache()
227
-			);
228
-		});
229
-
230
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
231
-			$util = new Encryption\Util(
232
-				new View(),
233
-				$c->getUserManager(),
234
-				$c->getGroupManager(),
235
-				$c->getConfig()
236
-			);
237
-			return new Encryption\File(
238
-				$util,
239
-				$c->getRootFolder(),
240
-				$c->getShareManager()
241
-			);
242
-		});
243
-
244
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
245
-			$view = new View();
246
-			$util = new Encryption\Util(
247
-				$view,
248
-				$c->getUserManager(),
249
-				$c->getGroupManager(),
250
-				$c->getConfig()
251
-			);
252
-
253
-			return new Encryption\Keys\Storage($view, $util);
254
-		});
255
-		$this->registerService('TagMapper', function (Server $c) {
256
-			return new TagMapper($c->getDatabaseConnection());
257
-		});
258
-
259
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
260
-			$tagMapper = $c->query('TagMapper');
261
-			return new TagManager($tagMapper, $c->getUserSession());
262
-		});
263
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
264
-
265
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
266
-			$config = $c->getConfig();
267
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
268
-			return new $factoryClass($this);
269
-		});
270
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
271
-			return $c->query('SystemTagManagerFactory')->getManager();
272
-		});
273
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
274
-
275
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
276
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
277
-		});
278
-		$this->registerService('RootFolder', function (Server $c) {
279
-			$manager = \OC\Files\Filesystem::getMountManager(null);
280
-			$view = new View();
281
-			$root = new Root(
282
-				$manager,
283
-				$view,
284
-				null,
285
-				$c->getUserMountCache(),
286
-				$this->getLogger(),
287
-				$this->getUserManager()
288
-			);
289
-			$connector = new HookConnector($root, $view);
290
-			$connector->viewToNode();
291
-
292
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
293
-			$previewConnector->connectWatcher();
294
-
295
-			return $root;
296
-		});
297
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
298
-
299
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
300
-			return new LazyRoot(function () use ($c) {
301
-				return $c->query('RootFolder');
302
-			});
303
-		});
304
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
305
-
306
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
307
-			$config = $c->getConfig();
308
-			return new \OC\User\Manager($config);
309
-		});
310
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
311
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
312
-
313
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
314
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
315
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
316
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
317
-			});
318
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
319
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
320
-			});
321
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
322
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
323
-			});
324
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
325
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
326
-			});
327
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
328
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
329
-			});
330
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
331
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
332
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
333
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
334
-			});
335
-			return $groupManager;
336
-		});
337
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
338
-
339
-		$this->registerService(Store::class, function (Server $c) {
340
-			$session = $c->getSession();
341
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
342
-				$tokenProvider = $c->query(IProvider::class);
343
-			} else {
344
-				$tokenProvider = null;
345
-			}
346
-			$logger = $c->getLogger();
347
-			return new Store($session, $logger, $tokenProvider);
348
-		});
349
-		$this->registerAlias(IStore::class, Store::class);
350
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
351
-			$dbConnection = $c->getDatabaseConnection();
352
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
353
-		});
354
-		$this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
355
-
356
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
357
-			$manager = $c->getUserManager();
358
-			$session = new \OC\Session\Memory('');
359
-			$timeFactory = new TimeFactory();
360
-			// Token providers might require a working database. This code
361
-			// might however be called when ownCloud is not yet setup.
362
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
363
-				$defaultTokenProvider = $c->query(IProvider::class);
364
-			} else {
365
-				$defaultTokenProvider = null;
366
-			}
367
-
368
-			$dispatcher = $c->getEventDispatcher();
369
-
370
-			$userSession = new \OC\User\Session(
371
-				$manager,
372
-				$session,
373
-				$timeFactory,
374
-				$defaultTokenProvider,
375
-				$c->getConfig(),
376
-				$c->getSecureRandom(),
377
-				$c->getLockdownManager(),
378
-				$c->getLogger()
379
-			);
380
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
381
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
382
-			});
383
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
384
-				/** @var $user \OC\User\User */
385
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
386
-			});
387
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
388
-				/** @var $user \OC\User\User */
389
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
390
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
391
-			});
392
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
393
-				/** @var $user \OC\User\User */
394
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
395
-			});
396
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
397
-				/** @var $user \OC\User\User */
398
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
399
-			});
400
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
401
-				/** @var $user \OC\User\User */
402
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
403
-			});
404
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
405
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
406
-			});
407
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
408
-				/** @var $user \OC\User\User */
409
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
410
-			});
411
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
412
-				/** @var $user \OC\User\User */
413
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
414
-			});
415
-			$userSession->listen('\OC\User', 'logout', function () {
416
-				\OC_Hook::emit('OC_User', 'logout', array());
417
-			});
418
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
419
-				/** @var $user \OC\User\User */
420
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
421
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
422
-			});
423
-			return $userSession;
424
-		});
425
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
426
-
427
-		$this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
428
-
429
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
430
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
431
-
432
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
433
-			return new \OC\AllConfig(
434
-				$c->getSystemConfig()
435
-			);
436
-		});
437
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
438
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
439
-
440
-		$this->registerService('SystemConfig', function ($c) use ($config) {
441
-			return new \OC\SystemConfig($config);
442
-		});
443
-
444
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
445
-			return new \OC\AppConfig($c->getDatabaseConnection());
446
-		});
447
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
448
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
449
-
450
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
451
-			return new \OC\L10N\Factory(
452
-				$c->getConfig(),
453
-				$c->getRequest(),
454
-				$c->getUserSession(),
455
-				\OC::$SERVERROOT
456
-			);
457
-		});
458
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
459
-
460
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
461
-			$config = $c->getConfig();
462
-			$cacheFactory = $c->getMemCacheFactory();
463
-			$request = $c->getRequest();
464
-			return new \OC\URLGenerator(
465
-				$config,
466
-				$cacheFactory,
467
-				$request
468
-			);
469
-		});
470
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
471
-
472
-		$this->registerAlias('AppFetcher', AppFetcher::class);
473
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474
-
475
-		$this->registerService(\OCP\ICache::class, function ($c) {
476
-			return new Cache\File();
477
-		});
478
-		$this->registerAlias('UserCache', \OCP\ICache::class);
479
-
480
-		$this->registerService(Factory::class, function (Server $c) {
481
-
482
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483
-				ArrayCache::class,
484
-				ArrayCache::class,
485
-				ArrayCache::class
486
-			);
487
-			$config = $c->getConfig();
488
-			$request = $c->getRequest();
489
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
490
-
491
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
492
-				$v = \OC_App::getAppVersions();
493
-				$v['core'] = implode(',', \OC_Util::getVersion());
494
-				$version = implode(',', $v);
495
-				$instanceId = \OC_Util::getInstanceId();
496
-				$path = \OC::$SERVERROOT;
497
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
498
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499
-					$config->getSystemValue('memcache.local', null),
500
-					$config->getSystemValue('memcache.distributed', null),
501
-					$config->getSystemValue('memcache.locking', null)
502
-				);
503
-			}
504
-			return $arrayCacheFactory;
505
-
506
-		});
507
-		$this->registerAlias('MemCacheFactory', Factory::class);
508
-		$this->registerAlias(ICacheFactory::class, Factory::class);
509
-
510
-		$this->registerService('RedisFactory', function (Server $c) {
511
-			$systemConfig = $c->getSystemConfig();
512
-			return new RedisFactory($systemConfig);
513
-		});
514
-
515
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
-			return new \OC\Activity\Manager(
517
-				$c->getRequest(),
518
-				$c->getUserSession(),
519
-				$c->getConfig(),
520
-				$c->query(IValidator::class)
521
-			);
522
-		});
523
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524
-
525
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
-			return new \OC\Activity\EventMerger(
527
-				$c->getL10N('lib')
528
-			);
529
-		});
530
-		$this->registerAlias(IValidator::class, Validator::class);
531
-
532
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
-			return new AvatarManager(
534
-				$c->query(\OC\User\Manager::class),
535
-				$c->getAppDataDir('avatar'),
536
-				$c->getL10N('lib'),
537
-				$c->getLogger(),
538
-				$c->getConfig()
539
-			);
540
-		});
541
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
542
-
543
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544
-
545
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
546
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547
-			$factory = new LogFactory($c, $this->getSystemConfig());
548
-			$logger = $factory->get($logType);
549
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
550
-
551
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
552
-		});
553
-		$this->registerAlias('Logger', \OCP\ILogger::class);
554
-
555
-		$this->registerService(ILogFactory::class, function (Server $c) {
556
-			return new LogFactory($c, $this->getSystemConfig());
557
-		});
558
-
559
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
560
-			$config = $c->getConfig();
561
-			return new \OC\BackgroundJob\JobList(
562
-				$c->getDatabaseConnection(),
563
-				$config,
564
-				new TimeFactory()
565
-			);
566
-		});
567
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
568
-
569
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
570
-			$cacheFactory = $c->getMemCacheFactory();
571
-			$logger = $c->getLogger();
572
-			if ($cacheFactory->isLocalCacheAvailable()) {
573
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
574
-			} else {
575
-				$router = new \OC\Route\Router($logger);
576
-			}
577
-			return $router;
578
-		});
579
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
580
-
581
-		$this->registerService(\OCP\ISearch::class, function ($c) {
582
-			return new Search();
583
-		});
584
-		$this->registerAlias('Search', \OCP\ISearch::class);
585
-
586
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
587
-			return new \OC\Security\RateLimiting\Limiter(
588
-				$this->getUserSession(),
589
-				$this->getRequest(),
590
-				new \OC\AppFramework\Utility\TimeFactory(),
591
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
592
-			);
593
-		});
594
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
595
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
596
-				$this->getMemCacheFactory(),
597
-				new \OC\AppFramework\Utility\TimeFactory()
598
-			);
599
-		});
600
-
601
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
602
-			return new SecureRandom();
603
-		});
604
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
605
-
606
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
607
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
608
-		});
609
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
610
-
611
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
612
-			return new Hasher($c->getConfig());
613
-		});
614
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
615
-
616
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
617
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
618
-		});
619
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
620
-
621
-		$this->registerService(IDBConnection::class, function (Server $c) {
622
-			$systemConfig = $c->getSystemConfig();
623
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
624
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
625
-			if (!$factory->isValidType($type)) {
626
-				throw new \OC\DatabaseException('Invalid database type');
627
-			}
628
-			$connectionParams = $factory->createConnectionParams();
629
-			$connection = $factory->getConnection($type, $connectionParams);
630
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
631
-			return $connection;
632
-		});
633
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
634
-
635
-
636
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
637
-			$user = \OC_User::getUser();
638
-			$uid = $user ? $user : null;
639
-			return new ClientService(
640
-				$c->getConfig(),
641
-				new \OC\Security\CertificateManager(
642
-					$uid,
643
-					new View(),
644
-					$c->getConfig(),
645
-					$c->getLogger(),
646
-					$c->getSecureRandom()
647
-				)
648
-			);
649
-		});
650
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
651
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
652
-			$eventLogger = new EventLogger();
653
-			if ($c->getSystemConfig()->getValue('debug', false)) {
654
-				// In debug mode, module is being activated by default
655
-				$eventLogger->activate();
656
-			}
657
-			return $eventLogger;
658
-		});
659
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
660
-
661
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
662
-			$queryLogger = new QueryLogger();
663
-			if ($c->getSystemConfig()->getValue('debug', false)) {
664
-				// In debug mode, module is being activated by default
665
-				$queryLogger->activate();
666
-			}
667
-			return $queryLogger;
668
-		});
669
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
670
-
671
-		$this->registerService(TempManager::class, function (Server $c) {
672
-			return new TempManager(
673
-				$c->getLogger(),
674
-				$c->getConfig()
675
-			);
676
-		});
677
-		$this->registerAlias('TempManager', TempManager::class);
678
-		$this->registerAlias(ITempManager::class, TempManager::class);
679
-
680
-		$this->registerService(AppManager::class, function (Server $c) {
681
-			return new \OC\App\AppManager(
682
-				$c->getUserSession(),
683
-				$c->query(\OC\AppConfig::class),
684
-				$c->getGroupManager(),
685
-				$c->getMemCacheFactory(),
686
-				$c->getEventDispatcher()
687
-			);
688
-		});
689
-		$this->registerAlias('AppManager', AppManager::class);
690
-		$this->registerAlias(IAppManager::class, AppManager::class);
691
-
692
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
693
-			return new DateTimeZone(
694
-				$c->getConfig(),
695
-				$c->getSession()
696
-			);
697
-		});
698
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
699
-
700
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
701
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
702
-
703
-			return new DateTimeFormatter(
704
-				$c->getDateTimeZone()->getTimeZone(),
705
-				$c->getL10N('lib', $language)
706
-			);
707
-		});
708
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
709
-
710
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
711
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
712
-			$listener = new UserMountCacheListener($mountCache);
713
-			$listener->listen($c->getUserManager());
714
-			return $mountCache;
715
-		});
716
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
717
-
718
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
719
-			$loader = \OC\Files\Filesystem::getLoader();
720
-			$mountCache = $c->query('UserMountCache');
721
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
722
-
723
-			// builtin providers
724
-
725
-			$config = $c->getConfig();
726
-			$manager->registerProvider(new CacheMountProvider($config));
727
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
728
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
729
-
730
-			return $manager;
731
-		});
732
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
733
-
734
-		$this->registerService('IniWrapper', function ($c) {
735
-			return new IniGetWrapper();
736
-		});
737
-		$this->registerService('AsyncCommandBus', function (Server $c) {
738
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
739
-			if ($busClass) {
740
-				list($app, $class) = explode('::', $busClass, 2);
741
-				if ($c->getAppManager()->isInstalled($app)) {
742
-					\OC_App::loadApp($app);
743
-					return $c->query($class);
744
-				} else {
745
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
746
-				}
747
-			} else {
748
-				$jobList = $c->getJobList();
749
-				return new CronBus($jobList);
750
-			}
751
-		});
752
-		$this->registerService('TrustedDomainHelper', function ($c) {
753
-			return new TrustedDomainHelper($this->getConfig());
754
-		});
755
-		$this->registerService('Throttler', function (Server $c) {
756
-			return new Throttler(
757
-				$c->getDatabaseConnection(),
758
-				new TimeFactory(),
759
-				$c->getLogger(),
760
-				$c->getConfig()
761
-			);
762
-		});
763
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
764
-			// IConfig and IAppManager requires a working database. This code
765
-			// might however be called when ownCloud is not yet setup.
766
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
767
-				$config = $c->getConfig();
768
-				$appManager = $c->getAppManager();
769
-			} else {
770
-				$config = null;
771
-				$appManager = null;
772
-			}
773
-
774
-			return new Checker(
775
-				new EnvironmentHelper(),
776
-				new FileAccessHelper(),
777
-				new AppLocator(),
778
-				$config,
779
-				$c->getMemCacheFactory(),
780
-				$appManager,
781
-				$c->getTempManager()
782
-			);
783
-		});
784
-		$this->registerService(\OCP\IRequest::class, function ($c) {
785
-			if (isset($this['urlParams'])) {
786
-				$urlParams = $this['urlParams'];
787
-			} else {
788
-				$urlParams = [];
789
-			}
790
-
791
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
792
-				&& in_array('fakeinput', stream_get_wrappers())
793
-			) {
794
-				$stream = 'fakeinput://data';
795
-			} else {
796
-				$stream = 'php://input';
797
-			}
798
-
799
-			return new Request(
800
-				[
801
-					'get' => $_GET,
802
-					'post' => $_POST,
803
-					'files' => $_FILES,
804
-					'server' => $_SERVER,
805
-					'env' => $_ENV,
806
-					'cookies' => $_COOKIE,
807
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
808
-						? $_SERVER['REQUEST_METHOD']
809
-						: '',
810
-					'urlParams' => $urlParams,
811
-				],
812
-				$this->getSecureRandom(),
813
-				$this->getConfig(),
814
-				$this->getCsrfTokenManager(),
815
-				$stream
816
-			);
817
-		});
818
-		$this->registerAlias('Request', \OCP\IRequest::class);
819
-
820
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
821
-			return new Mailer(
822
-				$c->getConfig(),
823
-				$c->getLogger(),
824
-				$c->query(Defaults::class),
825
-				$c->getURLGenerator(),
826
-				$c->getL10N('lib')
827
-			);
828
-		});
829
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
830
-
831
-		$this->registerService('LDAPProvider', function (Server $c) {
832
-			$config = $c->getConfig();
833
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
834
-			if (is_null($factoryClass)) {
835
-				throw new \Exception('ldapProviderFactory not set');
836
-			}
837
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
838
-			$factory = new $factoryClass($this);
839
-			return $factory->getLDAPProvider();
840
-		});
841
-		$this->registerService(ILockingProvider::class, function (Server $c) {
842
-			$ini = $c->getIniWrapper();
843
-			$config = $c->getConfig();
844
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
845
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
846
-				/** @var \OC\Memcache\Factory $memcacheFactory */
847
-				$memcacheFactory = $c->getMemCacheFactory();
848
-				$memcache = $memcacheFactory->createLocking('lock');
849
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
850
-					return new MemcacheLockingProvider($memcache, $ttl);
851
-				}
852
-				return new DBLockingProvider(
853
-					$c->getDatabaseConnection(),
854
-					$c->getLogger(),
855
-					new TimeFactory(),
856
-					$ttl,
857
-					!\OC::$CLI
858
-				);
859
-			}
860
-			return new NoopLockingProvider();
861
-		});
862
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
863
-
864
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
865
-			return new \OC\Files\Mount\Manager();
866
-		});
867
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
868
-
869
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
870
-			return new \OC\Files\Type\Detection(
871
-				$c->getURLGenerator(),
872
-				\OC::$configDir,
873
-				\OC::$SERVERROOT . '/resources/config/'
874
-			);
875
-		});
876
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
877
-
878
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
879
-			return new \OC\Files\Type\Loader(
880
-				$c->getDatabaseConnection()
881
-			);
882
-		});
883
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
884
-		$this->registerService(BundleFetcher::class, function () {
885
-			return new BundleFetcher($this->getL10N('lib'));
886
-		});
887
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
888
-			return new Manager(
889
-				$c->query(IValidator::class)
890
-			);
891
-		});
892
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
893
-
894
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
895
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
896
-			$manager->registerCapability(function () use ($c) {
897
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
898
-			});
899
-			$manager->registerCapability(function () use ($c) {
900
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
901
-			});
902
-			return $manager;
903
-		});
904
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
905
-
906
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
907
-			$config = $c->getConfig();
908
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
909
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
910
-			$factory = new $factoryClass($this);
911
-			$manager = $factory->getManager();
912
-
913
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
914
-				$manager = $c->getUserManager();
915
-				$user = $manager->get($id);
916
-				if(is_null($user)) {
917
-					$l = $c->getL10N('core');
918
-					$displayName = $l->t('Unknown user');
919
-				} else {
920
-					$displayName = $user->getDisplayName();
921
-				}
922
-				return $displayName;
923
-			});
924
-
925
-			return $manager;
926
-		});
927
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
928
-
929
-		$this->registerService('ThemingDefaults', function (Server $c) {
930
-			/*
162
+    /** @var string */
163
+    private $webRoot;
164
+
165
+    /**
166
+     * @param string $webRoot
167
+     * @param \OC\Config $config
168
+     */
169
+    public function __construct($webRoot, \OC\Config $config) {
170
+        parent::__construct();
171
+        $this->webRoot = $webRoot;
172
+
173
+        // To find out if we are running from CLI or not
174
+        $this->registerParameter('isCLI', \OC::$CLI);
175
+
176
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
177
+            return $c;
178
+        });
179
+
180
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
181
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
182
+
183
+        $this->registerAlias(\OCP\Calendar\Resource\IManager::class, \OC\Calendar\Resource\Manager::class);
184
+        $this->registerAlias('CalendarResourceBackendManager', \OC\Calendar\Resource\Manager::class);
185
+
186
+        $this->registerAlias(\OCP\Calendar\Room\IManager::class, \OC\Calendar\Room\Manager::class);
187
+        $this->registerAlias('CalendarRoomBackendManager', \OC\Calendar\Room\Manager::class);
188
+
189
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
190
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
191
+
192
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
193
+
194
+
195
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
196
+            return new PreviewManager(
197
+                $c->getConfig(),
198
+                $c->getRootFolder(),
199
+                $c->getAppDataDir('preview'),
200
+                $c->getEventDispatcher(),
201
+                $c->getSession()->get('user_id')
202
+            );
203
+        });
204
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
205
+
206
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
207
+            return new \OC\Preview\Watcher(
208
+                $c->getAppDataDir('preview')
209
+            );
210
+        });
211
+
212
+        $this->registerService('EncryptionManager', function (Server $c) {
213
+            $view = new View();
214
+            $util = new Encryption\Util(
215
+                $view,
216
+                $c->getUserManager(),
217
+                $c->getGroupManager(),
218
+                $c->getConfig()
219
+            );
220
+            return new Encryption\Manager(
221
+                $c->getConfig(),
222
+                $c->getLogger(),
223
+                $c->getL10N('core'),
224
+                new View(),
225
+                $util,
226
+                new ArrayCache()
227
+            );
228
+        });
229
+
230
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
231
+            $util = new Encryption\Util(
232
+                new View(),
233
+                $c->getUserManager(),
234
+                $c->getGroupManager(),
235
+                $c->getConfig()
236
+            );
237
+            return new Encryption\File(
238
+                $util,
239
+                $c->getRootFolder(),
240
+                $c->getShareManager()
241
+            );
242
+        });
243
+
244
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
245
+            $view = new View();
246
+            $util = new Encryption\Util(
247
+                $view,
248
+                $c->getUserManager(),
249
+                $c->getGroupManager(),
250
+                $c->getConfig()
251
+            );
252
+
253
+            return new Encryption\Keys\Storage($view, $util);
254
+        });
255
+        $this->registerService('TagMapper', function (Server $c) {
256
+            return new TagMapper($c->getDatabaseConnection());
257
+        });
258
+
259
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
260
+            $tagMapper = $c->query('TagMapper');
261
+            return new TagManager($tagMapper, $c->getUserSession());
262
+        });
263
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
264
+
265
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
266
+            $config = $c->getConfig();
267
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
268
+            return new $factoryClass($this);
269
+        });
270
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
271
+            return $c->query('SystemTagManagerFactory')->getManager();
272
+        });
273
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
274
+
275
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
276
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
277
+        });
278
+        $this->registerService('RootFolder', function (Server $c) {
279
+            $manager = \OC\Files\Filesystem::getMountManager(null);
280
+            $view = new View();
281
+            $root = new Root(
282
+                $manager,
283
+                $view,
284
+                null,
285
+                $c->getUserMountCache(),
286
+                $this->getLogger(),
287
+                $this->getUserManager()
288
+            );
289
+            $connector = new HookConnector($root, $view);
290
+            $connector->viewToNode();
291
+
292
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
293
+            $previewConnector->connectWatcher();
294
+
295
+            return $root;
296
+        });
297
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
298
+
299
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
300
+            return new LazyRoot(function () use ($c) {
301
+                return $c->query('RootFolder');
302
+            });
303
+        });
304
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
305
+
306
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
307
+            $config = $c->getConfig();
308
+            return new \OC\User\Manager($config);
309
+        });
310
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
311
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
312
+
313
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
314
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
315
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
316
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
317
+            });
318
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
319
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
320
+            });
321
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
322
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
323
+            });
324
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
325
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
326
+            });
327
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
328
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
329
+            });
330
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
331
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
332
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
333
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
334
+            });
335
+            return $groupManager;
336
+        });
337
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
338
+
339
+        $this->registerService(Store::class, function (Server $c) {
340
+            $session = $c->getSession();
341
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
342
+                $tokenProvider = $c->query(IProvider::class);
343
+            } else {
344
+                $tokenProvider = null;
345
+            }
346
+            $logger = $c->getLogger();
347
+            return new Store($session, $logger, $tokenProvider);
348
+        });
349
+        $this->registerAlias(IStore::class, Store::class);
350
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
351
+            $dbConnection = $c->getDatabaseConnection();
352
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
353
+        });
354
+        $this->registerAlias(IProvider::class, Authentication\Token\Manager::class);
355
+
356
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
357
+            $manager = $c->getUserManager();
358
+            $session = new \OC\Session\Memory('');
359
+            $timeFactory = new TimeFactory();
360
+            // Token providers might require a working database. This code
361
+            // might however be called when ownCloud is not yet setup.
362
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
363
+                $defaultTokenProvider = $c->query(IProvider::class);
364
+            } else {
365
+                $defaultTokenProvider = null;
366
+            }
367
+
368
+            $dispatcher = $c->getEventDispatcher();
369
+
370
+            $userSession = new \OC\User\Session(
371
+                $manager,
372
+                $session,
373
+                $timeFactory,
374
+                $defaultTokenProvider,
375
+                $c->getConfig(),
376
+                $c->getSecureRandom(),
377
+                $c->getLockdownManager(),
378
+                $c->getLogger()
379
+            );
380
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
381
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
382
+            });
383
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
384
+                /** @var $user \OC\User\User */
385
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
386
+            });
387
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
388
+                /** @var $user \OC\User\User */
389
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
390
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
391
+            });
392
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
393
+                /** @var $user \OC\User\User */
394
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
395
+            });
396
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
397
+                /** @var $user \OC\User\User */
398
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
399
+            });
400
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
401
+                /** @var $user \OC\User\User */
402
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
403
+            });
404
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
405
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
406
+            });
407
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
408
+                /** @var $user \OC\User\User */
409
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
410
+            });
411
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
412
+                /** @var $user \OC\User\User */
413
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
414
+            });
415
+            $userSession->listen('\OC\User', 'logout', function () {
416
+                \OC_Hook::emit('OC_User', 'logout', array());
417
+            });
418
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
419
+                /** @var $user \OC\User\User */
420
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
421
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
422
+            });
423
+            return $userSession;
424
+        });
425
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
426
+
427
+        $this->registerAlias(\OCP\Authentication\TwoFactorAuth\IRegistry::class, \OC\Authentication\TwoFactorAuth\Registry::class);
428
+
429
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
430
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
431
+
432
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
433
+            return new \OC\AllConfig(
434
+                $c->getSystemConfig()
435
+            );
436
+        });
437
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
438
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
439
+
440
+        $this->registerService('SystemConfig', function ($c) use ($config) {
441
+            return new \OC\SystemConfig($config);
442
+        });
443
+
444
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
445
+            return new \OC\AppConfig($c->getDatabaseConnection());
446
+        });
447
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
448
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
449
+
450
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
451
+            return new \OC\L10N\Factory(
452
+                $c->getConfig(),
453
+                $c->getRequest(),
454
+                $c->getUserSession(),
455
+                \OC::$SERVERROOT
456
+            );
457
+        });
458
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
459
+
460
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
461
+            $config = $c->getConfig();
462
+            $cacheFactory = $c->getMemCacheFactory();
463
+            $request = $c->getRequest();
464
+            return new \OC\URLGenerator(
465
+                $config,
466
+                $cacheFactory,
467
+                $request
468
+            );
469
+        });
470
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
471
+
472
+        $this->registerAlias('AppFetcher', AppFetcher::class);
473
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
474
+
475
+        $this->registerService(\OCP\ICache::class, function ($c) {
476
+            return new Cache\File();
477
+        });
478
+        $this->registerAlias('UserCache', \OCP\ICache::class);
479
+
480
+        $this->registerService(Factory::class, function (Server $c) {
481
+
482
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
483
+                ArrayCache::class,
484
+                ArrayCache::class,
485
+                ArrayCache::class
486
+            );
487
+            $config = $c->getConfig();
488
+            $request = $c->getRequest();
489
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
490
+
491
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
492
+                $v = \OC_App::getAppVersions();
493
+                $v['core'] = implode(',', \OC_Util::getVersion());
494
+                $version = implode(',', $v);
495
+                $instanceId = \OC_Util::getInstanceId();
496
+                $path = \OC::$SERVERROOT;
497
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
498
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
499
+                    $config->getSystemValue('memcache.local', null),
500
+                    $config->getSystemValue('memcache.distributed', null),
501
+                    $config->getSystemValue('memcache.locking', null)
502
+                );
503
+            }
504
+            return $arrayCacheFactory;
505
+
506
+        });
507
+        $this->registerAlias('MemCacheFactory', Factory::class);
508
+        $this->registerAlias(ICacheFactory::class, Factory::class);
509
+
510
+        $this->registerService('RedisFactory', function (Server $c) {
511
+            $systemConfig = $c->getSystemConfig();
512
+            return new RedisFactory($systemConfig);
513
+        });
514
+
515
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
516
+            return new \OC\Activity\Manager(
517
+                $c->getRequest(),
518
+                $c->getUserSession(),
519
+                $c->getConfig(),
520
+                $c->query(IValidator::class)
521
+            );
522
+        });
523
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
524
+
525
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
526
+            return new \OC\Activity\EventMerger(
527
+                $c->getL10N('lib')
528
+            );
529
+        });
530
+        $this->registerAlias(IValidator::class, Validator::class);
531
+
532
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
533
+            return new AvatarManager(
534
+                $c->query(\OC\User\Manager::class),
535
+                $c->getAppDataDir('avatar'),
536
+                $c->getL10N('lib'),
537
+                $c->getLogger(),
538
+                $c->getConfig()
539
+            );
540
+        });
541
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
542
+
543
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
544
+
545
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
546
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
547
+            $factory = new LogFactory($c, $this->getSystemConfig());
548
+            $logger = $factory->get($logType);
549
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
550
+
551
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
552
+        });
553
+        $this->registerAlias('Logger', \OCP\ILogger::class);
554
+
555
+        $this->registerService(ILogFactory::class, function (Server $c) {
556
+            return new LogFactory($c, $this->getSystemConfig());
557
+        });
558
+
559
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
560
+            $config = $c->getConfig();
561
+            return new \OC\BackgroundJob\JobList(
562
+                $c->getDatabaseConnection(),
563
+                $config,
564
+                new TimeFactory()
565
+            );
566
+        });
567
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
568
+
569
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
570
+            $cacheFactory = $c->getMemCacheFactory();
571
+            $logger = $c->getLogger();
572
+            if ($cacheFactory->isLocalCacheAvailable()) {
573
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
574
+            } else {
575
+                $router = new \OC\Route\Router($logger);
576
+            }
577
+            return $router;
578
+        });
579
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
580
+
581
+        $this->registerService(\OCP\ISearch::class, function ($c) {
582
+            return new Search();
583
+        });
584
+        $this->registerAlias('Search', \OCP\ISearch::class);
585
+
586
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
587
+            return new \OC\Security\RateLimiting\Limiter(
588
+                $this->getUserSession(),
589
+                $this->getRequest(),
590
+                new \OC\AppFramework\Utility\TimeFactory(),
591
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
592
+            );
593
+        });
594
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
595
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
596
+                $this->getMemCacheFactory(),
597
+                new \OC\AppFramework\Utility\TimeFactory()
598
+            );
599
+        });
600
+
601
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
602
+            return new SecureRandom();
603
+        });
604
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
605
+
606
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
607
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
608
+        });
609
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
610
+
611
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
612
+            return new Hasher($c->getConfig());
613
+        });
614
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
615
+
616
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
617
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
618
+        });
619
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
620
+
621
+        $this->registerService(IDBConnection::class, function (Server $c) {
622
+            $systemConfig = $c->getSystemConfig();
623
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
624
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
625
+            if (!$factory->isValidType($type)) {
626
+                throw new \OC\DatabaseException('Invalid database type');
627
+            }
628
+            $connectionParams = $factory->createConnectionParams();
629
+            $connection = $factory->getConnection($type, $connectionParams);
630
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
631
+            return $connection;
632
+        });
633
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
634
+
635
+
636
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
637
+            $user = \OC_User::getUser();
638
+            $uid = $user ? $user : null;
639
+            return new ClientService(
640
+                $c->getConfig(),
641
+                new \OC\Security\CertificateManager(
642
+                    $uid,
643
+                    new View(),
644
+                    $c->getConfig(),
645
+                    $c->getLogger(),
646
+                    $c->getSecureRandom()
647
+                )
648
+            );
649
+        });
650
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
651
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
652
+            $eventLogger = new EventLogger();
653
+            if ($c->getSystemConfig()->getValue('debug', false)) {
654
+                // In debug mode, module is being activated by default
655
+                $eventLogger->activate();
656
+            }
657
+            return $eventLogger;
658
+        });
659
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
660
+
661
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
662
+            $queryLogger = new QueryLogger();
663
+            if ($c->getSystemConfig()->getValue('debug', false)) {
664
+                // In debug mode, module is being activated by default
665
+                $queryLogger->activate();
666
+            }
667
+            return $queryLogger;
668
+        });
669
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
670
+
671
+        $this->registerService(TempManager::class, function (Server $c) {
672
+            return new TempManager(
673
+                $c->getLogger(),
674
+                $c->getConfig()
675
+            );
676
+        });
677
+        $this->registerAlias('TempManager', TempManager::class);
678
+        $this->registerAlias(ITempManager::class, TempManager::class);
679
+
680
+        $this->registerService(AppManager::class, function (Server $c) {
681
+            return new \OC\App\AppManager(
682
+                $c->getUserSession(),
683
+                $c->query(\OC\AppConfig::class),
684
+                $c->getGroupManager(),
685
+                $c->getMemCacheFactory(),
686
+                $c->getEventDispatcher()
687
+            );
688
+        });
689
+        $this->registerAlias('AppManager', AppManager::class);
690
+        $this->registerAlias(IAppManager::class, AppManager::class);
691
+
692
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
693
+            return new DateTimeZone(
694
+                $c->getConfig(),
695
+                $c->getSession()
696
+            );
697
+        });
698
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
699
+
700
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
701
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
702
+
703
+            return new DateTimeFormatter(
704
+                $c->getDateTimeZone()->getTimeZone(),
705
+                $c->getL10N('lib', $language)
706
+            );
707
+        });
708
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
709
+
710
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
711
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
712
+            $listener = new UserMountCacheListener($mountCache);
713
+            $listener->listen($c->getUserManager());
714
+            return $mountCache;
715
+        });
716
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
717
+
718
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
719
+            $loader = \OC\Files\Filesystem::getLoader();
720
+            $mountCache = $c->query('UserMountCache');
721
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
722
+
723
+            // builtin providers
724
+
725
+            $config = $c->getConfig();
726
+            $manager->registerProvider(new CacheMountProvider($config));
727
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
728
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
729
+
730
+            return $manager;
731
+        });
732
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
733
+
734
+        $this->registerService('IniWrapper', function ($c) {
735
+            return new IniGetWrapper();
736
+        });
737
+        $this->registerService('AsyncCommandBus', function (Server $c) {
738
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
739
+            if ($busClass) {
740
+                list($app, $class) = explode('::', $busClass, 2);
741
+                if ($c->getAppManager()->isInstalled($app)) {
742
+                    \OC_App::loadApp($app);
743
+                    return $c->query($class);
744
+                } else {
745
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
746
+                }
747
+            } else {
748
+                $jobList = $c->getJobList();
749
+                return new CronBus($jobList);
750
+            }
751
+        });
752
+        $this->registerService('TrustedDomainHelper', function ($c) {
753
+            return new TrustedDomainHelper($this->getConfig());
754
+        });
755
+        $this->registerService('Throttler', function (Server $c) {
756
+            return new Throttler(
757
+                $c->getDatabaseConnection(),
758
+                new TimeFactory(),
759
+                $c->getLogger(),
760
+                $c->getConfig()
761
+            );
762
+        });
763
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
764
+            // IConfig and IAppManager requires a working database. This code
765
+            // might however be called when ownCloud is not yet setup.
766
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
767
+                $config = $c->getConfig();
768
+                $appManager = $c->getAppManager();
769
+            } else {
770
+                $config = null;
771
+                $appManager = null;
772
+            }
773
+
774
+            return new Checker(
775
+                new EnvironmentHelper(),
776
+                new FileAccessHelper(),
777
+                new AppLocator(),
778
+                $config,
779
+                $c->getMemCacheFactory(),
780
+                $appManager,
781
+                $c->getTempManager()
782
+            );
783
+        });
784
+        $this->registerService(\OCP\IRequest::class, function ($c) {
785
+            if (isset($this['urlParams'])) {
786
+                $urlParams = $this['urlParams'];
787
+            } else {
788
+                $urlParams = [];
789
+            }
790
+
791
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
792
+                && in_array('fakeinput', stream_get_wrappers())
793
+            ) {
794
+                $stream = 'fakeinput://data';
795
+            } else {
796
+                $stream = 'php://input';
797
+            }
798
+
799
+            return new Request(
800
+                [
801
+                    'get' => $_GET,
802
+                    'post' => $_POST,
803
+                    'files' => $_FILES,
804
+                    'server' => $_SERVER,
805
+                    'env' => $_ENV,
806
+                    'cookies' => $_COOKIE,
807
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
808
+                        ? $_SERVER['REQUEST_METHOD']
809
+                        : '',
810
+                    'urlParams' => $urlParams,
811
+                ],
812
+                $this->getSecureRandom(),
813
+                $this->getConfig(),
814
+                $this->getCsrfTokenManager(),
815
+                $stream
816
+            );
817
+        });
818
+        $this->registerAlias('Request', \OCP\IRequest::class);
819
+
820
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
821
+            return new Mailer(
822
+                $c->getConfig(),
823
+                $c->getLogger(),
824
+                $c->query(Defaults::class),
825
+                $c->getURLGenerator(),
826
+                $c->getL10N('lib')
827
+            );
828
+        });
829
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
830
+
831
+        $this->registerService('LDAPProvider', function (Server $c) {
832
+            $config = $c->getConfig();
833
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
834
+            if (is_null($factoryClass)) {
835
+                throw new \Exception('ldapProviderFactory not set');
836
+            }
837
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
838
+            $factory = new $factoryClass($this);
839
+            return $factory->getLDAPProvider();
840
+        });
841
+        $this->registerService(ILockingProvider::class, function (Server $c) {
842
+            $ini = $c->getIniWrapper();
843
+            $config = $c->getConfig();
844
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
845
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
846
+                /** @var \OC\Memcache\Factory $memcacheFactory */
847
+                $memcacheFactory = $c->getMemCacheFactory();
848
+                $memcache = $memcacheFactory->createLocking('lock');
849
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
850
+                    return new MemcacheLockingProvider($memcache, $ttl);
851
+                }
852
+                return new DBLockingProvider(
853
+                    $c->getDatabaseConnection(),
854
+                    $c->getLogger(),
855
+                    new TimeFactory(),
856
+                    $ttl,
857
+                    !\OC::$CLI
858
+                );
859
+            }
860
+            return new NoopLockingProvider();
861
+        });
862
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
863
+
864
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
865
+            return new \OC\Files\Mount\Manager();
866
+        });
867
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
868
+
869
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
870
+            return new \OC\Files\Type\Detection(
871
+                $c->getURLGenerator(),
872
+                \OC::$configDir,
873
+                \OC::$SERVERROOT . '/resources/config/'
874
+            );
875
+        });
876
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
877
+
878
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
879
+            return new \OC\Files\Type\Loader(
880
+                $c->getDatabaseConnection()
881
+            );
882
+        });
883
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
884
+        $this->registerService(BundleFetcher::class, function () {
885
+            return new BundleFetcher($this->getL10N('lib'));
886
+        });
887
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
888
+            return new Manager(
889
+                $c->query(IValidator::class)
890
+            );
891
+        });
892
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
893
+
894
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
895
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
896
+            $manager->registerCapability(function () use ($c) {
897
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
898
+            });
899
+            $manager->registerCapability(function () use ($c) {
900
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
901
+            });
902
+            return $manager;
903
+        });
904
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
905
+
906
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
907
+            $config = $c->getConfig();
908
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
909
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
910
+            $factory = new $factoryClass($this);
911
+            $manager = $factory->getManager();
912
+
913
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
914
+                $manager = $c->getUserManager();
915
+                $user = $manager->get($id);
916
+                if(is_null($user)) {
917
+                    $l = $c->getL10N('core');
918
+                    $displayName = $l->t('Unknown user');
919
+                } else {
920
+                    $displayName = $user->getDisplayName();
921
+                }
922
+                return $displayName;
923
+            });
924
+
925
+            return $manager;
926
+        });
927
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
928
+
929
+        $this->registerService('ThemingDefaults', function (Server $c) {
930
+            /*
931 931
 			 * Dark magic for autoloader.
932 932
 			 * If we do a class_exists it will try to load the class which will
933 933
 			 * make composer cache the result. Resulting in errors when enabling
934 934
 			 * the theming app.
935 935
 			 */
936
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
937
-			if (isset($prefixes['OCA\\Theming\\'])) {
938
-				$classExists = true;
939
-			} else {
940
-				$classExists = false;
941
-			}
942
-
943
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
944
-				return new ThemingDefaults(
945
-					$c->getConfig(),
946
-					$c->getL10N('theming'),
947
-					$c->getURLGenerator(),
948
-					$c->getMemCacheFactory(),
949
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
950
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
951
-					$c->getAppManager()
952
-				);
953
-			}
954
-			return new \OC_Defaults();
955
-		});
956
-		$this->registerService(SCSSCacher::class, function (Server $c) {
957
-			/** @var Factory $cacheFactory */
958
-			$cacheFactory = $c->query(Factory::class);
959
-			return new SCSSCacher(
960
-				$c->getLogger(),
961
-				$c->query(\OC\Files\AppData\Factory::class),
962
-				$c->getURLGenerator(),
963
-				$c->getConfig(),
964
-				$c->getThemingDefaults(),
965
-				\OC::$SERVERROOT,
966
-				$this->getMemCacheFactory()
967
-			);
968
-		});
969
-		$this->registerService(JSCombiner::class, function (Server $c) {
970
-			/** @var Factory $cacheFactory */
971
-			$cacheFactory = $c->query(Factory::class);
972
-			return new JSCombiner(
973
-				$c->getAppDataDir('js'),
974
-				$c->getURLGenerator(),
975
-				$this->getMemCacheFactory(),
976
-				$c->getSystemConfig(),
977
-				$c->getLogger()
978
-			);
979
-		});
980
-		$this->registerService(EventDispatcher::class, function () {
981
-			return new EventDispatcher();
982
-		});
983
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
984
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
985
-
986
-		$this->registerService('CryptoWrapper', function (Server $c) {
987
-			// FIXME: Instantiiated here due to cyclic dependency
988
-			$request = new Request(
989
-				[
990
-					'get' => $_GET,
991
-					'post' => $_POST,
992
-					'files' => $_FILES,
993
-					'server' => $_SERVER,
994
-					'env' => $_ENV,
995
-					'cookies' => $_COOKIE,
996
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
997
-						? $_SERVER['REQUEST_METHOD']
998
-						: null,
999
-				],
1000
-				$c->getSecureRandom(),
1001
-				$c->getConfig()
1002
-			);
1003
-
1004
-			return new CryptoWrapper(
1005
-				$c->getConfig(),
1006
-				$c->getCrypto(),
1007
-				$c->getSecureRandom(),
1008
-				$request
1009
-			);
1010
-		});
1011
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1012
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1013
-
1014
-			return new CsrfTokenManager(
1015
-				$tokenGenerator,
1016
-				$c->query(SessionStorage::class)
1017
-			);
1018
-		});
1019
-		$this->registerService(SessionStorage::class, function (Server $c) {
1020
-			return new SessionStorage($c->getSession());
1021
-		});
1022
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1023
-			return new ContentSecurityPolicyManager();
1024
-		});
1025
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1026
-
1027
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1028
-			return new ContentSecurityPolicyNonceManager(
1029
-				$c->getCsrfTokenManager(),
1030
-				$c->getRequest()
1031
-			);
1032
-		});
1033
-
1034
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1035
-			$config = $c->getConfig();
1036
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1037
-			/** @var \OCP\Share\IProviderFactory $factory */
1038
-			$factory = new $factoryClass($this);
1039
-
1040
-			$manager = new \OC\Share20\Manager(
1041
-				$c->getLogger(),
1042
-				$c->getConfig(),
1043
-				$c->getSecureRandom(),
1044
-				$c->getHasher(),
1045
-				$c->getMountManager(),
1046
-				$c->getGroupManager(),
1047
-				$c->getL10N('lib'),
1048
-				$c->getL10NFactory(),
1049
-				$factory,
1050
-				$c->getUserManager(),
1051
-				$c->getLazyRootFolder(),
1052
-				$c->getEventDispatcher(),
1053
-				$c->getMailer(),
1054
-				$c->getURLGenerator(),
1055
-				$c->getThemingDefaults()
1056
-			);
1057
-
1058
-			return $manager;
1059
-		});
1060
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1061
-
1062
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1063
-			$instance = new Collaboration\Collaborators\Search($c);
1064
-
1065
-			// register default plugins
1066
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1067
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1068
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1069
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1070
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1071
-
1072
-			return $instance;
1073
-		});
1074
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1075
-
1076
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1077
-
1078
-		$this->registerService('SettingsManager', function (Server $c) {
1079
-			$manager = new \OC\Settings\Manager(
1080
-				$c->getLogger(),
1081
-				$c->getDatabaseConnection(),
1082
-				$c->getL10N('lib'),
1083
-				$c->getConfig(),
1084
-				$c->getEncryptionManager(),
1085
-				$c->getUserManager(),
1086
-				$c->getLockingProvider(),
1087
-				$c->getRequest(),
1088
-				$c->getURLGenerator(),
1089
-				$c->query(AccountManager::class),
1090
-				$c->getGroupManager(),
1091
-				$c->getL10NFactory(),
1092
-				$c->getAppManager()
1093
-			);
1094
-			return $manager;
1095
-		});
1096
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1097
-			return new \OC\Files\AppData\Factory(
1098
-				$c->getRootFolder(),
1099
-				$c->getSystemConfig()
1100
-			);
1101
-		});
1102
-
1103
-		$this->registerService('LockdownManager', function (Server $c) {
1104
-			return new LockdownManager(function () use ($c) {
1105
-				return $c->getSession();
1106
-			});
1107
-		});
1108
-
1109
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1110
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1111
-		});
1112
-
1113
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1114
-			return new CloudIdManager();
1115
-		});
1116
-
1117
-		$this->registerService(IConfig::class, function (Server $c) {
1118
-			return new GlobalScale\Config($c->getConfig());
1119
-		});
1120
-
1121
-		$this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1122
-			return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1123
-		});
1124
-
1125
-		$this->registerService(ICloudFederationFactory::class, function (Server $c) {
1126
-			return new CloudFederationFactory();
1127
-		});
1128
-
1129
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1130
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1131
-
1132
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1133
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1134
-
1135
-		$this->registerService(Defaults::class, function (Server $c) {
1136
-			return new Defaults(
1137
-				$c->getThemingDefaults()
1138
-			);
1139
-		});
1140
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1141
-
1142
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1143
-			return $c->query(\OCP\IUserSession::class)->getSession();
1144
-		});
1145
-
1146
-		$this->registerService(IShareHelper::class, function (Server $c) {
1147
-			return new ShareHelper(
1148
-				$c->query(\OCP\Share\IManager::class)
1149
-			);
1150
-		});
1151
-
1152
-		$this->registerService(Installer::class, function(Server $c) {
1153
-			return new Installer(
1154
-				$c->getAppFetcher(),
1155
-				$c->getHTTPClientService(),
1156
-				$c->getTempManager(),
1157
-				$c->getLogger(),
1158
-				$c->getConfig()
1159
-			);
1160
-		});
1161
-
1162
-		$this->registerService(IApiFactory::class, function(Server $c) {
1163
-			return new ApiFactory($c->getHTTPClientService());
1164
-		});
1165
-
1166
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1167
-			$memcacheFactory = $c->getMemCacheFactory();
1168
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1169
-		});
1170
-
1171
-		$this->registerService(IContactsStore::class, function(Server $c) {
1172
-			return new ContactsStore(
1173
-				$c->getContactsManager(),
1174
-				$c->getConfig(),
1175
-				$c->getUserManager(),
1176
-				$c->getGroupManager()
1177
-			);
1178
-		});
1179
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1180
-
1181
-		$this->connectDispatcher();
1182
-	}
1183
-
1184
-	/**
1185
-	 * @return \OCP\Calendar\IManager
1186
-	 */
1187
-	public function getCalendarManager() {
1188
-		return $this->query('CalendarManager');
1189
-	}
1190
-
1191
-	/**
1192
-	 * @return \OCP\Calendar\Resource\IManager
1193
-	 */
1194
-	public function getCalendarResourceBackendManager() {
1195
-		return $this->query('CalendarResourceBackendManager');
1196
-	}
1197
-
1198
-	/**
1199
-	 * @return \OCP\Calendar\Room\IManager
1200
-	 */
1201
-	public function getCalendarRoomBackendManager() {
1202
-		return $this->query('CalendarRoomBackendManager');
1203
-	}
1204
-
1205
-	private function connectDispatcher() {
1206
-		$dispatcher = $this->getEventDispatcher();
1207
-
1208
-		// Delete avatar on user deletion
1209
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1210
-			$logger = $this->getLogger();
1211
-			$manager = $this->getAvatarManager();
1212
-			/** @var IUser $user */
1213
-			$user = $e->getSubject();
1214
-
1215
-			try {
1216
-				$avatar = $manager->getAvatar($user->getUID());
1217
-				$avatar->remove();
1218
-			} catch (NotFoundException $e) {
1219
-				// no avatar to remove
1220
-			} catch (\Exception $e) {
1221
-				// Ignore exceptions
1222
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1223
-			}
1224
-		});
1225
-
1226
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1227
-			$manager = $this->getAvatarManager();
1228
-			/** @var IUser $user */
1229
-			$user = $e->getSubject();
1230
-			$feature = $e->getArgument('feature');
1231
-			$oldValue = $e->getArgument('oldValue');
1232
-			$value = $e->getArgument('value');
1233
-
1234
-			try {
1235
-				$avatar = $manager->getAvatar($user->getUID());
1236
-				$avatar->userChanged($feature, $oldValue, $value);
1237
-			} catch (NotFoundException $e) {
1238
-				// no avatar to remove
1239
-			}
1240
-		});
1241
-	}
1242
-
1243
-	/**
1244
-	 * @return \OCP\Contacts\IManager
1245
-	 */
1246
-	public function getContactsManager() {
1247
-		return $this->query('ContactsManager');
1248
-	}
1249
-
1250
-	/**
1251
-	 * @return \OC\Encryption\Manager
1252
-	 */
1253
-	public function getEncryptionManager() {
1254
-		return $this->query('EncryptionManager');
1255
-	}
1256
-
1257
-	/**
1258
-	 * @return \OC\Encryption\File
1259
-	 */
1260
-	public function getEncryptionFilesHelper() {
1261
-		return $this->query('EncryptionFileHelper');
1262
-	}
1263
-
1264
-	/**
1265
-	 * @return \OCP\Encryption\Keys\IStorage
1266
-	 */
1267
-	public function getEncryptionKeyStorage() {
1268
-		return $this->query('EncryptionKeyStorage');
1269
-	}
1270
-
1271
-	/**
1272
-	 * The current request object holding all information about the request
1273
-	 * currently being processed is returned from this method.
1274
-	 * In case the current execution was not initiated by a web request null is returned
1275
-	 *
1276
-	 * @return \OCP\IRequest
1277
-	 */
1278
-	public function getRequest() {
1279
-		return $this->query('Request');
1280
-	}
1281
-
1282
-	/**
1283
-	 * Returns the preview manager which can create preview images for a given file
1284
-	 *
1285
-	 * @return \OCP\IPreview
1286
-	 */
1287
-	public function getPreviewManager() {
1288
-		return $this->query('PreviewManager');
1289
-	}
1290
-
1291
-	/**
1292
-	 * Returns the tag manager which can get and set tags for different object types
1293
-	 *
1294
-	 * @see \OCP\ITagManager::load()
1295
-	 * @return \OCP\ITagManager
1296
-	 */
1297
-	public function getTagManager() {
1298
-		return $this->query('TagManager');
1299
-	}
1300
-
1301
-	/**
1302
-	 * Returns the system-tag manager
1303
-	 *
1304
-	 * @return \OCP\SystemTag\ISystemTagManager
1305
-	 *
1306
-	 * @since 9.0.0
1307
-	 */
1308
-	public function getSystemTagManager() {
1309
-		return $this->query('SystemTagManager');
1310
-	}
1311
-
1312
-	/**
1313
-	 * Returns the system-tag object mapper
1314
-	 *
1315
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1316
-	 *
1317
-	 * @since 9.0.0
1318
-	 */
1319
-	public function getSystemTagObjectMapper() {
1320
-		return $this->query('SystemTagObjectMapper');
1321
-	}
1322
-
1323
-	/**
1324
-	 * Returns the avatar manager, used for avatar functionality
1325
-	 *
1326
-	 * @return \OCP\IAvatarManager
1327
-	 */
1328
-	public function getAvatarManager() {
1329
-		return $this->query('AvatarManager');
1330
-	}
1331
-
1332
-	/**
1333
-	 * Returns the root folder of ownCloud's data directory
1334
-	 *
1335
-	 * @return \OCP\Files\IRootFolder
1336
-	 */
1337
-	public function getRootFolder() {
1338
-		return $this->query('LazyRootFolder');
1339
-	}
1340
-
1341
-	/**
1342
-	 * Returns the root folder of ownCloud's data directory
1343
-	 * This is the lazy variant so this gets only initialized once it
1344
-	 * is actually used.
1345
-	 *
1346
-	 * @return \OCP\Files\IRootFolder
1347
-	 */
1348
-	public function getLazyRootFolder() {
1349
-		return $this->query('LazyRootFolder');
1350
-	}
1351
-
1352
-	/**
1353
-	 * Returns a view to ownCloud's files folder
1354
-	 *
1355
-	 * @param string $userId user ID
1356
-	 * @return \OCP\Files\Folder|null
1357
-	 */
1358
-	public function getUserFolder($userId = null) {
1359
-		if ($userId === null) {
1360
-			$user = $this->getUserSession()->getUser();
1361
-			if (!$user) {
1362
-				return null;
1363
-			}
1364
-			$userId = $user->getUID();
1365
-		}
1366
-		$root = $this->getRootFolder();
1367
-		return $root->getUserFolder($userId);
1368
-	}
1369
-
1370
-	/**
1371
-	 * Returns an app-specific view in ownClouds data directory
1372
-	 *
1373
-	 * @return \OCP\Files\Folder
1374
-	 * @deprecated since 9.2.0 use IAppData
1375
-	 */
1376
-	public function getAppFolder() {
1377
-		$dir = '/' . \OC_App::getCurrentApp();
1378
-		$root = $this->getRootFolder();
1379
-		if (!$root->nodeExists($dir)) {
1380
-			$folder = $root->newFolder($dir);
1381
-		} else {
1382
-			$folder = $root->get($dir);
1383
-		}
1384
-		return $folder;
1385
-	}
1386
-
1387
-	/**
1388
-	 * @return \OC\User\Manager
1389
-	 */
1390
-	public function getUserManager() {
1391
-		return $this->query('UserManager');
1392
-	}
1393
-
1394
-	/**
1395
-	 * @return \OC\Group\Manager
1396
-	 */
1397
-	public function getGroupManager() {
1398
-		return $this->query('GroupManager');
1399
-	}
1400
-
1401
-	/**
1402
-	 * @return \OC\User\Session
1403
-	 */
1404
-	public function getUserSession() {
1405
-		return $this->query('UserSession');
1406
-	}
1407
-
1408
-	/**
1409
-	 * @return \OCP\ISession
1410
-	 */
1411
-	public function getSession() {
1412
-		return $this->query('UserSession')->getSession();
1413
-	}
1414
-
1415
-	/**
1416
-	 * @param \OCP\ISession $session
1417
-	 */
1418
-	public function setSession(\OCP\ISession $session) {
1419
-		$this->query(SessionStorage::class)->setSession($session);
1420
-		$this->query('UserSession')->setSession($session);
1421
-		$this->query(Store::class)->setSession($session);
1422
-	}
1423
-
1424
-	/**
1425
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1426
-	 */
1427
-	public function getTwoFactorAuthManager() {
1428
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1429
-	}
1430
-
1431
-	/**
1432
-	 * @return \OC\NavigationManager
1433
-	 */
1434
-	public function getNavigationManager() {
1435
-		return $this->query('NavigationManager');
1436
-	}
1437
-
1438
-	/**
1439
-	 * @return \OCP\IConfig
1440
-	 */
1441
-	public function getConfig() {
1442
-		return $this->query('AllConfig');
1443
-	}
1444
-
1445
-	/**
1446
-	 * @return \OC\SystemConfig
1447
-	 */
1448
-	public function getSystemConfig() {
1449
-		return $this->query('SystemConfig');
1450
-	}
1451
-
1452
-	/**
1453
-	 * Returns the app config manager
1454
-	 *
1455
-	 * @return \OCP\IAppConfig
1456
-	 */
1457
-	public function getAppConfig() {
1458
-		return $this->query('AppConfig');
1459
-	}
1460
-
1461
-	/**
1462
-	 * @return \OCP\L10N\IFactory
1463
-	 */
1464
-	public function getL10NFactory() {
1465
-		return $this->query('L10NFactory');
1466
-	}
1467
-
1468
-	/**
1469
-	 * get an L10N instance
1470
-	 *
1471
-	 * @param string $app appid
1472
-	 * @param string $lang
1473
-	 * @return IL10N
1474
-	 */
1475
-	public function getL10N($app, $lang = null) {
1476
-		return $this->getL10NFactory()->get($app, $lang);
1477
-	}
1478
-
1479
-	/**
1480
-	 * @return \OCP\IURLGenerator
1481
-	 */
1482
-	public function getURLGenerator() {
1483
-		return $this->query('URLGenerator');
1484
-	}
1485
-
1486
-	/**
1487
-	 * @return AppFetcher
1488
-	 */
1489
-	public function getAppFetcher() {
1490
-		return $this->query(AppFetcher::class);
1491
-	}
1492
-
1493
-	/**
1494
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1495
-	 * getMemCacheFactory() instead.
1496
-	 *
1497
-	 * @return \OCP\ICache
1498
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1499
-	 */
1500
-	public function getCache() {
1501
-		return $this->query('UserCache');
1502
-	}
1503
-
1504
-	/**
1505
-	 * Returns an \OCP\CacheFactory instance
1506
-	 *
1507
-	 * @return \OCP\ICacheFactory
1508
-	 */
1509
-	public function getMemCacheFactory() {
1510
-		return $this->query('MemCacheFactory');
1511
-	}
1512
-
1513
-	/**
1514
-	 * Returns an \OC\RedisFactory instance
1515
-	 *
1516
-	 * @return \OC\RedisFactory
1517
-	 */
1518
-	public function getGetRedisFactory() {
1519
-		return $this->query('RedisFactory');
1520
-	}
1521
-
1522
-
1523
-	/**
1524
-	 * Returns the current session
1525
-	 *
1526
-	 * @return \OCP\IDBConnection
1527
-	 */
1528
-	public function getDatabaseConnection() {
1529
-		return $this->query('DatabaseConnection');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Returns the activity manager
1534
-	 *
1535
-	 * @return \OCP\Activity\IManager
1536
-	 */
1537
-	public function getActivityManager() {
1538
-		return $this->query('ActivityManager');
1539
-	}
1540
-
1541
-	/**
1542
-	 * Returns an job list for controlling background jobs
1543
-	 *
1544
-	 * @return \OCP\BackgroundJob\IJobList
1545
-	 */
1546
-	public function getJobList() {
1547
-		return $this->query('JobList');
1548
-	}
1549
-
1550
-	/**
1551
-	 * Returns a logger instance
1552
-	 *
1553
-	 * @return \OCP\ILogger
1554
-	 */
1555
-	public function getLogger() {
1556
-		return $this->query('Logger');
1557
-	}
1558
-
1559
-	/**
1560
-	 * @return ILogFactory
1561
-	 * @throws \OCP\AppFramework\QueryException
1562
-	 */
1563
-	public function getLogFactory() {
1564
-		return $this->query(ILogFactory::class);
1565
-	}
1566
-
1567
-	/**
1568
-	 * Returns a router for generating and matching urls
1569
-	 *
1570
-	 * @return \OCP\Route\IRouter
1571
-	 */
1572
-	public function getRouter() {
1573
-		return $this->query('Router');
1574
-	}
1575
-
1576
-	/**
1577
-	 * Returns a search instance
1578
-	 *
1579
-	 * @return \OCP\ISearch
1580
-	 */
1581
-	public function getSearch() {
1582
-		return $this->query('Search');
1583
-	}
1584
-
1585
-	/**
1586
-	 * Returns a SecureRandom instance
1587
-	 *
1588
-	 * @return \OCP\Security\ISecureRandom
1589
-	 */
1590
-	public function getSecureRandom() {
1591
-		return $this->query('SecureRandom');
1592
-	}
1593
-
1594
-	/**
1595
-	 * Returns a Crypto instance
1596
-	 *
1597
-	 * @return \OCP\Security\ICrypto
1598
-	 */
1599
-	public function getCrypto() {
1600
-		return $this->query('Crypto');
1601
-	}
1602
-
1603
-	/**
1604
-	 * Returns a Hasher instance
1605
-	 *
1606
-	 * @return \OCP\Security\IHasher
1607
-	 */
1608
-	public function getHasher() {
1609
-		return $this->query('Hasher');
1610
-	}
1611
-
1612
-	/**
1613
-	 * Returns a CredentialsManager instance
1614
-	 *
1615
-	 * @return \OCP\Security\ICredentialsManager
1616
-	 */
1617
-	public function getCredentialsManager() {
1618
-		return $this->query('CredentialsManager');
1619
-	}
1620
-
1621
-	/**
1622
-	 * Get the certificate manager for the user
1623
-	 *
1624
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1625
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1626
-	 */
1627
-	public function getCertificateManager($userId = '') {
1628
-		if ($userId === '') {
1629
-			$userSession = $this->getUserSession();
1630
-			$user = $userSession->getUser();
1631
-			if (is_null($user)) {
1632
-				return null;
1633
-			}
1634
-			$userId = $user->getUID();
1635
-		}
1636
-		return new CertificateManager(
1637
-			$userId,
1638
-			new View(),
1639
-			$this->getConfig(),
1640
-			$this->getLogger(),
1641
-			$this->getSecureRandom()
1642
-		);
1643
-	}
1644
-
1645
-	/**
1646
-	 * Returns an instance of the HTTP client service
1647
-	 *
1648
-	 * @return \OCP\Http\Client\IClientService
1649
-	 */
1650
-	public function getHTTPClientService() {
1651
-		return $this->query('HttpClientService');
1652
-	}
1653
-
1654
-	/**
1655
-	 * Create a new event source
1656
-	 *
1657
-	 * @return \OCP\IEventSource
1658
-	 */
1659
-	public function createEventSource() {
1660
-		return new \OC_EventSource();
1661
-	}
1662
-
1663
-	/**
1664
-	 * Get the active event logger
1665
-	 *
1666
-	 * The returned logger only logs data when debug mode is enabled
1667
-	 *
1668
-	 * @return \OCP\Diagnostics\IEventLogger
1669
-	 */
1670
-	public function getEventLogger() {
1671
-		return $this->query('EventLogger');
1672
-	}
1673
-
1674
-	/**
1675
-	 * Get the active query logger
1676
-	 *
1677
-	 * The returned logger only logs data when debug mode is enabled
1678
-	 *
1679
-	 * @return \OCP\Diagnostics\IQueryLogger
1680
-	 */
1681
-	public function getQueryLogger() {
1682
-		return $this->query('QueryLogger');
1683
-	}
1684
-
1685
-	/**
1686
-	 * Get the manager for temporary files and folders
1687
-	 *
1688
-	 * @return \OCP\ITempManager
1689
-	 */
1690
-	public function getTempManager() {
1691
-		return $this->query('TempManager');
1692
-	}
1693
-
1694
-	/**
1695
-	 * Get the app manager
1696
-	 *
1697
-	 * @return \OCP\App\IAppManager
1698
-	 */
1699
-	public function getAppManager() {
1700
-		return $this->query('AppManager');
1701
-	}
1702
-
1703
-	/**
1704
-	 * Creates a new mailer
1705
-	 *
1706
-	 * @return \OCP\Mail\IMailer
1707
-	 */
1708
-	public function getMailer() {
1709
-		return $this->query('Mailer');
1710
-	}
1711
-
1712
-	/**
1713
-	 * Get the webroot
1714
-	 *
1715
-	 * @return string
1716
-	 */
1717
-	public function getWebRoot() {
1718
-		return $this->webRoot;
1719
-	}
1720
-
1721
-	/**
1722
-	 * @return \OC\OCSClient
1723
-	 */
1724
-	public function getOcsClient() {
1725
-		return $this->query('OcsClient');
1726
-	}
1727
-
1728
-	/**
1729
-	 * @return \OCP\IDateTimeZone
1730
-	 */
1731
-	public function getDateTimeZone() {
1732
-		return $this->query('DateTimeZone');
1733
-	}
1734
-
1735
-	/**
1736
-	 * @return \OCP\IDateTimeFormatter
1737
-	 */
1738
-	public function getDateTimeFormatter() {
1739
-		return $this->query('DateTimeFormatter');
1740
-	}
1741
-
1742
-	/**
1743
-	 * @return \OCP\Files\Config\IMountProviderCollection
1744
-	 */
1745
-	public function getMountProviderCollection() {
1746
-		return $this->query('MountConfigManager');
1747
-	}
1748
-
1749
-	/**
1750
-	 * Get the IniWrapper
1751
-	 *
1752
-	 * @return IniGetWrapper
1753
-	 */
1754
-	public function getIniWrapper() {
1755
-		return $this->query('IniWrapper');
1756
-	}
1757
-
1758
-	/**
1759
-	 * @return \OCP\Command\IBus
1760
-	 */
1761
-	public function getCommandBus() {
1762
-		return $this->query('AsyncCommandBus');
1763
-	}
1764
-
1765
-	/**
1766
-	 * Get the trusted domain helper
1767
-	 *
1768
-	 * @return TrustedDomainHelper
1769
-	 */
1770
-	public function getTrustedDomainHelper() {
1771
-		return $this->query('TrustedDomainHelper');
1772
-	}
1773
-
1774
-	/**
1775
-	 * Get the locking provider
1776
-	 *
1777
-	 * @return \OCP\Lock\ILockingProvider
1778
-	 * @since 8.1.0
1779
-	 */
1780
-	public function getLockingProvider() {
1781
-		return $this->query('LockingProvider');
1782
-	}
1783
-
1784
-	/**
1785
-	 * @return \OCP\Files\Mount\IMountManager
1786
-	 **/
1787
-	function getMountManager() {
1788
-		return $this->query('MountManager');
1789
-	}
1790
-
1791
-	/** @return \OCP\Files\Config\IUserMountCache */
1792
-	function getUserMountCache() {
1793
-		return $this->query('UserMountCache');
1794
-	}
1795
-
1796
-	/**
1797
-	 * Get the MimeTypeDetector
1798
-	 *
1799
-	 * @return \OCP\Files\IMimeTypeDetector
1800
-	 */
1801
-	public function getMimeTypeDetector() {
1802
-		return $this->query('MimeTypeDetector');
1803
-	}
1804
-
1805
-	/**
1806
-	 * Get the MimeTypeLoader
1807
-	 *
1808
-	 * @return \OCP\Files\IMimeTypeLoader
1809
-	 */
1810
-	public function getMimeTypeLoader() {
1811
-		return $this->query('MimeTypeLoader');
1812
-	}
1813
-
1814
-	/**
1815
-	 * Get the manager of all the capabilities
1816
-	 *
1817
-	 * @return \OC\CapabilitiesManager
1818
-	 */
1819
-	public function getCapabilitiesManager() {
1820
-		return $this->query('CapabilitiesManager');
1821
-	}
1822
-
1823
-	/**
1824
-	 * Get the EventDispatcher
1825
-	 *
1826
-	 * @return EventDispatcherInterface
1827
-	 * @since 8.2.0
1828
-	 */
1829
-	public function getEventDispatcher() {
1830
-		return $this->query('EventDispatcher');
1831
-	}
1832
-
1833
-	/**
1834
-	 * Get the Notification Manager
1835
-	 *
1836
-	 * @return \OCP\Notification\IManager
1837
-	 * @since 8.2.0
1838
-	 */
1839
-	public function getNotificationManager() {
1840
-		return $this->query('NotificationManager');
1841
-	}
1842
-
1843
-	/**
1844
-	 * @return \OCP\Comments\ICommentsManager
1845
-	 */
1846
-	public function getCommentsManager() {
1847
-		return $this->query('CommentsManager');
1848
-	}
1849
-
1850
-	/**
1851
-	 * @return \OCA\Theming\ThemingDefaults
1852
-	 */
1853
-	public function getThemingDefaults() {
1854
-		return $this->query('ThemingDefaults');
1855
-	}
1856
-
1857
-	/**
1858
-	 * @return \OC\IntegrityCheck\Checker
1859
-	 */
1860
-	public function getIntegrityCodeChecker() {
1861
-		return $this->query('IntegrityCodeChecker');
1862
-	}
1863
-
1864
-	/**
1865
-	 * @return \OC\Session\CryptoWrapper
1866
-	 */
1867
-	public function getSessionCryptoWrapper() {
1868
-		return $this->query('CryptoWrapper');
1869
-	}
1870
-
1871
-	/**
1872
-	 * @return CsrfTokenManager
1873
-	 */
1874
-	public function getCsrfTokenManager() {
1875
-		return $this->query('CsrfTokenManager');
1876
-	}
1877
-
1878
-	/**
1879
-	 * @return Throttler
1880
-	 */
1881
-	public function getBruteForceThrottler() {
1882
-		return $this->query('Throttler');
1883
-	}
1884
-
1885
-	/**
1886
-	 * @return IContentSecurityPolicyManager
1887
-	 */
1888
-	public function getContentSecurityPolicyManager() {
1889
-		return $this->query('ContentSecurityPolicyManager');
1890
-	}
1891
-
1892
-	/**
1893
-	 * @return ContentSecurityPolicyNonceManager
1894
-	 */
1895
-	public function getContentSecurityPolicyNonceManager() {
1896
-		return $this->query('ContentSecurityPolicyNonceManager');
1897
-	}
1898
-
1899
-	/**
1900
-	 * Not a public API as of 8.2, wait for 9.0
1901
-	 *
1902
-	 * @return \OCA\Files_External\Service\BackendService
1903
-	 */
1904
-	public function getStoragesBackendService() {
1905
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1906
-	}
1907
-
1908
-	/**
1909
-	 * Not a public API as of 8.2, wait for 9.0
1910
-	 *
1911
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1912
-	 */
1913
-	public function getGlobalStoragesService() {
1914
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1915
-	}
1916
-
1917
-	/**
1918
-	 * Not a public API as of 8.2, wait for 9.0
1919
-	 *
1920
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1921
-	 */
1922
-	public function getUserGlobalStoragesService() {
1923
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1924
-	}
1925
-
1926
-	/**
1927
-	 * Not a public API as of 8.2, wait for 9.0
1928
-	 *
1929
-	 * @return \OCA\Files_External\Service\UserStoragesService
1930
-	 */
1931
-	public function getUserStoragesService() {
1932
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1933
-	}
1934
-
1935
-	/**
1936
-	 * @return \OCP\Share\IManager
1937
-	 */
1938
-	public function getShareManager() {
1939
-		return $this->query('ShareManager');
1940
-	}
1941
-
1942
-	/**
1943
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1944
-	 */
1945
-	public function getCollaboratorSearch() {
1946
-		return $this->query('CollaboratorSearch');
1947
-	}
1948
-
1949
-	/**
1950
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1951
-	 */
1952
-	public function getAutoCompleteManager(){
1953
-		return $this->query(IManager::class);
1954
-	}
1955
-
1956
-	/**
1957
-	 * Returns the LDAP Provider
1958
-	 *
1959
-	 * @return \OCP\LDAP\ILDAPProvider
1960
-	 */
1961
-	public function getLDAPProvider() {
1962
-		return $this->query('LDAPProvider');
1963
-	}
1964
-
1965
-	/**
1966
-	 * @return \OCP\Settings\IManager
1967
-	 */
1968
-	public function getSettingsManager() {
1969
-		return $this->query('SettingsManager');
1970
-	}
1971
-
1972
-	/**
1973
-	 * @return \OCP\Files\IAppData
1974
-	 */
1975
-	public function getAppDataDir($app) {
1976
-		/** @var \OC\Files\AppData\Factory $factory */
1977
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1978
-		return $factory->get($app);
1979
-	}
1980
-
1981
-	/**
1982
-	 * @return \OCP\Lockdown\ILockdownManager
1983
-	 */
1984
-	public function getLockdownManager() {
1985
-		return $this->query('LockdownManager');
1986
-	}
1987
-
1988
-	/**
1989
-	 * @return \OCP\Federation\ICloudIdManager
1990
-	 */
1991
-	public function getCloudIdManager() {
1992
-		return $this->query(ICloudIdManager::class);
1993
-	}
1994
-
1995
-	/**
1996
-	 * @return \OCP\GlobalScale\IConfig
1997
-	 */
1998
-	public function getGlobalScaleConfig() {
1999
-		return $this->query(IConfig::class);
2000
-	}
2001
-
2002
-	/**
2003
-	 * @return \OCP\Federation\ICloudFederationProviderManager
2004
-	 */
2005
-	public function getCloudFederationProviderManager() {
2006
-		return $this->query(ICloudFederationProviderManager::class);
2007
-	}
2008
-
2009
-	/**
2010
-	 * @return \OCP\Remote\Api\IApiFactory
2011
-	 */
2012
-	public function getRemoteApiFactory() {
2013
-		return $this->query(IApiFactory::class);
2014
-	}
2015
-
2016
-	/**
2017
-	 * @return \OCP\Federation\ICloudFederationFactory
2018
-	 */
2019
-	public function getCloudFederationFactory() {
2020
-		return $this->query(ICloudFederationFactory::class);
2021
-	}
2022
-
2023
-	/**
2024
-	 * @return \OCP\Remote\IInstanceFactory
2025
-	 */
2026
-	public function getRemoteInstanceFactory() {
2027
-		return $this->query(IInstanceFactory::class);
2028
-	}
936
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
937
+            if (isset($prefixes['OCA\\Theming\\'])) {
938
+                $classExists = true;
939
+            } else {
940
+                $classExists = false;
941
+            }
942
+
943
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
944
+                return new ThemingDefaults(
945
+                    $c->getConfig(),
946
+                    $c->getL10N('theming'),
947
+                    $c->getURLGenerator(),
948
+                    $c->getMemCacheFactory(),
949
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
950
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator(), $this->getMemCacheFactory(), $this->getLogger()),
951
+                    $c->getAppManager()
952
+                );
953
+            }
954
+            return new \OC_Defaults();
955
+        });
956
+        $this->registerService(SCSSCacher::class, function (Server $c) {
957
+            /** @var Factory $cacheFactory */
958
+            $cacheFactory = $c->query(Factory::class);
959
+            return new SCSSCacher(
960
+                $c->getLogger(),
961
+                $c->query(\OC\Files\AppData\Factory::class),
962
+                $c->getURLGenerator(),
963
+                $c->getConfig(),
964
+                $c->getThemingDefaults(),
965
+                \OC::$SERVERROOT,
966
+                $this->getMemCacheFactory()
967
+            );
968
+        });
969
+        $this->registerService(JSCombiner::class, function (Server $c) {
970
+            /** @var Factory $cacheFactory */
971
+            $cacheFactory = $c->query(Factory::class);
972
+            return new JSCombiner(
973
+                $c->getAppDataDir('js'),
974
+                $c->getURLGenerator(),
975
+                $this->getMemCacheFactory(),
976
+                $c->getSystemConfig(),
977
+                $c->getLogger()
978
+            );
979
+        });
980
+        $this->registerService(EventDispatcher::class, function () {
981
+            return new EventDispatcher();
982
+        });
983
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
984
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
985
+
986
+        $this->registerService('CryptoWrapper', function (Server $c) {
987
+            // FIXME: Instantiiated here due to cyclic dependency
988
+            $request = new Request(
989
+                [
990
+                    'get' => $_GET,
991
+                    'post' => $_POST,
992
+                    'files' => $_FILES,
993
+                    'server' => $_SERVER,
994
+                    'env' => $_ENV,
995
+                    'cookies' => $_COOKIE,
996
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
997
+                        ? $_SERVER['REQUEST_METHOD']
998
+                        : null,
999
+                ],
1000
+                $c->getSecureRandom(),
1001
+                $c->getConfig()
1002
+            );
1003
+
1004
+            return new CryptoWrapper(
1005
+                $c->getConfig(),
1006
+                $c->getCrypto(),
1007
+                $c->getSecureRandom(),
1008
+                $request
1009
+            );
1010
+        });
1011
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1012
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1013
+
1014
+            return new CsrfTokenManager(
1015
+                $tokenGenerator,
1016
+                $c->query(SessionStorage::class)
1017
+            );
1018
+        });
1019
+        $this->registerService(SessionStorage::class, function (Server $c) {
1020
+            return new SessionStorage($c->getSession());
1021
+        });
1022
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1023
+            return new ContentSecurityPolicyManager();
1024
+        });
1025
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1026
+
1027
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1028
+            return new ContentSecurityPolicyNonceManager(
1029
+                $c->getCsrfTokenManager(),
1030
+                $c->getRequest()
1031
+            );
1032
+        });
1033
+
1034
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1035
+            $config = $c->getConfig();
1036
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1037
+            /** @var \OCP\Share\IProviderFactory $factory */
1038
+            $factory = new $factoryClass($this);
1039
+
1040
+            $manager = new \OC\Share20\Manager(
1041
+                $c->getLogger(),
1042
+                $c->getConfig(),
1043
+                $c->getSecureRandom(),
1044
+                $c->getHasher(),
1045
+                $c->getMountManager(),
1046
+                $c->getGroupManager(),
1047
+                $c->getL10N('lib'),
1048
+                $c->getL10NFactory(),
1049
+                $factory,
1050
+                $c->getUserManager(),
1051
+                $c->getLazyRootFolder(),
1052
+                $c->getEventDispatcher(),
1053
+                $c->getMailer(),
1054
+                $c->getURLGenerator(),
1055
+                $c->getThemingDefaults()
1056
+            );
1057
+
1058
+            return $manager;
1059
+        });
1060
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1061
+
1062
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1063
+            $instance = new Collaboration\Collaborators\Search($c);
1064
+
1065
+            // register default plugins
1066
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1067
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1068
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1069
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1070
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE_GROUP', 'class' => RemoteGroupPlugin::class]);
1071
+
1072
+            return $instance;
1073
+        });
1074
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1075
+
1076
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1077
+
1078
+        $this->registerService('SettingsManager', function (Server $c) {
1079
+            $manager = new \OC\Settings\Manager(
1080
+                $c->getLogger(),
1081
+                $c->getDatabaseConnection(),
1082
+                $c->getL10N('lib'),
1083
+                $c->getConfig(),
1084
+                $c->getEncryptionManager(),
1085
+                $c->getUserManager(),
1086
+                $c->getLockingProvider(),
1087
+                $c->getRequest(),
1088
+                $c->getURLGenerator(),
1089
+                $c->query(AccountManager::class),
1090
+                $c->getGroupManager(),
1091
+                $c->getL10NFactory(),
1092
+                $c->getAppManager()
1093
+            );
1094
+            return $manager;
1095
+        });
1096
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1097
+            return new \OC\Files\AppData\Factory(
1098
+                $c->getRootFolder(),
1099
+                $c->getSystemConfig()
1100
+            );
1101
+        });
1102
+
1103
+        $this->registerService('LockdownManager', function (Server $c) {
1104
+            return new LockdownManager(function () use ($c) {
1105
+                return $c->getSession();
1106
+            });
1107
+        });
1108
+
1109
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1110
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1111
+        });
1112
+
1113
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1114
+            return new CloudIdManager();
1115
+        });
1116
+
1117
+        $this->registerService(IConfig::class, function (Server $c) {
1118
+            return new GlobalScale\Config($c->getConfig());
1119
+        });
1120
+
1121
+        $this->registerService(ICloudFederationProviderManager::class, function (Server $c) {
1122
+            return new CloudFederationProviderManager($c->getAppManager(), $c->getHTTPClientService(), $c->getCloudIdManager(), $c->getLogger());
1123
+        });
1124
+
1125
+        $this->registerService(ICloudFederationFactory::class, function (Server $c) {
1126
+            return new CloudFederationFactory();
1127
+        });
1128
+
1129
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1130
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1131
+
1132
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1133
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1134
+
1135
+        $this->registerService(Defaults::class, function (Server $c) {
1136
+            return new Defaults(
1137
+                $c->getThemingDefaults()
1138
+            );
1139
+        });
1140
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1141
+
1142
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1143
+            return $c->query(\OCP\IUserSession::class)->getSession();
1144
+        });
1145
+
1146
+        $this->registerService(IShareHelper::class, function (Server $c) {
1147
+            return new ShareHelper(
1148
+                $c->query(\OCP\Share\IManager::class)
1149
+            );
1150
+        });
1151
+
1152
+        $this->registerService(Installer::class, function(Server $c) {
1153
+            return new Installer(
1154
+                $c->getAppFetcher(),
1155
+                $c->getHTTPClientService(),
1156
+                $c->getTempManager(),
1157
+                $c->getLogger(),
1158
+                $c->getConfig()
1159
+            );
1160
+        });
1161
+
1162
+        $this->registerService(IApiFactory::class, function(Server $c) {
1163
+            return new ApiFactory($c->getHTTPClientService());
1164
+        });
1165
+
1166
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1167
+            $memcacheFactory = $c->getMemCacheFactory();
1168
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1169
+        });
1170
+
1171
+        $this->registerService(IContactsStore::class, function(Server $c) {
1172
+            return new ContactsStore(
1173
+                $c->getContactsManager(),
1174
+                $c->getConfig(),
1175
+                $c->getUserManager(),
1176
+                $c->getGroupManager()
1177
+            );
1178
+        });
1179
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1180
+
1181
+        $this->connectDispatcher();
1182
+    }
1183
+
1184
+    /**
1185
+     * @return \OCP\Calendar\IManager
1186
+     */
1187
+    public function getCalendarManager() {
1188
+        return $this->query('CalendarManager');
1189
+    }
1190
+
1191
+    /**
1192
+     * @return \OCP\Calendar\Resource\IManager
1193
+     */
1194
+    public function getCalendarResourceBackendManager() {
1195
+        return $this->query('CalendarResourceBackendManager');
1196
+    }
1197
+
1198
+    /**
1199
+     * @return \OCP\Calendar\Room\IManager
1200
+     */
1201
+    public function getCalendarRoomBackendManager() {
1202
+        return $this->query('CalendarRoomBackendManager');
1203
+    }
1204
+
1205
+    private function connectDispatcher() {
1206
+        $dispatcher = $this->getEventDispatcher();
1207
+
1208
+        // Delete avatar on user deletion
1209
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1210
+            $logger = $this->getLogger();
1211
+            $manager = $this->getAvatarManager();
1212
+            /** @var IUser $user */
1213
+            $user = $e->getSubject();
1214
+
1215
+            try {
1216
+                $avatar = $manager->getAvatar($user->getUID());
1217
+                $avatar->remove();
1218
+            } catch (NotFoundException $e) {
1219
+                // no avatar to remove
1220
+            } catch (\Exception $e) {
1221
+                // Ignore exceptions
1222
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1223
+            }
1224
+        });
1225
+
1226
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1227
+            $manager = $this->getAvatarManager();
1228
+            /** @var IUser $user */
1229
+            $user = $e->getSubject();
1230
+            $feature = $e->getArgument('feature');
1231
+            $oldValue = $e->getArgument('oldValue');
1232
+            $value = $e->getArgument('value');
1233
+
1234
+            try {
1235
+                $avatar = $manager->getAvatar($user->getUID());
1236
+                $avatar->userChanged($feature, $oldValue, $value);
1237
+            } catch (NotFoundException $e) {
1238
+                // no avatar to remove
1239
+            }
1240
+        });
1241
+    }
1242
+
1243
+    /**
1244
+     * @return \OCP\Contacts\IManager
1245
+     */
1246
+    public function getContactsManager() {
1247
+        return $this->query('ContactsManager');
1248
+    }
1249
+
1250
+    /**
1251
+     * @return \OC\Encryption\Manager
1252
+     */
1253
+    public function getEncryptionManager() {
1254
+        return $this->query('EncryptionManager');
1255
+    }
1256
+
1257
+    /**
1258
+     * @return \OC\Encryption\File
1259
+     */
1260
+    public function getEncryptionFilesHelper() {
1261
+        return $this->query('EncryptionFileHelper');
1262
+    }
1263
+
1264
+    /**
1265
+     * @return \OCP\Encryption\Keys\IStorage
1266
+     */
1267
+    public function getEncryptionKeyStorage() {
1268
+        return $this->query('EncryptionKeyStorage');
1269
+    }
1270
+
1271
+    /**
1272
+     * The current request object holding all information about the request
1273
+     * currently being processed is returned from this method.
1274
+     * In case the current execution was not initiated by a web request null is returned
1275
+     *
1276
+     * @return \OCP\IRequest
1277
+     */
1278
+    public function getRequest() {
1279
+        return $this->query('Request');
1280
+    }
1281
+
1282
+    /**
1283
+     * Returns the preview manager which can create preview images for a given file
1284
+     *
1285
+     * @return \OCP\IPreview
1286
+     */
1287
+    public function getPreviewManager() {
1288
+        return $this->query('PreviewManager');
1289
+    }
1290
+
1291
+    /**
1292
+     * Returns the tag manager which can get and set tags for different object types
1293
+     *
1294
+     * @see \OCP\ITagManager::load()
1295
+     * @return \OCP\ITagManager
1296
+     */
1297
+    public function getTagManager() {
1298
+        return $this->query('TagManager');
1299
+    }
1300
+
1301
+    /**
1302
+     * Returns the system-tag manager
1303
+     *
1304
+     * @return \OCP\SystemTag\ISystemTagManager
1305
+     *
1306
+     * @since 9.0.0
1307
+     */
1308
+    public function getSystemTagManager() {
1309
+        return $this->query('SystemTagManager');
1310
+    }
1311
+
1312
+    /**
1313
+     * Returns the system-tag object mapper
1314
+     *
1315
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1316
+     *
1317
+     * @since 9.0.0
1318
+     */
1319
+    public function getSystemTagObjectMapper() {
1320
+        return $this->query('SystemTagObjectMapper');
1321
+    }
1322
+
1323
+    /**
1324
+     * Returns the avatar manager, used for avatar functionality
1325
+     *
1326
+     * @return \OCP\IAvatarManager
1327
+     */
1328
+    public function getAvatarManager() {
1329
+        return $this->query('AvatarManager');
1330
+    }
1331
+
1332
+    /**
1333
+     * Returns the root folder of ownCloud's data directory
1334
+     *
1335
+     * @return \OCP\Files\IRootFolder
1336
+     */
1337
+    public function getRootFolder() {
1338
+        return $this->query('LazyRootFolder');
1339
+    }
1340
+
1341
+    /**
1342
+     * Returns the root folder of ownCloud's data directory
1343
+     * This is the lazy variant so this gets only initialized once it
1344
+     * is actually used.
1345
+     *
1346
+     * @return \OCP\Files\IRootFolder
1347
+     */
1348
+    public function getLazyRootFolder() {
1349
+        return $this->query('LazyRootFolder');
1350
+    }
1351
+
1352
+    /**
1353
+     * Returns a view to ownCloud's files folder
1354
+     *
1355
+     * @param string $userId user ID
1356
+     * @return \OCP\Files\Folder|null
1357
+     */
1358
+    public function getUserFolder($userId = null) {
1359
+        if ($userId === null) {
1360
+            $user = $this->getUserSession()->getUser();
1361
+            if (!$user) {
1362
+                return null;
1363
+            }
1364
+            $userId = $user->getUID();
1365
+        }
1366
+        $root = $this->getRootFolder();
1367
+        return $root->getUserFolder($userId);
1368
+    }
1369
+
1370
+    /**
1371
+     * Returns an app-specific view in ownClouds data directory
1372
+     *
1373
+     * @return \OCP\Files\Folder
1374
+     * @deprecated since 9.2.0 use IAppData
1375
+     */
1376
+    public function getAppFolder() {
1377
+        $dir = '/' . \OC_App::getCurrentApp();
1378
+        $root = $this->getRootFolder();
1379
+        if (!$root->nodeExists($dir)) {
1380
+            $folder = $root->newFolder($dir);
1381
+        } else {
1382
+            $folder = $root->get($dir);
1383
+        }
1384
+        return $folder;
1385
+    }
1386
+
1387
+    /**
1388
+     * @return \OC\User\Manager
1389
+     */
1390
+    public function getUserManager() {
1391
+        return $this->query('UserManager');
1392
+    }
1393
+
1394
+    /**
1395
+     * @return \OC\Group\Manager
1396
+     */
1397
+    public function getGroupManager() {
1398
+        return $this->query('GroupManager');
1399
+    }
1400
+
1401
+    /**
1402
+     * @return \OC\User\Session
1403
+     */
1404
+    public function getUserSession() {
1405
+        return $this->query('UserSession');
1406
+    }
1407
+
1408
+    /**
1409
+     * @return \OCP\ISession
1410
+     */
1411
+    public function getSession() {
1412
+        return $this->query('UserSession')->getSession();
1413
+    }
1414
+
1415
+    /**
1416
+     * @param \OCP\ISession $session
1417
+     */
1418
+    public function setSession(\OCP\ISession $session) {
1419
+        $this->query(SessionStorage::class)->setSession($session);
1420
+        $this->query('UserSession')->setSession($session);
1421
+        $this->query(Store::class)->setSession($session);
1422
+    }
1423
+
1424
+    /**
1425
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1426
+     */
1427
+    public function getTwoFactorAuthManager() {
1428
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1429
+    }
1430
+
1431
+    /**
1432
+     * @return \OC\NavigationManager
1433
+     */
1434
+    public function getNavigationManager() {
1435
+        return $this->query('NavigationManager');
1436
+    }
1437
+
1438
+    /**
1439
+     * @return \OCP\IConfig
1440
+     */
1441
+    public function getConfig() {
1442
+        return $this->query('AllConfig');
1443
+    }
1444
+
1445
+    /**
1446
+     * @return \OC\SystemConfig
1447
+     */
1448
+    public function getSystemConfig() {
1449
+        return $this->query('SystemConfig');
1450
+    }
1451
+
1452
+    /**
1453
+     * Returns the app config manager
1454
+     *
1455
+     * @return \OCP\IAppConfig
1456
+     */
1457
+    public function getAppConfig() {
1458
+        return $this->query('AppConfig');
1459
+    }
1460
+
1461
+    /**
1462
+     * @return \OCP\L10N\IFactory
1463
+     */
1464
+    public function getL10NFactory() {
1465
+        return $this->query('L10NFactory');
1466
+    }
1467
+
1468
+    /**
1469
+     * get an L10N instance
1470
+     *
1471
+     * @param string $app appid
1472
+     * @param string $lang
1473
+     * @return IL10N
1474
+     */
1475
+    public function getL10N($app, $lang = null) {
1476
+        return $this->getL10NFactory()->get($app, $lang);
1477
+    }
1478
+
1479
+    /**
1480
+     * @return \OCP\IURLGenerator
1481
+     */
1482
+    public function getURLGenerator() {
1483
+        return $this->query('URLGenerator');
1484
+    }
1485
+
1486
+    /**
1487
+     * @return AppFetcher
1488
+     */
1489
+    public function getAppFetcher() {
1490
+        return $this->query(AppFetcher::class);
1491
+    }
1492
+
1493
+    /**
1494
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1495
+     * getMemCacheFactory() instead.
1496
+     *
1497
+     * @return \OCP\ICache
1498
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1499
+     */
1500
+    public function getCache() {
1501
+        return $this->query('UserCache');
1502
+    }
1503
+
1504
+    /**
1505
+     * Returns an \OCP\CacheFactory instance
1506
+     *
1507
+     * @return \OCP\ICacheFactory
1508
+     */
1509
+    public function getMemCacheFactory() {
1510
+        return $this->query('MemCacheFactory');
1511
+    }
1512
+
1513
+    /**
1514
+     * Returns an \OC\RedisFactory instance
1515
+     *
1516
+     * @return \OC\RedisFactory
1517
+     */
1518
+    public function getGetRedisFactory() {
1519
+        return $this->query('RedisFactory');
1520
+    }
1521
+
1522
+
1523
+    /**
1524
+     * Returns the current session
1525
+     *
1526
+     * @return \OCP\IDBConnection
1527
+     */
1528
+    public function getDatabaseConnection() {
1529
+        return $this->query('DatabaseConnection');
1530
+    }
1531
+
1532
+    /**
1533
+     * Returns the activity manager
1534
+     *
1535
+     * @return \OCP\Activity\IManager
1536
+     */
1537
+    public function getActivityManager() {
1538
+        return $this->query('ActivityManager');
1539
+    }
1540
+
1541
+    /**
1542
+     * Returns an job list for controlling background jobs
1543
+     *
1544
+     * @return \OCP\BackgroundJob\IJobList
1545
+     */
1546
+    public function getJobList() {
1547
+        return $this->query('JobList');
1548
+    }
1549
+
1550
+    /**
1551
+     * Returns a logger instance
1552
+     *
1553
+     * @return \OCP\ILogger
1554
+     */
1555
+    public function getLogger() {
1556
+        return $this->query('Logger');
1557
+    }
1558
+
1559
+    /**
1560
+     * @return ILogFactory
1561
+     * @throws \OCP\AppFramework\QueryException
1562
+     */
1563
+    public function getLogFactory() {
1564
+        return $this->query(ILogFactory::class);
1565
+    }
1566
+
1567
+    /**
1568
+     * Returns a router for generating and matching urls
1569
+     *
1570
+     * @return \OCP\Route\IRouter
1571
+     */
1572
+    public function getRouter() {
1573
+        return $this->query('Router');
1574
+    }
1575
+
1576
+    /**
1577
+     * Returns a search instance
1578
+     *
1579
+     * @return \OCP\ISearch
1580
+     */
1581
+    public function getSearch() {
1582
+        return $this->query('Search');
1583
+    }
1584
+
1585
+    /**
1586
+     * Returns a SecureRandom instance
1587
+     *
1588
+     * @return \OCP\Security\ISecureRandom
1589
+     */
1590
+    public function getSecureRandom() {
1591
+        return $this->query('SecureRandom');
1592
+    }
1593
+
1594
+    /**
1595
+     * Returns a Crypto instance
1596
+     *
1597
+     * @return \OCP\Security\ICrypto
1598
+     */
1599
+    public function getCrypto() {
1600
+        return $this->query('Crypto');
1601
+    }
1602
+
1603
+    /**
1604
+     * Returns a Hasher instance
1605
+     *
1606
+     * @return \OCP\Security\IHasher
1607
+     */
1608
+    public function getHasher() {
1609
+        return $this->query('Hasher');
1610
+    }
1611
+
1612
+    /**
1613
+     * Returns a CredentialsManager instance
1614
+     *
1615
+     * @return \OCP\Security\ICredentialsManager
1616
+     */
1617
+    public function getCredentialsManager() {
1618
+        return $this->query('CredentialsManager');
1619
+    }
1620
+
1621
+    /**
1622
+     * Get the certificate manager for the user
1623
+     *
1624
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1625
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1626
+     */
1627
+    public function getCertificateManager($userId = '') {
1628
+        if ($userId === '') {
1629
+            $userSession = $this->getUserSession();
1630
+            $user = $userSession->getUser();
1631
+            if (is_null($user)) {
1632
+                return null;
1633
+            }
1634
+            $userId = $user->getUID();
1635
+        }
1636
+        return new CertificateManager(
1637
+            $userId,
1638
+            new View(),
1639
+            $this->getConfig(),
1640
+            $this->getLogger(),
1641
+            $this->getSecureRandom()
1642
+        );
1643
+    }
1644
+
1645
+    /**
1646
+     * Returns an instance of the HTTP client service
1647
+     *
1648
+     * @return \OCP\Http\Client\IClientService
1649
+     */
1650
+    public function getHTTPClientService() {
1651
+        return $this->query('HttpClientService');
1652
+    }
1653
+
1654
+    /**
1655
+     * Create a new event source
1656
+     *
1657
+     * @return \OCP\IEventSource
1658
+     */
1659
+    public function createEventSource() {
1660
+        return new \OC_EventSource();
1661
+    }
1662
+
1663
+    /**
1664
+     * Get the active event logger
1665
+     *
1666
+     * The returned logger only logs data when debug mode is enabled
1667
+     *
1668
+     * @return \OCP\Diagnostics\IEventLogger
1669
+     */
1670
+    public function getEventLogger() {
1671
+        return $this->query('EventLogger');
1672
+    }
1673
+
1674
+    /**
1675
+     * Get the active query logger
1676
+     *
1677
+     * The returned logger only logs data when debug mode is enabled
1678
+     *
1679
+     * @return \OCP\Diagnostics\IQueryLogger
1680
+     */
1681
+    public function getQueryLogger() {
1682
+        return $this->query('QueryLogger');
1683
+    }
1684
+
1685
+    /**
1686
+     * Get the manager for temporary files and folders
1687
+     *
1688
+     * @return \OCP\ITempManager
1689
+     */
1690
+    public function getTempManager() {
1691
+        return $this->query('TempManager');
1692
+    }
1693
+
1694
+    /**
1695
+     * Get the app manager
1696
+     *
1697
+     * @return \OCP\App\IAppManager
1698
+     */
1699
+    public function getAppManager() {
1700
+        return $this->query('AppManager');
1701
+    }
1702
+
1703
+    /**
1704
+     * Creates a new mailer
1705
+     *
1706
+     * @return \OCP\Mail\IMailer
1707
+     */
1708
+    public function getMailer() {
1709
+        return $this->query('Mailer');
1710
+    }
1711
+
1712
+    /**
1713
+     * Get the webroot
1714
+     *
1715
+     * @return string
1716
+     */
1717
+    public function getWebRoot() {
1718
+        return $this->webRoot;
1719
+    }
1720
+
1721
+    /**
1722
+     * @return \OC\OCSClient
1723
+     */
1724
+    public function getOcsClient() {
1725
+        return $this->query('OcsClient');
1726
+    }
1727
+
1728
+    /**
1729
+     * @return \OCP\IDateTimeZone
1730
+     */
1731
+    public function getDateTimeZone() {
1732
+        return $this->query('DateTimeZone');
1733
+    }
1734
+
1735
+    /**
1736
+     * @return \OCP\IDateTimeFormatter
1737
+     */
1738
+    public function getDateTimeFormatter() {
1739
+        return $this->query('DateTimeFormatter');
1740
+    }
1741
+
1742
+    /**
1743
+     * @return \OCP\Files\Config\IMountProviderCollection
1744
+     */
1745
+    public function getMountProviderCollection() {
1746
+        return $this->query('MountConfigManager');
1747
+    }
1748
+
1749
+    /**
1750
+     * Get the IniWrapper
1751
+     *
1752
+     * @return IniGetWrapper
1753
+     */
1754
+    public function getIniWrapper() {
1755
+        return $this->query('IniWrapper');
1756
+    }
1757
+
1758
+    /**
1759
+     * @return \OCP\Command\IBus
1760
+     */
1761
+    public function getCommandBus() {
1762
+        return $this->query('AsyncCommandBus');
1763
+    }
1764
+
1765
+    /**
1766
+     * Get the trusted domain helper
1767
+     *
1768
+     * @return TrustedDomainHelper
1769
+     */
1770
+    public function getTrustedDomainHelper() {
1771
+        return $this->query('TrustedDomainHelper');
1772
+    }
1773
+
1774
+    /**
1775
+     * Get the locking provider
1776
+     *
1777
+     * @return \OCP\Lock\ILockingProvider
1778
+     * @since 8.1.0
1779
+     */
1780
+    public function getLockingProvider() {
1781
+        return $this->query('LockingProvider');
1782
+    }
1783
+
1784
+    /**
1785
+     * @return \OCP\Files\Mount\IMountManager
1786
+     **/
1787
+    function getMountManager() {
1788
+        return $this->query('MountManager');
1789
+    }
1790
+
1791
+    /** @return \OCP\Files\Config\IUserMountCache */
1792
+    function getUserMountCache() {
1793
+        return $this->query('UserMountCache');
1794
+    }
1795
+
1796
+    /**
1797
+     * Get the MimeTypeDetector
1798
+     *
1799
+     * @return \OCP\Files\IMimeTypeDetector
1800
+     */
1801
+    public function getMimeTypeDetector() {
1802
+        return $this->query('MimeTypeDetector');
1803
+    }
1804
+
1805
+    /**
1806
+     * Get the MimeTypeLoader
1807
+     *
1808
+     * @return \OCP\Files\IMimeTypeLoader
1809
+     */
1810
+    public function getMimeTypeLoader() {
1811
+        return $this->query('MimeTypeLoader');
1812
+    }
1813
+
1814
+    /**
1815
+     * Get the manager of all the capabilities
1816
+     *
1817
+     * @return \OC\CapabilitiesManager
1818
+     */
1819
+    public function getCapabilitiesManager() {
1820
+        return $this->query('CapabilitiesManager');
1821
+    }
1822
+
1823
+    /**
1824
+     * Get the EventDispatcher
1825
+     *
1826
+     * @return EventDispatcherInterface
1827
+     * @since 8.2.0
1828
+     */
1829
+    public function getEventDispatcher() {
1830
+        return $this->query('EventDispatcher');
1831
+    }
1832
+
1833
+    /**
1834
+     * Get the Notification Manager
1835
+     *
1836
+     * @return \OCP\Notification\IManager
1837
+     * @since 8.2.0
1838
+     */
1839
+    public function getNotificationManager() {
1840
+        return $this->query('NotificationManager');
1841
+    }
1842
+
1843
+    /**
1844
+     * @return \OCP\Comments\ICommentsManager
1845
+     */
1846
+    public function getCommentsManager() {
1847
+        return $this->query('CommentsManager');
1848
+    }
1849
+
1850
+    /**
1851
+     * @return \OCA\Theming\ThemingDefaults
1852
+     */
1853
+    public function getThemingDefaults() {
1854
+        return $this->query('ThemingDefaults');
1855
+    }
1856
+
1857
+    /**
1858
+     * @return \OC\IntegrityCheck\Checker
1859
+     */
1860
+    public function getIntegrityCodeChecker() {
1861
+        return $this->query('IntegrityCodeChecker');
1862
+    }
1863
+
1864
+    /**
1865
+     * @return \OC\Session\CryptoWrapper
1866
+     */
1867
+    public function getSessionCryptoWrapper() {
1868
+        return $this->query('CryptoWrapper');
1869
+    }
1870
+
1871
+    /**
1872
+     * @return CsrfTokenManager
1873
+     */
1874
+    public function getCsrfTokenManager() {
1875
+        return $this->query('CsrfTokenManager');
1876
+    }
1877
+
1878
+    /**
1879
+     * @return Throttler
1880
+     */
1881
+    public function getBruteForceThrottler() {
1882
+        return $this->query('Throttler');
1883
+    }
1884
+
1885
+    /**
1886
+     * @return IContentSecurityPolicyManager
1887
+     */
1888
+    public function getContentSecurityPolicyManager() {
1889
+        return $this->query('ContentSecurityPolicyManager');
1890
+    }
1891
+
1892
+    /**
1893
+     * @return ContentSecurityPolicyNonceManager
1894
+     */
1895
+    public function getContentSecurityPolicyNonceManager() {
1896
+        return $this->query('ContentSecurityPolicyNonceManager');
1897
+    }
1898
+
1899
+    /**
1900
+     * Not a public API as of 8.2, wait for 9.0
1901
+     *
1902
+     * @return \OCA\Files_External\Service\BackendService
1903
+     */
1904
+    public function getStoragesBackendService() {
1905
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1906
+    }
1907
+
1908
+    /**
1909
+     * Not a public API as of 8.2, wait for 9.0
1910
+     *
1911
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1912
+     */
1913
+    public function getGlobalStoragesService() {
1914
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1915
+    }
1916
+
1917
+    /**
1918
+     * Not a public API as of 8.2, wait for 9.0
1919
+     *
1920
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1921
+     */
1922
+    public function getUserGlobalStoragesService() {
1923
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1924
+    }
1925
+
1926
+    /**
1927
+     * Not a public API as of 8.2, wait for 9.0
1928
+     *
1929
+     * @return \OCA\Files_External\Service\UserStoragesService
1930
+     */
1931
+    public function getUserStoragesService() {
1932
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1933
+    }
1934
+
1935
+    /**
1936
+     * @return \OCP\Share\IManager
1937
+     */
1938
+    public function getShareManager() {
1939
+        return $this->query('ShareManager');
1940
+    }
1941
+
1942
+    /**
1943
+     * @return \OCP\Collaboration\Collaborators\ISearch
1944
+     */
1945
+    public function getCollaboratorSearch() {
1946
+        return $this->query('CollaboratorSearch');
1947
+    }
1948
+
1949
+    /**
1950
+     * @return \OCP\Collaboration\AutoComplete\IManager
1951
+     */
1952
+    public function getAutoCompleteManager(){
1953
+        return $this->query(IManager::class);
1954
+    }
1955
+
1956
+    /**
1957
+     * Returns the LDAP Provider
1958
+     *
1959
+     * @return \OCP\LDAP\ILDAPProvider
1960
+     */
1961
+    public function getLDAPProvider() {
1962
+        return $this->query('LDAPProvider');
1963
+    }
1964
+
1965
+    /**
1966
+     * @return \OCP\Settings\IManager
1967
+     */
1968
+    public function getSettingsManager() {
1969
+        return $this->query('SettingsManager');
1970
+    }
1971
+
1972
+    /**
1973
+     * @return \OCP\Files\IAppData
1974
+     */
1975
+    public function getAppDataDir($app) {
1976
+        /** @var \OC\Files\AppData\Factory $factory */
1977
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1978
+        return $factory->get($app);
1979
+    }
1980
+
1981
+    /**
1982
+     * @return \OCP\Lockdown\ILockdownManager
1983
+     */
1984
+    public function getLockdownManager() {
1985
+        return $this->query('LockdownManager');
1986
+    }
1987
+
1988
+    /**
1989
+     * @return \OCP\Federation\ICloudIdManager
1990
+     */
1991
+    public function getCloudIdManager() {
1992
+        return $this->query(ICloudIdManager::class);
1993
+    }
1994
+
1995
+    /**
1996
+     * @return \OCP\GlobalScale\IConfig
1997
+     */
1998
+    public function getGlobalScaleConfig() {
1999
+        return $this->query(IConfig::class);
2000
+    }
2001
+
2002
+    /**
2003
+     * @return \OCP\Federation\ICloudFederationProviderManager
2004
+     */
2005
+    public function getCloudFederationProviderManager() {
2006
+        return $this->query(ICloudFederationProviderManager::class);
2007
+    }
2008
+
2009
+    /**
2010
+     * @return \OCP\Remote\Api\IApiFactory
2011
+     */
2012
+    public function getRemoteApiFactory() {
2013
+        return $this->query(IApiFactory::class);
2014
+    }
2015
+
2016
+    /**
2017
+     * @return \OCP\Federation\ICloudFederationFactory
2018
+     */
2019
+    public function getCloudFederationFactory() {
2020
+        return $this->query(ICloudFederationFactory::class);
2021
+    }
2022
+
2023
+    /**
2024
+     * @return \OCP\Remote\IInstanceFactory
2025
+     */
2026
+    public function getRemoteInstanceFactory() {
2027
+        return $this->query(IInstanceFactory::class);
2028
+    }
2029 2029
 }
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +225 added lines, -225 removed lines patch added patch discarded remove patch
@@ -48,236 +48,236 @@
 block discarded – undo
48 48
  */
49 49
 class ProviderFactory implements IProviderFactory {
50 50
 
51
-	/** @var IServerContainer */
52
-	private $serverContainer;
53
-	/** @var DefaultShareProvider */
54
-	private $defaultProvider = null;
55
-	/** @var FederatedShareProvider */
56
-	private $federatedProvider = null;
57
-	/** @var  ShareByMailProvider */
58
-	private $shareByMailProvider;
59
-	/** @var  \OCA\Circles\ShareByCircleProvider */
60
-	private $shareByCircleProvider = null;
61
-	/** @var bool */
62
-	private $circlesAreNotAvailable = false;
63
-
64
-	/**
65
-	 * IProviderFactory constructor.
66
-	 *
67
-	 * @param IServerContainer $serverContainer
68
-	 */
69
-	public function __construct(IServerContainer $serverContainer) {
70
-		$this->serverContainer = $serverContainer;
71
-	}
72
-
73
-	/**
74
-	 * Create the default share provider.
75
-	 *
76
-	 * @return DefaultShareProvider
77
-	 */
78
-	protected function defaultShareProvider() {
79
-		if ($this->defaultProvider === null) {
80
-			$this->defaultProvider = new DefaultShareProvider(
81
-				$this->serverContainer->getDatabaseConnection(),
82
-				$this->serverContainer->getUserManager(),
83
-				$this->serverContainer->getGroupManager(),
84
-				$this->serverContainer->getLazyRootFolder()
85
-			);
86
-		}
87
-
88
-		return $this->defaultProvider;
89
-	}
90
-
91
-	/**
92
-	 * Create the federated share provider
93
-	 *
94
-	 * @return FederatedShareProvider
95
-	 */
96
-	protected function federatedShareProvider() {
97
-		if ($this->federatedProvider === null) {
98
-			/*
51
+    /** @var IServerContainer */
52
+    private $serverContainer;
53
+    /** @var DefaultShareProvider */
54
+    private $defaultProvider = null;
55
+    /** @var FederatedShareProvider */
56
+    private $federatedProvider = null;
57
+    /** @var  ShareByMailProvider */
58
+    private $shareByMailProvider;
59
+    /** @var  \OCA\Circles\ShareByCircleProvider */
60
+    private $shareByCircleProvider = null;
61
+    /** @var bool */
62
+    private $circlesAreNotAvailable = false;
63
+
64
+    /**
65
+     * IProviderFactory constructor.
66
+     *
67
+     * @param IServerContainer $serverContainer
68
+     */
69
+    public function __construct(IServerContainer $serverContainer) {
70
+        $this->serverContainer = $serverContainer;
71
+    }
72
+
73
+    /**
74
+     * Create the default share provider.
75
+     *
76
+     * @return DefaultShareProvider
77
+     */
78
+    protected function defaultShareProvider() {
79
+        if ($this->defaultProvider === null) {
80
+            $this->defaultProvider = new DefaultShareProvider(
81
+                $this->serverContainer->getDatabaseConnection(),
82
+                $this->serverContainer->getUserManager(),
83
+                $this->serverContainer->getGroupManager(),
84
+                $this->serverContainer->getLazyRootFolder()
85
+            );
86
+        }
87
+
88
+        return $this->defaultProvider;
89
+    }
90
+
91
+    /**
92
+     * Create the federated share provider
93
+     *
94
+     * @return FederatedShareProvider
95
+     */
96
+    protected function federatedShareProvider() {
97
+        if ($this->federatedProvider === null) {
98
+            /*
99 99
 			 * Check if the app is enabled
100 100
 			 */
101
-			$appManager = $this->serverContainer->getAppManager();
102
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
103
-				return null;
104
-			}
101
+            $appManager = $this->serverContainer->getAppManager();
102
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
103
+                return null;
104
+            }
105 105
 
106
-			/*
106
+            /*
107 107
 			 * TODO: add factory to federated sharing app
108 108
 			 */
109
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
110
-			$addressHandler = new AddressHandler(
111
-				$this->serverContainer->getURLGenerator(),
112
-				$l,
113
-				$this->serverContainer->getCloudIdManager()
114
-			);
115
-			$notifications = new Notifications(
116
-				$addressHandler,
117
-				$this->serverContainer->getHTTPClientService(),
118
-				$this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
119
-				$this->serverContainer->getJobList(),
120
-				\OC::$server->getCloudFederationProviderManager(),
121
-				\OC::$server->getCloudFederationFactory()
122
-			);
123
-			$tokenHandler = new TokenHandler(
124
-				$this->serverContainer->getSecureRandom()
125
-			);
126
-
127
-			$this->federatedProvider = new FederatedShareProvider(
128
-				$this->serverContainer->getDatabaseConnection(),
129
-				$addressHandler,
130
-				$notifications,
131
-				$tokenHandler,
132
-				$l,
133
-				$this->serverContainer->getLogger(),
134
-				$this->serverContainer->getLazyRootFolder(),
135
-				$this->serverContainer->getConfig(),
136
-				$this->serverContainer->getUserManager(),
137
-				$this->serverContainer->getCloudIdManager(),
138
-				$this->serverContainer->getGlobalScaleConfig(),
139
-				$this->serverContainer->getCloudFederationProviderManager()
140
-			);
141
-		}
142
-
143
-		return $this->federatedProvider;
144
-	}
145
-
146
-	/**
147
-	 * Create the federated share provider
148
-	 *
149
-	 * @return ShareByMailProvider
150
-	 */
151
-	protected function getShareByMailProvider() {
152
-		if ($this->shareByMailProvider === null) {
153
-			/*
109
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
110
+            $addressHandler = new AddressHandler(
111
+                $this->serverContainer->getURLGenerator(),
112
+                $l,
113
+                $this->serverContainer->getCloudIdManager()
114
+            );
115
+            $notifications = new Notifications(
116
+                $addressHandler,
117
+                $this->serverContainer->getHTTPClientService(),
118
+                $this->serverContainer->query(\OCP\OCS\IDiscoveryService::class),
119
+                $this->serverContainer->getJobList(),
120
+                \OC::$server->getCloudFederationProviderManager(),
121
+                \OC::$server->getCloudFederationFactory()
122
+            );
123
+            $tokenHandler = new TokenHandler(
124
+                $this->serverContainer->getSecureRandom()
125
+            );
126
+
127
+            $this->federatedProvider = new FederatedShareProvider(
128
+                $this->serverContainer->getDatabaseConnection(),
129
+                $addressHandler,
130
+                $notifications,
131
+                $tokenHandler,
132
+                $l,
133
+                $this->serverContainer->getLogger(),
134
+                $this->serverContainer->getLazyRootFolder(),
135
+                $this->serverContainer->getConfig(),
136
+                $this->serverContainer->getUserManager(),
137
+                $this->serverContainer->getCloudIdManager(),
138
+                $this->serverContainer->getGlobalScaleConfig(),
139
+                $this->serverContainer->getCloudFederationProviderManager()
140
+            );
141
+        }
142
+
143
+        return $this->federatedProvider;
144
+    }
145
+
146
+    /**
147
+     * Create the federated share provider
148
+     *
149
+     * @return ShareByMailProvider
150
+     */
151
+    protected function getShareByMailProvider() {
152
+        if ($this->shareByMailProvider === null) {
153
+            /*
154 154
 			 * Check if the app is enabled
155 155
 			 */
156
-			$appManager = $this->serverContainer->getAppManager();
157
-			if (!$appManager->isEnabledForUser('sharebymail')) {
158
-				return null;
159
-			}
160
-
161
-			$settingsManager = new SettingsManager($this->serverContainer->getConfig());
162
-
163
-			$this->shareByMailProvider = new ShareByMailProvider(
164
-				$this->serverContainer->getDatabaseConnection(),
165
-				$this->serverContainer->getSecureRandom(),
166
-				$this->serverContainer->getUserManager(),
167
-				$this->serverContainer->getLazyRootFolder(),
168
-				$this->serverContainer->getL10N('sharebymail'),
169
-				$this->serverContainer->getLogger(),
170
-				$this->serverContainer->getMailer(),
171
-				$this->serverContainer->getURLGenerator(),
172
-				$this->serverContainer->getActivityManager(),
173
-				$settingsManager,
174
-				$this->serverContainer->query(Defaults::class),
175
-				$this->serverContainer->getHasher(),
176
-				$this->serverContainer->query(CapabilitiesManager::class)
177
-			);
178
-		}
179
-
180
-		return $this->shareByMailProvider;
181
-	}
182
-
183
-
184
-	/**
185
-	 * Create the circle share provider
186
-	 *
187
-	 * @return FederatedShareProvider
188
-	 *
189
-	 * @suppress PhanUndeclaredClassMethod
190
-	 */
191
-	protected function getShareByCircleProvider() {
192
-
193
-		if ($this->circlesAreNotAvailable) {
194
-			return null;
195
-		}
196
-
197
-		if (!$this->serverContainer->getAppManager()->isEnabledForUser('circles') ||
198
-			!class_exists('\OCA\Circles\ShareByCircleProvider')
199
-		) {
200
-			$this->circlesAreNotAvailable = true;
201
-			return null;
202
-		}
203
-
204
-		if ($this->shareByCircleProvider === null) {
205
-
206
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
207
-				$this->serverContainer->getDatabaseConnection(),
208
-				$this->serverContainer->getSecureRandom(),
209
-				$this->serverContainer->getUserManager(),
210
-				$this->serverContainer->getLazyRootFolder(),
211
-				$this->serverContainer->getL10N('circles'),
212
-				$this->serverContainer->getLogger(),
213
-				$this->serverContainer->getURLGenerator()
214
-			);
215
-		}
216
-
217
-		return $this->shareByCircleProvider;
218
-	}
219
-
220
-
221
-	/**
222
-	 * @inheritdoc
223
-	 */
224
-	public function getProvider($id) {
225
-		$provider = null;
226
-		if ($id === 'ocinternal') {
227
-			$provider = $this->defaultShareProvider();
228
-		} else if ($id === 'ocFederatedSharing') {
229
-			$provider = $this->federatedShareProvider();
230
-		} else if ($id === 'ocMailShare') {
231
-			$provider = $this->getShareByMailProvider();
232
-		} else if ($id === 'ocCircleShare') {
233
-			$provider = $this->getShareByCircleProvider();
234
-		}
235
-
236
-		if ($provider === null) {
237
-			throw new ProviderException('No provider with id .' . $id . ' found.');
238
-		}
239
-
240
-		return $provider;
241
-	}
242
-
243
-	/**
244
-	 * @inheritdoc
245
-	 */
246
-	public function getProviderForType($shareType) {
247
-		$provider = null;
248
-
249
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
250
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
251
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
252
-		) {
253
-			$provider = $this->defaultShareProvider();
254
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE || \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
255
-			$provider = $this->federatedShareProvider();
256
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
257
-			$provider = $this->getShareByMailProvider();
258
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
259
-			$provider = $this->getShareByCircleProvider();
260
-		}
261
-
262
-
263
-		if ($provider === null) {
264
-			throw new ProviderException('No share provider for share type ' . $shareType);
265
-		}
266
-
267
-		return $provider;
268
-	}
269
-
270
-	public function getAllProviders() {
271
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
272
-		$shareByMail = $this->getShareByMailProvider();
273
-		if ($shareByMail !== null) {
274
-			$shares[] = $shareByMail;
275
-		}
276
-		$shareByCircle = $this->getShareByCircleProvider();
277
-		if ($shareByCircle !== null) {
278
-			$shares[] = $shareByCircle;
279
-		}
280
-
281
-		return $shares;
282
-	}
156
+            $appManager = $this->serverContainer->getAppManager();
157
+            if (!$appManager->isEnabledForUser('sharebymail')) {
158
+                return null;
159
+            }
160
+
161
+            $settingsManager = new SettingsManager($this->serverContainer->getConfig());
162
+
163
+            $this->shareByMailProvider = new ShareByMailProvider(
164
+                $this->serverContainer->getDatabaseConnection(),
165
+                $this->serverContainer->getSecureRandom(),
166
+                $this->serverContainer->getUserManager(),
167
+                $this->serverContainer->getLazyRootFolder(),
168
+                $this->serverContainer->getL10N('sharebymail'),
169
+                $this->serverContainer->getLogger(),
170
+                $this->serverContainer->getMailer(),
171
+                $this->serverContainer->getURLGenerator(),
172
+                $this->serverContainer->getActivityManager(),
173
+                $settingsManager,
174
+                $this->serverContainer->query(Defaults::class),
175
+                $this->serverContainer->getHasher(),
176
+                $this->serverContainer->query(CapabilitiesManager::class)
177
+            );
178
+        }
179
+
180
+        return $this->shareByMailProvider;
181
+    }
182
+
183
+
184
+    /**
185
+     * Create the circle share provider
186
+     *
187
+     * @return FederatedShareProvider
188
+     *
189
+     * @suppress PhanUndeclaredClassMethod
190
+     */
191
+    protected function getShareByCircleProvider() {
192
+
193
+        if ($this->circlesAreNotAvailable) {
194
+            return null;
195
+        }
196
+
197
+        if (!$this->serverContainer->getAppManager()->isEnabledForUser('circles') ||
198
+            !class_exists('\OCA\Circles\ShareByCircleProvider')
199
+        ) {
200
+            $this->circlesAreNotAvailable = true;
201
+            return null;
202
+        }
203
+
204
+        if ($this->shareByCircleProvider === null) {
205
+
206
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
207
+                $this->serverContainer->getDatabaseConnection(),
208
+                $this->serverContainer->getSecureRandom(),
209
+                $this->serverContainer->getUserManager(),
210
+                $this->serverContainer->getLazyRootFolder(),
211
+                $this->serverContainer->getL10N('circles'),
212
+                $this->serverContainer->getLogger(),
213
+                $this->serverContainer->getURLGenerator()
214
+            );
215
+        }
216
+
217
+        return $this->shareByCircleProvider;
218
+    }
219
+
220
+
221
+    /**
222
+     * @inheritdoc
223
+     */
224
+    public function getProvider($id) {
225
+        $provider = null;
226
+        if ($id === 'ocinternal') {
227
+            $provider = $this->defaultShareProvider();
228
+        } else if ($id === 'ocFederatedSharing') {
229
+            $provider = $this->federatedShareProvider();
230
+        } else if ($id === 'ocMailShare') {
231
+            $provider = $this->getShareByMailProvider();
232
+        } else if ($id === 'ocCircleShare') {
233
+            $provider = $this->getShareByCircleProvider();
234
+        }
235
+
236
+        if ($provider === null) {
237
+            throw new ProviderException('No provider with id .' . $id . ' found.');
238
+        }
239
+
240
+        return $provider;
241
+    }
242
+
243
+    /**
244
+     * @inheritdoc
245
+     */
246
+    public function getProviderForType($shareType) {
247
+        $provider = null;
248
+
249
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
250
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
251
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
252
+        ) {
253
+            $provider = $this->defaultShareProvider();
254
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE || \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
255
+            $provider = $this->federatedShareProvider();
256
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
257
+            $provider = $this->getShareByMailProvider();
258
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
259
+            $provider = $this->getShareByCircleProvider();
260
+        }
261
+
262
+
263
+        if ($provider === null) {
264
+            throw new ProviderException('No share provider for share type ' . $shareType);
265
+        }
266
+
267
+        return $provider;
268
+    }
269
+
270
+    public function getAllProviders() {
271
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
272
+        $shareByMail = $this->getShareByMailProvider();
273
+        if ($shareByMail !== null) {
274
+            $shares[] = $shareByMail;
275
+        }
276
+        $shareByCircle = $this->getShareByCircleProvider();
277
+        if ($shareByCircle !== null) {
278
+            $shares[] = $shareByCircle;
279
+        }
280
+
281
+        return $shares;
282
+    }
283 283
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 3 patches
Indentation   +1507 added lines, -1507 removed lines patch added patch discarded remove patch
@@ -72,1535 +72,1535 @@
 block discarded – undo
72 72
  */
73 73
 class Manager implements IManager {
74 74
 
75
-	/** @var IProviderFactory */
76
-	private $factory;
77
-	/** @var ILogger */
78
-	private $logger;
79
-	/** @var IConfig */
80
-	private $config;
81
-	/** @var ISecureRandom */
82
-	private $secureRandom;
83
-	/** @var IHasher */
84
-	private $hasher;
85
-	/** @var IMountManager */
86
-	private $mountManager;
87
-	/** @var IGroupManager */
88
-	private $groupManager;
89
-	/** @var IL10N */
90
-	private $l;
91
-	/** @var IFactory */
92
-	private $l10nFactory;
93
-	/** @var IUserManager */
94
-	private $userManager;
95
-	/** @var IRootFolder */
96
-	private $rootFolder;
97
-	/** @var CappedMemoryCache */
98
-	private $sharingDisabledForUsersCache;
99
-	/** @var EventDispatcher */
100
-	private $eventDispatcher;
101
-	/** @var LegacyHooks */
102
-	private $legacyHooks;
103
-	/** @var IMailer */
104
-	private $mailer;
105
-	/** @var IURLGenerator */
106
-	private $urlGenerator;
107
-	/** @var \OC_Defaults */
108
-	private $defaults;
109
-
110
-
111
-	/**
112
-	 * Manager constructor.
113
-	 *
114
-	 * @param ILogger $logger
115
-	 * @param IConfig $config
116
-	 * @param ISecureRandom $secureRandom
117
-	 * @param IHasher $hasher
118
-	 * @param IMountManager $mountManager
119
-	 * @param IGroupManager $groupManager
120
-	 * @param IL10N $l
121
-	 * @param IFactory $l10nFactory
122
-	 * @param IProviderFactory $factory
123
-	 * @param IUserManager $userManager
124
-	 * @param IRootFolder $rootFolder
125
-	 * @param EventDispatcher $eventDispatcher
126
-	 * @param IMailer $mailer
127
-	 * @param IURLGenerator $urlGenerator
128
-	 * @param \OC_Defaults $defaults
129
-	 */
130
-	public function __construct(
131
-			ILogger $logger,
132
-			IConfig $config,
133
-			ISecureRandom $secureRandom,
134
-			IHasher $hasher,
135
-			IMountManager $mountManager,
136
-			IGroupManager $groupManager,
137
-			IL10N $l,
138
-			IFactory $l10nFactory,
139
-			IProviderFactory $factory,
140
-			IUserManager $userManager,
141
-			IRootFolder $rootFolder,
142
-			EventDispatcher $eventDispatcher,
143
-			IMailer $mailer,
144
-			IURLGenerator $urlGenerator,
145
-			\OC_Defaults $defaults
146
-	) {
147
-		$this->logger = $logger;
148
-		$this->config = $config;
149
-		$this->secureRandom = $secureRandom;
150
-		$this->hasher = $hasher;
151
-		$this->mountManager = $mountManager;
152
-		$this->groupManager = $groupManager;
153
-		$this->l = $l;
154
-		$this->l10nFactory = $l10nFactory;
155
-		$this->factory = $factory;
156
-		$this->userManager = $userManager;
157
-		$this->rootFolder = $rootFolder;
158
-		$this->eventDispatcher = $eventDispatcher;
159
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
160
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
161
-		$this->mailer = $mailer;
162
-		$this->urlGenerator = $urlGenerator;
163
-		$this->defaults = $defaults;
164
-	}
165
-
166
-	/**
167
-	 * Convert from a full share id to a tuple (providerId, shareId)
168
-	 *
169
-	 * @param string $id
170
-	 * @return string[]
171
-	 */
172
-	private function splitFullId($id) {
173
-		return explode(':', $id, 2);
174
-	}
175
-
176
-	/**
177
-	 * Verify if a password meets all requirements
178
-	 *
179
-	 * @param string $password
180
-	 * @throws \Exception
181
-	 */
182
-	protected function verifyPassword($password) {
183
-		if ($password === null) {
184
-			// No password is set, check if this is allowed.
185
-			if ($this->shareApiLinkEnforcePassword()) {
186
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
187
-			}
188
-
189
-			return;
190
-		}
191
-
192
-		// Let others verify the password
193
-		try {
194
-			$event = new GenericEvent($password);
195
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
196
-		} catch (HintException $e) {
197
-			throw new \Exception($e->getHint());
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * Check for generic requirements before creating a share
203
-	 *
204
-	 * @param \OCP\Share\IShare $share
205
-	 * @throws \InvalidArgumentException
206
-	 * @throws GenericShareException
207
-	 *
208
-	 * @suppress PhanUndeclaredClassMethod
209
-	 */
210
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
211
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
212
-			// We expect a valid user as sharedWith for user shares
213
-			if (!$this->userManager->userExists($share->getSharedWith())) {
214
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
215
-			}
216
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
217
-			// We expect a valid group as sharedWith for group shares
218
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
219
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
222
-			if ($share->getSharedWith() !== null) {
223
-				throw new \InvalidArgumentException('SharedWith should be empty');
224
-			}
225
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
226
-			if ($share->getSharedWith() === null) {
227
-				throw new \InvalidArgumentException('SharedWith should not be empty');
228
-			}
229
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230
-			if ($share->getSharedWith() === null) {
231
-				throw new \InvalidArgumentException('SharedWith should not be empty');
232
-			}
233
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
234
-			if ($share->getSharedWith() === null) {
235
-				throw new \InvalidArgumentException('SharedWith should not be empty');
236
-			}
237
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
239
-			if ($circle === null) {
240
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
241
-			}
242
-		} else {
243
-			// We can't handle other types yet
244
-			throw new \InvalidArgumentException('unknown share type');
245
-		}
246
-
247
-		// Verify the initiator of the share is set
248
-		if ($share->getSharedBy() === null) {
249
-			throw new \InvalidArgumentException('SharedBy should be set');
250
-		}
251
-
252
-		// Cannot share with yourself
253
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
254
-			$share->getSharedWith() === $share->getSharedBy()) {
255
-			throw new \InvalidArgumentException('Can’t share with yourself');
256
-		}
257
-
258
-		// The path should be set
259
-		if ($share->getNode() === null) {
260
-			throw new \InvalidArgumentException('Path should be set');
261
-		}
262
-
263
-		// And it should be a file or a folder
264
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
265
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
266
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
267
-		}
268
-
269
-		// And you can't share your rootfolder
270
-		if ($this->userManager->userExists($share->getSharedBy())) {
271
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
272
-		} else {
273
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
274
-		}
275
-		if ($sharedPath === $share->getNode()->getPath()) {
276
-			throw new \InvalidArgumentException('You can’t share your root folder');
277
-		}
278
-
279
-		// Check if we actually have share permissions
280
-		if (!$share->getNode()->isShareable()) {
281
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
282
-			throw new GenericShareException($message_t, $message_t, 404);
283
-		}
284
-
285
-		// Permissions should be set
286
-		if ($share->getPermissions() === null) {
287
-			throw new \InvalidArgumentException('A share requires permissions');
288
-		}
289
-
290
-		/*
75
+    /** @var IProviderFactory */
76
+    private $factory;
77
+    /** @var ILogger */
78
+    private $logger;
79
+    /** @var IConfig */
80
+    private $config;
81
+    /** @var ISecureRandom */
82
+    private $secureRandom;
83
+    /** @var IHasher */
84
+    private $hasher;
85
+    /** @var IMountManager */
86
+    private $mountManager;
87
+    /** @var IGroupManager */
88
+    private $groupManager;
89
+    /** @var IL10N */
90
+    private $l;
91
+    /** @var IFactory */
92
+    private $l10nFactory;
93
+    /** @var IUserManager */
94
+    private $userManager;
95
+    /** @var IRootFolder */
96
+    private $rootFolder;
97
+    /** @var CappedMemoryCache */
98
+    private $sharingDisabledForUsersCache;
99
+    /** @var EventDispatcher */
100
+    private $eventDispatcher;
101
+    /** @var LegacyHooks */
102
+    private $legacyHooks;
103
+    /** @var IMailer */
104
+    private $mailer;
105
+    /** @var IURLGenerator */
106
+    private $urlGenerator;
107
+    /** @var \OC_Defaults */
108
+    private $defaults;
109
+
110
+
111
+    /**
112
+     * Manager constructor.
113
+     *
114
+     * @param ILogger $logger
115
+     * @param IConfig $config
116
+     * @param ISecureRandom $secureRandom
117
+     * @param IHasher $hasher
118
+     * @param IMountManager $mountManager
119
+     * @param IGroupManager $groupManager
120
+     * @param IL10N $l
121
+     * @param IFactory $l10nFactory
122
+     * @param IProviderFactory $factory
123
+     * @param IUserManager $userManager
124
+     * @param IRootFolder $rootFolder
125
+     * @param EventDispatcher $eventDispatcher
126
+     * @param IMailer $mailer
127
+     * @param IURLGenerator $urlGenerator
128
+     * @param \OC_Defaults $defaults
129
+     */
130
+    public function __construct(
131
+            ILogger $logger,
132
+            IConfig $config,
133
+            ISecureRandom $secureRandom,
134
+            IHasher $hasher,
135
+            IMountManager $mountManager,
136
+            IGroupManager $groupManager,
137
+            IL10N $l,
138
+            IFactory $l10nFactory,
139
+            IProviderFactory $factory,
140
+            IUserManager $userManager,
141
+            IRootFolder $rootFolder,
142
+            EventDispatcher $eventDispatcher,
143
+            IMailer $mailer,
144
+            IURLGenerator $urlGenerator,
145
+            \OC_Defaults $defaults
146
+    ) {
147
+        $this->logger = $logger;
148
+        $this->config = $config;
149
+        $this->secureRandom = $secureRandom;
150
+        $this->hasher = $hasher;
151
+        $this->mountManager = $mountManager;
152
+        $this->groupManager = $groupManager;
153
+        $this->l = $l;
154
+        $this->l10nFactory = $l10nFactory;
155
+        $this->factory = $factory;
156
+        $this->userManager = $userManager;
157
+        $this->rootFolder = $rootFolder;
158
+        $this->eventDispatcher = $eventDispatcher;
159
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
160
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
161
+        $this->mailer = $mailer;
162
+        $this->urlGenerator = $urlGenerator;
163
+        $this->defaults = $defaults;
164
+    }
165
+
166
+    /**
167
+     * Convert from a full share id to a tuple (providerId, shareId)
168
+     *
169
+     * @param string $id
170
+     * @return string[]
171
+     */
172
+    private function splitFullId($id) {
173
+        return explode(':', $id, 2);
174
+    }
175
+
176
+    /**
177
+     * Verify if a password meets all requirements
178
+     *
179
+     * @param string $password
180
+     * @throws \Exception
181
+     */
182
+    protected function verifyPassword($password) {
183
+        if ($password === null) {
184
+            // No password is set, check if this is allowed.
185
+            if ($this->shareApiLinkEnforcePassword()) {
186
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
187
+            }
188
+
189
+            return;
190
+        }
191
+
192
+        // Let others verify the password
193
+        try {
194
+            $event = new GenericEvent($password);
195
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
196
+        } catch (HintException $e) {
197
+            throw new \Exception($e->getHint());
198
+        }
199
+    }
200
+
201
+    /**
202
+     * Check for generic requirements before creating a share
203
+     *
204
+     * @param \OCP\Share\IShare $share
205
+     * @throws \InvalidArgumentException
206
+     * @throws GenericShareException
207
+     *
208
+     * @suppress PhanUndeclaredClassMethod
209
+     */
210
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
211
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
212
+            // We expect a valid user as sharedWith for user shares
213
+            if (!$this->userManager->userExists($share->getSharedWith())) {
214
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
215
+            }
216
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
217
+            // We expect a valid group as sharedWith for group shares
218
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
219
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
222
+            if ($share->getSharedWith() !== null) {
223
+                throw new \InvalidArgumentException('SharedWith should be empty');
224
+            }
225
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
226
+            if ($share->getSharedWith() === null) {
227
+                throw new \InvalidArgumentException('SharedWith should not be empty');
228
+            }
229
+        }  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230
+            if ($share->getSharedWith() === null) {
231
+                throw new \InvalidArgumentException('SharedWith should not be empty');
232
+            }
233
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
234
+            if ($share->getSharedWith() === null) {
235
+                throw new \InvalidArgumentException('SharedWith should not be empty');
236
+            }
237
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
239
+            if ($circle === null) {
240
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
241
+            }
242
+        } else {
243
+            // We can't handle other types yet
244
+            throw new \InvalidArgumentException('unknown share type');
245
+        }
246
+
247
+        // Verify the initiator of the share is set
248
+        if ($share->getSharedBy() === null) {
249
+            throw new \InvalidArgumentException('SharedBy should be set');
250
+        }
251
+
252
+        // Cannot share with yourself
253
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
254
+            $share->getSharedWith() === $share->getSharedBy()) {
255
+            throw new \InvalidArgumentException('Can’t share with yourself');
256
+        }
257
+
258
+        // The path should be set
259
+        if ($share->getNode() === null) {
260
+            throw new \InvalidArgumentException('Path should be set');
261
+        }
262
+
263
+        // And it should be a file or a folder
264
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
265
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
266
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
267
+        }
268
+
269
+        // And you can't share your rootfolder
270
+        if ($this->userManager->userExists($share->getSharedBy())) {
271
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
272
+        } else {
273
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
274
+        }
275
+        if ($sharedPath === $share->getNode()->getPath()) {
276
+            throw new \InvalidArgumentException('You can’t share your root folder');
277
+        }
278
+
279
+        // Check if we actually have share permissions
280
+        if (!$share->getNode()->isShareable()) {
281
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
282
+            throw new GenericShareException($message_t, $message_t, 404);
283
+        }
284
+
285
+        // Permissions should be set
286
+        if ($share->getPermissions() === null) {
287
+            throw new \InvalidArgumentException('A share requires permissions');
288
+        }
289
+
290
+        /*
291 291
 		 * Quick fix for #23536
292 292
 		 * Non moveable mount points do not have update and delete permissions
293 293
 		 * while we 'most likely' do have that on the storage.
294 294
 		 */
295
-		$permissions = $share->getNode()->getPermissions();
296
-		$mount = $share->getNode()->getMountPoint();
297
-		if (!($mount instanceof MoveableMount)) {
298
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
299
-		}
300
-
301
-		// Check that we do not share with more permissions than we have
302
-		if ($share->getPermissions() & ~$permissions) {
303
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
304
-			throw new GenericShareException($message_t, $message_t, 404);
305
-		}
306
-
307
-
308
-		// Check that read permissions are always set
309
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
310
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
311
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
312
-		if (!$noReadPermissionRequired &&
313
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
314
-			throw new \InvalidArgumentException('Shares need at least read permissions');
315
-		}
316
-
317
-		if ($share->getNode() instanceof \OCP\Files\File) {
318
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
319
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
320
-				throw new GenericShareException($message_t);
321
-			}
322
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
323
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
324
-				throw new GenericShareException($message_t);
325
-			}
326
-		}
327
-	}
328
-
329
-	/**
330
-	 * Validate if the expiration date fits the system settings
331
-	 *
332
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
333
-	 * @return \OCP\Share\IShare The modified share object
334
-	 * @throws GenericShareException
335
-	 * @throws \InvalidArgumentException
336
-	 * @throws \Exception
337
-	 */
338
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
339
-
340
-		$expirationDate = $share->getExpirationDate();
341
-
342
-		if ($expirationDate !== null) {
343
-			//Make sure the expiration date is a date
344
-			$expirationDate->setTime(0, 0, 0);
345
-
346
-			$date = new \DateTime();
347
-			$date->setTime(0, 0, 0);
348
-			if ($date >= $expirationDate) {
349
-				$message = $this->l->t('Expiration date is in the past');
350
-				throw new GenericShareException($message, $message, 404);
351
-			}
352
-		}
353
-
354
-		// If expiredate is empty set a default one if there is a default
355
-		$fullId = null;
356
-		try {
357
-			$fullId = $share->getFullId();
358
-		} catch (\UnexpectedValueException $e) {
359
-			// This is a new share
360
-		}
361
-
362
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
363
-			$expirationDate = new \DateTime();
364
-			$expirationDate->setTime(0,0,0);
365
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
366
-		}
367
-
368
-		// If we enforce the expiration date check that is does not exceed
369
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
370
-			if ($expirationDate === null) {
371
-				throw new \InvalidArgumentException('Expiration date is enforced');
372
-			}
373
-
374
-			$date = new \DateTime();
375
-			$date->setTime(0, 0, 0);
376
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
377
-			if ($date < $expirationDate) {
378
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
379
-				throw new GenericShareException($message, $message, 404);
380
-			}
381
-		}
382
-
383
-		$accepted = true;
384
-		$message = '';
385
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
386
-			'expirationDate' => &$expirationDate,
387
-			'accepted' => &$accepted,
388
-			'message' => &$message,
389
-			'passwordSet' => $share->getPassword() !== null,
390
-		]);
391
-
392
-		if (!$accepted) {
393
-			throw new \Exception($message);
394
-		}
395
-
396
-		$share->setExpirationDate($expirationDate);
397
-
398
-		return $share;
399
-	}
400
-
401
-	/**
402
-	 * Check for pre share requirements for user shares
403
-	 *
404
-	 * @param \OCP\Share\IShare $share
405
-	 * @throws \Exception
406
-	 */
407
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
408
-		// Check if we can share with group members only
409
-		if ($this->shareWithGroupMembersOnly()) {
410
-			$sharedBy = $this->userManager->get($share->getSharedBy());
411
-			$sharedWith = $this->userManager->get($share->getSharedWith());
412
-			// Verify we can share with this user
413
-			$groups = array_intersect(
414
-					$this->groupManager->getUserGroupIds($sharedBy),
415
-					$this->groupManager->getUserGroupIds($sharedWith)
416
-			);
417
-			if (empty($groups)) {
418
-				throw new \Exception('Sharing is only allowed with group members');
419
-			}
420
-		}
421
-
422
-		/*
295
+        $permissions = $share->getNode()->getPermissions();
296
+        $mount = $share->getNode()->getMountPoint();
297
+        if (!($mount instanceof MoveableMount)) {
298
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
299
+        }
300
+
301
+        // Check that we do not share with more permissions than we have
302
+        if ($share->getPermissions() & ~$permissions) {
303
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
304
+            throw new GenericShareException($message_t, $message_t, 404);
305
+        }
306
+
307
+
308
+        // Check that read permissions are always set
309
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
310
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
311
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
312
+        if (!$noReadPermissionRequired &&
313
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
314
+            throw new \InvalidArgumentException('Shares need at least read permissions');
315
+        }
316
+
317
+        if ($share->getNode() instanceof \OCP\Files\File) {
318
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
319
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
320
+                throw new GenericShareException($message_t);
321
+            }
322
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
323
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
324
+                throw new GenericShareException($message_t);
325
+            }
326
+        }
327
+    }
328
+
329
+    /**
330
+     * Validate if the expiration date fits the system settings
331
+     *
332
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
333
+     * @return \OCP\Share\IShare The modified share object
334
+     * @throws GenericShareException
335
+     * @throws \InvalidArgumentException
336
+     * @throws \Exception
337
+     */
338
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
339
+
340
+        $expirationDate = $share->getExpirationDate();
341
+
342
+        if ($expirationDate !== null) {
343
+            //Make sure the expiration date is a date
344
+            $expirationDate->setTime(0, 0, 0);
345
+
346
+            $date = new \DateTime();
347
+            $date->setTime(0, 0, 0);
348
+            if ($date >= $expirationDate) {
349
+                $message = $this->l->t('Expiration date is in the past');
350
+                throw new GenericShareException($message, $message, 404);
351
+            }
352
+        }
353
+
354
+        // If expiredate is empty set a default one if there is a default
355
+        $fullId = null;
356
+        try {
357
+            $fullId = $share->getFullId();
358
+        } catch (\UnexpectedValueException $e) {
359
+            // This is a new share
360
+        }
361
+
362
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
363
+            $expirationDate = new \DateTime();
364
+            $expirationDate->setTime(0,0,0);
365
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
366
+        }
367
+
368
+        // If we enforce the expiration date check that is does not exceed
369
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
370
+            if ($expirationDate === null) {
371
+                throw new \InvalidArgumentException('Expiration date is enforced');
372
+            }
373
+
374
+            $date = new \DateTime();
375
+            $date->setTime(0, 0, 0);
376
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
377
+            if ($date < $expirationDate) {
378
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
379
+                throw new GenericShareException($message, $message, 404);
380
+            }
381
+        }
382
+
383
+        $accepted = true;
384
+        $message = '';
385
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
386
+            'expirationDate' => &$expirationDate,
387
+            'accepted' => &$accepted,
388
+            'message' => &$message,
389
+            'passwordSet' => $share->getPassword() !== null,
390
+        ]);
391
+
392
+        if (!$accepted) {
393
+            throw new \Exception($message);
394
+        }
395
+
396
+        $share->setExpirationDate($expirationDate);
397
+
398
+        return $share;
399
+    }
400
+
401
+    /**
402
+     * Check for pre share requirements for user shares
403
+     *
404
+     * @param \OCP\Share\IShare $share
405
+     * @throws \Exception
406
+     */
407
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
408
+        // Check if we can share with group members only
409
+        if ($this->shareWithGroupMembersOnly()) {
410
+            $sharedBy = $this->userManager->get($share->getSharedBy());
411
+            $sharedWith = $this->userManager->get($share->getSharedWith());
412
+            // Verify we can share with this user
413
+            $groups = array_intersect(
414
+                    $this->groupManager->getUserGroupIds($sharedBy),
415
+                    $this->groupManager->getUserGroupIds($sharedWith)
416
+            );
417
+            if (empty($groups)) {
418
+                throw new \Exception('Sharing is only allowed with group members');
419
+            }
420
+        }
421
+
422
+        /*
423 423
 		 * TODO: Could be costly, fix
424 424
 		 *
425 425
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
426 426
 		 */
427
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
428
-		$existingShares = $provider->getSharesByPath($share->getNode());
429
-		foreach($existingShares as $existingShare) {
430
-			// Ignore if it is the same share
431
-			try {
432
-				if ($existingShare->getFullId() === $share->getFullId()) {
433
-					continue;
434
-				}
435
-			} catch (\UnexpectedValueException $e) {
436
-				//Shares are not identical
437
-			}
438
-
439
-			// Identical share already existst
440
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
441
-				throw new \Exception('Path is already shared with this user');
442
-			}
443
-
444
-			// The share is already shared with this user via a group share
445
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
446
-				$group = $this->groupManager->get($existingShare->getSharedWith());
447
-				if (!is_null($group)) {
448
-					$user = $this->userManager->get($share->getSharedWith());
449
-
450
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
451
-						throw new \Exception('Path is already shared with this user');
452
-					}
453
-				}
454
-			}
455
-		}
456
-	}
457
-
458
-	/**
459
-	 * Check for pre share requirements for group shares
460
-	 *
461
-	 * @param \OCP\Share\IShare $share
462
-	 * @throws \Exception
463
-	 */
464
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
465
-		// Verify group shares are allowed
466
-		if (!$this->allowGroupSharing()) {
467
-			throw new \Exception('Group sharing is now allowed');
468
-		}
469
-
470
-		// Verify if the user can share with this group
471
-		if ($this->shareWithGroupMembersOnly()) {
472
-			$sharedBy = $this->userManager->get($share->getSharedBy());
473
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
474
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
475
-				throw new \Exception('Sharing is only allowed within your own groups');
476
-			}
477
-		}
478
-
479
-		/*
427
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
428
+        $existingShares = $provider->getSharesByPath($share->getNode());
429
+        foreach($existingShares as $existingShare) {
430
+            // Ignore if it is the same share
431
+            try {
432
+                if ($existingShare->getFullId() === $share->getFullId()) {
433
+                    continue;
434
+                }
435
+            } catch (\UnexpectedValueException $e) {
436
+                //Shares are not identical
437
+            }
438
+
439
+            // Identical share already existst
440
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
441
+                throw new \Exception('Path is already shared with this user');
442
+            }
443
+
444
+            // The share is already shared with this user via a group share
445
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
446
+                $group = $this->groupManager->get($existingShare->getSharedWith());
447
+                if (!is_null($group)) {
448
+                    $user = $this->userManager->get($share->getSharedWith());
449
+
450
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
451
+                        throw new \Exception('Path is already shared with this user');
452
+                    }
453
+                }
454
+            }
455
+        }
456
+    }
457
+
458
+    /**
459
+     * Check for pre share requirements for group shares
460
+     *
461
+     * @param \OCP\Share\IShare $share
462
+     * @throws \Exception
463
+     */
464
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
465
+        // Verify group shares are allowed
466
+        if (!$this->allowGroupSharing()) {
467
+            throw new \Exception('Group sharing is now allowed');
468
+        }
469
+
470
+        // Verify if the user can share with this group
471
+        if ($this->shareWithGroupMembersOnly()) {
472
+            $sharedBy = $this->userManager->get($share->getSharedBy());
473
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
474
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
475
+                throw new \Exception('Sharing is only allowed within your own groups');
476
+            }
477
+        }
478
+
479
+        /*
480 480
 		 * TODO: Could be costly, fix
481 481
 		 *
482 482
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
483 483
 		 */
484
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
485
-		$existingShares = $provider->getSharesByPath($share->getNode());
486
-		foreach($existingShares as $existingShare) {
487
-			try {
488
-				if ($existingShare->getFullId() === $share->getFullId()) {
489
-					continue;
490
-				}
491
-			} catch (\UnexpectedValueException $e) {
492
-				//It is a new share so just continue
493
-			}
494
-
495
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
496
-				throw new \Exception('Path is already shared with this group');
497
-			}
498
-		}
499
-	}
500
-
501
-	/**
502
-	 * Check for pre share requirements for link shares
503
-	 *
504
-	 * @param \OCP\Share\IShare $share
505
-	 * @throws \Exception
506
-	 */
507
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
508
-		// Are link shares allowed?
509
-		if (!$this->shareApiAllowLinks()) {
510
-			throw new \Exception('Link sharing is not allowed');
511
-		}
512
-
513
-		// Link shares by definition can't have share permissions
514
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
515
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
516
-		}
517
-
518
-		// Check if public upload is allowed
519
-		if (!$this->shareApiLinkAllowPublicUpload() &&
520
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
521
-			throw new \InvalidArgumentException('Public upload is not allowed');
522
-		}
523
-	}
524
-
525
-	/**
526
-	 * To make sure we don't get invisible link shares we set the parent
527
-	 * of a link if it is a reshare. This is a quick word around
528
-	 * until we can properly display multiple link shares in the UI
529
-	 *
530
-	 * See: https://github.com/owncloud/core/issues/22295
531
-	 *
532
-	 * FIXME: Remove once multiple link shares can be properly displayed
533
-	 *
534
-	 * @param \OCP\Share\IShare $share
535
-	 */
536
-	protected function setLinkParent(\OCP\Share\IShare $share) {
537
-
538
-		// No sense in checking if the method is not there.
539
-		if (method_exists($share, 'setParent')) {
540
-			$storage = $share->getNode()->getStorage();
541
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
542
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
543
-				$share->setParent($storage->getShareId());
544
-			}
545
-		}
546
-	}
547
-
548
-	/**
549
-	 * @param File|Folder $path
550
-	 */
551
-	protected function pathCreateChecks($path) {
552
-		// Make sure that we do not share a path that contains a shared mountpoint
553
-		if ($path instanceof \OCP\Files\Folder) {
554
-			$mounts = $this->mountManager->findIn($path->getPath());
555
-			foreach($mounts as $mount) {
556
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
557
-					throw new \InvalidArgumentException('Path contains files shared with you');
558
-				}
559
-			}
560
-		}
561
-	}
562
-
563
-	/**
564
-	 * Check if the user that is sharing can actually share
565
-	 *
566
-	 * @param \OCP\Share\IShare $share
567
-	 * @throws \Exception
568
-	 */
569
-	protected function canShare(\OCP\Share\IShare $share) {
570
-		if (!$this->shareApiEnabled()) {
571
-			throw new \Exception('Sharing is disabled');
572
-		}
573
-
574
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
575
-			throw new \Exception('Sharing is disabled for you');
576
-		}
577
-	}
578
-
579
-	/**
580
-	 * Share a path
581
-	 *
582
-	 * @param \OCP\Share\IShare $share
583
-	 * @return Share The share object
584
-	 * @throws \Exception
585
-	 *
586
-	 * TODO: handle link share permissions or check them
587
-	 */
588
-	public function createShare(\OCP\Share\IShare $share) {
589
-		$this->canShare($share);
590
-
591
-		$this->generalCreateChecks($share);
592
-
593
-		// Verify if there are any issues with the path
594
-		$this->pathCreateChecks($share->getNode());
595
-
596
-		/*
484
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
485
+        $existingShares = $provider->getSharesByPath($share->getNode());
486
+        foreach($existingShares as $existingShare) {
487
+            try {
488
+                if ($existingShare->getFullId() === $share->getFullId()) {
489
+                    continue;
490
+                }
491
+            } catch (\UnexpectedValueException $e) {
492
+                //It is a new share so just continue
493
+            }
494
+
495
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
496
+                throw new \Exception('Path is already shared with this group');
497
+            }
498
+        }
499
+    }
500
+
501
+    /**
502
+     * Check for pre share requirements for link shares
503
+     *
504
+     * @param \OCP\Share\IShare $share
505
+     * @throws \Exception
506
+     */
507
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
508
+        // Are link shares allowed?
509
+        if (!$this->shareApiAllowLinks()) {
510
+            throw new \Exception('Link sharing is not allowed');
511
+        }
512
+
513
+        // Link shares by definition can't have share permissions
514
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
515
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
516
+        }
517
+
518
+        // Check if public upload is allowed
519
+        if (!$this->shareApiLinkAllowPublicUpload() &&
520
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
521
+            throw new \InvalidArgumentException('Public upload is not allowed');
522
+        }
523
+    }
524
+
525
+    /**
526
+     * To make sure we don't get invisible link shares we set the parent
527
+     * of a link if it is a reshare. This is a quick word around
528
+     * until we can properly display multiple link shares in the UI
529
+     *
530
+     * See: https://github.com/owncloud/core/issues/22295
531
+     *
532
+     * FIXME: Remove once multiple link shares can be properly displayed
533
+     *
534
+     * @param \OCP\Share\IShare $share
535
+     */
536
+    protected function setLinkParent(\OCP\Share\IShare $share) {
537
+
538
+        // No sense in checking if the method is not there.
539
+        if (method_exists($share, 'setParent')) {
540
+            $storage = $share->getNode()->getStorage();
541
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
542
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
543
+                $share->setParent($storage->getShareId());
544
+            }
545
+        }
546
+    }
547
+
548
+    /**
549
+     * @param File|Folder $path
550
+     */
551
+    protected function pathCreateChecks($path) {
552
+        // Make sure that we do not share a path that contains a shared mountpoint
553
+        if ($path instanceof \OCP\Files\Folder) {
554
+            $mounts = $this->mountManager->findIn($path->getPath());
555
+            foreach($mounts as $mount) {
556
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
557
+                    throw new \InvalidArgumentException('Path contains files shared with you');
558
+                }
559
+            }
560
+        }
561
+    }
562
+
563
+    /**
564
+     * Check if the user that is sharing can actually share
565
+     *
566
+     * @param \OCP\Share\IShare $share
567
+     * @throws \Exception
568
+     */
569
+    protected function canShare(\OCP\Share\IShare $share) {
570
+        if (!$this->shareApiEnabled()) {
571
+            throw new \Exception('Sharing is disabled');
572
+        }
573
+
574
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
575
+            throw new \Exception('Sharing is disabled for you');
576
+        }
577
+    }
578
+
579
+    /**
580
+     * Share a path
581
+     *
582
+     * @param \OCP\Share\IShare $share
583
+     * @return Share The share object
584
+     * @throws \Exception
585
+     *
586
+     * TODO: handle link share permissions or check them
587
+     */
588
+    public function createShare(\OCP\Share\IShare $share) {
589
+        $this->canShare($share);
590
+
591
+        $this->generalCreateChecks($share);
592
+
593
+        // Verify if there are any issues with the path
594
+        $this->pathCreateChecks($share->getNode());
595
+
596
+        /*
597 597
 		 * On creation of a share the owner is always the owner of the path
598 598
 		 * Except for mounted federated shares.
599 599
 		 */
600
-		$storage = $share->getNode()->getStorage();
601
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
602
-			$parent = $share->getNode()->getParent();
603
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
604
-				$parent = $parent->getParent();
605
-			}
606
-			$share->setShareOwner($parent->getOwner()->getUID());
607
-		} else {
608
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
609
-		}
610
-
611
-		//Verify share type
612
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
613
-			$this->userCreateChecks($share);
614
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
615
-			$this->groupCreateChecks($share);
616
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
617
-			$this->linkCreateChecks($share);
618
-			$this->setLinkParent($share);
619
-
620
-			/*
600
+        $storage = $share->getNode()->getStorage();
601
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
602
+            $parent = $share->getNode()->getParent();
603
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
604
+                $parent = $parent->getParent();
605
+            }
606
+            $share->setShareOwner($parent->getOwner()->getUID());
607
+        } else {
608
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
609
+        }
610
+
611
+        //Verify share type
612
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
613
+            $this->userCreateChecks($share);
614
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
615
+            $this->groupCreateChecks($share);
616
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
617
+            $this->linkCreateChecks($share);
618
+            $this->setLinkParent($share);
619
+
620
+            /*
621 621
 			 * For now ignore a set token.
622 622
 			 */
623
-			$share->setToken(
624
-				$this->secureRandom->generate(
625
-					\OC\Share\Constants::TOKEN_LENGTH,
626
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
627
-				)
628
-			);
629
-
630
-			//Verify the expiration date
631
-			$this->validateExpirationDate($share);
632
-
633
-			//Verify the password
634
-			$this->verifyPassword($share->getPassword());
635
-
636
-			// If a password is set. Hash it!
637
-			if ($share->getPassword() !== null) {
638
-				$share->setPassword($this->hasher->hash($share->getPassword()));
639
-			}
640
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
641
-			$share->setToken(
642
-				$this->secureRandom->generate(
643
-					\OC\Share\Constants::TOKEN_LENGTH,
644
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
645
-				)
646
-			);
647
-		}
648
-
649
-		// Cannot share with the owner
650
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
651
-			$share->getSharedWith() === $share->getShareOwner()) {
652
-			throw new \InvalidArgumentException('Can’t share with the share owner');
653
-		}
654
-
655
-		// Generate the target
656
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
657
-		$target = \OC\Files\Filesystem::normalizePath($target);
658
-		$share->setTarget($target);
659
-
660
-		// Pre share event
661
-		$event = new GenericEvent($share);
662
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
663
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
664
-			throw new \Exception($event->getArgument('error'));
665
-		}
666
-
667
-		$oldShare = $share;
668
-		$provider = $this->factory->getProviderForType($share->getShareType());
669
-		$share = $provider->create($share);
670
-		//reuse the node we already have
671
-		$share->setNode($oldShare->getNode());
672
-
673
-		// Post share event
674
-		$event = new GenericEvent($share);
675
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
676
-
677
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
678
-			$mailSend = $share->getMailSend();
679
-			if($mailSend === true) {
680
-				$user = $this->userManager->get($share->getSharedWith());
681
-				if ($user !== null) {
682
-					$emailAddress = $user->getEMailAddress();
683
-					if ($emailAddress !== null && $emailAddress !== '') {
684
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
685
-						$l = $this->l10nFactory->get('lib', $userLang);
686
-						$this->sendMailNotification(
687
-							$l,
688
-							$share->getNode()->getName(),
689
-							$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
690
-							$share->getSharedBy(),
691
-							$emailAddress,
692
-							$share->getExpirationDate()
693
-						);
694
-						$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
695
-					} else {
696
-						$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
697
-					}
698
-				} else {
699
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
700
-				}
701
-			} else {
702
-				$this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
703
-			}
704
-		}
705
-
706
-		return $share;
707
-	}
708
-
709
-	/**
710
-	 * @param IL10N $l Language of the recipient
711
-	 * @param string $filename file/folder name
712
-	 * @param string $link link to the file/folder
713
-	 * @param string $initiator user ID of share sender
714
-	 * @param string $shareWith email address of share receiver
715
-	 * @param \DateTime|null $expiration
716
-	 * @throws \Exception If mail couldn't be sent
717
-	 */
718
-	protected function sendMailNotification(IL10N $l,
719
-											$filename,
720
-											$link,
721
-											$initiator,
722
-											$shareWith,
723
-											\DateTime $expiration = null) {
724
-		$initiatorUser = $this->userManager->get($initiator);
725
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
726
-
727
-		$message = $this->mailer->createMessage();
728
-
729
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
730
-			'filename' => $filename,
731
-			'link' => $link,
732
-			'initiator' => $initiatorDisplayName,
733
-			'expiration' => $expiration,
734
-			'shareWith' => $shareWith,
735
-		]);
736
-
737
-		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
738
-		$emailTemplate->addHeader();
739
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
740
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
741
-
742
-		$emailTemplate->addBodyText(
743
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
744
-			$text
745
-		);
746
-		$emailTemplate->addBodyButton(
747
-			$l->t('Open »%s«', [$filename]),
748
-			$link
749
-		);
750
-
751
-		$message->setTo([$shareWith]);
752
-
753
-		// The "From" contains the sharers name
754
-		$instanceName = $this->defaults->getName();
755
-		$senderName = $l->t(
756
-			'%s via %s',
757
-			[
758
-				$initiatorDisplayName,
759
-				$instanceName
760
-			]
761
-		);
762
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
763
-
764
-		// The "Reply-To" is set to the sharer if an mail address is configured
765
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
766
-		$initiatorEmail = $initiatorUser->getEMailAddress();
767
-		if($initiatorEmail !== null) {
768
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
769
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
770
-		} else {
771
-			$emailTemplate->addFooter();
772
-		}
773
-
774
-		$message->useTemplate($emailTemplate);
775
-		$this->mailer->send($message);
776
-	}
777
-
778
-	/**
779
-	 * Update a share
780
-	 *
781
-	 * @param \OCP\Share\IShare $share
782
-	 * @return \OCP\Share\IShare The share object
783
-	 * @throws \InvalidArgumentException
784
-	 */
785
-	public function updateShare(\OCP\Share\IShare $share) {
786
-		$expirationDateUpdated = false;
787
-
788
-		$this->canShare($share);
789
-
790
-		try {
791
-			$originalShare = $this->getShareById($share->getFullId());
792
-		} catch (\UnexpectedValueException $e) {
793
-			throw new \InvalidArgumentException('Share does not have a full id');
794
-		}
795
-
796
-		// We can't change the share type!
797
-		if ($share->getShareType() !== $originalShare->getShareType()) {
798
-			throw new \InvalidArgumentException('Can’t change share type');
799
-		}
800
-
801
-		// We can only change the recipient on user shares
802
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
803
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
804
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
805
-		}
806
-
807
-		// Cannot share with the owner
808
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
809
-			$share->getSharedWith() === $share->getShareOwner()) {
810
-			throw new \InvalidArgumentException('Can’t share with the share owner');
811
-		}
812
-
813
-		$this->generalCreateChecks($share);
814
-
815
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
816
-			$this->userCreateChecks($share);
817
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
818
-			$this->groupCreateChecks($share);
819
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
820
-			$this->linkCreateChecks($share);
821
-
822
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
823
-
824
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
825
-				//Verify the expiration date
826
-				$this->validateExpirationDate($share);
827
-				$expirationDateUpdated = true;
828
-			}
829
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
830
-			$plainTextPassword = $share->getPassword();
831
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
832
-				$plainTextPassword = null;
833
-			}
834
-		}
835
-
836
-		$this->pathCreateChecks($share->getNode());
837
-
838
-		// Now update the share!
839
-		$provider = $this->factory->getProviderForType($share->getShareType());
840
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
841
-			$share = $provider->update($share, $plainTextPassword);
842
-		} else {
843
-			$share = $provider->update($share);
844
-		}
845
-
846
-		if ($expirationDateUpdated === true) {
847
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
848
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
849
-				'itemSource' => $share->getNode()->getId(),
850
-				'date' => $share->getExpirationDate(),
851
-				'uidOwner' => $share->getSharedBy(),
852
-			]);
853
-		}
854
-
855
-		if ($share->getPassword() !== $originalShare->getPassword()) {
856
-			\OC_Hook::emit(Share::class, 'post_update_password', [
857
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
858
-				'itemSource' => $share->getNode()->getId(),
859
-				'uidOwner' => $share->getSharedBy(),
860
-				'token' => $share->getToken(),
861
-				'disabled' => is_null($share->getPassword()),
862
-			]);
863
-		}
864
-
865
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
866
-			if ($this->userManager->userExists($share->getShareOwner())) {
867
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
868
-			} else {
869
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
870
-			}
871
-			\OC_Hook::emit(Share::class, 'post_update_permissions', array(
872
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
873
-				'itemSource' => $share->getNode()->getId(),
874
-				'shareType' => $share->getShareType(),
875
-				'shareWith' => $share->getSharedWith(),
876
-				'uidOwner' => $share->getSharedBy(),
877
-				'permissions' => $share->getPermissions(),
878
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
879
-			));
880
-		}
881
-
882
-		return $share;
883
-	}
884
-
885
-	/**
886
-	 * Updates the password of the given share if it is not the same as the
887
-	 * password of the original share.
888
-	 *
889
-	 * @param \OCP\Share\IShare $share the share to update its password.
890
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
891
-	 *        password with.
892
-	 * @return boolean whether the password was updated or not.
893
-	 */
894
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
895
-		// Password updated.
896
-		if ($share->getPassword() !== $originalShare->getPassword()) {
897
-			//Verify the password
898
-			$this->verifyPassword($share->getPassword());
899
-
900
-			// If a password is set. Hash it!
901
-			if ($share->getPassword() !== null) {
902
-				$share->setPassword($this->hasher->hash($share->getPassword()));
903
-
904
-				return true;
905
-			}
906
-		}
907
-
908
-		return false;
909
-	}
910
-
911
-	/**
912
-	 * Delete all the children of this share
913
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
914
-	 *
915
-	 * @param \OCP\Share\IShare $share
916
-	 * @return \OCP\Share\IShare[] List of deleted shares
917
-	 */
918
-	protected function deleteChildren(\OCP\Share\IShare $share) {
919
-		$deletedShares = [];
920
-
921
-		$provider = $this->factory->getProviderForType($share->getShareType());
922
-
923
-		foreach ($provider->getChildren($share) as $child) {
924
-			$deletedChildren = $this->deleteChildren($child);
925
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
926
-
927
-			$provider->delete($child);
928
-			$deletedShares[] = $child;
929
-		}
930
-
931
-		return $deletedShares;
932
-	}
933
-
934
-	/**
935
-	 * Delete a share
936
-	 *
937
-	 * @param \OCP\Share\IShare $share
938
-	 * @throws ShareNotFound
939
-	 * @throws \InvalidArgumentException
940
-	 */
941
-	public function deleteShare(\OCP\Share\IShare $share) {
942
-
943
-		try {
944
-			$share->getFullId();
945
-		} catch (\UnexpectedValueException $e) {
946
-			throw new \InvalidArgumentException('Share does not have a full id');
947
-		}
948
-
949
-		$event = new GenericEvent($share);
950
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
951
-
952
-		// Get all children and delete them as well
953
-		$deletedShares = $this->deleteChildren($share);
954
-
955
-		// Do the actual delete
956
-		$provider = $this->factory->getProviderForType($share->getShareType());
957
-		$provider->delete($share);
958
-
959
-		// All the deleted shares caused by this delete
960
-		$deletedShares[] = $share;
961
-
962
-		// Emit post hook
963
-		$event->setArgument('deletedShares', $deletedShares);
964
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
965
-	}
966
-
967
-
968
-	/**
969
-	 * Unshare a file as the recipient.
970
-	 * This can be different from a regular delete for example when one of
971
-	 * the users in a groups deletes that share. But the provider should
972
-	 * handle this.
973
-	 *
974
-	 * @param \OCP\Share\IShare $share
975
-	 * @param string $recipientId
976
-	 */
977
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
978
-		list($providerId, ) = $this->splitFullId($share->getFullId());
979
-		$provider = $this->factory->getProvider($providerId);
980
-
981
-		$provider->deleteFromSelf($share, $recipientId);
982
-		$event = new GenericEvent($share);
983
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
984
-	}
985
-
986
-	public function restoreShare(IShare $share, string $recipientId): IShare {
987
-		list($providerId, ) = $this->splitFullId($share->getFullId());
988
-		$provider = $this->factory->getProvider($providerId);
989
-
990
-		return $provider->restore($share, $recipientId);
991
-	}
992
-
993
-	/**
994
-	 * @inheritdoc
995
-	 */
996
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
997
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
998
-			throw new \InvalidArgumentException('Can’t change target of link share');
999
-		}
1000
-
1001
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1002
-			throw new \InvalidArgumentException('Invalid recipient');
1003
-		}
1004
-
1005
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1006
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1007
-			if (is_null($sharedWith)) {
1008
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1009
-			}
1010
-			$recipient = $this->userManager->get($recipientId);
1011
-			if (!$sharedWith->inGroup($recipient)) {
1012
-				throw new \InvalidArgumentException('Invalid recipient');
1013
-			}
1014
-		}
1015
-
1016
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1017
-		$provider = $this->factory->getProvider($providerId);
1018
-
1019
-		$provider->move($share, $recipientId);
1020
-	}
1021
-
1022
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1023
-		$providers = $this->factory->getAllProviders();
1024
-
1025
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1026
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1027
-			foreach ($newShares as $fid => $data) {
1028
-				if (!isset($shares[$fid])) {
1029
-					$shares[$fid] = [];
1030
-				}
1031
-
1032
-				$shares[$fid] = array_merge($shares[$fid], $data);
1033
-			}
1034
-			return $shares;
1035
-		}, []);
1036
-	}
1037
-
1038
-	/**
1039
-	 * @inheritdoc
1040
-	 */
1041
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1042
-		if ($path !== null &&
1043
-				!($path instanceof \OCP\Files\File) &&
1044
-				!($path instanceof \OCP\Files\Folder)) {
1045
-			throw new \InvalidArgumentException('invalid path');
1046
-		}
1047
-
1048
-		try {
1049
-			$provider = $this->factory->getProviderForType($shareType);
1050
-		} catch (ProviderException $e) {
1051
-			return [];
1052
-		}
1053
-
1054
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1055
-
1056
-		/*
623
+            $share->setToken(
624
+                $this->secureRandom->generate(
625
+                    \OC\Share\Constants::TOKEN_LENGTH,
626
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
627
+                )
628
+            );
629
+
630
+            //Verify the expiration date
631
+            $this->validateExpirationDate($share);
632
+
633
+            //Verify the password
634
+            $this->verifyPassword($share->getPassword());
635
+
636
+            // If a password is set. Hash it!
637
+            if ($share->getPassword() !== null) {
638
+                $share->setPassword($this->hasher->hash($share->getPassword()));
639
+            }
640
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
641
+            $share->setToken(
642
+                $this->secureRandom->generate(
643
+                    \OC\Share\Constants::TOKEN_LENGTH,
644
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
645
+                )
646
+            );
647
+        }
648
+
649
+        // Cannot share with the owner
650
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
651
+            $share->getSharedWith() === $share->getShareOwner()) {
652
+            throw new \InvalidArgumentException('Can’t share with the share owner');
653
+        }
654
+
655
+        // Generate the target
656
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
657
+        $target = \OC\Files\Filesystem::normalizePath($target);
658
+        $share->setTarget($target);
659
+
660
+        // Pre share event
661
+        $event = new GenericEvent($share);
662
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
663
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
664
+            throw new \Exception($event->getArgument('error'));
665
+        }
666
+
667
+        $oldShare = $share;
668
+        $provider = $this->factory->getProviderForType($share->getShareType());
669
+        $share = $provider->create($share);
670
+        //reuse the node we already have
671
+        $share->setNode($oldShare->getNode());
672
+
673
+        // Post share event
674
+        $event = new GenericEvent($share);
675
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
676
+
677
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
678
+            $mailSend = $share->getMailSend();
679
+            if($mailSend === true) {
680
+                $user = $this->userManager->get($share->getSharedWith());
681
+                if ($user !== null) {
682
+                    $emailAddress = $user->getEMailAddress();
683
+                    if ($emailAddress !== null && $emailAddress !== '') {
684
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
685
+                        $l = $this->l10nFactory->get('lib', $userLang);
686
+                        $this->sendMailNotification(
687
+                            $l,
688
+                            $share->getNode()->getName(),
689
+                            $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
690
+                            $share->getSharedBy(),
691
+                            $emailAddress,
692
+                            $share->getExpirationDate()
693
+                        );
694
+                        $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
695
+                    } else {
696
+                        $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
697
+                    }
698
+                } else {
699
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
700
+                }
701
+            } else {
702
+                $this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
703
+            }
704
+        }
705
+
706
+        return $share;
707
+    }
708
+
709
+    /**
710
+     * @param IL10N $l Language of the recipient
711
+     * @param string $filename file/folder name
712
+     * @param string $link link to the file/folder
713
+     * @param string $initiator user ID of share sender
714
+     * @param string $shareWith email address of share receiver
715
+     * @param \DateTime|null $expiration
716
+     * @throws \Exception If mail couldn't be sent
717
+     */
718
+    protected function sendMailNotification(IL10N $l,
719
+                                            $filename,
720
+                                            $link,
721
+                                            $initiator,
722
+                                            $shareWith,
723
+                                            \DateTime $expiration = null) {
724
+        $initiatorUser = $this->userManager->get($initiator);
725
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
726
+
727
+        $message = $this->mailer->createMessage();
728
+
729
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
730
+            'filename' => $filename,
731
+            'link' => $link,
732
+            'initiator' => $initiatorDisplayName,
733
+            'expiration' => $expiration,
734
+            'shareWith' => $shareWith,
735
+        ]);
736
+
737
+        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
738
+        $emailTemplate->addHeader();
739
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
740
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
741
+
742
+        $emailTemplate->addBodyText(
743
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
744
+            $text
745
+        );
746
+        $emailTemplate->addBodyButton(
747
+            $l->t('Open »%s«', [$filename]),
748
+            $link
749
+        );
750
+
751
+        $message->setTo([$shareWith]);
752
+
753
+        // The "From" contains the sharers name
754
+        $instanceName = $this->defaults->getName();
755
+        $senderName = $l->t(
756
+            '%s via %s',
757
+            [
758
+                $initiatorDisplayName,
759
+                $instanceName
760
+            ]
761
+        );
762
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
763
+
764
+        // The "Reply-To" is set to the sharer if an mail address is configured
765
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
766
+        $initiatorEmail = $initiatorUser->getEMailAddress();
767
+        if($initiatorEmail !== null) {
768
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
769
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
770
+        } else {
771
+            $emailTemplate->addFooter();
772
+        }
773
+
774
+        $message->useTemplate($emailTemplate);
775
+        $this->mailer->send($message);
776
+    }
777
+
778
+    /**
779
+     * Update a share
780
+     *
781
+     * @param \OCP\Share\IShare $share
782
+     * @return \OCP\Share\IShare The share object
783
+     * @throws \InvalidArgumentException
784
+     */
785
+    public function updateShare(\OCP\Share\IShare $share) {
786
+        $expirationDateUpdated = false;
787
+
788
+        $this->canShare($share);
789
+
790
+        try {
791
+            $originalShare = $this->getShareById($share->getFullId());
792
+        } catch (\UnexpectedValueException $e) {
793
+            throw new \InvalidArgumentException('Share does not have a full id');
794
+        }
795
+
796
+        // We can't change the share type!
797
+        if ($share->getShareType() !== $originalShare->getShareType()) {
798
+            throw new \InvalidArgumentException('Can’t change share type');
799
+        }
800
+
801
+        // We can only change the recipient on user shares
802
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
803
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
804
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
805
+        }
806
+
807
+        // Cannot share with the owner
808
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
809
+            $share->getSharedWith() === $share->getShareOwner()) {
810
+            throw new \InvalidArgumentException('Can’t share with the share owner');
811
+        }
812
+
813
+        $this->generalCreateChecks($share);
814
+
815
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
816
+            $this->userCreateChecks($share);
817
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
818
+            $this->groupCreateChecks($share);
819
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
820
+            $this->linkCreateChecks($share);
821
+
822
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
823
+
824
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
825
+                //Verify the expiration date
826
+                $this->validateExpirationDate($share);
827
+                $expirationDateUpdated = true;
828
+            }
829
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
830
+            $plainTextPassword = $share->getPassword();
831
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
832
+                $plainTextPassword = null;
833
+            }
834
+        }
835
+
836
+        $this->pathCreateChecks($share->getNode());
837
+
838
+        // Now update the share!
839
+        $provider = $this->factory->getProviderForType($share->getShareType());
840
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
841
+            $share = $provider->update($share, $plainTextPassword);
842
+        } else {
843
+            $share = $provider->update($share);
844
+        }
845
+
846
+        if ($expirationDateUpdated === true) {
847
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
848
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
849
+                'itemSource' => $share->getNode()->getId(),
850
+                'date' => $share->getExpirationDate(),
851
+                'uidOwner' => $share->getSharedBy(),
852
+            ]);
853
+        }
854
+
855
+        if ($share->getPassword() !== $originalShare->getPassword()) {
856
+            \OC_Hook::emit(Share::class, 'post_update_password', [
857
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
858
+                'itemSource' => $share->getNode()->getId(),
859
+                'uidOwner' => $share->getSharedBy(),
860
+                'token' => $share->getToken(),
861
+                'disabled' => is_null($share->getPassword()),
862
+            ]);
863
+        }
864
+
865
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
866
+            if ($this->userManager->userExists($share->getShareOwner())) {
867
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
868
+            } else {
869
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
870
+            }
871
+            \OC_Hook::emit(Share::class, 'post_update_permissions', array(
872
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
873
+                'itemSource' => $share->getNode()->getId(),
874
+                'shareType' => $share->getShareType(),
875
+                'shareWith' => $share->getSharedWith(),
876
+                'uidOwner' => $share->getSharedBy(),
877
+                'permissions' => $share->getPermissions(),
878
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
879
+            ));
880
+        }
881
+
882
+        return $share;
883
+    }
884
+
885
+    /**
886
+     * Updates the password of the given share if it is not the same as the
887
+     * password of the original share.
888
+     *
889
+     * @param \OCP\Share\IShare $share the share to update its password.
890
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
891
+     *        password with.
892
+     * @return boolean whether the password was updated or not.
893
+     */
894
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
895
+        // Password updated.
896
+        if ($share->getPassword() !== $originalShare->getPassword()) {
897
+            //Verify the password
898
+            $this->verifyPassword($share->getPassword());
899
+
900
+            // If a password is set. Hash it!
901
+            if ($share->getPassword() !== null) {
902
+                $share->setPassword($this->hasher->hash($share->getPassword()));
903
+
904
+                return true;
905
+            }
906
+        }
907
+
908
+        return false;
909
+    }
910
+
911
+    /**
912
+     * Delete all the children of this share
913
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
914
+     *
915
+     * @param \OCP\Share\IShare $share
916
+     * @return \OCP\Share\IShare[] List of deleted shares
917
+     */
918
+    protected function deleteChildren(\OCP\Share\IShare $share) {
919
+        $deletedShares = [];
920
+
921
+        $provider = $this->factory->getProviderForType($share->getShareType());
922
+
923
+        foreach ($provider->getChildren($share) as $child) {
924
+            $deletedChildren = $this->deleteChildren($child);
925
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
926
+
927
+            $provider->delete($child);
928
+            $deletedShares[] = $child;
929
+        }
930
+
931
+        return $deletedShares;
932
+    }
933
+
934
+    /**
935
+     * Delete a share
936
+     *
937
+     * @param \OCP\Share\IShare $share
938
+     * @throws ShareNotFound
939
+     * @throws \InvalidArgumentException
940
+     */
941
+    public function deleteShare(\OCP\Share\IShare $share) {
942
+
943
+        try {
944
+            $share->getFullId();
945
+        } catch (\UnexpectedValueException $e) {
946
+            throw new \InvalidArgumentException('Share does not have a full id');
947
+        }
948
+
949
+        $event = new GenericEvent($share);
950
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
951
+
952
+        // Get all children and delete them as well
953
+        $deletedShares = $this->deleteChildren($share);
954
+
955
+        // Do the actual delete
956
+        $provider = $this->factory->getProviderForType($share->getShareType());
957
+        $provider->delete($share);
958
+
959
+        // All the deleted shares caused by this delete
960
+        $deletedShares[] = $share;
961
+
962
+        // Emit post hook
963
+        $event->setArgument('deletedShares', $deletedShares);
964
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
965
+    }
966
+
967
+
968
+    /**
969
+     * Unshare a file as the recipient.
970
+     * This can be different from a regular delete for example when one of
971
+     * the users in a groups deletes that share. But the provider should
972
+     * handle this.
973
+     *
974
+     * @param \OCP\Share\IShare $share
975
+     * @param string $recipientId
976
+     */
977
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
978
+        list($providerId, ) = $this->splitFullId($share->getFullId());
979
+        $provider = $this->factory->getProvider($providerId);
980
+
981
+        $provider->deleteFromSelf($share, $recipientId);
982
+        $event = new GenericEvent($share);
983
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
984
+    }
985
+
986
+    public function restoreShare(IShare $share, string $recipientId): IShare {
987
+        list($providerId, ) = $this->splitFullId($share->getFullId());
988
+        $provider = $this->factory->getProvider($providerId);
989
+
990
+        return $provider->restore($share, $recipientId);
991
+    }
992
+
993
+    /**
994
+     * @inheritdoc
995
+     */
996
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
997
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
998
+            throw new \InvalidArgumentException('Can’t change target of link share');
999
+        }
1000
+
1001
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1002
+            throw new \InvalidArgumentException('Invalid recipient');
1003
+        }
1004
+
1005
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1006
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1007
+            if (is_null($sharedWith)) {
1008
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1009
+            }
1010
+            $recipient = $this->userManager->get($recipientId);
1011
+            if (!$sharedWith->inGroup($recipient)) {
1012
+                throw new \InvalidArgumentException('Invalid recipient');
1013
+            }
1014
+        }
1015
+
1016
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1017
+        $provider = $this->factory->getProvider($providerId);
1018
+
1019
+        $provider->move($share, $recipientId);
1020
+    }
1021
+
1022
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1023
+        $providers = $this->factory->getAllProviders();
1024
+
1025
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1026
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1027
+            foreach ($newShares as $fid => $data) {
1028
+                if (!isset($shares[$fid])) {
1029
+                    $shares[$fid] = [];
1030
+                }
1031
+
1032
+                $shares[$fid] = array_merge($shares[$fid], $data);
1033
+            }
1034
+            return $shares;
1035
+        }, []);
1036
+    }
1037
+
1038
+    /**
1039
+     * @inheritdoc
1040
+     */
1041
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1042
+        if ($path !== null &&
1043
+                !($path instanceof \OCP\Files\File) &&
1044
+                !($path instanceof \OCP\Files\Folder)) {
1045
+            throw new \InvalidArgumentException('invalid path');
1046
+        }
1047
+
1048
+        try {
1049
+            $provider = $this->factory->getProviderForType($shareType);
1050
+        } catch (ProviderException $e) {
1051
+            return [];
1052
+        }
1053
+
1054
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1055
+
1056
+        /*
1057 1057
 		 * Work around so we don't return expired shares but still follow
1058 1058
 		 * proper pagination.
1059 1059
 		 */
1060 1060
 
1061
-		$shares2 = [];
1062
-
1063
-		while(true) {
1064
-			$added = 0;
1065
-			foreach ($shares as $share) {
1066
-
1067
-				try {
1068
-					$this->checkExpireDate($share);
1069
-				} catch (ShareNotFound $e) {
1070
-					//Ignore since this basically means the share is deleted
1071
-					continue;
1072
-				}
1073
-
1074
-				$added++;
1075
-				$shares2[] = $share;
1076
-
1077
-				if (count($shares2) === $limit) {
1078
-					break;
1079
-				}
1080
-			}
1081
-
1082
-			// If we did not fetch more shares than the limit then there are no more shares
1083
-			if (count($shares) < $limit) {
1084
-				break;
1085
-			}
1086
-
1087
-			if (count($shares2) === $limit) {
1088
-				break;
1089
-			}
1090
-
1091
-			// If there was no limit on the select we are done
1092
-			if ($limit === -1) {
1093
-				break;
1094
-			}
1095
-
1096
-			$offset += $added;
1097
-
1098
-			// Fetch again $limit shares
1099
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1100
-
1101
-			// No more shares means we are done
1102
-			if (empty($shares)) {
1103
-				break;
1104
-			}
1105
-		}
1106
-
1107
-		$shares = $shares2;
1108
-
1109
-		return $shares;
1110
-	}
1111
-
1112
-	/**
1113
-	 * @inheritdoc
1114
-	 */
1115
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1116
-		try {
1117
-			$provider = $this->factory->getProviderForType($shareType);
1118
-		} catch (ProviderException $e) {
1119
-			return [];
1120
-		}
1121
-
1122
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1123
-
1124
-		// remove all shares which are already expired
1125
-		foreach ($shares as $key => $share) {
1126
-			try {
1127
-				$this->checkExpireDate($share);
1128
-			} catch (ShareNotFound $e) {
1129
-				unset($shares[$key]);
1130
-			}
1131
-		}
1132
-
1133
-		return $shares;
1134
-	}
1135
-
1136
-	/**
1137
-	 * @inheritdoc
1138
-	 */
1139
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1140
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1141
-
1142
-		// Only get deleted shares
1143
-		$shares = array_filter($shares, function(IShare $share) {
1144
-			return $share->getPermissions() === 0;
1145
-		});
1146
-
1147
-		// Only get shares where the owner still exists
1148
-		$shares = array_filter($shares, function (IShare $share) {
1149
-			return $this->userManager->userExists($share->getShareOwner());
1150
-		});
1151
-
1152
-		return $shares;
1153
-	}
1154
-
1155
-	/**
1156
-	 * @inheritdoc
1157
-	 */
1158
-	public function getShareById($id, $recipient = null) {
1159
-		if ($id === null) {
1160
-			throw new ShareNotFound();
1161
-		}
1162
-
1163
-		list($providerId, $id) = $this->splitFullId($id);
1164
-
1165
-		try {
1166
-			$provider = $this->factory->getProvider($providerId);
1167
-		} catch (ProviderException $e) {
1168
-			throw new ShareNotFound();
1169
-		}
1170
-
1171
-		$share = $provider->getShareById($id, $recipient);
1172
-
1173
-		$this->checkExpireDate($share);
1174
-
1175
-		return $share;
1176
-	}
1177
-
1178
-	/**
1179
-	 * Get all the shares for a given path
1180
-	 *
1181
-	 * @param \OCP\Files\Node $path
1182
-	 * @param int $page
1183
-	 * @param int $perPage
1184
-	 *
1185
-	 * @return Share[]
1186
-	 */
1187
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1188
-		return [];
1189
-	}
1190
-
1191
-	/**
1192
-	 * Get the share by token possible with password
1193
-	 *
1194
-	 * @param string $token
1195
-	 * @return Share
1196
-	 *
1197
-	 * @throws ShareNotFound
1198
-	 */
1199
-	public function getShareByToken($token) {
1200
-		$share = null;
1201
-		try {
1202
-			if($this->shareApiAllowLinks()) {
1203
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1204
-				$share = $provider->getShareByToken($token);
1205
-			}
1206
-		} catch (ProviderException $e) {
1207
-		} catch (ShareNotFound $e) {
1208
-		}
1209
-
1210
-
1211
-		// If it is not a link share try to fetch a federated share by token
1212
-		if ($share === null) {
1213
-			try {
1214
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1215
-				$share = $provider->getShareByToken($token);
1216
-			} catch (ProviderException $e) {
1217
-			} catch (ShareNotFound $e) {
1218
-			}
1219
-		}
1220
-
1221
-		// If it is not a link share try to fetch a mail share by token
1222
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1223
-			try {
1224
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1225
-				$share = $provider->getShareByToken($token);
1226
-			} catch (ProviderException $e) {
1227
-			} catch (ShareNotFound $e) {
1228
-			}
1229
-		}
1230
-
1231
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1232
-			try {
1233
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1234
-				$share = $provider->getShareByToken($token);
1235
-			} catch (ProviderException $e) {
1236
-			} catch (ShareNotFound $e) {
1237
-			}
1238
-		}
1239
-
1240
-		if ($share === null) {
1241
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1242
-		}
1243
-
1244
-		$this->checkExpireDate($share);
1245
-
1246
-		/*
1061
+        $shares2 = [];
1062
+
1063
+        while(true) {
1064
+            $added = 0;
1065
+            foreach ($shares as $share) {
1066
+
1067
+                try {
1068
+                    $this->checkExpireDate($share);
1069
+                } catch (ShareNotFound $e) {
1070
+                    //Ignore since this basically means the share is deleted
1071
+                    continue;
1072
+                }
1073
+
1074
+                $added++;
1075
+                $shares2[] = $share;
1076
+
1077
+                if (count($shares2) === $limit) {
1078
+                    break;
1079
+                }
1080
+            }
1081
+
1082
+            // If we did not fetch more shares than the limit then there are no more shares
1083
+            if (count($shares) < $limit) {
1084
+                break;
1085
+            }
1086
+
1087
+            if (count($shares2) === $limit) {
1088
+                break;
1089
+            }
1090
+
1091
+            // If there was no limit on the select we are done
1092
+            if ($limit === -1) {
1093
+                break;
1094
+            }
1095
+
1096
+            $offset += $added;
1097
+
1098
+            // Fetch again $limit shares
1099
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1100
+
1101
+            // No more shares means we are done
1102
+            if (empty($shares)) {
1103
+                break;
1104
+            }
1105
+        }
1106
+
1107
+        $shares = $shares2;
1108
+
1109
+        return $shares;
1110
+    }
1111
+
1112
+    /**
1113
+     * @inheritdoc
1114
+     */
1115
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1116
+        try {
1117
+            $provider = $this->factory->getProviderForType($shareType);
1118
+        } catch (ProviderException $e) {
1119
+            return [];
1120
+        }
1121
+
1122
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1123
+
1124
+        // remove all shares which are already expired
1125
+        foreach ($shares as $key => $share) {
1126
+            try {
1127
+                $this->checkExpireDate($share);
1128
+            } catch (ShareNotFound $e) {
1129
+                unset($shares[$key]);
1130
+            }
1131
+        }
1132
+
1133
+        return $shares;
1134
+    }
1135
+
1136
+    /**
1137
+     * @inheritdoc
1138
+     */
1139
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1140
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1141
+
1142
+        // Only get deleted shares
1143
+        $shares = array_filter($shares, function(IShare $share) {
1144
+            return $share->getPermissions() === 0;
1145
+        });
1146
+
1147
+        // Only get shares where the owner still exists
1148
+        $shares = array_filter($shares, function (IShare $share) {
1149
+            return $this->userManager->userExists($share->getShareOwner());
1150
+        });
1151
+
1152
+        return $shares;
1153
+    }
1154
+
1155
+    /**
1156
+     * @inheritdoc
1157
+     */
1158
+    public function getShareById($id, $recipient = null) {
1159
+        if ($id === null) {
1160
+            throw new ShareNotFound();
1161
+        }
1162
+
1163
+        list($providerId, $id) = $this->splitFullId($id);
1164
+
1165
+        try {
1166
+            $provider = $this->factory->getProvider($providerId);
1167
+        } catch (ProviderException $e) {
1168
+            throw new ShareNotFound();
1169
+        }
1170
+
1171
+        $share = $provider->getShareById($id, $recipient);
1172
+
1173
+        $this->checkExpireDate($share);
1174
+
1175
+        return $share;
1176
+    }
1177
+
1178
+    /**
1179
+     * Get all the shares for a given path
1180
+     *
1181
+     * @param \OCP\Files\Node $path
1182
+     * @param int $page
1183
+     * @param int $perPage
1184
+     *
1185
+     * @return Share[]
1186
+     */
1187
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1188
+        return [];
1189
+    }
1190
+
1191
+    /**
1192
+     * Get the share by token possible with password
1193
+     *
1194
+     * @param string $token
1195
+     * @return Share
1196
+     *
1197
+     * @throws ShareNotFound
1198
+     */
1199
+    public function getShareByToken($token) {
1200
+        $share = null;
1201
+        try {
1202
+            if($this->shareApiAllowLinks()) {
1203
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1204
+                $share = $provider->getShareByToken($token);
1205
+            }
1206
+        } catch (ProviderException $e) {
1207
+        } catch (ShareNotFound $e) {
1208
+        }
1209
+
1210
+
1211
+        // If it is not a link share try to fetch a federated share by token
1212
+        if ($share === null) {
1213
+            try {
1214
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1215
+                $share = $provider->getShareByToken($token);
1216
+            } catch (ProviderException $e) {
1217
+            } catch (ShareNotFound $e) {
1218
+            }
1219
+        }
1220
+
1221
+        // If it is not a link share try to fetch a mail share by token
1222
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1223
+            try {
1224
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1225
+                $share = $provider->getShareByToken($token);
1226
+            } catch (ProviderException $e) {
1227
+            } catch (ShareNotFound $e) {
1228
+            }
1229
+        }
1230
+
1231
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1232
+            try {
1233
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1234
+                $share = $provider->getShareByToken($token);
1235
+            } catch (ProviderException $e) {
1236
+            } catch (ShareNotFound $e) {
1237
+            }
1238
+        }
1239
+
1240
+        if ($share === null) {
1241
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1242
+        }
1243
+
1244
+        $this->checkExpireDate($share);
1245
+
1246
+        /*
1247 1247
 		 * Reduce the permissions for link shares if public upload is not enabled
1248 1248
 		 */
1249
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1250
-			!$this->shareApiLinkAllowPublicUpload()) {
1251
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1252
-		}
1253
-
1254
-		return $share;
1255
-	}
1256
-
1257
-	protected function checkExpireDate($share) {
1258
-		if ($share->getExpirationDate() !== null &&
1259
-			$share->getExpirationDate() <= new \DateTime()) {
1260
-			$this->deleteShare($share);
1261
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1262
-		}
1263
-
1264
-	}
1265
-
1266
-	/**
1267
-	 * Verify the password of a public share
1268
-	 *
1269
-	 * @param \OCP\Share\IShare $share
1270
-	 * @param string $password
1271
-	 * @return bool
1272
-	 */
1273
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1274
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1275
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1276
-		if (!$passwordProtected) {
1277
-			//TODO maybe exception?
1278
-			return false;
1279
-		}
1280
-
1281
-		if ($password === null || $share->getPassword() === null) {
1282
-			return false;
1283
-		}
1284
-
1285
-		$newHash = '';
1286
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1287
-			return false;
1288
-		}
1289
-
1290
-		if (!empty($newHash)) {
1291
-			$share->setPassword($newHash);
1292
-			$provider = $this->factory->getProviderForType($share->getShareType());
1293
-			$provider->update($share);
1294
-		}
1295
-
1296
-		return true;
1297
-	}
1298
-
1299
-	/**
1300
-	 * @inheritdoc
1301
-	 */
1302
-	public function userDeleted($uid) {
1303
-		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1304
-
1305
-		foreach ($types as $type) {
1306
-			try {
1307
-				$provider = $this->factory->getProviderForType($type);
1308
-			} catch (ProviderException $e) {
1309
-				continue;
1310
-			}
1311
-			$provider->userDeleted($uid, $type);
1312
-		}
1313
-	}
1314
-
1315
-	/**
1316
-	 * @inheritdoc
1317
-	 */
1318
-	public function groupDeleted($gid) {
1319
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1320
-		$provider->groupDeleted($gid);
1321
-	}
1322
-
1323
-	/**
1324
-	 * @inheritdoc
1325
-	 */
1326
-	public function userDeletedFromGroup($uid, $gid) {
1327
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1328
-		$provider->userDeletedFromGroup($uid, $gid);
1329
-	}
1330
-
1331
-	/**
1332
-	 * Get access list to a path. This means
1333
-	 * all the users that can access a given path.
1334
-	 *
1335
-	 * Consider:
1336
-	 * -root
1337
-	 * |-folder1 (23)
1338
-	 *  |-folder2 (32)
1339
-	 *   |-fileA (42)
1340
-	 *
1341
-	 * fileA is shared with user1 and user1@server1
1342
-	 * folder2 is shared with group2 (user4 is a member of group2)
1343
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1344
-	 *
1345
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1346
-	 * [
1347
-	 *  users  => [
1348
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1349
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1350
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1351
-	 *  ],
1352
-	 *  remote => [
1353
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1354
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1355
-	 *  ],
1356
-	 *  public => bool
1357
-	 *  mail => bool
1358
-	 * ]
1359
-	 *
1360
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1361
-	 * [
1362
-	 *  users  => ['user1', 'user2', 'user4'],
1363
-	 *  remote => bool,
1364
-	 *  public => bool
1365
-	 *  mail => bool
1366
-	 * ]
1367
-	 *
1368
-	 * This is required for encryption/activity
1369
-	 *
1370
-	 * @param \OCP\Files\Node $path
1371
-	 * @param bool $recursive Should we check all parent folders as well
1372
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1373
-	 * @return array
1374
-	 */
1375
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1376
-		$owner = $path->getOwner()->getUID();
1377
-
1378
-		if ($currentAccess) {
1379
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1380
-		} else {
1381
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1382
-		}
1383
-		if (!$this->userManager->userExists($owner)) {
1384
-			return $al;
1385
-		}
1386
-
1387
-		//Get node for the owner
1388
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1389
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1390
-			$path = $userFolder->getById($path->getId())[0];
1391
-		}
1392
-
1393
-		$providers = $this->factory->getAllProviders();
1394
-
1395
-		/** @var Node[] $nodes */
1396
-		$nodes = [];
1397
-
1398
-
1399
-		if ($currentAccess) {
1400
-			$ownerPath = $path->getPath();
1401
-			$ownerPath = explode('/', $ownerPath, 4);
1402
-			if (count($ownerPath) < 4) {
1403
-				$ownerPath = '';
1404
-			} else {
1405
-				$ownerPath = $ownerPath[3];
1406
-			}
1407
-			$al['users'][$owner] = [
1408
-				'node_id' => $path->getId(),
1409
-				'node_path' => '/' . $ownerPath,
1410
-			];
1411
-		} else {
1412
-			$al['users'][] = $owner;
1413
-		}
1414
-
1415
-		// Collect all the shares
1416
-		while ($path->getPath() !== $userFolder->getPath()) {
1417
-			$nodes[] = $path;
1418
-			if (!$recursive) {
1419
-				break;
1420
-			}
1421
-			$path = $path->getParent();
1422
-		}
1423
-
1424
-		foreach ($providers as $provider) {
1425
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1426
-
1427
-			foreach ($tmp as $k => $v) {
1428
-				if (isset($al[$k])) {
1429
-					if (is_array($al[$k])) {
1430
-						if ($currentAccess) {
1431
-							$al[$k] += $v;
1432
-						} else {
1433
-							$al[$k] = array_merge($al[$k], $v);
1434
-							$al[$k] = array_unique($al[$k]);
1435
-							$al[$k] = array_values($al[$k]);
1436
-						}
1437
-					} else {
1438
-						$al[$k] = $al[$k] || $v;
1439
-					}
1440
-				} else {
1441
-					$al[$k] = $v;
1442
-				}
1443
-			}
1444
-		}
1445
-
1446
-		return $al;
1447
-	}
1448
-
1449
-	/**
1450
-	 * Create a new share
1451
-	 * @return \OCP\Share\IShare
1452
-	 */
1453
-	public function newShare() {
1454
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1455
-	}
1456
-
1457
-	/**
1458
-	 * Is the share API enabled
1459
-	 *
1460
-	 * @return bool
1461
-	 */
1462
-	public function shareApiEnabled() {
1463
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1464
-	}
1465
-
1466
-	/**
1467
-	 * Is public link sharing enabled
1468
-	 *
1469
-	 * @return bool
1470
-	 */
1471
-	public function shareApiAllowLinks() {
1472
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1473
-	}
1474
-
1475
-	/**
1476
-	 * Is password on public link requires
1477
-	 *
1478
-	 * @return bool
1479
-	 */
1480
-	public function shareApiLinkEnforcePassword() {
1481
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1482
-	}
1483
-
1484
-	/**
1485
-	 * Is default expire date enabled
1486
-	 *
1487
-	 * @return bool
1488
-	 */
1489
-	public function shareApiLinkDefaultExpireDate() {
1490
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1491
-	}
1492
-
1493
-	/**
1494
-	 * Is default expire date enforced
1495
-	 *`
1496
-	 * @return bool
1497
-	 */
1498
-	public function shareApiLinkDefaultExpireDateEnforced() {
1499
-		return $this->shareApiLinkDefaultExpireDate() &&
1500
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1501
-	}
1502
-
1503
-	/**
1504
-	 * Number of default expire days
1505
-	 *shareApiLinkAllowPublicUpload
1506
-	 * @return int
1507
-	 */
1508
-	public function shareApiLinkDefaultExpireDays() {
1509
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1510
-	}
1511
-
1512
-	/**
1513
-	 * Allow public upload on link shares
1514
-	 *
1515
-	 * @return bool
1516
-	 */
1517
-	public function shareApiLinkAllowPublicUpload() {
1518
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1519
-	}
1520
-
1521
-	/**
1522
-	 * check if user can only share with group members
1523
-	 * @return bool
1524
-	 */
1525
-	public function shareWithGroupMembersOnly() {
1526
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1527
-	}
1528
-
1529
-	/**
1530
-	 * Check if users can share with groups
1531
-	 * @return bool
1532
-	 */
1533
-	public function allowGroupSharing() {
1534
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1535
-	}
1536
-
1537
-	/**
1538
-	 * Copied from \OC_Util::isSharingDisabledForUser
1539
-	 *
1540
-	 * TODO: Deprecate fuction from OC_Util
1541
-	 *
1542
-	 * @param string $userId
1543
-	 * @return bool
1544
-	 */
1545
-	public function sharingDisabledForUser($userId) {
1546
-		if ($userId === null) {
1547
-			return false;
1548
-		}
1549
-
1550
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1551
-			return $this->sharingDisabledForUsersCache[$userId];
1552
-		}
1553
-
1554
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1555
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1556
-			$excludedGroups = json_decode($groupsList);
1557
-			if (is_null($excludedGroups)) {
1558
-				$excludedGroups = explode(',', $groupsList);
1559
-				$newValue = json_encode($excludedGroups);
1560
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1561
-			}
1562
-			$user = $this->userManager->get($userId);
1563
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1564
-			if (!empty($usersGroups)) {
1565
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1566
-				// if the user is only in groups which are disabled for sharing then
1567
-				// sharing is also disabled for the user
1568
-				if (empty($remainingGroups)) {
1569
-					$this->sharingDisabledForUsersCache[$userId] = true;
1570
-					return true;
1571
-				}
1572
-			}
1573
-		}
1574
-
1575
-		$this->sharingDisabledForUsersCache[$userId] = false;
1576
-		return false;
1577
-	}
1578
-
1579
-	/**
1580
-	 * @inheritdoc
1581
-	 */
1582
-	public function outgoingServer2ServerSharesAllowed() {
1583
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1584
-	}
1585
-
1586
-	/**
1587
-	 * @inheritdoc
1588
-	 */
1589
-	public function outgoingServer2ServerGroupSharesAllowed() {
1590
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1591
-	}
1592
-
1593
-	/**
1594
-	 * @inheritdoc
1595
-	 */
1596
-	public function shareProviderExists($shareType) {
1597
-		try {
1598
-			$this->factory->getProviderForType($shareType);
1599
-		} catch (ProviderException $e) {
1600
-			return false;
1601
-		}
1602
-
1603
-		return true;
1604
-	}
1249
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1250
+            !$this->shareApiLinkAllowPublicUpload()) {
1251
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1252
+        }
1253
+
1254
+        return $share;
1255
+    }
1256
+
1257
+    protected function checkExpireDate($share) {
1258
+        if ($share->getExpirationDate() !== null &&
1259
+            $share->getExpirationDate() <= new \DateTime()) {
1260
+            $this->deleteShare($share);
1261
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1262
+        }
1263
+
1264
+    }
1265
+
1266
+    /**
1267
+     * Verify the password of a public share
1268
+     *
1269
+     * @param \OCP\Share\IShare $share
1270
+     * @param string $password
1271
+     * @return bool
1272
+     */
1273
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1274
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1275
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1276
+        if (!$passwordProtected) {
1277
+            //TODO maybe exception?
1278
+            return false;
1279
+        }
1280
+
1281
+        if ($password === null || $share->getPassword() === null) {
1282
+            return false;
1283
+        }
1284
+
1285
+        $newHash = '';
1286
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1287
+            return false;
1288
+        }
1289
+
1290
+        if (!empty($newHash)) {
1291
+            $share->setPassword($newHash);
1292
+            $provider = $this->factory->getProviderForType($share->getShareType());
1293
+            $provider->update($share);
1294
+        }
1295
+
1296
+        return true;
1297
+    }
1298
+
1299
+    /**
1300
+     * @inheritdoc
1301
+     */
1302
+    public function userDeleted($uid) {
1303
+        $types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE, \OCP\Share::SHARE_TYPE_EMAIL];
1304
+
1305
+        foreach ($types as $type) {
1306
+            try {
1307
+                $provider = $this->factory->getProviderForType($type);
1308
+            } catch (ProviderException $e) {
1309
+                continue;
1310
+            }
1311
+            $provider->userDeleted($uid, $type);
1312
+        }
1313
+    }
1314
+
1315
+    /**
1316
+     * @inheritdoc
1317
+     */
1318
+    public function groupDeleted($gid) {
1319
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1320
+        $provider->groupDeleted($gid);
1321
+    }
1322
+
1323
+    /**
1324
+     * @inheritdoc
1325
+     */
1326
+    public function userDeletedFromGroup($uid, $gid) {
1327
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1328
+        $provider->userDeletedFromGroup($uid, $gid);
1329
+    }
1330
+
1331
+    /**
1332
+     * Get access list to a path. This means
1333
+     * all the users that can access a given path.
1334
+     *
1335
+     * Consider:
1336
+     * -root
1337
+     * |-folder1 (23)
1338
+     *  |-folder2 (32)
1339
+     *   |-fileA (42)
1340
+     *
1341
+     * fileA is shared with user1 and user1@server1
1342
+     * folder2 is shared with group2 (user4 is a member of group2)
1343
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1344
+     *
1345
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1346
+     * [
1347
+     *  users  => [
1348
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1349
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1350
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1351
+     *  ],
1352
+     *  remote => [
1353
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1354
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1355
+     *  ],
1356
+     *  public => bool
1357
+     *  mail => bool
1358
+     * ]
1359
+     *
1360
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1361
+     * [
1362
+     *  users  => ['user1', 'user2', 'user4'],
1363
+     *  remote => bool,
1364
+     *  public => bool
1365
+     *  mail => bool
1366
+     * ]
1367
+     *
1368
+     * This is required for encryption/activity
1369
+     *
1370
+     * @param \OCP\Files\Node $path
1371
+     * @param bool $recursive Should we check all parent folders as well
1372
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1373
+     * @return array
1374
+     */
1375
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1376
+        $owner = $path->getOwner()->getUID();
1377
+
1378
+        if ($currentAccess) {
1379
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1380
+        } else {
1381
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1382
+        }
1383
+        if (!$this->userManager->userExists($owner)) {
1384
+            return $al;
1385
+        }
1386
+
1387
+        //Get node for the owner
1388
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1389
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1390
+            $path = $userFolder->getById($path->getId())[0];
1391
+        }
1392
+
1393
+        $providers = $this->factory->getAllProviders();
1394
+
1395
+        /** @var Node[] $nodes */
1396
+        $nodes = [];
1397
+
1398
+
1399
+        if ($currentAccess) {
1400
+            $ownerPath = $path->getPath();
1401
+            $ownerPath = explode('/', $ownerPath, 4);
1402
+            if (count($ownerPath) < 4) {
1403
+                $ownerPath = '';
1404
+            } else {
1405
+                $ownerPath = $ownerPath[3];
1406
+            }
1407
+            $al['users'][$owner] = [
1408
+                'node_id' => $path->getId(),
1409
+                'node_path' => '/' . $ownerPath,
1410
+            ];
1411
+        } else {
1412
+            $al['users'][] = $owner;
1413
+        }
1414
+
1415
+        // Collect all the shares
1416
+        while ($path->getPath() !== $userFolder->getPath()) {
1417
+            $nodes[] = $path;
1418
+            if (!$recursive) {
1419
+                break;
1420
+            }
1421
+            $path = $path->getParent();
1422
+        }
1423
+
1424
+        foreach ($providers as $provider) {
1425
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1426
+
1427
+            foreach ($tmp as $k => $v) {
1428
+                if (isset($al[$k])) {
1429
+                    if (is_array($al[$k])) {
1430
+                        if ($currentAccess) {
1431
+                            $al[$k] += $v;
1432
+                        } else {
1433
+                            $al[$k] = array_merge($al[$k], $v);
1434
+                            $al[$k] = array_unique($al[$k]);
1435
+                            $al[$k] = array_values($al[$k]);
1436
+                        }
1437
+                    } else {
1438
+                        $al[$k] = $al[$k] || $v;
1439
+                    }
1440
+                } else {
1441
+                    $al[$k] = $v;
1442
+                }
1443
+            }
1444
+        }
1445
+
1446
+        return $al;
1447
+    }
1448
+
1449
+    /**
1450
+     * Create a new share
1451
+     * @return \OCP\Share\IShare
1452
+     */
1453
+    public function newShare() {
1454
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1455
+    }
1456
+
1457
+    /**
1458
+     * Is the share API enabled
1459
+     *
1460
+     * @return bool
1461
+     */
1462
+    public function shareApiEnabled() {
1463
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1464
+    }
1465
+
1466
+    /**
1467
+     * Is public link sharing enabled
1468
+     *
1469
+     * @return bool
1470
+     */
1471
+    public function shareApiAllowLinks() {
1472
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1473
+    }
1474
+
1475
+    /**
1476
+     * Is password on public link requires
1477
+     *
1478
+     * @return bool
1479
+     */
1480
+    public function shareApiLinkEnforcePassword() {
1481
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1482
+    }
1483
+
1484
+    /**
1485
+     * Is default expire date enabled
1486
+     *
1487
+     * @return bool
1488
+     */
1489
+    public function shareApiLinkDefaultExpireDate() {
1490
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1491
+    }
1492
+
1493
+    /**
1494
+     * Is default expire date enforced
1495
+     *`
1496
+     * @return bool
1497
+     */
1498
+    public function shareApiLinkDefaultExpireDateEnforced() {
1499
+        return $this->shareApiLinkDefaultExpireDate() &&
1500
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1501
+    }
1502
+
1503
+    /**
1504
+     * Number of default expire days
1505
+     *shareApiLinkAllowPublicUpload
1506
+     * @return int
1507
+     */
1508
+    public function shareApiLinkDefaultExpireDays() {
1509
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1510
+    }
1511
+
1512
+    /**
1513
+     * Allow public upload on link shares
1514
+     *
1515
+     * @return bool
1516
+     */
1517
+    public function shareApiLinkAllowPublicUpload() {
1518
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1519
+    }
1520
+
1521
+    /**
1522
+     * check if user can only share with group members
1523
+     * @return bool
1524
+     */
1525
+    public function shareWithGroupMembersOnly() {
1526
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1527
+    }
1528
+
1529
+    /**
1530
+     * Check if users can share with groups
1531
+     * @return bool
1532
+     */
1533
+    public function allowGroupSharing() {
1534
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1535
+    }
1536
+
1537
+    /**
1538
+     * Copied from \OC_Util::isSharingDisabledForUser
1539
+     *
1540
+     * TODO: Deprecate fuction from OC_Util
1541
+     *
1542
+     * @param string $userId
1543
+     * @return bool
1544
+     */
1545
+    public function sharingDisabledForUser($userId) {
1546
+        if ($userId === null) {
1547
+            return false;
1548
+        }
1549
+
1550
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1551
+            return $this->sharingDisabledForUsersCache[$userId];
1552
+        }
1553
+
1554
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1555
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1556
+            $excludedGroups = json_decode($groupsList);
1557
+            if (is_null($excludedGroups)) {
1558
+                $excludedGroups = explode(',', $groupsList);
1559
+                $newValue = json_encode($excludedGroups);
1560
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1561
+            }
1562
+            $user = $this->userManager->get($userId);
1563
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1564
+            if (!empty($usersGroups)) {
1565
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1566
+                // if the user is only in groups which are disabled for sharing then
1567
+                // sharing is also disabled for the user
1568
+                if (empty($remainingGroups)) {
1569
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1570
+                    return true;
1571
+                }
1572
+            }
1573
+        }
1574
+
1575
+        $this->sharingDisabledForUsersCache[$userId] = false;
1576
+        return false;
1577
+    }
1578
+
1579
+    /**
1580
+     * @inheritdoc
1581
+     */
1582
+    public function outgoingServer2ServerSharesAllowed() {
1583
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1584
+    }
1585
+
1586
+    /**
1587
+     * @inheritdoc
1588
+     */
1589
+    public function outgoingServer2ServerGroupSharesAllowed() {
1590
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1591
+    }
1592
+
1593
+    /**
1594
+     * @inheritdoc
1595
+     */
1596
+    public function shareProviderExists($shareType) {
1597
+        try {
1598
+            $this->factory->getProviderForType($shareType);
1599
+        } catch (ProviderException $e) {
1600
+            return false;
1601
+        }
1602
+
1603
+        return true;
1604
+    }
1605 1605
 
1606 1606
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
 			if ($share->getSharedWith() === null) {
227 227
 				throw new \InvalidArgumentException('SharedWith should not be empty');
228 228
 			}
229
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
229
+		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230 230
 			if ($share->getSharedWith() === null) {
231 231
 				throw new \InvalidArgumentException('SharedWith should not be empty');
232 232
 			}
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 
362 362
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
363 363
 			$expirationDate = new \DateTime();
364
-			$expirationDate->setTime(0,0,0);
364
+			$expirationDate->setTime(0, 0, 0);
365 365
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
366 366
 		}
367 367
 
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 
374 374
 			$date = new \DateTime();
375 375
 			$date->setTime(0, 0, 0);
376
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
376
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
377 377
 			if ($date < $expirationDate) {
378 378
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
379 379
 				throw new GenericShareException($message, $message, 404);
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
 		 */
427 427
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
428 428
 		$existingShares = $provider->getSharesByPath($share->getNode());
429
-		foreach($existingShares as $existingShare) {
429
+		foreach ($existingShares as $existingShare) {
430 430
 			// Ignore if it is the same share
431 431
 			try {
432 432
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 		 */
484 484
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
485 485
 		$existingShares = $provider->getSharesByPath($share->getNode());
486
-		foreach($existingShares as $existingShare) {
486
+		foreach ($existingShares as $existingShare) {
487 487
 			try {
488 488
 				if ($existingShare->getFullId() === $share->getFullId()) {
489 489
 					continue;
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
 		// Make sure that we do not share a path that contains a shared mountpoint
553 553
 		if ($path instanceof \OCP\Files\Folder) {
554 554
 			$mounts = $this->mountManager->findIn($path->getPath());
555
-			foreach($mounts as $mount) {
555
+			foreach ($mounts as $mount) {
556 556
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
557 557
 					throw new \InvalidArgumentException('Path contains files shared with you');
558 558
 				}
@@ -600,7 +600,7 @@  discard block
 block discarded – undo
600 600
 		$storage = $share->getNode()->getStorage();
601 601
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
602 602
 			$parent = $share->getNode()->getParent();
603
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
603
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
604 604
 				$parent = $parent->getParent();
605 605
 			}
606 606
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
 		}
654 654
 
655 655
 		// Generate the target
656
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
656
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
657 657
 		$target = \OC\Files\Filesystem::normalizePath($target);
658 658
 		$share->setTarget($target);
659 659
 
@@ -676,7 +676,7 @@  discard block
 block discarded – undo
676 676
 
677 677
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
678 678
 			$mailSend = $share->getMailSend();
679
-			if($mailSend === true) {
679
+			if ($mailSend === true) {
680 680
 				$user = $this->userManager->get($share->getSharedWith());
681 681
 				if ($user !== null) {
682 682
 					$emailAddress = $user->getEMailAddress();
@@ -691,12 +691,12 @@  discard block
 block discarded – undo
691 691
 							$emailAddress,
692 692
 							$share->getExpirationDate()
693 693
 						);
694
-						$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
694
+						$this->logger->debug('Send share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']);
695 695
 					} else {
696
-						$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
696
+						$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']);
697 697
 					}
698 698
 				} else {
699
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
699
+					$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']);
700 700
 				}
701 701
 			} else {
702 702
 				$this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
@@ -740,7 +740,7 @@  discard block
 block discarded – undo
740 740
 		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
741 741
 
742 742
 		$emailTemplate->addBodyText(
743
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
743
+			htmlspecialchars($text.' '.$l->t('Click the button below to open it.')),
744 744
 			$text
745 745
 		);
746 746
 		$emailTemplate->addBodyButton(
@@ -764,9 +764,9 @@  discard block
 block discarded – undo
764 764
 		// The "Reply-To" is set to the sharer if an mail address is configured
765 765
 		// also the default footer contains a "Do not reply" which needs to be adjusted.
766 766
 		$initiatorEmail = $initiatorUser->getEMailAddress();
767
-		if($initiatorEmail !== null) {
767
+		if ($initiatorEmail !== null) {
768 768
 			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
769
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
769
+			$emailTemplate->addFooter($instanceName.($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : ''));
770 770
 		} else {
771 771
 			$emailTemplate->addFooter();
772 772
 		}
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
 	 * @param string $recipientId
976 976
 	 */
977 977
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
978
-		list($providerId, ) = $this->splitFullId($share->getFullId());
978
+		list($providerId,) = $this->splitFullId($share->getFullId());
979 979
 		$provider = $this->factory->getProvider($providerId);
980 980
 
981 981
 		$provider->deleteFromSelf($share, $recipientId);
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 	}
985 985
 
986 986
 	public function restoreShare(IShare $share, string $recipientId): IShare {
987
-		list($providerId, ) = $this->splitFullId($share->getFullId());
987
+		list($providerId,) = $this->splitFullId($share->getFullId());
988 988
 		$provider = $this->factory->getProvider($providerId);
989 989
 
990 990
 		return $provider->restore($share, $recipientId);
@@ -1005,7 +1005,7 @@  discard block
 block discarded – undo
1005 1005
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1006 1006
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
1007 1007
 			if (is_null($sharedWith)) {
1008
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1008
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
1009 1009
 			}
1010 1010
 			$recipient = $this->userManager->get($recipientId);
1011 1011
 			if (!$sharedWith->inGroup($recipient)) {
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
 			}
1014 1014
 		}
1015 1015
 
1016
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1016
+		list($providerId,) = $this->splitFullId($share->getFullId());
1017 1017
 		$provider = $this->factory->getProvider($providerId);
1018 1018
 
1019 1019
 		$provider->move($share, $recipientId);
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
 
1061 1061
 		$shares2 = [];
1062 1062
 
1063
-		while(true) {
1063
+		while (true) {
1064 1064
 			$added = 0;
1065 1065
 			foreach ($shares as $share) {
1066 1066
 
@@ -1145,7 +1145,7 @@  discard block
 block discarded – undo
1145 1145
 		});
1146 1146
 
1147 1147
 		// Only get shares where the owner still exists
1148
-		$shares = array_filter($shares, function (IShare $share) {
1148
+		$shares = array_filter($shares, function(IShare $share) {
1149 1149
 			return $this->userManager->userExists($share->getShareOwner());
1150 1150
 		});
1151 1151
 
@@ -1184,7 +1184,7 @@  discard block
 block discarded – undo
1184 1184
 	 *
1185 1185
 	 * @return Share[]
1186 1186
 	 */
1187
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1187
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1188 1188
 		return [];
1189 1189
 	}
1190 1190
 
@@ -1199,7 +1199,7 @@  discard block
 block discarded – undo
1199 1199
 	public function getShareByToken($token) {
1200 1200
 		$share = null;
1201 1201
 		try {
1202
-			if($this->shareApiAllowLinks()) {
1202
+			if ($this->shareApiAllowLinks()) {
1203 1203
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1204 1204
 				$share = $provider->getShareByToken($token);
1205 1205
 			}
@@ -1406,7 +1406,7 @@  discard block
 block discarded – undo
1406 1406
 			}
1407 1407
 			$al['users'][$owner] = [
1408 1408
 				'node_id' => $path->getId(),
1409
-				'node_path' => '/' . $ownerPath,
1409
+				'node_path' => '/'.$ownerPath,
1410 1410
 			];
1411 1411
 		} else {
1412 1412
 			$al['users'][] = $owner;
@@ -1506,7 +1506,7 @@  discard block
 block discarded – undo
1506 1506
 	 * @return int
1507 1507
 	 */
1508 1508
 	public function shareApiLinkDefaultExpireDays() {
1509
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1509
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1510 1510
 	}
1511 1511
 
1512 1512
 	/**
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -226,7 +226,7 @@
 block discarded – undo
226 226
 			if ($share->getSharedWith() === null) {
227 227
 				throw new \InvalidArgumentException('SharedWith should not be empty');
228 228
 			}
229
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
229
+		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230 230
 			if ($share->getSharedWith() === null) {
231 231
 				throw new \InvalidArgumentException('SharedWith should not be empty');
232 232
 			}
Please login to merge, or discard this patch.
lib/public/Share/IManager.php 1 patch
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -40,349 +40,349 @@
 block discarded – undo
40 40
  */
41 41
 interface IManager {
42 42
 
43
-	/**
44
-	 * Create a Share
45
-	 *
46
-	 * @param IShare $share
47
-	 * @return IShare The share object
48
-	 * @throws \Exception
49
-	 * @since 9.0.0
50
-	 */
51
-	public function createShare(IShare $share);
52
-
53
-	/**
54
-	 * Update a share.
55
-	 * The target of the share can't be changed this way: use moveShare
56
-	 * The share can't be removed this way (permission 0): use deleteShare
57
-	 *
58
-	 * @param IShare $share
59
-	 * @return IShare The share object
60
-	 * @throws \InvalidArgumentException
61
-	 * @since 9.0.0
62
-	 */
63
-	public function updateShare(IShare $share);
64
-
65
-	/**
66
-	 * Delete a share
67
-	 *
68
-	 * @param IShare $share
69
-	 * @throws ShareNotFound
70
-	 * @throws \InvalidArgumentException
71
-	 * @since 9.0.0
72
-	 */
73
-	public function deleteShare(IShare $share);
74
-
75
-	/**
76
-	 * Unshare a file as the recipient.
77
-	 * This can be different from a regular delete for example when one of
78
-	 * the users in a groups deletes that share. But the provider should
79
-	 * handle this.
80
-	 *
81
-	 * @param IShare $share
82
-	 * @param string $recipientId
83
-	 * @since 9.0.0
84
-	 */
85
-	public function deleteFromSelf(IShare $share, $recipientId);
86
-
87
-	/**
88
-	 * Restore the share when it has been deleted
89
-	 * Certain share types can be restored when they have been deleted
90
-	 * but the provider should properly handle this\
91
-	 *
92
-	 * @param IShare $share The share to restore
93
-	 * @param string $recipientId The user to restore the share for
94
-	 * @return IShare The restored share object
95
-	 * @throws GenericShareException In case restoring the share failed
96
-	 *
97
-	 * @since 14.0.0
98
-	 */
99
-	public function restoreShare(IShare $share, string $recipientId): IShare;
100
-
101
-	/**
102
-	 * Move the share as a recipient of the share.
103
-	 * This is updating the share target. So where the recipient has the share mounted.
104
-	 *
105
-	 * @param IShare $share
106
-	 * @param string $recipientId
107
-	 * @return IShare
108
-	 * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
109
-	 * @since 9.0.0
110
-	 */
111
-	public function moveShare(IShare $share, $recipientId);
112
-
113
-	/**
114
-	 * Get all shares shared by (initiated) by the provided user in a folder.
115
-	 *
116
-	 * @param string $userId
117
-	 * @param Folder $node
118
-	 * @param bool $reshares
119
-	 * @return IShare[][] [$fileId => IShare[], ...]
120
-	 * @since 11.0.0
121
-	 */
122
-	public function getSharesInFolder($userId, Folder $node, $reshares = false);
123
-
124
-	/**
125
-	 * Get shares shared by (initiated) by the provided user.
126
-	 *
127
-	 * @param string $userId
128
-	 * @param int $shareType
129
-	 * @param Node|null $path
130
-	 * @param bool $reshares
131
-	 * @param int $limit The maximum number of returned results, -1 for all results
132
-	 * @param int $offset
133
-	 * @return IShare[]
134
-	 * @since 9.0.0
135
-	 */
136
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
137
-
138
-	/**
139
-	 * Get shares shared with $user.
140
-	 * Filter by $node if provided
141
-	 *
142
-	 * @param string $userId
143
-	 * @param int $shareType
144
-	 * @param Node|null $node
145
-	 * @param int $limit The maximum number of shares returned, -1 for all
146
-	 * @param int $offset
147
-	 * @return IShare[]
148
-	 * @since 9.0.0
149
-	 */
150
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
151
-
152
-	/**
153
-	 * Get deleted shares shared with $user.
154
-	 * Filter by $node if provided
155
-	 *
156
-	 * @param string $userId
157
-	 * @param int $shareType
158
-	 * @param Node|null $node
159
-	 * @param int $limit The maximum number of shares returned, -1 for all
160
-	 * @param int $offset
161
-	 * @return IShare[]
162
-	 * @since 14.0.0
163
-	 */
164
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
165
-
166
-	/**
167
-	 * Retrieve a share by the share id.
168
-	 * If the recipient is set make sure to retrieve the file for that user.
169
-	 * This makes sure that if a user has moved/deleted a group share this
170
-	 * is reflected.
171
-	 *
172
-	 * @param string $id
173
-	 * @param string|null $recipient userID of the recipient
174
-	 * @return IShare
175
-	 * @throws ShareNotFound
176
-	 * @since 9.0.0
177
-	 */
178
-	public function getShareById($id, $recipient = null);
179
-
180
-	/**
181
-	 * Get the share by token possible with password
182
-	 *
183
-	 * @param string $token
184
-	 * @return IShare
185
-	 * @throws ShareNotFound
186
-	 * @since 9.0.0
187
-	 */
188
-	public function getShareByToken($token);
189
-
190
-	/**
191
-	 * Verify the password of a public share
192
-	 *
193
-	 * @param IShare $share
194
-	 * @param string $password
195
-	 * @return bool
196
-	 * @since 9.0.0
197
-	 */
198
-	public function checkPassword(IShare $share, $password);
199
-
200
-	/**
201
-	 * The user with UID is deleted.
202
-	 * All share providers have to cleanup the shares with this user as well
203
-	 * as shares owned by this user.
204
-	 * Shares only initiated by this user are fine.
205
-	 *
206
-	 * @param string $uid
207
-	 * @since 9.1.0
208
-	 */
209
-	public function userDeleted($uid);
210
-
211
-	/**
212
-	 * The group with $gid is deleted
213
-	 * We need to clear up all shares to this group
214
-	 *
215
-	 * @param string $gid
216
-	 * @since 9.1.0
217
-	 */
218
-	public function groupDeleted($gid);
219
-
220
-	/**
221
-	 * The user $uid is deleted from the group $gid
222
-	 * All user specific group shares have to be removed
223
-	 *
224
-	 * @param string $uid
225
-	 * @param string $gid
226
-	 * @since 9.1.0
227
-	 */
228
-	public function userDeletedFromGroup($uid, $gid);
229
-
230
-	/**
231
-	 * Get access list to a path. This means
232
-	 * all the users that can access a given path.
233
-	 *
234
-	 * Consider:
235
-	 * -root
236
-	 * |-folder1 (23)
237
-	 *  |-folder2 (32)
238
-	 *   |-fileA (42)
239
-	 *
240
-	 * fileA is shared with user1 and user1@server1
241
-	 * folder2 is shared with group2 (user4 is a member of group2)
242
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
243
-	 *
244
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
245
-	 * [
246
-	 *  users  => [
247
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
248
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
249
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
250
-	 *  ],
251
-	 *  remote => [
252
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
253
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
254
-	 *  ],
255
-	 *  public => bool
256
-	 *  mail => bool
257
-	 * ]
258
-	 *
259
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
260
-	 * [
261
-	 *  users  => ['user1', 'user2', 'user4'],
262
-	 *  remote => bool,
263
-	 *  public => bool
264
-	 *  mail => bool
265
-	 * ]
266
-	 *
267
-	 * This is required for encryption/activity
268
-	 *
269
-	 * @param \OCP\Files\Node $path
270
-	 * @param bool $recursive Should we check all parent folders as well
271
-	 * @param bool $currentAccess Should the user have currently access to the file
272
-	 * @return array
273
-	 * @since 12
274
-	 */
275
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
276
-
277
-	/**
278
-	 * Instantiates a new share object. This is to be passed to
279
-	 * createShare.
280
-	 *
281
-	 * @return IShare
282
-	 * @since 9.0.0
283
-	 */
284
-	public function newShare();
285
-
286
-	/**
287
-	 * Is the share API enabled
288
-	 *
289
-	 * @return bool
290
-	 * @since 9.0.0
291
-	 */
292
-	public function shareApiEnabled();
293
-
294
-	/**
295
-	 * Is public link sharing enabled
296
-	 *
297
-	 * @return bool
298
-	 * @since 9.0.0
299
-	 */
300
-	public function shareApiAllowLinks();
301
-
302
-	/**
303
-	 * Is password on public link requires
304
-	 *
305
-	 * @return bool
306
-	 * @since 9.0.0
307
-	 */
308
-	public function shareApiLinkEnforcePassword();
309
-
310
-	/**
311
-	 * Is default expire date enabled
312
-	 *
313
-	 * @return bool
314
-	 * @since 9.0.0
315
-	 */
316
-	public function shareApiLinkDefaultExpireDate();
317
-
318
-	/**
319
-	 * Is default expire date enforced
320
-	 *`
321
-	 * @return bool
322
-	 * @since 9.0.0
323
-	 */
324
-	public function shareApiLinkDefaultExpireDateEnforced();
325
-
326
-	/**
327
-	 * Number of default expire days
328
-	 *
329
-	 * @return int
330
-	 * @since 9.0.0
331
-	 */
332
-	public function shareApiLinkDefaultExpireDays();
333
-
334
-	/**
335
-	 * Allow public upload on link shares
336
-	 *
337
-	 * @return bool
338
-	 * @since 9.0.0
339
-	 */
340
-	public function shareApiLinkAllowPublicUpload();
341
-
342
-	/**
343
-	 * check if user can only share with group members
344
-	 * @return bool
345
-	 * @since 9.0.0
346
-	 */
347
-	public function shareWithGroupMembersOnly();
348
-
349
-	/**
350
-	 * Check if users can share with groups
351
-	 * @return bool
352
-	 * @since 9.0.1
353
-	 */
354
-	public function allowGroupSharing();
355
-
356
-	/**
357
-	 * Check if sharing is disabled for the given user
358
-	 *
359
-	 * @param string $userId
360
-	 * @return bool
361
-	 * @since 9.0.0
362
-	 */
363
-	public function sharingDisabledForUser($userId);
364
-
365
-	/**
366
-	 * Check if outgoing server2server shares are allowed
367
-	 * @return bool
368
-	 * @since 9.0.0
369
-	 */
370
-	public function outgoingServer2ServerSharesAllowed();
371
-
372
-	/**
373
-	 * Check if outgoing server2server shares are allowed
374
-	 * @return bool
375
-	 * @since 14.0.0
376
-	 */
377
-	public function outgoingServer2ServerGroupSharesAllowed();
378
-
379
-
380
-	/**
381
-	 * Check if a given share provider exists
382
-	 * @param int $shareType
383
-	 * @return bool
384
-	 * @since 11.0.0
385
-	 */
386
-	public function shareProviderExists($shareType);
43
+    /**
44
+     * Create a Share
45
+     *
46
+     * @param IShare $share
47
+     * @return IShare The share object
48
+     * @throws \Exception
49
+     * @since 9.0.0
50
+     */
51
+    public function createShare(IShare $share);
52
+
53
+    /**
54
+     * Update a share.
55
+     * The target of the share can't be changed this way: use moveShare
56
+     * The share can't be removed this way (permission 0): use deleteShare
57
+     *
58
+     * @param IShare $share
59
+     * @return IShare The share object
60
+     * @throws \InvalidArgumentException
61
+     * @since 9.0.0
62
+     */
63
+    public function updateShare(IShare $share);
64
+
65
+    /**
66
+     * Delete a share
67
+     *
68
+     * @param IShare $share
69
+     * @throws ShareNotFound
70
+     * @throws \InvalidArgumentException
71
+     * @since 9.0.0
72
+     */
73
+    public function deleteShare(IShare $share);
74
+
75
+    /**
76
+     * Unshare a file as the recipient.
77
+     * This can be different from a regular delete for example when one of
78
+     * the users in a groups deletes that share. But the provider should
79
+     * handle this.
80
+     *
81
+     * @param IShare $share
82
+     * @param string $recipientId
83
+     * @since 9.0.0
84
+     */
85
+    public function deleteFromSelf(IShare $share, $recipientId);
86
+
87
+    /**
88
+     * Restore the share when it has been deleted
89
+     * Certain share types can be restored when they have been deleted
90
+     * but the provider should properly handle this\
91
+     *
92
+     * @param IShare $share The share to restore
93
+     * @param string $recipientId The user to restore the share for
94
+     * @return IShare The restored share object
95
+     * @throws GenericShareException In case restoring the share failed
96
+     *
97
+     * @since 14.0.0
98
+     */
99
+    public function restoreShare(IShare $share, string $recipientId): IShare;
100
+
101
+    /**
102
+     * Move the share as a recipient of the share.
103
+     * This is updating the share target. So where the recipient has the share mounted.
104
+     *
105
+     * @param IShare $share
106
+     * @param string $recipientId
107
+     * @return IShare
108
+     * @throws \InvalidArgumentException If $share is a link share or the $recipient does not match
109
+     * @since 9.0.0
110
+     */
111
+    public function moveShare(IShare $share, $recipientId);
112
+
113
+    /**
114
+     * Get all shares shared by (initiated) by the provided user in a folder.
115
+     *
116
+     * @param string $userId
117
+     * @param Folder $node
118
+     * @param bool $reshares
119
+     * @return IShare[][] [$fileId => IShare[], ...]
120
+     * @since 11.0.0
121
+     */
122
+    public function getSharesInFolder($userId, Folder $node, $reshares = false);
123
+
124
+    /**
125
+     * Get shares shared by (initiated) by the provided user.
126
+     *
127
+     * @param string $userId
128
+     * @param int $shareType
129
+     * @param Node|null $path
130
+     * @param bool $reshares
131
+     * @param int $limit The maximum number of returned results, -1 for all results
132
+     * @param int $offset
133
+     * @return IShare[]
134
+     * @since 9.0.0
135
+     */
136
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0);
137
+
138
+    /**
139
+     * Get shares shared with $user.
140
+     * Filter by $node if provided
141
+     *
142
+     * @param string $userId
143
+     * @param int $shareType
144
+     * @param Node|null $node
145
+     * @param int $limit The maximum number of shares returned, -1 for all
146
+     * @param int $offset
147
+     * @return IShare[]
148
+     * @since 9.0.0
149
+     */
150
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
151
+
152
+    /**
153
+     * Get deleted shares shared with $user.
154
+     * Filter by $node if provided
155
+     *
156
+     * @param string $userId
157
+     * @param int $shareType
158
+     * @param Node|null $node
159
+     * @param int $limit The maximum number of shares returned, -1 for all
160
+     * @param int $offset
161
+     * @return IShare[]
162
+     * @since 14.0.0
163
+     */
164
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0);
165
+
166
+    /**
167
+     * Retrieve a share by the share id.
168
+     * If the recipient is set make sure to retrieve the file for that user.
169
+     * This makes sure that if a user has moved/deleted a group share this
170
+     * is reflected.
171
+     *
172
+     * @param string $id
173
+     * @param string|null $recipient userID of the recipient
174
+     * @return IShare
175
+     * @throws ShareNotFound
176
+     * @since 9.0.0
177
+     */
178
+    public function getShareById($id, $recipient = null);
179
+
180
+    /**
181
+     * Get the share by token possible with password
182
+     *
183
+     * @param string $token
184
+     * @return IShare
185
+     * @throws ShareNotFound
186
+     * @since 9.0.0
187
+     */
188
+    public function getShareByToken($token);
189
+
190
+    /**
191
+     * Verify the password of a public share
192
+     *
193
+     * @param IShare $share
194
+     * @param string $password
195
+     * @return bool
196
+     * @since 9.0.0
197
+     */
198
+    public function checkPassword(IShare $share, $password);
199
+
200
+    /**
201
+     * The user with UID is deleted.
202
+     * All share providers have to cleanup the shares with this user as well
203
+     * as shares owned by this user.
204
+     * Shares only initiated by this user are fine.
205
+     *
206
+     * @param string $uid
207
+     * @since 9.1.0
208
+     */
209
+    public function userDeleted($uid);
210
+
211
+    /**
212
+     * The group with $gid is deleted
213
+     * We need to clear up all shares to this group
214
+     *
215
+     * @param string $gid
216
+     * @since 9.1.0
217
+     */
218
+    public function groupDeleted($gid);
219
+
220
+    /**
221
+     * The user $uid is deleted from the group $gid
222
+     * All user specific group shares have to be removed
223
+     *
224
+     * @param string $uid
225
+     * @param string $gid
226
+     * @since 9.1.0
227
+     */
228
+    public function userDeletedFromGroup($uid, $gid);
229
+
230
+    /**
231
+     * Get access list to a path. This means
232
+     * all the users that can access a given path.
233
+     *
234
+     * Consider:
235
+     * -root
236
+     * |-folder1 (23)
237
+     *  |-folder2 (32)
238
+     *   |-fileA (42)
239
+     *
240
+     * fileA is shared with user1 and user1@server1
241
+     * folder2 is shared with group2 (user4 is a member of group2)
242
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
243
+     *
244
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
245
+     * [
246
+     *  users  => [
247
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
248
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
249
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
250
+     *  ],
251
+     *  remote => [
252
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
253
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
254
+     *  ],
255
+     *  public => bool
256
+     *  mail => bool
257
+     * ]
258
+     *
259
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
260
+     * [
261
+     *  users  => ['user1', 'user2', 'user4'],
262
+     *  remote => bool,
263
+     *  public => bool
264
+     *  mail => bool
265
+     * ]
266
+     *
267
+     * This is required for encryption/activity
268
+     *
269
+     * @param \OCP\Files\Node $path
270
+     * @param bool $recursive Should we check all parent folders as well
271
+     * @param bool $currentAccess Should the user have currently access to the file
272
+     * @return array
273
+     * @since 12
274
+     */
275
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false);
276
+
277
+    /**
278
+     * Instantiates a new share object. This is to be passed to
279
+     * createShare.
280
+     *
281
+     * @return IShare
282
+     * @since 9.0.0
283
+     */
284
+    public function newShare();
285
+
286
+    /**
287
+     * Is the share API enabled
288
+     *
289
+     * @return bool
290
+     * @since 9.0.0
291
+     */
292
+    public function shareApiEnabled();
293
+
294
+    /**
295
+     * Is public link sharing enabled
296
+     *
297
+     * @return bool
298
+     * @since 9.0.0
299
+     */
300
+    public function shareApiAllowLinks();
301
+
302
+    /**
303
+     * Is password on public link requires
304
+     *
305
+     * @return bool
306
+     * @since 9.0.0
307
+     */
308
+    public function shareApiLinkEnforcePassword();
309
+
310
+    /**
311
+     * Is default expire date enabled
312
+     *
313
+     * @return bool
314
+     * @since 9.0.0
315
+     */
316
+    public function shareApiLinkDefaultExpireDate();
317
+
318
+    /**
319
+     * Is default expire date enforced
320
+     *`
321
+     * @return bool
322
+     * @since 9.0.0
323
+     */
324
+    public function shareApiLinkDefaultExpireDateEnforced();
325
+
326
+    /**
327
+     * Number of default expire days
328
+     *
329
+     * @return int
330
+     * @since 9.0.0
331
+     */
332
+    public function shareApiLinkDefaultExpireDays();
333
+
334
+    /**
335
+     * Allow public upload on link shares
336
+     *
337
+     * @return bool
338
+     * @since 9.0.0
339
+     */
340
+    public function shareApiLinkAllowPublicUpload();
341
+
342
+    /**
343
+     * check if user can only share with group members
344
+     * @return bool
345
+     * @since 9.0.0
346
+     */
347
+    public function shareWithGroupMembersOnly();
348
+
349
+    /**
350
+     * Check if users can share with groups
351
+     * @return bool
352
+     * @since 9.0.1
353
+     */
354
+    public function allowGroupSharing();
355
+
356
+    /**
357
+     * Check if sharing is disabled for the given user
358
+     *
359
+     * @param string $userId
360
+     * @return bool
361
+     * @since 9.0.0
362
+     */
363
+    public function sharingDisabledForUser($userId);
364
+
365
+    /**
366
+     * Check if outgoing server2server shares are allowed
367
+     * @return bool
368
+     * @since 9.0.0
369
+     */
370
+    public function outgoingServer2ServerSharesAllowed();
371
+
372
+    /**
373
+     * Check if outgoing server2server shares are allowed
374
+     * @return bool
375
+     * @since 14.0.0
376
+     */
377
+    public function outgoingServer2ServerGroupSharesAllowed();
378
+
379
+
380
+    /**
381
+     * Check if a given share provider exists
382
+     * @param int $shareType
383
+     * @return bool
384
+     * @since 11.0.0
385
+     */
386
+    public function shareProviderExists($shareType);
387 387
 
388 388
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/ShareBackend/File.php 1 patch
Indentation   +215 added lines, -215 removed lines patch added patch discarded remove patch
@@ -37,219 +37,219 @@
 block discarded – undo
37 37
 
38 38
 class File implements \OCP\Share_Backend_File_Dependent {
39 39
 
40
-	const FORMAT_SHARED_STORAGE = 0;
41
-	const FORMAT_GET_FOLDER_CONTENTS = 1;
42
-	const FORMAT_FILE_APP_ROOT = 2;
43
-	const FORMAT_OPENDIR = 3;
44
-	const FORMAT_GET_ALL = 4;
45
-	const FORMAT_PERMISSIONS = 5;
46
-	const FORMAT_TARGET_NAMES = 6;
47
-
48
-	private $path;
49
-
50
-	/** @var FederatedShareProvider */
51
-	private $federatedShareProvider;
52
-
53
-	public function __construct(FederatedShareProvider $federatedShareProvider = null) {
54
-		if ($federatedShareProvider) {
55
-			$this->federatedShareProvider = $federatedShareProvider;
56
-		} else {
57
-			$federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
58
-			$this->federatedShareProvider = $federatedSharingApp->getFederatedShareProvider();
59
-		}
60
-	}
61
-
62
-	public function isValidSource($itemSource, $uidOwner) {
63
-		try {
64
-			$path = \OC\Files\Filesystem::getPath($itemSource);
65
-			// FIXME: attributes should not be set here,
66
-			// keeping this pattern for now to avoid unexpected
67
-			// regressions
68
-			$this->path = \OC\Files\Filesystem::normalizePath(basename($path));
69
-			return true;
70
-		} catch (\OCP\Files\NotFoundException $e) {
71
-			return false;
72
-		}
73
-	}
74
-
75
-	public function getFilePath($itemSource, $uidOwner) {
76
-		if (isset($this->path)) {
77
-			$path = $this->path;
78
-			$this->path = null;
79
-			return $path;
80
-		} else {
81
-			try {
82
-				$path = \OC\Files\Filesystem::getPath($itemSource);
83
-				return $path;
84
-			} catch (\OCP\Files\NotFoundException $e) {
85
-				return false;
86
-			}
87
-		}
88
-	}
89
-
90
-	/**
91
-	 * create unique target
92
-	 * @param string $filePath
93
-	 * @param string $shareWith
94
-	 * @param array $exclude (optional)
95
-	 * @return string
96
-	 */
97
-	public function generateTarget($filePath, $shareWith, $exclude = null) {
98
-		$shareFolder = \OCA\Files_Sharing\Helper::getShareFolder();
99
-		$target = \OC\Files\Filesystem::normalizePath($shareFolder . '/' . basename($filePath));
100
-
101
-		// for group shares we return the target right away
102
-		if ($shareWith === false) {
103
-			return $target;
104
-		}
105
-
106
-		\OC\Files\Filesystem::initMountPoints($shareWith);
107
-		$view = new \OC\Files\View('/' . $shareWith . '/files');
108
-
109
-		if (!$view->is_dir($shareFolder)) {
110
-			$dir = '';
111
-			$subdirs = explode('/', $shareFolder);
112
-			foreach ($subdirs as $subdir) {
113
-				$dir = $dir . '/' . $subdir;
114
-				if (!$view->is_dir($dir)) {
115
-					$view->mkdir($dir);
116
-				}
117
-			}
118
-		}
119
-
120
-		$excludeList = is_array($exclude) ? $exclude : array();
121
-
122
-		return \OCA\Files_Sharing\Helper::generateUniqueTarget($target, $excludeList, $view);
123
-	}
124
-
125
-	public function formatItems($items, $format, $parameters = null) {
126
-		if ($format === self::FORMAT_SHARED_STORAGE) {
127
-			// Only 1 item should come through for this format call
128
-			$item = array_shift($items);
129
-			return array(
130
-				'parent' => $item['parent'],
131
-				'path' => $item['path'],
132
-				'storage' => $item['storage'],
133
-				'permissions' => $item['permissions'],
134
-				'uid_owner' => $item['uid_owner'],
135
-			);
136
-		} else if ($format === self::FORMAT_GET_FOLDER_CONTENTS) {
137
-			$files = array();
138
-			foreach ($items as $item) {
139
-				$file = array();
140
-				$file['fileid'] = $item['file_source'];
141
-				$file['storage'] = $item['storage'];
142
-				$file['path'] = $item['file_target'];
143
-				$file['parent'] = $item['file_parent'];
144
-				$file['name'] = basename($item['file_target']);
145
-				$file['mimetype'] = $item['mimetype'];
146
-				$file['mimepart'] = $item['mimepart'];
147
-				$file['mtime'] = $item['mtime'];
148
-				$file['encrypted'] = $item['encrypted'];
149
-				$file['etag'] = $item['etag'];
150
-				$file['uid_owner'] = $item['uid_owner'];
151
-				$file['displayname_owner'] = $item['displayname_owner'];
152
-
153
-				$storage = \OC\Files\Filesystem::getStorage('/');
154
-				$cache = $storage->getCache();
155
-				$file['size'] = $item['size'];
156
-				$files[] = $file;
157
-			}
158
-			return $files;
159
-		} else if ($format === self::FORMAT_OPENDIR) {
160
-			$files = array();
161
-			foreach ($items as $item) {
162
-				$files[] = basename($item['file_target']);
163
-			}
164
-			return $files;
165
-		} else if ($format === self::FORMAT_GET_ALL) {
166
-			$ids = array();
167
-			foreach ($items as $item) {
168
-				$ids[] = $item['file_source'];
169
-			}
170
-			return $ids;
171
-		} else if ($format === self::FORMAT_PERMISSIONS) {
172
-			$filePermissions = array();
173
-			foreach ($items as $item) {
174
-				$filePermissions[$item['file_source']] = $item['permissions'];
175
-			}
176
-			return $filePermissions;
177
-		} else if ($format === self::FORMAT_TARGET_NAMES) {
178
-			$targets = array();
179
-			foreach ($items as $item) {
180
-				$targets[] = $item['file_target'];
181
-			}
182
-			return $targets;
183
-		}
184
-		return array();
185
-	}
186
-
187
-	/**
188
-	 * check if server2server share is enabled
189
-	 *
190
-	 * @param int $shareType
191
-	 * @return boolean
192
-	 */
193
-	public function isShareTypeAllowed($shareType) {
194
-		if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
195
-			return $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
196
-		}
197
-
198
-		if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
199
-			return $this->federatedShareProvider->isOutgoingServer2serverGroupShareEnabled();
200
-		}
201
-
202
-		return true;
203
-	}
204
-
205
-	/**
206
-	 * resolve reshares to return the correct source item
207
-	 * @param array $source
208
-	 * @return array source item
209
-	 */
210
-	protected static function resolveReshares($source) {
211
-		if (isset($source['parent'])) {
212
-			$parent = $source['parent'];
213
-			while (isset($parent)) {
214
-				$qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
215
-				$qb->select('parent', 'uid_owner')
216
-					->from('share')
217
-					->where(
218
-						$qb->expr()->eq('id', $qb->createNamedParameter($parent))
219
-					);
220
-				$result = $qb->execute();
221
-				$item = $result->fetch();
222
-				$result->closeCursor();
223
-				if (isset($item['parent'])) {
224
-					$parent = $item['parent'];
225
-				} else {
226
-					$fileOwner = $item['uid_owner'];
227
-					break;
228
-				}
229
-			}
230
-		} else {
231
-			$fileOwner = $source['uid_owner'];
232
-		}
233
-		if (isset($fileOwner)) {
234
-			$source['fileOwner'] = $fileOwner;
235
-		} else {
236
-			\OC::$server->getLogger()->error('No owner found for reshare', ['app' => 'files_sharing']);
237
-		}
238
-
239
-		return $source;
240
-	}
241
-
242
-	/**
243
-	 * @param string $target
244
-	 * @param array $share
245
-	 * @return array|false source item
246
-	 */
247
-	public static function getSource($target, $share) {
248
-		if ($share['item_type'] === 'folder' && $target !== '') {
249
-			// note: in case of ext storage mount points the path might be empty
250
-			// which would cause a leading slash to appear
251
-			$share['path'] = ltrim($share['path'] . '/' . $target, '/');
252
-		}
253
-		return self::resolveReshares($share);
254
-	}
40
+    const FORMAT_SHARED_STORAGE = 0;
41
+    const FORMAT_GET_FOLDER_CONTENTS = 1;
42
+    const FORMAT_FILE_APP_ROOT = 2;
43
+    const FORMAT_OPENDIR = 3;
44
+    const FORMAT_GET_ALL = 4;
45
+    const FORMAT_PERMISSIONS = 5;
46
+    const FORMAT_TARGET_NAMES = 6;
47
+
48
+    private $path;
49
+
50
+    /** @var FederatedShareProvider */
51
+    private $federatedShareProvider;
52
+
53
+    public function __construct(FederatedShareProvider $federatedShareProvider = null) {
54
+        if ($federatedShareProvider) {
55
+            $this->federatedShareProvider = $federatedShareProvider;
56
+        } else {
57
+            $federatedSharingApp = new \OCA\FederatedFileSharing\AppInfo\Application();
58
+            $this->federatedShareProvider = $federatedSharingApp->getFederatedShareProvider();
59
+        }
60
+    }
61
+
62
+    public function isValidSource($itemSource, $uidOwner) {
63
+        try {
64
+            $path = \OC\Files\Filesystem::getPath($itemSource);
65
+            // FIXME: attributes should not be set here,
66
+            // keeping this pattern for now to avoid unexpected
67
+            // regressions
68
+            $this->path = \OC\Files\Filesystem::normalizePath(basename($path));
69
+            return true;
70
+        } catch (\OCP\Files\NotFoundException $e) {
71
+            return false;
72
+        }
73
+    }
74
+
75
+    public function getFilePath($itemSource, $uidOwner) {
76
+        if (isset($this->path)) {
77
+            $path = $this->path;
78
+            $this->path = null;
79
+            return $path;
80
+        } else {
81
+            try {
82
+                $path = \OC\Files\Filesystem::getPath($itemSource);
83
+                return $path;
84
+            } catch (\OCP\Files\NotFoundException $e) {
85
+                return false;
86
+            }
87
+        }
88
+    }
89
+
90
+    /**
91
+     * create unique target
92
+     * @param string $filePath
93
+     * @param string $shareWith
94
+     * @param array $exclude (optional)
95
+     * @return string
96
+     */
97
+    public function generateTarget($filePath, $shareWith, $exclude = null) {
98
+        $shareFolder = \OCA\Files_Sharing\Helper::getShareFolder();
99
+        $target = \OC\Files\Filesystem::normalizePath($shareFolder . '/' . basename($filePath));
100
+
101
+        // for group shares we return the target right away
102
+        if ($shareWith === false) {
103
+            return $target;
104
+        }
105
+
106
+        \OC\Files\Filesystem::initMountPoints($shareWith);
107
+        $view = new \OC\Files\View('/' . $shareWith . '/files');
108
+
109
+        if (!$view->is_dir($shareFolder)) {
110
+            $dir = '';
111
+            $subdirs = explode('/', $shareFolder);
112
+            foreach ($subdirs as $subdir) {
113
+                $dir = $dir . '/' . $subdir;
114
+                if (!$view->is_dir($dir)) {
115
+                    $view->mkdir($dir);
116
+                }
117
+            }
118
+        }
119
+
120
+        $excludeList = is_array($exclude) ? $exclude : array();
121
+
122
+        return \OCA\Files_Sharing\Helper::generateUniqueTarget($target, $excludeList, $view);
123
+    }
124
+
125
+    public function formatItems($items, $format, $parameters = null) {
126
+        if ($format === self::FORMAT_SHARED_STORAGE) {
127
+            // Only 1 item should come through for this format call
128
+            $item = array_shift($items);
129
+            return array(
130
+                'parent' => $item['parent'],
131
+                'path' => $item['path'],
132
+                'storage' => $item['storage'],
133
+                'permissions' => $item['permissions'],
134
+                'uid_owner' => $item['uid_owner'],
135
+            );
136
+        } else if ($format === self::FORMAT_GET_FOLDER_CONTENTS) {
137
+            $files = array();
138
+            foreach ($items as $item) {
139
+                $file = array();
140
+                $file['fileid'] = $item['file_source'];
141
+                $file['storage'] = $item['storage'];
142
+                $file['path'] = $item['file_target'];
143
+                $file['parent'] = $item['file_parent'];
144
+                $file['name'] = basename($item['file_target']);
145
+                $file['mimetype'] = $item['mimetype'];
146
+                $file['mimepart'] = $item['mimepart'];
147
+                $file['mtime'] = $item['mtime'];
148
+                $file['encrypted'] = $item['encrypted'];
149
+                $file['etag'] = $item['etag'];
150
+                $file['uid_owner'] = $item['uid_owner'];
151
+                $file['displayname_owner'] = $item['displayname_owner'];
152
+
153
+                $storage = \OC\Files\Filesystem::getStorage('/');
154
+                $cache = $storage->getCache();
155
+                $file['size'] = $item['size'];
156
+                $files[] = $file;
157
+            }
158
+            return $files;
159
+        } else if ($format === self::FORMAT_OPENDIR) {
160
+            $files = array();
161
+            foreach ($items as $item) {
162
+                $files[] = basename($item['file_target']);
163
+            }
164
+            return $files;
165
+        } else if ($format === self::FORMAT_GET_ALL) {
166
+            $ids = array();
167
+            foreach ($items as $item) {
168
+                $ids[] = $item['file_source'];
169
+            }
170
+            return $ids;
171
+        } else if ($format === self::FORMAT_PERMISSIONS) {
172
+            $filePermissions = array();
173
+            foreach ($items as $item) {
174
+                $filePermissions[$item['file_source']] = $item['permissions'];
175
+            }
176
+            return $filePermissions;
177
+        } else if ($format === self::FORMAT_TARGET_NAMES) {
178
+            $targets = array();
179
+            foreach ($items as $item) {
180
+                $targets[] = $item['file_target'];
181
+            }
182
+            return $targets;
183
+        }
184
+        return array();
185
+    }
186
+
187
+    /**
188
+     * check if server2server share is enabled
189
+     *
190
+     * @param int $shareType
191
+     * @return boolean
192
+     */
193
+    public function isShareTypeAllowed($shareType) {
194
+        if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
195
+            return $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
196
+        }
197
+
198
+        if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
199
+            return $this->federatedShareProvider->isOutgoingServer2serverGroupShareEnabled();
200
+        }
201
+
202
+        return true;
203
+    }
204
+
205
+    /**
206
+     * resolve reshares to return the correct source item
207
+     * @param array $source
208
+     * @return array source item
209
+     */
210
+    protected static function resolveReshares($source) {
211
+        if (isset($source['parent'])) {
212
+            $parent = $source['parent'];
213
+            while (isset($parent)) {
214
+                $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
215
+                $qb->select('parent', 'uid_owner')
216
+                    ->from('share')
217
+                    ->where(
218
+                        $qb->expr()->eq('id', $qb->createNamedParameter($parent))
219
+                    );
220
+                $result = $qb->execute();
221
+                $item = $result->fetch();
222
+                $result->closeCursor();
223
+                if (isset($item['parent'])) {
224
+                    $parent = $item['parent'];
225
+                } else {
226
+                    $fileOwner = $item['uid_owner'];
227
+                    break;
228
+                }
229
+            }
230
+        } else {
231
+            $fileOwner = $source['uid_owner'];
232
+        }
233
+        if (isset($fileOwner)) {
234
+            $source['fileOwner'] = $fileOwner;
235
+        } else {
236
+            \OC::$server->getLogger()->error('No owner found for reshare', ['app' => 'files_sharing']);
237
+        }
238
+
239
+        return $source;
240
+    }
241
+
242
+    /**
243
+     * @param string $target
244
+     * @param array $share
245
+     * @return array|false source item
246
+     */
247
+    public static function getSource($target, $share) {
248
+        if ($share['item_type'] === 'folder' && $target !== '') {
249
+            // note: in case of ext storage mount points the path might be empty
250
+            // which would cause a leading slash to appear
251
+            $share['path'] = ltrim($share['path'] . '/' . $target, '/');
252
+        }
253
+        return self::resolveReshares($share);
254
+    }
255 255
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareesAPIController.php 1 patch
Indentation   +216 added lines, -216 removed lines patch added patch discarded remove patch
@@ -40,220 +40,220 @@
 block discarded – undo
40 40
 use OCP\Share\IManager;
41 41
 
42 42
 class ShareesAPIController extends OCSController {
43
-	/** @var IConfig */
44
-	protected $config;
45
-
46
-	/** @var IURLGenerator */
47
-	protected $urlGenerator;
48
-
49
-	/** @var IManager */
50
-	protected $shareManager;
51
-
52
-	/** @var bool */
53
-	protected $shareWithGroupOnly = false;
54
-
55
-	/** @var bool */
56
-	protected $shareeEnumeration = true;
57
-
58
-	/** @var int */
59
-	protected $offset = 0;
60
-
61
-	/** @var int */
62
-	protected $limit = 10;
63
-
64
-	/** @var array */
65
-	protected $result = [
66
-		'exact' => [
67
-			'users' => [],
68
-			'groups' => [],
69
-			'remotes' => [],
70
-			'remote_groups' => [],
71
-			'emails' => [],
72
-			'circles' => [],
73
-		],
74
-		'users' => [],
75
-		'groups' => [],
76
-		'remotes' => [],
77
-		'remote_groups' => [],
78
-		'emails' => [],
79
-		'lookup' => [],
80
-		'circles' => [],
81
-	];
82
-
83
-	protected $reachedEndFor = [];
84
-	/** @var ISearch */
85
-	private $collaboratorSearch;
86
-
87
-	/**
88
-	 * @param string $appName
89
-	 * @param IRequest $request
90
-	 * @param IConfig $config
91
-	 * @param IURLGenerator $urlGenerator
92
-	 * @param IManager $shareManager
93
-	 * @param ISearch $collaboratorSearch
94
-	 */
95
-	public function __construct(
96
-		string $appName,
97
-		IRequest $request,
98
-		IConfig $config,
99
-		IURLGenerator $urlGenerator,
100
-		IManager $shareManager,
101
-		ISearch $collaboratorSearch
102
-	) {
103
-		parent::__construct($appName, $request);
104
-
105
-		$this->config = $config;
106
-		$this->urlGenerator = $urlGenerator;
107
-		$this->shareManager = $shareManager;
108
-		$this->collaboratorSearch = $collaboratorSearch;
109
-	}
110
-
111
-	/**
112
-	 * @NoAdminRequired
113
-	 *
114
-	 * @param string $search
115
-	 * @param string $itemType
116
-	 * @param int $page
117
-	 * @param int $perPage
118
-	 * @param int|int[] $shareType
119
-	 * @param bool $lookup
120
-	 * @return DataResponse
121
-	 * @throws OCSBadRequestException
122
-	 */
123
-	public function search(string $search = '', string $itemType = null, int $page = 1, int $perPage = 200, $shareType = null, bool $lookup = true): DataResponse {
124
-
125
-		// only search for string larger than a given threshold
126
-		$threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
127
-		if (strlen($search) < $threshold) {
128
-			return new DataResponse($this->result);
129
-		}
130
-
131
-		// never return more than the max. number of results configured in the config.php
132
-		$maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
133
-		if ($maxResults > 0) {
134
-			$perPage = min($perPage, $maxResults);
135
-		}
136
-		if ($perPage <= 0) {
137
-			throw new OCSBadRequestException('Invalid perPage argument');
138
-		}
139
-		if ($page <= 0) {
140
-			throw new OCSBadRequestException('Invalid page');
141
-		}
142
-
143
-		$shareTypes = [
144
-			Share::SHARE_TYPE_USER,
145
-		];
146
-
147
-		if ($itemType === null) {
148
-			throw new OCSBadRequestException('Missing itemType');
149
-		} elseif ($itemType === 'file' || $itemType === 'folder') {
150
-			if ($this->shareManager->allowGroupSharing()) {
151
-				$shareTypes[] = Share::SHARE_TYPE_GROUP;
152
-			}
153
-
154
-			if ($this->isRemoteSharingAllowed($itemType)) {
155
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE;
156
-			}
157
-
158
-			if ($this->isRemoteGroupSharingAllowed($itemType)) {
159
-				$shareTypes[] = Share::SHARE_TYPE_REMOTE_GROUP;
160
-			}
161
-
162
-			if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
163
-				$shareTypes[] = Share::SHARE_TYPE_EMAIL;
164
-			}
165
-		} else {
166
-			$shareTypes[] = Share::SHARE_TYPE_GROUP;
167
-			$shareTypes[] = Share::SHARE_TYPE_EMAIL;
168
-		}
169
-
170
-		// FIXME: DI
171
-		if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
172
-			$shareTypes[] = Share::SHARE_TYPE_CIRCLE;
173
-		}
174
-
175
-		if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
176
-			$shareTypes = array_intersect($shareTypes, $_GET['shareType']);
177
-			sort($shareTypes);
178
-		} else if (is_numeric($shareType)) {
179
-			$shareTypes = array_intersect($shareTypes, [(int) $shareType]);
180
-			sort($shareTypes);
181
-		}
182
-
183
-		$this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
184
-		$this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
185
-		$this->limit = (int) $perPage;
186
-		$this->offset = $perPage * ($page - 1);
187
-
188
-		list($result, $hasMoreResults) = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset);
189
-
190
-		// extra treatment for 'exact' subarray, with a single merge expected keys might be lost
191
-		if(isset($result['exact'])) {
192
-			$result['exact'] = array_merge($this->result['exact'], $result['exact']);
193
-		}
194
-		$this->result = array_merge($this->result, $result);
195
-		$response = new DataResponse($this->result);
196
-
197
-		if ($hasMoreResults) {
198
-			$response->addHeader('Link', $this->getPaginationLink($page, [
199
-				'search' => $search,
200
-				'itemType' => $itemType,
201
-				'shareType' => $shareTypes,
202
-				'perPage' => $perPage,
203
-			]));
204
-		}
205
-
206
-		return $response;
207
-	}
208
-
209
-	/**
210
-	 * Method to get out the static call for better testing
211
-	 *
212
-	 * @param string $itemType
213
-	 * @return bool
214
-	 */
215
-	protected function isRemoteSharingAllowed(string $itemType): bool {
216
-		try {
217
-			// FIXME: static foo makes unit testing unnecessarily difficult
218
-			$backend = \OC\Share\Share::getBackend($itemType);
219
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
220
-		} catch (\Exception $e) {
221
-			return false;
222
-		}
223
-	}
224
-
225
-	protected function isRemoteGroupSharingAllowed(string $itemType): bool {
226
-		try {
227
-			// FIXME: static foo makes unit testing unnecessarily difficult
228
-			$backend = \OC\Share\Share::getBackend($itemType);
229
-			return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE_GROUP);
230
-		} catch (\Exception $e) {
231
-			return false;
232
-		}
233
-	}
234
-
235
-
236
-	/**
237
-	 * Generates a bunch of pagination links for the current page
238
-	 *
239
-	 * @param int $page Current page
240
-	 * @param array $params Parameters for the URL
241
-	 * @return string
242
-	 */
243
-	protected function getPaginationLink(int $page, array $params): string {
244
-		if ($this->isV2()) {
245
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
246
-		} else {
247
-			$url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
248
-		}
249
-		$params['page'] = $page + 1;
250
-		return '<' . $url . http_build_query($params) . '>; rel="next"';
251
-	}
252
-
253
-	/**
254
-	 * @return bool
255
-	 */
256
-	protected function isV2(): bool {
257
-		return $this->request->getScriptName() === '/ocs/v2.php';
258
-	}
43
+    /** @var IConfig */
44
+    protected $config;
45
+
46
+    /** @var IURLGenerator */
47
+    protected $urlGenerator;
48
+
49
+    /** @var IManager */
50
+    protected $shareManager;
51
+
52
+    /** @var bool */
53
+    protected $shareWithGroupOnly = false;
54
+
55
+    /** @var bool */
56
+    protected $shareeEnumeration = true;
57
+
58
+    /** @var int */
59
+    protected $offset = 0;
60
+
61
+    /** @var int */
62
+    protected $limit = 10;
63
+
64
+    /** @var array */
65
+    protected $result = [
66
+        'exact' => [
67
+            'users' => [],
68
+            'groups' => [],
69
+            'remotes' => [],
70
+            'remote_groups' => [],
71
+            'emails' => [],
72
+            'circles' => [],
73
+        ],
74
+        'users' => [],
75
+        'groups' => [],
76
+        'remotes' => [],
77
+        'remote_groups' => [],
78
+        'emails' => [],
79
+        'lookup' => [],
80
+        'circles' => [],
81
+    ];
82
+
83
+    protected $reachedEndFor = [];
84
+    /** @var ISearch */
85
+    private $collaboratorSearch;
86
+
87
+    /**
88
+     * @param string $appName
89
+     * @param IRequest $request
90
+     * @param IConfig $config
91
+     * @param IURLGenerator $urlGenerator
92
+     * @param IManager $shareManager
93
+     * @param ISearch $collaboratorSearch
94
+     */
95
+    public function __construct(
96
+        string $appName,
97
+        IRequest $request,
98
+        IConfig $config,
99
+        IURLGenerator $urlGenerator,
100
+        IManager $shareManager,
101
+        ISearch $collaboratorSearch
102
+    ) {
103
+        parent::__construct($appName, $request);
104
+
105
+        $this->config = $config;
106
+        $this->urlGenerator = $urlGenerator;
107
+        $this->shareManager = $shareManager;
108
+        $this->collaboratorSearch = $collaboratorSearch;
109
+    }
110
+
111
+    /**
112
+     * @NoAdminRequired
113
+     *
114
+     * @param string $search
115
+     * @param string $itemType
116
+     * @param int $page
117
+     * @param int $perPage
118
+     * @param int|int[] $shareType
119
+     * @param bool $lookup
120
+     * @return DataResponse
121
+     * @throws OCSBadRequestException
122
+     */
123
+    public function search(string $search = '', string $itemType = null, int $page = 1, int $perPage = 200, $shareType = null, bool $lookup = true): DataResponse {
124
+
125
+        // only search for string larger than a given threshold
126
+        $threshold = (int)$this->config->getSystemValue('sharing.minSearchStringLength', 0);
127
+        if (strlen($search) < $threshold) {
128
+            return new DataResponse($this->result);
129
+        }
130
+
131
+        // never return more than the max. number of results configured in the config.php
132
+        $maxResults = (int)$this->config->getSystemValue('sharing.maxAutocompleteResults', 0);
133
+        if ($maxResults > 0) {
134
+            $perPage = min($perPage, $maxResults);
135
+        }
136
+        if ($perPage <= 0) {
137
+            throw new OCSBadRequestException('Invalid perPage argument');
138
+        }
139
+        if ($page <= 0) {
140
+            throw new OCSBadRequestException('Invalid page');
141
+        }
142
+
143
+        $shareTypes = [
144
+            Share::SHARE_TYPE_USER,
145
+        ];
146
+
147
+        if ($itemType === null) {
148
+            throw new OCSBadRequestException('Missing itemType');
149
+        } elseif ($itemType === 'file' || $itemType === 'folder') {
150
+            if ($this->shareManager->allowGroupSharing()) {
151
+                $shareTypes[] = Share::SHARE_TYPE_GROUP;
152
+            }
153
+
154
+            if ($this->isRemoteSharingAllowed($itemType)) {
155
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE;
156
+            }
157
+
158
+            if ($this->isRemoteGroupSharingAllowed($itemType)) {
159
+                $shareTypes[] = Share::SHARE_TYPE_REMOTE_GROUP;
160
+            }
161
+
162
+            if ($this->shareManager->shareProviderExists(Share::SHARE_TYPE_EMAIL)) {
163
+                $shareTypes[] = Share::SHARE_TYPE_EMAIL;
164
+            }
165
+        } else {
166
+            $shareTypes[] = Share::SHARE_TYPE_GROUP;
167
+            $shareTypes[] = Share::SHARE_TYPE_EMAIL;
168
+        }
169
+
170
+        // FIXME: DI
171
+        if (\OC::$server->getAppManager()->isEnabledForUser('circles') && class_exists('\OCA\Circles\ShareByCircleProvider')) {
172
+            $shareTypes[] = Share::SHARE_TYPE_CIRCLE;
173
+        }
174
+
175
+        if (isset($_GET['shareType']) && is_array($_GET['shareType'])) {
176
+            $shareTypes = array_intersect($shareTypes, $_GET['shareType']);
177
+            sort($shareTypes);
178
+        } else if (is_numeric($shareType)) {
179
+            $shareTypes = array_intersect($shareTypes, [(int) $shareType]);
180
+            sort($shareTypes);
181
+        }
182
+
183
+        $this->shareWithGroupOnly = $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
184
+        $this->shareeEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
185
+        $this->limit = (int) $perPage;
186
+        $this->offset = $perPage * ($page - 1);
187
+
188
+        list($result, $hasMoreResults) = $this->collaboratorSearch->search($search, $shareTypes, $lookup, $this->limit, $this->offset);
189
+
190
+        // extra treatment for 'exact' subarray, with a single merge expected keys might be lost
191
+        if(isset($result['exact'])) {
192
+            $result['exact'] = array_merge($this->result['exact'], $result['exact']);
193
+        }
194
+        $this->result = array_merge($this->result, $result);
195
+        $response = new DataResponse($this->result);
196
+
197
+        if ($hasMoreResults) {
198
+            $response->addHeader('Link', $this->getPaginationLink($page, [
199
+                'search' => $search,
200
+                'itemType' => $itemType,
201
+                'shareType' => $shareTypes,
202
+                'perPage' => $perPage,
203
+            ]));
204
+        }
205
+
206
+        return $response;
207
+    }
208
+
209
+    /**
210
+     * Method to get out the static call for better testing
211
+     *
212
+     * @param string $itemType
213
+     * @return bool
214
+     */
215
+    protected function isRemoteSharingAllowed(string $itemType): bool {
216
+        try {
217
+            // FIXME: static foo makes unit testing unnecessarily difficult
218
+            $backend = \OC\Share\Share::getBackend($itemType);
219
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE);
220
+        } catch (\Exception $e) {
221
+            return false;
222
+        }
223
+    }
224
+
225
+    protected function isRemoteGroupSharingAllowed(string $itemType): bool {
226
+        try {
227
+            // FIXME: static foo makes unit testing unnecessarily difficult
228
+            $backend = \OC\Share\Share::getBackend($itemType);
229
+            return $backend->isShareTypeAllowed(Share::SHARE_TYPE_REMOTE_GROUP);
230
+        } catch (\Exception $e) {
231
+            return false;
232
+        }
233
+    }
234
+
235
+
236
+    /**
237
+     * Generates a bunch of pagination links for the current page
238
+     *
239
+     * @param int $page Current page
240
+     * @param array $params Parameters for the URL
241
+     * @return string
242
+     */
243
+    protected function getPaginationLink(int $page, array $params): string {
244
+        if ($this->isV2()) {
245
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v2.php/apps/files_sharing/api/v1/sharees') . '?';
246
+        } else {
247
+            $url = $this->urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/sharees') . '?';
248
+        }
249
+        $params['page'] = $page + 1;
250
+        return '<' . $url . http_build_query($params) . '>; rel="next"';
251
+    }
252
+
253
+    /**
254
+     * @return bool
255
+     */
256
+    protected function isV2(): bool {
257
+        return $this->request->getScriptName() === '/ocs/v2.php';
258
+    }
259 259
 }
Please login to merge, or discard this patch.