Completed
Push — master ( 25f772...35f6b8 )
by Joas
340:56 queued 325:44
created
lib/private/Share20/Manager.php 2 patches
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
 
311 311
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
312 312
 			$expirationDate = new \DateTime();
313
-			$expirationDate->setTime(0,0,0);
313
+			$expirationDate->setTime(0, 0, 0);
314 314
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
315 315
 		}
316 316
 
@@ -322,7 +322,7 @@  discard block
 block discarded – undo
322 322
 
323 323
 			$date = new \DateTime();
324 324
 			$date->setTime(0, 0, 0);
325
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
325
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
326 326
 			if ($date < $expirationDate) {
327 327
 				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
328 328
 				throw new GenericShareException($message, $message, 404);
@@ -375,7 +375,7 @@  discard block
 block discarded – undo
375 375
 		 */
376 376
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
377 377
 		$existingShares = $provider->getSharesByPath($share->getNode());
378
-		foreach($existingShares as $existingShare) {
378
+		foreach ($existingShares as $existingShare) {
379 379
 			// Ignore if it is the same share
380 380
 			try {
381 381
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 		 */
433 433
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
434 434
 		$existingShares = $provider->getSharesByPath($share->getNode());
435
-		foreach($existingShares as $existingShare) {
435
+		foreach ($existingShares as $existingShare) {
436 436
 			try {
437 437
 				if ($existingShare->getFullId() === $share->getFullId()) {
438 438
 					continue;
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 		// Make sure that we do not share a path that contains a shared mountpoint
502 502
 		if ($path instanceof \OCP\Files\Folder) {
503 503
 			$mounts = $this->mountManager->findIn($path->getPath());
504
-			foreach($mounts as $mount) {
504
+			foreach ($mounts as $mount) {
505 505
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
506 506
 					throw new \InvalidArgumentException('Path contains files shared with you');
507 507
 				}
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 		$storage = $share->getNode()->getStorage();
550 550
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
551 551
 			$parent = $share->getNode()->getParent();
552
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
552
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
553 553
 				$parent = $parent->getParent();
554 554
 			}
555 555
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 		}
607 607
 
608 608
 		// Generate the target
609
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
609
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
610 610
 		$target = \OC\Files\Filesystem::normalizePath($target);
611 611
 		$share->setTarget($target);
612 612
 
@@ -868,7 +868,7 @@  discard block
 block discarded – undo
868 868
 	 * @param string $recipientId
869 869
 	 */
870 870
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
871
-		list($providerId, ) = $this->splitFullId($share->getFullId());
871
+		list($providerId,) = $this->splitFullId($share->getFullId());
872 872
 		$provider = $this->factory->getProvider($providerId);
873 873
 
874 874
 		$provider->deleteFromSelf($share, $recipientId);
@@ -889,7 +889,7 @@  discard block
 block discarded – undo
889 889
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
890 890
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
891 891
 			if (is_null($sharedWith)) {
892
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
892
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
893 893
 			}
894 894
 			$recipient = $this->userManager->get($recipientId);
895 895
 			if (!$sharedWith->inGroup($recipient)) {
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
 			}
898 898
 		}
899 899
 
900
-		list($providerId, ) = $this->splitFullId($share->getFullId());
900
+		list($providerId,) = $this->splitFullId($share->getFullId());
901 901
 		$provider = $this->factory->getProvider($providerId);
902 902
 
903 903
 		$provider->move($share, $recipientId);
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 			$shares2 = [];
946 946
 			$today = new \DateTime();
947 947
 
948
-			while(true) {
948
+			while (true) {
949 949
 				$added = 0;
950 950
 				foreach ($shares as $share) {
951 951
 					// Check if the share is expired and if so delete it
@@ -1044,7 +1044,7 @@  discard block
 block discarded – undo
1044 1044
 	 *
1045 1045
 	 * @return Share[]
1046 1046
 	 */
1047
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1047
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1048 1048
 		return [];
1049 1049
 	}
1050 1050
 
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
 	public function getShareByToken($token) {
1060 1060
 		$share = null;
1061 1061
 		try {
1062
-			if($this->shareApiAllowLinks()) {
1062
+			if ($this->shareApiAllowLinks()) {
1063 1063
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1064 1064
 				$share = $provider->getShareByToken($token);
1065 1065
 			}
@@ -1259,7 +1259,7 @@  discard block
 block discarded – undo
1259 1259
 	 * @return int
1260 1260
 	 */
1261 1261
 	public function shareApiLinkDefaultExpireDays() {
1262
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1262
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1263 1263
 	}
1264 1264
 
1265 1265
 	/**
Please login to merge, or discard this patch.
Indentation   +1274 added lines, -1274 removed lines patch added patch discarded remove patch
@@ -57,1301 +57,1301 @@
 block discarded – undo
57 57
  */
58 58
 class Manager implements IManager {
59 59
 
60
-	/** @var IProviderFactory */
61
-	private $factory;
62
-	/** @var ILogger */
63
-	private $logger;
64
-	/** @var IConfig */
65
-	private $config;
66
-	/** @var ISecureRandom */
67
-	private $secureRandom;
68
-	/** @var IHasher */
69
-	private $hasher;
70
-	/** @var IMountManager */
71
-	private $mountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IL10N */
75
-	private $l;
76
-	/** @var IUserManager */
77
-	private $userManager;
78
-	/** @var IRootFolder */
79
-	private $rootFolder;
80
-	/** @var CappedMemoryCache */
81
-	private $sharingDisabledForUsersCache;
82
-	/** @var EventDispatcher */
83
-	private $eventDispatcher;
84
-
85
-
86
-	/**
87
-	 * Manager constructor.
88
-	 *
89
-	 * @param ILogger $logger
90
-	 * @param IConfig $config
91
-	 * @param ISecureRandom $secureRandom
92
-	 * @param IHasher $hasher
93
-	 * @param IMountManager $mountManager
94
-	 * @param IGroupManager $groupManager
95
-	 * @param IL10N $l
96
-	 * @param IProviderFactory $factory
97
-	 * @param IUserManager $userManager
98
-	 * @param IRootFolder $rootFolder
99
-	 * @param EventDispatcher $eventDispatcher
100
-	 */
101
-	public function __construct(
102
-			ILogger $logger,
103
-			IConfig $config,
104
-			ISecureRandom $secureRandom,
105
-			IHasher $hasher,
106
-			IMountManager $mountManager,
107
-			IGroupManager $groupManager,
108
-			IL10N $l,
109
-			IProviderFactory $factory,
110
-			IUserManager $userManager,
111
-			IRootFolder $rootFolder,
112
-			EventDispatcher $eventDispatcher
113
-	) {
114
-		$this->logger = $logger;
115
-		$this->config = $config;
116
-		$this->secureRandom = $secureRandom;
117
-		$this->hasher = $hasher;
118
-		$this->mountManager = $mountManager;
119
-		$this->groupManager = $groupManager;
120
-		$this->l = $l;
121
-		$this->factory = $factory;
122
-		$this->userManager = $userManager;
123
-		$this->rootFolder = $rootFolder;
124
-		$this->eventDispatcher = $eventDispatcher;
125
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
126
-	}
127
-
128
-	/**
129
-	 * Convert from a full share id to a tuple (providerId, shareId)
130
-	 *
131
-	 * @param string $id
132
-	 * @return string[]
133
-	 */
134
-	private function splitFullId($id) {
135
-		return explode(':', $id, 2);
136
-	}
137
-
138
-	/**
139
-	 * Verify if a password meets all requirements
140
-	 *
141
-	 * @param string $password
142
-	 * @throws \Exception
143
-	 */
144
-	protected function verifyPassword($password) {
145
-		if ($password === null) {
146
-			// No password is set, check if this is allowed.
147
-			if ($this->shareApiLinkEnforcePassword()) {
148
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
149
-			}
150
-
151
-			return;
152
-		}
153
-
154
-		// Let others verify the password
155
-		try {
156
-			$event = new GenericEvent($password);
157
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
158
-		} catch (HintException $e) {
159
-			throw new \Exception($e->getHint());
160
-		}
161
-	}
162
-
163
-	/**
164
-	 * Check for generic requirements before creating a share
165
-	 *
166
-	 * @param \OCP\Share\IShare $share
167
-	 * @throws \InvalidArgumentException
168
-	 * @throws GenericShareException
169
-	 */
170
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
171
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
172
-			// We expect a valid user as sharedWith for user shares
173
-			if (!$this->userManager->userExists($share->getSharedWith())) {
174
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
175
-			}
176
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
177
-			// We expect a valid group as sharedWith for group shares
178
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
179
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
180
-			}
181
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
182
-			if ($share->getSharedWith() !== null) {
183
-				throw new \InvalidArgumentException('SharedWith should be empty');
184
-			}
185
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
186
-			if ($share->getSharedWith() === null) {
187
-				throw new \InvalidArgumentException('SharedWith should not be empty');
188
-			}
189
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
190
-			if ($share->getSharedWith() === null) {
191
-				throw new \InvalidArgumentException('SharedWith should not be empty');
192
-			}
193
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
194
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
195
-			if ($circle === null) {
196
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
197
-			}
198
-		} else {
199
-			// We can't handle other types yet
200
-			throw new \InvalidArgumentException('unknown share type');
201
-		}
202
-
203
-		// Verify the initiator of the share is set
204
-		if ($share->getSharedBy() === null) {
205
-			throw new \InvalidArgumentException('SharedBy should be set');
206
-		}
207
-
208
-		// Cannot share with yourself
209
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
210
-			$share->getSharedWith() === $share->getSharedBy()) {
211
-			throw new \InvalidArgumentException('Can\'t share with yourself');
212
-		}
213
-
214
-		// The path should be set
215
-		if ($share->getNode() === null) {
216
-			throw new \InvalidArgumentException('Path should be set');
217
-		}
218
-
219
-		// And it should be a file or a folder
220
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
221
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
222
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
223
-		}
224
-
225
-		// And you can't share your rootfolder
226
-		if ($this->userManager->userExists($share->getSharedBy())) {
227
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
228
-		} else {
229
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
230
-		}
231
-		if ($sharedPath === $share->getNode()->getPath()) {
232
-			throw new \InvalidArgumentException('You can\'t share your root folder');
233
-		}
234
-
235
-		// Check if we actually have share permissions
236
-		if (!$share->getNode()->isShareable()) {
237
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
238
-			throw new GenericShareException($message_t, $message_t, 404);
239
-		}
240
-
241
-		// Permissions should be set
242
-		if ($share->getPermissions() === null) {
243
-			throw new \InvalidArgumentException('A share requires permissions');
244
-		}
245
-
246
-		/*
60
+    /** @var IProviderFactory */
61
+    private $factory;
62
+    /** @var ILogger */
63
+    private $logger;
64
+    /** @var IConfig */
65
+    private $config;
66
+    /** @var ISecureRandom */
67
+    private $secureRandom;
68
+    /** @var IHasher */
69
+    private $hasher;
70
+    /** @var IMountManager */
71
+    private $mountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IL10N */
75
+    private $l;
76
+    /** @var IUserManager */
77
+    private $userManager;
78
+    /** @var IRootFolder */
79
+    private $rootFolder;
80
+    /** @var CappedMemoryCache */
81
+    private $sharingDisabledForUsersCache;
82
+    /** @var EventDispatcher */
83
+    private $eventDispatcher;
84
+
85
+
86
+    /**
87
+     * Manager constructor.
88
+     *
89
+     * @param ILogger $logger
90
+     * @param IConfig $config
91
+     * @param ISecureRandom $secureRandom
92
+     * @param IHasher $hasher
93
+     * @param IMountManager $mountManager
94
+     * @param IGroupManager $groupManager
95
+     * @param IL10N $l
96
+     * @param IProviderFactory $factory
97
+     * @param IUserManager $userManager
98
+     * @param IRootFolder $rootFolder
99
+     * @param EventDispatcher $eventDispatcher
100
+     */
101
+    public function __construct(
102
+            ILogger $logger,
103
+            IConfig $config,
104
+            ISecureRandom $secureRandom,
105
+            IHasher $hasher,
106
+            IMountManager $mountManager,
107
+            IGroupManager $groupManager,
108
+            IL10N $l,
109
+            IProviderFactory $factory,
110
+            IUserManager $userManager,
111
+            IRootFolder $rootFolder,
112
+            EventDispatcher $eventDispatcher
113
+    ) {
114
+        $this->logger = $logger;
115
+        $this->config = $config;
116
+        $this->secureRandom = $secureRandom;
117
+        $this->hasher = $hasher;
118
+        $this->mountManager = $mountManager;
119
+        $this->groupManager = $groupManager;
120
+        $this->l = $l;
121
+        $this->factory = $factory;
122
+        $this->userManager = $userManager;
123
+        $this->rootFolder = $rootFolder;
124
+        $this->eventDispatcher = $eventDispatcher;
125
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
126
+    }
127
+
128
+    /**
129
+     * Convert from a full share id to a tuple (providerId, shareId)
130
+     *
131
+     * @param string $id
132
+     * @return string[]
133
+     */
134
+    private function splitFullId($id) {
135
+        return explode(':', $id, 2);
136
+    }
137
+
138
+    /**
139
+     * Verify if a password meets all requirements
140
+     *
141
+     * @param string $password
142
+     * @throws \Exception
143
+     */
144
+    protected function verifyPassword($password) {
145
+        if ($password === null) {
146
+            // No password is set, check if this is allowed.
147
+            if ($this->shareApiLinkEnforcePassword()) {
148
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
149
+            }
150
+
151
+            return;
152
+        }
153
+
154
+        // Let others verify the password
155
+        try {
156
+            $event = new GenericEvent($password);
157
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
158
+        } catch (HintException $e) {
159
+            throw new \Exception($e->getHint());
160
+        }
161
+    }
162
+
163
+    /**
164
+     * Check for generic requirements before creating a share
165
+     *
166
+     * @param \OCP\Share\IShare $share
167
+     * @throws \InvalidArgumentException
168
+     * @throws GenericShareException
169
+     */
170
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
171
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
172
+            // We expect a valid user as sharedWith for user shares
173
+            if (!$this->userManager->userExists($share->getSharedWith())) {
174
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
175
+            }
176
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
177
+            // We expect a valid group as sharedWith for group shares
178
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
179
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
180
+            }
181
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
182
+            if ($share->getSharedWith() !== null) {
183
+                throw new \InvalidArgumentException('SharedWith should be empty');
184
+            }
185
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
186
+            if ($share->getSharedWith() === null) {
187
+                throw new \InvalidArgumentException('SharedWith should not be empty');
188
+            }
189
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
190
+            if ($share->getSharedWith() === null) {
191
+                throw new \InvalidArgumentException('SharedWith should not be empty');
192
+            }
193
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
194
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
195
+            if ($circle === null) {
196
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
197
+            }
198
+        } else {
199
+            // We can't handle other types yet
200
+            throw new \InvalidArgumentException('unknown share type');
201
+        }
202
+
203
+        // Verify the initiator of the share is set
204
+        if ($share->getSharedBy() === null) {
205
+            throw new \InvalidArgumentException('SharedBy should be set');
206
+        }
207
+
208
+        // Cannot share with yourself
209
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
210
+            $share->getSharedWith() === $share->getSharedBy()) {
211
+            throw new \InvalidArgumentException('Can\'t share with yourself');
212
+        }
213
+
214
+        // The path should be set
215
+        if ($share->getNode() === null) {
216
+            throw new \InvalidArgumentException('Path should be set');
217
+        }
218
+
219
+        // And it should be a file or a folder
220
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
221
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
222
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
223
+        }
224
+
225
+        // And you can't share your rootfolder
226
+        if ($this->userManager->userExists($share->getSharedBy())) {
227
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
228
+        } else {
229
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
230
+        }
231
+        if ($sharedPath === $share->getNode()->getPath()) {
232
+            throw new \InvalidArgumentException('You can\'t share your root folder');
233
+        }
234
+
235
+        // Check if we actually have share permissions
236
+        if (!$share->getNode()->isShareable()) {
237
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
238
+            throw new GenericShareException($message_t, $message_t, 404);
239
+        }
240
+
241
+        // Permissions should be set
242
+        if ($share->getPermissions() === null) {
243
+            throw new \InvalidArgumentException('A share requires permissions');
244
+        }
245
+
246
+        /*
247 247
 		 * Quick fix for #23536
248 248
 		 * Non moveable mount points do not have update and delete permissions
249 249
 		 * while we 'most likely' do have that on the storage.
250 250
 		 */
251
-		$permissions = $share->getNode()->getPermissions();
252
-		$mount = $share->getNode()->getMountPoint();
253
-		if (!($mount instanceof MoveableMount)) {
254
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
255
-		}
256
-
257
-		// Check that we do not share with more permissions than we have
258
-		if ($share->getPermissions() & ~$permissions) {
259
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
260
-			throw new GenericShareException($message_t, $message_t, 404);
261
-		}
262
-
263
-
264
-		// Check that read permissions are always set
265
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
266
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
267
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
268
-			throw new \InvalidArgumentException('Shares need at least read permissions');
269
-		}
270
-
271
-		if ($share->getNode() instanceof \OCP\Files\File) {
272
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
273
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
274
-				throw new GenericShareException($message_t);
275
-			}
276
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
277
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
278
-				throw new GenericShareException($message_t);
279
-			}
280
-		}
281
-	}
282
-
283
-	/**
284
-	 * Validate if the expiration date fits the system settings
285
-	 *
286
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
287
-	 * @return \OCP\Share\IShare The modified share object
288
-	 * @throws GenericShareException
289
-	 * @throws \InvalidArgumentException
290
-	 * @throws \Exception
291
-	 */
292
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
293
-
294
-		$expirationDate = $share->getExpirationDate();
295
-
296
-		if ($expirationDate !== null) {
297
-			//Make sure the expiration date is a date
298
-			$expirationDate->setTime(0, 0, 0);
299
-
300
-			$date = new \DateTime();
301
-			$date->setTime(0, 0, 0);
302
-			if ($date >= $expirationDate) {
303
-				$message = $this->l->t('Expiration date is in the past');
304
-				throw new GenericShareException($message, $message, 404);
305
-			}
306
-		}
307
-
308
-		// If expiredate is empty set a default one if there is a default
309
-		$fullId = null;
310
-		try {
311
-			$fullId = $share->getFullId();
312
-		} catch (\UnexpectedValueException $e) {
313
-			// This is a new share
314
-		}
315
-
316
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
317
-			$expirationDate = new \DateTime();
318
-			$expirationDate->setTime(0,0,0);
319
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
320
-		}
321
-
322
-		// If we enforce the expiration date check that is does not exceed
323
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
324
-			if ($expirationDate === null) {
325
-				throw new \InvalidArgumentException('Expiration date is enforced');
326
-			}
327
-
328
-			$date = new \DateTime();
329
-			$date->setTime(0, 0, 0);
330
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
331
-			if ($date < $expirationDate) {
332
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
333
-				throw new GenericShareException($message, $message, 404);
334
-			}
335
-		}
336
-
337
-		$accepted = true;
338
-		$message = '';
339
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
340
-			'expirationDate' => &$expirationDate,
341
-			'accepted' => &$accepted,
342
-			'message' => &$message,
343
-			'passwordSet' => $share->getPassword() !== null,
344
-		]);
345
-
346
-		if (!$accepted) {
347
-			throw new \Exception($message);
348
-		}
349
-
350
-		$share->setExpirationDate($expirationDate);
351
-
352
-		return $share;
353
-	}
354
-
355
-	/**
356
-	 * Check for pre share requirements for user shares
357
-	 *
358
-	 * @param \OCP\Share\IShare $share
359
-	 * @throws \Exception
360
-	 */
361
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
362
-		// Check if we can share with group members only
363
-		if ($this->shareWithGroupMembersOnly()) {
364
-			$sharedBy = $this->userManager->get($share->getSharedBy());
365
-			$sharedWith = $this->userManager->get($share->getSharedWith());
366
-			// Verify we can share with this user
367
-			$groups = array_intersect(
368
-					$this->groupManager->getUserGroupIds($sharedBy),
369
-					$this->groupManager->getUserGroupIds($sharedWith)
370
-			);
371
-			if (empty($groups)) {
372
-				throw new \Exception('Only sharing with group members is allowed');
373
-			}
374
-		}
375
-
376
-		/*
251
+        $permissions = $share->getNode()->getPermissions();
252
+        $mount = $share->getNode()->getMountPoint();
253
+        if (!($mount instanceof MoveableMount)) {
254
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
255
+        }
256
+
257
+        // Check that we do not share with more permissions than we have
258
+        if ($share->getPermissions() & ~$permissions) {
259
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
260
+            throw new GenericShareException($message_t, $message_t, 404);
261
+        }
262
+
263
+
264
+        // Check that read permissions are always set
265
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
266
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
267
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
268
+            throw new \InvalidArgumentException('Shares need at least read permissions');
269
+        }
270
+
271
+        if ($share->getNode() instanceof \OCP\Files\File) {
272
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
273
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
274
+                throw new GenericShareException($message_t);
275
+            }
276
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
277
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
278
+                throw new GenericShareException($message_t);
279
+            }
280
+        }
281
+    }
282
+
283
+    /**
284
+     * Validate if the expiration date fits the system settings
285
+     *
286
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
287
+     * @return \OCP\Share\IShare The modified share object
288
+     * @throws GenericShareException
289
+     * @throws \InvalidArgumentException
290
+     * @throws \Exception
291
+     */
292
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
293
+
294
+        $expirationDate = $share->getExpirationDate();
295
+
296
+        if ($expirationDate !== null) {
297
+            //Make sure the expiration date is a date
298
+            $expirationDate->setTime(0, 0, 0);
299
+
300
+            $date = new \DateTime();
301
+            $date->setTime(0, 0, 0);
302
+            if ($date >= $expirationDate) {
303
+                $message = $this->l->t('Expiration date is in the past');
304
+                throw new GenericShareException($message, $message, 404);
305
+            }
306
+        }
307
+
308
+        // If expiredate is empty set a default one if there is a default
309
+        $fullId = null;
310
+        try {
311
+            $fullId = $share->getFullId();
312
+        } catch (\UnexpectedValueException $e) {
313
+            // This is a new share
314
+        }
315
+
316
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
317
+            $expirationDate = new \DateTime();
318
+            $expirationDate->setTime(0,0,0);
319
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
320
+        }
321
+
322
+        // If we enforce the expiration date check that is does not exceed
323
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
324
+            if ($expirationDate === null) {
325
+                throw new \InvalidArgumentException('Expiration date is enforced');
326
+            }
327
+
328
+            $date = new \DateTime();
329
+            $date->setTime(0, 0, 0);
330
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
331
+            if ($date < $expirationDate) {
332
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
333
+                throw new GenericShareException($message, $message, 404);
334
+            }
335
+        }
336
+
337
+        $accepted = true;
338
+        $message = '';
339
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
340
+            'expirationDate' => &$expirationDate,
341
+            'accepted' => &$accepted,
342
+            'message' => &$message,
343
+            'passwordSet' => $share->getPassword() !== null,
344
+        ]);
345
+
346
+        if (!$accepted) {
347
+            throw new \Exception($message);
348
+        }
349
+
350
+        $share->setExpirationDate($expirationDate);
351
+
352
+        return $share;
353
+    }
354
+
355
+    /**
356
+     * Check for pre share requirements for user shares
357
+     *
358
+     * @param \OCP\Share\IShare $share
359
+     * @throws \Exception
360
+     */
361
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
362
+        // Check if we can share with group members only
363
+        if ($this->shareWithGroupMembersOnly()) {
364
+            $sharedBy = $this->userManager->get($share->getSharedBy());
365
+            $sharedWith = $this->userManager->get($share->getSharedWith());
366
+            // Verify we can share with this user
367
+            $groups = array_intersect(
368
+                    $this->groupManager->getUserGroupIds($sharedBy),
369
+                    $this->groupManager->getUserGroupIds($sharedWith)
370
+            );
371
+            if (empty($groups)) {
372
+                throw new \Exception('Only sharing with group members is allowed');
373
+            }
374
+        }
375
+
376
+        /*
377 377
 		 * TODO: Could be costly, fix
378 378
 		 *
379 379
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
380 380
 		 */
381
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
382
-		$existingShares = $provider->getSharesByPath($share->getNode());
383
-		foreach($existingShares as $existingShare) {
384
-			// Ignore if it is the same share
385
-			try {
386
-				if ($existingShare->getFullId() === $share->getFullId()) {
387
-					continue;
388
-				}
389
-			} catch (\UnexpectedValueException $e) {
390
-				//Shares are not identical
391
-			}
392
-
393
-			// Identical share already existst
394
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
395
-				throw new \Exception('Path already shared with this user');
396
-			}
397
-
398
-			// The share is already shared with this user via a group share
399
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
400
-				$group = $this->groupManager->get($existingShare->getSharedWith());
401
-				if (!is_null($group)) {
402
-					$user = $this->userManager->get($share->getSharedWith());
403
-
404
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
405
-						throw new \Exception('Path already shared with this user');
406
-					}
407
-				}
408
-			}
409
-		}
410
-	}
411
-
412
-	/**
413
-	 * Check for pre share requirements for group shares
414
-	 *
415
-	 * @param \OCP\Share\IShare $share
416
-	 * @throws \Exception
417
-	 */
418
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
419
-		// Verify group shares are allowed
420
-		if (!$this->allowGroupSharing()) {
421
-			throw new \Exception('Group sharing is now allowed');
422
-		}
423
-
424
-		// Verify if the user can share with this group
425
-		if ($this->shareWithGroupMembersOnly()) {
426
-			$sharedBy = $this->userManager->get($share->getSharedBy());
427
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
428
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
429
-				throw new \Exception('Only sharing within your own groups is allowed');
430
-			}
431
-		}
432
-
433
-		/*
381
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
382
+        $existingShares = $provider->getSharesByPath($share->getNode());
383
+        foreach($existingShares as $existingShare) {
384
+            // Ignore if it is the same share
385
+            try {
386
+                if ($existingShare->getFullId() === $share->getFullId()) {
387
+                    continue;
388
+                }
389
+            } catch (\UnexpectedValueException $e) {
390
+                //Shares are not identical
391
+            }
392
+
393
+            // Identical share already existst
394
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
395
+                throw new \Exception('Path already shared with this user');
396
+            }
397
+
398
+            // The share is already shared with this user via a group share
399
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
400
+                $group = $this->groupManager->get($existingShare->getSharedWith());
401
+                if (!is_null($group)) {
402
+                    $user = $this->userManager->get($share->getSharedWith());
403
+
404
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
405
+                        throw new \Exception('Path already shared with this user');
406
+                    }
407
+                }
408
+            }
409
+        }
410
+    }
411
+
412
+    /**
413
+     * Check for pre share requirements for group shares
414
+     *
415
+     * @param \OCP\Share\IShare $share
416
+     * @throws \Exception
417
+     */
418
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
419
+        // Verify group shares are allowed
420
+        if (!$this->allowGroupSharing()) {
421
+            throw new \Exception('Group sharing is now allowed');
422
+        }
423
+
424
+        // Verify if the user can share with this group
425
+        if ($this->shareWithGroupMembersOnly()) {
426
+            $sharedBy = $this->userManager->get($share->getSharedBy());
427
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
428
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
429
+                throw new \Exception('Only sharing within your own groups is allowed');
430
+            }
431
+        }
432
+
433
+        /*
434 434
 		 * TODO: Could be costly, fix
435 435
 		 *
436 436
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
437 437
 		 */
438
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
439
-		$existingShares = $provider->getSharesByPath($share->getNode());
440
-		foreach($existingShares as $existingShare) {
441
-			try {
442
-				if ($existingShare->getFullId() === $share->getFullId()) {
443
-					continue;
444
-				}
445
-			} catch (\UnexpectedValueException $e) {
446
-				//It is a new share so just continue
447
-			}
448
-
449
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
450
-				throw new \Exception('Path already shared with this group');
451
-			}
452
-		}
453
-	}
454
-
455
-	/**
456
-	 * Check for pre share requirements for link shares
457
-	 *
458
-	 * @param \OCP\Share\IShare $share
459
-	 * @throws \Exception
460
-	 */
461
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
462
-		// Are link shares allowed?
463
-		if (!$this->shareApiAllowLinks()) {
464
-			throw new \Exception('Link sharing not allowed');
465
-		}
466
-
467
-		// Link shares by definition can't have share permissions
468
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
469
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
470
-		}
471
-
472
-		// Check if public upload is allowed
473
-		if (!$this->shareApiLinkAllowPublicUpload() &&
474
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
475
-			throw new \InvalidArgumentException('Public upload not allowed');
476
-		}
477
-	}
478
-
479
-	/**
480
-	 * To make sure we don't get invisible link shares we set the parent
481
-	 * of a link if it is a reshare. This is a quick word around
482
-	 * until we can properly display multiple link shares in the UI
483
-	 *
484
-	 * See: https://github.com/owncloud/core/issues/22295
485
-	 *
486
-	 * FIXME: Remove once multiple link shares can be properly displayed
487
-	 *
488
-	 * @param \OCP\Share\IShare $share
489
-	 */
490
-	protected function setLinkParent(\OCP\Share\IShare $share) {
491
-
492
-		// No sense in checking if the method is not there.
493
-		if (method_exists($share, 'setParent')) {
494
-			$storage = $share->getNode()->getStorage();
495
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
496
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
497
-				$share->setParent($storage->getShareId());
498
-			}
499
-		};
500
-	}
501
-
502
-	/**
503
-	 * @param File|Folder $path
504
-	 */
505
-	protected function pathCreateChecks($path) {
506
-		// Make sure that we do not share a path that contains a shared mountpoint
507
-		if ($path instanceof \OCP\Files\Folder) {
508
-			$mounts = $this->mountManager->findIn($path->getPath());
509
-			foreach($mounts as $mount) {
510
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
511
-					throw new \InvalidArgumentException('Path contains files shared with you');
512
-				}
513
-			}
514
-		}
515
-	}
516
-
517
-	/**
518
-	 * Check if the user that is sharing can actually share
519
-	 *
520
-	 * @param \OCP\Share\IShare $share
521
-	 * @throws \Exception
522
-	 */
523
-	protected function canShare(\OCP\Share\IShare $share) {
524
-		if (!$this->shareApiEnabled()) {
525
-			throw new \Exception('The share API is disabled');
526
-		}
527
-
528
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
529
-			throw new \Exception('You are not allowed to share');
530
-		}
531
-	}
532
-
533
-	/**
534
-	 * Share a path
535
-	 *
536
-	 * @param \OCP\Share\IShare $share
537
-	 * @return Share The share object
538
-	 * @throws \Exception
539
-	 *
540
-	 * TODO: handle link share permissions or check them
541
-	 */
542
-	public function createShare(\OCP\Share\IShare $share) {
543
-		$this->canShare($share);
544
-
545
-		$this->generalCreateChecks($share);
546
-
547
-		// Verify if there are any issues with the path
548
-		$this->pathCreateChecks($share->getNode());
549
-
550
-		/*
438
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
439
+        $existingShares = $provider->getSharesByPath($share->getNode());
440
+        foreach($existingShares as $existingShare) {
441
+            try {
442
+                if ($existingShare->getFullId() === $share->getFullId()) {
443
+                    continue;
444
+                }
445
+            } catch (\UnexpectedValueException $e) {
446
+                //It is a new share so just continue
447
+            }
448
+
449
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
450
+                throw new \Exception('Path already shared with this group');
451
+            }
452
+        }
453
+    }
454
+
455
+    /**
456
+     * Check for pre share requirements for link shares
457
+     *
458
+     * @param \OCP\Share\IShare $share
459
+     * @throws \Exception
460
+     */
461
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
462
+        // Are link shares allowed?
463
+        if (!$this->shareApiAllowLinks()) {
464
+            throw new \Exception('Link sharing not allowed');
465
+        }
466
+
467
+        // Link shares by definition can't have share permissions
468
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
469
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
470
+        }
471
+
472
+        // Check if public upload is allowed
473
+        if (!$this->shareApiLinkAllowPublicUpload() &&
474
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
475
+            throw new \InvalidArgumentException('Public upload not allowed');
476
+        }
477
+    }
478
+
479
+    /**
480
+     * To make sure we don't get invisible link shares we set the parent
481
+     * of a link if it is a reshare. This is a quick word around
482
+     * until we can properly display multiple link shares in the UI
483
+     *
484
+     * See: https://github.com/owncloud/core/issues/22295
485
+     *
486
+     * FIXME: Remove once multiple link shares can be properly displayed
487
+     *
488
+     * @param \OCP\Share\IShare $share
489
+     */
490
+    protected function setLinkParent(\OCP\Share\IShare $share) {
491
+
492
+        // No sense in checking if the method is not there.
493
+        if (method_exists($share, 'setParent')) {
494
+            $storage = $share->getNode()->getStorage();
495
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
496
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
497
+                $share->setParent($storage->getShareId());
498
+            }
499
+        };
500
+    }
501
+
502
+    /**
503
+     * @param File|Folder $path
504
+     */
505
+    protected function pathCreateChecks($path) {
506
+        // Make sure that we do not share a path that contains a shared mountpoint
507
+        if ($path instanceof \OCP\Files\Folder) {
508
+            $mounts = $this->mountManager->findIn($path->getPath());
509
+            foreach($mounts as $mount) {
510
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
511
+                    throw new \InvalidArgumentException('Path contains files shared with you');
512
+                }
513
+            }
514
+        }
515
+    }
516
+
517
+    /**
518
+     * Check if the user that is sharing can actually share
519
+     *
520
+     * @param \OCP\Share\IShare $share
521
+     * @throws \Exception
522
+     */
523
+    protected function canShare(\OCP\Share\IShare $share) {
524
+        if (!$this->shareApiEnabled()) {
525
+            throw new \Exception('The share API is disabled');
526
+        }
527
+
528
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
529
+            throw new \Exception('You are not allowed to share');
530
+        }
531
+    }
532
+
533
+    /**
534
+     * Share a path
535
+     *
536
+     * @param \OCP\Share\IShare $share
537
+     * @return Share The share object
538
+     * @throws \Exception
539
+     *
540
+     * TODO: handle link share permissions or check them
541
+     */
542
+    public function createShare(\OCP\Share\IShare $share) {
543
+        $this->canShare($share);
544
+
545
+        $this->generalCreateChecks($share);
546
+
547
+        // Verify if there are any issues with the path
548
+        $this->pathCreateChecks($share->getNode());
549
+
550
+        /*
551 551
 		 * On creation of a share the owner is always the owner of the path
552 552
 		 * Except for mounted federated shares.
553 553
 		 */
554
-		$storage = $share->getNode()->getStorage();
555
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
556
-			$parent = $share->getNode()->getParent();
557
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
558
-				$parent = $parent->getParent();
559
-			}
560
-			$share->setShareOwner($parent->getOwner()->getUID());
561
-		} else {
562
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
563
-		}
564
-
565
-		//Verify share type
566
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
567
-			$this->userCreateChecks($share);
568
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
569
-			$this->groupCreateChecks($share);
570
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
571
-			$this->linkCreateChecks($share);
572
-			$this->setLinkParent($share);
573
-
574
-			/*
554
+        $storage = $share->getNode()->getStorage();
555
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
556
+            $parent = $share->getNode()->getParent();
557
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
558
+                $parent = $parent->getParent();
559
+            }
560
+            $share->setShareOwner($parent->getOwner()->getUID());
561
+        } else {
562
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
563
+        }
564
+
565
+        //Verify share type
566
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
567
+            $this->userCreateChecks($share);
568
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
569
+            $this->groupCreateChecks($share);
570
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
571
+            $this->linkCreateChecks($share);
572
+            $this->setLinkParent($share);
573
+
574
+            /*
575 575
 			 * For now ignore a set token.
576 576
 			 */
577
-			$share->setToken(
578
-				$this->secureRandom->generate(
579
-					\OC\Share\Constants::TOKEN_LENGTH,
580
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
581
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
582
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
583
-				)
584
-			);
585
-
586
-			//Verify the expiration date
587
-			$this->validateExpirationDate($share);
588
-
589
-			//Verify the password
590
-			$this->verifyPassword($share->getPassword());
591
-
592
-			// If a password is set. Hash it!
593
-			if ($share->getPassword() !== null) {
594
-				$share->setPassword($this->hasher->hash($share->getPassword()));
595
-			}
596
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
597
-			$share->setToken(
598
-				$this->secureRandom->generate(
599
-					\OC\Share\Constants::TOKEN_LENGTH,
600
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
601
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
602
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
603
-				)
604
-			);
605
-		}
606
-
607
-		// Cannot share with the owner
608
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
609
-			$share->getSharedWith() === $share->getShareOwner()) {
610
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
611
-		}
612
-
613
-		// Generate the target
614
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
615
-		$target = \OC\Files\Filesystem::normalizePath($target);
616
-		$share->setTarget($target);
617
-
618
-		// Pre share hook
619
-		$run = true;
620
-		$error = '';
621
-		$preHookData = [
622
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
623
-			'itemSource' => $share->getNode()->getId(),
624
-			'shareType' => $share->getShareType(),
625
-			'uidOwner' => $share->getSharedBy(),
626
-			'permissions' => $share->getPermissions(),
627
-			'fileSource' => $share->getNode()->getId(),
628
-			'expiration' => $share->getExpirationDate(),
629
-			'token' => $share->getToken(),
630
-			'itemTarget' => $share->getTarget(),
631
-			'shareWith' => $share->getSharedWith(),
632
-			'run' => &$run,
633
-			'error' => &$error,
634
-		];
635
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
636
-
637
-		if ($run === false) {
638
-			throw new \Exception($error);
639
-		}
640
-
641
-		$oldShare = $share;
642
-		$provider = $this->factory->getProviderForType($share->getShareType());
643
-		$share = $provider->create($share);
644
-		//reuse the node we already have
645
-		$share->setNode($oldShare->getNode());
646
-
647
-		// Post share hook
648
-		$postHookData = [
649
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
650
-			'itemSource' => $share->getNode()->getId(),
651
-			'shareType' => $share->getShareType(),
652
-			'uidOwner' => $share->getSharedBy(),
653
-			'permissions' => $share->getPermissions(),
654
-			'fileSource' => $share->getNode()->getId(),
655
-			'expiration' => $share->getExpirationDate(),
656
-			'token' => $share->getToken(),
657
-			'id' => $share->getId(),
658
-			'shareWith' => $share->getSharedWith(),
659
-			'itemTarget' => $share->getTarget(),
660
-			'fileTarget' => $share->getTarget(),
661
-		];
662
-
663
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
664
-
665
-		return $share;
666
-	}
667
-
668
-	/**
669
-	 * Update a share
670
-	 *
671
-	 * @param \OCP\Share\IShare $share
672
-	 * @return \OCP\Share\IShare The share object
673
-	 * @throws \InvalidArgumentException
674
-	 */
675
-	public function updateShare(\OCP\Share\IShare $share) {
676
-		$expirationDateUpdated = false;
677
-
678
-		$this->canShare($share);
679
-
680
-		try {
681
-			$originalShare = $this->getShareById($share->getFullId());
682
-		} catch (\UnexpectedValueException $e) {
683
-			throw new \InvalidArgumentException('Share does not have a full id');
684
-		}
685
-
686
-		// We can't change the share type!
687
-		if ($share->getShareType() !== $originalShare->getShareType()) {
688
-			throw new \InvalidArgumentException('Can\'t change share type');
689
-		}
690
-
691
-		// We can only change the recipient on user shares
692
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
693
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
694
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
695
-		}
696
-
697
-		// Cannot share with the owner
698
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
699
-			$share->getSharedWith() === $share->getShareOwner()) {
700
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
701
-		}
702
-
703
-		$this->generalCreateChecks($share);
704
-
705
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
706
-			$this->userCreateChecks($share);
707
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
708
-			$this->groupCreateChecks($share);
709
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
710
-			$this->linkCreateChecks($share);
711
-
712
-			// Password updated.
713
-			if ($share->getPassword() !== $originalShare->getPassword()) {
714
-				//Verify the password
715
-				$this->verifyPassword($share->getPassword());
716
-
717
-				// If a password is set. Hash it!
718
-				if ($share->getPassword() !== null) {
719
-					$share->setPassword($this->hasher->hash($share->getPassword()));
720
-				}
721
-			}
722
-
723
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
724
-				//Verify the expiration date
725
-				$this->validateExpirationDate($share);
726
-				$expirationDateUpdated = true;
727
-			}
728
-		}
729
-
730
-		$this->pathCreateChecks($share->getNode());
731
-
732
-		// Now update the share!
733
-		$provider = $this->factory->getProviderForType($share->getShareType());
734
-		$share = $provider->update($share);
735
-
736
-		if ($expirationDateUpdated === true) {
737
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
738
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
739
-				'itemSource' => $share->getNode()->getId(),
740
-				'date' => $share->getExpirationDate(),
741
-				'uidOwner' => $share->getSharedBy(),
742
-			]);
743
-		}
744
-
745
-		if ($share->getPassword() !== $originalShare->getPassword()) {
746
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
747
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
748
-				'itemSource' => $share->getNode()->getId(),
749
-				'uidOwner' => $share->getSharedBy(),
750
-				'token' => $share->getToken(),
751
-				'disabled' => is_null($share->getPassword()),
752
-			]);
753
-		}
754
-
755
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
756
-			if ($this->userManager->userExists($share->getShareOwner())) {
757
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
758
-			} else {
759
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
760
-			}
761
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
762
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
763
-				'itemSource' => $share->getNode()->getId(),
764
-				'shareType' => $share->getShareType(),
765
-				'shareWith' => $share->getSharedWith(),
766
-				'uidOwner' => $share->getSharedBy(),
767
-				'permissions' => $share->getPermissions(),
768
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
769
-			));
770
-		}
771
-
772
-		return $share;
773
-	}
774
-
775
-	/**
776
-	 * Delete all the children of this share
777
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
778
-	 *
779
-	 * @param \OCP\Share\IShare $share
780
-	 * @return \OCP\Share\IShare[] List of deleted shares
781
-	 */
782
-	protected function deleteChildren(\OCP\Share\IShare $share) {
783
-		$deletedShares = [];
784
-
785
-		$provider = $this->factory->getProviderForType($share->getShareType());
786
-
787
-		foreach ($provider->getChildren($share) as $child) {
788
-			$deletedChildren = $this->deleteChildren($child);
789
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
790
-
791
-			$provider->delete($child);
792
-			$deletedShares[] = $child;
793
-		}
794
-
795
-		return $deletedShares;
796
-	}
797
-
798
-	/**
799
-	 * Delete a share
800
-	 *
801
-	 * @param \OCP\Share\IShare $share
802
-	 * @throws ShareNotFound
803
-	 * @throws \InvalidArgumentException
804
-	 */
805
-	public function deleteShare(\OCP\Share\IShare $share) {
806
-
807
-		try {
808
-			$share->getFullId();
809
-		} catch (\UnexpectedValueException $e) {
810
-			throw new \InvalidArgumentException('Share does not have a full id');
811
-		}
812
-
813
-		$formatHookParams = function(\OCP\Share\IShare $share) {
814
-			// Prepare hook
815
-			$shareType = $share->getShareType();
816
-			$sharedWith = '';
817
-			if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
818
-				$sharedWith = $share->getSharedWith();
819
-			} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
820
-				$sharedWith = $share->getSharedWith();
821
-			} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
822
-				$sharedWith = $share->getSharedWith();
823
-			}
824
-
825
-			$hookParams = [
826
-				'id'         => $share->getId(),
827
-				'itemType'   => $share->getNodeType(),
828
-				'itemSource' => $share->getNodeId(),
829
-				'shareType'  => $shareType,
830
-				'shareWith'  => $sharedWith,
831
-				'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
832
-				'uidOwner'   => $share->getSharedBy(),
833
-				'fileSource' => $share->getNodeId(),
834
-				'fileTarget' => $share->getTarget()
835
-			];
836
-			return $hookParams;
837
-		};
838
-
839
-		$hookParams = $formatHookParams($share);
840
-
841
-		// Emit pre-hook
842
-		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
843
-
844
-		// Get all children and delete them as well
845
-		$deletedShares = $this->deleteChildren($share);
846
-
847
-		// Do the actual delete
848
-		$provider = $this->factory->getProviderForType($share->getShareType());
849
-		$provider->delete($share);
850
-
851
-		// All the deleted shares caused by this delete
852
-		$deletedShares[] = $share;
853
-
854
-		//Format hook info
855
-		$formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
856
-			return $formatHookParams($share);
857
-		}, $deletedShares);
858
-
859
-		$hookParams['deletedShares'] = $formattedDeletedShares;
860
-
861
-		// Emit post hook
862
-		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
863
-	}
864
-
865
-
866
-	/**
867
-	 * Unshare a file as the recipient.
868
-	 * This can be different from a regular delete for example when one of
869
-	 * the users in a groups deletes that share. But the provider should
870
-	 * handle this.
871
-	 *
872
-	 * @param \OCP\Share\IShare $share
873
-	 * @param string $recipientId
874
-	 */
875
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
876
-		list($providerId, ) = $this->splitFullId($share->getFullId());
877
-		$provider = $this->factory->getProvider($providerId);
878
-
879
-		$provider->deleteFromSelf($share, $recipientId);
880
-	}
881
-
882
-	/**
883
-	 * @inheritdoc
884
-	 */
885
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
886
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
887
-			throw new \InvalidArgumentException('Can\'t change target of link share');
888
-		}
889
-
890
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
891
-			throw new \InvalidArgumentException('Invalid recipient');
892
-		}
893
-
894
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
895
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
896
-			if (is_null($sharedWith)) {
897
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
898
-			}
899
-			$recipient = $this->userManager->get($recipientId);
900
-			if (!$sharedWith->inGroup($recipient)) {
901
-				throw new \InvalidArgumentException('Invalid recipient');
902
-			}
903
-		}
904
-
905
-		list($providerId, ) = $this->splitFullId($share->getFullId());
906
-		$provider = $this->factory->getProvider($providerId);
907
-
908
-		$provider->move($share, $recipientId);
909
-	}
910
-
911
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
912
-		$providers = $this->factory->getAllProviders();
913
-
914
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
915
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
916
-			foreach ($newShares as $fid => $data) {
917
-				if (!isset($shares[$fid])) {
918
-					$shares[$fid] = [];
919
-				}
920
-
921
-				$shares[$fid] = array_merge($shares[$fid], $data);
922
-			}
923
-			return $shares;
924
-		}, []);
925
-	}
926
-
927
-	/**
928
-	 * @inheritdoc
929
-	 */
930
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
931
-		if ($path !== null &&
932
-				!($path instanceof \OCP\Files\File) &&
933
-				!($path instanceof \OCP\Files\Folder)) {
934
-			throw new \InvalidArgumentException('invalid path');
935
-		}
936
-
937
-		try {
938
-			$provider = $this->factory->getProviderForType($shareType);
939
-		} catch (ProviderException $e) {
940
-			return [];
941
-		}
942
-
943
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
944
-
945
-		/*
577
+            $share->setToken(
578
+                $this->secureRandom->generate(
579
+                    \OC\Share\Constants::TOKEN_LENGTH,
580
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
581
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
582
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
583
+                )
584
+            );
585
+
586
+            //Verify the expiration date
587
+            $this->validateExpirationDate($share);
588
+
589
+            //Verify the password
590
+            $this->verifyPassword($share->getPassword());
591
+
592
+            // If a password is set. Hash it!
593
+            if ($share->getPassword() !== null) {
594
+                $share->setPassword($this->hasher->hash($share->getPassword()));
595
+            }
596
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
597
+            $share->setToken(
598
+                $this->secureRandom->generate(
599
+                    \OC\Share\Constants::TOKEN_LENGTH,
600
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
601
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
602
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
603
+                )
604
+            );
605
+        }
606
+
607
+        // Cannot share with the owner
608
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
609
+            $share->getSharedWith() === $share->getShareOwner()) {
610
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
611
+        }
612
+
613
+        // Generate the target
614
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
615
+        $target = \OC\Files\Filesystem::normalizePath($target);
616
+        $share->setTarget($target);
617
+
618
+        // Pre share hook
619
+        $run = true;
620
+        $error = '';
621
+        $preHookData = [
622
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
623
+            'itemSource' => $share->getNode()->getId(),
624
+            'shareType' => $share->getShareType(),
625
+            'uidOwner' => $share->getSharedBy(),
626
+            'permissions' => $share->getPermissions(),
627
+            'fileSource' => $share->getNode()->getId(),
628
+            'expiration' => $share->getExpirationDate(),
629
+            'token' => $share->getToken(),
630
+            'itemTarget' => $share->getTarget(),
631
+            'shareWith' => $share->getSharedWith(),
632
+            'run' => &$run,
633
+            'error' => &$error,
634
+        ];
635
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
636
+
637
+        if ($run === false) {
638
+            throw new \Exception($error);
639
+        }
640
+
641
+        $oldShare = $share;
642
+        $provider = $this->factory->getProviderForType($share->getShareType());
643
+        $share = $provider->create($share);
644
+        //reuse the node we already have
645
+        $share->setNode($oldShare->getNode());
646
+
647
+        // Post share hook
648
+        $postHookData = [
649
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
650
+            'itemSource' => $share->getNode()->getId(),
651
+            'shareType' => $share->getShareType(),
652
+            'uidOwner' => $share->getSharedBy(),
653
+            'permissions' => $share->getPermissions(),
654
+            'fileSource' => $share->getNode()->getId(),
655
+            'expiration' => $share->getExpirationDate(),
656
+            'token' => $share->getToken(),
657
+            'id' => $share->getId(),
658
+            'shareWith' => $share->getSharedWith(),
659
+            'itemTarget' => $share->getTarget(),
660
+            'fileTarget' => $share->getTarget(),
661
+        ];
662
+
663
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
664
+
665
+        return $share;
666
+    }
667
+
668
+    /**
669
+     * Update a share
670
+     *
671
+     * @param \OCP\Share\IShare $share
672
+     * @return \OCP\Share\IShare The share object
673
+     * @throws \InvalidArgumentException
674
+     */
675
+    public function updateShare(\OCP\Share\IShare $share) {
676
+        $expirationDateUpdated = false;
677
+
678
+        $this->canShare($share);
679
+
680
+        try {
681
+            $originalShare = $this->getShareById($share->getFullId());
682
+        } catch (\UnexpectedValueException $e) {
683
+            throw new \InvalidArgumentException('Share does not have a full id');
684
+        }
685
+
686
+        // We can't change the share type!
687
+        if ($share->getShareType() !== $originalShare->getShareType()) {
688
+            throw new \InvalidArgumentException('Can\'t change share type');
689
+        }
690
+
691
+        // We can only change the recipient on user shares
692
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
693
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
694
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
695
+        }
696
+
697
+        // Cannot share with the owner
698
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
699
+            $share->getSharedWith() === $share->getShareOwner()) {
700
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
701
+        }
702
+
703
+        $this->generalCreateChecks($share);
704
+
705
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
706
+            $this->userCreateChecks($share);
707
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
708
+            $this->groupCreateChecks($share);
709
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
710
+            $this->linkCreateChecks($share);
711
+
712
+            // Password updated.
713
+            if ($share->getPassword() !== $originalShare->getPassword()) {
714
+                //Verify the password
715
+                $this->verifyPassword($share->getPassword());
716
+
717
+                // If a password is set. Hash it!
718
+                if ($share->getPassword() !== null) {
719
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
720
+                }
721
+            }
722
+
723
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
724
+                //Verify the expiration date
725
+                $this->validateExpirationDate($share);
726
+                $expirationDateUpdated = true;
727
+            }
728
+        }
729
+
730
+        $this->pathCreateChecks($share->getNode());
731
+
732
+        // Now update the share!
733
+        $provider = $this->factory->getProviderForType($share->getShareType());
734
+        $share = $provider->update($share);
735
+
736
+        if ($expirationDateUpdated === true) {
737
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
738
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
739
+                'itemSource' => $share->getNode()->getId(),
740
+                'date' => $share->getExpirationDate(),
741
+                'uidOwner' => $share->getSharedBy(),
742
+            ]);
743
+        }
744
+
745
+        if ($share->getPassword() !== $originalShare->getPassword()) {
746
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
747
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
748
+                'itemSource' => $share->getNode()->getId(),
749
+                'uidOwner' => $share->getSharedBy(),
750
+                'token' => $share->getToken(),
751
+                'disabled' => is_null($share->getPassword()),
752
+            ]);
753
+        }
754
+
755
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
756
+            if ($this->userManager->userExists($share->getShareOwner())) {
757
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
758
+            } else {
759
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
760
+            }
761
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
762
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
763
+                'itemSource' => $share->getNode()->getId(),
764
+                'shareType' => $share->getShareType(),
765
+                'shareWith' => $share->getSharedWith(),
766
+                'uidOwner' => $share->getSharedBy(),
767
+                'permissions' => $share->getPermissions(),
768
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
769
+            ));
770
+        }
771
+
772
+        return $share;
773
+    }
774
+
775
+    /**
776
+     * Delete all the children of this share
777
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
778
+     *
779
+     * @param \OCP\Share\IShare $share
780
+     * @return \OCP\Share\IShare[] List of deleted shares
781
+     */
782
+    protected function deleteChildren(\OCP\Share\IShare $share) {
783
+        $deletedShares = [];
784
+
785
+        $provider = $this->factory->getProviderForType($share->getShareType());
786
+
787
+        foreach ($provider->getChildren($share) as $child) {
788
+            $deletedChildren = $this->deleteChildren($child);
789
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
790
+
791
+            $provider->delete($child);
792
+            $deletedShares[] = $child;
793
+        }
794
+
795
+        return $deletedShares;
796
+    }
797
+
798
+    /**
799
+     * Delete a share
800
+     *
801
+     * @param \OCP\Share\IShare $share
802
+     * @throws ShareNotFound
803
+     * @throws \InvalidArgumentException
804
+     */
805
+    public function deleteShare(\OCP\Share\IShare $share) {
806
+
807
+        try {
808
+            $share->getFullId();
809
+        } catch (\UnexpectedValueException $e) {
810
+            throw new \InvalidArgumentException('Share does not have a full id');
811
+        }
812
+
813
+        $formatHookParams = function(\OCP\Share\IShare $share) {
814
+            // Prepare hook
815
+            $shareType = $share->getShareType();
816
+            $sharedWith = '';
817
+            if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
818
+                $sharedWith = $share->getSharedWith();
819
+            } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
820
+                $sharedWith = $share->getSharedWith();
821
+            } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
822
+                $sharedWith = $share->getSharedWith();
823
+            }
824
+
825
+            $hookParams = [
826
+                'id'         => $share->getId(),
827
+                'itemType'   => $share->getNodeType(),
828
+                'itemSource' => $share->getNodeId(),
829
+                'shareType'  => $shareType,
830
+                'shareWith'  => $sharedWith,
831
+                'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
832
+                'uidOwner'   => $share->getSharedBy(),
833
+                'fileSource' => $share->getNodeId(),
834
+                'fileTarget' => $share->getTarget()
835
+            ];
836
+            return $hookParams;
837
+        };
838
+
839
+        $hookParams = $formatHookParams($share);
840
+
841
+        // Emit pre-hook
842
+        \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
843
+
844
+        // Get all children and delete them as well
845
+        $deletedShares = $this->deleteChildren($share);
846
+
847
+        // Do the actual delete
848
+        $provider = $this->factory->getProviderForType($share->getShareType());
849
+        $provider->delete($share);
850
+
851
+        // All the deleted shares caused by this delete
852
+        $deletedShares[] = $share;
853
+
854
+        //Format hook info
855
+        $formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
856
+            return $formatHookParams($share);
857
+        }, $deletedShares);
858
+
859
+        $hookParams['deletedShares'] = $formattedDeletedShares;
860
+
861
+        // Emit post hook
862
+        \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
863
+    }
864
+
865
+
866
+    /**
867
+     * Unshare a file as the recipient.
868
+     * This can be different from a regular delete for example when one of
869
+     * the users in a groups deletes that share. But the provider should
870
+     * handle this.
871
+     *
872
+     * @param \OCP\Share\IShare $share
873
+     * @param string $recipientId
874
+     */
875
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
876
+        list($providerId, ) = $this->splitFullId($share->getFullId());
877
+        $provider = $this->factory->getProvider($providerId);
878
+
879
+        $provider->deleteFromSelf($share, $recipientId);
880
+    }
881
+
882
+    /**
883
+     * @inheritdoc
884
+     */
885
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
886
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
887
+            throw new \InvalidArgumentException('Can\'t change target of link share');
888
+        }
889
+
890
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
891
+            throw new \InvalidArgumentException('Invalid recipient');
892
+        }
893
+
894
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
895
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
896
+            if (is_null($sharedWith)) {
897
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
898
+            }
899
+            $recipient = $this->userManager->get($recipientId);
900
+            if (!$sharedWith->inGroup($recipient)) {
901
+                throw new \InvalidArgumentException('Invalid recipient');
902
+            }
903
+        }
904
+
905
+        list($providerId, ) = $this->splitFullId($share->getFullId());
906
+        $provider = $this->factory->getProvider($providerId);
907
+
908
+        $provider->move($share, $recipientId);
909
+    }
910
+
911
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
912
+        $providers = $this->factory->getAllProviders();
913
+
914
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
915
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
916
+            foreach ($newShares as $fid => $data) {
917
+                if (!isset($shares[$fid])) {
918
+                    $shares[$fid] = [];
919
+                }
920
+
921
+                $shares[$fid] = array_merge($shares[$fid], $data);
922
+            }
923
+            return $shares;
924
+        }, []);
925
+    }
926
+
927
+    /**
928
+     * @inheritdoc
929
+     */
930
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
931
+        if ($path !== null &&
932
+                !($path instanceof \OCP\Files\File) &&
933
+                !($path instanceof \OCP\Files\Folder)) {
934
+            throw new \InvalidArgumentException('invalid path');
935
+        }
936
+
937
+        try {
938
+            $provider = $this->factory->getProviderForType($shareType);
939
+        } catch (ProviderException $e) {
940
+            return [];
941
+        }
942
+
943
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
944
+
945
+        /*
946 946
 		 * Work around so we don't return expired shares but still follow
947 947
 		 * proper pagination.
948 948
 		 */
949
-		if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
950
-			$shares2 = [];
951
-			$today = new \DateTime();
952
-
953
-			while(true) {
954
-				$added = 0;
955
-				foreach ($shares as $share) {
956
-					// Check if the share is expired and if so delete it
957
-					if ($share->getExpirationDate() !== null &&
958
-						$share->getExpirationDate() <= $today
959
-					) {
960
-						try {
961
-							$this->deleteShare($share);
962
-						} catch (NotFoundException $e) {
963
-							//Ignore since this basically means the share is deleted
964
-						}
965
-						continue;
966
-					}
967
-					$added++;
968
-					$shares2[] = $share;
969
-
970
-					if (count($shares2) === $limit) {
971
-						break;
972
-					}
973
-				}
974
-
975
-				if (count($shares2) === $limit) {
976
-					break;
977
-				}
978
-
979
-				// If there was no limit on the select we are done
980
-				if ($limit === -1) {
981
-					break;
982
-				}
983
-
984
-				$offset += $added;
985
-
986
-				// Fetch again $limit shares
987
-				$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
988
-
989
-				// No more shares means we are done
990
-				if (empty($shares)) {
991
-					break;
992
-				}
993
-			}
994
-
995
-			$shares = $shares2;
996
-		}
997
-
998
-		return $shares;
999
-	}
1000
-
1001
-	/**
1002
-	 * @inheritdoc
1003
-	 */
1004
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1005
-		try {
1006
-			$provider = $this->factory->getProviderForType($shareType);
1007
-		} catch (ProviderException $e) {
1008
-			return [];
1009
-		}
1010
-
1011
-		return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1012
-	}
1013
-
1014
-	/**
1015
-	 * @inheritdoc
1016
-	 */
1017
-	public function getShareById($id, $recipient = null) {
1018
-		if ($id === null) {
1019
-			throw new ShareNotFound();
1020
-		}
1021
-
1022
-		list($providerId, $id) = $this->splitFullId($id);
1023
-
1024
-		try {
1025
-			$provider = $this->factory->getProvider($providerId);
1026
-		} catch (ProviderException $e) {
1027
-			throw new ShareNotFound();
1028
-		}
1029
-
1030
-		$share = $provider->getShareById($id, $recipient);
1031
-
1032
-		// Validate link shares expiration date
1033
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1034
-			$share->getExpirationDate() !== null &&
1035
-			$share->getExpirationDate() <= new \DateTime()) {
1036
-			$this->deleteShare($share);
1037
-			throw new ShareNotFound();
1038
-		}
1039
-
1040
-		return $share;
1041
-	}
1042
-
1043
-	/**
1044
-	 * Get all the shares for a given path
1045
-	 *
1046
-	 * @param \OCP\Files\Node $path
1047
-	 * @param int $page
1048
-	 * @param int $perPage
1049
-	 *
1050
-	 * @return Share[]
1051
-	 */
1052
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1053
-		return [];
1054
-	}
1055
-
1056
-	/**
1057
-	 * Get the share by token possible with password
1058
-	 *
1059
-	 * @param string $token
1060
-	 * @return Share
1061
-	 *
1062
-	 * @throws ShareNotFound
1063
-	 */
1064
-	public function getShareByToken($token) {
1065
-		$share = null;
1066
-		try {
1067
-			if($this->shareApiAllowLinks()) {
1068
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1069
-				$share = $provider->getShareByToken($token);
1070
-			}
1071
-		} catch (ProviderException $e) {
1072
-		} catch (ShareNotFound $e) {
1073
-		}
1074
-
1075
-
1076
-		// If it is not a link share try to fetch a federated share by token
1077
-		if ($share === null) {
1078
-			try {
1079
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1080
-				$share = $provider->getShareByToken($token);
1081
-			} catch (ProviderException $e) {
1082
-			} catch (ShareNotFound $e) {
1083
-			}
1084
-		}
1085
-
1086
-		// If it is not a link share try to fetch a mail share by token
1087
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1088
-			try {
1089
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1090
-				$share = $provider->getShareByToken($token);
1091
-			} catch (ProviderException $e) {
1092
-			} catch (ShareNotFound $e) {
1093
-			}
1094
-		}
1095
-
1096
-		if ($share === null) {
1097
-			throw new ShareNotFound();
1098
-		}
1099
-
1100
-		if ($share->getExpirationDate() !== null &&
1101
-			$share->getExpirationDate() <= new \DateTime()) {
1102
-			$this->deleteShare($share);
1103
-			throw new ShareNotFound();
1104
-		}
1105
-
1106
-		/*
949
+        if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
950
+            $shares2 = [];
951
+            $today = new \DateTime();
952
+
953
+            while(true) {
954
+                $added = 0;
955
+                foreach ($shares as $share) {
956
+                    // Check if the share is expired and if so delete it
957
+                    if ($share->getExpirationDate() !== null &&
958
+                        $share->getExpirationDate() <= $today
959
+                    ) {
960
+                        try {
961
+                            $this->deleteShare($share);
962
+                        } catch (NotFoundException $e) {
963
+                            //Ignore since this basically means the share is deleted
964
+                        }
965
+                        continue;
966
+                    }
967
+                    $added++;
968
+                    $shares2[] = $share;
969
+
970
+                    if (count($shares2) === $limit) {
971
+                        break;
972
+                    }
973
+                }
974
+
975
+                if (count($shares2) === $limit) {
976
+                    break;
977
+                }
978
+
979
+                // If there was no limit on the select we are done
980
+                if ($limit === -1) {
981
+                    break;
982
+                }
983
+
984
+                $offset += $added;
985
+
986
+                // Fetch again $limit shares
987
+                $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
988
+
989
+                // No more shares means we are done
990
+                if (empty($shares)) {
991
+                    break;
992
+                }
993
+            }
994
+
995
+            $shares = $shares2;
996
+        }
997
+
998
+        return $shares;
999
+    }
1000
+
1001
+    /**
1002
+     * @inheritdoc
1003
+     */
1004
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1005
+        try {
1006
+            $provider = $this->factory->getProviderForType($shareType);
1007
+        } catch (ProviderException $e) {
1008
+            return [];
1009
+        }
1010
+
1011
+        return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1012
+    }
1013
+
1014
+    /**
1015
+     * @inheritdoc
1016
+     */
1017
+    public function getShareById($id, $recipient = null) {
1018
+        if ($id === null) {
1019
+            throw new ShareNotFound();
1020
+        }
1021
+
1022
+        list($providerId, $id) = $this->splitFullId($id);
1023
+
1024
+        try {
1025
+            $provider = $this->factory->getProvider($providerId);
1026
+        } catch (ProviderException $e) {
1027
+            throw new ShareNotFound();
1028
+        }
1029
+
1030
+        $share = $provider->getShareById($id, $recipient);
1031
+
1032
+        // Validate link shares expiration date
1033
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1034
+            $share->getExpirationDate() !== null &&
1035
+            $share->getExpirationDate() <= new \DateTime()) {
1036
+            $this->deleteShare($share);
1037
+            throw new ShareNotFound();
1038
+        }
1039
+
1040
+        return $share;
1041
+    }
1042
+
1043
+    /**
1044
+     * Get all the shares for a given path
1045
+     *
1046
+     * @param \OCP\Files\Node $path
1047
+     * @param int $page
1048
+     * @param int $perPage
1049
+     *
1050
+     * @return Share[]
1051
+     */
1052
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1053
+        return [];
1054
+    }
1055
+
1056
+    /**
1057
+     * Get the share by token possible with password
1058
+     *
1059
+     * @param string $token
1060
+     * @return Share
1061
+     *
1062
+     * @throws ShareNotFound
1063
+     */
1064
+    public function getShareByToken($token) {
1065
+        $share = null;
1066
+        try {
1067
+            if($this->shareApiAllowLinks()) {
1068
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1069
+                $share = $provider->getShareByToken($token);
1070
+            }
1071
+        } catch (ProviderException $e) {
1072
+        } catch (ShareNotFound $e) {
1073
+        }
1074
+
1075
+
1076
+        // If it is not a link share try to fetch a federated share by token
1077
+        if ($share === null) {
1078
+            try {
1079
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1080
+                $share = $provider->getShareByToken($token);
1081
+            } catch (ProviderException $e) {
1082
+            } catch (ShareNotFound $e) {
1083
+            }
1084
+        }
1085
+
1086
+        // If it is not a link share try to fetch a mail share by token
1087
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1088
+            try {
1089
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1090
+                $share = $provider->getShareByToken($token);
1091
+            } catch (ProviderException $e) {
1092
+            } catch (ShareNotFound $e) {
1093
+            }
1094
+        }
1095
+
1096
+        if ($share === null) {
1097
+            throw new ShareNotFound();
1098
+        }
1099
+
1100
+        if ($share->getExpirationDate() !== null &&
1101
+            $share->getExpirationDate() <= new \DateTime()) {
1102
+            $this->deleteShare($share);
1103
+            throw new ShareNotFound();
1104
+        }
1105
+
1106
+        /*
1107 1107
 		 * Reduce the permissions for link shares if public upload is not enabled
1108 1108
 		 */
1109
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1110
-			!$this->shareApiLinkAllowPublicUpload()) {
1111
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1112
-		}
1113
-
1114
-		return $share;
1115
-	}
1116
-
1117
-	/**
1118
-	 * Verify the password of a public share
1119
-	 *
1120
-	 * @param \OCP\Share\IShare $share
1121
-	 * @param string $password
1122
-	 * @return bool
1123
-	 */
1124
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1125
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
1126
-			//TODO maybe exception?
1127
-			return false;
1128
-		}
1129
-
1130
-		if ($password === null || $share->getPassword() === null) {
1131
-			return false;
1132
-		}
1133
-
1134
-		$newHash = '';
1135
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1136
-			return false;
1137
-		}
1138
-
1139
-		if (!empty($newHash)) {
1140
-			$share->setPassword($newHash);
1141
-			$provider = $this->factory->getProviderForType($share->getShareType());
1142
-			$provider->update($share);
1143
-		}
1144
-
1145
-		return true;
1146
-	}
1147
-
1148
-	/**
1149
-	 * @inheritdoc
1150
-	 */
1151
-	public function userDeleted($uid) {
1152
-		$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];
1153
-
1154
-		foreach ($types as $type) {
1155
-			try {
1156
-				$provider = $this->factory->getProviderForType($type);
1157
-			} catch (ProviderException $e) {
1158
-				continue;
1159
-			}
1160
-			$provider->userDeleted($uid, $type);
1161
-		}
1162
-	}
1163
-
1164
-	/**
1165
-	 * @inheritdoc
1166
-	 */
1167
-	public function groupDeleted($gid) {
1168
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1169
-		$provider->groupDeleted($gid);
1170
-	}
1171
-
1172
-	/**
1173
-	 * @inheritdoc
1174
-	 */
1175
-	public function userDeletedFromGroup($uid, $gid) {
1176
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1177
-		$provider->userDeletedFromGroup($uid, $gid);
1178
-	}
1179
-
1180
-	/**
1181
-	 * Get access list to a path. This means
1182
-	 * all the users and groups that can access a given path.
1183
-	 *
1184
-	 * Consider:
1185
-	 * -root
1186
-	 * |-folder1
1187
-	 *  |-folder2
1188
-	 *   |-fileA
1189
-	 *
1190
-	 * fileA is shared with user1
1191
-	 * folder2 is shared with group2
1192
-	 * folder1 is shared with user2
1193
-	 *
1194
-	 * Then the access list will to '/folder1/folder2/fileA' is:
1195
-	 * [
1196
-	 * 	'users' => ['user1', 'user2'],
1197
-	 *  'groups' => ['group2']
1198
-	 * ]
1199
-	 *
1200
-	 * This is required for encryption
1201
-	 *
1202
-	 * @param \OCP\Files\Node $path
1203
-	 */
1204
-	public function getAccessList(\OCP\Files\Node $path) {
1205
-	}
1206
-
1207
-	/**
1208
-	 * Create a new share
1209
-	 * @return \OCP\Share\IShare;
1210
-	 */
1211
-	public function newShare() {
1212
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1213
-	}
1214
-
1215
-	/**
1216
-	 * Is the share API enabled
1217
-	 *
1218
-	 * @return bool
1219
-	 */
1220
-	public function shareApiEnabled() {
1221
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1222
-	}
1223
-
1224
-	/**
1225
-	 * Is public link sharing enabled
1226
-	 *
1227
-	 * @return bool
1228
-	 */
1229
-	public function shareApiAllowLinks() {
1230
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1231
-	}
1232
-
1233
-	/**
1234
-	 * Is password on public link requires
1235
-	 *
1236
-	 * @return bool
1237
-	 */
1238
-	public function shareApiLinkEnforcePassword() {
1239
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1240
-	}
1241
-
1242
-	/**
1243
-	 * Is default expire date enabled
1244
-	 *
1245
-	 * @return bool
1246
-	 */
1247
-	public function shareApiLinkDefaultExpireDate() {
1248
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1249
-	}
1250
-
1251
-	/**
1252
-	 * Is default expire date enforced
1253
-	 *`
1254
-	 * @return bool
1255
-	 */
1256
-	public function shareApiLinkDefaultExpireDateEnforced() {
1257
-		return $this->shareApiLinkDefaultExpireDate() &&
1258
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1259
-	}
1260
-
1261
-	/**
1262
-	 * Number of default expire days
1263
-	 *shareApiLinkAllowPublicUpload
1264
-	 * @return int
1265
-	 */
1266
-	public function shareApiLinkDefaultExpireDays() {
1267
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1268
-	}
1269
-
1270
-	/**
1271
-	 * Allow public upload on link shares
1272
-	 *
1273
-	 * @return bool
1274
-	 */
1275
-	public function shareApiLinkAllowPublicUpload() {
1276
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1277
-	}
1278
-
1279
-	/**
1280
-	 * check if user can only share with group members
1281
-	 * @return bool
1282
-	 */
1283
-	public function shareWithGroupMembersOnly() {
1284
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1285
-	}
1286
-
1287
-	/**
1288
-	 * Check if users can share with groups
1289
-	 * @return bool
1290
-	 */
1291
-	public function allowGroupSharing() {
1292
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1293
-	}
1294
-
1295
-	/**
1296
-	 * Copied from \OC_Util::isSharingDisabledForUser
1297
-	 *
1298
-	 * TODO: Deprecate fuction from OC_Util
1299
-	 *
1300
-	 * @param string $userId
1301
-	 * @return bool
1302
-	 */
1303
-	public function sharingDisabledForUser($userId) {
1304
-		if ($userId === null) {
1305
-			return false;
1306
-		}
1307
-
1308
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1309
-			return $this->sharingDisabledForUsersCache[$userId];
1310
-		}
1311
-
1312
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1313
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1314
-			$excludedGroups = json_decode($groupsList);
1315
-			if (is_null($excludedGroups)) {
1316
-				$excludedGroups = explode(',', $groupsList);
1317
-				$newValue = json_encode($excludedGroups);
1318
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1319
-			}
1320
-			$user = $this->userManager->get($userId);
1321
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1322
-			if (!empty($usersGroups)) {
1323
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1324
-				// if the user is only in groups which are disabled for sharing then
1325
-				// sharing is also disabled for the user
1326
-				if (empty($remainingGroups)) {
1327
-					$this->sharingDisabledForUsersCache[$userId] = true;
1328
-					return true;
1329
-				}
1330
-			}
1331
-		}
1332
-
1333
-		$this->sharingDisabledForUsersCache[$userId] = false;
1334
-		return false;
1335
-	}
1336
-
1337
-	/**
1338
-	 * @inheritdoc
1339
-	 */
1340
-	public function outgoingServer2ServerSharesAllowed() {
1341
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1342
-	}
1343
-
1344
-	/**
1345
-	 * @inheritdoc
1346
-	 */
1347
-	public function shareProviderExists($shareType) {
1348
-		try {
1349
-			$this->factory->getProviderForType($shareType);
1350
-		} catch (ProviderException $e) {
1351
-			return false;
1352
-		}
1353
-
1354
-		return true;
1355
-	}
1109
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1110
+            !$this->shareApiLinkAllowPublicUpload()) {
1111
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1112
+        }
1113
+
1114
+        return $share;
1115
+    }
1116
+
1117
+    /**
1118
+     * Verify the password of a public share
1119
+     *
1120
+     * @param \OCP\Share\IShare $share
1121
+     * @param string $password
1122
+     * @return bool
1123
+     */
1124
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1125
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
1126
+            //TODO maybe exception?
1127
+            return false;
1128
+        }
1129
+
1130
+        if ($password === null || $share->getPassword() === null) {
1131
+            return false;
1132
+        }
1133
+
1134
+        $newHash = '';
1135
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1136
+            return false;
1137
+        }
1138
+
1139
+        if (!empty($newHash)) {
1140
+            $share->setPassword($newHash);
1141
+            $provider = $this->factory->getProviderForType($share->getShareType());
1142
+            $provider->update($share);
1143
+        }
1144
+
1145
+        return true;
1146
+    }
1147
+
1148
+    /**
1149
+     * @inheritdoc
1150
+     */
1151
+    public function userDeleted($uid) {
1152
+        $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];
1153
+
1154
+        foreach ($types as $type) {
1155
+            try {
1156
+                $provider = $this->factory->getProviderForType($type);
1157
+            } catch (ProviderException $e) {
1158
+                continue;
1159
+            }
1160
+            $provider->userDeleted($uid, $type);
1161
+        }
1162
+    }
1163
+
1164
+    /**
1165
+     * @inheritdoc
1166
+     */
1167
+    public function groupDeleted($gid) {
1168
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1169
+        $provider->groupDeleted($gid);
1170
+    }
1171
+
1172
+    /**
1173
+     * @inheritdoc
1174
+     */
1175
+    public function userDeletedFromGroup($uid, $gid) {
1176
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1177
+        $provider->userDeletedFromGroup($uid, $gid);
1178
+    }
1179
+
1180
+    /**
1181
+     * Get access list to a path. This means
1182
+     * all the users and groups that can access a given path.
1183
+     *
1184
+     * Consider:
1185
+     * -root
1186
+     * |-folder1
1187
+     *  |-folder2
1188
+     *   |-fileA
1189
+     *
1190
+     * fileA is shared with user1
1191
+     * folder2 is shared with group2
1192
+     * folder1 is shared with user2
1193
+     *
1194
+     * Then the access list will to '/folder1/folder2/fileA' is:
1195
+     * [
1196
+     * 	'users' => ['user1', 'user2'],
1197
+     *  'groups' => ['group2']
1198
+     * ]
1199
+     *
1200
+     * This is required for encryption
1201
+     *
1202
+     * @param \OCP\Files\Node $path
1203
+     */
1204
+    public function getAccessList(\OCP\Files\Node $path) {
1205
+    }
1206
+
1207
+    /**
1208
+     * Create a new share
1209
+     * @return \OCP\Share\IShare;
1210
+     */
1211
+    public function newShare() {
1212
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1213
+    }
1214
+
1215
+    /**
1216
+     * Is the share API enabled
1217
+     *
1218
+     * @return bool
1219
+     */
1220
+    public function shareApiEnabled() {
1221
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1222
+    }
1223
+
1224
+    /**
1225
+     * Is public link sharing enabled
1226
+     *
1227
+     * @return bool
1228
+     */
1229
+    public function shareApiAllowLinks() {
1230
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1231
+    }
1232
+
1233
+    /**
1234
+     * Is password on public link requires
1235
+     *
1236
+     * @return bool
1237
+     */
1238
+    public function shareApiLinkEnforcePassword() {
1239
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1240
+    }
1241
+
1242
+    /**
1243
+     * Is default expire date enabled
1244
+     *
1245
+     * @return bool
1246
+     */
1247
+    public function shareApiLinkDefaultExpireDate() {
1248
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1249
+    }
1250
+
1251
+    /**
1252
+     * Is default expire date enforced
1253
+     *`
1254
+     * @return bool
1255
+     */
1256
+    public function shareApiLinkDefaultExpireDateEnforced() {
1257
+        return $this->shareApiLinkDefaultExpireDate() &&
1258
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1259
+    }
1260
+
1261
+    /**
1262
+     * Number of default expire days
1263
+     *shareApiLinkAllowPublicUpload
1264
+     * @return int
1265
+     */
1266
+    public function shareApiLinkDefaultExpireDays() {
1267
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1268
+    }
1269
+
1270
+    /**
1271
+     * Allow public upload on link shares
1272
+     *
1273
+     * @return bool
1274
+     */
1275
+    public function shareApiLinkAllowPublicUpload() {
1276
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1277
+    }
1278
+
1279
+    /**
1280
+     * check if user can only share with group members
1281
+     * @return bool
1282
+     */
1283
+    public function shareWithGroupMembersOnly() {
1284
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1285
+    }
1286
+
1287
+    /**
1288
+     * Check if users can share with groups
1289
+     * @return bool
1290
+     */
1291
+    public function allowGroupSharing() {
1292
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1293
+    }
1294
+
1295
+    /**
1296
+     * Copied from \OC_Util::isSharingDisabledForUser
1297
+     *
1298
+     * TODO: Deprecate fuction from OC_Util
1299
+     *
1300
+     * @param string $userId
1301
+     * @return bool
1302
+     */
1303
+    public function sharingDisabledForUser($userId) {
1304
+        if ($userId === null) {
1305
+            return false;
1306
+        }
1307
+
1308
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1309
+            return $this->sharingDisabledForUsersCache[$userId];
1310
+        }
1311
+
1312
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1313
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1314
+            $excludedGroups = json_decode($groupsList);
1315
+            if (is_null($excludedGroups)) {
1316
+                $excludedGroups = explode(',', $groupsList);
1317
+                $newValue = json_encode($excludedGroups);
1318
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1319
+            }
1320
+            $user = $this->userManager->get($userId);
1321
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1322
+            if (!empty($usersGroups)) {
1323
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1324
+                // if the user is only in groups which are disabled for sharing then
1325
+                // sharing is also disabled for the user
1326
+                if (empty($remainingGroups)) {
1327
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1328
+                    return true;
1329
+                }
1330
+            }
1331
+        }
1332
+
1333
+        $this->sharingDisabledForUsersCache[$userId] = false;
1334
+        return false;
1335
+    }
1336
+
1337
+    /**
1338
+     * @inheritdoc
1339
+     */
1340
+    public function outgoingServer2ServerSharesAllowed() {
1341
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1342
+    }
1343
+
1344
+    /**
1345
+     * @inheritdoc
1346
+     */
1347
+    public function shareProviderExists($shareType) {
1348
+        try {
1349
+            $this->factory->getProviderForType($shareType);
1350
+        } catch (ProviderException $e) {
1351
+            return false;
1352
+        }
1353
+
1354
+        return true;
1355
+    }
1356 1356
 
1357 1357
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 2 patches
Indentation   +987 added lines, -987 removed lines patch added patch discarded remove patch
@@ -47,1024 +47,1024 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('share_with', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->execute();
206
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
-			$qb = $this->dbConn->getQueryBuilder();
208
-			$qb->update('share')
209
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->execute();
216
-
217
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->execute();
206
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
207
+            $qb = $this->dbConn->getQueryBuilder();
208
+            $qb->update('share')
209
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
210
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
211
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
212
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
213
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
214
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->execute();
216
+
217
+            /*
218 218
 			 * Update all user defined group shares
219 219
 			 */
220
-			$qb = $this->dbConn->getQueryBuilder();
221
-			$qb->update('share')
222
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
223
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
224
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
225
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
226
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
227
-				->execute();
228
-
229
-			/*
220
+            $qb = $this->dbConn->getQueryBuilder();
221
+            $qb->update('share')
222
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
223
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
224
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
225
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
226
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
227
+                ->execute();
228
+
229
+            /*
230 230
 			 * Now update the permissions for all children that have not set it to 0
231 231
 			 */
232
-			$qb = $this->dbConn->getQueryBuilder();
233
-			$qb->update('share')
234
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
235
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
236
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
237
-				->execute();
238
-
239
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
240
-			$qb = $this->dbConn->getQueryBuilder();
241
-			$qb->update('share')
242
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
243
-				->set('share_with', $qb->createNamedParameter($share->getPassword()))
244
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
245
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
246
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
247
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
248
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
249
-				->set('token', $qb->createNamedParameter($share->getToken()))
250
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
251
-				->execute();
252
-		}
253
-
254
-		return $share;
255
-	}
256
-
257
-	/**
258
-	 * Get all children of this share
259
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
260
-	 *
261
-	 * @param \OCP\Share\IShare $parent
262
-	 * @return \OCP\Share\IShare[]
263
-	 */
264
-	public function getChildren(\OCP\Share\IShare $parent) {
265
-		$children = [];
266
-
267
-		$qb = $this->dbConn->getQueryBuilder();
268
-		$qb->select('*')
269
-			->from('share')
270
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
271
-			->andWhere(
272
-				$qb->expr()->in(
273
-					'share_type',
274
-					$qb->createNamedParameter([
275
-						\OCP\Share::SHARE_TYPE_USER,
276
-						\OCP\Share::SHARE_TYPE_GROUP,
277
-						\OCP\Share::SHARE_TYPE_LINK,
278
-					], IQueryBuilder::PARAM_INT_ARRAY)
279
-				)
280
-			)
281
-			->andWhere($qb->expr()->orX(
282
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
283
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
284
-			))
285
-			->orderBy('id');
286
-
287
-		$cursor = $qb->execute();
288
-		while($data = $cursor->fetch()) {
289
-			$children[] = $this->createShare($data);
290
-		}
291
-		$cursor->closeCursor();
292
-
293
-		return $children;
294
-	}
295
-
296
-	/**
297
-	 * Delete a share
298
-	 *
299
-	 * @param \OCP\Share\IShare $share
300
-	 */
301
-	public function delete(\OCP\Share\IShare $share) {
302
-		$qb = $this->dbConn->getQueryBuilder();
303
-		$qb->delete('share')
304
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
305
-
306
-		/*
232
+            $qb = $this->dbConn->getQueryBuilder();
233
+            $qb->update('share')
234
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
235
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
236
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
237
+                ->execute();
238
+
239
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
240
+            $qb = $this->dbConn->getQueryBuilder();
241
+            $qb->update('share')
242
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
243
+                ->set('share_with', $qb->createNamedParameter($share->getPassword()))
244
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
245
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
246
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
247
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
248
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
249
+                ->set('token', $qb->createNamedParameter($share->getToken()))
250
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
251
+                ->execute();
252
+        }
253
+
254
+        return $share;
255
+    }
256
+
257
+    /**
258
+     * Get all children of this share
259
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
260
+     *
261
+     * @param \OCP\Share\IShare $parent
262
+     * @return \OCP\Share\IShare[]
263
+     */
264
+    public function getChildren(\OCP\Share\IShare $parent) {
265
+        $children = [];
266
+
267
+        $qb = $this->dbConn->getQueryBuilder();
268
+        $qb->select('*')
269
+            ->from('share')
270
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
271
+            ->andWhere(
272
+                $qb->expr()->in(
273
+                    'share_type',
274
+                    $qb->createNamedParameter([
275
+                        \OCP\Share::SHARE_TYPE_USER,
276
+                        \OCP\Share::SHARE_TYPE_GROUP,
277
+                        \OCP\Share::SHARE_TYPE_LINK,
278
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
279
+                )
280
+            )
281
+            ->andWhere($qb->expr()->orX(
282
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
283
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
284
+            ))
285
+            ->orderBy('id');
286
+
287
+        $cursor = $qb->execute();
288
+        while($data = $cursor->fetch()) {
289
+            $children[] = $this->createShare($data);
290
+        }
291
+        $cursor->closeCursor();
292
+
293
+        return $children;
294
+    }
295
+
296
+    /**
297
+     * Delete a share
298
+     *
299
+     * @param \OCP\Share\IShare $share
300
+     */
301
+    public function delete(\OCP\Share\IShare $share) {
302
+        $qb = $this->dbConn->getQueryBuilder();
303
+        $qb->delete('share')
304
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
305
+
306
+        /*
307 307
 		 * If the share is a group share delete all possible
308 308
 		 * user defined groups shares.
309 309
 		 */
310
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
311
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
312
-		}
313
-
314
-		$qb->execute();
315
-	}
316
-
317
-	/**
318
-	 * Unshare a share from the recipient. If this is a group share
319
-	 * this means we need a special entry in the share db.
320
-	 *
321
-	 * @param \OCP\Share\IShare $share
322
-	 * @param string $recipient UserId of recipient
323
-	 * @throws BackendError
324
-	 * @throws ProviderException
325
-	 */
326
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
327
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
328
-
329
-			$group = $this->groupManager->get($share->getSharedWith());
330
-			$user = $this->userManager->get($recipient);
331
-
332
-			if (is_null($group)) {
333
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
334
-			}
335
-
336
-			if (!$group->inGroup($user)) {
337
-				throw new ProviderException('Recipient not in receiving group');
338
-			}
339
-
340
-			// Try to fetch user specific share
341
-			$qb = $this->dbConn->getQueryBuilder();
342
-			$stmt = $qb->select('*')
343
-				->from('share')
344
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
345
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
346
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
347
-				->andWhere($qb->expr()->orX(
348
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
349
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
350
-				))
351
-				->execute();
352
-
353
-			$data = $stmt->fetch();
354
-
355
-			/*
310
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
311
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
312
+        }
313
+
314
+        $qb->execute();
315
+    }
316
+
317
+    /**
318
+     * Unshare a share from the recipient. If this is a group share
319
+     * this means we need a special entry in the share db.
320
+     *
321
+     * @param \OCP\Share\IShare $share
322
+     * @param string $recipient UserId of recipient
323
+     * @throws BackendError
324
+     * @throws ProviderException
325
+     */
326
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
327
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
328
+
329
+            $group = $this->groupManager->get($share->getSharedWith());
330
+            $user = $this->userManager->get($recipient);
331
+
332
+            if (is_null($group)) {
333
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
334
+            }
335
+
336
+            if (!$group->inGroup($user)) {
337
+                throw new ProviderException('Recipient not in receiving group');
338
+            }
339
+
340
+            // Try to fetch user specific share
341
+            $qb = $this->dbConn->getQueryBuilder();
342
+            $stmt = $qb->select('*')
343
+                ->from('share')
344
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
345
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
346
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
347
+                ->andWhere($qb->expr()->orX(
348
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
349
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
350
+                ))
351
+                ->execute();
352
+
353
+            $data = $stmt->fetch();
354
+
355
+            /*
356 356
 			 * Check if there already is a user specific group share.
357 357
 			 * If there is update it (if required).
358 358
 			 */
359
-			if ($data === false) {
360
-				$qb = $this->dbConn->getQueryBuilder();
361
-
362
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
363
-
364
-				//Insert new share
365
-				$qb->insert('share')
366
-					->values([
367
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
368
-						'share_with' => $qb->createNamedParameter($recipient),
369
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
370
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
371
-						'parent' => $qb->createNamedParameter($share->getId()),
372
-						'item_type' => $qb->createNamedParameter($type),
373
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
374
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
375
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
376
-						'permissions' => $qb->createNamedParameter(0),
377
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
378
-					])->execute();
379
-
380
-			} else if ($data['permissions'] !== 0) {
381
-
382
-				// Update existing usergroup share
383
-				$qb = $this->dbConn->getQueryBuilder();
384
-				$qb->update('share')
385
-					->set('permissions', $qb->createNamedParameter(0))
386
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
387
-					->execute();
388
-			}
389
-
390
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
391
-
392
-			if ($share->getSharedWith() !== $recipient) {
393
-				throw new ProviderException('Recipient does not match');
394
-			}
395
-
396
-			// We can just delete user and link shares
397
-			$this->delete($share);
398
-		} else {
399
-			throw new ProviderException('Invalid shareType');
400
-		}
401
-	}
402
-
403
-	/**
404
-	 * @inheritdoc
405
-	 */
406
-	public function move(\OCP\Share\IShare $share, $recipient) {
407
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
408
-			// Just update the target
409
-			$qb = $this->dbConn->getQueryBuilder();
410
-			$qb->update('share')
411
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
412
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
413
-				->execute();
414
-
415
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
416
-
417
-			// Check if there is a usergroup share
418
-			$qb = $this->dbConn->getQueryBuilder();
419
-			$stmt = $qb->select('id')
420
-				->from('share')
421
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
422
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
423
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
424
-				->andWhere($qb->expr()->orX(
425
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
426
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
427
-				))
428
-				->setMaxResults(1)
429
-				->execute();
430
-
431
-			$data = $stmt->fetch();
432
-			$stmt->closeCursor();
433
-
434
-			if ($data === false) {
435
-				// No usergroup share yet. Create one.
436
-				$qb = $this->dbConn->getQueryBuilder();
437
-				$qb->insert('share')
438
-					->values([
439
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
440
-						'share_with' => $qb->createNamedParameter($recipient),
441
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
442
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
443
-						'parent' => $qb->createNamedParameter($share->getId()),
444
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
445
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
446
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
447
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
448
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
449
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
450
-					])->execute();
451
-			} else {
452
-				// Already a usergroup share. Update it.
453
-				$qb = $this->dbConn->getQueryBuilder();
454
-				$qb->update('share')
455
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
456
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
457
-					->execute();
458
-			}
459
-		}
460
-
461
-		return $share;
462
-	}
463
-
464
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
465
-		$qb = $this->dbConn->getQueryBuilder();
466
-		$qb->select('*')
467
-			->from('share', 's')
468
-			->andWhere($qb->expr()->orX(
469
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
470
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
471
-			));
472
-
473
-		$qb->andWhere($qb->expr()->orX(
474
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
475
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
476
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
477
-		));
478
-
479
-		/**
480
-		 * Reshares for this user are shares where they are the owner.
481
-		 */
482
-		if ($reshares === false) {
483
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
484
-		} else {
485
-			$qb->andWhere(
486
-				$qb->expr()->orX(
487
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
488
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
489
-				)
490
-			);
491
-		}
492
-
493
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
494
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495
-
496
-		$qb->orderBy('id');
497
-
498
-		$cursor = $qb->execute();
499
-		$shares = [];
500
-		while ($data = $cursor->fetch()) {
501
-			$shares[$data['fileid']][] = $this->createShare($data);
502
-		}
503
-		$cursor->closeCursor();
504
-
505
-		return $shares;
506
-	}
507
-
508
-	/**
509
-	 * @inheritdoc
510
-	 */
511
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
512
-		$qb = $this->dbConn->getQueryBuilder();
513
-		$qb->select('*')
514
-			->from('share')
515
-			->andWhere($qb->expr()->orX(
516
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
517
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
518
-			));
519
-
520
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
521
-
522
-		/**
523
-		 * Reshares for this user are shares where they are the owner.
524
-		 */
525
-		if ($reshares === false) {
526
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
527
-		} else {
528
-			$qb->andWhere(
529
-				$qb->expr()->orX(
530
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
531
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
532
-				)
533
-			);
534
-		}
535
-
536
-		if ($node !== null) {
537
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
538
-		}
539
-
540
-		if ($limit !== -1) {
541
-			$qb->setMaxResults($limit);
542
-		}
543
-
544
-		$qb->setFirstResult($offset);
545
-		$qb->orderBy('id');
546
-
547
-		$cursor = $qb->execute();
548
-		$shares = [];
549
-		while($data = $cursor->fetch()) {
550
-			$shares[] = $this->createShare($data);
551
-		}
552
-		$cursor->closeCursor();
553
-
554
-		return $shares;
555
-	}
556
-
557
-	/**
558
-	 * @inheritdoc
559
-	 */
560
-	public function getShareById($id, $recipientId = null) {
561
-		$qb = $this->dbConn->getQueryBuilder();
562
-
563
-		$qb->select('*')
564
-			->from('share')
565
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
566
-			->andWhere(
567
-				$qb->expr()->in(
568
-					'share_type',
569
-					$qb->createNamedParameter([
570
-						\OCP\Share::SHARE_TYPE_USER,
571
-						\OCP\Share::SHARE_TYPE_GROUP,
572
-						\OCP\Share::SHARE_TYPE_LINK,
573
-					], IQueryBuilder::PARAM_INT_ARRAY)
574
-				)
575
-			)
576
-			->andWhere($qb->expr()->orX(
577
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
578
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
579
-			));
580
-
581
-		$cursor = $qb->execute();
582
-		$data = $cursor->fetch();
583
-		$cursor->closeCursor();
584
-
585
-		if ($data === false) {
586
-			throw new ShareNotFound();
587
-		}
588
-
589
-		try {
590
-			$share = $this->createShare($data);
591
-		} catch (InvalidShare $e) {
592
-			throw new ShareNotFound();
593
-		}
594
-
595
-		// If the recipient is set for a group share resolve to that user
596
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
597
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
598
-		}
599
-
600
-		return $share;
601
-	}
602
-
603
-	/**
604
-	 * Get shares for a given path
605
-	 *
606
-	 * @param \OCP\Files\Node $path
607
-	 * @return \OCP\Share\IShare[]
608
-	 */
609
-	public function getSharesByPath(Node $path) {
610
-		$qb = $this->dbConn->getQueryBuilder();
611
-
612
-		$cursor = $qb->select('*')
613
-			->from('share')
614
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
615
-			->andWhere(
616
-				$qb->expr()->orX(
617
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
618
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
619
-				)
620
-			)
621
-			->andWhere($qb->expr()->orX(
622
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
623
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
624
-			))
625
-			->execute();
626
-
627
-		$shares = [];
628
-		while($data = $cursor->fetch()) {
629
-			$shares[] = $this->createShare($data);
630
-		}
631
-		$cursor->closeCursor();
632
-
633
-		return $shares;
634
-	}
635
-
636
-	/**
637
-	 * Returns whether the given database result can be interpreted as
638
-	 * a share with accessible file (not trashed, not deleted)
639
-	 */
640
-	private function isAccessibleResult($data) {
641
-		// exclude shares leading to deleted file entries
642
-		if ($data['fileid'] === null) {
643
-			return false;
644
-		}
645
-
646
-		// exclude shares leading to trashbin on home storages
647
-		$pathSections = explode('/', $data['path'], 2);
648
-		// FIXME: would not detect rare md5'd home storage case properly
649
-		if ($pathSections[0] !== 'files' 
650
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
651
-			return false;
652
-		}
653
-		return true;
654
-	}
655
-
656
-	/**
657
-	 * @inheritdoc
658
-	 */
659
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
660
-		/** @var Share[] $shares */
661
-		$shares = [];
662
-
663
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
664
-			//Get shares directly with this user
665
-			$qb = $this->dbConn->getQueryBuilder();
666
-			$qb->select('s.*',
667
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
668
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
669
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
670
-			)
671
-				->selectAlias('st.id', 'storage_string_id')
672
-				->from('share', 's')
673
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
674
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
675
-
676
-			// Order by id
677
-			$qb->orderBy('s.id');
678
-
679
-			// Set limit and offset
680
-			if ($limit !== -1) {
681
-				$qb->setMaxResults($limit);
682
-			}
683
-			$qb->setFirstResult($offset);
684
-
685
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
686
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
687
-				->andWhere($qb->expr()->orX(
688
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
689
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
690
-				));
691
-
692
-			// Filter by node if provided
693
-			if ($node !== null) {
694
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
695
-			}
696
-
697
-			$cursor = $qb->execute();
698
-
699
-			while($data = $cursor->fetch()) {
700
-				if ($this->isAccessibleResult($data)) {
701
-					$shares[] = $this->createShare($data);
702
-				}
703
-			}
704
-			$cursor->closeCursor();
705
-
706
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
707
-			$user = $this->userManager->get($userId);
708
-			$allGroups = $this->groupManager->getUserGroups($user);
709
-
710
-			/** @var Share[] $shares2 */
711
-			$shares2 = [];
712
-
713
-			$start = 0;
714
-			while(true) {
715
-				$groups = array_slice($allGroups, $start, 100);
716
-				$start += 100;
717
-
718
-				if ($groups === []) {
719
-					break;
720
-				}
721
-
722
-				$qb = $this->dbConn->getQueryBuilder();
723
-				$qb->select('s.*',
724
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
725
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
726
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
727
-				)
728
-					->selectAlias('st.id', 'storage_string_id')
729
-					->from('share', 's')
730
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
731
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
732
-					->orderBy('s.id')
733
-					->setFirstResult(0);
734
-
735
-				if ($limit !== -1) {
736
-					$qb->setMaxResults($limit - count($shares));
737
-				}
738
-
739
-				// Filter by node if provided
740
-				if ($node !== null) {
741
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
742
-				}
743
-
744
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
745
-
746
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
747
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
748
-						$groups,
749
-						IQueryBuilder::PARAM_STR_ARRAY
750
-					)))
751
-					->andWhere($qb->expr()->orX(
752
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
753
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
754
-					));
755
-
756
-				$cursor = $qb->execute();
757
-				while($data = $cursor->fetch()) {
758
-					if ($offset > 0) {
759
-						$offset--;
760
-						continue;
761
-					}
762
-
763
-					if ($this->isAccessibleResult($data)) {
764
-						$shares2[] = $this->createShare($data);
765
-					}
766
-				}
767
-				$cursor->closeCursor();
768
-			}
769
-
770
-			/*
359
+            if ($data === false) {
360
+                $qb = $this->dbConn->getQueryBuilder();
361
+
362
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
363
+
364
+                //Insert new share
365
+                $qb->insert('share')
366
+                    ->values([
367
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
368
+                        'share_with' => $qb->createNamedParameter($recipient),
369
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
370
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
371
+                        'parent' => $qb->createNamedParameter($share->getId()),
372
+                        'item_type' => $qb->createNamedParameter($type),
373
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
374
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
375
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
376
+                        'permissions' => $qb->createNamedParameter(0),
377
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
378
+                    ])->execute();
379
+
380
+            } else if ($data['permissions'] !== 0) {
381
+
382
+                // Update existing usergroup share
383
+                $qb = $this->dbConn->getQueryBuilder();
384
+                $qb->update('share')
385
+                    ->set('permissions', $qb->createNamedParameter(0))
386
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
387
+                    ->execute();
388
+            }
389
+
390
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
391
+
392
+            if ($share->getSharedWith() !== $recipient) {
393
+                throw new ProviderException('Recipient does not match');
394
+            }
395
+
396
+            // We can just delete user and link shares
397
+            $this->delete($share);
398
+        } else {
399
+            throw new ProviderException('Invalid shareType');
400
+        }
401
+    }
402
+
403
+    /**
404
+     * @inheritdoc
405
+     */
406
+    public function move(\OCP\Share\IShare $share, $recipient) {
407
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
408
+            // Just update the target
409
+            $qb = $this->dbConn->getQueryBuilder();
410
+            $qb->update('share')
411
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
412
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
413
+                ->execute();
414
+
415
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
416
+
417
+            // Check if there is a usergroup share
418
+            $qb = $this->dbConn->getQueryBuilder();
419
+            $stmt = $qb->select('id')
420
+                ->from('share')
421
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
422
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
423
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
424
+                ->andWhere($qb->expr()->orX(
425
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
426
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
427
+                ))
428
+                ->setMaxResults(1)
429
+                ->execute();
430
+
431
+            $data = $stmt->fetch();
432
+            $stmt->closeCursor();
433
+
434
+            if ($data === false) {
435
+                // No usergroup share yet. Create one.
436
+                $qb = $this->dbConn->getQueryBuilder();
437
+                $qb->insert('share')
438
+                    ->values([
439
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
440
+                        'share_with' => $qb->createNamedParameter($recipient),
441
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
442
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
443
+                        'parent' => $qb->createNamedParameter($share->getId()),
444
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
445
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
446
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
447
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
448
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
449
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
450
+                    ])->execute();
451
+            } else {
452
+                // Already a usergroup share. Update it.
453
+                $qb = $this->dbConn->getQueryBuilder();
454
+                $qb->update('share')
455
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
456
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
457
+                    ->execute();
458
+            }
459
+        }
460
+
461
+        return $share;
462
+    }
463
+
464
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
465
+        $qb = $this->dbConn->getQueryBuilder();
466
+        $qb->select('*')
467
+            ->from('share', 's')
468
+            ->andWhere($qb->expr()->orX(
469
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
470
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
471
+            ));
472
+
473
+        $qb->andWhere($qb->expr()->orX(
474
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
475
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
476
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
477
+        ));
478
+
479
+        /**
480
+         * Reshares for this user are shares where they are the owner.
481
+         */
482
+        if ($reshares === false) {
483
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
484
+        } else {
485
+            $qb->andWhere(
486
+                $qb->expr()->orX(
487
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
488
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
489
+                )
490
+            );
491
+        }
492
+
493
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
494
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495
+
496
+        $qb->orderBy('id');
497
+
498
+        $cursor = $qb->execute();
499
+        $shares = [];
500
+        while ($data = $cursor->fetch()) {
501
+            $shares[$data['fileid']][] = $this->createShare($data);
502
+        }
503
+        $cursor->closeCursor();
504
+
505
+        return $shares;
506
+    }
507
+
508
+    /**
509
+     * @inheritdoc
510
+     */
511
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
512
+        $qb = $this->dbConn->getQueryBuilder();
513
+        $qb->select('*')
514
+            ->from('share')
515
+            ->andWhere($qb->expr()->orX(
516
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
517
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
518
+            ));
519
+
520
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
521
+
522
+        /**
523
+         * Reshares for this user are shares where they are the owner.
524
+         */
525
+        if ($reshares === false) {
526
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
527
+        } else {
528
+            $qb->andWhere(
529
+                $qb->expr()->orX(
530
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
531
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
532
+                )
533
+            );
534
+        }
535
+
536
+        if ($node !== null) {
537
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
538
+        }
539
+
540
+        if ($limit !== -1) {
541
+            $qb->setMaxResults($limit);
542
+        }
543
+
544
+        $qb->setFirstResult($offset);
545
+        $qb->orderBy('id');
546
+
547
+        $cursor = $qb->execute();
548
+        $shares = [];
549
+        while($data = $cursor->fetch()) {
550
+            $shares[] = $this->createShare($data);
551
+        }
552
+        $cursor->closeCursor();
553
+
554
+        return $shares;
555
+    }
556
+
557
+    /**
558
+     * @inheritdoc
559
+     */
560
+    public function getShareById($id, $recipientId = null) {
561
+        $qb = $this->dbConn->getQueryBuilder();
562
+
563
+        $qb->select('*')
564
+            ->from('share')
565
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
566
+            ->andWhere(
567
+                $qb->expr()->in(
568
+                    'share_type',
569
+                    $qb->createNamedParameter([
570
+                        \OCP\Share::SHARE_TYPE_USER,
571
+                        \OCP\Share::SHARE_TYPE_GROUP,
572
+                        \OCP\Share::SHARE_TYPE_LINK,
573
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
574
+                )
575
+            )
576
+            ->andWhere($qb->expr()->orX(
577
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
578
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
579
+            ));
580
+
581
+        $cursor = $qb->execute();
582
+        $data = $cursor->fetch();
583
+        $cursor->closeCursor();
584
+
585
+        if ($data === false) {
586
+            throw new ShareNotFound();
587
+        }
588
+
589
+        try {
590
+            $share = $this->createShare($data);
591
+        } catch (InvalidShare $e) {
592
+            throw new ShareNotFound();
593
+        }
594
+
595
+        // If the recipient is set for a group share resolve to that user
596
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
597
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
598
+        }
599
+
600
+        return $share;
601
+    }
602
+
603
+    /**
604
+     * Get shares for a given path
605
+     *
606
+     * @param \OCP\Files\Node $path
607
+     * @return \OCP\Share\IShare[]
608
+     */
609
+    public function getSharesByPath(Node $path) {
610
+        $qb = $this->dbConn->getQueryBuilder();
611
+
612
+        $cursor = $qb->select('*')
613
+            ->from('share')
614
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
615
+            ->andWhere(
616
+                $qb->expr()->orX(
617
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
618
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
619
+                )
620
+            )
621
+            ->andWhere($qb->expr()->orX(
622
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
623
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
624
+            ))
625
+            ->execute();
626
+
627
+        $shares = [];
628
+        while($data = $cursor->fetch()) {
629
+            $shares[] = $this->createShare($data);
630
+        }
631
+        $cursor->closeCursor();
632
+
633
+        return $shares;
634
+    }
635
+
636
+    /**
637
+     * Returns whether the given database result can be interpreted as
638
+     * a share with accessible file (not trashed, not deleted)
639
+     */
640
+    private function isAccessibleResult($data) {
641
+        // exclude shares leading to deleted file entries
642
+        if ($data['fileid'] === null) {
643
+            return false;
644
+        }
645
+
646
+        // exclude shares leading to trashbin on home storages
647
+        $pathSections = explode('/', $data['path'], 2);
648
+        // FIXME: would not detect rare md5'd home storage case properly
649
+        if ($pathSections[0] !== 'files' 
650
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
651
+            return false;
652
+        }
653
+        return true;
654
+    }
655
+
656
+    /**
657
+     * @inheritdoc
658
+     */
659
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
660
+        /** @var Share[] $shares */
661
+        $shares = [];
662
+
663
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
664
+            //Get shares directly with this user
665
+            $qb = $this->dbConn->getQueryBuilder();
666
+            $qb->select('s.*',
667
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
668
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
669
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
670
+            )
671
+                ->selectAlias('st.id', 'storage_string_id')
672
+                ->from('share', 's')
673
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
674
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
675
+
676
+            // Order by id
677
+            $qb->orderBy('s.id');
678
+
679
+            // Set limit and offset
680
+            if ($limit !== -1) {
681
+                $qb->setMaxResults($limit);
682
+            }
683
+            $qb->setFirstResult($offset);
684
+
685
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
686
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
687
+                ->andWhere($qb->expr()->orX(
688
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
689
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
690
+                ));
691
+
692
+            // Filter by node if provided
693
+            if ($node !== null) {
694
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
695
+            }
696
+
697
+            $cursor = $qb->execute();
698
+
699
+            while($data = $cursor->fetch()) {
700
+                if ($this->isAccessibleResult($data)) {
701
+                    $shares[] = $this->createShare($data);
702
+                }
703
+            }
704
+            $cursor->closeCursor();
705
+
706
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
707
+            $user = $this->userManager->get($userId);
708
+            $allGroups = $this->groupManager->getUserGroups($user);
709
+
710
+            /** @var Share[] $shares2 */
711
+            $shares2 = [];
712
+
713
+            $start = 0;
714
+            while(true) {
715
+                $groups = array_slice($allGroups, $start, 100);
716
+                $start += 100;
717
+
718
+                if ($groups === []) {
719
+                    break;
720
+                }
721
+
722
+                $qb = $this->dbConn->getQueryBuilder();
723
+                $qb->select('s.*',
724
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
725
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
726
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
727
+                )
728
+                    ->selectAlias('st.id', 'storage_string_id')
729
+                    ->from('share', 's')
730
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
731
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
732
+                    ->orderBy('s.id')
733
+                    ->setFirstResult(0);
734
+
735
+                if ($limit !== -1) {
736
+                    $qb->setMaxResults($limit - count($shares));
737
+                }
738
+
739
+                // Filter by node if provided
740
+                if ($node !== null) {
741
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
742
+                }
743
+
744
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
745
+
746
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
747
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
748
+                        $groups,
749
+                        IQueryBuilder::PARAM_STR_ARRAY
750
+                    )))
751
+                    ->andWhere($qb->expr()->orX(
752
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
753
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
754
+                    ));
755
+
756
+                $cursor = $qb->execute();
757
+                while($data = $cursor->fetch()) {
758
+                    if ($offset > 0) {
759
+                        $offset--;
760
+                        continue;
761
+                    }
762
+
763
+                    if ($this->isAccessibleResult($data)) {
764
+                        $shares2[] = $this->createShare($data);
765
+                    }
766
+                }
767
+                $cursor->closeCursor();
768
+            }
769
+
770
+            /*
771 771
  			 * Resolve all group shares to user specific shares
772 772
  			 */
773
-			$shares = $this->resolveGroupShares($shares2, $userId);
774
-		} else {
775
-			throw new BackendError('Invalid backend');
776
-		}
777
-
778
-
779
-		return $shares;
780
-	}
781
-
782
-	/**
783
-	 * Get a share by token
784
-	 *
785
-	 * @param string $token
786
-	 * @return \OCP\Share\IShare
787
-	 * @throws ShareNotFound
788
-	 */
789
-	public function getShareByToken($token) {
790
-		$qb = $this->dbConn->getQueryBuilder();
791
-
792
-		$cursor = $qb->select('*')
793
-			->from('share')
794
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
795
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
796
-			->andWhere($qb->expr()->orX(
797
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
798
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
799
-			))
800
-			->execute();
801
-
802
-		$data = $cursor->fetch();
803
-
804
-		if ($data === false) {
805
-			throw new ShareNotFound();
806
-		}
807
-
808
-		try {
809
-			$share = $this->createShare($data);
810
-		} catch (InvalidShare $e) {
811
-			throw new ShareNotFound();
812
-		}
813
-
814
-		return $share;
815
-	}
816
-
817
-	/**
818
-	 * Create a share object from an database row
819
-	 *
820
-	 * @param mixed[] $data
821
-	 * @return \OCP\Share\IShare
822
-	 * @throws InvalidShare
823
-	 */
824
-	private function createShare($data) {
825
-		$share = new Share($this->rootFolder, $this->userManager);
826
-		$share->setId((int)$data['id'])
827
-			->setShareType((int)$data['share_type'])
828
-			->setPermissions((int)$data['permissions'])
829
-			->setTarget($data['file_target'])
830
-			->setMailSend((bool)$data['mail_send']);
831
-
832
-		$shareTime = new \DateTime();
833
-		$shareTime->setTimestamp((int)$data['stime']);
834
-		$share->setShareTime($shareTime);
835
-
836
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
837
-			$share->setSharedWith($data['share_with']);
838
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
839
-			$share->setSharedWith($data['share_with']);
840
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
841
-			$share->setPassword($data['share_with']);
842
-			$share->setToken($data['token']);
843
-		}
844
-
845
-		$share->setSharedBy($data['uid_initiator']);
846
-		$share->setShareOwner($data['uid_owner']);
847
-
848
-		$share->setNodeId((int)$data['file_source']);
849
-		$share->setNodeType($data['item_type']);
850
-
851
-		if ($data['expiration'] !== null) {
852
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
853
-			$share->setExpirationDate($expiration);
854
-		}
855
-
856
-		if (isset($data['f_permissions'])) {
857
-			$entryData = $data;
858
-			$entryData['permissions'] = $entryData['f_permissions'];
859
-			$entryData['parent'] = $entryData['f_parent'];;
860
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861
-				\OC::$server->getMimeTypeLoader()));
862
-		}
863
-
864
-		$share->setProviderId($this->identifier());
865
-
866
-		return $share;
867
-	}
868
-
869
-	/**
870
-	 * @param Share[] $shares
871
-	 * @param $userId
872
-	 * @return Share[] The updates shares if no update is found for a share return the original
873
-	 */
874
-	private function resolveGroupShares($shares, $userId) {
875
-		$result = [];
876
-
877
-		$start = 0;
878
-		while(true) {
879
-			/** @var Share[] $shareSlice */
880
-			$shareSlice = array_slice($shares, $start, 100);
881
-			$start += 100;
882
-
883
-			if ($shareSlice === []) {
884
-				break;
885
-			}
886
-
887
-			/** @var int[] $ids */
888
-			$ids = [];
889
-			/** @var Share[] $shareMap */
890
-			$shareMap = [];
891
-
892
-			foreach ($shareSlice as $share) {
893
-				$ids[] = (int)$share->getId();
894
-				$shareMap[$share->getId()] = $share;
895
-			}
896
-
897
-			$qb = $this->dbConn->getQueryBuilder();
898
-
899
-			$query = $qb->select('*')
900
-				->from('share')
901
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
902
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
903
-				->andWhere($qb->expr()->orX(
904
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
905
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
906
-				));
907
-
908
-			$stmt = $query->execute();
909
-
910
-			while($data = $stmt->fetch()) {
911
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
912
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
913
-			}
914
-
915
-			$stmt->closeCursor();
916
-
917
-			foreach ($shareMap as $share) {
918
-				$result[] = $share;
919
-			}
920
-		}
921
-
922
-		return $result;
923
-	}
924
-
925
-	/**
926
-	 * A user is deleted from the system
927
-	 * So clean up the relevant shares.
928
-	 *
929
-	 * @param string $uid
930
-	 * @param int $shareType
931
-	 */
932
-	public function userDeleted($uid, $shareType) {
933
-		$qb = $this->dbConn->getQueryBuilder();
934
-
935
-		$qb->delete('share');
936
-
937
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
938
-			/*
773
+            $shares = $this->resolveGroupShares($shares2, $userId);
774
+        } else {
775
+            throw new BackendError('Invalid backend');
776
+        }
777
+
778
+
779
+        return $shares;
780
+    }
781
+
782
+    /**
783
+     * Get a share by token
784
+     *
785
+     * @param string $token
786
+     * @return \OCP\Share\IShare
787
+     * @throws ShareNotFound
788
+     */
789
+    public function getShareByToken($token) {
790
+        $qb = $this->dbConn->getQueryBuilder();
791
+
792
+        $cursor = $qb->select('*')
793
+            ->from('share')
794
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
795
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
796
+            ->andWhere($qb->expr()->orX(
797
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
798
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
799
+            ))
800
+            ->execute();
801
+
802
+        $data = $cursor->fetch();
803
+
804
+        if ($data === false) {
805
+            throw new ShareNotFound();
806
+        }
807
+
808
+        try {
809
+            $share = $this->createShare($data);
810
+        } catch (InvalidShare $e) {
811
+            throw new ShareNotFound();
812
+        }
813
+
814
+        return $share;
815
+    }
816
+
817
+    /**
818
+     * Create a share object from an database row
819
+     *
820
+     * @param mixed[] $data
821
+     * @return \OCP\Share\IShare
822
+     * @throws InvalidShare
823
+     */
824
+    private function createShare($data) {
825
+        $share = new Share($this->rootFolder, $this->userManager);
826
+        $share->setId((int)$data['id'])
827
+            ->setShareType((int)$data['share_type'])
828
+            ->setPermissions((int)$data['permissions'])
829
+            ->setTarget($data['file_target'])
830
+            ->setMailSend((bool)$data['mail_send']);
831
+
832
+        $shareTime = new \DateTime();
833
+        $shareTime->setTimestamp((int)$data['stime']);
834
+        $share->setShareTime($shareTime);
835
+
836
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
837
+            $share->setSharedWith($data['share_with']);
838
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
839
+            $share->setSharedWith($data['share_with']);
840
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
841
+            $share->setPassword($data['share_with']);
842
+            $share->setToken($data['token']);
843
+        }
844
+
845
+        $share->setSharedBy($data['uid_initiator']);
846
+        $share->setShareOwner($data['uid_owner']);
847
+
848
+        $share->setNodeId((int)$data['file_source']);
849
+        $share->setNodeType($data['item_type']);
850
+
851
+        if ($data['expiration'] !== null) {
852
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
853
+            $share->setExpirationDate($expiration);
854
+        }
855
+
856
+        if (isset($data['f_permissions'])) {
857
+            $entryData = $data;
858
+            $entryData['permissions'] = $entryData['f_permissions'];
859
+            $entryData['parent'] = $entryData['f_parent'];;
860
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861
+                \OC::$server->getMimeTypeLoader()));
862
+        }
863
+
864
+        $share->setProviderId($this->identifier());
865
+
866
+        return $share;
867
+    }
868
+
869
+    /**
870
+     * @param Share[] $shares
871
+     * @param $userId
872
+     * @return Share[] The updates shares if no update is found for a share return the original
873
+     */
874
+    private function resolveGroupShares($shares, $userId) {
875
+        $result = [];
876
+
877
+        $start = 0;
878
+        while(true) {
879
+            /** @var Share[] $shareSlice */
880
+            $shareSlice = array_slice($shares, $start, 100);
881
+            $start += 100;
882
+
883
+            if ($shareSlice === []) {
884
+                break;
885
+            }
886
+
887
+            /** @var int[] $ids */
888
+            $ids = [];
889
+            /** @var Share[] $shareMap */
890
+            $shareMap = [];
891
+
892
+            foreach ($shareSlice as $share) {
893
+                $ids[] = (int)$share->getId();
894
+                $shareMap[$share->getId()] = $share;
895
+            }
896
+
897
+            $qb = $this->dbConn->getQueryBuilder();
898
+
899
+            $query = $qb->select('*')
900
+                ->from('share')
901
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
902
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
903
+                ->andWhere($qb->expr()->orX(
904
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
905
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
906
+                ));
907
+
908
+            $stmt = $query->execute();
909
+
910
+            while($data = $stmt->fetch()) {
911
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
912
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
913
+            }
914
+
915
+            $stmt->closeCursor();
916
+
917
+            foreach ($shareMap as $share) {
918
+                $result[] = $share;
919
+            }
920
+        }
921
+
922
+        return $result;
923
+    }
924
+
925
+    /**
926
+     * A user is deleted from the system
927
+     * So clean up the relevant shares.
928
+     *
929
+     * @param string $uid
930
+     * @param int $shareType
931
+     */
932
+    public function userDeleted($uid, $shareType) {
933
+        $qb = $this->dbConn->getQueryBuilder();
934
+
935
+        $qb->delete('share');
936
+
937
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
938
+            /*
939 939
 			 * Delete all user shares that are owned by this user
940 940
 			 * or that are received by this user
941 941
 			 */
942 942
 
943
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
943
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
944 944
 
945
-			$qb->andWhere(
946
-				$qb->expr()->orX(
947
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
948
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
949
-				)
950
-			);
951
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
952
-			/*
945
+            $qb->andWhere(
946
+                $qb->expr()->orX(
947
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
948
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
949
+                )
950
+            );
951
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
952
+            /*
953 953
 			 * Delete all group shares that are owned by this user
954 954
 			 * Or special user group shares that are received by this user
955 955
 			 */
956
-			$qb->where(
957
-				$qb->expr()->andX(
958
-					$qb->expr()->orX(
959
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
960
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
961
-					),
962
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
963
-				)
964
-			);
965
-
966
-			$qb->orWhere(
967
-				$qb->expr()->andX(
968
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
969
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
970
-				)
971
-			);
972
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
973
-			/*
956
+            $qb->where(
957
+                $qb->expr()->andX(
958
+                    $qb->expr()->orX(
959
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
960
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
961
+                    ),
962
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
963
+                )
964
+            );
965
+
966
+            $qb->orWhere(
967
+                $qb->expr()->andX(
968
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
969
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
970
+                )
971
+            );
972
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
973
+            /*
974 974
 			 * Delete all link shares owned by this user.
975 975
 			 * And all link shares initiated by this user (until #22327 is in)
976 976
 			 */
977
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
978
-
979
-			$qb->andWhere(
980
-				$qb->expr()->orX(
981
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
982
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
983
-				)
984
-			);
985
-		}
986
-
987
-		$qb->execute();
988
-	}
989
-
990
-	/**
991
-	 * Delete all shares received by this group. As well as any custom group
992
-	 * shares for group members.
993
-	 *
994
-	 * @param string $gid
995
-	 */
996
-	public function groupDeleted($gid) {
997
-		/*
977
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
978
+
979
+            $qb->andWhere(
980
+                $qb->expr()->orX(
981
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
982
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
983
+                )
984
+            );
985
+        }
986
+
987
+        $qb->execute();
988
+    }
989
+
990
+    /**
991
+     * Delete all shares received by this group. As well as any custom group
992
+     * shares for group members.
993
+     *
994
+     * @param string $gid
995
+     */
996
+    public function groupDeleted($gid) {
997
+        /*
998 998
 		 * First delete all custom group shares for group members
999 999
 		 */
1000
-		$qb = $this->dbConn->getQueryBuilder();
1001
-		$qb->select('id')
1002
-			->from('share')
1003
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1004
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1005
-
1006
-		$cursor = $qb->execute();
1007
-		$ids = [];
1008
-		while($row = $cursor->fetch()) {
1009
-			$ids[] = (int)$row['id'];
1010
-		}
1011
-		$cursor->closeCursor();
1012
-
1013
-		if (!empty($ids)) {
1014
-			$chunks = array_chunk($ids, 100);
1015
-			foreach ($chunks as $chunk) {
1016
-				$qb->delete('share')
1017
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1018
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1019
-				$qb->execute();
1020
-			}
1021
-		}
1022
-
1023
-		/*
1000
+        $qb = $this->dbConn->getQueryBuilder();
1001
+        $qb->select('id')
1002
+            ->from('share')
1003
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1004
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1005
+
1006
+        $cursor = $qb->execute();
1007
+        $ids = [];
1008
+        while($row = $cursor->fetch()) {
1009
+            $ids[] = (int)$row['id'];
1010
+        }
1011
+        $cursor->closeCursor();
1012
+
1013
+        if (!empty($ids)) {
1014
+            $chunks = array_chunk($ids, 100);
1015
+            foreach ($chunks as $chunk) {
1016
+                $qb->delete('share')
1017
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1018
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1019
+                $qb->execute();
1020
+            }
1021
+        }
1022
+
1023
+        /*
1024 1024
 		 * Now delete all the group shares
1025 1025
 		 */
1026
-		$qb = $this->dbConn->getQueryBuilder();
1027
-		$qb->delete('share')
1028
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1029
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1030
-		$qb->execute();
1031
-	}
1032
-
1033
-	/**
1034
-	 * Delete custom group shares to this group for this user
1035
-	 *
1036
-	 * @param string $uid
1037
-	 * @param string $gid
1038
-	 */
1039
-	public function userDeletedFromGroup($uid, $gid) {
1040
-		/*
1026
+        $qb = $this->dbConn->getQueryBuilder();
1027
+        $qb->delete('share')
1028
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1029
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1030
+        $qb->execute();
1031
+    }
1032
+
1033
+    /**
1034
+     * Delete custom group shares to this group for this user
1035
+     *
1036
+     * @param string $uid
1037
+     * @param string $gid
1038
+     */
1039
+    public function userDeletedFromGroup($uid, $gid) {
1040
+        /*
1041 1041
 		 * Get all group shares
1042 1042
 		 */
1043
-		$qb = $this->dbConn->getQueryBuilder();
1044
-		$qb->select('id')
1045
-			->from('share')
1046
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1047
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1048
-
1049
-		$cursor = $qb->execute();
1050
-		$ids = [];
1051
-		while($row = $cursor->fetch()) {
1052
-			$ids[] = (int)$row['id'];
1053
-		}
1054
-		$cursor->closeCursor();
1055
-
1056
-		if (!empty($ids)) {
1057
-			$chunks = array_chunk($ids, 100);
1058
-			foreach ($chunks as $chunk) {
1059
-				/*
1043
+        $qb = $this->dbConn->getQueryBuilder();
1044
+        $qb->select('id')
1045
+            ->from('share')
1046
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1047
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1048
+
1049
+        $cursor = $qb->execute();
1050
+        $ids = [];
1051
+        while($row = $cursor->fetch()) {
1052
+            $ids[] = (int)$row['id'];
1053
+        }
1054
+        $cursor->closeCursor();
1055
+
1056
+        if (!empty($ids)) {
1057
+            $chunks = array_chunk($ids, 100);
1058
+            foreach ($chunks as $chunk) {
1059
+                /*
1060 1060
 				 * Delete all special shares wit this users for the found group shares
1061 1061
 				 */
1062
-				$qb->delete('share')
1063
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1064
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1065
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1066
-				$qb->execute();
1067
-			}
1068
-		}
1069
-	}
1062
+                $qb->delete('share')
1063
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1064
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1065
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1066
+                $qb->execute();
1067
+            }
1068
+        }
1069
+    }
1070 1070
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -285,7 +285,7 @@  discard block
 block discarded – undo
285 285
 			->orderBy('id');
286 286
 
287 287
 		$cursor = $qb->execute();
288
-		while($data = $cursor->fetch()) {
288
+		while ($data = $cursor->fetch()) {
289 289
 			$children[] = $this->createShare($data);
290 290
 		}
291 291
 		$cursor->closeCursor();
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 			$user = $this->userManager->get($recipient);
331 331
 
332 332
 			if (is_null($group)) {
333
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
333
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
334 334
 			}
335 335
 
336 336
 			if (!$group->inGroup($user)) {
@@ -490,7 +490,7 @@  discard block
 block discarded – undo
490 490
 			);
491 491
 		}
492 492
 
493
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
493
+		$qb->innerJoin('s', 'filecache', 'f', 's.file_source = f.fileid');
494 494
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
495 495
 
496 496
 		$qb->orderBy('id');
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 
547 547
 		$cursor = $qb->execute();
548 548
 		$shares = [];
549
-		while($data = $cursor->fetch()) {
549
+		while ($data = $cursor->fetch()) {
550 550
 			$shares[] = $this->createShare($data);
551 551
 		}
552 552
 		$cursor->closeCursor();
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 			->execute();
626 626
 
627 627
 		$shares = [];
628
-		while($data = $cursor->fetch()) {
628
+		while ($data = $cursor->fetch()) {
629 629
 			$shares[] = $this->createShare($data);
630 630
 		}
631 631
 		$cursor->closeCursor();
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 
697 697
 			$cursor = $qb->execute();
698 698
 
699
-			while($data = $cursor->fetch()) {
699
+			while ($data = $cursor->fetch()) {
700 700
 				if ($this->isAccessibleResult($data)) {
701 701
 					$shares[] = $this->createShare($data);
702 702
 				}
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 			$shares2 = [];
712 712
 
713 713
 			$start = 0;
714
-			while(true) {
714
+			while (true) {
715 715
 				$groups = array_slice($allGroups, $start, 100);
716 716
 				$start += 100;
717 717
 
@@ -754,7 +754,7 @@  discard block
 block discarded – undo
754 754
 					));
755 755
 
756 756
 				$cursor = $qb->execute();
757
-				while($data = $cursor->fetch()) {
757
+				while ($data = $cursor->fetch()) {
758 758
 					if ($offset > 0) {
759 759
 						$offset--;
760 760
 						continue;
@@ -823,14 +823,14 @@  discard block
 block discarded – undo
823 823
 	 */
824 824
 	private function createShare($data) {
825 825
 		$share = new Share($this->rootFolder, $this->userManager);
826
-		$share->setId((int)$data['id'])
827
-			->setShareType((int)$data['share_type'])
828
-			->setPermissions((int)$data['permissions'])
826
+		$share->setId((int) $data['id'])
827
+			->setShareType((int) $data['share_type'])
828
+			->setPermissions((int) $data['permissions'])
829 829
 			->setTarget($data['file_target'])
830
-			->setMailSend((bool)$data['mail_send']);
830
+			->setMailSend((bool) $data['mail_send']);
831 831
 
832 832
 		$shareTime = new \DateTime();
833
-		$shareTime->setTimestamp((int)$data['stime']);
833
+		$shareTime->setTimestamp((int) $data['stime']);
834 834
 		$share->setShareTime($shareTime);
835 835
 
836 836
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -845,7 +845,7 @@  discard block
 block discarded – undo
845 845
 		$share->setSharedBy($data['uid_initiator']);
846 846
 		$share->setShareOwner($data['uid_owner']);
847 847
 
848
-		$share->setNodeId((int)$data['file_source']);
848
+		$share->setNodeId((int) $data['file_source']);
849 849
 		$share->setNodeType($data['item_type']);
850 850
 
851 851
 		if ($data['expiration'] !== null) {
@@ -856,7 +856,7 @@  discard block
 block discarded – undo
856 856
 		if (isset($data['f_permissions'])) {
857 857
 			$entryData = $data;
858 858
 			$entryData['permissions'] = $entryData['f_permissions'];
859
-			$entryData['parent'] = $entryData['f_parent'];;
859
+			$entryData['parent'] = $entryData['f_parent']; ;
860 860
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
861 861
 				\OC::$server->getMimeTypeLoader()));
862 862
 		}
@@ -875,7 +875,7 @@  discard block
 block discarded – undo
875 875
 		$result = [];
876 876
 
877 877
 		$start = 0;
878
-		while(true) {
878
+		while (true) {
879 879
 			/** @var Share[] $shareSlice */
880 880
 			$shareSlice = array_slice($shares, $start, 100);
881 881
 			$start += 100;
@@ -890,7 +890,7 @@  discard block
 block discarded – undo
890 890
 			$shareMap = [];
891 891
 
892 892
 			foreach ($shareSlice as $share) {
893
-				$ids[] = (int)$share->getId();
893
+				$ids[] = (int) $share->getId();
894 894
 				$shareMap[$share->getId()] = $share;
895 895
 			}
896 896
 
@@ -907,8 +907,8 @@  discard block
 block discarded – undo
907 907
 
908 908
 			$stmt = $query->execute();
909 909
 
910
-			while($data = $stmt->fetch()) {
911
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
910
+			while ($data = $stmt->fetch()) {
911
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
912 912
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
913 913
 			}
914 914
 
@@ -1005,8 +1005,8 @@  discard block
 block discarded – undo
1005 1005
 
1006 1006
 		$cursor = $qb->execute();
1007 1007
 		$ids = [];
1008
-		while($row = $cursor->fetch()) {
1009
-			$ids[] = (int)$row['id'];
1008
+		while ($row = $cursor->fetch()) {
1009
+			$ids[] = (int) $row['id'];
1010 1010
 		}
1011 1011
 		$cursor->closeCursor();
1012 1012
 
@@ -1048,8 +1048,8 @@  discard block
 block discarded – undo
1048 1048
 
1049 1049
 		$cursor = $qb->execute();
1050 1050
 		$ids = [];
1051
-		while($row = $cursor->fetch()) {
1052
-			$ids[] = (int)$row['id'];
1051
+		while ($row = $cursor->fetch()) {
1052
+			$ids[] = (int) $row['id'];
1053 1053
 		}
1054 1054
 		$cursor->closeCursor();
1055 1055
 
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 2 patches
Indentation   +318 added lines, -318 removed lines patch added patch discarded remove patch
@@ -58,323 +58,323 @@
 block discarded – undo
58 58
  * @package OC\Group
59 59
  */
60 60
 class Manager extends PublicEmitter implements IGroupManager {
61
-	/**
62
-	 * @var GroupInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\Manager $userManager
68
-	 */
69
-	private $userManager;
70
-
71
-	/**
72
-	 * @var \OC\Group\Group[]
73
-	 */
74
-	private $cachedGroups = array();
75
-
76
-	/**
77
-	 * @var \OC\Group\Group[]
78
-	 */
79
-	private $cachedUserGroups = array();
80
-
81
-	/** @var \OC\SubAdmin */
82
-	private $subAdmin = null;
83
-
84
-	/** @var ILogger */
85
-	private $logger;
86
-
87
-	/**
88
-	 * @param \OC\User\Manager $userManager
89
-	 * @param ILogger $logger
90
-	 */
91
-	public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
-		$this->userManager = $userManager;
93
-		$this->logger = $logger;
94
-		$cachedGroups = & $this->cachedGroups;
95
-		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
-			/**
98
-			 * @var \OC\Group\Group $group
99
-			 */
100
-			unset($cachedGroups[$group->getGID()]);
101
-			$cachedUserGroups = array();
102
-		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
-			/**
105
-			 * @var \OC\Group\Group $group
106
-			 */
107
-			$cachedUserGroups = array();
108
-		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
-			/**
111
-			 * @var \OC\Group\Group $group
112
-			 */
113
-			$cachedUserGroups = array();
114
-		});
115
-	}
116
-
117
-	/**
118
-	 * Checks whether a given backend is used
119
-	 *
120
-	 * @param string $backendClass Full classname including complete namespace
121
-	 * @return bool
122
-	 */
123
-	public function isBackendUsed($backendClass) {
124
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
125
-
126
-		foreach ($this->backends as $backend) {
127
-			if (strtolower(get_class($backend)) === $backendClass) {
128
-				return true;
129
-			}
130
-		}
131
-
132
-		return false;
133
-	}
134
-
135
-	/**
136
-	 * @param \OCP\GroupInterface $backend
137
-	 */
138
-	public function addBackend($backend) {
139
-		$this->backends[] = $backend;
140
-		$this->clearCaches();
141
-	}
142
-
143
-	public function clearBackends() {
144
-		$this->backends = array();
145
-		$this->clearCaches();
146
-	}
61
+    /**
62
+     * @var GroupInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\Manager $userManager
68
+     */
69
+    private $userManager;
70
+
71
+    /**
72
+     * @var \OC\Group\Group[]
73
+     */
74
+    private $cachedGroups = array();
75
+
76
+    /**
77
+     * @var \OC\Group\Group[]
78
+     */
79
+    private $cachedUserGroups = array();
80
+
81
+    /** @var \OC\SubAdmin */
82
+    private $subAdmin = null;
83
+
84
+    /** @var ILogger */
85
+    private $logger;
86
+
87
+    /**
88
+     * @param \OC\User\Manager $userManager
89
+     * @param ILogger $logger
90
+     */
91
+    public function __construct(\OC\User\Manager $userManager, ILogger $logger) {
92
+        $this->userManager = $userManager;
93
+        $this->logger = $logger;
94
+        $cachedGroups = & $this->cachedGroups;
95
+        $cachedUserGroups = & $this->cachedUserGroups;
96
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
97
+            /**
98
+             * @var \OC\Group\Group $group
99
+             */
100
+            unset($cachedGroups[$group->getGID()]);
101
+            $cachedUserGroups = array();
102
+        });
103
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
104
+            /**
105
+             * @var \OC\Group\Group $group
106
+             */
107
+            $cachedUserGroups = array();
108
+        });
109
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
110
+            /**
111
+             * @var \OC\Group\Group $group
112
+             */
113
+            $cachedUserGroups = array();
114
+        });
115
+    }
116
+
117
+    /**
118
+     * Checks whether a given backend is used
119
+     *
120
+     * @param string $backendClass Full classname including complete namespace
121
+     * @return bool
122
+     */
123
+    public function isBackendUsed($backendClass) {
124
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
125
+
126
+        foreach ($this->backends as $backend) {
127
+            if (strtolower(get_class($backend)) === $backendClass) {
128
+                return true;
129
+            }
130
+        }
131
+
132
+        return false;
133
+    }
134
+
135
+    /**
136
+     * @param \OCP\GroupInterface $backend
137
+     */
138
+    public function addBackend($backend) {
139
+        $this->backends[] = $backend;
140
+        $this->clearCaches();
141
+    }
142
+
143
+    public function clearBackends() {
144
+        $this->backends = array();
145
+        $this->clearCaches();
146
+    }
147 147
 	
148
-	protected function clearCaches() {
149
-		$this->cachedGroups = array();
150
-		$this->cachedUserGroups = array();
151
-	}
152
-
153
-	/**
154
-	 * @param string $gid
155
-	 * @return \OC\Group\Group
156
-	 */
157
-	public function get($gid) {
158
-		if (isset($this->cachedGroups[$gid])) {
159
-			return $this->cachedGroups[$gid];
160
-		}
161
-		return $this->getGroupObject($gid);
162
-	}
163
-
164
-	/**
165
-	 * @param string $gid
166
-	 * @param string $displayName
167
-	 * @return \OCP\IGroup
168
-	 */
169
-	protected function getGroupObject($gid, $displayName = null) {
170
-		$backends = array();
171
-		foreach ($this->backends as $backend) {
172
-			if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
-				$groupData = $backend->getGroupDetails($gid);
174
-				if (is_array($groupData)) {
175
-					// take the display name from the first backend that has a non-null one
176
-					if (is_null($displayName) && isset($groupData['displayName'])) {
177
-						$displayName = $groupData['displayName'];
178
-					}
179
-					$backends[] = $backend;
180
-				}
181
-			} else if ($backend->groupExists($gid)) {
182
-				$backends[] = $backend;
183
-			}
184
-		}
185
-		if (count($backends) === 0) {
186
-			return null;
187
-		}
188
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
-		return $this->cachedGroups[$gid];
190
-	}
191
-
192
-	/**
193
-	 * @param string $gid
194
-	 * @return bool
195
-	 */
196
-	public function groupExists($gid) {
197
-		return $this->get($gid) instanceof IGroup;
198
-	}
199
-
200
-	/**
201
-	 * @param string $gid
202
-	 * @return \OC\Group\Group
203
-	 */
204
-	public function createGroup($gid) {
205
-		if ($gid === '' || $gid === null) {
206
-			return false;
207
-		} else if ($group = $this->get($gid)) {
208
-			return $group;
209
-		} else {
210
-			$this->emit('\OC\Group', 'preCreate', array($gid));
211
-			foreach ($this->backends as $backend) {
212
-				if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
-					$backend->createGroup($gid);
214
-					$group = $this->getGroupObject($gid);
215
-					$this->emit('\OC\Group', 'postCreate', array($group));
216
-					return $group;
217
-				}
218
-			}
219
-			return null;
220
-		}
221
-	}
222
-
223
-	/**
224
-	 * @param string $search
225
-	 * @param int $limit
226
-	 * @param int $offset
227
-	 * @return \OC\Group\Group[]
228
-	 */
229
-	public function search($search, $limit = null, $offset = null) {
230
-		$groups = array();
231
-		foreach ($this->backends as $backend) {
232
-			$groupIds = $backend->getGroups($search, $limit, $offset);
233
-			foreach ($groupIds as $groupId) {
234
-				$aGroup = $this->get($groupId);
235
-				if ($aGroup instanceof IGroup) {
236
-					$groups[$groupId] = $aGroup;
237
-				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
-				}
240
-			}
241
-			if (!is_null($limit) and $limit <= 0) {
242
-				return array_values($groups);
243
-			}
244
-		}
245
-		return array_values($groups);
246
-	}
247
-
248
-	/**
249
-	 * @param \OC\User\User|null $user
250
-	 * @return \OC\Group\Group[]
251
-	 */
252
-	public function getUserGroups($user) {
253
-		if (!$user instanceof IUser) {
254
-			return [];
255
-		}
256
-		return $this->getUserIdGroups($user->getUID());
257
-	}
258
-
259
-	/**
260
-	 * @param string $uid the user id
261
-	 * @return \OC\Group\Group[]
262
-	 */
263
-	public function getUserIdGroups($uid) {
264
-		if (isset($this->cachedUserGroups[$uid])) {
265
-			return $this->cachedUserGroups[$uid];
266
-		}
267
-		$groups = array();
268
-		foreach ($this->backends as $backend) {
269
-			$groupIds = $backend->getUserGroups($uid);
270
-			if (is_array($groupIds)) {
271
-				foreach ($groupIds as $groupId) {
272
-					$aGroup = $this->get($groupId);
273
-					if ($aGroup instanceof IGroup) {
274
-						$groups[$groupId] = $aGroup;
275
-					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
-					}
278
-				}
279
-			}
280
-		}
281
-		$this->cachedUserGroups[$uid] = $groups;
282
-		return $this->cachedUserGroups[$uid];
283
-	}
284
-
285
-	/**
286
-	 * Checks if a userId is in the admin group
287
-	 * @param string $userId
288
-	 * @return bool if admin
289
-	 */
290
-	public function isAdmin($userId) {
291
-		return $this->isInGroup($userId, 'admin');
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in a group
296
-	 * @param string $userId
297
-	 * @param string $group
298
-	 * @return bool if in group
299
-	 */
300
-	public function isInGroup($userId, $group) {
301
-		return array_key_exists($group, $this->getUserIdGroups($userId));
302
-	}
303
-
304
-	/**
305
-	 * get a list of group ids for a user
306
-	 * @param \OC\User\User $user
307
-	 * @return array with group ids
308
-	 */
309
-	public function getUserGroupIds($user) {
310
-		return array_map(function($value) {
311
-			return (string) $value;
312
-		}, array_keys($this->getUserGroups($user)));
313
-	}
314
-
315
-	/**
316
-	 * get a list of all display names in a group
317
-	 * @param string $gid
318
-	 * @param string $search
319
-	 * @param int $limit
320
-	 * @param int $offset
321
-	 * @return array an array of display names (value) and user ids (key)
322
-	 */
323
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
-		$group = $this->get($gid);
325
-		if(is_null($group)) {
326
-			return array();
327
-		}
328
-
329
-		$search = trim($search);
330
-		$groupUsers = array();
331
-
332
-		if(!empty($search)) {
333
-			// only user backends have the capability to do a complex search for users
334
-			$searchOffset = 0;
335
-			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
337
-				$searchLimit = 500;
338
-			}
339
-
340
-			do {
341
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
345
-					}
346
-				}
347
-				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
-
350
-			if($limit === -1) {
351
-				$groupUsers = array_slice($groupUsers, $offset);
352
-			} else {
353
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
354
-			}
355
-		} else {
356
-			$groupUsers = $group->searchUsers('', $limit, $offset);
357
-		}
358
-
359
-		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
361
-			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362
-		}
363
-		return $matchingUsers;
364
-	}
365
-
366
-	/**
367
-	 * @return \OC\SubAdmin
368
-	 */
369
-	public function getSubAdmin() {
370
-		if (!$this->subAdmin) {
371
-			$this->subAdmin = new \OC\SubAdmin(
372
-				$this->userManager,
373
-				$this,
374
-				\OC::$server->getDatabaseConnection()
375
-			);
376
-		}
377
-
378
-		return $this->subAdmin;
379
-	}
148
+    protected function clearCaches() {
149
+        $this->cachedGroups = array();
150
+        $this->cachedUserGroups = array();
151
+    }
152
+
153
+    /**
154
+     * @param string $gid
155
+     * @return \OC\Group\Group
156
+     */
157
+    public function get($gid) {
158
+        if (isset($this->cachedGroups[$gid])) {
159
+            return $this->cachedGroups[$gid];
160
+        }
161
+        return $this->getGroupObject($gid);
162
+    }
163
+
164
+    /**
165
+     * @param string $gid
166
+     * @param string $displayName
167
+     * @return \OCP\IGroup
168
+     */
169
+    protected function getGroupObject($gid, $displayName = null) {
170
+        $backends = array();
171
+        foreach ($this->backends as $backend) {
172
+            if ($backend->implementsActions(\OC\Group\Backend::GROUP_DETAILS)) {
173
+                $groupData = $backend->getGroupDetails($gid);
174
+                if (is_array($groupData)) {
175
+                    // take the display name from the first backend that has a non-null one
176
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
177
+                        $displayName = $groupData['displayName'];
178
+                    }
179
+                    $backends[] = $backend;
180
+                }
181
+            } else if ($backend->groupExists($gid)) {
182
+                $backends[] = $backend;
183
+            }
184
+        }
185
+        if (count($backends) === 0) {
186
+            return null;
187
+        }
188
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->userManager, $this, $displayName);
189
+        return $this->cachedGroups[$gid];
190
+    }
191
+
192
+    /**
193
+     * @param string $gid
194
+     * @return bool
195
+     */
196
+    public function groupExists($gid) {
197
+        return $this->get($gid) instanceof IGroup;
198
+    }
199
+
200
+    /**
201
+     * @param string $gid
202
+     * @return \OC\Group\Group
203
+     */
204
+    public function createGroup($gid) {
205
+        if ($gid === '' || $gid === null) {
206
+            return false;
207
+        } else if ($group = $this->get($gid)) {
208
+            return $group;
209
+        } else {
210
+            $this->emit('\OC\Group', 'preCreate', array($gid));
211
+            foreach ($this->backends as $backend) {
212
+                if ($backend->implementsActions(\OC\Group\Backend::CREATE_GROUP)) {
213
+                    $backend->createGroup($gid);
214
+                    $group = $this->getGroupObject($gid);
215
+                    $this->emit('\OC\Group', 'postCreate', array($group));
216
+                    return $group;
217
+                }
218
+            }
219
+            return null;
220
+        }
221
+    }
222
+
223
+    /**
224
+     * @param string $search
225
+     * @param int $limit
226
+     * @param int $offset
227
+     * @return \OC\Group\Group[]
228
+     */
229
+    public function search($search, $limit = null, $offset = null) {
230
+        $groups = array();
231
+        foreach ($this->backends as $backend) {
232
+            $groupIds = $backend->getGroups($search, $limit, $offset);
233
+            foreach ($groupIds as $groupId) {
234
+                $aGroup = $this->get($groupId);
235
+                if ($aGroup instanceof IGroup) {
236
+                    $groups[$groupId] = $aGroup;
237
+                } else {
238
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
239
+                }
240
+            }
241
+            if (!is_null($limit) and $limit <= 0) {
242
+                return array_values($groups);
243
+            }
244
+        }
245
+        return array_values($groups);
246
+    }
247
+
248
+    /**
249
+     * @param \OC\User\User|null $user
250
+     * @return \OC\Group\Group[]
251
+     */
252
+    public function getUserGroups($user) {
253
+        if (!$user instanceof IUser) {
254
+            return [];
255
+        }
256
+        return $this->getUserIdGroups($user->getUID());
257
+    }
258
+
259
+    /**
260
+     * @param string $uid the user id
261
+     * @return \OC\Group\Group[]
262
+     */
263
+    public function getUserIdGroups($uid) {
264
+        if (isset($this->cachedUserGroups[$uid])) {
265
+            return $this->cachedUserGroups[$uid];
266
+        }
267
+        $groups = array();
268
+        foreach ($this->backends as $backend) {
269
+            $groupIds = $backend->getUserGroups($uid);
270
+            if (is_array($groupIds)) {
271
+                foreach ($groupIds as $groupId) {
272
+                    $aGroup = $this->get($groupId);
273
+                    if ($aGroup instanceof IGroup) {
274
+                        $groups[$groupId] = $aGroup;
275
+                    } else {
276
+                        $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
277
+                    }
278
+                }
279
+            }
280
+        }
281
+        $this->cachedUserGroups[$uid] = $groups;
282
+        return $this->cachedUserGroups[$uid];
283
+    }
284
+
285
+    /**
286
+     * Checks if a userId is in the admin group
287
+     * @param string $userId
288
+     * @return bool if admin
289
+     */
290
+    public function isAdmin($userId) {
291
+        return $this->isInGroup($userId, 'admin');
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in a group
296
+     * @param string $userId
297
+     * @param string $group
298
+     * @return bool if in group
299
+     */
300
+    public function isInGroup($userId, $group) {
301
+        return array_key_exists($group, $this->getUserIdGroups($userId));
302
+    }
303
+
304
+    /**
305
+     * get a list of group ids for a user
306
+     * @param \OC\User\User $user
307
+     * @return array with group ids
308
+     */
309
+    public function getUserGroupIds($user) {
310
+        return array_map(function($value) {
311
+            return (string) $value;
312
+        }, array_keys($this->getUserGroups($user)));
313
+    }
314
+
315
+    /**
316
+     * get a list of all display names in a group
317
+     * @param string $gid
318
+     * @param string $search
319
+     * @param int $limit
320
+     * @param int $offset
321
+     * @return array an array of display names (value) and user ids (key)
322
+     */
323
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324
+        $group = $this->get($gid);
325
+        if(is_null($group)) {
326
+            return array();
327
+        }
328
+
329
+        $search = trim($search);
330
+        $groupUsers = array();
331
+
332
+        if(!empty($search)) {
333
+            // only user backends have the capability to do a complex search for users
334
+            $searchOffset = 0;
335
+            $searchLimit = $limit * 100;
336
+            if($limit === -1) {
337
+                $searchLimit = 500;
338
+            }
339
+
340
+            do {
341
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
+                foreach($filteredUsers as $filteredUser) {
343
+                    if($group->inGroup($filteredUser)) {
344
+                        $groupUsers[]= $filteredUser;
345
+                    }
346
+                }
347
+                $searchOffset += $searchLimit;
348
+            } while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
349
+
350
+            if($limit === -1) {
351
+                $groupUsers = array_slice($groupUsers, $offset);
352
+            } else {
353
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
354
+            }
355
+        } else {
356
+            $groupUsers = $group->searchUsers('', $limit, $offset);
357
+        }
358
+
359
+        $matchingUsers = array();
360
+        foreach($groupUsers as $groupUser) {
361
+            $matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362
+        }
363
+        return $matchingUsers;
364
+    }
365
+
366
+    /**
367
+     * @return \OC\SubAdmin
368
+     */
369
+    public function getSubAdmin() {
370
+        if (!$this->subAdmin) {
371
+            $this->subAdmin = new \OC\SubAdmin(
372
+                $this->userManager,
373
+                $this,
374
+                \OC::$server->getDatabaseConnection()
375
+            );
376
+        }
377
+
378
+        return $this->subAdmin;
379
+    }
380 380
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -93,20 +93,20 @@  discard block
 block discarded – undo
93 93
 		$this->logger = $logger;
94 94
 		$cachedGroups = & $this->cachedGroups;
95 95
 		$cachedUserGroups = & $this->cachedUserGroups;
96
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
96
+		$this->listen('\OC\Group', 'postDelete', function($group) use (&$cachedGroups, &$cachedUserGroups) {
97 97
 			/**
98 98
 			 * @var \OC\Group\Group $group
99 99
 			 */
100 100
 			unset($cachedGroups[$group->getGID()]);
101 101
 			$cachedUserGroups = array();
102 102
 		});
103
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
103
+		$this->listen('\OC\Group', 'postAddUser', function($group) use (&$cachedUserGroups) {
104 104
 			/**
105 105
 			 * @var \OC\Group\Group $group
106 106
 			 */
107 107
 			$cachedUserGroups = array();
108 108
 		});
109
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
109
+		$this->listen('\OC\Group', 'postRemoveUser', function($group) use (&$cachedUserGroups) {
110 110
 			/**
111 111
 			 * @var \OC\Group\Group $group
112 112
 			 */
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 				if ($aGroup instanceof IGroup) {
236 236
 					$groups[$groupId] = $aGroup;
237 237
 				} else {
238
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
238
+					$this->logger->debug('Group "'.$groupId.'" was returned by search but not found through direct access', ['app' => 'core']);
239 239
 				}
240 240
 			}
241 241
 			if (!is_null($limit) and $limit <= 0) {
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 					if ($aGroup instanceof IGroup) {
274 274
 						$groups[$groupId] = $aGroup;
275 275
 					} else {
276
-						$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
276
+						$this->logger->debug('User "'.$uid.'" belongs to deleted group: "'.$groupId.'"', ['app' => 'core']);
277 277
 					}
278 278
 				}
279 279
 			}
@@ -322,32 +322,32 @@  discard block
 block discarded – undo
322 322
 	 */
323 323
 	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
324 324
 		$group = $this->get($gid);
325
-		if(is_null($group)) {
325
+		if (is_null($group)) {
326 326
 			return array();
327 327
 		}
328 328
 
329 329
 		$search = trim($search);
330 330
 		$groupUsers = array();
331 331
 
332
-		if(!empty($search)) {
332
+		if (!empty($search)) {
333 333
 			// only user backends have the capability to do a complex search for users
334 334
 			$searchOffset = 0;
335 335
 			$searchLimit = $limit * 100;
336
-			if($limit === -1) {
336
+			if ($limit === -1) {
337 337
 				$searchLimit = 500;
338 338
 			}
339 339
 
340 340
 			do {
341 341
 				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
342
-				foreach($filteredUsers as $filteredUser) {
343
-					if($group->inGroup($filteredUser)) {
344
-						$groupUsers[]= $filteredUser;
342
+				foreach ($filteredUsers as $filteredUser) {
343
+					if ($group->inGroup($filteredUser)) {
344
+						$groupUsers[] = $filteredUser;
345 345
 					}
346 346
 				}
347 347
 				$searchOffset += $searchLimit;
348
-			} while(count($groupUsers) < $searchLimit+$offset && count($filteredUsers) >= $searchLimit);
348
+			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
349 349
 
350
-			if($limit === -1) {
350
+			if ($limit === -1) {
351 351
 				$groupUsers = array_slice($groupUsers, $offset);
352 352
 			} else {
353 353
 				$groupUsers = array_slice($groupUsers, $offset, $limit);
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 		}
358 358
 
359 359
 		$matchingUsers = array();
360
-		foreach($groupUsers as $groupUser) {
360
+		foreach ($groupUsers as $groupUser) {
361 361
 			$matchingUsers[$groupUser->getUID()] = $groupUser->getDisplayName();
362 362
 		}
363 363
 		return $matchingUsers;
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareAPIController.php 1 patch
Indentation   +847 added lines, -847 removed lines patch added patch discarded remove patch
@@ -51,860 +51,860 @@
 block discarded – undo
51 51
  */
52 52
 class ShareAPIController extends OCSController {
53 53
 
54
-	/** @var IManager */
55
-	private $shareManager;
56
-	/** @var IGroupManager */
57
-	private $groupManager;
58
-	/** @var IUserManager */
59
-	private $userManager;
60
-	/** @var IRequest */
61
-	protected $request;
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-	/** @var string */
67
-	private $currentUser;
68
-	/** @var IL10N */
69
-	private $l;
70
-	/** @var \OCP\Files\Node */
71
-	private $lockedNode;
72
-
73
-	/**
74
-	 * Share20OCS constructor.
75
-	 *
76
-	 * @param string $appName
77
-	 * @param IRequest $request
78
-	 * @param IManager $shareManager
79
-	 * @param IGroupManager $groupManager
80
-	 * @param IUserManager $userManager
81
-	 * @param IRootFolder $rootFolder
82
-	 * @param IURLGenerator $urlGenerator
83
-	 * @param string $userId
84
-	 * @param IL10N $l10n
85
-	 */
86
-	public function __construct(
87
-		$appName,
88
-		IRequest $request,
89
-		IManager $shareManager,
90
-		IGroupManager $groupManager,
91
-		IUserManager $userManager,
92
-		IRootFolder $rootFolder,
93
-		IURLGenerator $urlGenerator,
94
-		$userId,
95
-		IL10N $l10n
96
-	) {
97
-		parent::__construct($appName, $request);
98
-
99
-		$this->shareManager = $shareManager;
100
-		$this->userManager = $userManager;
101
-		$this->groupManager = $groupManager;
102
-		$this->request = $request;
103
-		$this->rootFolder = $rootFolder;
104
-		$this->urlGenerator = $urlGenerator;
105
-		$this->currentUser = $userId;
106
-		$this->l = $l10n;
107
-	}
108
-
109
-	/**
110
-	 * Convert an IShare to an array for OCS output
111
-	 *
112
-	 * @param \OCP\Share\IShare $share
113
-	 * @param Node|null $recipientNode
114
-	 * @return array
115
-	 * @throws NotFoundException In case the node can't be resolved.
116
-	 */
117
-	protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
118
-		$sharedBy = $this->userManager->get($share->getSharedBy());
119
-		$shareOwner = $this->userManager->get($share->getShareOwner());
120
-
121
-		$result = [
122
-			'id' => $share->getId(),
123
-			'share_type' => $share->getShareType(),
124
-			'uid_owner' => $share->getSharedBy(),
125
-			'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
126
-			'permissions' => $share->getPermissions(),
127
-			'stime' => $share->getShareTime()->getTimestamp(),
128
-			'parent' => null,
129
-			'expiration' => null,
130
-			'token' => null,
131
-			'uid_file_owner' => $share->getShareOwner(),
132
-			'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
133
-		];
134
-
135
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
136
-		if ($recipientNode) {
137
-			$node = $recipientNode;
138
-		} else {
139
-			$nodes = $userFolder->getById($share->getNodeId());
140
-
141
-			if (empty($nodes)) {
142
-				// fallback to guessing the path
143
-				$node = $userFolder->get($share->getTarget());
144
-				if ($node === null) {
145
-					throw new NotFoundException();
146
-				}
147
-			} else {
148
-				$node = $nodes[0];
149
-			}
150
-		}
151
-
152
-		$result['path'] = $userFolder->getRelativePath($node->getPath());
153
-		if ($node instanceOf \OCP\Files\Folder) {
154
-			$result['item_type'] = 'folder';
155
-		} else {
156
-			$result['item_type'] = 'file';
157
-		}
158
-		$result['mimetype'] = $node->getMimetype();
159
-		$result['storage_id'] = $node->getStorage()->getId();
160
-		$result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
161
-		$result['item_source'] = $node->getId();
162
-		$result['file_source'] = $node->getId();
163
-		$result['file_parent'] = $node->getParent()->getId();
164
-		$result['file_target'] = $share->getTarget();
165
-
166
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
167
-			$sharedWith = $this->userManager->get($share->getSharedWith());
168
-			$result['share_with'] = $share->getSharedWith();
169
-			$result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
170
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
171
-			$group = $this->groupManager->get($share->getSharedWith());
172
-			$result['share_with'] = $share->getSharedWith();
173
-			$result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
174
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
175
-
176
-			$result['share_with'] = $share->getPassword();
177
-			$result['share_with_displayname'] = $share->getPassword();
178
-
179
-			$result['token'] = $share->getToken();
180
-			$result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
181
-
182
-			$expiration = $share->getExpirationDate();
183
-			if ($expiration !== null) {
184
-				$result['expiration'] = $expiration->format('Y-m-d 00:00:00');
185
-			}
186
-
187
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
-			$result['share_with'] = $share->getSharedWith();
189
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
190
-			$result['token'] = $share->getToken();
191
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
-			$result['share_with'] = $share->getSharedWith();
193
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
194
-			$result['token'] = $share->getToken();
195
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
196
-			$result['share_with_displayname'] = $share->getSharedWith();
197
-			$result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
198
-		}
199
-
200
-
201
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
202
-
203
-		return $result;
204
-	}
205
-
206
-	/**
207
-	 * Check if one of the users address books knows the exact property, if
208
-	 * yes we return the full name.
209
-	 *
210
-	 * @param string $query
211
-	 * @param string $property
212
-	 * @return string
213
-	 */
214
-	private function getDisplayNameFromAddressBook($query, $property) {
215
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
216
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
217
-		foreach ($result as $r) {
218
-			foreach($r[$property] as $value) {
219
-				if ($value === $query) {
220
-					return $r['FN'];
221
-				}
222
-			}
223
-		}
224
-
225
-		return $query;
226
-	}
227
-
228
-	/**
229
-	 * Get a specific share by id
230
-	 *
231
-	 * @NoAdminRequired
232
-	 *
233
-	 * @param string $id
234
-	 * @return DataResponse
235
-	 * @throws OCSNotFoundException
236
-	 */
237
-	public function getShare($id) {
238
-		try {
239
-			$share = $this->getShareById($id);
240
-		} catch (ShareNotFound $e) {
241
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
242
-		}
243
-
244
-		if ($this->canAccessShare($share)) {
245
-			try {
246
-				$share = $this->formatShare($share);
247
-				return new DataResponse([$share]);
248
-			} catch (NotFoundException $e) {
249
-				//Fall trough
250
-			}
251
-		}
252
-
253
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
254
-	}
255
-
256
-	/**
257
-	 * Delete a share
258
-	 *
259
-	 * @NoAdminRequired
260
-	 *
261
-	 * @param string $id
262
-	 * @return DataResponse
263
-	 * @throws OCSNotFoundException
264
-	 */
265
-	public function deleteShare($id) {
266
-		try {
267
-			$share = $this->getShareById($id);
268
-		} catch (ShareNotFound $e) {
269
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
270
-		}
271
-
272
-		try {
273
-			$this->lock($share->getNode());
274
-		} catch (LockedException $e) {
275
-			throw new OCSNotFoundException($this->l->t('could not delete share'));
276
-		}
277
-
278
-		if (!$this->canAccessShare($share)) {
279
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
280
-		}
281
-
282
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
283
-			$share->getShareOwner() !== $this->currentUser &&
284
-			$share->getSharedBy() !== $this->currentUser) {
285
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
286
-		} else {
287
-			$this->shareManager->deleteShare($share);
288
-		}
289
-
290
-		return new DataResponse();
291
-	}
292
-
293
-	/**
294
-	 * @NoAdminRequired
295
-	 *
296
-	 * @param string $path
297
-	 * @param int $permissions
298
-	 * @param int $shareType
299
-	 * @param string $shareWith
300
-	 * @param string $publicUpload
301
-	 * @param string $password
302
-	 * @param string $expireDate
303
-	 *
304
-	 * @return DataResponse
305
-	 * @throws OCSNotFoundException
306
-	 * @throws OCSForbiddenException
307
-	 * @throws OCSBadRequestException
308
-	 * @throws OCSException
309
-	 */
310
-	public function createShare(
311
-		$path = null,
312
-		$permissions = \OCP\Constants::PERMISSION_ALL,
313
-		$shareType = -1,
314
-		$shareWith = null,
315
-		$publicUpload = 'false',
316
-		$password = '',
317
-		$expireDate = ''
318
-	) {
319
-		$share = $this->shareManager->newShare();
320
-
321
-		// Verify path
322
-		if ($path === null) {
323
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
324
-		}
325
-
326
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
327
-		try {
328
-			$path = $userFolder->get($path);
329
-		} catch (NotFoundException $e) {
330
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
331
-		}
332
-
333
-		$share->setNode($path);
334
-
335
-		try {
336
-			$this->lock($share->getNode());
337
-		} catch (LockedException $e) {
338
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
339
-		}
340
-
341
-		if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
342
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
343
-		}
344
-
345
-		// Shares always require read permissions
346
-		$permissions |= \OCP\Constants::PERMISSION_READ;
347
-
348
-		if ($path instanceof \OCP\Files\File) {
349
-			// Single file shares should never have delete or create permissions
350
-			$permissions &= ~\OCP\Constants::PERMISSION_DELETE;
351
-			$permissions &= ~\OCP\Constants::PERMISSION_CREATE;
352
-		}
353
-
354
-		/*
54
+    /** @var IManager */
55
+    private $shareManager;
56
+    /** @var IGroupManager */
57
+    private $groupManager;
58
+    /** @var IUserManager */
59
+    private $userManager;
60
+    /** @var IRequest */
61
+    protected $request;
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+    /** @var string */
67
+    private $currentUser;
68
+    /** @var IL10N */
69
+    private $l;
70
+    /** @var \OCP\Files\Node */
71
+    private $lockedNode;
72
+
73
+    /**
74
+     * Share20OCS constructor.
75
+     *
76
+     * @param string $appName
77
+     * @param IRequest $request
78
+     * @param IManager $shareManager
79
+     * @param IGroupManager $groupManager
80
+     * @param IUserManager $userManager
81
+     * @param IRootFolder $rootFolder
82
+     * @param IURLGenerator $urlGenerator
83
+     * @param string $userId
84
+     * @param IL10N $l10n
85
+     */
86
+    public function __construct(
87
+        $appName,
88
+        IRequest $request,
89
+        IManager $shareManager,
90
+        IGroupManager $groupManager,
91
+        IUserManager $userManager,
92
+        IRootFolder $rootFolder,
93
+        IURLGenerator $urlGenerator,
94
+        $userId,
95
+        IL10N $l10n
96
+    ) {
97
+        parent::__construct($appName, $request);
98
+
99
+        $this->shareManager = $shareManager;
100
+        $this->userManager = $userManager;
101
+        $this->groupManager = $groupManager;
102
+        $this->request = $request;
103
+        $this->rootFolder = $rootFolder;
104
+        $this->urlGenerator = $urlGenerator;
105
+        $this->currentUser = $userId;
106
+        $this->l = $l10n;
107
+    }
108
+
109
+    /**
110
+     * Convert an IShare to an array for OCS output
111
+     *
112
+     * @param \OCP\Share\IShare $share
113
+     * @param Node|null $recipientNode
114
+     * @return array
115
+     * @throws NotFoundException In case the node can't be resolved.
116
+     */
117
+    protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
118
+        $sharedBy = $this->userManager->get($share->getSharedBy());
119
+        $shareOwner = $this->userManager->get($share->getShareOwner());
120
+
121
+        $result = [
122
+            'id' => $share->getId(),
123
+            'share_type' => $share->getShareType(),
124
+            'uid_owner' => $share->getSharedBy(),
125
+            'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
126
+            'permissions' => $share->getPermissions(),
127
+            'stime' => $share->getShareTime()->getTimestamp(),
128
+            'parent' => null,
129
+            'expiration' => null,
130
+            'token' => null,
131
+            'uid_file_owner' => $share->getShareOwner(),
132
+            'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
133
+        ];
134
+
135
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
136
+        if ($recipientNode) {
137
+            $node = $recipientNode;
138
+        } else {
139
+            $nodes = $userFolder->getById($share->getNodeId());
140
+
141
+            if (empty($nodes)) {
142
+                // fallback to guessing the path
143
+                $node = $userFolder->get($share->getTarget());
144
+                if ($node === null) {
145
+                    throw new NotFoundException();
146
+                }
147
+            } else {
148
+                $node = $nodes[0];
149
+            }
150
+        }
151
+
152
+        $result['path'] = $userFolder->getRelativePath($node->getPath());
153
+        if ($node instanceOf \OCP\Files\Folder) {
154
+            $result['item_type'] = 'folder';
155
+        } else {
156
+            $result['item_type'] = 'file';
157
+        }
158
+        $result['mimetype'] = $node->getMimetype();
159
+        $result['storage_id'] = $node->getStorage()->getId();
160
+        $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
161
+        $result['item_source'] = $node->getId();
162
+        $result['file_source'] = $node->getId();
163
+        $result['file_parent'] = $node->getParent()->getId();
164
+        $result['file_target'] = $share->getTarget();
165
+
166
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
167
+            $sharedWith = $this->userManager->get($share->getSharedWith());
168
+            $result['share_with'] = $share->getSharedWith();
169
+            $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
170
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
171
+            $group = $this->groupManager->get($share->getSharedWith());
172
+            $result['share_with'] = $share->getSharedWith();
173
+            $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
174
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
175
+
176
+            $result['share_with'] = $share->getPassword();
177
+            $result['share_with_displayname'] = $share->getPassword();
178
+
179
+            $result['token'] = $share->getToken();
180
+            $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
181
+
182
+            $expiration = $share->getExpirationDate();
183
+            if ($expiration !== null) {
184
+                $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
185
+            }
186
+
187
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
+            $result['share_with'] = $share->getSharedWith();
189
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
190
+            $result['token'] = $share->getToken();
191
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
+            $result['share_with'] = $share->getSharedWith();
193
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
194
+            $result['token'] = $share->getToken();
195
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
196
+            $result['share_with_displayname'] = $share->getSharedWith();
197
+            $result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
198
+        }
199
+
200
+
201
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
202
+
203
+        return $result;
204
+    }
205
+
206
+    /**
207
+     * Check if one of the users address books knows the exact property, if
208
+     * yes we return the full name.
209
+     *
210
+     * @param string $query
211
+     * @param string $property
212
+     * @return string
213
+     */
214
+    private function getDisplayNameFromAddressBook($query, $property) {
215
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
216
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
217
+        foreach ($result as $r) {
218
+            foreach($r[$property] as $value) {
219
+                if ($value === $query) {
220
+                    return $r['FN'];
221
+                }
222
+            }
223
+        }
224
+
225
+        return $query;
226
+    }
227
+
228
+    /**
229
+     * Get a specific share by id
230
+     *
231
+     * @NoAdminRequired
232
+     *
233
+     * @param string $id
234
+     * @return DataResponse
235
+     * @throws OCSNotFoundException
236
+     */
237
+    public function getShare($id) {
238
+        try {
239
+            $share = $this->getShareById($id);
240
+        } catch (ShareNotFound $e) {
241
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
242
+        }
243
+
244
+        if ($this->canAccessShare($share)) {
245
+            try {
246
+                $share = $this->formatShare($share);
247
+                return new DataResponse([$share]);
248
+            } catch (NotFoundException $e) {
249
+                //Fall trough
250
+            }
251
+        }
252
+
253
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
254
+    }
255
+
256
+    /**
257
+     * Delete a share
258
+     *
259
+     * @NoAdminRequired
260
+     *
261
+     * @param string $id
262
+     * @return DataResponse
263
+     * @throws OCSNotFoundException
264
+     */
265
+    public function deleteShare($id) {
266
+        try {
267
+            $share = $this->getShareById($id);
268
+        } catch (ShareNotFound $e) {
269
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
270
+        }
271
+
272
+        try {
273
+            $this->lock($share->getNode());
274
+        } catch (LockedException $e) {
275
+            throw new OCSNotFoundException($this->l->t('could not delete share'));
276
+        }
277
+
278
+        if (!$this->canAccessShare($share)) {
279
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
280
+        }
281
+
282
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
283
+            $share->getShareOwner() !== $this->currentUser &&
284
+            $share->getSharedBy() !== $this->currentUser) {
285
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
286
+        } else {
287
+            $this->shareManager->deleteShare($share);
288
+        }
289
+
290
+        return new DataResponse();
291
+    }
292
+
293
+    /**
294
+     * @NoAdminRequired
295
+     *
296
+     * @param string $path
297
+     * @param int $permissions
298
+     * @param int $shareType
299
+     * @param string $shareWith
300
+     * @param string $publicUpload
301
+     * @param string $password
302
+     * @param string $expireDate
303
+     *
304
+     * @return DataResponse
305
+     * @throws OCSNotFoundException
306
+     * @throws OCSForbiddenException
307
+     * @throws OCSBadRequestException
308
+     * @throws OCSException
309
+     */
310
+    public function createShare(
311
+        $path = null,
312
+        $permissions = \OCP\Constants::PERMISSION_ALL,
313
+        $shareType = -1,
314
+        $shareWith = null,
315
+        $publicUpload = 'false',
316
+        $password = '',
317
+        $expireDate = ''
318
+    ) {
319
+        $share = $this->shareManager->newShare();
320
+
321
+        // Verify path
322
+        if ($path === null) {
323
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
324
+        }
325
+
326
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
327
+        try {
328
+            $path = $userFolder->get($path);
329
+        } catch (NotFoundException $e) {
330
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
331
+        }
332
+
333
+        $share->setNode($path);
334
+
335
+        try {
336
+            $this->lock($share->getNode());
337
+        } catch (LockedException $e) {
338
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
339
+        }
340
+
341
+        if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
342
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
343
+        }
344
+
345
+        // Shares always require read permissions
346
+        $permissions |= \OCP\Constants::PERMISSION_READ;
347
+
348
+        if ($path instanceof \OCP\Files\File) {
349
+            // Single file shares should never have delete or create permissions
350
+            $permissions &= ~\OCP\Constants::PERMISSION_DELETE;
351
+            $permissions &= ~\OCP\Constants::PERMISSION_CREATE;
352
+        }
353
+
354
+        /*
355 355
 		 * Hack for https://github.com/owncloud/core/issues/22587
356 356
 		 * We check the permissions via webdav. But the permissions of the mount point
357 357
 		 * do not equal the share permissions. Here we fix that for federated mounts.
358 358
 		 */
359
-		if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
360
-			$permissions &= ~($permissions & ~$path->getPermissions());
361
-		}
362
-
363
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
364
-			// Valid user is required to share
365
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
366
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
367
-			}
368
-			$share->setSharedWith($shareWith);
369
-			$share->setPermissions($permissions);
370
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
371
-			if (!$this->shareManager->allowGroupSharing()) {
372
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
373
-			}
374
-
375
-			// Valid group is required to share
376
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
377
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
378
-			}
379
-			$share->setSharedWith($shareWith);
380
-			$share->setPermissions($permissions);
381
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
382
-			//Can we even share links?
383
-			if (!$this->shareManager->shareApiAllowLinks()) {
384
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
385
-			}
386
-
387
-			/*
359
+        if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
360
+            $permissions &= ~($permissions & ~$path->getPermissions());
361
+        }
362
+
363
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
364
+            // Valid user is required to share
365
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
366
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
367
+            }
368
+            $share->setSharedWith($shareWith);
369
+            $share->setPermissions($permissions);
370
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
371
+            if (!$this->shareManager->allowGroupSharing()) {
372
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
373
+            }
374
+
375
+            // Valid group is required to share
376
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
377
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
378
+            }
379
+            $share->setSharedWith($shareWith);
380
+            $share->setPermissions($permissions);
381
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
382
+            //Can we even share links?
383
+            if (!$this->shareManager->shareApiAllowLinks()) {
384
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
385
+            }
386
+
387
+            /*
388 388
 			 * For now we only allow 1 link share.
389 389
 			 * Return the existing link share if this is a duplicate
390 390
 			 */
391
-			$existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
392
-			if (!empty($existingShares)) {
393
-				return new DataResponse($this->formatShare($existingShares[0]));
394
-			}
395
-
396
-			if ($publicUpload === 'true') {
397
-				// Check if public upload is allowed
398
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
399
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
400
-				}
401
-
402
-				// Public upload can only be set for folders
403
-				if ($path instanceof \OCP\Files\File) {
404
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
405
-				}
406
-
407
-				$share->setPermissions(
408
-					\OCP\Constants::PERMISSION_READ |
409
-					\OCP\Constants::PERMISSION_CREATE |
410
-					\OCP\Constants::PERMISSION_UPDATE |
411
-					\OCP\Constants::PERMISSION_DELETE
412
-				);
413
-			} else {
414
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
415
-			}
416
-
417
-			// Set password
418
-			if ($password !== '') {
419
-				$share->setPassword($password);
420
-			}
421
-
422
-			//Expire date
423
-			if ($expireDate !== '') {
424
-				try {
425
-					$expireDate = $this->parseDate($expireDate);
426
-					$share->setExpirationDate($expireDate);
427
-				} catch (\Exception $e) {
428
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
429
-				}
430
-			}
431
-
432
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
433
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
434
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
435
-			}
436
-
437
-			$share->setSharedWith($shareWith);
438
-			$share->setPermissions($permissions);
439
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
440
-			if ($share->getNodeType() === 'file') {
441
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
442
-			} else {
443
-				$share->setPermissions(
444
-					\OCP\Constants::PERMISSION_READ |
445
-					\OCP\Constants::PERMISSION_CREATE |
446
-					\OCP\Constants::PERMISSION_UPDATE |
447
-					\OCP\Constants::PERMISSION_DELETE);
448
-			}
449
-			$share->setSharedWith($shareWith);
450
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
451
-			if (!\OCP\App::isEnabled('circles')) {
452
-				throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
453
-			}
454
-
455
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($shareWith);
456
-
457
-			// Valid circle is required to share
458
-			if ($circle === null) {
459
-				throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
460
-			}
461
-			$share->setSharedWith($shareWith);
462
-			$share->setPermissions($permissions);
463
-		} else {
464
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
465
-		}
466
-
467
-		$share->setShareType($shareType);
468
-		$share->setSharedBy($this->currentUser);
469
-
470
-		try {
471
-			$share = $this->shareManager->createShare($share);
472
-		} catch (GenericShareException $e) {
473
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
474
-			throw new OCSException($e->getHint(), $code);
475
-		} catch (\Exception $e) {
476
-			throw new OCSForbiddenException($e->getMessage());
477
-		}
478
-
479
-		$output = $this->formatShare($share);
480
-
481
-		return new DataResponse($output);
482
-	}
483
-
484
-	/**
485
-	 * @param \OCP\Files\File|\OCP\Files\Folder $node
486
-	 * @return DataResponse
487
-	 */
488
-	private function getSharedWithMe($node = null) {
489
-
490
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
491
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
492
-		$circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
493
-
494
-		$shares = array_merge($userShares, $groupShares, $circleShares);
495
-
496
-		$shares = array_filter($shares, function (IShare $share) {
497
-			return $share->getShareOwner() !== $this->currentUser;
498
-		});
499
-
500
-		$formatted = [];
501
-		foreach ($shares as $share) {
502
-			if ($this->canAccessShare($share)) {
503
-				try {
504
-					$formatted[] = $this->formatShare($share);
505
-				} catch (NotFoundException $e) {
506
-					// Ignore this share
507
-				}
508
-			}
509
-		}
510
-
511
-		return new DataResponse($formatted);
512
-	}
513
-
514
-	/**
515
-	 * @param \OCP\Files\Folder $folder
516
-	 * @return DataResponse
517
-	 * @throws OCSBadRequestException
518
-	 */
519
-	private function getSharesInDir($folder) {
520
-		if (!($folder instanceof \OCP\Files\Folder)) {
521
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
522
-		}
523
-
524
-		$nodes = $folder->getDirectoryListing();
525
-		/** @var \OCP\Share\IShare[] $shares */
526
-		$shares = [];
527
-		foreach ($nodes as $node) {
528
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
529
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
530
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
531
-			if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
532
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
533
-			}
534
-			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
535
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
536
-			}
537
-		}
538
-
539
-		$formatted = [];
540
-		foreach ($shares as $share) {
541
-			try {
542
-				$formatted[] = $this->formatShare($share);
543
-			} catch (NotFoundException $e) {
544
-				//Ignore this share
545
-			}
546
-		}
547
-
548
-		return new DataResponse($formatted);
549
-	}
550
-
551
-	/**
552
-	 * The getShares function.
553
-	 *
554
-	 * @NoAdminRequired
555
-	 *
556
-	 * @param string $shared_with_me
557
-	 * @param string $reshares
558
-	 * @param string $subfiles
559
-	 * @param string $path
560
-	 *
561
-	 * - Get shares by the current user
562
-	 * - Get shares by the current user and reshares (?reshares=true)
563
-	 * - Get shares with the current user (?shared_with_me=true)
564
-	 * - Get shares for a specific path (?path=...)
565
-	 * - Get all shares in a folder (?subfiles=true&path=..)
566
-	 *
567
-	 * @return DataResponse
568
-	 * @throws OCSNotFoundException
569
-	 */
570
-	public function getShares(
571
-		$shared_with_me = 'false',
572
-		$reshares = 'false',
573
-		$subfiles = 'false',
574
-		$path = null
575
-	) {
576
-
577
-		if ($path !== null) {
578
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
579
-			try {
580
-				$path = $userFolder->get($path);
581
-				$this->lock($path);
582
-			} catch (\OCP\Files\NotFoundException $e) {
583
-				throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
584
-			} catch (LockedException $e) {
585
-				throw new OCSNotFoundException($this->l->t('Could not lock path'));
586
-			}
587
-		}
588
-
589
-		if ($shared_with_me === 'true') {
590
-			$result = $this->getSharedWithMe($path);
591
-			return $result;
592
-		}
593
-
594
-		if ($subfiles === 'true') {
595
-			$result = $this->getSharesInDir($path);
596
-			return $result;
597
-		}
598
-
599
-		if ($reshares === 'true') {
600
-			$reshares = true;
601
-		} else {
602
-			$reshares = false;
603
-		}
604
-
605
-		// Get all shares
606
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
607
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
608
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
609
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
610
-			$mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
611
-		} else {
612
-			$mailShares = [];
613
-		}
614
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
615
-			$circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
616
-		} else {
617
-			$circleShares = [];
618
-		}
619
-
620
-		$shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
621
-
622
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
623
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
624
-			$shares = array_merge($shares, $federatedShares);
625
-		}
626
-
627
-		$formatted = [];
628
-		foreach ($shares as $share) {
629
-			try {
630
-				$formatted[] = $this->formatShare($share, $path);
631
-			} catch (NotFoundException $e) {
632
-				//Ignore share
633
-			}
634
-		}
635
-
636
-		return new DataResponse($formatted);
637
-	}
638
-
639
-	/**
640
-	 * @NoAdminRequired
641
-	 *
642
-	 * @param int $id
643
-	 * @param int $permissions
644
-	 * @param string $password
645
-	 * @param string $publicUpload
646
-	 * @param string $expireDate
647
-	 * @return DataResponse
648
-	 * @throws OCSNotFoundException
649
-	 * @throws OCSBadRequestException
650
-	 * @throws OCSForbiddenException
651
-	 */
652
-	public function updateShare(
653
-		$id,
654
-		$permissions = null,
655
-		$password = null,
656
-		$publicUpload = null,
657
-		$expireDate = null
658
-	) {
659
-		try {
660
-			$share = $this->getShareById($id);
661
-		} catch (ShareNotFound $e) {
662
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
663
-		}
664
-
665
-		$this->lock($share->getNode());
666
-
667
-		if (!$this->canAccessShare($share, false)) {
668
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
669
-		}
670
-
671
-		/*
391
+            $existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
392
+            if (!empty($existingShares)) {
393
+                return new DataResponse($this->formatShare($existingShares[0]));
394
+            }
395
+
396
+            if ($publicUpload === 'true') {
397
+                // Check if public upload is allowed
398
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
399
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
400
+                }
401
+
402
+                // Public upload can only be set for folders
403
+                if ($path instanceof \OCP\Files\File) {
404
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
405
+                }
406
+
407
+                $share->setPermissions(
408
+                    \OCP\Constants::PERMISSION_READ |
409
+                    \OCP\Constants::PERMISSION_CREATE |
410
+                    \OCP\Constants::PERMISSION_UPDATE |
411
+                    \OCP\Constants::PERMISSION_DELETE
412
+                );
413
+            } else {
414
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
415
+            }
416
+
417
+            // Set password
418
+            if ($password !== '') {
419
+                $share->setPassword($password);
420
+            }
421
+
422
+            //Expire date
423
+            if ($expireDate !== '') {
424
+                try {
425
+                    $expireDate = $this->parseDate($expireDate);
426
+                    $share->setExpirationDate($expireDate);
427
+                } catch (\Exception $e) {
428
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
429
+                }
430
+            }
431
+
432
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
433
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
434
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
435
+            }
436
+
437
+            $share->setSharedWith($shareWith);
438
+            $share->setPermissions($permissions);
439
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
440
+            if ($share->getNodeType() === 'file') {
441
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
442
+            } else {
443
+                $share->setPermissions(
444
+                    \OCP\Constants::PERMISSION_READ |
445
+                    \OCP\Constants::PERMISSION_CREATE |
446
+                    \OCP\Constants::PERMISSION_UPDATE |
447
+                    \OCP\Constants::PERMISSION_DELETE);
448
+            }
449
+            $share->setSharedWith($shareWith);
450
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
451
+            if (!\OCP\App::isEnabled('circles')) {
452
+                throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
453
+            }
454
+
455
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($shareWith);
456
+
457
+            // Valid circle is required to share
458
+            if ($circle === null) {
459
+                throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
460
+            }
461
+            $share->setSharedWith($shareWith);
462
+            $share->setPermissions($permissions);
463
+        } else {
464
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
465
+        }
466
+
467
+        $share->setShareType($shareType);
468
+        $share->setSharedBy($this->currentUser);
469
+
470
+        try {
471
+            $share = $this->shareManager->createShare($share);
472
+        } catch (GenericShareException $e) {
473
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
474
+            throw new OCSException($e->getHint(), $code);
475
+        } catch (\Exception $e) {
476
+            throw new OCSForbiddenException($e->getMessage());
477
+        }
478
+
479
+        $output = $this->formatShare($share);
480
+
481
+        return new DataResponse($output);
482
+    }
483
+
484
+    /**
485
+     * @param \OCP\Files\File|\OCP\Files\Folder $node
486
+     * @return DataResponse
487
+     */
488
+    private function getSharedWithMe($node = null) {
489
+
490
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
491
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
492
+        $circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
493
+
494
+        $shares = array_merge($userShares, $groupShares, $circleShares);
495
+
496
+        $shares = array_filter($shares, function (IShare $share) {
497
+            return $share->getShareOwner() !== $this->currentUser;
498
+        });
499
+
500
+        $formatted = [];
501
+        foreach ($shares as $share) {
502
+            if ($this->canAccessShare($share)) {
503
+                try {
504
+                    $formatted[] = $this->formatShare($share);
505
+                } catch (NotFoundException $e) {
506
+                    // Ignore this share
507
+                }
508
+            }
509
+        }
510
+
511
+        return new DataResponse($formatted);
512
+    }
513
+
514
+    /**
515
+     * @param \OCP\Files\Folder $folder
516
+     * @return DataResponse
517
+     * @throws OCSBadRequestException
518
+     */
519
+    private function getSharesInDir($folder) {
520
+        if (!($folder instanceof \OCP\Files\Folder)) {
521
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
522
+        }
523
+
524
+        $nodes = $folder->getDirectoryListing();
525
+        /** @var \OCP\Share\IShare[] $shares */
526
+        $shares = [];
527
+        foreach ($nodes as $node) {
528
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
529
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
530
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
531
+            if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
532
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
533
+            }
534
+            if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
535
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
536
+            }
537
+        }
538
+
539
+        $formatted = [];
540
+        foreach ($shares as $share) {
541
+            try {
542
+                $formatted[] = $this->formatShare($share);
543
+            } catch (NotFoundException $e) {
544
+                //Ignore this share
545
+            }
546
+        }
547
+
548
+        return new DataResponse($formatted);
549
+    }
550
+
551
+    /**
552
+     * The getShares function.
553
+     *
554
+     * @NoAdminRequired
555
+     *
556
+     * @param string $shared_with_me
557
+     * @param string $reshares
558
+     * @param string $subfiles
559
+     * @param string $path
560
+     *
561
+     * - Get shares by the current user
562
+     * - Get shares by the current user and reshares (?reshares=true)
563
+     * - Get shares with the current user (?shared_with_me=true)
564
+     * - Get shares for a specific path (?path=...)
565
+     * - Get all shares in a folder (?subfiles=true&path=..)
566
+     *
567
+     * @return DataResponse
568
+     * @throws OCSNotFoundException
569
+     */
570
+    public function getShares(
571
+        $shared_with_me = 'false',
572
+        $reshares = 'false',
573
+        $subfiles = 'false',
574
+        $path = null
575
+    ) {
576
+
577
+        if ($path !== null) {
578
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
579
+            try {
580
+                $path = $userFolder->get($path);
581
+                $this->lock($path);
582
+            } catch (\OCP\Files\NotFoundException $e) {
583
+                throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
584
+            } catch (LockedException $e) {
585
+                throw new OCSNotFoundException($this->l->t('Could not lock path'));
586
+            }
587
+        }
588
+
589
+        if ($shared_with_me === 'true') {
590
+            $result = $this->getSharedWithMe($path);
591
+            return $result;
592
+        }
593
+
594
+        if ($subfiles === 'true') {
595
+            $result = $this->getSharesInDir($path);
596
+            return $result;
597
+        }
598
+
599
+        if ($reshares === 'true') {
600
+            $reshares = true;
601
+        } else {
602
+            $reshares = false;
603
+        }
604
+
605
+        // Get all shares
606
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
607
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
608
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
609
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
610
+            $mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
611
+        } else {
612
+            $mailShares = [];
613
+        }
614
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
615
+            $circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
616
+        } else {
617
+            $circleShares = [];
618
+        }
619
+
620
+        $shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
621
+
622
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
623
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
624
+            $shares = array_merge($shares, $federatedShares);
625
+        }
626
+
627
+        $formatted = [];
628
+        foreach ($shares as $share) {
629
+            try {
630
+                $formatted[] = $this->formatShare($share, $path);
631
+            } catch (NotFoundException $e) {
632
+                //Ignore share
633
+            }
634
+        }
635
+
636
+        return new DataResponse($formatted);
637
+    }
638
+
639
+    /**
640
+     * @NoAdminRequired
641
+     *
642
+     * @param int $id
643
+     * @param int $permissions
644
+     * @param string $password
645
+     * @param string $publicUpload
646
+     * @param string $expireDate
647
+     * @return DataResponse
648
+     * @throws OCSNotFoundException
649
+     * @throws OCSBadRequestException
650
+     * @throws OCSForbiddenException
651
+     */
652
+    public function updateShare(
653
+        $id,
654
+        $permissions = null,
655
+        $password = null,
656
+        $publicUpload = null,
657
+        $expireDate = null
658
+    ) {
659
+        try {
660
+            $share = $this->getShareById($id);
661
+        } catch (ShareNotFound $e) {
662
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
663
+        }
664
+
665
+        $this->lock($share->getNode());
666
+
667
+        if (!$this->canAccessShare($share, false)) {
668
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
669
+        }
670
+
671
+        /*
672 672
 		 * expirationdate, password and publicUpload only make sense for link shares
673 673
 		 */
674
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
675
-			if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
676
-				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
677
-			}
678
-
679
-			$newPermissions = null;
680
-			if ($publicUpload === 'true') {
681
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
682
-			} else if ($publicUpload === 'false') {
683
-				$newPermissions = \OCP\Constants::PERMISSION_READ;
684
-			}
685
-
686
-			if ($permissions !== null) {
687
-				$newPermissions = (int)$permissions;
688
-			}
689
-
690
-			if ($newPermissions !== null &&
691
-				!in_array($newPermissions, [
692
-					\OCP\Constants::PERMISSION_READ,
693
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
694
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
695
-					\OCP\Constants::PERMISSION_CREATE, // hidden file list
696
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
697
-				])
698
-			) {
699
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
700
-			}
701
-
702
-			if (
703
-				// legacy
704
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
705
-				// correct
706
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
707
-			) {
708
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
709
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
710
-				}
711
-
712
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
713
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
714
-				}
715
-
716
-				// normalize to correct public upload permissions
717
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
718
-			}
719
-
720
-			if ($newPermissions !== null) {
721
-				$share->setPermissions($newPermissions);
722
-				$permissions = $newPermissions;
723
-			}
724
-
725
-			if ($expireDate === '') {
726
-				$share->setExpirationDate(null);
727
-			} else if ($expireDate !== null) {
728
-				try {
729
-					$expireDate = $this->parseDate($expireDate);
730
-				} catch (\Exception $e) {
731
-					throw new OCSBadRequestException($e->getMessage());
732
-				}
733
-				$share->setExpirationDate($expireDate);
734
-			}
735
-
736
-			if ($password === '') {
737
-				$share->setPassword(null);
738
-			} else if ($password !== null) {
739
-				$share->setPassword($password);
740
-			}
741
-
742
-		} else {
743
-			// For other shares only permissions is valid.
744
-			if ($permissions === null) {
745
-				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
746
-			} else {
747
-				$permissions = (int)$permissions;
748
-				$share->setPermissions($permissions);
749
-			}
750
-		}
751
-
752
-		if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
753
-			/* Check if this is an incomming share */
754
-			$incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
755
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
756
-
757
-			/** @var \OCP\Share\IShare[] $incomingShares */
758
-			if (!empty($incomingShares)) {
759
-				$maxPermissions = 0;
760
-				foreach ($incomingShares as $incomingShare) {
761
-					$maxPermissions |= $incomingShare->getPermissions();
762
-				}
763
-
764
-				if ($share->getPermissions() & ~$maxPermissions) {
765
-					throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
766
-				}
767
-			}
768
-		}
769
-
770
-
771
-		try {
772
-			$share = $this->shareManager->updateShare($share);
773
-		} catch (\Exception $e) {
774
-			throw new OCSBadRequestException($e->getMessage());
775
-		}
776
-
777
-		return new DataResponse($this->formatShare($share));
778
-	}
779
-
780
-	/**
781
-	 * @param \OCP\Share\IShare $share
782
-	 * @return bool
783
-	 */
784
-	protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
785
-		// A file with permissions 0 can't be accessed by us. So Don't show it
786
-		if ($share->getPermissions() === 0) {
787
-			return false;
788
-		}
789
-
790
-		// Owner of the file and the sharer of the file can always get share
791
-		if ($share->getShareOwner() === $this->currentUser ||
792
-			$share->getSharedBy() === $this->currentUser
793
-		) {
794
-			return true;
795
-		}
796
-
797
-		// If the share is shared with you (or a group you are a member of)
798
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
799
-			$share->getSharedWith() === $this->currentUser
800
-		) {
801
-			return true;
802
-		}
803
-
804
-		if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
805
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
806
-			$user = $this->userManager->get($this->currentUser);
807
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
808
-				return true;
809
-			}
810
-		}
811
-
812
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
813
-			// TODO: have a sanity check like above?
814
-			return true;
815
-		}
816
-
817
-		return false;
818
-	}
819
-
820
-	/**
821
-	 * Make sure that the passed date is valid ISO 8601
822
-	 * So YYYY-MM-DD
823
-	 * If not throw an exception
824
-	 *
825
-	 * @param string $expireDate
826
-	 *
827
-	 * @throws \Exception
828
-	 * @return \DateTime
829
-	 */
830
-	private function parseDate($expireDate) {
831
-		try {
832
-			$date = new \DateTime($expireDate);
833
-		} catch (\Exception $e) {
834
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
835
-		}
836
-
837
-		if ($date === false) {
838
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
839
-		}
840
-
841
-		$date->setTime(0, 0, 0);
842
-
843
-		return $date;
844
-	}
845
-
846
-	/**
847
-	 * Since we have multiple providers but the OCS Share API v1 does
848
-	 * not support this we need to check all backends.
849
-	 *
850
-	 * @param string $id
851
-	 * @return \OCP\Share\IShare
852
-	 * @throws ShareNotFound
853
-	 */
854
-	private function getShareById($id) {
855
-		$share = null;
856
-
857
-		// First check if it is an internal share.
858
-		try {
859
-			$share = $this->shareManager->getShareById('ocinternal:' . $id);
860
-			return $share;
861
-		} catch (ShareNotFound $e) {
862
-			// Do nothing, just try the other share type
863
-		}
864
-
865
-
866
-		try {
867
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
868
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id);
869
-				return $share;
870
-			}
871
-		} catch (ShareNotFound $e) {
872
-			// Do nothing, just try the other share type
873
-		}
874
-
875
-		try {
876
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
877
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id);
878
-				return $share;
879
-			}
880
-		} catch (ShareNotFound $e) {
881
-			// Do nothing, just try the other share type
882
-		}
883
-
884
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
885
-			throw new ShareNotFound();
886
-		}
887
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
888
-
889
-		return $share;
890
-	}
891
-
892
-	/**
893
-	 * Lock a Node
894
-	 *
895
-	 * @param \OCP\Files\Node $node
896
-	 */
897
-	private function lock(\OCP\Files\Node $node) {
898
-		$node->lock(ILockingProvider::LOCK_SHARED);
899
-		$this->lockedNode = $node;
900
-	}
901
-
902
-	/**
903
-	 * Cleanup the remaining locks
904
-	 */
905
-	public function cleanup() {
906
-		if ($this->lockedNode !== null) {
907
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
908
-		}
909
-	}
674
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
675
+            if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
676
+                throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
677
+            }
678
+
679
+            $newPermissions = null;
680
+            if ($publicUpload === 'true') {
681
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
682
+            } else if ($publicUpload === 'false') {
683
+                $newPermissions = \OCP\Constants::PERMISSION_READ;
684
+            }
685
+
686
+            if ($permissions !== null) {
687
+                $newPermissions = (int)$permissions;
688
+            }
689
+
690
+            if ($newPermissions !== null &&
691
+                !in_array($newPermissions, [
692
+                    \OCP\Constants::PERMISSION_READ,
693
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
694
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
695
+                    \OCP\Constants::PERMISSION_CREATE, // hidden file list
696
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
697
+                ])
698
+            ) {
699
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
700
+            }
701
+
702
+            if (
703
+                // legacy
704
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
705
+                // correct
706
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
707
+            ) {
708
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
709
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
710
+                }
711
+
712
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
713
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
714
+                }
715
+
716
+                // normalize to correct public upload permissions
717
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
718
+            }
719
+
720
+            if ($newPermissions !== null) {
721
+                $share->setPermissions($newPermissions);
722
+                $permissions = $newPermissions;
723
+            }
724
+
725
+            if ($expireDate === '') {
726
+                $share->setExpirationDate(null);
727
+            } else if ($expireDate !== null) {
728
+                try {
729
+                    $expireDate = $this->parseDate($expireDate);
730
+                } catch (\Exception $e) {
731
+                    throw new OCSBadRequestException($e->getMessage());
732
+                }
733
+                $share->setExpirationDate($expireDate);
734
+            }
735
+
736
+            if ($password === '') {
737
+                $share->setPassword(null);
738
+            } else if ($password !== null) {
739
+                $share->setPassword($password);
740
+            }
741
+
742
+        } else {
743
+            // For other shares only permissions is valid.
744
+            if ($permissions === null) {
745
+                throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
746
+            } else {
747
+                $permissions = (int)$permissions;
748
+                $share->setPermissions($permissions);
749
+            }
750
+        }
751
+
752
+        if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
753
+            /* Check if this is an incomming share */
754
+            $incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
755
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
756
+
757
+            /** @var \OCP\Share\IShare[] $incomingShares */
758
+            if (!empty($incomingShares)) {
759
+                $maxPermissions = 0;
760
+                foreach ($incomingShares as $incomingShare) {
761
+                    $maxPermissions |= $incomingShare->getPermissions();
762
+                }
763
+
764
+                if ($share->getPermissions() & ~$maxPermissions) {
765
+                    throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
766
+                }
767
+            }
768
+        }
769
+
770
+
771
+        try {
772
+            $share = $this->shareManager->updateShare($share);
773
+        } catch (\Exception $e) {
774
+            throw new OCSBadRequestException($e->getMessage());
775
+        }
776
+
777
+        return new DataResponse($this->formatShare($share));
778
+    }
779
+
780
+    /**
781
+     * @param \OCP\Share\IShare $share
782
+     * @return bool
783
+     */
784
+    protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
785
+        // A file with permissions 0 can't be accessed by us. So Don't show it
786
+        if ($share->getPermissions() === 0) {
787
+            return false;
788
+        }
789
+
790
+        // Owner of the file and the sharer of the file can always get share
791
+        if ($share->getShareOwner() === $this->currentUser ||
792
+            $share->getSharedBy() === $this->currentUser
793
+        ) {
794
+            return true;
795
+        }
796
+
797
+        // If the share is shared with you (or a group you are a member of)
798
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
799
+            $share->getSharedWith() === $this->currentUser
800
+        ) {
801
+            return true;
802
+        }
803
+
804
+        if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
805
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
806
+            $user = $this->userManager->get($this->currentUser);
807
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
808
+                return true;
809
+            }
810
+        }
811
+
812
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
813
+            // TODO: have a sanity check like above?
814
+            return true;
815
+        }
816
+
817
+        return false;
818
+    }
819
+
820
+    /**
821
+     * Make sure that the passed date is valid ISO 8601
822
+     * So YYYY-MM-DD
823
+     * If not throw an exception
824
+     *
825
+     * @param string $expireDate
826
+     *
827
+     * @throws \Exception
828
+     * @return \DateTime
829
+     */
830
+    private function parseDate($expireDate) {
831
+        try {
832
+            $date = new \DateTime($expireDate);
833
+        } catch (\Exception $e) {
834
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
835
+        }
836
+
837
+        if ($date === false) {
838
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
839
+        }
840
+
841
+        $date->setTime(0, 0, 0);
842
+
843
+        return $date;
844
+    }
845
+
846
+    /**
847
+     * Since we have multiple providers but the OCS Share API v1 does
848
+     * not support this we need to check all backends.
849
+     *
850
+     * @param string $id
851
+     * @return \OCP\Share\IShare
852
+     * @throws ShareNotFound
853
+     */
854
+    private function getShareById($id) {
855
+        $share = null;
856
+
857
+        // First check if it is an internal share.
858
+        try {
859
+            $share = $this->shareManager->getShareById('ocinternal:' . $id);
860
+            return $share;
861
+        } catch (ShareNotFound $e) {
862
+            // Do nothing, just try the other share type
863
+        }
864
+
865
+
866
+        try {
867
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
868
+                $share = $this->shareManager->getShareById('ocCircleShare:' . $id);
869
+                return $share;
870
+            }
871
+        } catch (ShareNotFound $e) {
872
+            // Do nothing, just try the other share type
873
+        }
874
+
875
+        try {
876
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
877
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id);
878
+                return $share;
879
+            }
880
+        } catch (ShareNotFound $e) {
881
+            // Do nothing, just try the other share type
882
+        }
883
+
884
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
885
+            throw new ShareNotFound();
886
+        }
887
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
888
+
889
+        return $share;
890
+    }
891
+
892
+    /**
893
+     * Lock a Node
894
+     *
895
+     * @param \OCP\Files\Node $node
896
+     */
897
+    private function lock(\OCP\Files\Node $node) {
898
+        $node->lock(ILockingProvider::LOCK_SHARED);
899
+        $this->lockedNode = $node;
900
+    }
901
+
902
+    /**
903
+     * Cleanup the remaining locks
904
+     */
905
+    public function cleanup() {
906
+        if ($this->lockedNode !== null) {
907
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
908
+        }
909
+    }
910 910
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/MountProvider.php 2 patches
Indentation   +170 added lines, -170 removed lines patch added patch discarded remove patch
@@ -33,174 +33,174 @@
 block discarded – undo
33 33
 use OCP\Share\IManager;
34 34
 
35 35
 class MountProvider implements IMountProvider {
36
-	/**
37
-	 * @var \OCP\IConfig
38
-	 */
39
-	protected $config;
40
-
41
-	/**
42
-	 * @var IManager
43
-	 */
44
-	protected $shareManager;
45
-
46
-	/**
47
-	 * @var ILogger
48
-	 */
49
-	protected $logger;
50
-
51
-	/**
52
-	 * @param \OCP\IConfig $config
53
-	 * @param IManager $shareManager
54
-	 * @param ILogger $logger
55
-	 */
56
-	public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
57
-		$this->config = $config;
58
-		$this->shareManager = $shareManager;
59
-		$this->logger = $logger;
60
-	}
61
-
62
-
63
-	/**
64
-	 * Get all mountpoints applicable for the user and check for shares where we need to update the etags
65
-	 *
66
-	 * @param \OCP\IUser $user
67
-	 * @param \OCP\Files\Storage\IStorageFactory $storageFactory
68
-	 * @return \OCP\Files\Mount\IMountPoint[]
69
-	 */
70
-	public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
71
-
72
-		$shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
73
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
74
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_CIRCLE, null, -1));
75
-
76
-		// filter out excluded shares and group shares that includes self
77
-		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
78
-			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
79
-		});
80
-
81
-		$superShares = $this->buildSuperShares($shares, $user);
82
-
83
-		$mounts = [];
84
-		foreach ($superShares as $share) {
85
-			try {
86
-				$mounts[] = new SharedMount(
87
-					'\OCA\Files_Sharing\SharedStorage',
88
-					$mounts,
89
-					[
90
-						'user' => $user->getUID(),
91
-						// parent share
92
-						'superShare' => $share[0],
93
-						// children/component of the superShare
94
-						'groupedShares' => $share[1],
95
-					],
96
-					$storageFactory
97
-				);
98
-			} catch (\Exception $e) {
99
-				$this->logger->logException($e);
100
-				$this->logger->error('Error while trying to create shared mount');
101
-			}
102
-		}
103
-
104
-		// array_filter removes the null values from the array
105
-		return array_filter($mounts);
106
-	}
107
-
108
-	/**
109
-	 * Groups shares by path (nodeId) and target path
110
-	 *
111
-	 * @param \OCP\Share\IShare[] $shares
112
-	 * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
113
-	 * array is a group which itself is an array of shares
114
-	 */
115
-	private function groupShares(array $shares) {
116
-		$tmp = [];
117
-
118
-		foreach ($shares as $share) {
119
-			if (!isset($tmp[$share->getNodeId()])) {
120
-				$tmp[$share->getNodeId()] = [];
121
-			}
122
-			$tmp[$share->getNodeId()][] = $share;
123
-		}
124
-
125
-		$result = [];
126
-		// sort by stime, the super share will be based on the least recent share
127
-		foreach ($tmp as &$tmp2) {
128
-			@usort($tmp2, function($a, $b) {
129
-				if ($a->getShareTime() <= $b->getShareTime()) {
130
-					return -1;
131
-				}
132
-				return 1;
133
-			});
134
-			$result[] = $tmp2;
135
-		}
136
-
137
-		return array_values($result);
138
-	}
139
-
140
-	/**
141
-	 * Build super shares (virtual share) by grouping them by node id and target,
142
-	 * then for each group compute the super share and return it along with the matching
143
-	 * grouped shares. The most permissive permissions are used based on the permissions
144
-	 * of all shares within the group.
145
-	 *
146
-	 * @param \OCP\Share\IShare[] $allShares
147
-	 * @param \OCP\IUser $user user
148
-	 * @return array Tuple of [superShare, groupedShares]
149
-	 */
150
-	private function buildSuperShares(array $allShares, \OCP\IUser $user) {
151
-		$result = [];
152
-
153
-		$groupedShares = $this->groupShares($allShares);
154
-
155
-		/** @var \OCP\Share\IShare[] $shares */
156
-		foreach ($groupedShares as $shares) {
157
-			if (count($shares) === 0) {
158
-				continue;
159
-			}
160
-
161
-			$superShare = $this->shareManager->newShare();
162
-
163
-			// compute super share based on first entry of the group
164
-			$superShare->setId($shares[0]->getId())
165
-				->setShareOwner($shares[0]->getShareOwner())
166
-				->setNodeId($shares[0]->getNodeId())
167
-				->setTarget($shares[0]->getTarget());
168
-
169
-			// use most permissive permissions
170
-			$permissions = 0;
171
-			foreach ($shares as $share) {
172
-				$permissions |= $share->getPermissions();
173
-				if ($share->getTarget() !== $superShare->getTarget()) {
174
-					// adjust target, for database consistency
175
-					$share->setTarget($superShare->getTarget());
176
-					try {
177
-						$this->shareManager->moveShare($share, $user->getUID());
178
-					} catch (\InvalidArgumentException $e) {
179
-						// ignore as it is not important and we don't want to
180
-						// block FS setup
181
-
182
-						// the subsequent code anyway only uses the target of the
183
-						// super share
184
-
185
-						// such issue can usually happen when dealing with
186
-						// null groups which usually appear with group backend
187
-						// caching inconsistencies
188
-						$this->logger->debug(
189
-							'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
190
-							['app' => 'files_sharing']
191
-						);
192
-					}
193
-				}
194
-				if (!is_null($share->getNodeCacheEntry())) {
195
-					$superShare->setNodeCacheEntry($share->getNodeCacheEntry());
196
-				}
197
-			}
198
-
199
-			$superShare->setPermissions($permissions);
200
-
201
-			$result[] = [$superShare, $shares];
202
-		}
203
-
204
-		return $result;
205
-	}
36
+    /**
37
+     * @var \OCP\IConfig
38
+     */
39
+    protected $config;
40
+
41
+    /**
42
+     * @var IManager
43
+     */
44
+    protected $shareManager;
45
+
46
+    /**
47
+     * @var ILogger
48
+     */
49
+    protected $logger;
50
+
51
+    /**
52
+     * @param \OCP\IConfig $config
53
+     * @param IManager $shareManager
54
+     * @param ILogger $logger
55
+     */
56
+    public function __construct(IConfig $config, IManager $shareManager, ILogger $logger) {
57
+        $this->config = $config;
58
+        $this->shareManager = $shareManager;
59
+        $this->logger = $logger;
60
+    }
61
+
62
+
63
+    /**
64
+     * Get all mountpoints applicable for the user and check for shares where we need to update the etags
65
+     *
66
+     * @param \OCP\IUser $user
67
+     * @param \OCP\Files\Storage\IStorageFactory $storageFactory
68
+     * @return \OCP\Files\Mount\IMountPoint[]
69
+     */
70
+    public function getMountsForUser(IUser $user, IStorageFactory $storageFactory) {
71
+
72
+        $shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
73
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
74
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_CIRCLE, null, -1));
75
+
76
+        // filter out excluded shares and group shares that includes self
77
+        $shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
78
+            return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
79
+        });
80
+
81
+        $superShares = $this->buildSuperShares($shares, $user);
82
+
83
+        $mounts = [];
84
+        foreach ($superShares as $share) {
85
+            try {
86
+                $mounts[] = new SharedMount(
87
+                    '\OCA\Files_Sharing\SharedStorage',
88
+                    $mounts,
89
+                    [
90
+                        'user' => $user->getUID(),
91
+                        // parent share
92
+                        'superShare' => $share[0],
93
+                        // children/component of the superShare
94
+                        'groupedShares' => $share[1],
95
+                    ],
96
+                    $storageFactory
97
+                );
98
+            } catch (\Exception $e) {
99
+                $this->logger->logException($e);
100
+                $this->logger->error('Error while trying to create shared mount');
101
+            }
102
+        }
103
+
104
+        // array_filter removes the null values from the array
105
+        return array_filter($mounts);
106
+    }
107
+
108
+    /**
109
+     * Groups shares by path (nodeId) and target path
110
+     *
111
+     * @param \OCP\Share\IShare[] $shares
112
+     * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
113
+     * array is a group which itself is an array of shares
114
+     */
115
+    private function groupShares(array $shares) {
116
+        $tmp = [];
117
+
118
+        foreach ($shares as $share) {
119
+            if (!isset($tmp[$share->getNodeId()])) {
120
+                $tmp[$share->getNodeId()] = [];
121
+            }
122
+            $tmp[$share->getNodeId()][] = $share;
123
+        }
124
+
125
+        $result = [];
126
+        // sort by stime, the super share will be based on the least recent share
127
+        foreach ($tmp as &$tmp2) {
128
+            @usort($tmp2, function($a, $b) {
129
+                if ($a->getShareTime() <= $b->getShareTime()) {
130
+                    return -1;
131
+                }
132
+                return 1;
133
+            });
134
+            $result[] = $tmp2;
135
+        }
136
+
137
+        return array_values($result);
138
+    }
139
+
140
+    /**
141
+     * Build super shares (virtual share) by grouping them by node id and target,
142
+     * then for each group compute the super share and return it along with the matching
143
+     * grouped shares. The most permissive permissions are used based on the permissions
144
+     * of all shares within the group.
145
+     *
146
+     * @param \OCP\Share\IShare[] $allShares
147
+     * @param \OCP\IUser $user user
148
+     * @return array Tuple of [superShare, groupedShares]
149
+     */
150
+    private function buildSuperShares(array $allShares, \OCP\IUser $user) {
151
+        $result = [];
152
+
153
+        $groupedShares = $this->groupShares($allShares);
154
+
155
+        /** @var \OCP\Share\IShare[] $shares */
156
+        foreach ($groupedShares as $shares) {
157
+            if (count($shares) === 0) {
158
+                continue;
159
+            }
160
+
161
+            $superShare = $this->shareManager->newShare();
162
+
163
+            // compute super share based on first entry of the group
164
+            $superShare->setId($shares[0]->getId())
165
+                ->setShareOwner($shares[0]->getShareOwner())
166
+                ->setNodeId($shares[0]->getNodeId())
167
+                ->setTarget($shares[0]->getTarget());
168
+
169
+            // use most permissive permissions
170
+            $permissions = 0;
171
+            foreach ($shares as $share) {
172
+                $permissions |= $share->getPermissions();
173
+                if ($share->getTarget() !== $superShare->getTarget()) {
174
+                    // adjust target, for database consistency
175
+                    $share->setTarget($superShare->getTarget());
176
+                    try {
177
+                        $this->shareManager->moveShare($share, $user->getUID());
178
+                    } catch (\InvalidArgumentException $e) {
179
+                        // ignore as it is not important and we don't want to
180
+                        // block FS setup
181
+
182
+                        // the subsequent code anyway only uses the target of the
183
+                        // super share
184
+
185
+                        // such issue can usually happen when dealing with
186
+                        // null groups which usually appear with group backend
187
+                        // caching inconsistencies
188
+                        $this->logger->debug(
189
+                            'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
190
+                            ['app' => 'files_sharing']
191
+                        );
192
+                    }
193
+                }
194
+                if (!is_null($share->getNodeCacheEntry())) {
195
+                    $superShare->setNodeCacheEntry($share->getNodeCacheEntry());
196
+                }
197
+            }
198
+
199
+            $superShare->setPermissions($permissions);
200
+
201
+            $result[] = [$superShare, $shares];
202
+        }
203
+
204
+        return $result;
205
+    }
206 206
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_CIRCLE, null, -1));
75 75
 
76 76
 		// filter out excluded shares and group shares that includes self
77
-		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
77
+		$shares = array_filter($shares, function(\OCP\Share\IShare $share) use ($user) {
78 78
 			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
79 79
 		});
80 80
 
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 						// null groups which usually appear with group backend
187 187
 						// caching inconsistencies
188 188
 						$this->logger->debug(
189
-							'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
189
+							'Could not adjust share target for share '.$share->getId().' to make it consistent: '.$e->getMessage(),
190 190
 							['app' => 'files_sharing']
191 191
 						);
192 192
 					}
Please login to merge, or discard this patch.
lib/private/Server.php 2 patches
Indentation   +1471 added lines, -1471 removed lines patch added patch discarded remove patch
@@ -108,1480 +108,1480 @@
 block discarded – undo
108 108
  * TODO: hookup all manager classes
109 109
  */
110 110
 class Server extends ServerContainer implements IServerContainer {
111
-	/** @var string */
112
-	private $webRoot;
113
-
114
-	/**
115
-	 * @param string $webRoot
116
-	 * @param \OC\Config $config
117
-	 */
118
-	public function __construct($webRoot, \OC\Config $config) {
119
-		parent::__construct();
120
-		$this->webRoot = $webRoot;
121
-
122
-		$this->registerService('ContactsManager', function ($c) {
123
-			return new ContactsManager();
124
-		});
125
-
126
-		$this->registerService('PreviewManager', function (Server $c) {
127
-			return new PreviewManager(
128
-				$c->getConfig(),
129
-				$c->getRootFolder(),
130
-				$c->getAppDataDir('preview'),
131
-				$c->getEventDispatcher(),
132
-				$c->getSession()->get('user_id')
133
-			);
134
-		});
135
-
136
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
137
-			return new \OC\Preview\Watcher(
138
-				$c->getAppDataDir('preview')
139
-			);
140
-		});
141
-
142
-		$this->registerService('EncryptionManager', function (Server $c) {
143
-			$view = new View();
144
-			$util = new Encryption\Util(
145
-				$view,
146
-				$c->getUserManager(),
147
-				$c->getGroupManager(),
148
-				$c->getConfig()
149
-			);
150
-			return new Encryption\Manager(
151
-				$c->getConfig(),
152
-				$c->getLogger(),
153
-				$c->getL10N('core'),
154
-				new View(),
155
-				$util,
156
-				new ArrayCache()
157
-			);
158
-		});
159
-
160
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
161
-			$util = new Encryption\Util(
162
-				new View(),
163
-				$c->getUserManager(),
164
-				$c->getGroupManager(),
165
-				$c->getConfig()
166
-			);
167
-			return new Encryption\File($util);
168
-		});
169
-
170
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
171
-			$view = new View();
172
-			$util = new Encryption\Util(
173
-				$view,
174
-				$c->getUserManager(),
175
-				$c->getGroupManager(),
176
-				$c->getConfig()
177
-			);
178
-
179
-			return new Encryption\Keys\Storage($view, $util);
180
-		});
181
-		$this->registerService('TagMapper', function (Server $c) {
182
-			return new TagMapper($c->getDatabaseConnection());
183
-		});
184
-		$this->registerService('TagManager', function (Server $c) {
185
-			$tagMapper = $c->query('TagMapper');
186
-			return new TagManager($tagMapper, $c->getUserSession());
187
-		});
188
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
189
-			$config = $c->getConfig();
190
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
191
-			/** @var \OC\SystemTag\ManagerFactory $factory */
192
-			$factory = new $factoryClass($this);
193
-			return $factory;
194
-		});
195
-		$this->registerService('SystemTagManager', function (Server $c) {
196
-			return $c->query('SystemTagManagerFactory')->getManager();
197
-		});
198
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
199
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
200
-		});
201
-		$this->registerService('RootFolder', function (Server $c) {
202
-			$manager = \OC\Files\Filesystem::getMountManager(null);
203
-			$view = new View();
204
-			$root = new Root(
205
-				$manager,
206
-				$view,
207
-				null,
208
-				$c->getUserMountCache(),
209
-				$this->getLogger(),
210
-				$this->getUserManager()
211
-			);
212
-			$connector = new HookConnector($root, $view);
213
-			$connector->viewToNode();
214
-
215
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
216
-			$previewConnector->connectWatcher();
217
-
218
-			return $root;
219
-		});
220
-		$this->registerService('LazyRootFolder', function(Server $c) {
221
-			return new LazyRoot(function() use ($c) {
222
-				return $c->query('RootFolder');
223
-			});
224
-		});
225
-		$this->registerService('UserManager', function (Server $c) {
226
-			$config = $c->getConfig();
227
-			return new \OC\User\Manager($config);
228
-		});
229
-		$this->registerService('GroupManager', function (Server $c) {
230
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
231
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
232
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
233
-			});
234
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
235
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
236
-			});
237
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
238
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
239
-			});
240
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
241
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
242
-			});
243
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
244
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
245
-			});
246
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
247
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
248
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
249
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
250
-			});
251
-			return $groupManager;
252
-		});
253
-		$this->registerService(Store::class, function(Server $c) {
254
-			$session = $c->getSession();
255
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
256
-				$tokenProvider = $c->query('OC\Authentication\Token\IProvider');
257
-			} else {
258
-				$tokenProvider = null;
259
-			}
260
-			$logger = $c->getLogger();
261
-			return new Store($session, $logger, $tokenProvider);
262
-		});
263
-		$this->registerAlias(IStore::class, Store::class);
264
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
265
-			$dbConnection = $c->getDatabaseConnection();
266
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
267
-		});
268
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
269
-			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
270
-			$crypto = $c->getCrypto();
271
-			$config = $c->getConfig();
272
-			$logger = $c->getLogger();
273
-			$timeFactory = new TimeFactory();
274
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
275
-		});
276
-		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
277
-		$this->registerService('UserSession', function (Server $c) {
278
-			$manager = $c->getUserManager();
279
-			$session = new \OC\Session\Memory('');
280
-			$timeFactory = new TimeFactory();
281
-			// Token providers might require a working database. This code
282
-			// might however be called when ownCloud is not yet setup.
283
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
284
-				$defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
285
-			} else {
286
-				$defaultTokenProvider = null;
287
-			}
288
-
289
-			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
290
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
291
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
292
-			});
293
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
294
-				/** @var $user \OC\User\User */
295
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
296
-			});
297
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
298
-				/** @var $user \OC\User\User */
299
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
300
-			});
301
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
302
-				/** @var $user \OC\User\User */
303
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
304
-			});
305
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
306
-				/** @var $user \OC\User\User */
307
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
308
-			});
309
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
310
-				/** @var $user \OC\User\User */
311
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
312
-			});
313
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
314
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
315
-			});
316
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
317
-				/** @var $user \OC\User\User */
318
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
319
-			});
320
-			$userSession->listen('\OC\User', 'logout', function () {
321
-				\OC_Hook::emit('OC_User', 'logout', array());
322
-			});
323
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
324
-				/** @var $user \OC\User\User */
325
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
326
-			});
327
-			return $userSession;
328
-		});
329
-
330
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
331
-			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
332
-		});
333
-
334
-		$this->registerService('NavigationManager', function (Server $c) {
335
-			return new \OC\NavigationManager($c->getAppManager(),
336
-				$c->getURLGenerator(),
337
-				$c->getL10NFactory(),
338
-				$c->getUserSession(),
339
-				$c->getGroupManager());
340
-		});
341
-		$this->registerService('AllConfig', function (Server $c) {
342
-			return new \OC\AllConfig(
343
-				$c->getSystemConfig()
344
-			);
345
-		});
346
-		$this->registerService('SystemConfig', function ($c) use ($config) {
347
-			return new \OC\SystemConfig($config);
348
-		});
349
-		$this->registerService('AppConfig', function (Server $c) {
350
-			return new \OC\AppConfig($c->getDatabaseConnection());
351
-		});
352
-		$this->registerService('L10NFactory', function (Server $c) {
353
-			return new \OC\L10N\Factory(
354
-				$c->getConfig(),
355
-				$c->getRequest(),
356
-				$c->getUserSession(),
357
-				\OC::$SERVERROOT
358
-			);
359
-		});
360
-		$this->registerService('URLGenerator', function (Server $c) {
361
-			$config = $c->getConfig();
362
-			$cacheFactory = $c->getMemCacheFactory();
363
-			return new \OC\URLGenerator(
364
-				$config,
365
-				$cacheFactory
366
-			);
367
-		});
368
-		$this->registerService('AppHelper', function ($c) {
369
-			return new \OC\AppHelper();
370
-		});
371
-		$this->registerService('AppFetcher', function ($c) {
372
-			return new AppFetcher(
373
-				$this->getAppDataDir('appstore'),
374
-				$this->getHTTPClientService(),
375
-				$this->query(TimeFactory::class),
376
-				$this->getConfig()
377
-			);
378
-		});
379
-		$this->registerService('CategoryFetcher', function ($c) {
380
-			return new CategoryFetcher(
381
-				$this->getAppDataDir('appstore'),
382
-				$this->getHTTPClientService(),
383
-				$this->query(TimeFactory::class),
384
-				$this->getConfig()
385
-			);
386
-		});
387
-		$this->registerService('UserCache', function ($c) {
388
-			return new Cache\File();
389
-		});
390
-		$this->registerService('MemCacheFactory', function (Server $c) {
391
-			$config = $c->getConfig();
392
-
393
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
394
-				$v = \OC_App::getAppVersions();
395
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
396
-				$version = implode(',', $v);
397
-				$instanceId = \OC_Util::getInstanceId();
398
-				$path = \OC::$SERVERROOT;
399
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
400
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
401
-					$config->getSystemValue('memcache.local', null),
402
-					$config->getSystemValue('memcache.distributed', null),
403
-					$config->getSystemValue('memcache.locking', null)
404
-				);
405
-			}
406
-
407
-			return new \OC\Memcache\Factory('', $c->getLogger(),
408
-				'\\OC\\Memcache\\ArrayCache',
409
-				'\\OC\\Memcache\\ArrayCache',
410
-				'\\OC\\Memcache\\ArrayCache'
411
-			);
412
-		});
413
-		$this->registerService('RedisFactory', function (Server $c) {
414
-			$systemConfig = $c->getSystemConfig();
415
-			return new RedisFactory($systemConfig);
416
-		});
417
-		$this->registerService('ActivityManager', function (Server $c) {
418
-			return new \OC\Activity\Manager(
419
-				$c->getRequest(),
420
-				$c->getUserSession(),
421
-				$c->getConfig(),
422
-				$c->query(IValidator::class)
423
-			);
424
-		});
425
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
426
-			return new \OC\Activity\EventMerger(
427
-				$c->getL10N('lib')
428
-			);
429
-		});
430
-		$this->registerAlias(IValidator::class, Validator::class);
431
-		$this->registerService('AvatarManager', function (Server $c) {
432
-			return new AvatarManager(
433
-				$c->getUserManager(),
434
-				$c->getAppDataDir('avatar'),
435
-				$c->getL10N('lib'),
436
-				$c->getLogger(),
437
-				$c->getConfig()
438
-			);
439
-		});
440
-		$this->registerService('Logger', function (Server $c) {
441
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
442
-			$logger = Log::getLogClass($logType);
443
-			call_user_func(array($logger, 'init'));
444
-
445
-			return new Log($logger);
446
-		});
447
-		$this->registerService('JobList', function (Server $c) {
448
-			$config = $c->getConfig();
449
-			return new \OC\BackgroundJob\JobList(
450
-				$c->getDatabaseConnection(),
451
-				$config,
452
-				new TimeFactory()
453
-			);
454
-		});
455
-		$this->registerService('Router', function (Server $c) {
456
-			$cacheFactory = $c->getMemCacheFactory();
457
-			$logger = $c->getLogger();
458
-			if ($cacheFactory->isAvailable()) {
459
-				$router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
460
-			} else {
461
-				$router = new \OC\Route\Router($logger);
462
-			}
463
-			return $router;
464
-		});
465
-		$this->registerService('Search', function ($c) {
466
-			return new Search();
467
-		});
468
-		$this->registerService('SecureRandom', function ($c) {
469
-			return new SecureRandom();
470
-		});
471
-		$this->registerService('Crypto', function (Server $c) {
472
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
473
-		});
474
-		$this->registerService('Hasher', function (Server $c) {
475
-			return new Hasher($c->getConfig());
476
-		});
477
-		$this->registerService('CredentialsManager', function (Server $c) {
478
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
479
-		});
480
-		$this->registerService('DatabaseConnection', function (Server $c) {
481
-			$systemConfig = $c->getSystemConfig();
482
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
483
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
484
-			if (!$factory->isValidType($type)) {
485
-				throw new \OC\DatabaseException('Invalid database type');
486
-			}
487
-			$connectionParams = $factory->createConnectionParams();
488
-			$connection = $factory->getConnection($type, $connectionParams);
489
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
490
-			return $connection;
491
-		});
492
-		$this->registerService('HTTPHelper', function (Server $c) {
493
-			$config = $c->getConfig();
494
-			return new HTTPHelper(
495
-				$config,
496
-				$c->getHTTPClientService()
497
-			);
498
-		});
499
-		$this->registerService('HttpClientService', function (Server $c) {
500
-			$user = \OC_User::getUser();
501
-			$uid = $user ? $user : null;
502
-			return new ClientService(
503
-				$c->getConfig(),
504
-				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
505
-			);
506
-		});
507
-		$this->registerService('EventLogger', function (Server $c) {
508
-			if ($c->getSystemConfig()->getValue('debug', false)) {
509
-				return new EventLogger();
510
-			} else {
511
-				return new NullEventLogger();
512
-			}
513
-		});
514
-		$this->registerService('QueryLogger', function (Server $c) {
515
-			if ($c->getSystemConfig()->getValue('debug', false)) {
516
-				return new QueryLogger();
517
-			} else {
518
-				return new NullQueryLogger();
519
-			}
520
-		});
521
-		$this->registerService('TempManager', function (Server $c) {
522
-			return new TempManager(
523
-				$c->getLogger(),
524
-				$c->getConfig()
525
-			);
526
-		});
527
-		$this->registerService('AppManager', function (Server $c) {
528
-			return new \OC\App\AppManager(
529
-				$c->getUserSession(),
530
-				$c->getAppConfig(),
531
-				$c->getGroupManager(),
532
-				$c->getMemCacheFactory(),
533
-				$c->getEventDispatcher()
534
-			);
535
-		});
536
-		$this->registerService('DateTimeZone', function (Server $c) {
537
-			return new DateTimeZone(
538
-				$c->getConfig(),
539
-				$c->getSession()
540
-			);
541
-		});
542
-		$this->registerService('DateTimeFormatter', function (Server $c) {
543
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
544
-
545
-			return new DateTimeFormatter(
546
-				$c->getDateTimeZone()->getTimeZone(),
547
-				$c->getL10N('lib', $language)
548
-			);
549
-		});
550
-		$this->registerService('UserMountCache', function (Server $c) {
551
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
552
-			$listener = new UserMountCacheListener($mountCache);
553
-			$listener->listen($c->getUserManager());
554
-			return $mountCache;
555
-		});
556
-		$this->registerService('MountConfigManager', function (Server $c) {
557
-			$loader = \OC\Files\Filesystem::getLoader();
558
-			$mountCache = $c->query('UserMountCache');
559
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
560
-
561
-			// builtin providers
562
-
563
-			$config = $c->getConfig();
564
-			$manager->registerProvider(new CacheMountProvider($config));
565
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
566
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
567
-
568
-			return $manager;
569
-		});
570
-		$this->registerService('IniWrapper', function ($c) {
571
-			return new IniGetWrapper();
572
-		});
573
-		$this->registerService('AsyncCommandBus', function (Server $c) {
574
-			$jobList = $c->getJobList();
575
-			return new AsyncBus($jobList);
576
-		});
577
-		$this->registerService('TrustedDomainHelper', function ($c) {
578
-			return new TrustedDomainHelper($this->getConfig());
579
-		});
580
-		$this->registerService('Throttler', function(Server $c) {
581
-			return new Throttler(
582
-				$c->getDatabaseConnection(),
583
-				new TimeFactory(),
584
-				$c->getLogger(),
585
-				$c->getConfig()
586
-			);
587
-		});
588
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
589
-			// IConfig and IAppManager requires a working database. This code
590
-			// might however be called when ownCloud is not yet setup.
591
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
592
-				$config = $c->getConfig();
593
-				$appManager = $c->getAppManager();
594
-			} else {
595
-				$config = null;
596
-				$appManager = null;
597
-			}
598
-
599
-			return new Checker(
600
-					new EnvironmentHelper(),
601
-					new FileAccessHelper(),
602
-					new AppLocator(),
603
-					$config,
604
-					$c->getMemCacheFactory(),
605
-					$appManager,
606
-					$c->getTempManager()
607
-			);
608
-		});
609
-		$this->registerService('Request', function ($c) {
610
-			if (isset($this['urlParams'])) {
611
-				$urlParams = $this['urlParams'];
612
-			} else {
613
-				$urlParams = [];
614
-			}
615
-
616
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
617
-				&& in_array('fakeinput', stream_get_wrappers())
618
-			) {
619
-				$stream = 'fakeinput://data';
620
-			} else {
621
-				$stream = 'php://input';
622
-			}
623
-
624
-			return new Request(
625
-				[
626
-					'get' => $_GET,
627
-					'post' => $_POST,
628
-					'files' => $_FILES,
629
-					'server' => $_SERVER,
630
-					'env' => $_ENV,
631
-					'cookies' => $_COOKIE,
632
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
633
-						? $_SERVER['REQUEST_METHOD']
634
-						: null,
635
-					'urlParams' => $urlParams,
636
-				],
637
-				$this->getSecureRandom(),
638
-				$this->getConfig(),
639
-				$this->getCsrfTokenManager(),
640
-				$stream
641
-			);
642
-		});
643
-		$this->registerService('Mailer', function (Server $c) {
644
-			return new Mailer(
645
-				$c->getConfig(),
646
-				$c->getLogger(),
647
-				$c->getThemingDefaults()
648
-			);
649
-		});
650
-		$this->registerService('LDAPProvider', function(Server $c) {
651
-			$config = $c->getConfig();
652
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
653
-			if(is_null($factoryClass)) {
654
-				throw new \Exception('ldapProviderFactory not set');
655
-			}
656
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
657
-			$factory = new $factoryClass($this);
658
-			return $factory->getLDAPProvider();
659
-		});
660
-		$this->registerService('LockingProvider', function (Server $c) {
661
-			$ini = $c->getIniWrapper();
662
-			$config = $c->getConfig();
663
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
664
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
665
-				/** @var \OC\Memcache\Factory $memcacheFactory */
666
-				$memcacheFactory = $c->getMemCacheFactory();
667
-				$memcache = $memcacheFactory->createLocking('lock');
668
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
669
-					return new MemcacheLockingProvider($memcache, $ttl);
670
-				}
671
-				return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
672
-			}
673
-			return new NoopLockingProvider();
674
-		});
675
-		$this->registerService('MountManager', function () {
676
-			return new \OC\Files\Mount\Manager();
677
-		});
678
-		$this->registerService('MimeTypeDetector', function (Server $c) {
679
-			return new \OC\Files\Type\Detection(
680
-				$c->getURLGenerator(),
681
-				\OC::$configDir,
682
-				\OC::$SERVERROOT . '/resources/config/'
683
-			);
684
-		});
685
-		$this->registerService('MimeTypeLoader', function (Server $c) {
686
-			return new \OC\Files\Type\Loader(
687
-				$c->getDatabaseConnection()
688
-			);
689
-		});
690
-		$this->registerService('NotificationManager', function (Server $c) {
691
-			return new Manager(
692
-				$c->query(IValidator::class)
693
-			);
694
-		});
695
-		$this->registerService('CapabilitiesManager', function (Server $c) {
696
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
697
-			$manager->registerCapability(function () use ($c) {
698
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
699
-			});
700
-			return $manager;
701
-		});
702
-		$this->registerService('CommentsManager', function(Server $c) {
703
-			$config = $c->getConfig();
704
-			$factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
705
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
706
-			$factory = new $factoryClass($this);
707
-			return $factory->getManager();
708
-		});
709
-		$this->registerService('ThemingDefaults', function(Server $c) {
710
-			/*
111
+    /** @var string */
112
+    private $webRoot;
113
+
114
+    /**
115
+     * @param string $webRoot
116
+     * @param \OC\Config $config
117
+     */
118
+    public function __construct($webRoot, \OC\Config $config) {
119
+        parent::__construct();
120
+        $this->webRoot = $webRoot;
121
+
122
+        $this->registerService('ContactsManager', function ($c) {
123
+            return new ContactsManager();
124
+        });
125
+
126
+        $this->registerService('PreviewManager', function (Server $c) {
127
+            return new PreviewManager(
128
+                $c->getConfig(),
129
+                $c->getRootFolder(),
130
+                $c->getAppDataDir('preview'),
131
+                $c->getEventDispatcher(),
132
+                $c->getSession()->get('user_id')
133
+            );
134
+        });
135
+
136
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
137
+            return new \OC\Preview\Watcher(
138
+                $c->getAppDataDir('preview')
139
+            );
140
+        });
141
+
142
+        $this->registerService('EncryptionManager', function (Server $c) {
143
+            $view = new View();
144
+            $util = new Encryption\Util(
145
+                $view,
146
+                $c->getUserManager(),
147
+                $c->getGroupManager(),
148
+                $c->getConfig()
149
+            );
150
+            return new Encryption\Manager(
151
+                $c->getConfig(),
152
+                $c->getLogger(),
153
+                $c->getL10N('core'),
154
+                new View(),
155
+                $util,
156
+                new ArrayCache()
157
+            );
158
+        });
159
+
160
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
161
+            $util = new Encryption\Util(
162
+                new View(),
163
+                $c->getUserManager(),
164
+                $c->getGroupManager(),
165
+                $c->getConfig()
166
+            );
167
+            return new Encryption\File($util);
168
+        });
169
+
170
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
171
+            $view = new View();
172
+            $util = new Encryption\Util(
173
+                $view,
174
+                $c->getUserManager(),
175
+                $c->getGroupManager(),
176
+                $c->getConfig()
177
+            );
178
+
179
+            return new Encryption\Keys\Storage($view, $util);
180
+        });
181
+        $this->registerService('TagMapper', function (Server $c) {
182
+            return new TagMapper($c->getDatabaseConnection());
183
+        });
184
+        $this->registerService('TagManager', function (Server $c) {
185
+            $tagMapper = $c->query('TagMapper');
186
+            return new TagManager($tagMapper, $c->getUserSession());
187
+        });
188
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
189
+            $config = $c->getConfig();
190
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
191
+            /** @var \OC\SystemTag\ManagerFactory $factory */
192
+            $factory = new $factoryClass($this);
193
+            return $factory;
194
+        });
195
+        $this->registerService('SystemTagManager', function (Server $c) {
196
+            return $c->query('SystemTagManagerFactory')->getManager();
197
+        });
198
+        $this->registerService('SystemTagObjectMapper', function (Server $c) {
199
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
200
+        });
201
+        $this->registerService('RootFolder', function (Server $c) {
202
+            $manager = \OC\Files\Filesystem::getMountManager(null);
203
+            $view = new View();
204
+            $root = new Root(
205
+                $manager,
206
+                $view,
207
+                null,
208
+                $c->getUserMountCache(),
209
+                $this->getLogger(),
210
+                $this->getUserManager()
211
+            );
212
+            $connector = new HookConnector($root, $view);
213
+            $connector->viewToNode();
214
+
215
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
216
+            $previewConnector->connectWatcher();
217
+
218
+            return $root;
219
+        });
220
+        $this->registerService('LazyRootFolder', function(Server $c) {
221
+            return new LazyRoot(function() use ($c) {
222
+                return $c->query('RootFolder');
223
+            });
224
+        });
225
+        $this->registerService('UserManager', function (Server $c) {
226
+            $config = $c->getConfig();
227
+            return new \OC\User\Manager($config);
228
+        });
229
+        $this->registerService('GroupManager', function (Server $c) {
230
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
231
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
232
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
233
+            });
234
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
235
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
236
+            });
237
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
238
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
239
+            });
240
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
241
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
242
+            });
243
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
244
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
245
+            });
246
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
247
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
248
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
249
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
250
+            });
251
+            return $groupManager;
252
+        });
253
+        $this->registerService(Store::class, function(Server $c) {
254
+            $session = $c->getSession();
255
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
256
+                $tokenProvider = $c->query('OC\Authentication\Token\IProvider');
257
+            } else {
258
+                $tokenProvider = null;
259
+            }
260
+            $logger = $c->getLogger();
261
+            return new Store($session, $logger, $tokenProvider);
262
+        });
263
+        $this->registerAlias(IStore::class, Store::class);
264
+        $this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
265
+            $dbConnection = $c->getDatabaseConnection();
266
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
267
+        });
268
+        $this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
269
+            $mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
270
+            $crypto = $c->getCrypto();
271
+            $config = $c->getConfig();
272
+            $logger = $c->getLogger();
273
+            $timeFactory = new TimeFactory();
274
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
275
+        });
276
+        $this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
277
+        $this->registerService('UserSession', function (Server $c) {
278
+            $manager = $c->getUserManager();
279
+            $session = new \OC\Session\Memory('');
280
+            $timeFactory = new TimeFactory();
281
+            // Token providers might require a working database. This code
282
+            // might however be called when ownCloud is not yet setup.
283
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
284
+                $defaultTokenProvider = $c->query('OC\Authentication\Token\IProvider');
285
+            } else {
286
+                $defaultTokenProvider = null;
287
+            }
288
+
289
+            $userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
290
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
291
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
292
+            });
293
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
294
+                /** @var $user \OC\User\User */
295
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
296
+            });
297
+            $userSession->listen('\OC\User', 'preDelete', function ($user) {
298
+                /** @var $user \OC\User\User */
299
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
300
+            });
301
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
302
+                /** @var $user \OC\User\User */
303
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
304
+            });
305
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
306
+                /** @var $user \OC\User\User */
307
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
308
+            });
309
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
310
+                /** @var $user \OC\User\User */
311
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
312
+            });
313
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
314
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
315
+            });
316
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
317
+                /** @var $user \OC\User\User */
318
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
319
+            });
320
+            $userSession->listen('\OC\User', 'logout', function () {
321
+                \OC_Hook::emit('OC_User', 'logout', array());
322
+            });
323
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
324
+                /** @var $user \OC\User\User */
325
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
326
+            });
327
+            return $userSession;
328
+        });
329
+
330
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
331
+            return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
332
+        });
333
+
334
+        $this->registerService('NavigationManager', function (Server $c) {
335
+            return new \OC\NavigationManager($c->getAppManager(),
336
+                $c->getURLGenerator(),
337
+                $c->getL10NFactory(),
338
+                $c->getUserSession(),
339
+                $c->getGroupManager());
340
+        });
341
+        $this->registerService('AllConfig', function (Server $c) {
342
+            return new \OC\AllConfig(
343
+                $c->getSystemConfig()
344
+            );
345
+        });
346
+        $this->registerService('SystemConfig', function ($c) use ($config) {
347
+            return new \OC\SystemConfig($config);
348
+        });
349
+        $this->registerService('AppConfig', function (Server $c) {
350
+            return new \OC\AppConfig($c->getDatabaseConnection());
351
+        });
352
+        $this->registerService('L10NFactory', function (Server $c) {
353
+            return new \OC\L10N\Factory(
354
+                $c->getConfig(),
355
+                $c->getRequest(),
356
+                $c->getUserSession(),
357
+                \OC::$SERVERROOT
358
+            );
359
+        });
360
+        $this->registerService('URLGenerator', function (Server $c) {
361
+            $config = $c->getConfig();
362
+            $cacheFactory = $c->getMemCacheFactory();
363
+            return new \OC\URLGenerator(
364
+                $config,
365
+                $cacheFactory
366
+            );
367
+        });
368
+        $this->registerService('AppHelper', function ($c) {
369
+            return new \OC\AppHelper();
370
+        });
371
+        $this->registerService('AppFetcher', function ($c) {
372
+            return new AppFetcher(
373
+                $this->getAppDataDir('appstore'),
374
+                $this->getHTTPClientService(),
375
+                $this->query(TimeFactory::class),
376
+                $this->getConfig()
377
+            );
378
+        });
379
+        $this->registerService('CategoryFetcher', function ($c) {
380
+            return new CategoryFetcher(
381
+                $this->getAppDataDir('appstore'),
382
+                $this->getHTTPClientService(),
383
+                $this->query(TimeFactory::class),
384
+                $this->getConfig()
385
+            );
386
+        });
387
+        $this->registerService('UserCache', function ($c) {
388
+            return new Cache\File();
389
+        });
390
+        $this->registerService('MemCacheFactory', function (Server $c) {
391
+            $config = $c->getConfig();
392
+
393
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
394
+                $v = \OC_App::getAppVersions();
395
+                $v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
396
+                $version = implode(',', $v);
397
+                $instanceId = \OC_Util::getInstanceId();
398
+                $path = \OC::$SERVERROOT;
399
+                $prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
400
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
401
+                    $config->getSystemValue('memcache.local', null),
402
+                    $config->getSystemValue('memcache.distributed', null),
403
+                    $config->getSystemValue('memcache.locking', null)
404
+                );
405
+            }
406
+
407
+            return new \OC\Memcache\Factory('', $c->getLogger(),
408
+                '\\OC\\Memcache\\ArrayCache',
409
+                '\\OC\\Memcache\\ArrayCache',
410
+                '\\OC\\Memcache\\ArrayCache'
411
+            );
412
+        });
413
+        $this->registerService('RedisFactory', function (Server $c) {
414
+            $systemConfig = $c->getSystemConfig();
415
+            return new RedisFactory($systemConfig);
416
+        });
417
+        $this->registerService('ActivityManager', function (Server $c) {
418
+            return new \OC\Activity\Manager(
419
+                $c->getRequest(),
420
+                $c->getUserSession(),
421
+                $c->getConfig(),
422
+                $c->query(IValidator::class)
423
+            );
424
+        });
425
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
426
+            return new \OC\Activity\EventMerger(
427
+                $c->getL10N('lib')
428
+            );
429
+        });
430
+        $this->registerAlias(IValidator::class, Validator::class);
431
+        $this->registerService('AvatarManager', function (Server $c) {
432
+            return new AvatarManager(
433
+                $c->getUserManager(),
434
+                $c->getAppDataDir('avatar'),
435
+                $c->getL10N('lib'),
436
+                $c->getLogger(),
437
+                $c->getConfig()
438
+            );
439
+        });
440
+        $this->registerService('Logger', function (Server $c) {
441
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
442
+            $logger = Log::getLogClass($logType);
443
+            call_user_func(array($logger, 'init'));
444
+
445
+            return new Log($logger);
446
+        });
447
+        $this->registerService('JobList', function (Server $c) {
448
+            $config = $c->getConfig();
449
+            return new \OC\BackgroundJob\JobList(
450
+                $c->getDatabaseConnection(),
451
+                $config,
452
+                new TimeFactory()
453
+            );
454
+        });
455
+        $this->registerService('Router', function (Server $c) {
456
+            $cacheFactory = $c->getMemCacheFactory();
457
+            $logger = $c->getLogger();
458
+            if ($cacheFactory->isAvailable()) {
459
+                $router = new \OC\Route\CachingRouter($cacheFactory->create('route'), $logger);
460
+            } else {
461
+                $router = new \OC\Route\Router($logger);
462
+            }
463
+            return $router;
464
+        });
465
+        $this->registerService('Search', function ($c) {
466
+            return new Search();
467
+        });
468
+        $this->registerService('SecureRandom', function ($c) {
469
+            return new SecureRandom();
470
+        });
471
+        $this->registerService('Crypto', function (Server $c) {
472
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
473
+        });
474
+        $this->registerService('Hasher', function (Server $c) {
475
+            return new Hasher($c->getConfig());
476
+        });
477
+        $this->registerService('CredentialsManager', function (Server $c) {
478
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
479
+        });
480
+        $this->registerService('DatabaseConnection', function (Server $c) {
481
+            $systemConfig = $c->getSystemConfig();
482
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
483
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
484
+            if (!$factory->isValidType($type)) {
485
+                throw new \OC\DatabaseException('Invalid database type');
486
+            }
487
+            $connectionParams = $factory->createConnectionParams();
488
+            $connection = $factory->getConnection($type, $connectionParams);
489
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
490
+            return $connection;
491
+        });
492
+        $this->registerService('HTTPHelper', function (Server $c) {
493
+            $config = $c->getConfig();
494
+            return new HTTPHelper(
495
+                $config,
496
+                $c->getHTTPClientService()
497
+            );
498
+        });
499
+        $this->registerService('HttpClientService', function (Server $c) {
500
+            $user = \OC_User::getUser();
501
+            $uid = $user ? $user : null;
502
+            return new ClientService(
503
+                $c->getConfig(),
504
+                new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
505
+            );
506
+        });
507
+        $this->registerService('EventLogger', function (Server $c) {
508
+            if ($c->getSystemConfig()->getValue('debug', false)) {
509
+                return new EventLogger();
510
+            } else {
511
+                return new NullEventLogger();
512
+            }
513
+        });
514
+        $this->registerService('QueryLogger', function (Server $c) {
515
+            if ($c->getSystemConfig()->getValue('debug', false)) {
516
+                return new QueryLogger();
517
+            } else {
518
+                return new NullQueryLogger();
519
+            }
520
+        });
521
+        $this->registerService('TempManager', function (Server $c) {
522
+            return new TempManager(
523
+                $c->getLogger(),
524
+                $c->getConfig()
525
+            );
526
+        });
527
+        $this->registerService('AppManager', function (Server $c) {
528
+            return new \OC\App\AppManager(
529
+                $c->getUserSession(),
530
+                $c->getAppConfig(),
531
+                $c->getGroupManager(),
532
+                $c->getMemCacheFactory(),
533
+                $c->getEventDispatcher()
534
+            );
535
+        });
536
+        $this->registerService('DateTimeZone', function (Server $c) {
537
+            return new DateTimeZone(
538
+                $c->getConfig(),
539
+                $c->getSession()
540
+            );
541
+        });
542
+        $this->registerService('DateTimeFormatter', function (Server $c) {
543
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
544
+
545
+            return new DateTimeFormatter(
546
+                $c->getDateTimeZone()->getTimeZone(),
547
+                $c->getL10N('lib', $language)
548
+            );
549
+        });
550
+        $this->registerService('UserMountCache', function (Server $c) {
551
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
552
+            $listener = new UserMountCacheListener($mountCache);
553
+            $listener->listen($c->getUserManager());
554
+            return $mountCache;
555
+        });
556
+        $this->registerService('MountConfigManager', function (Server $c) {
557
+            $loader = \OC\Files\Filesystem::getLoader();
558
+            $mountCache = $c->query('UserMountCache');
559
+            $manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
560
+
561
+            // builtin providers
562
+
563
+            $config = $c->getConfig();
564
+            $manager->registerProvider(new CacheMountProvider($config));
565
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
566
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
567
+
568
+            return $manager;
569
+        });
570
+        $this->registerService('IniWrapper', function ($c) {
571
+            return new IniGetWrapper();
572
+        });
573
+        $this->registerService('AsyncCommandBus', function (Server $c) {
574
+            $jobList = $c->getJobList();
575
+            return new AsyncBus($jobList);
576
+        });
577
+        $this->registerService('TrustedDomainHelper', function ($c) {
578
+            return new TrustedDomainHelper($this->getConfig());
579
+        });
580
+        $this->registerService('Throttler', function(Server $c) {
581
+            return new Throttler(
582
+                $c->getDatabaseConnection(),
583
+                new TimeFactory(),
584
+                $c->getLogger(),
585
+                $c->getConfig()
586
+            );
587
+        });
588
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
589
+            // IConfig and IAppManager requires a working database. This code
590
+            // might however be called when ownCloud is not yet setup.
591
+            if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
592
+                $config = $c->getConfig();
593
+                $appManager = $c->getAppManager();
594
+            } else {
595
+                $config = null;
596
+                $appManager = null;
597
+            }
598
+
599
+            return new Checker(
600
+                    new EnvironmentHelper(),
601
+                    new FileAccessHelper(),
602
+                    new AppLocator(),
603
+                    $config,
604
+                    $c->getMemCacheFactory(),
605
+                    $appManager,
606
+                    $c->getTempManager()
607
+            );
608
+        });
609
+        $this->registerService('Request', function ($c) {
610
+            if (isset($this['urlParams'])) {
611
+                $urlParams = $this['urlParams'];
612
+            } else {
613
+                $urlParams = [];
614
+            }
615
+
616
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
617
+                && in_array('fakeinput', stream_get_wrappers())
618
+            ) {
619
+                $stream = 'fakeinput://data';
620
+            } else {
621
+                $stream = 'php://input';
622
+            }
623
+
624
+            return new Request(
625
+                [
626
+                    'get' => $_GET,
627
+                    'post' => $_POST,
628
+                    'files' => $_FILES,
629
+                    'server' => $_SERVER,
630
+                    'env' => $_ENV,
631
+                    'cookies' => $_COOKIE,
632
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
633
+                        ? $_SERVER['REQUEST_METHOD']
634
+                        : null,
635
+                    'urlParams' => $urlParams,
636
+                ],
637
+                $this->getSecureRandom(),
638
+                $this->getConfig(),
639
+                $this->getCsrfTokenManager(),
640
+                $stream
641
+            );
642
+        });
643
+        $this->registerService('Mailer', function (Server $c) {
644
+            return new Mailer(
645
+                $c->getConfig(),
646
+                $c->getLogger(),
647
+                $c->getThemingDefaults()
648
+            );
649
+        });
650
+        $this->registerService('LDAPProvider', function(Server $c) {
651
+            $config = $c->getConfig();
652
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
653
+            if(is_null($factoryClass)) {
654
+                throw new \Exception('ldapProviderFactory not set');
655
+            }
656
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
657
+            $factory = new $factoryClass($this);
658
+            return $factory->getLDAPProvider();
659
+        });
660
+        $this->registerService('LockingProvider', function (Server $c) {
661
+            $ini = $c->getIniWrapper();
662
+            $config = $c->getConfig();
663
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
664
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
665
+                /** @var \OC\Memcache\Factory $memcacheFactory */
666
+                $memcacheFactory = $c->getMemCacheFactory();
667
+                $memcache = $memcacheFactory->createLocking('lock');
668
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
669
+                    return new MemcacheLockingProvider($memcache, $ttl);
670
+                }
671
+                return new DBLockingProvider($c->getDatabaseConnection(), $c->getLogger(), new TimeFactory(), $ttl);
672
+            }
673
+            return new NoopLockingProvider();
674
+        });
675
+        $this->registerService('MountManager', function () {
676
+            return new \OC\Files\Mount\Manager();
677
+        });
678
+        $this->registerService('MimeTypeDetector', function (Server $c) {
679
+            return new \OC\Files\Type\Detection(
680
+                $c->getURLGenerator(),
681
+                \OC::$configDir,
682
+                \OC::$SERVERROOT . '/resources/config/'
683
+            );
684
+        });
685
+        $this->registerService('MimeTypeLoader', function (Server $c) {
686
+            return new \OC\Files\Type\Loader(
687
+                $c->getDatabaseConnection()
688
+            );
689
+        });
690
+        $this->registerService('NotificationManager', function (Server $c) {
691
+            return new Manager(
692
+                $c->query(IValidator::class)
693
+            );
694
+        });
695
+        $this->registerService('CapabilitiesManager', function (Server $c) {
696
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
697
+            $manager->registerCapability(function () use ($c) {
698
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
699
+            });
700
+            return $manager;
701
+        });
702
+        $this->registerService('CommentsManager', function(Server $c) {
703
+            $config = $c->getConfig();
704
+            $factoryClass = $config->getSystemValue('comments.managerFactory', '\OC\Comments\ManagerFactory');
705
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
706
+            $factory = new $factoryClass($this);
707
+            return $factory->getManager();
708
+        });
709
+        $this->registerService('ThemingDefaults', function(Server $c) {
710
+            /*
711 711
 			 * Dark magic for autoloader.
712 712
 			 * If we do a class_exists it will try to load the class which will
713 713
 			 * make composer cache the result. Resulting in errors when enabling
714 714
 			 * the theming app.
715 715
 			 */
716
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
717
-			if (isset($prefixes['OCA\\Theming\\'])) {
718
-				$classExists = true;
719
-			} else {
720
-				$classExists = false;
721
-			}
722
-
723
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
724
-				return new ThemingDefaults(
725
-					$c->getConfig(),
726
-					$c->getL10N('theming'),
727
-					$c->getURLGenerator(),
728
-					new \OC_Defaults(),
729
-					$c->getLazyRootFolder(),
730
-					$c->getMemCacheFactory()
731
-				);
732
-			}
733
-			return new \OC_Defaults();
734
-		});
735
-		$this->registerService('EventDispatcher', function () {
736
-			return new EventDispatcher();
737
-		});
738
-		$this->registerService('CryptoWrapper', function (Server $c) {
739
-			// FIXME: Instantiiated here due to cyclic dependency
740
-			$request = new Request(
741
-				[
742
-					'get' => $_GET,
743
-					'post' => $_POST,
744
-					'files' => $_FILES,
745
-					'server' => $_SERVER,
746
-					'env' => $_ENV,
747
-					'cookies' => $_COOKIE,
748
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
749
-						? $_SERVER['REQUEST_METHOD']
750
-						: null,
751
-				],
752
-				$c->getSecureRandom(),
753
-				$c->getConfig()
754
-			);
755
-
756
-			return new CryptoWrapper(
757
-				$c->getConfig(),
758
-				$c->getCrypto(),
759
-				$c->getSecureRandom(),
760
-				$request
761
-			);
762
-		});
763
-		$this->registerService('CsrfTokenManager', function (Server $c) {
764
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
765
-
766
-			return new CsrfTokenManager(
767
-				$tokenGenerator,
768
-				$c->query(SessionStorage::class)
769
-			);
770
-		});
771
-		$this->registerService(SessionStorage::class, function (Server $c) {
772
-			return new SessionStorage($c->getSession());
773
-		});
774
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
775
-			return new ContentSecurityPolicyManager();
776
-		});
777
-		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
778
-			return new ContentSecurityPolicyNonceManager(
779
-				$c->getCsrfTokenManager(),
780
-				$c->getRequest()
781
-			);
782
-		});
783
-		$this->registerService('ShareManager', function(Server $c) {
784
-			$config = $c->getConfig();
785
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
786
-			/** @var \OCP\Share\IProviderFactory $factory */
787
-			$factory = new $factoryClass($this);
788
-
789
-			$manager = new \OC\Share20\Manager(
790
-				$c->getLogger(),
791
-				$c->getConfig(),
792
-				$c->getSecureRandom(),
793
-				$c->getHasher(),
794
-				$c->getMountManager(),
795
-				$c->getGroupManager(),
796
-				$c->getL10N('core'),
797
-				$factory,
798
-				$c->getUserManager(),
799
-				$c->getLazyRootFolder(),
800
-				$c->getEventDispatcher()
801
-			);
802
-
803
-			return $manager;
804
-		});
805
-		$this->registerService('SettingsManager', function(Server $c) {
806
-			$manager = new \OC\Settings\Manager(
807
-				$c->getLogger(),
808
-				$c->getDatabaseConnection(),
809
-				$c->getL10N('lib'),
810
-				$c->getConfig(),
811
-				$c->getEncryptionManager(),
812
-				$c->getUserManager(),
813
-				$c->getLockingProvider(),
814
-				$c->getRequest(),
815
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
816
-				$c->getURLGenerator()
817
-			);
818
-			return $manager;
819
-		});
820
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
821
-			return new \OC\Files\AppData\Factory(
822
-				$c->getRootFolder(),
823
-				$c->getSystemConfig()
824
-			);
825
-		});
826
-
827
-		$this->registerService('LockdownManager', function (Server $c) {
828
-			return new LockdownManager();
829
-		});
830
-
831
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
832
-			return new CloudIdManager();
833
-		});
834
-
835
-		/* To trick DI since we don't extend the DIContainer here */
836
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
837
-			return new CleanPreviewsBackgroundJob(
838
-				$c->getRootFolder(),
839
-				$c->getLogger(),
840
-				$c->getJobList(),
841
-				new TimeFactory()
842
-			);
843
-		});
844
-	}
845
-
846
-	/**
847
-	 * @return \OCP\Contacts\IManager
848
-	 */
849
-	public function getContactsManager() {
850
-		return $this->query('ContactsManager');
851
-	}
852
-
853
-	/**
854
-	 * @return \OC\Encryption\Manager
855
-	 */
856
-	public function getEncryptionManager() {
857
-		return $this->query('EncryptionManager');
858
-	}
859
-
860
-	/**
861
-	 * @return \OC\Encryption\File
862
-	 */
863
-	public function getEncryptionFilesHelper() {
864
-		return $this->query('EncryptionFileHelper');
865
-	}
866
-
867
-	/**
868
-	 * @return \OCP\Encryption\Keys\IStorage
869
-	 */
870
-	public function getEncryptionKeyStorage() {
871
-		return $this->query('EncryptionKeyStorage');
872
-	}
873
-
874
-	/**
875
-	 * The current request object holding all information about the request
876
-	 * currently being processed is returned from this method.
877
-	 * In case the current execution was not initiated by a web request null is returned
878
-	 *
879
-	 * @return \OCP\IRequest
880
-	 */
881
-	public function getRequest() {
882
-		return $this->query('Request');
883
-	}
884
-
885
-	/**
886
-	 * Returns the preview manager which can create preview images for a given file
887
-	 *
888
-	 * @return \OCP\IPreview
889
-	 */
890
-	public function getPreviewManager() {
891
-		return $this->query('PreviewManager');
892
-	}
893
-
894
-	/**
895
-	 * Returns the tag manager which can get and set tags for different object types
896
-	 *
897
-	 * @see \OCP\ITagManager::load()
898
-	 * @return \OCP\ITagManager
899
-	 */
900
-	public function getTagManager() {
901
-		return $this->query('TagManager');
902
-	}
903
-
904
-	/**
905
-	 * Returns the system-tag manager
906
-	 *
907
-	 * @return \OCP\SystemTag\ISystemTagManager
908
-	 *
909
-	 * @since 9.0.0
910
-	 */
911
-	public function getSystemTagManager() {
912
-		return $this->query('SystemTagManager');
913
-	}
914
-
915
-	/**
916
-	 * Returns the system-tag object mapper
917
-	 *
918
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
919
-	 *
920
-	 * @since 9.0.0
921
-	 */
922
-	public function getSystemTagObjectMapper() {
923
-		return $this->query('SystemTagObjectMapper');
924
-	}
925
-
926
-	/**
927
-	 * Returns the avatar manager, used for avatar functionality
928
-	 *
929
-	 * @return \OCP\IAvatarManager
930
-	 */
931
-	public function getAvatarManager() {
932
-		return $this->query('AvatarManager');
933
-	}
934
-
935
-	/**
936
-	 * Returns the root folder of ownCloud's data directory
937
-	 *
938
-	 * @return \OCP\Files\IRootFolder
939
-	 */
940
-	public function getRootFolder() {
941
-		return $this->query('LazyRootFolder');
942
-	}
943
-
944
-	/**
945
-	 * Returns the root folder of ownCloud's data directory
946
-	 * This is the lazy variant so this gets only initialized once it
947
-	 * is actually used.
948
-	 *
949
-	 * @return \OCP\Files\IRootFolder
950
-	 */
951
-	public function getLazyRootFolder() {
952
-		return $this->query('LazyRootFolder');
953
-	}
954
-
955
-	/**
956
-	 * Returns a view to ownCloud's files folder
957
-	 *
958
-	 * @param string $userId user ID
959
-	 * @return \OCP\Files\Folder|null
960
-	 */
961
-	public function getUserFolder($userId = null) {
962
-		if ($userId === null) {
963
-			$user = $this->getUserSession()->getUser();
964
-			if (!$user) {
965
-				return null;
966
-			}
967
-			$userId = $user->getUID();
968
-		}
969
-		$root = $this->getRootFolder();
970
-		return $root->getUserFolder($userId);
971
-	}
972
-
973
-	/**
974
-	 * Returns an app-specific view in ownClouds data directory
975
-	 *
976
-	 * @return \OCP\Files\Folder
977
-	 * @deprecated since 9.2.0 use IAppData
978
-	 */
979
-	public function getAppFolder() {
980
-		$dir = '/' . \OC_App::getCurrentApp();
981
-		$root = $this->getRootFolder();
982
-		if (!$root->nodeExists($dir)) {
983
-			$folder = $root->newFolder($dir);
984
-		} else {
985
-			$folder = $root->get($dir);
986
-		}
987
-		return $folder;
988
-	}
989
-
990
-	/**
991
-	 * @return \OC\User\Manager
992
-	 */
993
-	public function getUserManager() {
994
-		return $this->query('UserManager');
995
-	}
996
-
997
-	/**
998
-	 * @return \OC\Group\Manager
999
-	 */
1000
-	public function getGroupManager() {
1001
-		return $this->query('GroupManager');
1002
-	}
1003
-
1004
-	/**
1005
-	 * @return \OC\User\Session
1006
-	 */
1007
-	public function getUserSession() {
1008
-		return $this->query('UserSession');
1009
-	}
1010
-
1011
-	/**
1012
-	 * @return \OCP\ISession
1013
-	 */
1014
-	public function getSession() {
1015
-		return $this->query('UserSession')->getSession();
1016
-	}
1017
-
1018
-	/**
1019
-	 * @param \OCP\ISession $session
1020
-	 */
1021
-	public function setSession(\OCP\ISession $session) {
1022
-		$this->query(SessionStorage::class)->setSession($session);
1023
-		$this->query('UserSession')->setSession($session);
1024
-		$this->query(Store::class)->setSession($session);
1025
-	}
1026
-
1027
-	/**
1028
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1029
-	 */
1030
-	public function getTwoFactorAuthManager() {
1031
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1032
-	}
1033
-
1034
-	/**
1035
-	 * @return \OC\NavigationManager
1036
-	 */
1037
-	public function getNavigationManager() {
1038
-		return $this->query('NavigationManager');
1039
-	}
1040
-
1041
-	/**
1042
-	 * @return \OCP\IConfig
1043
-	 */
1044
-	public function getConfig() {
1045
-		return $this->query('AllConfig');
1046
-	}
1047
-
1048
-	/**
1049
-	 * @internal For internal use only
1050
-	 * @return \OC\SystemConfig
1051
-	 */
1052
-	public function getSystemConfig() {
1053
-		return $this->query('SystemConfig');
1054
-	}
1055
-
1056
-	/**
1057
-	 * Returns the app config manager
1058
-	 *
1059
-	 * @return \OCP\IAppConfig
1060
-	 */
1061
-	public function getAppConfig() {
1062
-		return $this->query('AppConfig');
1063
-	}
1064
-
1065
-	/**
1066
-	 * @return \OCP\L10N\IFactory
1067
-	 */
1068
-	public function getL10NFactory() {
1069
-		return $this->query('L10NFactory');
1070
-	}
1071
-
1072
-	/**
1073
-	 * get an L10N instance
1074
-	 *
1075
-	 * @param string $app appid
1076
-	 * @param string $lang
1077
-	 * @return IL10N
1078
-	 */
1079
-	public function getL10N($app, $lang = null) {
1080
-		return $this->getL10NFactory()->get($app, $lang);
1081
-	}
1082
-
1083
-	/**
1084
-	 * @return \OCP\IURLGenerator
1085
-	 */
1086
-	public function getURLGenerator() {
1087
-		return $this->query('URLGenerator');
1088
-	}
1089
-
1090
-	/**
1091
-	 * @return \OCP\IHelper
1092
-	 */
1093
-	public function getHelper() {
1094
-		return $this->query('AppHelper');
1095
-	}
1096
-
1097
-	/**
1098
-	 * @return AppFetcher
1099
-	 */
1100
-	public function getAppFetcher() {
1101
-		return $this->query('AppFetcher');
1102
-	}
1103
-
1104
-	/**
1105
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1106
-	 * getMemCacheFactory() instead.
1107
-	 *
1108
-	 * @return \OCP\ICache
1109
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1110
-	 */
1111
-	public function getCache() {
1112
-		return $this->query('UserCache');
1113
-	}
1114
-
1115
-	/**
1116
-	 * Returns an \OCP\CacheFactory instance
1117
-	 *
1118
-	 * @return \OCP\ICacheFactory
1119
-	 */
1120
-	public function getMemCacheFactory() {
1121
-		return $this->query('MemCacheFactory');
1122
-	}
1123
-
1124
-	/**
1125
-	 * Returns an \OC\RedisFactory instance
1126
-	 *
1127
-	 * @return \OC\RedisFactory
1128
-	 */
1129
-	public function getGetRedisFactory() {
1130
-		return $this->query('RedisFactory');
1131
-	}
1132
-
1133
-
1134
-	/**
1135
-	 * Returns the current session
1136
-	 *
1137
-	 * @return \OCP\IDBConnection
1138
-	 */
1139
-	public function getDatabaseConnection() {
1140
-		return $this->query('DatabaseConnection');
1141
-	}
1142
-
1143
-	/**
1144
-	 * Returns the activity manager
1145
-	 *
1146
-	 * @return \OCP\Activity\IManager
1147
-	 */
1148
-	public function getActivityManager() {
1149
-		return $this->query('ActivityManager');
1150
-	}
1151
-
1152
-	/**
1153
-	 * Returns an job list for controlling background jobs
1154
-	 *
1155
-	 * @return \OCP\BackgroundJob\IJobList
1156
-	 */
1157
-	public function getJobList() {
1158
-		return $this->query('JobList');
1159
-	}
1160
-
1161
-	/**
1162
-	 * Returns a logger instance
1163
-	 *
1164
-	 * @return \OCP\ILogger
1165
-	 */
1166
-	public function getLogger() {
1167
-		return $this->query('Logger');
1168
-	}
1169
-
1170
-	/**
1171
-	 * Returns a router for generating and matching urls
1172
-	 *
1173
-	 * @return \OCP\Route\IRouter
1174
-	 */
1175
-	public function getRouter() {
1176
-		return $this->query('Router');
1177
-	}
1178
-
1179
-	/**
1180
-	 * Returns a search instance
1181
-	 *
1182
-	 * @return \OCP\ISearch
1183
-	 */
1184
-	public function getSearch() {
1185
-		return $this->query('Search');
1186
-	}
1187
-
1188
-	/**
1189
-	 * Returns a SecureRandom instance
1190
-	 *
1191
-	 * @return \OCP\Security\ISecureRandom
1192
-	 */
1193
-	public function getSecureRandom() {
1194
-		return $this->query('SecureRandom');
1195
-	}
1196
-
1197
-	/**
1198
-	 * Returns a Crypto instance
1199
-	 *
1200
-	 * @return \OCP\Security\ICrypto
1201
-	 */
1202
-	public function getCrypto() {
1203
-		return $this->query('Crypto');
1204
-	}
1205
-
1206
-	/**
1207
-	 * Returns a Hasher instance
1208
-	 *
1209
-	 * @return \OCP\Security\IHasher
1210
-	 */
1211
-	public function getHasher() {
1212
-		return $this->query('Hasher');
1213
-	}
1214
-
1215
-	/**
1216
-	 * Returns a CredentialsManager instance
1217
-	 *
1218
-	 * @return \OCP\Security\ICredentialsManager
1219
-	 */
1220
-	public function getCredentialsManager() {
1221
-		return $this->query('CredentialsManager');
1222
-	}
1223
-
1224
-	/**
1225
-	 * Returns an instance of the HTTP helper class
1226
-	 *
1227
-	 * @deprecated Use getHTTPClientService()
1228
-	 * @return \OC\HTTPHelper
1229
-	 */
1230
-	public function getHTTPHelper() {
1231
-		return $this->query('HTTPHelper');
1232
-	}
1233
-
1234
-	/**
1235
-	 * Get the certificate manager for the user
1236
-	 *
1237
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1238
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1239
-	 */
1240
-	public function getCertificateManager($userId = '') {
1241
-		if ($userId === '') {
1242
-			$userSession = $this->getUserSession();
1243
-			$user = $userSession->getUser();
1244
-			if (is_null($user)) {
1245
-				return null;
1246
-			}
1247
-			$userId = $user->getUID();
1248
-		}
1249
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1250
-	}
1251
-
1252
-	/**
1253
-	 * Returns an instance of the HTTP client service
1254
-	 *
1255
-	 * @return \OCP\Http\Client\IClientService
1256
-	 */
1257
-	public function getHTTPClientService() {
1258
-		return $this->query('HttpClientService');
1259
-	}
1260
-
1261
-	/**
1262
-	 * Create a new event source
1263
-	 *
1264
-	 * @return \OCP\IEventSource
1265
-	 */
1266
-	public function createEventSource() {
1267
-		return new \OC_EventSource();
1268
-	}
1269
-
1270
-	/**
1271
-	 * Get the active event logger
1272
-	 *
1273
-	 * The returned logger only logs data when debug mode is enabled
1274
-	 *
1275
-	 * @return \OCP\Diagnostics\IEventLogger
1276
-	 */
1277
-	public function getEventLogger() {
1278
-		return $this->query('EventLogger');
1279
-	}
1280
-
1281
-	/**
1282
-	 * Get the active query logger
1283
-	 *
1284
-	 * The returned logger only logs data when debug mode is enabled
1285
-	 *
1286
-	 * @return \OCP\Diagnostics\IQueryLogger
1287
-	 */
1288
-	public function getQueryLogger() {
1289
-		return $this->query('QueryLogger');
1290
-	}
1291
-
1292
-	/**
1293
-	 * Get the manager for temporary files and folders
1294
-	 *
1295
-	 * @return \OCP\ITempManager
1296
-	 */
1297
-	public function getTempManager() {
1298
-		return $this->query('TempManager');
1299
-	}
1300
-
1301
-	/**
1302
-	 * Get the app manager
1303
-	 *
1304
-	 * @return \OCP\App\IAppManager
1305
-	 */
1306
-	public function getAppManager() {
1307
-		return $this->query('AppManager');
1308
-	}
1309
-
1310
-	/**
1311
-	 * Creates a new mailer
1312
-	 *
1313
-	 * @return \OCP\Mail\IMailer
1314
-	 */
1315
-	public function getMailer() {
1316
-		return $this->query('Mailer');
1317
-	}
1318
-
1319
-	/**
1320
-	 * Get the webroot
1321
-	 *
1322
-	 * @return string
1323
-	 */
1324
-	public function getWebRoot() {
1325
-		return $this->webRoot;
1326
-	}
1327
-
1328
-	/**
1329
-	 * @return \OC\OCSClient
1330
-	 */
1331
-	public function getOcsClient() {
1332
-		return $this->query('OcsClient');
1333
-	}
1334
-
1335
-	/**
1336
-	 * @return \OCP\IDateTimeZone
1337
-	 */
1338
-	public function getDateTimeZone() {
1339
-		return $this->query('DateTimeZone');
1340
-	}
1341
-
1342
-	/**
1343
-	 * @return \OCP\IDateTimeFormatter
1344
-	 */
1345
-	public function getDateTimeFormatter() {
1346
-		return $this->query('DateTimeFormatter');
1347
-	}
1348
-
1349
-	/**
1350
-	 * @return \OCP\Files\Config\IMountProviderCollection
1351
-	 */
1352
-	public function getMountProviderCollection() {
1353
-		return $this->query('MountConfigManager');
1354
-	}
1355
-
1356
-	/**
1357
-	 * Get the IniWrapper
1358
-	 *
1359
-	 * @return IniGetWrapper
1360
-	 */
1361
-	public function getIniWrapper() {
1362
-		return $this->query('IniWrapper');
1363
-	}
1364
-
1365
-	/**
1366
-	 * @return \OCP\Command\IBus
1367
-	 */
1368
-	public function getCommandBus() {
1369
-		return $this->query('AsyncCommandBus');
1370
-	}
1371
-
1372
-	/**
1373
-	 * Get the trusted domain helper
1374
-	 *
1375
-	 * @return TrustedDomainHelper
1376
-	 */
1377
-	public function getTrustedDomainHelper() {
1378
-		return $this->query('TrustedDomainHelper');
1379
-	}
1380
-
1381
-	/**
1382
-	 * Get the locking provider
1383
-	 *
1384
-	 * @return \OCP\Lock\ILockingProvider
1385
-	 * @since 8.1.0
1386
-	 */
1387
-	public function getLockingProvider() {
1388
-		return $this->query('LockingProvider');
1389
-	}
1390
-
1391
-	/**
1392
-	 * @return \OCP\Files\Mount\IMountManager
1393
-	 **/
1394
-	function getMountManager() {
1395
-		return $this->query('MountManager');
1396
-	}
1397
-
1398
-	/** @return \OCP\Files\Config\IUserMountCache */
1399
-	function getUserMountCache() {
1400
-		return $this->query('UserMountCache');
1401
-	}
1402
-
1403
-	/**
1404
-	 * Get the MimeTypeDetector
1405
-	 *
1406
-	 * @return \OCP\Files\IMimeTypeDetector
1407
-	 */
1408
-	public function getMimeTypeDetector() {
1409
-		return $this->query('MimeTypeDetector');
1410
-	}
1411
-
1412
-	/**
1413
-	 * Get the MimeTypeLoader
1414
-	 *
1415
-	 * @return \OCP\Files\IMimeTypeLoader
1416
-	 */
1417
-	public function getMimeTypeLoader() {
1418
-		return $this->query('MimeTypeLoader');
1419
-	}
1420
-
1421
-	/**
1422
-	 * Get the manager of all the capabilities
1423
-	 *
1424
-	 * @return \OC\CapabilitiesManager
1425
-	 */
1426
-	public function getCapabilitiesManager() {
1427
-		return $this->query('CapabilitiesManager');
1428
-	}
1429
-
1430
-	/**
1431
-	 * Get the EventDispatcher
1432
-	 *
1433
-	 * @return EventDispatcherInterface
1434
-	 * @since 8.2.0
1435
-	 */
1436
-	public function getEventDispatcher() {
1437
-		return $this->query('EventDispatcher');
1438
-	}
1439
-
1440
-	/**
1441
-	 * Get the Notification Manager
1442
-	 *
1443
-	 * @return \OCP\Notification\IManager
1444
-	 * @since 8.2.0
1445
-	 */
1446
-	public function getNotificationManager() {
1447
-		return $this->query('NotificationManager');
1448
-	}
1449
-
1450
-	/**
1451
-	 * @return \OCP\Comments\ICommentsManager
1452
-	 */
1453
-	public function getCommentsManager() {
1454
-		return $this->query('CommentsManager');
1455
-	}
1456
-
1457
-	/**
1458
-	 * @return \OC_Defaults
1459
-	 */
1460
-	public function getThemingDefaults() {
1461
-		return $this->query('ThemingDefaults');
1462
-	}
1463
-
1464
-	/**
1465
-	 * @return \OC\IntegrityCheck\Checker
1466
-	 */
1467
-	public function getIntegrityCodeChecker() {
1468
-		return $this->query('IntegrityCodeChecker');
1469
-	}
1470
-
1471
-	/**
1472
-	 * @return \OC\Session\CryptoWrapper
1473
-	 */
1474
-	public function getSessionCryptoWrapper() {
1475
-		return $this->query('CryptoWrapper');
1476
-	}
1477
-
1478
-	/**
1479
-	 * @return CsrfTokenManager
1480
-	 */
1481
-	public function getCsrfTokenManager() {
1482
-		return $this->query('CsrfTokenManager');
1483
-	}
1484
-
1485
-	/**
1486
-	 * @return Throttler
1487
-	 */
1488
-	public function getBruteForceThrottler() {
1489
-		return $this->query('Throttler');
1490
-	}
1491
-
1492
-	/**
1493
-	 * @return IContentSecurityPolicyManager
1494
-	 */
1495
-	public function getContentSecurityPolicyManager() {
1496
-		return $this->query('ContentSecurityPolicyManager');
1497
-	}
1498
-
1499
-	/**
1500
-	 * @return ContentSecurityPolicyNonceManager
1501
-	 */
1502
-	public function getContentSecurityPolicyNonceManager() {
1503
-		return $this->query('ContentSecurityPolicyNonceManager');
1504
-	}
1505
-
1506
-	/**
1507
-	 * Not a public API as of 8.2, wait for 9.0
1508
-	 *
1509
-	 * @return \OCA\Files_External\Service\BackendService
1510
-	 */
1511
-	public function getStoragesBackendService() {
1512
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1513
-	}
1514
-
1515
-	/**
1516
-	 * Not a public API as of 8.2, wait for 9.0
1517
-	 *
1518
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1519
-	 */
1520
-	public function getGlobalStoragesService() {
1521
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1522
-	}
1523
-
1524
-	/**
1525
-	 * Not a public API as of 8.2, wait for 9.0
1526
-	 *
1527
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1528
-	 */
1529
-	public function getUserGlobalStoragesService() {
1530
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1531
-	}
1532
-
1533
-	/**
1534
-	 * Not a public API as of 8.2, wait for 9.0
1535
-	 *
1536
-	 * @return \OCA\Files_External\Service\UserStoragesService
1537
-	 */
1538
-	public function getUserStoragesService() {
1539
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1540
-	}
1541
-
1542
-	/**
1543
-	 * @return \OCP\Share\IManager
1544
-	 */
1545
-	public function getShareManager() {
1546
-		return $this->query('ShareManager');
1547
-	}
1548
-
1549
-	/**
1550
-	 * Returns the LDAP Provider
1551
-	 *
1552
-	 * @return \OCP\LDAP\ILDAPProvider
1553
-	 */
1554
-	public function getLDAPProvider() {
1555
-		return $this->query('LDAPProvider');
1556
-	}
1557
-
1558
-	/**
1559
-	 * @return \OCP\Settings\IManager
1560
-	 */
1561
-	public function getSettingsManager() {
1562
-		return $this->query('SettingsManager');
1563
-	}
1564
-
1565
-	/**
1566
-	 * @return \OCP\Files\IAppData
1567
-	 */
1568
-	public function getAppDataDir($app) {
1569
-		/** @var \OC\Files\AppData\Factory $factory */
1570
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1571
-		return $factory->get($app);
1572
-	}
1573
-
1574
-	/**
1575
-	 * @return \OCP\Lockdown\ILockdownManager
1576
-	 */
1577
-	public function getLockdownManager() {
1578
-		return $this->query('LockdownManager');
1579
-	}
1580
-
1581
-	/**
1582
-	 * @return \OCP\Federation\ICloudIdManager
1583
-	 */
1584
-	public function getCloudIdManager() {
1585
-		return $this->query(ICloudIdManager::class);
1586
-	}
716
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
717
+            if (isset($prefixes['OCA\\Theming\\'])) {
718
+                $classExists = true;
719
+            } else {
720
+                $classExists = false;
721
+            }
722
+
723
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming')) {
724
+                return new ThemingDefaults(
725
+                    $c->getConfig(),
726
+                    $c->getL10N('theming'),
727
+                    $c->getURLGenerator(),
728
+                    new \OC_Defaults(),
729
+                    $c->getLazyRootFolder(),
730
+                    $c->getMemCacheFactory()
731
+                );
732
+            }
733
+            return new \OC_Defaults();
734
+        });
735
+        $this->registerService('EventDispatcher', function () {
736
+            return new EventDispatcher();
737
+        });
738
+        $this->registerService('CryptoWrapper', function (Server $c) {
739
+            // FIXME: Instantiiated here due to cyclic dependency
740
+            $request = new Request(
741
+                [
742
+                    'get' => $_GET,
743
+                    'post' => $_POST,
744
+                    'files' => $_FILES,
745
+                    'server' => $_SERVER,
746
+                    'env' => $_ENV,
747
+                    'cookies' => $_COOKIE,
748
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
749
+                        ? $_SERVER['REQUEST_METHOD']
750
+                        : null,
751
+                ],
752
+                $c->getSecureRandom(),
753
+                $c->getConfig()
754
+            );
755
+
756
+            return new CryptoWrapper(
757
+                $c->getConfig(),
758
+                $c->getCrypto(),
759
+                $c->getSecureRandom(),
760
+                $request
761
+            );
762
+        });
763
+        $this->registerService('CsrfTokenManager', function (Server $c) {
764
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
765
+
766
+            return new CsrfTokenManager(
767
+                $tokenGenerator,
768
+                $c->query(SessionStorage::class)
769
+            );
770
+        });
771
+        $this->registerService(SessionStorage::class, function (Server $c) {
772
+            return new SessionStorage($c->getSession());
773
+        });
774
+        $this->registerService('ContentSecurityPolicyManager', function (Server $c) {
775
+            return new ContentSecurityPolicyManager();
776
+        });
777
+        $this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
778
+            return new ContentSecurityPolicyNonceManager(
779
+                $c->getCsrfTokenManager(),
780
+                $c->getRequest()
781
+            );
782
+        });
783
+        $this->registerService('ShareManager', function(Server $c) {
784
+            $config = $c->getConfig();
785
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', '\OC\Share20\ProviderFactory');
786
+            /** @var \OCP\Share\IProviderFactory $factory */
787
+            $factory = new $factoryClass($this);
788
+
789
+            $manager = new \OC\Share20\Manager(
790
+                $c->getLogger(),
791
+                $c->getConfig(),
792
+                $c->getSecureRandom(),
793
+                $c->getHasher(),
794
+                $c->getMountManager(),
795
+                $c->getGroupManager(),
796
+                $c->getL10N('core'),
797
+                $factory,
798
+                $c->getUserManager(),
799
+                $c->getLazyRootFolder(),
800
+                $c->getEventDispatcher()
801
+            );
802
+
803
+            return $manager;
804
+        });
805
+        $this->registerService('SettingsManager', function(Server $c) {
806
+            $manager = new \OC\Settings\Manager(
807
+                $c->getLogger(),
808
+                $c->getDatabaseConnection(),
809
+                $c->getL10N('lib'),
810
+                $c->getConfig(),
811
+                $c->getEncryptionManager(),
812
+                $c->getUserManager(),
813
+                $c->getLockingProvider(),
814
+                $c->getRequest(),
815
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
816
+                $c->getURLGenerator()
817
+            );
818
+            return $manager;
819
+        });
820
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
821
+            return new \OC\Files\AppData\Factory(
822
+                $c->getRootFolder(),
823
+                $c->getSystemConfig()
824
+            );
825
+        });
826
+
827
+        $this->registerService('LockdownManager', function (Server $c) {
828
+            return new LockdownManager();
829
+        });
830
+
831
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
832
+            return new CloudIdManager();
833
+        });
834
+
835
+        /* To trick DI since we don't extend the DIContainer here */
836
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
837
+            return new CleanPreviewsBackgroundJob(
838
+                $c->getRootFolder(),
839
+                $c->getLogger(),
840
+                $c->getJobList(),
841
+                new TimeFactory()
842
+            );
843
+        });
844
+    }
845
+
846
+    /**
847
+     * @return \OCP\Contacts\IManager
848
+     */
849
+    public function getContactsManager() {
850
+        return $this->query('ContactsManager');
851
+    }
852
+
853
+    /**
854
+     * @return \OC\Encryption\Manager
855
+     */
856
+    public function getEncryptionManager() {
857
+        return $this->query('EncryptionManager');
858
+    }
859
+
860
+    /**
861
+     * @return \OC\Encryption\File
862
+     */
863
+    public function getEncryptionFilesHelper() {
864
+        return $this->query('EncryptionFileHelper');
865
+    }
866
+
867
+    /**
868
+     * @return \OCP\Encryption\Keys\IStorage
869
+     */
870
+    public function getEncryptionKeyStorage() {
871
+        return $this->query('EncryptionKeyStorage');
872
+    }
873
+
874
+    /**
875
+     * The current request object holding all information about the request
876
+     * currently being processed is returned from this method.
877
+     * In case the current execution was not initiated by a web request null is returned
878
+     *
879
+     * @return \OCP\IRequest
880
+     */
881
+    public function getRequest() {
882
+        return $this->query('Request');
883
+    }
884
+
885
+    /**
886
+     * Returns the preview manager which can create preview images for a given file
887
+     *
888
+     * @return \OCP\IPreview
889
+     */
890
+    public function getPreviewManager() {
891
+        return $this->query('PreviewManager');
892
+    }
893
+
894
+    /**
895
+     * Returns the tag manager which can get and set tags for different object types
896
+     *
897
+     * @see \OCP\ITagManager::load()
898
+     * @return \OCP\ITagManager
899
+     */
900
+    public function getTagManager() {
901
+        return $this->query('TagManager');
902
+    }
903
+
904
+    /**
905
+     * Returns the system-tag manager
906
+     *
907
+     * @return \OCP\SystemTag\ISystemTagManager
908
+     *
909
+     * @since 9.0.0
910
+     */
911
+    public function getSystemTagManager() {
912
+        return $this->query('SystemTagManager');
913
+    }
914
+
915
+    /**
916
+     * Returns the system-tag object mapper
917
+     *
918
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
919
+     *
920
+     * @since 9.0.0
921
+     */
922
+    public function getSystemTagObjectMapper() {
923
+        return $this->query('SystemTagObjectMapper');
924
+    }
925
+
926
+    /**
927
+     * Returns the avatar manager, used for avatar functionality
928
+     *
929
+     * @return \OCP\IAvatarManager
930
+     */
931
+    public function getAvatarManager() {
932
+        return $this->query('AvatarManager');
933
+    }
934
+
935
+    /**
936
+     * Returns the root folder of ownCloud's data directory
937
+     *
938
+     * @return \OCP\Files\IRootFolder
939
+     */
940
+    public function getRootFolder() {
941
+        return $this->query('LazyRootFolder');
942
+    }
943
+
944
+    /**
945
+     * Returns the root folder of ownCloud's data directory
946
+     * This is the lazy variant so this gets only initialized once it
947
+     * is actually used.
948
+     *
949
+     * @return \OCP\Files\IRootFolder
950
+     */
951
+    public function getLazyRootFolder() {
952
+        return $this->query('LazyRootFolder');
953
+    }
954
+
955
+    /**
956
+     * Returns a view to ownCloud's files folder
957
+     *
958
+     * @param string $userId user ID
959
+     * @return \OCP\Files\Folder|null
960
+     */
961
+    public function getUserFolder($userId = null) {
962
+        if ($userId === null) {
963
+            $user = $this->getUserSession()->getUser();
964
+            if (!$user) {
965
+                return null;
966
+            }
967
+            $userId = $user->getUID();
968
+        }
969
+        $root = $this->getRootFolder();
970
+        return $root->getUserFolder($userId);
971
+    }
972
+
973
+    /**
974
+     * Returns an app-specific view in ownClouds data directory
975
+     *
976
+     * @return \OCP\Files\Folder
977
+     * @deprecated since 9.2.0 use IAppData
978
+     */
979
+    public function getAppFolder() {
980
+        $dir = '/' . \OC_App::getCurrentApp();
981
+        $root = $this->getRootFolder();
982
+        if (!$root->nodeExists($dir)) {
983
+            $folder = $root->newFolder($dir);
984
+        } else {
985
+            $folder = $root->get($dir);
986
+        }
987
+        return $folder;
988
+    }
989
+
990
+    /**
991
+     * @return \OC\User\Manager
992
+     */
993
+    public function getUserManager() {
994
+        return $this->query('UserManager');
995
+    }
996
+
997
+    /**
998
+     * @return \OC\Group\Manager
999
+     */
1000
+    public function getGroupManager() {
1001
+        return $this->query('GroupManager');
1002
+    }
1003
+
1004
+    /**
1005
+     * @return \OC\User\Session
1006
+     */
1007
+    public function getUserSession() {
1008
+        return $this->query('UserSession');
1009
+    }
1010
+
1011
+    /**
1012
+     * @return \OCP\ISession
1013
+     */
1014
+    public function getSession() {
1015
+        return $this->query('UserSession')->getSession();
1016
+    }
1017
+
1018
+    /**
1019
+     * @param \OCP\ISession $session
1020
+     */
1021
+    public function setSession(\OCP\ISession $session) {
1022
+        $this->query(SessionStorage::class)->setSession($session);
1023
+        $this->query('UserSession')->setSession($session);
1024
+        $this->query(Store::class)->setSession($session);
1025
+    }
1026
+
1027
+    /**
1028
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1029
+     */
1030
+    public function getTwoFactorAuthManager() {
1031
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1032
+    }
1033
+
1034
+    /**
1035
+     * @return \OC\NavigationManager
1036
+     */
1037
+    public function getNavigationManager() {
1038
+        return $this->query('NavigationManager');
1039
+    }
1040
+
1041
+    /**
1042
+     * @return \OCP\IConfig
1043
+     */
1044
+    public function getConfig() {
1045
+        return $this->query('AllConfig');
1046
+    }
1047
+
1048
+    /**
1049
+     * @internal For internal use only
1050
+     * @return \OC\SystemConfig
1051
+     */
1052
+    public function getSystemConfig() {
1053
+        return $this->query('SystemConfig');
1054
+    }
1055
+
1056
+    /**
1057
+     * Returns the app config manager
1058
+     *
1059
+     * @return \OCP\IAppConfig
1060
+     */
1061
+    public function getAppConfig() {
1062
+        return $this->query('AppConfig');
1063
+    }
1064
+
1065
+    /**
1066
+     * @return \OCP\L10N\IFactory
1067
+     */
1068
+    public function getL10NFactory() {
1069
+        return $this->query('L10NFactory');
1070
+    }
1071
+
1072
+    /**
1073
+     * get an L10N instance
1074
+     *
1075
+     * @param string $app appid
1076
+     * @param string $lang
1077
+     * @return IL10N
1078
+     */
1079
+    public function getL10N($app, $lang = null) {
1080
+        return $this->getL10NFactory()->get($app, $lang);
1081
+    }
1082
+
1083
+    /**
1084
+     * @return \OCP\IURLGenerator
1085
+     */
1086
+    public function getURLGenerator() {
1087
+        return $this->query('URLGenerator');
1088
+    }
1089
+
1090
+    /**
1091
+     * @return \OCP\IHelper
1092
+     */
1093
+    public function getHelper() {
1094
+        return $this->query('AppHelper');
1095
+    }
1096
+
1097
+    /**
1098
+     * @return AppFetcher
1099
+     */
1100
+    public function getAppFetcher() {
1101
+        return $this->query('AppFetcher');
1102
+    }
1103
+
1104
+    /**
1105
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1106
+     * getMemCacheFactory() instead.
1107
+     *
1108
+     * @return \OCP\ICache
1109
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1110
+     */
1111
+    public function getCache() {
1112
+        return $this->query('UserCache');
1113
+    }
1114
+
1115
+    /**
1116
+     * Returns an \OCP\CacheFactory instance
1117
+     *
1118
+     * @return \OCP\ICacheFactory
1119
+     */
1120
+    public function getMemCacheFactory() {
1121
+        return $this->query('MemCacheFactory');
1122
+    }
1123
+
1124
+    /**
1125
+     * Returns an \OC\RedisFactory instance
1126
+     *
1127
+     * @return \OC\RedisFactory
1128
+     */
1129
+    public function getGetRedisFactory() {
1130
+        return $this->query('RedisFactory');
1131
+    }
1132
+
1133
+
1134
+    /**
1135
+     * Returns the current session
1136
+     *
1137
+     * @return \OCP\IDBConnection
1138
+     */
1139
+    public function getDatabaseConnection() {
1140
+        return $this->query('DatabaseConnection');
1141
+    }
1142
+
1143
+    /**
1144
+     * Returns the activity manager
1145
+     *
1146
+     * @return \OCP\Activity\IManager
1147
+     */
1148
+    public function getActivityManager() {
1149
+        return $this->query('ActivityManager');
1150
+    }
1151
+
1152
+    /**
1153
+     * Returns an job list for controlling background jobs
1154
+     *
1155
+     * @return \OCP\BackgroundJob\IJobList
1156
+     */
1157
+    public function getJobList() {
1158
+        return $this->query('JobList');
1159
+    }
1160
+
1161
+    /**
1162
+     * Returns a logger instance
1163
+     *
1164
+     * @return \OCP\ILogger
1165
+     */
1166
+    public function getLogger() {
1167
+        return $this->query('Logger');
1168
+    }
1169
+
1170
+    /**
1171
+     * Returns a router for generating and matching urls
1172
+     *
1173
+     * @return \OCP\Route\IRouter
1174
+     */
1175
+    public function getRouter() {
1176
+        return $this->query('Router');
1177
+    }
1178
+
1179
+    /**
1180
+     * Returns a search instance
1181
+     *
1182
+     * @return \OCP\ISearch
1183
+     */
1184
+    public function getSearch() {
1185
+        return $this->query('Search');
1186
+    }
1187
+
1188
+    /**
1189
+     * Returns a SecureRandom instance
1190
+     *
1191
+     * @return \OCP\Security\ISecureRandom
1192
+     */
1193
+    public function getSecureRandom() {
1194
+        return $this->query('SecureRandom');
1195
+    }
1196
+
1197
+    /**
1198
+     * Returns a Crypto instance
1199
+     *
1200
+     * @return \OCP\Security\ICrypto
1201
+     */
1202
+    public function getCrypto() {
1203
+        return $this->query('Crypto');
1204
+    }
1205
+
1206
+    /**
1207
+     * Returns a Hasher instance
1208
+     *
1209
+     * @return \OCP\Security\IHasher
1210
+     */
1211
+    public function getHasher() {
1212
+        return $this->query('Hasher');
1213
+    }
1214
+
1215
+    /**
1216
+     * Returns a CredentialsManager instance
1217
+     *
1218
+     * @return \OCP\Security\ICredentialsManager
1219
+     */
1220
+    public function getCredentialsManager() {
1221
+        return $this->query('CredentialsManager');
1222
+    }
1223
+
1224
+    /**
1225
+     * Returns an instance of the HTTP helper class
1226
+     *
1227
+     * @deprecated Use getHTTPClientService()
1228
+     * @return \OC\HTTPHelper
1229
+     */
1230
+    public function getHTTPHelper() {
1231
+        return $this->query('HTTPHelper');
1232
+    }
1233
+
1234
+    /**
1235
+     * Get the certificate manager for the user
1236
+     *
1237
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1238
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1239
+     */
1240
+    public function getCertificateManager($userId = '') {
1241
+        if ($userId === '') {
1242
+            $userSession = $this->getUserSession();
1243
+            $user = $userSession->getUser();
1244
+            if (is_null($user)) {
1245
+                return null;
1246
+            }
1247
+            $userId = $user->getUID();
1248
+        }
1249
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1250
+    }
1251
+
1252
+    /**
1253
+     * Returns an instance of the HTTP client service
1254
+     *
1255
+     * @return \OCP\Http\Client\IClientService
1256
+     */
1257
+    public function getHTTPClientService() {
1258
+        return $this->query('HttpClientService');
1259
+    }
1260
+
1261
+    /**
1262
+     * Create a new event source
1263
+     *
1264
+     * @return \OCP\IEventSource
1265
+     */
1266
+    public function createEventSource() {
1267
+        return new \OC_EventSource();
1268
+    }
1269
+
1270
+    /**
1271
+     * Get the active event logger
1272
+     *
1273
+     * The returned logger only logs data when debug mode is enabled
1274
+     *
1275
+     * @return \OCP\Diagnostics\IEventLogger
1276
+     */
1277
+    public function getEventLogger() {
1278
+        return $this->query('EventLogger');
1279
+    }
1280
+
1281
+    /**
1282
+     * Get the active query logger
1283
+     *
1284
+     * The returned logger only logs data when debug mode is enabled
1285
+     *
1286
+     * @return \OCP\Diagnostics\IQueryLogger
1287
+     */
1288
+    public function getQueryLogger() {
1289
+        return $this->query('QueryLogger');
1290
+    }
1291
+
1292
+    /**
1293
+     * Get the manager for temporary files and folders
1294
+     *
1295
+     * @return \OCP\ITempManager
1296
+     */
1297
+    public function getTempManager() {
1298
+        return $this->query('TempManager');
1299
+    }
1300
+
1301
+    /**
1302
+     * Get the app manager
1303
+     *
1304
+     * @return \OCP\App\IAppManager
1305
+     */
1306
+    public function getAppManager() {
1307
+        return $this->query('AppManager');
1308
+    }
1309
+
1310
+    /**
1311
+     * Creates a new mailer
1312
+     *
1313
+     * @return \OCP\Mail\IMailer
1314
+     */
1315
+    public function getMailer() {
1316
+        return $this->query('Mailer');
1317
+    }
1318
+
1319
+    /**
1320
+     * Get the webroot
1321
+     *
1322
+     * @return string
1323
+     */
1324
+    public function getWebRoot() {
1325
+        return $this->webRoot;
1326
+    }
1327
+
1328
+    /**
1329
+     * @return \OC\OCSClient
1330
+     */
1331
+    public function getOcsClient() {
1332
+        return $this->query('OcsClient');
1333
+    }
1334
+
1335
+    /**
1336
+     * @return \OCP\IDateTimeZone
1337
+     */
1338
+    public function getDateTimeZone() {
1339
+        return $this->query('DateTimeZone');
1340
+    }
1341
+
1342
+    /**
1343
+     * @return \OCP\IDateTimeFormatter
1344
+     */
1345
+    public function getDateTimeFormatter() {
1346
+        return $this->query('DateTimeFormatter');
1347
+    }
1348
+
1349
+    /**
1350
+     * @return \OCP\Files\Config\IMountProviderCollection
1351
+     */
1352
+    public function getMountProviderCollection() {
1353
+        return $this->query('MountConfigManager');
1354
+    }
1355
+
1356
+    /**
1357
+     * Get the IniWrapper
1358
+     *
1359
+     * @return IniGetWrapper
1360
+     */
1361
+    public function getIniWrapper() {
1362
+        return $this->query('IniWrapper');
1363
+    }
1364
+
1365
+    /**
1366
+     * @return \OCP\Command\IBus
1367
+     */
1368
+    public function getCommandBus() {
1369
+        return $this->query('AsyncCommandBus');
1370
+    }
1371
+
1372
+    /**
1373
+     * Get the trusted domain helper
1374
+     *
1375
+     * @return TrustedDomainHelper
1376
+     */
1377
+    public function getTrustedDomainHelper() {
1378
+        return $this->query('TrustedDomainHelper');
1379
+    }
1380
+
1381
+    /**
1382
+     * Get the locking provider
1383
+     *
1384
+     * @return \OCP\Lock\ILockingProvider
1385
+     * @since 8.1.0
1386
+     */
1387
+    public function getLockingProvider() {
1388
+        return $this->query('LockingProvider');
1389
+    }
1390
+
1391
+    /**
1392
+     * @return \OCP\Files\Mount\IMountManager
1393
+     **/
1394
+    function getMountManager() {
1395
+        return $this->query('MountManager');
1396
+    }
1397
+
1398
+    /** @return \OCP\Files\Config\IUserMountCache */
1399
+    function getUserMountCache() {
1400
+        return $this->query('UserMountCache');
1401
+    }
1402
+
1403
+    /**
1404
+     * Get the MimeTypeDetector
1405
+     *
1406
+     * @return \OCP\Files\IMimeTypeDetector
1407
+     */
1408
+    public function getMimeTypeDetector() {
1409
+        return $this->query('MimeTypeDetector');
1410
+    }
1411
+
1412
+    /**
1413
+     * Get the MimeTypeLoader
1414
+     *
1415
+     * @return \OCP\Files\IMimeTypeLoader
1416
+     */
1417
+    public function getMimeTypeLoader() {
1418
+        return $this->query('MimeTypeLoader');
1419
+    }
1420
+
1421
+    /**
1422
+     * Get the manager of all the capabilities
1423
+     *
1424
+     * @return \OC\CapabilitiesManager
1425
+     */
1426
+    public function getCapabilitiesManager() {
1427
+        return $this->query('CapabilitiesManager');
1428
+    }
1429
+
1430
+    /**
1431
+     * Get the EventDispatcher
1432
+     *
1433
+     * @return EventDispatcherInterface
1434
+     * @since 8.2.0
1435
+     */
1436
+    public function getEventDispatcher() {
1437
+        return $this->query('EventDispatcher');
1438
+    }
1439
+
1440
+    /**
1441
+     * Get the Notification Manager
1442
+     *
1443
+     * @return \OCP\Notification\IManager
1444
+     * @since 8.2.0
1445
+     */
1446
+    public function getNotificationManager() {
1447
+        return $this->query('NotificationManager');
1448
+    }
1449
+
1450
+    /**
1451
+     * @return \OCP\Comments\ICommentsManager
1452
+     */
1453
+    public function getCommentsManager() {
1454
+        return $this->query('CommentsManager');
1455
+    }
1456
+
1457
+    /**
1458
+     * @return \OC_Defaults
1459
+     */
1460
+    public function getThemingDefaults() {
1461
+        return $this->query('ThemingDefaults');
1462
+    }
1463
+
1464
+    /**
1465
+     * @return \OC\IntegrityCheck\Checker
1466
+     */
1467
+    public function getIntegrityCodeChecker() {
1468
+        return $this->query('IntegrityCodeChecker');
1469
+    }
1470
+
1471
+    /**
1472
+     * @return \OC\Session\CryptoWrapper
1473
+     */
1474
+    public function getSessionCryptoWrapper() {
1475
+        return $this->query('CryptoWrapper');
1476
+    }
1477
+
1478
+    /**
1479
+     * @return CsrfTokenManager
1480
+     */
1481
+    public function getCsrfTokenManager() {
1482
+        return $this->query('CsrfTokenManager');
1483
+    }
1484
+
1485
+    /**
1486
+     * @return Throttler
1487
+     */
1488
+    public function getBruteForceThrottler() {
1489
+        return $this->query('Throttler');
1490
+    }
1491
+
1492
+    /**
1493
+     * @return IContentSecurityPolicyManager
1494
+     */
1495
+    public function getContentSecurityPolicyManager() {
1496
+        return $this->query('ContentSecurityPolicyManager');
1497
+    }
1498
+
1499
+    /**
1500
+     * @return ContentSecurityPolicyNonceManager
1501
+     */
1502
+    public function getContentSecurityPolicyNonceManager() {
1503
+        return $this->query('ContentSecurityPolicyNonceManager');
1504
+    }
1505
+
1506
+    /**
1507
+     * Not a public API as of 8.2, wait for 9.0
1508
+     *
1509
+     * @return \OCA\Files_External\Service\BackendService
1510
+     */
1511
+    public function getStoragesBackendService() {
1512
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1513
+    }
1514
+
1515
+    /**
1516
+     * Not a public API as of 8.2, wait for 9.0
1517
+     *
1518
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1519
+     */
1520
+    public function getGlobalStoragesService() {
1521
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1522
+    }
1523
+
1524
+    /**
1525
+     * Not a public API as of 8.2, wait for 9.0
1526
+     *
1527
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1528
+     */
1529
+    public function getUserGlobalStoragesService() {
1530
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1531
+    }
1532
+
1533
+    /**
1534
+     * Not a public API as of 8.2, wait for 9.0
1535
+     *
1536
+     * @return \OCA\Files_External\Service\UserStoragesService
1537
+     */
1538
+    public function getUserStoragesService() {
1539
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1540
+    }
1541
+
1542
+    /**
1543
+     * @return \OCP\Share\IManager
1544
+     */
1545
+    public function getShareManager() {
1546
+        return $this->query('ShareManager');
1547
+    }
1548
+
1549
+    /**
1550
+     * Returns the LDAP Provider
1551
+     *
1552
+     * @return \OCP\LDAP\ILDAPProvider
1553
+     */
1554
+    public function getLDAPProvider() {
1555
+        return $this->query('LDAPProvider');
1556
+    }
1557
+
1558
+    /**
1559
+     * @return \OCP\Settings\IManager
1560
+     */
1561
+    public function getSettingsManager() {
1562
+        return $this->query('SettingsManager');
1563
+    }
1564
+
1565
+    /**
1566
+     * @return \OCP\Files\IAppData
1567
+     */
1568
+    public function getAppDataDir($app) {
1569
+        /** @var \OC\Files\AppData\Factory $factory */
1570
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1571
+        return $factory->get($app);
1572
+    }
1573
+
1574
+    /**
1575
+     * @return \OCP\Lockdown\ILockdownManager
1576
+     */
1577
+    public function getLockdownManager() {
1578
+        return $this->query('LockdownManager');
1579
+    }
1580
+
1581
+    /**
1582
+     * @return \OCP\Federation\ICloudIdManager
1583
+     */
1584
+    public function getCloudIdManager() {
1585
+        return $this->query(ICloudIdManager::class);
1586
+    }
1587 1587
 }
Please login to merge, or discard this patch.
Spacing   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -119,11 +119,11 @@  discard block
 block discarded – undo
119 119
 		parent::__construct();
120 120
 		$this->webRoot = $webRoot;
121 121
 
122
-		$this->registerService('ContactsManager', function ($c) {
122
+		$this->registerService('ContactsManager', function($c) {
123 123
 			return new ContactsManager();
124 124
 		});
125 125
 
126
-		$this->registerService('PreviewManager', function (Server $c) {
126
+		$this->registerService('PreviewManager', function(Server $c) {
127 127
 			return new PreviewManager(
128 128
 				$c->getConfig(),
129 129
 				$c->getRootFolder(),
@@ -133,13 +133,13 @@  discard block
 block discarded – undo
133 133
 			);
134 134
 		});
135 135
 
136
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
136
+		$this->registerService(\OC\Preview\Watcher::class, function(Server $c) {
137 137
 			return new \OC\Preview\Watcher(
138 138
 				$c->getAppDataDir('preview')
139 139
 			);
140 140
 		});
141 141
 
142
-		$this->registerService('EncryptionManager', function (Server $c) {
142
+		$this->registerService('EncryptionManager', function(Server $c) {
143 143
 			$view = new View();
144 144
 			$util = new Encryption\Util(
145 145
 				$view,
@@ -157,7 +157,7 @@  discard block
 block discarded – undo
157 157
 			);
158 158
 		});
159 159
 
160
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
160
+		$this->registerService('EncryptionFileHelper', function(Server $c) {
161 161
 			$util = new Encryption\Util(
162 162
 				new View(),
163 163
 				$c->getUserManager(),
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
 			return new Encryption\File($util);
168 168
 		});
169 169
 
170
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
170
+		$this->registerService('EncryptionKeyStorage', function(Server $c) {
171 171
 			$view = new View();
172 172
 			$util = new Encryption\Util(
173 173
 				$view,
@@ -178,27 +178,27 @@  discard block
 block discarded – undo
178 178
 
179 179
 			return new Encryption\Keys\Storage($view, $util);
180 180
 		});
181
-		$this->registerService('TagMapper', function (Server $c) {
181
+		$this->registerService('TagMapper', function(Server $c) {
182 182
 			return new TagMapper($c->getDatabaseConnection());
183 183
 		});
184
-		$this->registerService('TagManager', function (Server $c) {
184
+		$this->registerService('TagManager', function(Server $c) {
185 185
 			$tagMapper = $c->query('TagMapper');
186 186
 			return new TagManager($tagMapper, $c->getUserSession());
187 187
 		});
188
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
188
+		$this->registerService('SystemTagManagerFactory', function(Server $c) {
189 189
 			$config = $c->getConfig();
190 190
 			$factoryClass = $config->getSystemValue('systemtags.managerFactory', '\OC\SystemTag\ManagerFactory');
191 191
 			/** @var \OC\SystemTag\ManagerFactory $factory */
192 192
 			$factory = new $factoryClass($this);
193 193
 			return $factory;
194 194
 		});
195
-		$this->registerService('SystemTagManager', function (Server $c) {
195
+		$this->registerService('SystemTagManager', function(Server $c) {
196 196
 			return $c->query('SystemTagManagerFactory')->getManager();
197 197
 		});
198
-		$this->registerService('SystemTagObjectMapper', function (Server $c) {
198
+		$this->registerService('SystemTagObjectMapper', function(Server $c) {
199 199
 			return $c->query('SystemTagManagerFactory')->getObjectMapper();
200 200
 		});
201
-		$this->registerService('RootFolder', function (Server $c) {
201
+		$this->registerService('RootFolder', function(Server $c) {
202 202
 			$manager = \OC\Files\Filesystem::getMountManager(null);
203 203
 			$view = new View();
204 204
 			$root = new Root(
@@ -222,28 +222,28 @@  discard block
 block discarded – undo
222 222
 				return $c->query('RootFolder');
223 223
 			});
224 224
 		});
225
-		$this->registerService('UserManager', function (Server $c) {
225
+		$this->registerService('UserManager', function(Server $c) {
226 226
 			$config = $c->getConfig();
227 227
 			return new \OC\User\Manager($config);
228 228
 		});
229
-		$this->registerService('GroupManager', function (Server $c) {
229
+		$this->registerService('GroupManager', function(Server $c) {
230 230
 			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
231
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
231
+			$groupManager->listen('\OC\Group', 'preCreate', function($gid) {
232 232
 				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
233 233
 			});
234
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
234
+			$groupManager->listen('\OC\Group', 'postCreate', function(\OC\Group\Group $gid) {
235 235
 				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
236 236
 			});
237
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
237
+			$groupManager->listen('\OC\Group', 'preDelete', function(\OC\Group\Group $group) {
238 238
 				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
239 239
 			});
240
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
240
+			$groupManager->listen('\OC\Group', 'postDelete', function(\OC\Group\Group $group) {
241 241
 				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
242 242
 			});
243
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
243
+			$groupManager->listen('\OC\Group', 'preAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
244 244
 				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
245 245
 			});
246
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
246
+			$groupManager->listen('\OC\Group', 'postAddUser', function(\OC\Group\Group $group, \OC\User\User $user) {
247 247
 				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
248 248
 				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
249 249
 				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
@@ -261,11 +261,11 @@  discard block
 block discarded – undo
261 261
 			return new Store($session, $logger, $tokenProvider);
262 262
 		});
263 263
 		$this->registerAlias(IStore::class, Store::class);
264
-		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function (Server $c) {
264
+		$this->registerService('OC\Authentication\Token\DefaultTokenMapper', function(Server $c) {
265 265
 			$dbConnection = $c->getDatabaseConnection();
266 266
 			return new Authentication\Token\DefaultTokenMapper($dbConnection);
267 267
 		});
268
-		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function (Server $c) {
268
+		$this->registerService('OC\Authentication\Token\DefaultTokenProvider', function(Server $c) {
269 269
 			$mapper = $c->query('OC\Authentication\Token\DefaultTokenMapper');
270 270
 			$crypto = $c->getCrypto();
271 271
 			$config = $c->getConfig();
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
275 275
 		});
276 276
 		$this->registerAlias('OC\Authentication\Token\IProvider', 'OC\Authentication\Token\DefaultTokenProvider');
277
-		$this->registerService('UserSession', function (Server $c) {
277
+		$this->registerService('UserSession', function(Server $c) {
278 278
 			$manager = $c->getUserManager();
279 279
 			$session = new \OC\Session\Memory('');
280 280
 			$timeFactory = new TimeFactory();
@@ -287,69 +287,69 @@  discard block
 block discarded – undo
287 287
 			}
288 288
 
289 289
 			$userSession = new \OC\User\Session($manager, $session, $timeFactory, $defaultTokenProvider, $c->getConfig(), $c->getSecureRandom());
290
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
290
+			$userSession->listen('\OC\User', 'preCreateUser', function($uid, $password) {
291 291
 				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
292 292
 			});
293
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
293
+			$userSession->listen('\OC\User', 'postCreateUser', function($user, $password) {
294 294
 				/** @var $user \OC\User\User */
295 295
 				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
296 296
 			});
297
-			$userSession->listen('\OC\User', 'preDelete', function ($user) {
297
+			$userSession->listen('\OC\User', 'preDelete', function($user) {
298 298
 				/** @var $user \OC\User\User */
299 299
 				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
300 300
 			});
301
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
301
+			$userSession->listen('\OC\User', 'postDelete', function($user) {
302 302
 				/** @var $user \OC\User\User */
303 303
 				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
304 304
 			});
305
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
305
+			$userSession->listen('\OC\User', 'preSetPassword', function($user, $password, $recoveryPassword) {
306 306
 				/** @var $user \OC\User\User */
307 307
 				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
308 308
 			});
309
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
309
+			$userSession->listen('\OC\User', 'postSetPassword', function($user, $password, $recoveryPassword) {
310 310
 				/** @var $user \OC\User\User */
311 311
 				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
312 312
 			});
313
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
313
+			$userSession->listen('\OC\User', 'preLogin', function($uid, $password) {
314 314
 				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
315 315
 			});
316
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
316
+			$userSession->listen('\OC\User', 'postLogin', function($user, $password) {
317 317
 				/** @var $user \OC\User\User */
318 318
 				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
319 319
 			});
320
-			$userSession->listen('\OC\User', 'logout', function () {
320
+			$userSession->listen('\OC\User', 'logout', function() {
321 321
 				\OC_Hook::emit('OC_User', 'logout', array());
322 322
 			});
323
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value) {
323
+			$userSession->listen('\OC\User', 'changeUser', function($user, $feature, $value) {
324 324
 				/** @var $user \OC\User\User */
325 325
 				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value));
326 326
 			});
327 327
 			return $userSession;
328 328
 		});
329 329
 
330
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
330
+		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function(Server $c) {
331 331
 			return new \OC\Authentication\TwoFactorAuth\Manager($c->getAppManager(), $c->getSession(), $c->getConfig(), $c->getActivityManager(), $c->getLogger());
332 332
 		});
333 333
 
334
-		$this->registerService('NavigationManager', function (Server $c) {
334
+		$this->registerService('NavigationManager', function(Server $c) {
335 335
 			return new \OC\NavigationManager($c->getAppManager(),
336 336
 				$c->getURLGenerator(),
337 337
 				$c->getL10NFactory(),
338 338
 				$c->getUserSession(),
339 339
 				$c->getGroupManager());
340 340
 		});
341
-		$this->registerService('AllConfig', function (Server $c) {
341
+		$this->registerService('AllConfig', function(Server $c) {
342 342
 			return new \OC\AllConfig(
343 343
 				$c->getSystemConfig()
344 344
 			);
345 345
 		});
346
-		$this->registerService('SystemConfig', function ($c) use ($config) {
346
+		$this->registerService('SystemConfig', function($c) use ($config) {
347 347
 			return new \OC\SystemConfig($config);
348 348
 		});
349
-		$this->registerService('AppConfig', function (Server $c) {
349
+		$this->registerService('AppConfig', function(Server $c) {
350 350
 			return new \OC\AppConfig($c->getDatabaseConnection());
351 351
 		});
352
-		$this->registerService('L10NFactory', function (Server $c) {
352
+		$this->registerService('L10NFactory', function(Server $c) {
353 353
 			return new \OC\L10N\Factory(
354 354
 				$c->getConfig(),
355 355
 				$c->getRequest(),
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 				\OC::$SERVERROOT
358 358
 			);
359 359
 		});
360
-		$this->registerService('URLGenerator', function (Server $c) {
360
+		$this->registerService('URLGenerator', function(Server $c) {
361 361
 			$config = $c->getConfig();
362 362
 			$cacheFactory = $c->getMemCacheFactory();
363 363
 			return new \OC\URLGenerator(
@@ -365,10 +365,10 @@  discard block
 block discarded – undo
365 365
 				$cacheFactory
366 366
 			);
367 367
 		});
368
-		$this->registerService('AppHelper', function ($c) {
368
+		$this->registerService('AppHelper', function($c) {
369 369
 			return new \OC\AppHelper();
370 370
 		});
371
-		$this->registerService('AppFetcher', function ($c) {
371
+		$this->registerService('AppFetcher', function($c) {
372 372
 			return new AppFetcher(
373 373
 				$this->getAppDataDir('appstore'),
374 374
 				$this->getHTTPClientService(),
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 				$this->getConfig()
377 377
 			);
378 378
 		});
379
-		$this->registerService('CategoryFetcher', function ($c) {
379
+		$this->registerService('CategoryFetcher', function($c) {
380 380
 			return new CategoryFetcher(
381 381
 				$this->getAppDataDir('appstore'),
382 382
 				$this->getHTTPClientService(),
@@ -384,19 +384,19 @@  discard block
 block discarded – undo
384 384
 				$this->getConfig()
385 385
 			);
386 386
 		});
387
-		$this->registerService('UserCache', function ($c) {
387
+		$this->registerService('UserCache', function($c) {
388 388
 			return new Cache\File();
389 389
 		});
390
-		$this->registerService('MemCacheFactory', function (Server $c) {
390
+		$this->registerService('MemCacheFactory', function(Server $c) {
391 391
 			$config = $c->getConfig();
392 392
 
393 393
 			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
394 394
 				$v = \OC_App::getAppVersions();
395
-				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT . '/version.php'));
395
+				$v['core'] = md5(file_get_contents(\OC::$SERVERROOT.'/version.php'));
396 396
 				$version = implode(',', $v);
397 397
 				$instanceId = \OC_Util::getInstanceId();
398 398
 				$path = \OC::$SERVERROOT;
399
-				$prefix = md5($instanceId . '-' . $version . '-' . $path . '-' . \OC::$WEBROOT);
399
+				$prefix = md5($instanceId.'-'.$version.'-'.$path.'-'.\OC::$WEBROOT);
400 400
 				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
401 401
 					$config->getSystemValue('memcache.local', null),
402 402
 					$config->getSystemValue('memcache.distributed', null),
@@ -410,11 +410,11 @@  discard block
 block discarded – undo
410 410
 				'\\OC\\Memcache\\ArrayCache'
411 411
 			);
412 412
 		});
413
-		$this->registerService('RedisFactory', function (Server $c) {
413
+		$this->registerService('RedisFactory', function(Server $c) {
414 414
 			$systemConfig = $c->getSystemConfig();
415 415
 			return new RedisFactory($systemConfig);
416 416
 		});
417
-		$this->registerService('ActivityManager', function (Server $c) {
417
+		$this->registerService('ActivityManager', function(Server $c) {
418 418
 			return new \OC\Activity\Manager(
419 419
 				$c->getRequest(),
420 420
 				$c->getUserSession(),
@@ -422,13 +422,13 @@  discard block
 block discarded – undo
422 422
 				$c->query(IValidator::class)
423 423
 			);
424 424
 		});
425
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
425
+		$this->registerService(\OCP\Activity\IEventMerger::class, function(Server $c) {
426 426
 			return new \OC\Activity\EventMerger(
427 427
 				$c->getL10N('lib')
428 428
 			);
429 429
 		});
430 430
 		$this->registerAlias(IValidator::class, Validator::class);
431
-		$this->registerService('AvatarManager', function (Server $c) {
431
+		$this->registerService('AvatarManager', function(Server $c) {
432 432
 			return new AvatarManager(
433 433
 				$c->getUserManager(),
434 434
 				$c->getAppDataDir('avatar'),
@@ -437,14 +437,14 @@  discard block
 block discarded – undo
437 437
 				$c->getConfig()
438 438
 			);
439 439
 		});
440
-		$this->registerService('Logger', function (Server $c) {
440
+		$this->registerService('Logger', function(Server $c) {
441 441
 			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
442 442
 			$logger = Log::getLogClass($logType);
443 443
 			call_user_func(array($logger, 'init'));
444 444
 
445 445
 			return new Log($logger);
446 446
 		});
447
-		$this->registerService('JobList', function (Server $c) {
447
+		$this->registerService('JobList', function(Server $c) {
448 448
 			$config = $c->getConfig();
449 449
 			return new \OC\BackgroundJob\JobList(
450 450
 				$c->getDatabaseConnection(),
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 				new TimeFactory()
453 453
 			);
454 454
 		});
455
-		$this->registerService('Router', function (Server $c) {
455
+		$this->registerService('Router', function(Server $c) {
456 456
 			$cacheFactory = $c->getMemCacheFactory();
457 457
 			$logger = $c->getLogger();
458 458
 			if ($cacheFactory->isAvailable()) {
@@ -462,22 +462,22 @@  discard block
 block discarded – undo
462 462
 			}
463 463
 			return $router;
464 464
 		});
465
-		$this->registerService('Search', function ($c) {
465
+		$this->registerService('Search', function($c) {
466 466
 			return new Search();
467 467
 		});
468
-		$this->registerService('SecureRandom', function ($c) {
468
+		$this->registerService('SecureRandom', function($c) {
469 469
 			return new SecureRandom();
470 470
 		});
471
-		$this->registerService('Crypto', function (Server $c) {
471
+		$this->registerService('Crypto', function(Server $c) {
472 472
 			return new Crypto($c->getConfig(), $c->getSecureRandom());
473 473
 		});
474
-		$this->registerService('Hasher', function (Server $c) {
474
+		$this->registerService('Hasher', function(Server $c) {
475 475
 			return new Hasher($c->getConfig());
476 476
 		});
477
-		$this->registerService('CredentialsManager', function (Server $c) {
477
+		$this->registerService('CredentialsManager', function(Server $c) {
478 478
 			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
479 479
 		});
480
-		$this->registerService('DatabaseConnection', function (Server $c) {
480
+		$this->registerService('DatabaseConnection', function(Server $c) {
481 481
 			$systemConfig = $c->getSystemConfig();
482 482
 			$factory = new \OC\DB\ConnectionFactory($systemConfig);
483 483
 			$type = $systemConfig->getValue('dbtype', 'sqlite');
@@ -489,14 +489,14 @@  discard block
 block discarded – undo
489 489
 			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
490 490
 			return $connection;
491 491
 		});
492
-		$this->registerService('HTTPHelper', function (Server $c) {
492
+		$this->registerService('HTTPHelper', function(Server $c) {
493 493
 			$config = $c->getConfig();
494 494
 			return new HTTPHelper(
495 495
 				$config,
496 496
 				$c->getHTTPClientService()
497 497
 			);
498 498
 		});
499
-		$this->registerService('HttpClientService', function (Server $c) {
499
+		$this->registerService('HttpClientService', function(Server $c) {
500 500
 			$user = \OC_User::getUser();
501 501
 			$uid = $user ? $user : null;
502 502
 			return new ClientService(
@@ -504,27 +504,27 @@  discard block
 block discarded – undo
504 504
 				new \OC\Security\CertificateManager($uid, new View(), $c->getConfig(), $c->getLogger())
505 505
 			);
506 506
 		});
507
-		$this->registerService('EventLogger', function (Server $c) {
507
+		$this->registerService('EventLogger', function(Server $c) {
508 508
 			if ($c->getSystemConfig()->getValue('debug', false)) {
509 509
 				return new EventLogger();
510 510
 			} else {
511 511
 				return new NullEventLogger();
512 512
 			}
513 513
 		});
514
-		$this->registerService('QueryLogger', function (Server $c) {
514
+		$this->registerService('QueryLogger', function(Server $c) {
515 515
 			if ($c->getSystemConfig()->getValue('debug', false)) {
516 516
 				return new QueryLogger();
517 517
 			} else {
518 518
 				return new NullQueryLogger();
519 519
 			}
520 520
 		});
521
-		$this->registerService('TempManager', function (Server $c) {
521
+		$this->registerService('TempManager', function(Server $c) {
522 522
 			return new TempManager(
523 523
 				$c->getLogger(),
524 524
 				$c->getConfig()
525 525
 			);
526 526
 		});
527
-		$this->registerService('AppManager', function (Server $c) {
527
+		$this->registerService('AppManager', function(Server $c) {
528 528
 			return new \OC\App\AppManager(
529 529
 				$c->getUserSession(),
530 530
 				$c->getAppConfig(),
@@ -533,13 +533,13 @@  discard block
 block discarded – undo
533 533
 				$c->getEventDispatcher()
534 534
 			);
535 535
 		});
536
-		$this->registerService('DateTimeZone', function (Server $c) {
536
+		$this->registerService('DateTimeZone', function(Server $c) {
537 537
 			return new DateTimeZone(
538 538
 				$c->getConfig(),
539 539
 				$c->getSession()
540 540
 			);
541 541
 		});
542
-		$this->registerService('DateTimeFormatter', function (Server $c) {
542
+		$this->registerService('DateTimeFormatter', function(Server $c) {
543 543
 			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
544 544
 
545 545
 			return new DateTimeFormatter(
@@ -547,16 +547,16 @@  discard block
 block discarded – undo
547 547
 				$c->getL10N('lib', $language)
548 548
 			);
549 549
 		});
550
-		$this->registerService('UserMountCache', function (Server $c) {
550
+		$this->registerService('UserMountCache', function(Server $c) {
551 551
 			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
552 552
 			$listener = new UserMountCacheListener($mountCache);
553 553
 			$listener->listen($c->getUserManager());
554 554
 			return $mountCache;
555 555
 		});
556
-		$this->registerService('MountConfigManager', function (Server $c) {
556
+		$this->registerService('MountConfigManager', function(Server $c) {
557 557
 			$loader = \OC\Files\Filesystem::getLoader();
558 558
 			$mountCache = $c->query('UserMountCache');
559
-			$manager =  new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
559
+			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
560 560
 
561 561
 			// builtin providers
562 562
 
@@ -567,14 +567,14 @@  discard block
 block discarded – undo
567 567
 
568 568
 			return $manager;
569 569
 		});
570
-		$this->registerService('IniWrapper', function ($c) {
570
+		$this->registerService('IniWrapper', function($c) {
571 571
 			return new IniGetWrapper();
572 572
 		});
573
-		$this->registerService('AsyncCommandBus', function (Server $c) {
573
+		$this->registerService('AsyncCommandBus', function(Server $c) {
574 574
 			$jobList = $c->getJobList();
575 575
 			return new AsyncBus($jobList);
576 576
 		});
577
-		$this->registerService('TrustedDomainHelper', function ($c) {
577
+		$this->registerService('TrustedDomainHelper', function($c) {
578 578
 			return new TrustedDomainHelper($this->getConfig());
579 579
 		});
580 580
 		$this->registerService('Throttler', function(Server $c) {
@@ -585,10 +585,10 @@  discard block
 block discarded – undo
585 585
 				$c->getConfig()
586 586
 			);
587 587
 		});
588
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
588
+		$this->registerService('IntegrityCodeChecker', function(Server $c) {
589 589
 			// IConfig and IAppManager requires a working database. This code
590 590
 			// might however be called when ownCloud is not yet setup.
591
-			if(\OC::$server->getSystemConfig()->getValue('installed', false)) {
591
+			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
592 592
 				$config = $c->getConfig();
593 593
 				$appManager = $c->getAppManager();
594 594
 			} else {
@@ -606,7 +606,7 @@  discard block
 block discarded – undo
606 606
 					$c->getTempManager()
607 607
 			);
608 608
 		});
609
-		$this->registerService('Request', function ($c) {
609
+		$this->registerService('Request', function($c) {
610 610
 			if (isset($this['urlParams'])) {
611 611
 				$urlParams = $this['urlParams'];
612 612
 			} else {
@@ -640,7 +640,7 @@  discard block
 block discarded – undo
640 640
 				$stream
641 641
 			);
642 642
 		});
643
-		$this->registerService('Mailer', function (Server $c) {
643
+		$this->registerService('Mailer', function(Server $c) {
644 644
 			return new Mailer(
645 645
 				$c->getConfig(),
646 646
 				$c->getLogger(),
@@ -650,14 +650,14 @@  discard block
 block discarded – undo
650 650
 		$this->registerService('LDAPProvider', function(Server $c) {
651 651
 			$config = $c->getConfig();
652 652
 			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
653
-			if(is_null($factoryClass)) {
653
+			if (is_null($factoryClass)) {
654 654
 				throw new \Exception('ldapProviderFactory not set');
655 655
 			}
656 656
 			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
657 657
 			$factory = new $factoryClass($this);
658 658
 			return $factory->getLDAPProvider();
659 659
 		});
660
-		$this->registerService('LockingProvider', function (Server $c) {
660
+		$this->registerService('LockingProvider', function(Server $c) {
661 661
 			$ini = $c->getIniWrapper();
662 662
 			$config = $c->getConfig();
663 663
 			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
@@ -672,29 +672,29 @@  discard block
 block discarded – undo
672 672
 			}
673 673
 			return new NoopLockingProvider();
674 674
 		});
675
-		$this->registerService('MountManager', function () {
675
+		$this->registerService('MountManager', function() {
676 676
 			return new \OC\Files\Mount\Manager();
677 677
 		});
678
-		$this->registerService('MimeTypeDetector', function (Server $c) {
678
+		$this->registerService('MimeTypeDetector', function(Server $c) {
679 679
 			return new \OC\Files\Type\Detection(
680 680
 				$c->getURLGenerator(),
681 681
 				\OC::$configDir,
682
-				\OC::$SERVERROOT . '/resources/config/'
682
+				\OC::$SERVERROOT.'/resources/config/'
683 683
 			);
684 684
 		});
685
-		$this->registerService('MimeTypeLoader', function (Server $c) {
685
+		$this->registerService('MimeTypeLoader', function(Server $c) {
686 686
 			return new \OC\Files\Type\Loader(
687 687
 				$c->getDatabaseConnection()
688 688
 			);
689 689
 		});
690
-		$this->registerService('NotificationManager', function (Server $c) {
690
+		$this->registerService('NotificationManager', function(Server $c) {
691 691
 			return new Manager(
692 692
 				$c->query(IValidator::class)
693 693
 			);
694 694
 		});
695
-		$this->registerService('CapabilitiesManager', function (Server $c) {
695
+		$this->registerService('CapabilitiesManager', function(Server $c) {
696 696
 			$manager = new \OC\CapabilitiesManager($c->getLogger());
697
-			$manager->registerCapability(function () use ($c) {
697
+			$manager->registerCapability(function() use ($c) {
698 698
 				return new \OC\OCS\CoreCapabilities($c->getConfig());
699 699
 			});
700 700
 			return $manager;
@@ -732,10 +732,10 @@  discard block
 block discarded – undo
732 732
 			}
733 733
 			return new \OC_Defaults();
734 734
 		});
735
-		$this->registerService('EventDispatcher', function () {
735
+		$this->registerService('EventDispatcher', function() {
736 736
 			return new EventDispatcher();
737 737
 		});
738
-		$this->registerService('CryptoWrapper', function (Server $c) {
738
+		$this->registerService('CryptoWrapper', function(Server $c) {
739 739
 			// FIXME: Instantiiated here due to cyclic dependency
740 740
 			$request = new Request(
741 741
 				[
@@ -760,7 +760,7 @@  discard block
 block discarded – undo
760 760
 				$request
761 761
 			);
762 762
 		});
763
-		$this->registerService('CsrfTokenManager', function (Server $c) {
763
+		$this->registerService('CsrfTokenManager', function(Server $c) {
764 764
 			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
765 765
 
766 766
 			return new CsrfTokenManager(
@@ -768,10 +768,10 @@  discard block
 block discarded – undo
768 768
 				$c->query(SessionStorage::class)
769 769
 			);
770 770
 		});
771
-		$this->registerService(SessionStorage::class, function (Server $c) {
771
+		$this->registerService(SessionStorage::class, function(Server $c) {
772 772
 			return new SessionStorage($c->getSession());
773 773
 		});
774
-		$this->registerService('ContentSecurityPolicyManager', function (Server $c) {
774
+		$this->registerService('ContentSecurityPolicyManager', function(Server $c) {
775 775
 			return new ContentSecurityPolicyManager();
776 776
 		});
777 777
 		$this->registerService('ContentSecurityPolicyNonceManager', function(Server $c) {
@@ -817,23 +817,23 @@  discard block
 block discarded – undo
817 817
 			);
818 818
 			return $manager;
819 819
 		});
820
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
820
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
821 821
 			return new \OC\Files\AppData\Factory(
822 822
 				$c->getRootFolder(),
823 823
 				$c->getSystemConfig()
824 824
 			);
825 825
 		});
826 826
 
827
-		$this->registerService('LockdownManager', function (Server $c) {
827
+		$this->registerService('LockdownManager', function(Server $c) {
828 828
 			return new LockdownManager();
829 829
 		});
830 830
 
831
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
831
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
832 832
 			return new CloudIdManager();
833 833
 		});
834 834
 
835 835
 		/* To trick DI since we don't extend the DIContainer here */
836
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
836
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
837 837
 			return new CleanPreviewsBackgroundJob(
838 838
 				$c->getRootFolder(),
839 839
 				$c->getLogger(),
@@ -977,7 +977,7 @@  discard block
 block discarded – undo
977 977
 	 * @deprecated since 9.2.0 use IAppData
978 978
 	 */
979 979
 	public function getAppFolder() {
980
-		$dir = '/' . \OC_App::getCurrentApp();
980
+		$dir = '/'.\OC_App::getCurrentApp();
981 981
 		$root = $this->getRootFolder();
982 982
 		if (!$root->nodeExists($dir)) {
983 983
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.