Completed
Pull Request — master (#3884)
by Joas
120:31 queued 105:15
created
lib/private/Share20/Manager.php 2 patches
Indentation   +1269 added lines, -1269 removed lines patch added patch discarded remove patch
@@ -57,1296 +57,1296 @@
 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 {
194
-			// We can't handle other types yet
195
-			throw new \InvalidArgumentException('unkown share type');
196
-		}
197
-
198
-		// Verify the initiator of the share is set
199
-		if ($share->getSharedBy() === null) {
200
-			throw new \InvalidArgumentException('SharedBy should be set');
201
-		}
202
-
203
-		// Cannot share with yourself
204
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
205
-			$share->getSharedWith() === $share->getSharedBy()) {
206
-			throw new \InvalidArgumentException('Can\'t share with yourself');
207
-		}
208
-
209
-		// The path should be set
210
-		if ($share->getNode() === null) {
211
-			throw new \InvalidArgumentException('Path should be set');
212
-		}
213
-
214
-		// And it should be a file or a folder
215
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
216
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
217
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
218
-		}
219
-
220
-		// And you can't share your rootfolder
221
-		if ($this->userManager->userExists($share->getSharedBy())) {
222
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
223
-		} else {
224
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
225
-		}
226
-		if ($sharedPath === $share->getNode()->getPath()) {
227
-			throw new \InvalidArgumentException('You can\'t share your root folder');
228
-		}
229
-
230
-		// Check if we actually have share permissions
231
-		if (!$share->getNode()->isShareable()) {
232
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
233
-			throw new GenericShareException($message_t, $message_t, 404);
234
-		}
235
-
236
-		// Permissions should be set
237
-		if ($share->getPermissions() === null) {
238
-			throw new \InvalidArgumentException('A share requires permissions');
239
-		}
240
-
241
-		/*
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 {
194
+            // We can't handle other types yet
195
+            throw new \InvalidArgumentException('unkown share type');
196
+        }
197
+
198
+        // Verify the initiator of the share is set
199
+        if ($share->getSharedBy() === null) {
200
+            throw new \InvalidArgumentException('SharedBy should be set');
201
+        }
202
+
203
+        // Cannot share with yourself
204
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
205
+            $share->getSharedWith() === $share->getSharedBy()) {
206
+            throw new \InvalidArgumentException('Can\'t share with yourself');
207
+        }
208
+
209
+        // The path should be set
210
+        if ($share->getNode() === null) {
211
+            throw new \InvalidArgumentException('Path should be set');
212
+        }
213
+
214
+        // And it should be a file or a folder
215
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
216
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
217
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
218
+        }
219
+
220
+        // And you can't share your rootfolder
221
+        if ($this->userManager->userExists($share->getSharedBy())) {
222
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
223
+        } else {
224
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
225
+        }
226
+        if ($sharedPath === $share->getNode()->getPath()) {
227
+            throw new \InvalidArgumentException('You can\'t share your root folder');
228
+        }
229
+
230
+        // Check if we actually have share permissions
231
+        if (!$share->getNode()->isShareable()) {
232
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
233
+            throw new GenericShareException($message_t, $message_t, 404);
234
+        }
235
+
236
+        // Permissions should be set
237
+        if ($share->getPermissions() === null) {
238
+            throw new \InvalidArgumentException('A share requires permissions');
239
+        }
240
+
241
+        /*
242 242
 		 * Quick fix for #23536
243 243
 		 * Non moveable mount points do not have update and delete permissions
244 244
 		 * while we 'most likely' do have that on the storage.
245 245
 		 */
246
-		$permissions = $share->getNode()->getPermissions();
247
-		$mount = $share->getNode()->getMountPoint();
248
-		if (!($mount instanceof MoveableMount)) {
249
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
250
-		}
251
-
252
-		// Check that we do not share with more permissions than we have
253
-		if ($share->getPermissions() & ~$permissions) {
254
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
255
-			throw new GenericShareException($message_t, $message_t, 404);
256
-		}
257
-
258
-
259
-		// Check that read permissions are always set
260
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
261
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
262
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
263
-			throw new \InvalidArgumentException('Shares need at least read permissions');
264
-		}
265
-
266
-		if ($share->getNode() instanceof \OCP\Files\File) {
267
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
268
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
269
-				throw new GenericShareException($message_t);
270
-			}
271
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
272
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
273
-				throw new GenericShareException($message_t);
274
-			}
275
-		}
276
-	}
277
-
278
-	/**
279
-	 * Validate if the expiration date fits the system settings
280
-	 *
281
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
282
-	 * @return \OCP\Share\IShare The modified share object
283
-	 * @throws GenericShareException
284
-	 * @throws \InvalidArgumentException
285
-	 * @throws \Exception
286
-	 */
287
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
288
-
289
-		$expirationDate = $share->getExpirationDate();
290
-
291
-		if ($expirationDate !== null) {
292
-			//Make sure the expiration date is a date
293
-			$expirationDate->setTime(0, 0, 0);
294
-
295
-			$date = new \DateTime();
296
-			$date->setTime(0, 0, 0);
297
-			if ($date >= $expirationDate) {
298
-				$message = $this->l->t('Expiration date is in the past');
299
-				throw new GenericShareException($message, $message, 404);
300
-			}
301
-		}
302
-
303
-		// If expiredate is empty set a default one if there is a default
304
-		$fullId = null;
305
-		try {
306
-			$fullId = $share->getFullId();
307
-		} catch (\UnexpectedValueException $e) {
308
-			// This is a new share
309
-		}
310
-
311
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
312
-			$expirationDate = new \DateTime();
313
-			$expirationDate->setTime(0,0,0);
314
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
315
-		}
316
-
317
-		// If we enforce the expiration date check that is does not exceed
318
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
319
-			if ($expirationDate === null) {
320
-				throw new \InvalidArgumentException('Expiration date is enforced');
321
-			}
322
-
323
-			$date = new \DateTime();
324
-			$date->setTime(0, 0, 0);
325
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
326
-			if ($date < $expirationDate) {
327
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
328
-				throw new GenericShareException($message, $message, 404);
329
-			}
330
-		}
331
-
332
-		$accepted = true;
333
-		$message = '';
334
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
335
-			'expirationDate' => &$expirationDate,
336
-			'accepted' => &$accepted,
337
-			'message' => &$message,
338
-			'passwordSet' => $share->getPassword() !== null,
339
-		]);
340
-
341
-		if (!$accepted) {
342
-			throw new \Exception($message);
343
-		}
344
-
345
-		$share->setExpirationDate($expirationDate);
346
-
347
-		return $share;
348
-	}
349
-
350
-	/**
351
-	 * Check for pre share requirements for user shares
352
-	 *
353
-	 * @param \OCP\Share\IShare $share
354
-	 * @throws \Exception
355
-	 */
356
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
357
-		// Check if we can share with group members only
358
-		if ($this->shareWithGroupMembersOnly()) {
359
-			$sharedBy = $this->userManager->get($share->getSharedBy());
360
-			$sharedWith = $this->userManager->get($share->getSharedWith());
361
-			// Verify we can share with this user
362
-			$groups = array_intersect(
363
-					$this->groupManager->getUserGroupIds($sharedBy),
364
-					$this->groupManager->getUserGroupIds($sharedWith)
365
-			);
366
-			if (empty($groups)) {
367
-				throw new \Exception('Only sharing with group members is allowed');
368
-			}
369
-		}
370
-
371
-		/*
246
+        $permissions = $share->getNode()->getPermissions();
247
+        $mount = $share->getNode()->getMountPoint();
248
+        if (!($mount instanceof MoveableMount)) {
249
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
250
+        }
251
+
252
+        // Check that we do not share with more permissions than we have
253
+        if ($share->getPermissions() & ~$permissions) {
254
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
255
+            throw new GenericShareException($message_t, $message_t, 404);
256
+        }
257
+
258
+
259
+        // Check that read permissions are always set
260
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
261
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK &&
262
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
263
+            throw new \InvalidArgumentException('Shares need at least read permissions');
264
+        }
265
+
266
+        if ($share->getNode() instanceof \OCP\Files\File) {
267
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
268
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
269
+                throw new GenericShareException($message_t);
270
+            }
271
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
272
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
273
+                throw new GenericShareException($message_t);
274
+            }
275
+        }
276
+    }
277
+
278
+    /**
279
+     * Validate if the expiration date fits the system settings
280
+     *
281
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
282
+     * @return \OCP\Share\IShare The modified share object
283
+     * @throws GenericShareException
284
+     * @throws \InvalidArgumentException
285
+     * @throws \Exception
286
+     */
287
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
288
+
289
+        $expirationDate = $share->getExpirationDate();
290
+
291
+        if ($expirationDate !== null) {
292
+            //Make sure the expiration date is a date
293
+            $expirationDate->setTime(0, 0, 0);
294
+
295
+            $date = new \DateTime();
296
+            $date->setTime(0, 0, 0);
297
+            if ($date >= $expirationDate) {
298
+                $message = $this->l->t('Expiration date is in the past');
299
+                throw new GenericShareException($message, $message, 404);
300
+            }
301
+        }
302
+
303
+        // If expiredate is empty set a default one if there is a default
304
+        $fullId = null;
305
+        try {
306
+            $fullId = $share->getFullId();
307
+        } catch (\UnexpectedValueException $e) {
308
+            // This is a new share
309
+        }
310
+
311
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
312
+            $expirationDate = new \DateTime();
313
+            $expirationDate->setTime(0,0,0);
314
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
315
+        }
316
+
317
+        // If we enforce the expiration date check that is does not exceed
318
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
319
+            if ($expirationDate === null) {
320
+                throw new \InvalidArgumentException('Expiration date is enforced');
321
+            }
322
+
323
+            $date = new \DateTime();
324
+            $date->setTime(0, 0, 0);
325
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
326
+            if ($date < $expirationDate) {
327
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
328
+                throw new GenericShareException($message, $message, 404);
329
+            }
330
+        }
331
+
332
+        $accepted = true;
333
+        $message = '';
334
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
335
+            'expirationDate' => &$expirationDate,
336
+            'accepted' => &$accepted,
337
+            'message' => &$message,
338
+            'passwordSet' => $share->getPassword() !== null,
339
+        ]);
340
+
341
+        if (!$accepted) {
342
+            throw new \Exception($message);
343
+        }
344
+
345
+        $share->setExpirationDate($expirationDate);
346
+
347
+        return $share;
348
+    }
349
+
350
+    /**
351
+     * Check for pre share requirements for user shares
352
+     *
353
+     * @param \OCP\Share\IShare $share
354
+     * @throws \Exception
355
+     */
356
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
357
+        // Check if we can share with group members only
358
+        if ($this->shareWithGroupMembersOnly()) {
359
+            $sharedBy = $this->userManager->get($share->getSharedBy());
360
+            $sharedWith = $this->userManager->get($share->getSharedWith());
361
+            // Verify we can share with this user
362
+            $groups = array_intersect(
363
+                    $this->groupManager->getUserGroupIds($sharedBy),
364
+                    $this->groupManager->getUserGroupIds($sharedWith)
365
+            );
366
+            if (empty($groups)) {
367
+                throw new \Exception('Only sharing with group members is allowed');
368
+            }
369
+        }
370
+
371
+        /*
372 372
 		 * TODO: Could be costly, fix
373 373
 		 *
374 374
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
375 375
 		 */
376
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
377
-		$existingShares = $provider->getSharesByPath($share->getNode());
378
-		foreach($existingShares as $existingShare) {
379
-			// Ignore if it is the same share
380
-			try {
381
-				if ($existingShare->getFullId() === $share->getFullId()) {
382
-					continue;
383
-				}
384
-			} catch (\UnexpectedValueException $e) {
385
-				//Shares are not identical
386
-			}
387
-
388
-			// Identical share already existst
389
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
390
-				throw new \Exception('Path already shared with this user');
391
-			}
392
-
393
-			// The share is already shared with this user via a group share
394
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
395
-				$group = $this->groupManager->get($existingShare->getSharedWith());
396
-				if (!is_null($group)) {
397
-					$user = $this->userManager->get($share->getSharedWith());
398
-
399
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
400
-						throw new \Exception('Path already shared with this user');
401
-					}
402
-				}
403
-			}
404
-		}
405
-	}
406
-
407
-	/**
408
-	 * Check for pre share requirements for group shares
409
-	 *
410
-	 * @param \OCP\Share\IShare $share
411
-	 * @throws \Exception
412
-	 */
413
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
414
-		// Verify group shares are allowed
415
-		if (!$this->allowGroupSharing()) {
416
-			throw new \Exception('Group sharing is now allowed');
417
-		}
418
-
419
-		// Verify if the user can share with this group
420
-		if ($this->shareWithGroupMembersOnly()) {
421
-			$sharedBy = $this->userManager->get($share->getSharedBy());
422
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
423
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
424
-				throw new \Exception('Only sharing within your own groups is allowed');
425
-			}
426
-		}
427
-
428
-		/*
376
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
377
+        $existingShares = $provider->getSharesByPath($share->getNode());
378
+        foreach($existingShares as $existingShare) {
379
+            // Ignore if it is the same share
380
+            try {
381
+                if ($existingShare->getFullId() === $share->getFullId()) {
382
+                    continue;
383
+                }
384
+            } catch (\UnexpectedValueException $e) {
385
+                //Shares are not identical
386
+            }
387
+
388
+            // Identical share already existst
389
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
390
+                throw new \Exception('Path already shared with this user');
391
+            }
392
+
393
+            // The share is already shared with this user via a group share
394
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
395
+                $group = $this->groupManager->get($existingShare->getSharedWith());
396
+                if (!is_null($group)) {
397
+                    $user = $this->userManager->get($share->getSharedWith());
398
+
399
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
400
+                        throw new \Exception('Path already shared with this user');
401
+                    }
402
+                }
403
+            }
404
+        }
405
+    }
406
+
407
+    /**
408
+     * Check for pre share requirements for group shares
409
+     *
410
+     * @param \OCP\Share\IShare $share
411
+     * @throws \Exception
412
+     */
413
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
414
+        // Verify group shares are allowed
415
+        if (!$this->allowGroupSharing()) {
416
+            throw new \Exception('Group sharing is now allowed');
417
+        }
418
+
419
+        // Verify if the user can share with this group
420
+        if ($this->shareWithGroupMembersOnly()) {
421
+            $sharedBy = $this->userManager->get($share->getSharedBy());
422
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
423
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
424
+                throw new \Exception('Only sharing within your own groups is allowed');
425
+            }
426
+        }
427
+
428
+        /*
429 429
 		 * TODO: Could be costly, fix
430 430
 		 *
431 431
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
432 432
 		 */
433
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
434
-		$existingShares = $provider->getSharesByPath($share->getNode());
435
-		foreach($existingShares as $existingShare) {
436
-			try {
437
-				if ($existingShare->getFullId() === $share->getFullId()) {
438
-					continue;
439
-				}
440
-			} catch (\UnexpectedValueException $e) {
441
-				//It is a new share so just continue
442
-			}
443
-
444
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
445
-				throw new \Exception('Path already shared with this group');
446
-			}
447
-		}
448
-	}
449
-
450
-	/**
451
-	 * Check for pre share requirements for link shares
452
-	 *
453
-	 * @param \OCP\Share\IShare $share
454
-	 * @throws \Exception
455
-	 */
456
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
457
-		// Are link shares allowed?
458
-		if (!$this->shareApiAllowLinks()) {
459
-			throw new \Exception('Link sharing not allowed');
460
-		}
461
-
462
-		// Link shares by definition can't have share permissions
463
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
464
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
465
-		}
466
-
467
-		// Check if public upload is allowed
468
-		if (!$this->shareApiLinkAllowPublicUpload() &&
469
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
470
-			throw new \InvalidArgumentException('Public upload not allowed');
471
-		}
472
-	}
473
-
474
-	/**
475
-	 * To make sure we don't get invisible link shares we set the parent
476
-	 * of a link if it is a reshare. This is a quick word around
477
-	 * until we can properly display multiple link shares in the UI
478
-	 *
479
-	 * See: https://github.com/owncloud/core/issues/22295
480
-	 *
481
-	 * FIXME: Remove once multiple link shares can be properly displayed
482
-	 *
483
-	 * @param \OCP\Share\IShare $share
484
-	 */
485
-	protected function setLinkParent(\OCP\Share\IShare $share) {
486
-
487
-		// No sense in checking if the method is not there.
488
-		if (method_exists($share, 'setParent')) {
489
-			$storage = $share->getNode()->getStorage();
490
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
491
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
492
-				$share->setParent($storage->getShareId());
493
-			}
494
-		};
495
-	}
496
-
497
-	/**
498
-	 * @param File|Folder $path
499
-	 */
500
-	protected function pathCreateChecks($path) {
501
-		// Make sure that we do not share a path that contains a shared mountpoint
502
-		if ($path instanceof \OCP\Files\Folder) {
503
-			$mounts = $this->mountManager->findIn($path->getPath());
504
-			foreach($mounts as $mount) {
505
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
506
-					throw new \InvalidArgumentException('Path contains files shared with you');
507
-				}
508
-			}
509
-		}
510
-	}
511
-
512
-	/**
513
-	 * Check if the user that is sharing can actually share
514
-	 *
515
-	 * @param \OCP\Share\IShare $share
516
-	 * @throws \Exception
517
-	 */
518
-	protected function canShare(\OCP\Share\IShare $share) {
519
-		if (!$this->shareApiEnabled()) {
520
-			throw new \Exception('The share API is disabled');
521
-		}
522
-
523
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
524
-			throw new \Exception('You are not allowed to share');
525
-		}
526
-	}
527
-
528
-	/**
529
-	 * Share a path
530
-	 *
531
-	 * @param \OCP\Share\IShare $share
532
-	 * @return Share The share object
533
-	 * @throws \Exception
534
-	 *
535
-	 * TODO: handle link share permissions or check them
536
-	 */
537
-	public function createShare(\OCP\Share\IShare $share) {
538
-		$this->canShare($share);
539
-
540
-		$this->generalCreateChecks($share);
541
-
542
-		// Verify if there are any issues with the path
543
-		$this->pathCreateChecks($share->getNode());
544
-
545
-		/*
433
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
434
+        $existingShares = $provider->getSharesByPath($share->getNode());
435
+        foreach($existingShares as $existingShare) {
436
+            try {
437
+                if ($existingShare->getFullId() === $share->getFullId()) {
438
+                    continue;
439
+                }
440
+            } catch (\UnexpectedValueException $e) {
441
+                //It is a new share so just continue
442
+            }
443
+
444
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
445
+                throw new \Exception('Path already shared with this group');
446
+            }
447
+        }
448
+    }
449
+
450
+    /**
451
+     * Check for pre share requirements for link shares
452
+     *
453
+     * @param \OCP\Share\IShare $share
454
+     * @throws \Exception
455
+     */
456
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
457
+        // Are link shares allowed?
458
+        if (!$this->shareApiAllowLinks()) {
459
+            throw new \Exception('Link sharing not allowed');
460
+        }
461
+
462
+        // Link shares by definition can't have share permissions
463
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
464
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
465
+        }
466
+
467
+        // Check if public upload is allowed
468
+        if (!$this->shareApiLinkAllowPublicUpload() &&
469
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
470
+            throw new \InvalidArgumentException('Public upload not allowed');
471
+        }
472
+    }
473
+
474
+    /**
475
+     * To make sure we don't get invisible link shares we set the parent
476
+     * of a link if it is a reshare. This is a quick word around
477
+     * until we can properly display multiple link shares in the UI
478
+     *
479
+     * See: https://github.com/owncloud/core/issues/22295
480
+     *
481
+     * FIXME: Remove once multiple link shares can be properly displayed
482
+     *
483
+     * @param \OCP\Share\IShare $share
484
+     */
485
+    protected function setLinkParent(\OCP\Share\IShare $share) {
486
+
487
+        // No sense in checking if the method is not there.
488
+        if (method_exists($share, 'setParent')) {
489
+            $storage = $share->getNode()->getStorage();
490
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
491
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
492
+                $share->setParent($storage->getShareId());
493
+            }
494
+        };
495
+    }
496
+
497
+    /**
498
+     * @param File|Folder $path
499
+     */
500
+    protected function pathCreateChecks($path) {
501
+        // Make sure that we do not share a path that contains a shared mountpoint
502
+        if ($path instanceof \OCP\Files\Folder) {
503
+            $mounts = $this->mountManager->findIn($path->getPath());
504
+            foreach($mounts as $mount) {
505
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
506
+                    throw new \InvalidArgumentException('Path contains files shared with you');
507
+                }
508
+            }
509
+        }
510
+    }
511
+
512
+    /**
513
+     * Check if the user that is sharing can actually share
514
+     *
515
+     * @param \OCP\Share\IShare $share
516
+     * @throws \Exception
517
+     */
518
+    protected function canShare(\OCP\Share\IShare $share) {
519
+        if (!$this->shareApiEnabled()) {
520
+            throw new \Exception('The share API is disabled');
521
+        }
522
+
523
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
524
+            throw new \Exception('You are not allowed to share');
525
+        }
526
+    }
527
+
528
+    /**
529
+     * Share a path
530
+     *
531
+     * @param \OCP\Share\IShare $share
532
+     * @return Share The share object
533
+     * @throws \Exception
534
+     *
535
+     * TODO: handle link share permissions or check them
536
+     */
537
+    public function createShare(\OCP\Share\IShare $share) {
538
+        $this->canShare($share);
539
+
540
+        $this->generalCreateChecks($share);
541
+
542
+        // Verify if there are any issues with the path
543
+        $this->pathCreateChecks($share->getNode());
544
+
545
+        /*
546 546
 		 * On creation of a share the owner is always the owner of the path
547 547
 		 * Except for mounted federated shares.
548 548
 		 */
549
-		$storage = $share->getNode()->getStorage();
550
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
551
-			$parent = $share->getNode()->getParent();
552
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
553
-				$parent = $parent->getParent();
554
-			}
555
-			$share->setShareOwner($parent->getOwner()->getUID());
556
-		} else {
557
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
558
-		}
559
-
560
-		//Verify share type
561
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
562
-			$this->userCreateChecks($share);
563
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
564
-			$this->groupCreateChecks($share);
565
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
566
-			$this->linkCreateChecks($share);
567
-			$this->setLinkParent($share);
568
-
569
-			/*
549
+        $storage = $share->getNode()->getStorage();
550
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
551
+            $parent = $share->getNode()->getParent();
552
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
553
+                $parent = $parent->getParent();
554
+            }
555
+            $share->setShareOwner($parent->getOwner()->getUID());
556
+        } else {
557
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
558
+        }
559
+
560
+        //Verify share type
561
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
562
+            $this->userCreateChecks($share);
563
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
564
+            $this->groupCreateChecks($share);
565
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
566
+            $this->linkCreateChecks($share);
567
+            $this->setLinkParent($share);
568
+
569
+            /*
570 570
 			 * For now ignore a set token.
571 571
 			 */
572
-			$share->setToken(
573
-				$this->secureRandom->generate(
574
-					\OC\Share\Constants::TOKEN_LENGTH,
575
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
576
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
577
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
578
-				)
579
-			);
580
-
581
-			//Verify the expiration date
582
-			$this->validateExpirationDate($share);
583
-
584
-			//Verify the password
585
-			$this->verifyPassword($share->getPassword());
586
-
587
-			// If a password is set. Hash it!
588
-			if ($share->getPassword() !== null) {
589
-				$share->setPassword($this->hasher->hash($share->getPassword()));
590
-			}
591
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
592
-			$share->setToken(
593
-				$this->secureRandom->generate(
594
-					\OC\Share\Constants::TOKEN_LENGTH,
595
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
596
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
597
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
598
-				)
599
-			);
600
-		}
601
-
602
-		// Cannot share with the owner
603
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
604
-			$share->getSharedWith() === $share->getShareOwner()) {
605
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
606
-		}
607
-
608
-		// Generate the target
609
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
610
-		$target = \OC\Files\Filesystem::normalizePath($target);
611
-		$share->setTarget($target);
612
-
613
-		// Pre share hook
614
-		$run = true;
615
-		$error = '';
616
-		$preHookData = [
617
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
618
-			'itemSource' => $share->getNode()->getId(),
619
-			'shareType' => $share->getShareType(),
620
-			'uidOwner' => $share->getSharedBy(),
621
-			'permissions' => $share->getPermissions(),
622
-			'fileSource' => $share->getNode()->getId(),
623
-			'expiration' => $share->getExpirationDate(),
624
-			'token' => $share->getToken(),
625
-			'itemTarget' => $share->getTarget(),
626
-			'shareWith' => $share->getSharedWith(),
627
-			'run' => &$run,
628
-			'error' => &$error,
629
-		];
630
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
631
-
632
-		if ($run === false) {
633
-			throw new \Exception($error);
634
-		}
635
-
636
-		$oldShare = $share;
637
-		$provider = $this->factory->getProviderForType($share->getShareType());
638
-		$share = $provider->create($share);
639
-		//reuse the node we already have
640
-		$share->setNode($oldShare->getNode());
641
-
642
-		// Post share hook
643
-		$postHookData = [
644
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
645
-			'itemSource' => $share->getNode()->getId(),
646
-			'shareType' => $share->getShareType(),
647
-			'uidOwner' => $share->getSharedBy(),
648
-			'permissions' => $share->getPermissions(),
649
-			'fileSource' => $share->getNode()->getId(),
650
-			'expiration' => $share->getExpirationDate(),
651
-			'token' => $share->getToken(),
652
-			'id' => $share->getId(),
653
-			'shareWith' => $share->getSharedWith(),
654
-			'itemTarget' => $share->getTarget(),
655
-			'fileTarget' => $share->getTarget(),
656
-		];
657
-
658
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
659
-
660
-		return $share;
661
-	}
662
-
663
-	/**
664
-	 * Update a share
665
-	 *
666
-	 * @param \OCP\Share\IShare $share
667
-	 * @return \OCP\Share\IShare The share object
668
-	 * @throws \InvalidArgumentException
669
-	 */
670
-	public function updateShare(\OCP\Share\IShare $share) {
671
-		$expirationDateUpdated = false;
672
-
673
-		$this->canShare($share);
674
-
675
-		try {
676
-			$originalShare = $this->getShareById($share->getFullId());
677
-		} catch (\UnexpectedValueException $e) {
678
-			throw new \InvalidArgumentException('Share does not have a full id');
679
-		}
680
-
681
-		// We can't change the share type!
682
-		if ($share->getShareType() !== $originalShare->getShareType()) {
683
-			throw new \InvalidArgumentException('Can\'t change share type');
684
-		}
685
-
686
-		// We can only change the recipient on user shares
687
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
688
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
689
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
690
-		}
691
-
692
-		// Cannot share with the owner
693
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
694
-			$share->getSharedWith() === $share->getShareOwner()) {
695
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
696
-		}
697
-
698
-		$this->generalCreateChecks($share);
699
-
700
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
701
-			$this->userCreateChecks($share);
702
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
703
-			$this->groupCreateChecks($share);
704
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
705
-			$this->linkCreateChecks($share);
706
-
707
-			// Password updated.
708
-			if ($share->getPassword() !== $originalShare->getPassword()) {
709
-				//Verify the password
710
-				$this->verifyPassword($share->getPassword());
711
-
712
-				// If a password is set. Hash it!
713
-				if ($share->getPassword() !== null) {
714
-					$share->setPassword($this->hasher->hash($share->getPassword()));
715
-				}
716
-			}
717
-
718
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
719
-				//Verify the expiration date
720
-				$this->validateExpirationDate($share);
721
-				$expirationDateUpdated = true;
722
-			}
723
-		}
724
-
725
-		$this->pathCreateChecks($share->getNode());
726
-
727
-		// Now update the share!
728
-		$provider = $this->factory->getProviderForType($share->getShareType());
729
-		$share = $provider->update($share);
730
-
731
-		if ($expirationDateUpdated === true) {
732
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
733
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
734
-				'itemSource' => $share->getNode()->getId(),
735
-				'date' => $share->getExpirationDate(),
736
-				'uidOwner' => $share->getSharedBy(),
737
-			]);
738
-		}
739
-
740
-		if ($share->getPassword() !== $originalShare->getPassword()) {
741
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
742
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
743
-				'itemSource' => $share->getNode()->getId(),
744
-				'uidOwner' => $share->getSharedBy(),
745
-				'token' => $share->getToken(),
746
-				'disabled' => is_null($share->getPassword()),
747
-			]);
748
-		}
749
-
750
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
751
-			if ($this->userManager->userExists($share->getShareOwner())) {
752
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
753
-			} else {
754
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
755
-			}
756
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
757
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
758
-				'itemSource' => $share->getNode()->getId(),
759
-				'shareType' => $share->getShareType(),
760
-				'shareWith' => $share->getSharedWith(),
761
-				'uidOwner' => $share->getSharedBy(),
762
-				'permissions' => $share->getPermissions(),
763
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
764
-			));
765
-		}
766
-
767
-		return $share;
768
-	}
769
-
770
-	/**
771
-	 * Delete all the children of this share
772
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
773
-	 *
774
-	 * @param \OCP\Share\IShare $share
775
-	 * @return \OCP\Share\IShare[] List of deleted shares
776
-	 */
777
-	protected function deleteChildren(\OCP\Share\IShare $share) {
778
-		$deletedShares = [];
779
-
780
-		$provider = $this->factory->getProviderForType($share->getShareType());
781
-
782
-		foreach ($provider->getChildren($share) as $child) {
783
-			$deletedChildren = $this->deleteChildren($child);
784
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
785
-
786
-			$provider->delete($child);
787
-			$deletedShares[] = $child;
788
-		}
789
-
790
-		return $deletedShares;
791
-	}
792
-
793
-	/**
794
-	 * Delete a share
795
-	 *
796
-	 * @param \OCP\Share\IShare $share
797
-	 * @throws ShareNotFound
798
-	 * @throws \InvalidArgumentException
799
-	 */
800
-	public function deleteShare(\OCP\Share\IShare $share) {
801
-
802
-		try {
803
-			$share->getFullId();
804
-		} catch (\UnexpectedValueException $e) {
805
-			throw new \InvalidArgumentException('Share does not have a full id');
806
-		}
807
-
808
-		$formatHookParams = function(\OCP\Share\IShare $share) {
809
-			// Prepare hook
810
-			$shareType = $share->getShareType();
811
-			$sharedWith = '';
812
-			if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
813
-				$sharedWith = $share->getSharedWith();
814
-			} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
815
-				$sharedWith = $share->getSharedWith();
816
-			} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
817
-				$sharedWith = $share->getSharedWith();
818
-			}
819
-
820
-			$hookParams = [
821
-				'id'         => $share->getId(),
822
-				'itemType'   => $share->getNodeType(),
823
-				'itemSource' => $share->getNodeId(),
824
-				'shareType'  => $shareType,
825
-				'shareWith'  => $sharedWith,
826
-				'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
827
-				'uidOwner'   => $share->getSharedBy(),
828
-				'fileSource' => $share->getNodeId(),
829
-				'fileTarget' => $share->getTarget()
830
-			];
831
-			return $hookParams;
832
-		};
833
-
834
-		$hookParams = $formatHookParams($share);
835
-
836
-		// Emit pre-hook
837
-		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
838
-
839
-		// Get all children and delete them as well
840
-		$deletedShares = $this->deleteChildren($share);
841
-
842
-		// Do the actual delete
843
-		$provider = $this->factory->getProviderForType($share->getShareType());
844
-		$provider->delete($share);
845
-
846
-		// All the deleted shares caused by this delete
847
-		$deletedShares[] = $share;
848
-
849
-		//Format hook info
850
-		$formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
851
-			return $formatHookParams($share);
852
-		}, $deletedShares);
853
-
854
-		$hookParams['deletedShares'] = $formattedDeletedShares;
855
-
856
-		// Emit post hook
857
-		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
858
-	}
859
-
860
-
861
-	/**
862
-	 * Unshare a file as the recipient.
863
-	 * This can be different from a regular delete for example when one of
864
-	 * the users in a groups deletes that share. But the provider should
865
-	 * handle this.
866
-	 *
867
-	 * @param \OCP\Share\IShare $share
868
-	 * @param string $recipientId
869
-	 */
870
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
871
-		list($providerId, ) = $this->splitFullId($share->getFullId());
872
-		$provider = $this->factory->getProvider($providerId);
873
-
874
-		$provider->deleteFromSelf($share, $recipientId);
875
-	}
876
-
877
-	/**
878
-	 * @inheritdoc
879
-	 */
880
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
881
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
882
-			throw new \InvalidArgumentException('Can\'t change target of link share');
883
-		}
884
-
885
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
886
-			throw new \InvalidArgumentException('Invalid recipient');
887
-		}
888
-
889
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
890
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
891
-			if (is_null($sharedWith)) {
892
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
893
-			}
894
-			$recipient = $this->userManager->get($recipientId);
895
-			if (!$sharedWith->inGroup($recipient)) {
896
-				throw new \InvalidArgumentException('Invalid recipient');
897
-			}
898
-		}
899
-
900
-		list($providerId, ) = $this->splitFullId($share->getFullId());
901
-		$provider = $this->factory->getProvider($providerId);
902
-
903
-		$provider->move($share, $recipientId);
904
-	}
905
-
906
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
907
-		$providers = $this->factory->getAllProviders();
908
-
909
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
910
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
911
-			foreach ($newShares as $fid => $data) {
912
-				if (!isset($shares[$fid])) {
913
-					$shares[$fid] = [];
914
-				}
915
-
916
-				$shares[$fid] = array_merge($shares[$fid], $data);
917
-			}
918
-			return $shares;
919
-		}, []);
920
-	}
921
-
922
-	/**
923
-	 * @inheritdoc
924
-	 */
925
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
926
-		if ($path !== null &&
927
-				!($path instanceof \OCP\Files\File) &&
928
-				!($path instanceof \OCP\Files\Folder)) {
929
-			throw new \InvalidArgumentException('invalid path');
930
-		}
931
-
932
-		try {
933
-			$provider = $this->factory->getProviderForType($shareType);
934
-		} catch (ProviderException $e) {
935
-			return [];
936
-		}
937
-
938
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
939
-
940
-		/*
572
+            $share->setToken(
573
+                $this->secureRandom->generate(
574
+                    \OC\Share\Constants::TOKEN_LENGTH,
575
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
576
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
577
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
578
+                )
579
+            );
580
+
581
+            //Verify the expiration date
582
+            $this->validateExpirationDate($share);
583
+
584
+            //Verify the password
585
+            $this->verifyPassword($share->getPassword());
586
+
587
+            // If a password is set. Hash it!
588
+            if ($share->getPassword() !== null) {
589
+                $share->setPassword($this->hasher->hash($share->getPassword()));
590
+            }
591
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
592
+            $share->setToken(
593
+                $this->secureRandom->generate(
594
+                    \OC\Share\Constants::TOKEN_LENGTH,
595
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
596
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
597
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
598
+                )
599
+            );
600
+        }
601
+
602
+        // Cannot share with the owner
603
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
604
+            $share->getSharedWith() === $share->getShareOwner()) {
605
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
606
+        }
607
+
608
+        // Generate the target
609
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
610
+        $target = \OC\Files\Filesystem::normalizePath($target);
611
+        $share->setTarget($target);
612
+
613
+        // Pre share hook
614
+        $run = true;
615
+        $error = '';
616
+        $preHookData = [
617
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
618
+            'itemSource' => $share->getNode()->getId(),
619
+            'shareType' => $share->getShareType(),
620
+            'uidOwner' => $share->getSharedBy(),
621
+            'permissions' => $share->getPermissions(),
622
+            'fileSource' => $share->getNode()->getId(),
623
+            'expiration' => $share->getExpirationDate(),
624
+            'token' => $share->getToken(),
625
+            'itemTarget' => $share->getTarget(),
626
+            'shareWith' => $share->getSharedWith(),
627
+            'run' => &$run,
628
+            'error' => &$error,
629
+        ];
630
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
631
+
632
+        if ($run === false) {
633
+            throw new \Exception($error);
634
+        }
635
+
636
+        $oldShare = $share;
637
+        $provider = $this->factory->getProviderForType($share->getShareType());
638
+        $share = $provider->create($share);
639
+        //reuse the node we already have
640
+        $share->setNode($oldShare->getNode());
641
+
642
+        // Post share hook
643
+        $postHookData = [
644
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
645
+            'itemSource' => $share->getNode()->getId(),
646
+            'shareType' => $share->getShareType(),
647
+            'uidOwner' => $share->getSharedBy(),
648
+            'permissions' => $share->getPermissions(),
649
+            'fileSource' => $share->getNode()->getId(),
650
+            'expiration' => $share->getExpirationDate(),
651
+            'token' => $share->getToken(),
652
+            'id' => $share->getId(),
653
+            'shareWith' => $share->getSharedWith(),
654
+            'itemTarget' => $share->getTarget(),
655
+            'fileTarget' => $share->getTarget(),
656
+        ];
657
+
658
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
659
+
660
+        return $share;
661
+    }
662
+
663
+    /**
664
+     * Update a share
665
+     *
666
+     * @param \OCP\Share\IShare $share
667
+     * @return \OCP\Share\IShare The share object
668
+     * @throws \InvalidArgumentException
669
+     */
670
+    public function updateShare(\OCP\Share\IShare $share) {
671
+        $expirationDateUpdated = false;
672
+
673
+        $this->canShare($share);
674
+
675
+        try {
676
+            $originalShare = $this->getShareById($share->getFullId());
677
+        } catch (\UnexpectedValueException $e) {
678
+            throw new \InvalidArgumentException('Share does not have a full id');
679
+        }
680
+
681
+        // We can't change the share type!
682
+        if ($share->getShareType() !== $originalShare->getShareType()) {
683
+            throw new \InvalidArgumentException('Can\'t change share type');
684
+        }
685
+
686
+        // We can only change the recipient on user shares
687
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
688
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
689
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
690
+        }
691
+
692
+        // Cannot share with the owner
693
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
694
+            $share->getSharedWith() === $share->getShareOwner()) {
695
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
696
+        }
697
+
698
+        $this->generalCreateChecks($share);
699
+
700
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
701
+            $this->userCreateChecks($share);
702
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
703
+            $this->groupCreateChecks($share);
704
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
705
+            $this->linkCreateChecks($share);
706
+
707
+            // Password updated.
708
+            if ($share->getPassword() !== $originalShare->getPassword()) {
709
+                //Verify the password
710
+                $this->verifyPassword($share->getPassword());
711
+
712
+                // If a password is set. Hash it!
713
+                if ($share->getPassword() !== null) {
714
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
715
+                }
716
+            }
717
+
718
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
719
+                //Verify the expiration date
720
+                $this->validateExpirationDate($share);
721
+                $expirationDateUpdated = true;
722
+            }
723
+        }
724
+
725
+        $this->pathCreateChecks($share->getNode());
726
+
727
+        // Now update the share!
728
+        $provider = $this->factory->getProviderForType($share->getShareType());
729
+        $share = $provider->update($share);
730
+
731
+        if ($expirationDateUpdated === true) {
732
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
733
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
734
+                'itemSource' => $share->getNode()->getId(),
735
+                'date' => $share->getExpirationDate(),
736
+                'uidOwner' => $share->getSharedBy(),
737
+            ]);
738
+        }
739
+
740
+        if ($share->getPassword() !== $originalShare->getPassword()) {
741
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
742
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
743
+                'itemSource' => $share->getNode()->getId(),
744
+                'uidOwner' => $share->getSharedBy(),
745
+                'token' => $share->getToken(),
746
+                'disabled' => is_null($share->getPassword()),
747
+            ]);
748
+        }
749
+
750
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
751
+            if ($this->userManager->userExists($share->getShareOwner())) {
752
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
753
+            } else {
754
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
755
+            }
756
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
757
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
758
+                'itemSource' => $share->getNode()->getId(),
759
+                'shareType' => $share->getShareType(),
760
+                'shareWith' => $share->getSharedWith(),
761
+                'uidOwner' => $share->getSharedBy(),
762
+                'permissions' => $share->getPermissions(),
763
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
764
+            ));
765
+        }
766
+
767
+        return $share;
768
+    }
769
+
770
+    /**
771
+     * Delete all the children of this share
772
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
773
+     *
774
+     * @param \OCP\Share\IShare $share
775
+     * @return \OCP\Share\IShare[] List of deleted shares
776
+     */
777
+    protected function deleteChildren(\OCP\Share\IShare $share) {
778
+        $deletedShares = [];
779
+
780
+        $provider = $this->factory->getProviderForType($share->getShareType());
781
+
782
+        foreach ($provider->getChildren($share) as $child) {
783
+            $deletedChildren = $this->deleteChildren($child);
784
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
785
+
786
+            $provider->delete($child);
787
+            $deletedShares[] = $child;
788
+        }
789
+
790
+        return $deletedShares;
791
+    }
792
+
793
+    /**
794
+     * Delete a share
795
+     *
796
+     * @param \OCP\Share\IShare $share
797
+     * @throws ShareNotFound
798
+     * @throws \InvalidArgumentException
799
+     */
800
+    public function deleteShare(\OCP\Share\IShare $share) {
801
+
802
+        try {
803
+            $share->getFullId();
804
+        } catch (\UnexpectedValueException $e) {
805
+            throw new \InvalidArgumentException('Share does not have a full id');
806
+        }
807
+
808
+        $formatHookParams = function(\OCP\Share\IShare $share) {
809
+            // Prepare hook
810
+            $shareType = $share->getShareType();
811
+            $sharedWith = '';
812
+            if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
813
+                $sharedWith = $share->getSharedWith();
814
+            } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
815
+                $sharedWith = $share->getSharedWith();
816
+            } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
817
+                $sharedWith = $share->getSharedWith();
818
+            }
819
+
820
+            $hookParams = [
821
+                'id'         => $share->getId(),
822
+                'itemType'   => $share->getNodeType(),
823
+                'itemSource' => $share->getNodeId(),
824
+                'shareType'  => $shareType,
825
+                'shareWith'  => $sharedWith,
826
+                'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
827
+                'uidOwner'   => $share->getSharedBy(),
828
+                'fileSource' => $share->getNodeId(),
829
+                'fileTarget' => $share->getTarget()
830
+            ];
831
+            return $hookParams;
832
+        };
833
+
834
+        $hookParams = $formatHookParams($share);
835
+
836
+        // Emit pre-hook
837
+        \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
838
+
839
+        // Get all children and delete them as well
840
+        $deletedShares = $this->deleteChildren($share);
841
+
842
+        // Do the actual delete
843
+        $provider = $this->factory->getProviderForType($share->getShareType());
844
+        $provider->delete($share);
845
+
846
+        // All the deleted shares caused by this delete
847
+        $deletedShares[] = $share;
848
+
849
+        //Format hook info
850
+        $formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
851
+            return $formatHookParams($share);
852
+        }, $deletedShares);
853
+
854
+        $hookParams['deletedShares'] = $formattedDeletedShares;
855
+
856
+        // Emit post hook
857
+        \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
858
+    }
859
+
860
+
861
+    /**
862
+     * Unshare a file as the recipient.
863
+     * This can be different from a regular delete for example when one of
864
+     * the users in a groups deletes that share. But the provider should
865
+     * handle this.
866
+     *
867
+     * @param \OCP\Share\IShare $share
868
+     * @param string $recipientId
869
+     */
870
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
871
+        list($providerId, ) = $this->splitFullId($share->getFullId());
872
+        $provider = $this->factory->getProvider($providerId);
873
+
874
+        $provider->deleteFromSelf($share, $recipientId);
875
+    }
876
+
877
+    /**
878
+     * @inheritdoc
879
+     */
880
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
881
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
882
+            throw new \InvalidArgumentException('Can\'t change target of link share');
883
+        }
884
+
885
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
886
+            throw new \InvalidArgumentException('Invalid recipient');
887
+        }
888
+
889
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
890
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
891
+            if (is_null($sharedWith)) {
892
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
893
+            }
894
+            $recipient = $this->userManager->get($recipientId);
895
+            if (!$sharedWith->inGroup($recipient)) {
896
+                throw new \InvalidArgumentException('Invalid recipient');
897
+            }
898
+        }
899
+
900
+        list($providerId, ) = $this->splitFullId($share->getFullId());
901
+        $provider = $this->factory->getProvider($providerId);
902
+
903
+        $provider->move($share, $recipientId);
904
+    }
905
+
906
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
907
+        $providers = $this->factory->getAllProviders();
908
+
909
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
910
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
911
+            foreach ($newShares as $fid => $data) {
912
+                if (!isset($shares[$fid])) {
913
+                    $shares[$fid] = [];
914
+                }
915
+
916
+                $shares[$fid] = array_merge($shares[$fid], $data);
917
+            }
918
+            return $shares;
919
+        }, []);
920
+    }
921
+
922
+    /**
923
+     * @inheritdoc
924
+     */
925
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
926
+        if ($path !== null &&
927
+                !($path instanceof \OCP\Files\File) &&
928
+                !($path instanceof \OCP\Files\Folder)) {
929
+            throw new \InvalidArgumentException('invalid path');
930
+        }
931
+
932
+        try {
933
+            $provider = $this->factory->getProviderForType($shareType);
934
+        } catch (ProviderException $e) {
935
+            return [];
936
+        }
937
+
938
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
939
+
940
+        /*
941 941
 		 * Work around so we don't return expired shares but still follow
942 942
 		 * proper pagination.
943 943
 		 */
944
-		if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
945
-			$shares2 = [];
946
-			$today = new \DateTime();
947
-
948
-			while(true) {
949
-				$added = 0;
950
-				foreach ($shares as $share) {
951
-					// Check if the share is expired and if so delete it
952
-					if ($share->getExpirationDate() !== null &&
953
-						$share->getExpirationDate() <= $today
954
-					) {
955
-						try {
956
-							$this->deleteShare($share);
957
-						} catch (NotFoundException $e) {
958
-							//Ignore since this basically means the share is deleted
959
-						}
960
-						continue;
961
-					}
962
-					$added++;
963
-					$shares2[] = $share;
964
-
965
-					if (count($shares2) === $limit) {
966
-						break;
967
-					}
968
-				}
969
-
970
-				if (count($shares2) === $limit) {
971
-					break;
972
-				}
973
-
974
-				// If there was no limit on the select we are done
975
-				if ($limit === -1) {
976
-					break;
977
-				}
978
-
979
-				$offset += $added;
980
-
981
-				// Fetch again $limit shares
982
-				$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
983
-
984
-				// No more shares means we are done
985
-				if (empty($shares)) {
986
-					break;
987
-				}
988
-			}
989
-
990
-			$shares = $shares2;
991
-		}
992
-
993
-		return $shares;
994
-	}
995
-
996
-	/**
997
-	 * @inheritdoc
998
-	 */
999
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1000
-		try {
1001
-			$provider = $this->factory->getProviderForType($shareType);
1002
-		} catch (ProviderException $e) {
1003
-			return [];
1004
-		}
1005
-
1006
-		return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1007
-	}
1008
-
1009
-	/**
1010
-	 * @inheritdoc
1011
-	 */
1012
-	public function getShareById($id, $recipient = null) {
1013
-		if ($id === null) {
1014
-			throw new ShareNotFound();
1015
-		}
1016
-
1017
-		list($providerId, $id) = $this->splitFullId($id);
1018
-
1019
-		try {
1020
-			$provider = $this->factory->getProvider($providerId);
1021
-		} catch (ProviderException $e) {
1022
-			throw new ShareNotFound();
1023
-		}
1024
-
1025
-		$share = $provider->getShareById($id, $recipient);
1026
-
1027
-		// Validate link shares expiration date
1028
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1029
-			$share->getExpirationDate() !== null &&
1030
-			$share->getExpirationDate() <= new \DateTime()) {
1031
-			$this->deleteShare($share);
1032
-			throw new ShareNotFound();
1033
-		}
1034
-
1035
-		return $share;
1036
-	}
1037
-
1038
-	/**
1039
-	 * Get all the shares for a given path
1040
-	 *
1041
-	 * @param \OCP\Files\Node $path
1042
-	 * @param int $page
1043
-	 * @param int $perPage
1044
-	 *
1045
-	 * @return Share[]
1046
-	 */
1047
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1048
-		return [];
1049
-	}
1050
-
1051
-	/**
1052
-	 * Get the share by token possible with password
1053
-	 *
1054
-	 * @param string $token
1055
-	 * @return Share
1056
-	 *
1057
-	 * @throws ShareNotFound
1058
-	 */
1059
-	public function getShareByToken($token) {
1060
-		$share = null;
1061
-		try {
1062
-			if($this->shareApiAllowLinks()) {
1063
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1064
-				$share = $provider->getShareByToken($token);
1065
-			}
1066
-		} catch (ProviderException $e) {
1067
-		} catch (ShareNotFound $e) {
1068
-		}
1069
-
1070
-
1071
-		// If it is not a link share try to fetch a federated share by token
1072
-		if ($share === null) {
1073
-			try {
1074
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1075
-				$share = $provider->getShareByToken($token);
1076
-			} catch (ProviderException $e) {
1077
-			} catch (ShareNotFound $e) {
1078
-			}
1079
-		}
1080
-
1081
-		// If it is not a link share try to fetch a mail share by token
1082
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1083
-			try {
1084
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1085
-				$share = $provider->getShareByToken($token);
1086
-			} catch (ProviderException $e) {
1087
-			} catch (ShareNotFound $e) {
1088
-			}
1089
-		}
1090
-
1091
-		if ($share === null) {
1092
-			throw new ShareNotFound();
1093
-		}
1094
-
1095
-		if ($share->getExpirationDate() !== null &&
1096
-			$share->getExpirationDate() <= new \DateTime()) {
1097
-			$this->deleteShare($share);
1098
-			throw new ShareNotFound();
1099
-		}
1100
-
1101
-		/*
944
+        if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
945
+            $shares2 = [];
946
+            $today = new \DateTime();
947
+
948
+            while(true) {
949
+                $added = 0;
950
+                foreach ($shares as $share) {
951
+                    // Check if the share is expired and if so delete it
952
+                    if ($share->getExpirationDate() !== null &&
953
+                        $share->getExpirationDate() <= $today
954
+                    ) {
955
+                        try {
956
+                            $this->deleteShare($share);
957
+                        } catch (NotFoundException $e) {
958
+                            //Ignore since this basically means the share is deleted
959
+                        }
960
+                        continue;
961
+                    }
962
+                    $added++;
963
+                    $shares2[] = $share;
964
+
965
+                    if (count($shares2) === $limit) {
966
+                        break;
967
+                    }
968
+                }
969
+
970
+                if (count($shares2) === $limit) {
971
+                    break;
972
+                }
973
+
974
+                // If there was no limit on the select we are done
975
+                if ($limit === -1) {
976
+                    break;
977
+                }
978
+
979
+                $offset += $added;
980
+
981
+                // Fetch again $limit shares
982
+                $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
983
+
984
+                // No more shares means we are done
985
+                if (empty($shares)) {
986
+                    break;
987
+                }
988
+            }
989
+
990
+            $shares = $shares2;
991
+        }
992
+
993
+        return $shares;
994
+    }
995
+
996
+    /**
997
+     * @inheritdoc
998
+     */
999
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1000
+        try {
1001
+            $provider = $this->factory->getProviderForType($shareType);
1002
+        } catch (ProviderException $e) {
1003
+            return [];
1004
+        }
1005
+
1006
+        return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1007
+    }
1008
+
1009
+    /**
1010
+     * @inheritdoc
1011
+     */
1012
+    public function getShareById($id, $recipient = null) {
1013
+        if ($id === null) {
1014
+            throw new ShareNotFound();
1015
+        }
1016
+
1017
+        list($providerId, $id) = $this->splitFullId($id);
1018
+
1019
+        try {
1020
+            $provider = $this->factory->getProvider($providerId);
1021
+        } catch (ProviderException $e) {
1022
+            throw new ShareNotFound();
1023
+        }
1024
+
1025
+        $share = $provider->getShareById($id, $recipient);
1026
+
1027
+        // Validate link shares expiration date
1028
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1029
+            $share->getExpirationDate() !== null &&
1030
+            $share->getExpirationDate() <= new \DateTime()) {
1031
+            $this->deleteShare($share);
1032
+            throw new ShareNotFound();
1033
+        }
1034
+
1035
+        return $share;
1036
+    }
1037
+
1038
+    /**
1039
+     * Get all the shares for a given path
1040
+     *
1041
+     * @param \OCP\Files\Node $path
1042
+     * @param int $page
1043
+     * @param int $perPage
1044
+     *
1045
+     * @return Share[]
1046
+     */
1047
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1048
+        return [];
1049
+    }
1050
+
1051
+    /**
1052
+     * Get the share by token possible with password
1053
+     *
1054
+     * @param string $token
1055
+     * @return Share
1056
+     *
1057
+     * @throws ShareNotFound
1058
+     */
1059
+    public function getShareByToken($token) {
1060
+        $share = null;
1061
+        try {
1062
+            if($this->shareApiAllowLinks()) {
1063
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1064
+                $share = $provider->getShareByToken($token);
1065
+            }
1066
+        } catch (ProviderException $e) {
1067
+        } catch (ShareNotFound $e) {
1068
+        }
1069
+
1070
+
1071
+        // If it is not a link share try to fetch a federated share by token
1072
+        if ($share === null) {
1073
+            try {
1074
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1075
+                $share = $provider->getShareByToken($token);
1076
+            } catch (ProviderException $e) {
1077
+            } catch (ShareNotFound $e) {
1078
+            }
1079
+        }
1080
+
1081
+        // If it is not a link share try to fetch a mail share by token
1082
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1083
+            try {
1084
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1085
+                $share = $provider->getShareByToken($token);
1086
+            } catch (ProviderException $e) {
1087
+            } catch (ShareNotFound $e) {
1088
+            }
1089
+        }
1090
+
1091
+        if ($share === null) {
1092
+            throw new ShareNotFound();
1093
+        }
1094
+
1095
+        if ($share->getExpirationDate() !== null &&
1096
+            $share->getExpirationDate() <= new \DateTime()) {
1097
+            $this->deleteShare($share);
1098
+            throw new ShareNotFound();
1099
+        }
1100
+
1101
+        /*
1102 1102
 		 * Reduce the permissions for link shares if public upload is not enabled
1103 1103
 		 */
1104
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1105
-			!$this->shareApiLinkAllowPublicUpload()) {
1106
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1107
-		}
1108
-
1109
-		return $share;
1110
-	}
1111
-
1112
-	/**
1113
-	 * Verify the password of a public share
1114
-	 *
1115
-	 * @param \OCP\Share\IShare $share
1116
-	 * @param string $password
1117
-	 * @return bool
1118
-	 */
1119
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1120
-		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
1121
-			//TODO maybe exception?
1122
-			return false;
1123
-		}
1124
-
1125
-		if ($password === null || $share->getPassword() === null) {
1126
-			return false;
1127
-		}
1128
-
1129
-		$newHash = '';
1130
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1131
-			return false;
1132
-		}
1133
-
1134
-		if (!empty($newHash)) {
1135
-			$share->setPassword($newHash);
1136
-			$provider = $this->factory->getProviderForType($share->getShareType());
1137
-			$provider->update($share);
1138
-		}
1139
-
1140
-		return true;
1141
-	}
1142
-
1143
-	/**
1144
-	 * @inheritdoc
1145
-	 */
1146
-	public function userDeleted($uid) {
1147
-		$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];
1148
-
1149
-		foreach ($types as $type) {
1150
-			try {
1151
-				$provider = $this->factory->getProviderForType($type);
1152
-			} catch (ProviderException $e) {
1153
-				continue;
1154
-			}
1155
-			$provider->userDeleted($uid, $type);
1156
-		}
1157
-	}
1158
-
1159
-	/**
1160
-	 * @inheritdoc
1161
-	 */
1162
-	public function groupDeleted($gid) {
1163
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1164
-		$provider->groupDeleted($gid);
1165
-	}
1166
-
1167
-	/**
1168
-	 * @inheritdoc
1169
-	 */
1170
-	public function userDeletedFromGroup($uid, $gid) {
1171
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1172
-		$provider->userDeletedFromGroup($uid, $gid);
1173
-	}
1174
-
1175
-	/**
1176
-	 * Get access list to a path. This means
1177
-	 * all the users and groups that can access a given path.
1178
-	 *
1179
-	 * Consider:
1180
-	 * -root
1181
-	 * |-folder1
1182
-	 *  |-folder2
1183
-	 *   |-fileA
1184
-	 *
1185
-	 * fileA is shared with user1
1186
-	 * folder2 is shared with group2
1187
-	 * folder1 is shared with user2
1188
-	 *
1189
-	 * Then the access list will to '/folder1/folder2/fileA' is:
1190
-	 * [
1191
-	 * 	'users' => ['user1', 'user2'],
1192
-	 *  'groups' => ['group2']
1193
-	 * ]
1194
-	 *
1195
-	 * This is required for encryption
1196
-	 *
1197
-	 * @param \OCP\Files\Node $path
1198
-	 */
1199
-	public function getAccessList(\OCP\Files\Node $path) {
1200
-	}
1201
-
1202
-	/**
1203
-	 * Create a new share
1204
-	 * @return \OCP\Share\IShare;
1205
-	 */
1206
-	public function newShare() {
1207
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1208
-	}
1209
-
1210
-	/**
1211
-	 * Is the share API enabled
1212
-	 *
1213
-	 * @return bool
1214
-	 */
1215
-	public function shareApiEnabled() {
1216
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1217
-	}
1218
-
1219
-	/**
1220
-	 * Is public link sharing enabled
1221
-	 *
1222
-	 * @return bool
1223
-	 */
1224
-	public function shareApiAllowLinks() {
1225
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1226
-	}
1227
-
1228
-	/**
1229
-	 * Is password on public link requires
1230
-	 *
1231
-	 * @return bool
1232
-	 */
1233
-	public function shareApiLinkEnforcePassword() {
1234
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1235
-	}
1236
-
1237
-	/**
1238
-	 * Is default expire date enabled
1239
-	 *
1240
-	 * @return bool
1241
-	 */
1242
-	public function shareApiLinkDefaultExpireDate() {
1243
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1244
-	}
1245
-
1246
-	/**
1247
-	 * Is default expire date enforced
1248
-	 *`
1249
-	 * @return bool
1250
-	 */
1251
-	public function shareApiLinkDefaultExpireDateEnforced() {
1252
-		return $this->shareApiLinkDefaultExpireDate() &&
1253
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1254
-	}
1255
-
1256
-	/**
1257
-	 * Number of default expire days
1258
-	 *shareApiLinkAllowPublicUpload
1259
-	 * @return int
1260
-	 */
1261
-	public function shareApiLinkDefaultExpireDays() {
1262
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1263
-	}
1264
-
1265
-	/**
1266
-	 * Allow public upload on link shares
1267
-	 *
1268
-	 * @return bool
1269
-	 */
1270
-	public function shareApiLinkAllowPublicUpload() {
1271
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1272
-	}
1273
-
1274
-	/**
1275
-	 * check if user can only share with group members
1276
-	 * @return bool
1277
-	 */
1278
-	public function shareWithGroupMembersOnly() {
1279
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1280
-	}
1281
-
1282
-	/**
1283
-	 * Check if users can share with groups
1284
-	 * @return bool
1285
-	 */
1286
-	public function allowGroupSharing() {
1287
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1288
-	}
1289
-
1290
-	/**
1291
-	 * Copied from \OC_Util::isSharingDisabledForUser
1292
-	 *
1293
-	 * TODO: Deprecate fuction from OC_Util
1294
-	 *
1295
-	 * @param string $userId
1296
-	 * @return bool
1297
-	 */
1298
-	public function sharingDisabledForUser($userId) {
1299
-		if ($userId === null) {
1300
-			return false;
1301
-		}
1302
-
1303
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1304
-			return $this->sharingDisabledForUsersCache[$userId];
1305
-		}
1306
-
1307
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1308
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1309
-			$excludedGroups = json_decode($groupsList);
1310
-			if (is_null($excludedGroups)) {
1311
-				$excludedGroups = explode(',', $groupsList);
1312
-				$newValue = json_encode($excludedGroups);
1313
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1314
-			}
1315
-			$user = $this->userManager->get($userId);
1316
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1317
-			if (!empty($usersGroups)) {
1318
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1319
-				// if the user is only in groups which are disabled for sharing then
1320
-				// sharing is also disabled for the user
1321
-				if (empty($remainingGroups)) {
1322
-					$this->sharingDisabledForUsersCache[$userId] = true;
1323
-					return true;
1324
-				}
1325
-			}
1326
-		}
1327
-
1328
-		$this->sharingDisabledForUsersCache[$userId] = false;
1329
-		return false;
1330
-	}
1331
-
1332
-	/**
1333
-	 * @inheritdoc
1334
-	 */
1335
-	public function outgoingServer2ServerSharesAllowed() {
1336
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1337
-	}
1338
-
1339
-	/**
1340
-	 * @inheritdoc
1341
-	 */
1342
-	public function shareProviderExists($shareType) {
1343
-		try {
1344
-			$this->factory->getProviderForType($shareType);
1345
-		} catch (ProviderException $e) {
1346
-			return false;
1347
-		}
1348
-
1349
-		return true;
1350
-	}
1104
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1105
+            !$this->shareApiLinkAllowPublicUpload()) {
1106
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1107
+        }
1108
+
1109
+        return $share;
1110
+    }
1111
+
1112
+    /**
1113
+     * Verify the password of a public share
1114
+     *
1115
+     * @param \OCP\Share\IShare $share
1116
+     * @param string $password
1117
+     * @return bool
1118
+     */
1119
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1120
+        if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
1121
+            //TODO maybe exception?
1122
+            return false;
1123
+        }
1124
+
1125
+        if ($password === null || $share->getPassword() === null) {
1126
+            return false;
1127
+        }
1128
+
1129
+        $newHash = '';
1130
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1131
+            return false;
1132
+        }
1133
+
1134
+        if (!empty($newHash)) {
1135
+            $share->setPassword($newHash);
1136
+            $provider = $this->factory->getProviderForType($share->getShareType());
1137
+            $provider->update($share);
1138
+        }
1139
+
1140
+        return true;
1141
+    }
1142
+
1143
+    /**
1144
+     * @inheritdoc
1145
+     */
1146
+    public function userDeleted($uid) {
1147
+        $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];
1148
+
1149
+        foreach ($types as $type) {
1150
+            try {
1151
+                $provider = $this->factory->getProviderForType($type);
1152
+            } catch (ProviderException $e) {
1153
+                continue;
1154
+            }
1155
+            $provider->userDeleted($uid, $type);
1156
+        }
1157
+    }
1158
+
1159
+    /**
1160
+     * @inheritdoc
1161
+     */
1162
+    public function groupDeleted($gid) {
1163
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1164
+        $provider->groupDeleted($gid);
1165
+    }
1166
+
1167
+    /**
1168
+     * @inheritdoc
1169
+     */
1170
+    public function userDeletedFromGroup($uid, $gid) {
1171
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1172
+        $provider->userDeletedFromGroup($uid, $gid);
1173
+    }
1174
+
1175
+    /**
1176
+     * Get access list to a path. This means
1177
+     * all the users and groups that can access a given path.
1178
+     *
1179
+     * Consider:
1180
+     * -root
1181
+     * |-folder1
1182
+     *  |-folder2
1183
+     *   |-fileA
1184
+     *
1185
+     * fileA is shared with user1
1186
+     * folder2 is shared with group2
1187
+     * folder1 is shared with user2
1188
+     *
1189
+     * Then the access list will to '/folder1/folder2/fileA' is:
1190
+     * [
1191
+     * 	'users' => ['user1', 'user2'],
1192
+     *  'groups' => ['group2']
1193
+     * ]
1194
+     *
1195
+     * This is required for encryption
1196
+     *
1197
+     * @param \OCP\Files\Node $path
1198
+     */
1199
+    public function getAccessList(\OCP\Files\Node $path) {
1200
+    }
1201
+
1202
+    /**
1203
+     * Create a new share
1204
+     * @return \OCP\Share\IShare;
1205
+     */
1206
+    public function newShare() {
1207
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1208
+    }
1209
+
1210
+    /**
1211
+     * Is the share API enabled
1212
+     *
1213
+     * @return bool
1214
+     */
1215
+    public function shareApiEnabled() {
1216
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1217
+    }
1218
+
1219
+    /**
1220
+     * Is public link sharing enabled
1221
+     *
1222
+     * @return bool
1223
+     */
1224
+    public function shareApiAllowLinks() {
1225
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1226
+    }
1227
+
1228
+    /**
1229
+     * Is password on public link requires
1230
+     *
1231
+     * @return bool
1232
+     */
1233
+    public function shareApiLinkEnforcePassword() {
1234
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1235
+    }
1236
+
1237
+    /**
1238
+     * Is default expire date enabled
1239
+     *
1240
+     * @return bool
1241
+     */
1242
+    public function shareApiLinkDefaultExpireDate() {
1243
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1244
+    }
1245
+
1246
+    /**
1247
+     * Is default expire date enforced
1248
+     *`
1249
+     * @return bool
1250
+     */
1251
+    public function shareApiLinkDefaultExpireDateEnforced() {
1252
+        return $this->shareApiLinkDefaultExpireDate() &&
1253
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1254
+    }
1255
+
1256
+    /**
1257
+     * Number of default expire days
1258
+     *shareApiLinkAllowPublicUpload
1259
+     * @return int
1260
+     */
1261
+    public function shareApiLinkDefaultExpireDays() {
1262
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1263
+    }
1264
+
1265
+    /**
1266
+     * Allow public upload on link shares
1267
+     *
1268
+     * @return bool
1269
+     */
1270
+    public function shareApiLinkAllowPublicUpload() {
1271
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1272
+    }
1273
+
1274
+    /**
1275
+     * check if user can only share with group members
1276
+     * @return bool
1277
+     */
1278
+    public function shareWithGroupMembersOnly() {
1279
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1280
+    }
1281
+
1282
+    /**
1283
+     * Check if users can share with groups
1284
+     * @return bool
1285
+     */
1286
+    public function allowGroupSharing() {
1287
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1288
+    }
1289
+
1290
+    /**
1291
+     * Copied from \OC_Util::isSharingDisabledForUser
1292
+     *
1293
+     * TODO: Deprecate fuction from OC_Util
1294
+     *
1295
+     * @param string $userId
1296
+     * @return bool
1297
+     */
1298
+    public function sharingDisabledForUser($userId) {
1299
+        if ($userId === null) {
1300
+            return false;
1301
+        }
1302
+
1303
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1304
+            return $this->sharingDisabledForUsersCache[$userId];
1305
+        }
1306
+
1307
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1308
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1309
+            $excludedGroups = json_decode($groupsList);
1310
+            if (is_null($excludedGroups)) {
1311
+                $excludedGroups = explode(',', $groupsList);
1312
+                $newValue = json_encode($excludedGroups);
1313
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1314
+            }
1315
+            $user = $this->userManager->get($userId);
1316
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1317
+            if (!empty($usersGroups)) {
1318
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1319
+                // if the user is only in groups which are disabled for sharing then
1320
+                // sharing is also disabled for the user
1321
+                if (empty($remainingGroups)) {
1322
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1323
+                    return true;
1324
+                }
1325
+            }
1326
+        }
1327
+
1328
+        $this->sharingDisabledForUsersCache[$userId] = false;
1329
+        return false;
1330
+    }
1331
+
1332
+    /**
1333
+     * @inheritdoc
1334
+     */
1335
+    public function outgoingServer2ServerSharesAllowed() {
1336
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1337
+    }
1338
+
1339
+    /**
1340
+     * @inheritdoc
1341
+     */
1342
+    public function shareProviderExists($shareType) {
1343
+        try {
1344
+            $this->factory->getProviderForType($shareType);
1345
+        } catch (ProviderException $e) {
1346
+            return false;
1347
+        }
1348
+
1349
+        return true;
1350
+    }
1351 1351
 
1352 1352
 }
Please login to merge, or discard this patch.
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.
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.
apps/files_sharing/lib/Controller/ShareAPIController.php 1 patch
Indentation   +807 added lines, -807 removed lines patch added patch discarded remove patch
@@ -51,820 +51,820 @@
 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
-		}
196
-
197
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
198
-
199
-		return $result;
200
-	}
201
-
202
-	/**
203
-	 * Check if one of the users address books knows the exact property, if
204
-	 * yes we return the full name.
205
-	 *
206
-	 * @param string $query
207
-	 * @param string $property
208
-	 * @return string
209
-	 */
210
-	private function getDisplayNameFromAddressBook($query, $property) {
211
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
212
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
213
-		foreach ($result as $r) {
214
-			foreach($r[$property] as $value) {
215
-				if ($value === $query) {
216
-					return $r['FN'];
217
-				}
218
-			}
219
-		}
220
-
221
-		return $query;
222
-	}
223
-
224
-	/**
225
-	 * Get a specific share by id
226
-	 *
227
-	 * @NoAdminRequired
228
-	 *
229
-	 * @param string $id
230
-	 * @return DataResponse
231
-	 * @throws OCSNotFoundException
232
-	 */
233
-	public function getShare($id) {
234
-		try {
235
-			$share = $this->getShareById($id);
236
-		} catch (ShareNotFound $e) {
237
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
238
-		}
239
-
240
-		if ($this->canAccessShare($share)) {
241
-			try {
242
-				$share = $this->formatShare($share);
243
-				return new DataResponse([$share]);
244
-			} catch (NotFoundException $e) {
245
-				//Fall trough
246
-			}
247
-		}
248
-
249
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
250
-	}
251
-
252
-	/**
253
-	 * Delete a share
254
-	 *
255
-	 * @NoAdminRequired
256
-	 *
257
-	 * @param string $id
258
-	 * @return DataResponse
259
-	 * @throws OCSNotFoundException
260
-	 */
261
-	public function deleteShare($id) {
262
-		try {
263
-			$share = $this->getShareById($id);
264
-		} catch (ShareNotFound $e) {
265
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
266
-		}
267
-
268
-		try {
269
-			$this->lock($share->getNode());
270
-		} catch (LockedException $e) {
271
-			throw new OCSNotFoundException($this->l->t('could not delete share'));
272
-		}
273
-
274
-		if (!$this->canAccessShare($share)) {
275
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
276
-		}
277
-
278
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
279
-			$share->getShareOwner() !== $this->currentUser &&
280
-			$share->getSharedBy() !== $this->currentUser) {
281
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
282
-		} else {
283
-			$this->shareManager->deleteShare($share);
284
-		}
285
-
286
-		return new DataResponse();
287
-	}
288
-
289
-	/**
290
-	 * @NoAdminRequired
291
-	 *
292
-	 * @param string $path
293
-	 * @param int $permissions
294
-	 * @param int $shareType
295
-	 * @param string $shareWith
296
-	 * @param string $publicUpload
297
-	 * @param string $password
298
-	 * @param string $expireDate
299
-	 *
300
-	 * @return DataResponse
301
-	 * @throws OCSNotFoundException
302
-	 * @throws OCSForbiddenException
303
-	 * @throws OCSBadRequestException
304
-	 * @throws OCSException
305
-	 */
306
-	public function createShare(
307
-		$path = null,
308
-		$permissions = \OCP\Constants::PERMISSION_ALL,
309
-		$shareType = -1,
310
-		$shareWith = null,
311
-		$publicUpload = 'false',
312
-		$password = '',
313
-		$expireDate = ''
314
-	) {
315
-		$share = $this->shareManager->newShare();
316
-
317
-		// Verify path
318
-		if ($path === null) {
319
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
320
-		}
321
-
322
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
323
-		try {
324
-			$path = $userFolder->get($path);
325
-		} catch (NotFoundException $e) {
326
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
327
-		}
328
-
329
-		$share->setNode($path);
330
-
331
-		try {
332
-			$this->lock($share->getNode());
333
-		} catch (LockedException $e) {
334
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
335
-		}
336
-
337
-		if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
338
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
339
-		}
340
-
341
-		// Shares always require read permissions
342
-		$permissions |= \OCP\Constants::PERMISSION_READ;
343
-
344
-		if ($path instanceof \OCP\Files\File) {
345
-			// Single file shares should never have delete or create permissions
346
-			$permissions &= ~\OCP\Constants::PERMISSION_DELETE;
347
-			$permissions &= ~\OCP\Constants::PERMISSION_CREATE;
348
-		}
349
-
350
-		/*
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
+        }
196
+
197
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
198
+
199
+        return $result;
200
+    }
201
+
202
+    /**
203
+     * Check if one of the users address books knows the exact property, if
204
+     * yes we return the full name.
205
+     *
206
+     * @param string $query
207
+     * @param string $property
208
+     * @return string
209
+     */
210
+    private function getDisplayNameFromAddressBook($query, $property) {
211
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
212
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
213
+        foreach ($result as $r) {
214
+            foreach($r[$property] as $value) {
215
+                if ($value === $query) {
216
+                    return $r['FN'];
217
+                }
218
+            }
219
+        }
220
+
221
+        return $query;
222
+    }
223
+
224
+    /**
225
+     * Get a specific share by id
226
+     *
227
+     * @NoAdminRequired
228
+     *
229
+     * @param string $id
230
+     * @return DataResponse
231
+     * @throws OCSNotFoundException
232
+     */
233
+    public function getShare($id) {
234
+        try {
235
+            $share = $this->getShareById($id);
236
+        } catch (ShareNotFound $e) {
237
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
238
+        }
239
+
240
+        if ($this->canAccessShare($share)) {
241
+            try {
242
+                $share = $this->formatShare($share);
243
+                return new DataResponse([$share]);
244
+            } catch (NotFoundException $e) {
245
+                //Fall trough
246
+            }
247
+        }
248
+
249
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
250
+    }
251
+
252
+    /**
253
+     * Delete a share
254
+     *
255
+     * @NoAdminRequired
256
+     *
257
+     * @param string $id
258
+     * @return DataResponse
259
+     * @throws OCSNotFoundException
260
+     */
261
+    public function deleteShare($id) {
262
+        try {
263
+            $share = $this->getShareById($id);
264
+        } catch (ShareNotFound $e) {
265
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
266
+        }
267
+
268
+        try {
269
+            $this->lock($share->getNode());
270
+        } catch (LockedException $e) {
271
+            throw new OCSNotFoundException($this->l->t('could not delete share'));
272
+        }
273
+
274
+        if (!$this->canAccessShare($share)) {
275
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
276
+        }
277
+
278
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
279
+            $share->getShareOwner() !== $this->currentUser &&
280
+            $share->getSharedBy() !== $this->currentUser) {
281
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
282
+        } else {
283
+            $this->shareManager->deleteShare($share);
284
+        }
285
+
286
+        return new DataResponse();
287
+    }
288
+
289
+    /**
290
+     * @NoAdminRequired
291
+     *
292
+     * @param string $path
293
+     * @param int $permissions
294
+     * @param int $shareType
295
+     * @param string $shareWith
296
+     * @param string $publicUpload
297
+     * @param string $password
298
+     * @param string $expireDate
299
+     *
300
+     * @return DataResponse
301
+     * @throws OCSNotFoundException
302
+     * @throws OCSForbiddenException
303
+     * @throws OCSBadRequestException
304
+     * @throws OCSException
305
+     */
306
+    public function createShare(
307
+        $path = null,
308
+        $permissions = \OCP\Constants::PERMISSION_ALL,
309
+        $shareType = -1,
310
+        $shareWith = null,
311
+        $publicUpload = 'false',
312
+        $password = '',
313
+        $expireDate = ''
314
+    ) {
315
+        $share = $this->shareManager->newShare();
316
+
317
+        // Verify path
318
+        if ($path === null) {
319
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
320
+        }
321
+
322
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
323
+        try {
324
+            $path = $userFolder->get($path);
325
+        } catch (NotFoundException $e) {
326
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
327
+        }
328
+
329
+        $share->setNode($path);
330
+
331
+        try {
332
+            $this->lock($share->getNode());
333
+        } catch (LockedException $e) {
334
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
335
+        }
336
+
337
+        if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
338
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
339
+        }
340
+
341
+        // Shares always require read permissions
342
+        $permissions |= \OCP\Constants::PERMISSION_READ;
343
+
344
+        if ($path instanceof \OCP\Files\File) {
345
+            // Single file shares should never have delete or create permissions
346
+            $permissions &= ~\OCP\Constants::PERMISSION_DELETE;
347
+            $permissions &= ~\OCP\Constants::PERMISSION_CREATE;
348
+        }
349
+
350
+        /*
351 351
 		 * Hack for https://github.com/owncloud/core/issues/22587
352 352
 		 * We check the permissions via webdav. But the permissions of the mount point
353 353
 		 * do not equal the share permissions. Here we fix that for federated mounts.
354 354
 		 */
355
-		if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
356
-			$permissions &= ~($permissions & ~$path->getPermissions());
357
-		}
358
-
359
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
360
-			// Valid user is required to share
361
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
362
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
363
-			}
364
-			$share->setSharedWith($shareWith);
365
-			$share->setPermissions($permissions);
366
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
367
-			if (!$this->shareManager->allowGroupSharing()) {
368
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
369
-			}
370
-
371
-			// Valid group is required to share
372
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
373
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
374
-			}
375
-			$share->setSharedWith($shareWith);
376
-			$share->setPermissions($permissions);
377
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
378
-			//Can we even share links?
379
-			if (!$this->shareManager->shareApiAllowLinks()) {
380
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
381
-			}
382
-
383
-			/*
355
+        if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
356
+            $permissions &= ~($permissions & ~$path->getPermissions());
357
+        }
358
+
359
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
360
+            // Valid user is required to share
361
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
362
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
363
+            }
364
+            $share->setSharedWith($shareWith);
365
+            $share->setPermissions($permissions);
366
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
367
+            if (!$this->shareManager->allowGroupSharing()) {
368
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
369
+            }
370
+
371
+            // Valid group is required to share
372
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
373
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
374
+            }
375
+            $share->setSharedWith($shareWith);
376
+            $share->setPermissions($permissions);
377
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
378
+            //Can we even share links?
379
+            if (!$this->shareManager->shareApiAllowLinks()) {
380
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
381
+            }
382
+
383
+            /*
384 384
 			 * For now we only allow 1 link share.
385 385
 			 * Return the existing link share if this is a duplicate
386 386
 			 */
387
-			$existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
388
-			if (!empty($existingShares)) {
389
-				return new DataResponse($this->formatShare($existingShares[0]));
390
-			}
391
-
392
-			if ($publicUpload === 'true') {
393
-				// Check if public upload is allowed
394
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
395
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
396
-				}
397
-
398
-				// Public upload can only be set for folders
399
-				if ($path instanceof \OCP\Files\File) {
400
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
401
-				}
402
-
403
-				$share->setPermissions(
404
-					\OCP\Constants::PERMISSION_READ |
405
-					\OCP\Constants::PERMISSION_CREATE |
406
-					\OCP\Constants::PERMISSION_UPDATE |
407
-					\OCP\Constants::PERMISSION_DELETE
408
-				);
409
-			} else {
410
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
411
-			}
412
-
413
-			// Set password
414
-			if ($password !== '') {
415
-				$share->setPassword($password);
416
-			}
417
-
418
-			//Expire date
419
-			if ($expireDate !== '') {
420
-				try {
421
-					$expireDate = $this->parseDate($expireDate);
422
-					$share->setExpirationDate($expireDate);
423
-				} catch (\Exception $e) {
424
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
425
-				}
426
-			}
427
-
428
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
429
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
430
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
431
-			}
432
-
433
-			$share->setSharedWith($shareWith);
434
-			$share->setPermissions($permissions);
435
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
436
-			if ($share->getNodeType() === 'file') {
437
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
438
-			} else {
439
-				$share->setPermissions(
440
-					\OCP\Constants::PERMISSION_READ |
441
-					\OCP\Constants::PERMISSION_CREATE |
442
-					\OCP\Constants::PERMISSION_UPDATE |
443
-					\OCP\Constants::PERMISSION_DELETE);
444
-			}
445
-			$share->setSharedWith($shareWith);
446
-		} else {
447
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
448
-		}
449
-
450
-		$share->setShareType($shareType);
451
-		$share->setSharedBy($this->currentUser);
452
-
453
-		try {
454
-			$share = $this->shareManager->createShare($share);
455
-		} catch (GenericShareException $e) {
456
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
457
-			throw new OCSException($e->getHint(), $code);
458
-		} catch (\Exception $e) {
459
-			throw new OCSForbiddenException($e->getMessage());
460
-		}
461
-
462
-		$output = $this->formatShare($share);
463
-
464
-		return new DataResponse($output);
465
-	}
466
-
467
-	/**
468
-	 * @param \OCP\Files\File|\OCP\Files\Folder $node
469
-	 * @return DataResponse
470
-	 */
471
-	private function getSharedWithMe($node = null) {
472
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
473
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
474
-
475
-		$shares = array_merge($userShares, $groupShares);
476
-
477
-		$shares = array_filter($shares, function (IShare $share) {
478
-			return $share->getShareOwner() !== $this->currentUser;
479
-		});
480
-
481
-		$formatted = [];
482
-		foreach ($shares as $share) {
483
-			if ($this->canAccessShare($share)) {
484
-				try {
485
-					$formatted[] = $this->formatShare($share);
486
-				} catch (NotFoundException $e) {
487
-					// Ignore this share
488
-				}
489
-			}
490
-		}
491
-
492
-		return new DataResponse($formatted);
493
-	}
494
-
495
-	/**
496
-	 * @param \OCP\Files\Folder $folder
497
-	 * @return DataResponse
498
-	 * @throws OCSBadRequestException
499
-	 */
500
-	private function getSharesInDir($folder) {
501
-		if (!($folder instanceof \OCP\Files\Folder)) {
502
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
503
-		}
504
-
505
-		$nodes = $folder->getDirectoryListing();
506
-		/** @var \OCP\Share\IShare[] $shares */
507
-		$shares = [];
508
-		foreach ($nodes as $node) {
509
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
510
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
511
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
512
-			if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
513
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
514
-			}
515
-			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
516
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
517
-			}
518
-		}
519
-
520
-		$formatted = [];
521
-		foreach ($shares as $share) {
522
-			try {
523
-				$formatted[] = $this->formatShare($share);
524
-			} catch (NotFoundException $e) {
525
-				//Ignore this share
526
-			}
527
-		}
528
-
529
-		return new DataResponse($formatted);
530
-	}
531
-
532
-	/**
533
-	 * The getShares function.
534
-	 *
535
-	 * @NoAdminRequired
536
-	 *
537
-	 * @param string $shared_with_me
538
-	 * @param string $reshares
539
-	 * @param string $subfiles
540
-	 * @param string $path
541
-	 *
542
-	 * - Get shares by the current user
543
-	 * - Get shares by the current user and reshares (?reshares=true)
544
-	 * - Get shares with the current user (?shared_with_me=true)
545
-	 * - Get shares for a specific path (?path=...)
546
-	 * - Get all shares in a folder (?subfiles=true&path=..)
547
-	 *
548
-	 * @return DataResponse
549
-	 * @throws OCSNotFoundException
550
-	 */
551
-	public function getShares(
552
-		$shared_with_me = 'false',
553
-		$reshares = 'false',
554
-		$subfiles = 'false',
555
-		$path = null
556
-	) {
557
-
558
-		if ($path !== null) {
559
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
560
-			try {
561
-				$path = $userFolder->get($path);
562
-				$this->lock($path);
563
-			} catch (\OCP\Files\NotFoundException $e) {
564
-				throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
565
-			} catch (LockedException $e) {
566
-				throw new OCSNotFoundException($this->l->t('Could not lock path'));
567
-			}
568
-		}
569
-
570
-		if ($shared_with_me === 'true') {
571
-			$result = $this->getSharedWithMe($path);
572
-			return $result;
573
-		}
574
-
575
-		if ($subfiles === 'true') {
576
-			$result = $this->getSharesInDir($path);
577
-			return $result;
578
-		}
579
-
580
-		if ($reshares === 'true') {
581
-			$reshares = true;
582
-		} else {
583
-			$reshares = false;
584
-		}
585
-
586
-		// Get all shares
587
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
588
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
589
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
590
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
591
-			$mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
592
-		} else {
593
-			$mailShares = [];
594
-		}
595
-		$shares = array_merge($userShares, $groupShares, $linkShares, $mailShares);
596
-
597
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
598
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
599
-			$shares = array_merge($shares, $federatedShares);
600
-		}
601
-
602
-		$formatted = [];
603
-		foreach ($shares as $share) {
604
-			try {
605
-				$formatted[] = $this->formatShare($share, $path);
606
-			} catch (NotFoundException $e) {
607
-				//Ignore share
608
-			}
609
-		}
610
-
611
-		return new DataResponse($formatted);
612
-	}
613
-
614
-	/**
615
-	 * @NoAdminRequired
616
-	 *
617
-	 * @param int $id
618
-	 * @param int $permissions
619
-	 * @param string $password
620
-	 * @param string $publicUpload
621
-	 * @param string $expireDate
622
-	 * @return DataResponse
623
-	 * @throws OCSNotFoundException
624
-	 * @throws OCSBadRequestException
625
-	 * @throws OCSForbiddenException
626
-	 */
627
-	public function updateShare(
628
-		$id,
629
-		$permissions = null,
630
-		$password = null,
631
-		$publicUpload = null,
632
-		$expireDate = null
633
-	) {
634
-		try {
635
-			$share = $this->getShareById($id);
636
-		} catch (ShareNotFound $e) {
637
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
638
-		}
639
-
640
-		$this->lock($share->getNode());
641
-
642
-		if (!$this->canAccessShare($share, false)) {
643
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
644
-		}
645
-
646
-		/*
387
+            $existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
388
+            if (!empty($existingShares)) {
389
+                return new DataResponse($this->formatShare($existingShares[0]));
390
+            }
391
+
392
+            if ($publicUpload === 'true') {
393
+                // Check if public upload is allowed
394
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
395
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
396
+                }
397
+
398
+                // Public upload can only be set for folders
399
+                if ($path instanceof \OCP\Files\File) {
400
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
401
+                }
402
+
403
+                $share->setPermissions(
404
+                    \OCP\Constants::PERMISSION_READ |
405
+                    \OCP\Constants::PERMISSION_CREATE |
406
+                    \OCP\Constants::PERMISSION_UPDATE |
407
+                    \OCP\Constants::PERMISSION_DELETE
408
+                );
409
+            } else {
410
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
411
+            }
412
+
413
+            // Set password
414
+            if ($password !== '') {
415
+                $share->setPassword($password);
416
+            }
417
+
418
+            //Expire date
419
+            if ($expireDate !== '') {
420
+                try {
421
+                    $expireDate = $this->parseDate($expireDate);
422
+                    $share->setExpirationDate($expireDate);
423
+                } catch (\Exception $e) {
424
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
425
+                }
426
+            }
427
+
428
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
429
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
430
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
431
+            }
432
+
433
+            $share->setSharedWith($shareWith);
434
+            $share->setPermissions($permissions);
435
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
436
+            if ($share->getNodeType() === 'file') {
437
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
438
+            } else {
439
+                $share->setPermissions(
440
+                    \OCP\Constants::PERMISSION_READ |
441
+                    \OCP\Constants::PERMISSION_CREATE |
442
+                    \OCP\Constants::PERMISSION_UPDATE |
443
+                    \OCP\Constants::PERMISSION_DELETE);
444
+            }
445
+            $share->setSharedWith($shareWith);
446
+        } else {
447
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
448
+        }
449
+
450
+        $share->setShareType($shareType);
451
+        $share->setSharedBy($this->currentUser);
452
+
453
+        try {
454
+            $share = $this->shareManager->createShare($share);
455
+        } catch (GenericShareException $e) {
456
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
457
+            throw new OCSException($e->getHint(), $code);
458
+        } catch (\Exception $e) {
459
+            throw new OCSForbiddenException($e->getMessage());
460
+        }
461
+
462
+        $output = $this->formatShare($share);
463
+
464
+        return new DataResponse($output);
465
+    }
466
+
467
+    /**
468
+     * @param \OCP\Files\File|\OCP\Files\Folder $node
469
+     * @return DataResponse
470
+     */
471
+    private function getSharedWithMe($node = null) {
472
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
473
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
474
+
475
+        $shares = array_merge($userShares, $groupShares);
476
+
477
+        $shares = array_filter($shares, function (IShare $share) {
478
+            return $share->getShareOwner() !== $this->currentUser;
479
+        });
480
+
481
+        $formatted = [];
482
+        foreach ($shares as $share) {
483
+            if ($this->canAccessShare($share)) {
484
+                try {
485
+                    $formatted[] = $this->formatShare($share);
486
+                } catch (NotFoundException $e) {
487
+                    // Ignore this share
488
+                }
489
+            }
490
+        }
491
+
492
+        return new DataResponse($formatted);
493
+    }
494
+
495
+    /**
496
+     * @param \OCP\Files\Folder $folder
497
+     * @return DataResponse
498
+     * @throws OCSBadRequestException
499
+     */
500
+    private function getSharesInDir($folder) {
501
+        if (!($folder instanceof \OCP\Files\Folder)) {
502
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
503
+        }
504
+
505
+        $nodes = $folder->getDirectoryListing();
506
+        /** @var \OCP\Share\IShare[] $shares */
507
+        $shares = [];
508
+        foreach ($nodes as $node) {
509
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
510
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
511
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
512
+            if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
513
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
514
+            }
515
+            if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
516
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
517
+            }
518
+        }
519
+
520
+        $formatted = [];
521
+        foreach ($shares as $share) {
522
+            try {
523
+                $formatted[] = $this->formatShare($share);
524
+            } catch (NotFoundException $e) {
525
+                //Ignore this share
526
+            }
527
+        }
528
+
529
+        return new DataResponse($formatted);
530
+    }
531
+
532
+    /**
533
+     * The getShares function.
534
+     *
535
+     * @NoAdminRequired
536
+     *
537
+     * @param string $shared_with_me
538
+     * @param string $reshares
539
+     * @param string $subfiles
540
+     * @param string $path
541
+     *
542
+     * - Get shares by the current user
543
+     * - Get shares by the current user and reshares (?reshares=true)
544
+     * - Get shares with the current user (?shared_with_me=true)
545
+     * - Get shares for a specific path (?path=...)
546
+     * - Get all shares in a folder (?subfiles=true&path=..)
547
+     *
548
+     * @return DataResponse
549
+     * @throws OCSNotFoundException
550
+     */
551
+    public function getShares(
552
+        $shared_with_me = 'false',
553
+        $reshares = 'false',
554
+        $subfiles = 'false',
555
+        $path = null
556
+    ) {
557
+
558
+        if ($path !== null) {
559
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
560
+            try {
561
+                $path = $userFolder->get($path);
562
+                $this->lock($path);
563
+            } catch (\OCP\Files\NotFoundException $e) {
564
+                throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
565
+            } catch (LockedException $e) {
566
+                throw new OCSNotFoundException($this->l->t('Could not lock path'));
567
+            }
568
+        }
569
+
570
+        if ($shared_with_me === 'true') {
571
+            $result = $this->getSharedWithMe($path);
572
+            return $result;
573
+        }
574
+
575
+        if ($subfiles === 'true') {
576
+            $result = $this->getSharesInDir($path);
577
+            return $result;
578
+        }
579
+
580
+        if ($reshares === 'true') {
581
+            $reshares = true;
582
+        } else {
583
+            $reshares = false;
584
+        }
585
+
586
+        // Get all shares
587
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
588
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
589
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
590
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
591
+            $mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
592
+        } else {
593
+            $mailShares = [];
594
+        }
595
+        $shares = array_merge($userShares, $groupShares, $linkShares, $mailShares);
596
+
597
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
598
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
599
+            $shares = array_merge($shares, $federatedShares);
600
+        }
601
+
602
+        $formatted = [];
603
+        foreach ($shares as $share) {
604
+            try {
605
+                $formatted[] = $this->formatShare($share, $path);
606
+            } catch (NotFoundException $e) {
607
+                //Ignore share
608
+            }
609
+        }
610
+
611
+        return new DataResponse($formatted);
612
+    }
613
+
614
+    /**
615
+     * @NoAdminRequired
616
+     *
617
+     * @param int $id
618
+     * @param int $permissions
619
+     * @param string $password
620
+     * @param string $publicUpload
621
+     * @param string $expireDate
622
+     * @return DataResponse
623
+     * @throws OCSNotFoundException
624
+     * @throws OCSBadRequestException
625
+     * @throws OCSForbiddenException
626
+     */
627
+    public function updateShare(
628
+        $id,
629
+        $permissions = null,
630
+        $password = null,
631
+        $publicUpload = null,
632
+        $expireDate = null
633
+    ) {
634
+        try {
635
+            $share = $this->getShareById($id);
636
+        } catch (ShareNotFound $e) {
637
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
638
+        }
639
+
640
+        $this->lock($share->getNode());
641
+
642
+        if (!$this->canAccessShare($share, false)) {
643
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
644
+        }
645
+
646
+        /*
647 647
 		 * expirationdate, password and publicUpload only make sense for link shares
648 648
 		 */
649
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
650
-			if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
651
-				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
652
-			}
653
-
654
-			$newPermissions = null;
655
-			if ($publicUpload === 'true') {
656
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
657
-			} else if ($publicUpload === 'false') {
658
-				$newPermissions = \OCP\Constants::PERMISSION_READ;
659
-			}
660
-
661
-			if ($permissions !== null) {
662
-				$newPermissions = (int)$permissions;
663
-			}
664
-
665
-			if ($newPermissions !== null &&
666
-				!in_array($newPermissions, [
667
-					\OCP\Constants::PERMISSION_READ,
668
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
669
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
670
-					\OCP\Constants::PERMISSION_CREATE, // hidden file list
671
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
672
-				])
673
-			) {
674
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
675
-			}
676
-
677
-			if (
678
-				// legacy
679
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
680
-				// correct
681
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
682
-			) {
683
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
684
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
685
-				}
686
-
687
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
688
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
689
-				}
690
-
691
-				// normalize to correct public upload permissions
692
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
693
-			}
694
-
695
-			if ($newPermissions !== null) {
696
-				$share->setPermissions($newPermissions);
697
-				$permissions = $newPermissions;
698
-			}
699
-
700
-			if ($expireDate === '') {
701
-				$share->setExpirationDate(null);
702
-			} else if ($expireDate !== null) {
703
-				try {
704
-					$expireDate = $this->parseDate($expireDate);
705
-				} catch (\Exception $e) {
706
-					throw new OCSBadRequestException($e->getMessage());
707
-				}
708
-				$share->setExpirationDate($expireDate);
709
-			}
710
-
711
-			if ($password === '') {
712
-				$share->setPassword(null);
713
-			} else if ($password !== null) {
714
-				$share->setPassword($password);
715
-			}
716
-
717
-		} else {
718
-			// For other shares only permissions is valid.
719
-			if ($permissions === null) {
720
-				throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
721
-			} else {
722
-				$permissions = (int)$permissions;
723
-				$share->setPermissions($permissions);
724
-			}
725
-		}
726
-
727
-		if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
728
-			/* Check if this is an incomming share */
729
-			$incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
730
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
731
-
732
-			/** @var \OCP\Share\IShare[] $incomingShares */
733
-			if (!empty($incomingShares)) {
734
-				$maxPermissions = 0;
735
-				foreach ($incomingShares as $incomingShare) {
736
-					$maxPermissions |= $incomingShare->getPermissions();
737
-				}
738
-
739
-				if ($share->getPermissions() & ~$maxPermissions) {
740
-					throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
741
-				}
742
-			}
743
-		}
744
-
745
-
746
-		try {
747
-			$share = $this->shareManager->updateShare($share);
748
-		} catch (\Exception $e) {
749
-			throw new OCSBadRequestException($e->getMessage());
750
-		}
751
-
752
-		return new DataResponse($this->formatShare($share));
753
-	}
754
-
755
-	/**
756
-	 * @param \OCP\Share\IShare $share
757
-	 * @return bool
758
-	 */
759
-	protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
760
-		// A file with permissions 0 can't be accessed by us. So Don't show it
761
-		if ($share->getPermissions() === 0) {
762
-			return false;
763
-		}
764
-
765
-		// Owner of the file and the sharer of the file can always get share
766
-		if ($share->getShareOwner() === $this->currentUser ||
767
-			$share->getSharedBy() === $this->currentUser
768
-		) {
769
-			return true;
770
-		}
771
-
772
-		// If the share is shared with you (or a group you are a member of)
773
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
774
-			$share->getSharedWith() === $this->currentUser
775
-		) {
776
-			return true;
777
-		}
778
-
779
-		if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
780
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
781
-			$user = $this->userManager->get($this->currentUser);
782
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
783
-				return true;
784
-			}
785
-		}
786
-
787
-		return false;
788
-	}
789
-
790
-	/**
791
-	 * Make sure that the passed date is valid ISO 8601
792
-	 * So YYYY-MM-DD
793
-	 * If not throw an exception
794
-	 *
795
-	 * @param string $expireDate
796
-	 *
797
-	 * @throws \Exception
798
-	 * @return \DateTime
799
-	 */
800
-	private function parseDate($expireDate) {
801
-		try {
802
-			$date = new \DateTime($expireDate);
803
-		} catch (\Exception $e) {
804
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
805
-		}
806
-
807
-		if ($date === false) {
808
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
809
-		}
810
-
811
-		$date->setTime(0, 0, 0);
812
-
813
-		return $date;
814
-	}
815
-
816
-	/**
817
-	 * Since we have multiple providers but the OCS Share API v1 does
818
-	 * not support this we need to check all backends.
819
-	 *
820
-	 * @param string $id
821
-	 * @return \OCP\Share\IShare
822
-	 * @throws ShareNotFound
823
-	 */
824
-	private function getShareById($id) {
825
-		$share = null;
826
-
827
-		// First check if it is an internal share.
828
-		try {
829
-			$share = $this->shareManager->getShareById('ocinternal:' . $id);
830
-			return $share;
831
-		} catch (ShareNotFound $e) {
832
-			// Do nothing, just try the other share type
833
-		}
834
-
835
-		try {
836
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
837
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id);
838
-				return $share;
839
-			}
840
-		} catch (ShareNotFound $e) {
841
-			// Do nothing, just try the other share type
842
-		}
843
-
844
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
845
-			throw new ShareNotFound();
846
-		}
847
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
848
-
849
-		return $share;
850
-	}
851
-
852
-	/**
853
-	 * Lock a Node
854
-	 *
855
-	 * @param \OCP\Files\Node $node
856
-	 */
857
-	private function lock(\OCP\Files\Node $node) {
858
-		$node->lock(ILockingProvider::LOCK_SHARED);
859
-		$this->lockedNode = $node;
860
-	}
861
-
862
-	/**
863
-	 * Cleanup the remaining locks
864
-	 */
865
-	public function cleanup() {
866
-		if ($this->lockedNode !== null) {
867
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
868
-		}
869
-	}
649
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
650
+            if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
651
+                throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
652
+            }
653
+
654
+            $newPermissions = null;
655
+            if ($publicUpload === 'true') {
656
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
657
+            } else if ($publicUpload === 'false') {
658
+                $newPermissions = \OCP\Constants::PERMISSION_READ;
659
+            }
660
+
661
+            if ($permissions !== null) {
662
+                $newPermissions = (int)$permissions;
663
+            }
664
+
665
+            if ($newPermissions !== null &&
666
+                !in_array($newPermissions, [
667
+                    \OCP\Constants::PERMISSION_READ,
668
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
669
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
670
+                    \OCP\Constants::PERMISSION_CREATE, // hidden file list
671
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
672
+                ])
673
+            ) {
674
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
675
+            }
676
+
677
+            if (
678
+                // legacy
679
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
680
+                // correct
681
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
682
+            ) {
683
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
684
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
685
+                }
686
+
687
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
688
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
689
+                }
690
+
691
+                // normalize to correct public upload permissions
692
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
693
+            }
694
+
695
+            if ($newPermissions !== null) {
696
+                $share->setPermissions($newPermissions);
697
+                $permissions = $newPermissions;
698
+            }
699
+
700
+            if ($expireDate === '') {
701
+                $share->setExpirationDate(null);
702
+            } else if ($expireDate !== null) {
703
+                try {
704
+                    $expireDate = $this->parseDate($expireDate);
705
+                } catch (\Exception $e) {
706
+                    throw new OCSBadRequestException($e->getMessage());
707
+                }
708
+                $share->setExpirationDate($expireDate);
709
+            }
710
+
711
+            if ($password === '') {
712
+                $share->setPassword(null);
713
+            } else if ($password !== null) {
714
+                $share->setPassword($password);
715
+            }
716
+
717
+        } else {
718
+            // For other shares only permissions is valid.
719
+            if ($permissions === null) {
720
+                throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
721
+            } else {
722
+                $permissions = (int)$permissions;
723
+                $share->setPermissions($permissions);
724
+            }
725
+        }
726
+
727
+        if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
728
+            /* Check if this is an incomming share */
729
+            $incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
730
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
731
+
732
+            /** @var \OCP\Share\IShare[] $incomingShares */
733
+            if (!empty($incomingShares)) {
734
+                $maxPermissions = 0;
735
+                foreach ($incomingShares as $incomingShare) {
736
+                    $maxPermissions |= $incomingShare->getPermissions();
737
+                }
738
+
739
+                if ($share->getPermissions() & ~$maxPermissions) {
740
+                    throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
741
+                }
742
+            }
743
+        }
744
+
745
+
746
+        try {
747
+            $share = $this->shareManager->updateShare($share);
748
+        } catch (\Exception $e) {
749
+            throw new OCSBadRequestException($e->getMessage());
750
+        }
751
+
752
+        return new DataResponse($this->formatShare($share));
753
+    }
754
+
755
+    /**
756
+     * @param \OCP\Share\IShare $share
757
+     * @return bool
758
+     */
759
+    protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
760
+        // A file with permissions 0 can't be accessed by us. So Don't show it
761
+        if ($share->getPermissions() === 0) {
762
+            return false;
763
+        }
764
+
765
+        // Owner of the file and the sharer of the file can always get share
766
+        if ($share->getShareOwner() === $this->currentUser ||
767
+            $share->getSharedBy() === $this->currentUser
768
+        ) {
769
+            return true;
770
+        }
771
+
772
+        // If the share is shared with you (or a group you are a member of)
773
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
774
+            $share->getSharedWith() === $this->currentUser
775
+        ) {
776
+            return true;
777
+        }
778
+
779
+        if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
780
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
781
+            $user = $this->userManager->get($this->currentUser);
782
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
783
+                return true;
784
+            }
785
+        }
786
+
787
+        return false;
788
+    }
789
+
790
+    /**
791
+     * Make sure that the passed date is valid ISO 8601
792
+     * So YYYY-MM-DD
793
+     * If not throw an exception
794
+     *
795
+     * @param string $expireDate
796
+     *
797
+     * @throws \Exception
798
+     * @return \DateTime
799
+     */
800
+    private function parseDate($expireDate) {
801
+        try {
802
+            $date = new \DateTime($expireDate);
803
+        } catch (\Exception $e) {
804
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
805
+        }
806
+
807
+        if ($date === false) {
808
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
809
+        }
810
+
811
+        $date->setTime(0, 0, 0);
812
+
813
+        return $date;
814
+    }
815
+
816
+    /**
817
+     * Since we have multiple providers but the OCS Share API v1 does
818
+     * not support this we need to check all backends.
819
+     *
820
+     * @param string $id
821
+     * @return \OCP\Share\IShare
822
+     * @throws ShareNotFound
823
+     */
824
+    private function getShareById($id) {
825
+        $share = null;
826
+
827
+        // First check if it is an internal share.
828
+        try {
829
+            $share = $this->shareManager->getShareById('ocinternal:' . $id);
830
+            return $share;
831
+        } catch (ShareNotFound $e) {
832
+            // Do nothing, just try the other share type
833
+        }
834
+
835
+        try {
836
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
837
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id);
838
+                return $share;
839
+            }
840
+        } catch (ShareNotFound $e) {
841
+            // Do nothing, just try the other share type
842
+        }
843
+
844
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
845
+            throw new ShareNotFound();
846
+        }
847
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
848
+
849
+        return $share;
850
+    }
851
+
852
+    /**
853
+     * Lock a Node
854
+     *
855
+     * @param \OCP\Files\Node $node
856
+     */
857
+    private function lock(\OCP\Files\Node $node) {
858
+        $node->lock(ILockingProvider::LOCK_SHARED);
859
+        $this->lockedNode = $node;
860
+    }
861
+
862
+    /**
863
+     * Cleanup the remaining locks
864
+     */
865
+    public function cleanup() {
866
+        if ($this->lockedNode !== null) {
867
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
868
+        }
869
+    }
870 870
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/MountProvider.php 2 patches
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -33,171 +33,171 @@
 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
-		$shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
72
-		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
73
-		// filter out excluded shares and group shares that includes self
74
-		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
75
-			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
76
-		});
77
-
78
-		$superShares = $this->buildSuperShares($shares, $user);
79
-
80
-		$mounts = [];
81
-		foreach ($superShares as $share) {
82
-			try {
83
-				$mounts[] = new SharedMount(
84
-					'\OCA\Files_Sharing\SharedStorage',
85
-					$mounts,
86
-					[
87
-						'user' => $user->getUID(),
88
-						// parent share
89
-						'superShare' => $share[0],
90
-						// children/component of the superShare
91
-						'groupedShares' => $share[1],
92
-					],
93
-					$storageFactory
94
-				);
95
-			} catch (\Exception $e) {
96
-				$this->logger->logException($e);
97
-				$this->logger->error('Error while trying to create shared mount');
98
-			}
99
-		}
100
-
101
-		// array_filter removes the null values from the array
102
-		return array_filter($mounts);
103
-	}
104
-
105
-	/**
106
-	 * Groups shares by path (nodeId) and target path
107
-	 *
108
-	 * @param \OCP\Share\IShare[] $shares
109
-	 * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
110
-	 * array is a group which itself is an array of shares
111
-	 */
112
-	private function groupShares(array $shares) {
113
-		$tmp = [];
114
-
115
-		foreach ($shares as $share) {
116
-			if (!isset($tmp[$share->getNodeId()])) {
117
-				$tmp[$share->getNodeId()] = [];
118
-			}
119
-			$tmp[$share->getNodeId()][] = $share;
120
-		}
121
-
122
-		$result = [];
123
-		// sort by stime, the super share will be based on the least recent share
124
-		foreach ($tmp as &$tmp2) {
125
-			@usort($tmp2, function($a, $b) {
126
-				if ($a->getShareTime() <= $b->getShareTime()) {
127
-					return -1;
128
-				}
129
-				return 1;
130
-			});
131
-			$result[] = $tmp2;
132
-		}
133
-
134
-		return array_values($result);
135
-	}
136
-
137
-	/**
138
-	 * Build super shares (virtual share) by grouping them by node id and target,
139
-	 * then for each group compute the super share and return it along with the matching
140
-	 * grouped shares. The most permissive permissions are used based on the permissions
141
-	 * of all shares within the group.
142
-	 *
143
-	 * @param \OCP\Share\IShare[] $allShares
144
-	 * @param \OCP\IUser $user user
145
-	 * @return array Tuple of [superShare, groupedShares]
146
-	 */
147
-	private function buildSuperShares(array $allShares, \OCP\IUser $user) {
148
-		$result = [];
149
-
150
-		$groupedShares = $this->groupShares($allShares);
151
-
152
-		/** @var \OCP\Share\IShare[] $shares */
153
-		foreach ($groupedShares as $shares) {
154
-			if (count($shares) === 0) {
155
-				continue;
156
-			}
157
-
158
-			$superShare = $this->shareManager->newShare();
159
-
160
-			// compute super share based on first entry of the group
161
-			$superShare->setId($shares[0]->getId())
162
-				->setShareOwner($shares[0]->getShareOwner())
163
-				->setNodeId($shares[0]->getNodeId())
164
-				->setTarget($shares[0]->getTarget());
165
-
166
-			// use most permissive permissions
167
-			$permissions = 0;
168
-			foreach ($shares as $share) {
169
-				$permissions |= $share->getPermissions();
170
-				if ($share->getTarget() !== $superShare->getTarget()) {
171
-					// adjust target, for database consistency
172
-					$share->setTarget($superShare->getTarget());
173
-					try {
174
-						$this->shareManager->moveShare($share, $user->getUID());
175
-					} catch (\InvalidArgumentException $e) {
176
-						// ignore as it is not important and we don't want to
177
-						// block FS setup
178
-
179
-						// the subsequent code anyway only uses the target of the
180
-						// super share
181
-
182
-						// such issue can usually happen when dealing with
183
-						// null groups which usually appear with group backend
184
-						// caching inconsistencies
185
-						$this->logger->debug(
186
-							'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
187
-							['app' => 'files_sharing']
188
-						);
189
-					}
190
-				}
191
-				if (!is_null($share->getNodeCacheEntry())) {
192
-					$superShare->setNodeCacheEntry($share->getNodeCacheEntry());
193
-				}
194
-			}
195
-
196
-			$superShare->setPermissions($permissions);
197
-
198
-			$result[] = [$superShare, $shares];
199
-		}
200
-
201
-		return $result;
202
-	}
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
+        $shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
72
+        $shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
73
+        // filter out excluded shares and group shares that includes self
74
+        $shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
75
+            return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
76
+        });
77
+
78
+        $superShares = $this->buildSuperShares($shares, $user);
79
+
80
+        $mounts = [];
81
+        foreach ($superShares as $share) {
82
+            try {
83
+                $mounts[] = new SharedMount(
84
+                    '\OCA\Files_Sharing\SharedStorage',
85
+                    $mounts,
86
+                    [
87
+                        'user' => $user->getUID(),
88
+                        // parent share
89
+                        'superShare' => $share[0],
90
+                        // children/component of the superShare
91
+                        'groupedShares' => $share[1],
92
+                    ],
93
+                    $storageFactory
94
+                );
95
+            } catch (\Exception $e) {
96
+                $this->logger->logException($e);
97
+                $this->logger->error('Error while trying to create shared mount');
98
+            }
99
+        }
100
+
101
+        // array_filter removes the null values from the array
102
+        return array_filter($mounts);
103
+    }
104
+
105
+    /**
106
+     * Groups shares by path (nodeId) and target path
107
+     *
108
+     * @param \OCP\Share\IShare[] $shares
109
+     * @return \OCP\Share\IShare[][] array of grouped shares, each element in the
110
+     * array is a group which itself is an array of shares
111
+     */
112
+    private function groupShares(array $shares) {
113
+        $tmp = [];
114
+
115
+        foreach ($shares as $share) {
116
+            if (!isset($tmp[$share->getNodeId()])) {
117
+                $tmp[$share->getNodeId()] = [];
118
+            }
119
+            $tmp[$share->getNodeId()][] = $share;
120
+        }
121
+
122
+        $result = [];
123
+        // sort by stime, the super share will be based on the least recent share
124
+        foreach ($tmp as &$tmp2) {
125
+            @usort($tmp2, function($a, $b) {
126
+                if ($a->getShareTime() <= $b->getShareTime()) {
127
+                    return -1;
128
+                }
129
+                return 1;
130
+            });
131
+            $result[] = $tmp2;
132
+        }
133
+
134
+        return array_values($result);
135
+    }
136
+
137
+    /**
138
+     * Build super shares (virtual share) by grouping them by node id and target,
139
+     * then for each group compute the super share and return it along with the matching
140
+     * grouped shares. The most permissive permissions are used based on the permissions
141
+     * of all shares within the group.
142
+     *
143
+     * @param \OCP\Share\IShare[] $allShares
144
+     * @param \OCP\IUser $user user
145
+     * @return array Tuple of [superShare, groupedShares]
146
+     */
147
+    private function buildSuperShares(array $allShares, \OCP\IUser $user) {
148
+        $result = [];
149
+
150
+        $groupedShares = $this->groupShares($allShares);
151
+
152
+        /** @var \OCP\Share\IShare[] $shares */
153
+        foreach ($groupedShares as $shares) {
154
+            if (count($shares) === 0) {
155
+                continue;
156
+            }
157
+
158
+            $superShare = $this->shareManager->newShare();
159
+
160
+            // compute super share based on first entry of the group
161
+            $superShare->setId($shares[0]->getId())
162
+                ->setShareOwner($shares[0]->getShareOwner())
163
+                ->setNodeId($shares[0]->getNodeId())
164
+                ->setTarget($shares[0]->getTarget());
165
+
166
+            // use most permissive permissions
167
+            $permissions = 0;
168
+            foreach ($shares as $share) {
169
+                $permissions |= $share->getPermissions();
170
+                if ($share->getTarget() !== $superShare->getTarget()) {
171
+                    // adjust target, for database consistency
172
+                    $share->setTarget($superShare->getTarget());
173
+                    try {
174
+                        $this->shareManager->moveShare($share, $user->getUID());
175
+                    } catch (\InvalidArgumentException $e) {
176
+                        // ignore as it is not important and we don't want to
177
+                        // block FS setup
178
+
179
+                        // the subsequent code anyway only uses the target of the
180
+                        // super share
181
+
182
+                        // such issue can usually happen when dealing with
183
+                        // null groups which usually appear with group backend
184
+                        // caching inconsistencies
185
+                        $this->logger->debug(
186
+                            'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
187
+                            ['app' => 'files_sharing']
188
+                        );
189
+                    }
190
+                }
191
+                if (!is_null($share->getNodeCacheEntry())) {
192
+                    $superShare->setNodeCacheEntry($share->getNodeCacheEntry());
193
+                }
194
+            }
195
+
196
+            $superShare->setPermissions($permissions);
197
+
198
+            $result[] = [$superShare, $shares];
199
+        }
200
+
201
+        return $result;
202
+    }
203 203
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -71,7 +71,7 @@  discard block
 block discarded – undo
71 71
 		$shares = $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_USER, null, -1);
72 72
 		$shares = array_merge($shares, $this->shareManager->getSharedWith($user->getUID(), \OCP\Share::SHARE_TYPE_GROUP, null, -1));
73 73
 		// filter out excluded shares and group shares that includes self
74
-		$shares = array_filter($shares, function (\OCP\Share\IShare $share) use ($user) {
74
+		$shares = array_filter($shares, function(\OCP\Share\IShare $share) use ($user) {
75 75
 			return $share->getPermissions() > 0 && $share->getShareOwner() !== $user->getUID();
76 76
 		});
77 77
 
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 						// null groups which usually appear with group backend
184 184
 						// caching inconsistencies
185 185
 						$this->logger->debug(
186
-							'Could not adjust share target for share ' . $share->getId() . ' to make it consistent: ' . $e->getMessage(),
186
+							'Could not adjust share target for share '.$share->getId().' to make it consistent: '.$e->getMessage(),
187 187
 							['app' => 'files_sharing']
188 188
 						);
189 189
 					}
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.
lib/private/Server.php 2 patches
Indentation   +1470 added lines, -1470 removed lines patch added patch discarded remove patch
@@ -108,1479 +108,1479 @@
 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($c->getConfig());
483
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
484
-			if (!$factory->isValidType($type)) {
485
-				throw new \OC\DatabaseException('Invalid database type');
486
-			}
487
-			$connectionParams = $factory->createConnectionParams($systemConfig);
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($c->getConfig());
483
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
484
+            if (!$factory->isValidType($type)) {
485
+                throw new \OC\DatabaseException('Invalid database type');
486
+            }
487
+            $connectionParams = $factory->createConnectionParams($systemConfig);
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
-				new \OC\Settings\Mapper($c->getDatabaseConnection()),
815
-				$c->getURLGenerator()
816
-			);
817
-			return $manager;
818
-		});
819
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
820
-			return new \OC\Files\AppData\Factory(
821
-				$c->getRootFolder(),
822
-				$c->getSystemConfig()
823
-			);
824
-		});
825
-
826
-		$this->registerService('LockdownManager', function (Server $c) {
827
-			return new LockdownManager();
828
-		});
829
-
830
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
831
-			return new CloudIdManager();
832
-		});
833
-
834
-		/* To trick DI since we don't extend the DIContainer here */
835
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
836
-			return new CleanPreviewsBackgroundJob(
837
-				$c->getRootFolder(),
838
-				$c->getLogger(),
839
-				$c->getJobList(),
840
-				new TimeFactory()
841
-			);
842
-		});
843
-	}
844
-
845
-	/**
846
-	 * @return \OCP\Contacts\IManager
847
-	 */
848
-	public function getContactsManager() {
849
-		return $this->query('ContactsManager');
850
-	}
851
-
852
-	/**
853
-	 * @return \OC\Encryption\Manager
854
-	 */
855
-	public function getEncryptionManager() {
856
-		return $this->query('EncryptionManager');
857
-	}
858
-
859
-	/**
860
-	 * @return \OC\Encryption\File
861
-	 */
862
-	public function getEncryptionFilesHelper() {
863
-		return $this->query('EncryptionFileHelper');
864
-	}
865
-
866
-	/**
867
-	 * @return \OCP\Encryption\Keys\IStorage
868
-	 */
869
-	public function getEncryptionKeyStorage() {
870
-		return $this->query('EncryptionKeyStorage');
871
-	}
872
-
873
-	/**
874
-	 * The current request object holding all information about the request
875
-	 * currently being processed is returned from this method.
876
-	 * In case the current execution was not initiated by a web request null is returned
877
-	 *
878
-	 * @return \OCP\IRequest
879
-	 */
880
-	public function getRequest() {
881
-		return $this->query('Request');
882
-	}
883
-
884
-	/**
885
-	 * Returns the preview manager which can create preview images for a given file
886
-	 *
887
-	 * @return \OCP\IPreview
888
-	 */
889
-	public function getPreviewManager() {
890
-		return $this->query('PreviewManager');
891
-	}
892
-
893
-	/**
894
-	 * Returns the tag manager which can get and set tags for different object types
895
-	 *
896
-	 * @see \OCP\ITagManager::load()
897
-	 * @return \OCP\ITagManager
898
-	 */
899
-	public function getTagManager() {
900
-		return $this->query('TagManager');
901
-	}
902
-
903
-	/**
904
-	 * Returns the system-tag manager
905
-	 *
906
-	 * @return \OCP\SystemTag\ISystemTagManager
907
-	 *
908
-	 * @since 9.0.0
909
-	 */
910
-	public function getSystemTagManager() {
911
-		return $this->query('SystemTagManager');
912
-	}
913
-
914
-	/**
915
-	 * Returns the system-tag object mapper
916
-	 *
917
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
918
-	 *
919
-	 * @since 9.0.0
920
-	 */
921
-	public function getSystemTagObjectMapper() {
922
-		return $this->query('SystemTagObjectMapper');
923
-	}
924
-
925
-	/**
926
-	 * Returns the avatar manager, used for avatar functionality
927
-	 *
928
-	 * @return \OCP\IAvatarManager
929
-	 */
930
-	public function getAvatarManager() {
931
-		return $this->query('AvatarManager');
932
-	}
933
-
934
-	/**
935
-	 * Returns the root folder of ownCloud's data directory
936
-	 *
937
-	 * @return \OCP\Files\IRootFolder
938
-	 */
939
-	public function getRootFolder() {
940
-		return $this->query('LazyRootFolder');
941
-	}
942
-
943
-	/**
944
-	 * Returns the root folder of ownCloud's data directory
945
-	 * This is the lazy variant so this gets only initialized once it
946
-	 * is actually used.
947
-	 *
948
-	 * @return \OCP\Files\IRootFolder
949
-	 */
950
-	public function getLazyRootFolder() {
951
-		return $this->query('LazyRootFolder');
952
-	}
953
-
954
-	/**
955
-	 * Returns a view to ownCloud's files folder
956
-	 *
957
-	 * @param string $userId user ID
958
-	 * @return \OCP\Files\Folder|null
959
-	 */
960
-	public function getUserFolder($userId = null) {
961
-		if ($userId === null) {
962
-			$user = $this->getUserSession()->getUser();
963
-			if (!$user) {
964
-				return null;
965
-			}
966
-			$userId = $user->getUID();
967
-		}
968
-		$root = $this->getRootFolder();
969
-		return $root->getUserFolder($userId);
970
-	}
971
-
972
-	/**
973
-	 * Returns an app-specific view in ownClouds data directory
974
-	 *
975
-	 * @return \OCP\Files\Folder
976
-	 * @deprecated since 9.2.0 use IAppData
977
-	 */
978
-	public function getAppFolder() {
979
-		$dir = '/' . \OC_App::getCurrentApp();
980
-		$root = $this->getRootFolder();
981
-		if (!$root->nodeExists($dir)) {
982
-			$folder = $root->newFolder($dir);
983
-		} else {
984
-			$folder = $root->get($dir);
985
-		}
986
-		return $folder;
987
-	}
988
-
989
-	/**
990
-	 * @return \OC\User\Manager
991
-	 */
992
-	public function getUserManager() {
993
-		return $this->query('UserManager');
994
-	}
995
-
996
-	/**
997
-	 * @return \OC\Group\Manager
998
-	 */
999
-	public function getGroupManager() {
1000
-		return $this->query('GroupManager');
1001
-	}
1002
-
1003
-	/**
1004
-	 * @return \OC\User\Session
1005
-	 */
1006
-	public function getUserSession() {
1007
-		return $this->query('UserSession');
1008
-	}
1009
-
1010
-	/**
1011
-	 * @return \OCP\ISession
1012
-	 */
1013
-	public function getSession() {
1014
-		return $this->query('UserSession')->getSession();
1015
-	}
1016
-
1017
-	/**
1018
-	 * @param \OCP\ISession $session
1019
-	 */
1020
-	public function setSession(\OCP\ISession $session) {
1021
-		$this->query(SessionStorage::class)->setSession($session);
1022
-		$this->query('UserSession')->setSession($session);
1023
-		$this->query(Store::class)->setSession($session);
1024
-	}
1025
-
1026
-	/**
1027
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1028
-	 */
1029
-	public function getTwoFactorAuthManager() {
1030
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1031
-	}
1032
-
1033
-	/**
1034
-	 * @return \OC\NavigationManager
1035
-	 */
1036
-	public function getNavigationManager() {
1037
-		return $this->query('NavigationManager');
1038
-	}
1039
-
1040
-	/**
1041
-	 * @return \OCP\IConfig
1042
-	 */
1043
-	public function getConfig() {
1044
-		return $this->query('AllConfig');
1045
-	}
1046
-
1047
-	/**
1048
-	 * @internal For internal use only
1049
-	 * @return \OC\SystemConfig
1050
-	 */
1051
-	public function getSystemConfig() {
1052
-		return $this->query('SystemConfig');
1053
-	}
1054
-
1055
-	/**
1056
-	 * Returns the app config manager
1057
-	 *
1058
-	 * @return \OCP\IAppConfig
1059
-	 */
1060
-	public function getAppConfig() {
1061
-		return $this->query('AppConfig');
1062
-	}
1063
-
1064
-	/**
1065
-	 * @return \OCP\L10N\IFactory
1066
-	 */
1067
-	public function getL10NFactory() {
1068
-		return $this->query('L10NFactory');
1069
-	}
1070
-
1071
-	/**
1072
-	 * get an L10N instance
1073
-	 *
1074
-	 * @param string $app appid
1075
-	 * @param string $lang
1076
-	 * @return IL10N
1077
-	 */
1078
-	public function getL10N($app, $lang = null) {
1079
-		return $this->getL10NFactory()->get($app, $lang);
1080
-	}
1081
-
1082
-	/**
1083
-	 * @return \OCP\IURLGenerator
1084
-	 */
1085
-	public function getURLGenerator() {
1086
-		return $this->query('URLGenerator');
1087
-	}
1088
-
1089
-	/**
1090
-	 * @return \OCP\IHelper
1091
-	 */
1092
-	public function getHelper() {
1093
-		return $this->query('AppHelper');
1094
-	}
1095
-
1096
-	/**
1097
-	 * @return AppFetcher
1098
-	 */
1099
-	public function getAppFetcher() {
1100
-		return $this->query('AppFetcher');
1101
-	}
1102
-
1103
-	/**
1104
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1105
-	 * getMemCacheFactory() instead.
1106
-	 *
1107
-	 * @return \OCP\ICache
1108
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1109
-	 */
1110
-	public function getCache() {
1111
-		return $this->query('UserCache');
1112
-	}
1113
-
1114
-	/**
1115
-	 * Returns an \OCP\CacheFactory instance
1116
-	 *
1117
-	 * @return \OCP\ICacheFactory
1118
-	 */
1119
-	public function getMemCacheFactory() {
1120
-		return $this->query('MemCacheFactory');
1121
-	}
1122
-
1123
-	/**
1124
-	 * Returns an \OC\RedisFactory instance
1125
-	 *
1126
-	 * @return \OC\RedisFactory
1127
-	 */
1128
-	public function getGetRedisFactory() {
1129
-		return $this->query('RedisFactory');
1130
-	}
1131
-
1132
-
1133
-	/**
1134
-	 * Returns the current session
1135
-	 *
1136
-	 * @return \OCP\IDBConnection
1137
-	 */
1138
-	public function getDatabaseConnection() {
1139
-		return $this->query('DatabaseConnection');
1140
-	}
1141
-
1142
-	/**
1143
-	 * Returns the activity manager
1144
-	 *
1145
-	 * @return \OCP\Activity\IManager
1146
-	 */
1147
-	public function getActivityManager() {
1148
-		return $this->query('ActivityManager');
1149
-	}
1150
-
1151
-	/**
1152
-	 * Returns an job list for controlling background jobs
1153
-	 *
1154
-	 * @return \OCP\BackgroundJob\IJobList
1155
-	 */
1156
-	public function getJobList() {
1157
-		return $this->query('JobList');
1158
-	}
1159
-
1160
-	/**
1161
-	 * Returns a logger instance
1162
-	 *
1163
-	 * @return \OCP\ILogger
1164
-	 */
1165
-	public function getLogger() {
1166
-		return $this->query('Logger');
1167
-	}
1168
-
1169
-	/**
1170
-	 * Returns a router for generating and matching urls
1171
-	 *
1172
-	 * @return \OCP\Route\IRouter
1173
-	 */
1174
-	public function getRouter() {
1175
-		return $this->query('Router');
1176
-	}
1177
-
1178
-	/**
1179
-	 * Returns a search instance
1180
-	 *
1181
-	 * @return \OCP\ISearch
1182
-	 */
1183
-	public function getSearch() {
1184
-		return $this->query('Search');
1185
-	}
1186
-
1187
-	/**
1188
-	 * Returns a SecureRandom instance
1189
-	 *
1190
-	 * @return \OCP\Security\ISecureRandom
1191
-	 */
1192
-	public function getSecureRandom() {
1193
-		return $this->query('SecureRandom');
1194
-	}
1195
-
1196
-	/**
1197
-	 * Returns a Crypto instance
1198
-	 *
1199
-	 * @return \OCP\Security\ICrypto
1200
-	 */
1201
-	public function getCrypto() {
1202
-		return $this->query('Crypto');
1203
-	}
1204
-
1205
-	/**
1206
-	 * Returns a Hasher instance
1207
-	 *
1208
-	 * @return \OCP\Security\IHasher
1209
-	 */
1210
-	public function getHasher() {
1211
-		return $this->query('Hasher');
1212
-	}
1213
-
1214
-	/**
1215
-	 * Returns a CredentialsManager instance
1216
-	 *
1217
-	 * @return \OCP\Security\ICredentialsManager
1218
-	 */
1219
-	public function getCredentialsManager() {
1220
-		return $this->query('CredentialsManager');
1221
-	}
1222
-
1223
-	/**
1224
-	 * Returns an instance of the HTTP helper class
1225
-	 *
1226
-	 * @deprecated Use getHTTPClientService()
1227
-	 * @return \OC\HTTPHelper
1228
-	 */
1229
-	public function getHTTPHelper() {
1230
-		return $this->query('HTTPHelper');
1231
-	}
1232
-
1233
-	/**
1234
-	 * Get the certificate manager for the user
1235
-	 *
1236
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1237
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1238
-	 */
1239
-	public function getCertificateManager($userId = '') {
1240
-		if ($userId === '') {
1241
-			$userSession = $this->getUserSession();
1242
-			$user = $userSession->getUser();
1243
-			if (is_null($user)) {
1244
-				return null;
1245
-			}
1246
-			$userId = $user->getUID();
1247
-		}
1248
-		return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1249
-	}
1250
-
1251
-	/**
1252
-	 * Returns an instance of the HTTP client service
1253
-	 *
1254
-	 * @return \OCP\Http\Client\IClientService
1255
-	 */
1256
-	public function getHTTPClientService() {
1257
-		return $this->query('HttpClientService');
1258
-	}
1259
-
1260
-	/**
1261
-	 * Create a new event source
1262
-	 *
1263
-	 * @return \OCP\IEventSource
1264
-	 */
1265
-	public function createEventSource() {
1266
-		return new \OC_EventSource();
1267
-	}
1268
-
1269
-	/**
1270
-	 * Get the active event logger
1271
-	 *
1272
-	 * The returned logger only logs data when debug mode is enabled
1273
-	 *
1274
-	 * @return \OCP\Diagnostics\IEventLogger
1275
-	 */
1276
-	public function getEventLogger() {
1277
-		return $this->query('EventLogger');
1278
-	}
1279
-
1280
-	/**
1281
-	 * Get the active query logger
1282
-	 *
1283
-	 * The returned logger only logs data when debug mode is enabled
1284
-	 *
1285
-	 * @return \OCP\Diagnostics\IQueryLogger
1286
-	 */
1287
-	public function getQueryLogger() {
1288
-		return $this->query('QueryLogger');
1289
-	}
1290
-
1291
-	/**
1292
-	 * Get the manager for temporary files and folders
1293
-	 *
1294
-	 * @return \OCP\ITempManager
1295
-	 */
1296
-	public function getTempManager() {
1297
-		return $this->query('TempManager');
1298
-	}
1299
-
1300
-	/**
1301
-	 * Get the app manager
1302
-	 *
1303
-	 * @return \OCP\App\IAppManager
1304
-	 */
1305
-	public function getAppManager() {
1306
-		return $this->query('AppManager');
1307
-	}
1308
-
1309
-	/**
1310
-	 * Creates a new mailer
1311
-	 *
1312
-	 * @return \OCP\Mail\IMailer
1313
-	 */
1314
-	public function getMailer() {
1315
-		return $this->query('Mailer');
1316
-	}
1317
-
1318
-	/**
1319
-	 * Get the webroot
1320
-	 *
1321
-	 * @return string
1322
-	 */
1323
-	public function getWebRoot() {
1324
-		return $this->webRoot;
1325
-	}
1326
-
1327
-	/**
1328
-	 * @return \OC\OCSClient
1329
-	 */
1330
-	public function getOcsClient() {
1331
-		return $this->query('OcsClient');
1332
-	}
1333
-
1334
-	/**
1335
-	 * @return \OCP\IDateTimeZone
1336
-	 */
1337
-	public function getDateTimeZone() {
1338
-		return $this->query('DateTimeZone');
1339
-	}
1340
-
1341
-	/**
1342
-	 * @return \OCP\IDateTimeFormatter
1343
-	 */
1344
-	public function getDateTimeFormatter() {
1345
-		return $this->query('DateTimeFormatter');
1346
-	}
1347
-
1348
-	/**
1349
-	 * @return \OCP\Files\Config\IMountProviderCollection
1350
-	 */
1351
-	public function getMountProviderCollection() {
1352
-		return $this->query('MountConfigManager');
1353
-	}
1354
-
1355
-	/**
1356
-	 * Get the IniWrapper
1357
-	 *
1358
-	 * @return IniGetWrapper
1359
-	 */
1360
-	public function getIniWrapper() {
1361
-		return $this->query('IniWrapper');
1362
-	}
1363
-
1364
-	/**
1365
-	 * @return \OCP\Command\IBus
1366
-	 */
1367
-	public function getCommandBus() {
1368
-		return $this->query('AsyncCommandBus');
1369
-	}
1370
-
1371
-	/**
1372
-	 * Get the trusted domain helper
1373
-	 *
1374
-	 * @return TrustedDomainHelper
1375
-	 */
1376
-	public function getTrustedDomainHelper() {
1377
-		return $this->query('TrustedDomainHelper');
1378
-	}
1379
-
1380
-	/**
1381
-	 * Get the locking provider
1382
-	 *
1383
-	 * @return \OCP\Lock\ILockingProvider
1384
-	 * @since 8.1.0
1385
-	 */
1386
-	public function getLockingProvider() {
1387
-		return $this->query('LockingProvider');
1388
-	}
1389
-
1390
-	/**
1391
-	 * @return \OCP\Files\Mount\IMountManager
1392
-	 **/
1393
-	function getMountManager() {
1394
-		return $this->query('MountManager');
1395
-	}
1396
-
1397
-	/** @return \OCP\Files\Config\IUserMountCache */
1398
-	function getUserMountCache() {
1399
-		return $this->query('UserMountCache');
1400
-	}
1401
-
1402
-	/**
1403
-	 * Get the MimeTypeDetector
1404
-	 *
1405
-	 * @return \OCP\Files\IMimeTypeDetector
1406
-	 */
1407
-	public function getMimeTypeDetector() {
1408
-		return $this->query('MimeTypeDetector');
1409
-	}
1410
-
1411
-	/**
1412
-	 * Get the MimeTypeLoader
1413
-	 *
1414
-	 * @return \OCP\Files\IMimeTypeLoader
1415
-	 */
1416
-	public function getMimeTypeLoader() {
1417
-		return $this->query('MimeTypeLoader');
1418
-	}
1419
-
1420
-	/**
1421
-	 * Get the manager of all the capabilities
1422
-	 *
1423
-	 * @return \OC\CapabilitiesManager
1424
-	 */
1425
-	public function getCapabilitiesManager() {
1426
-		return $this->query('CapabilitiesManager');
1427
-	}
1428
-
1429
-	/**
1430
-	 * Get the EventDispatcher
1431
-	 *
1432
-	 * @return EventDispatcherInterface
1433
-	 * @since 8.2.0
1434
-	 */
1435
-	public function getEventDispatcher() {
1436
-		return $this->query('EventDispatcher');
1437
-	}
1438
-
1439
-	/**
1440
-	 * Get the Notification Manager
1441
-	 *
1442
-	 * @return \OCP\Notification\IManager
1443
-	 * @since 8.2.0
1444
-	 */
1445
-	public function getNotificationManager() {
1446
-		return $this->query('NotificationManager');
1447
-	}
1448
-
1449
-	/**
1450
-	 * @return \OCP\Comments\ICommentsManager
1451
-	 */
1452
-	public function getCommentsManager() {
1453
-		return $this->query('CommentsManager');
1454
-	}
1455
-
1456
-	/**
1457
-	 * @return \OC_Defaults
1458
-	 */
1459
-	public function getThemingDefaults() {
1460
-		return $this->query('ThemingDefaults');
1461
-	}
1462
-
1463
-	/**
1464
-	 * @return \OC\IntegrityCheck\Checker
1465
-	 */
1466
-	public function getIntegrityCodeChecker() {
1467
-		return $this->query('IntegrityCodeChecker');
1468
-	}
1469
-
1470
-	/**
1471
-	 * @return \OC\Session\CryptoWrapper
1472
-	 */
1473
-	public function getSessionCryptoWrapper() {
1474
-		return $this->query('CryptoWrapper');
1475
-	}
1476
-
1477
-	/**
1478
-	 * @return CsrfTokenManager
1479
-	 */
1480
-	public function getCsrfTokenManager() {
1481
-		return $this->query('CsrfTokenManager');
1482
-	}
1483
-
1484
-	/**
1485
-	 * @return Throttler
1486
-	 */
1487
-	public function getBruteForceThrottler() {
1488
-		return $this->query('Throttler');
1489
-	}
1490
-
1491
-	/**
1492
-	 * @return IContentSecurityPolicyManager
1493
-	 */
1494
-	public function getContentSecurityPolicyManager() {
1495
-		return $this->query('ContentSecurityPolicyManager');
1496
-	}
1497
-
1498
-	/**
1499
-	 * @return ContentSecurityPolicyNonceManager
1500
-	 */
1501
-	public function getContentSecurityPolicyNonceManager() {
1502
-		return $this->query('ContentSecurityPolicyNonceManager');
1503
-	}
1504
-
1505
-	/**
1506
-	 * Not a public API as of 8.2, wait for 9.0
1507
-	 *
1508
-	 * @return \OCA\Files_External\Service\BackendService
1509
-	 */
1510
-	public function getStoragesBackendService() {
1511
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1512
-	}
1513
-
1514
-	/**
1515
-	 * Not a public API as of 8.2, wait for 9.0
1516
-	 *
1517
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1518
-	 */
1519
-	public function getGlobalStoragesService() {
1520
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1521
-	}
1522
-
1523
-	/**
1524
-	 * Not a public API as of 8.2, wait for 9.0
1525
-	 *
1526
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1527
-	 */
1528
-	public function getUserGlobalStoragesService() {
1529
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1530
-	}
1531
-
1532
-	/**
1533
-	 * Not a public API as of 8.2, wait for 9.0
1534
-	 *
1535
-	 * @return \OCA\Files_External\Service\UserStoragesService
1536
-	 */
1537
-	public function getUserStoragesService() {
1538
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1539
-	}
1540
-
1541
-	/**
1542
-	 * @return \OCP\Share\IManager
1543
-	 */
1544
-	public function getShareManager() {
1545
-		return $this->query('ShareManager');
1546
-	}
1547
-
1548
-	/**
1549
-	 * Returns the LDAP Provider
1550
-	 *
1551
-	 * @return \OCP\LDAP\ILDAPProvider
1552
-	 */
1553
-	public function getLDAPProvider() {
1554
-		return $this->query('LDAPProvider');
1555
-	}
1556
-
1557
-	/**
1558
-	 * @return \OCP\Settings\IManager
1559
-	 */
1560
-	public function getSettingsManager() {
1561
-		return $this->query('SettingsManager');
1562
-	}
1563
-
1564
-	/**
1565
-	 * @return \OCP\Files\IAppData
1566
-	 */
1567
-	public function getAppDataDir($app) {
1568
-		/** @var \OC\Files\AppData\Factory $factory */
1569
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1570
-		return $factory->get($app);
1571
-	}
1572
-
1573
-	/**
1574
-	 * @return \OCP\Lockdown\ILockdownManager
1575
-	 */
1576
-	public function getLockdownManager() {
1577
-		return $this->query('LockdownManager');
1578
-	}
1579
-
1580
-	/**
1581
-	 * @return \OCP\Federation\ICloudIdManager
1582
-	 */
1583
-	public function getCloudIdManager() {
1584
-		return $this->query(ICloudIdManager::class);
1585
-	}
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
+                new \OC\Settings\Mapper($c->getDatabaseConnection()),
815
+                $c->getURLGenerator()
816
+            );
817
+            return $manager;
818
+        });
819
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
820
+            return new \OC\Files\AppData\Factory(
821
+                $c->getRootFolder(),
822
+                $c->getSystemConfig()
823
+            );
824
+        });
825
+
826
+        $this->registerService('LockdownManager', function (Server $c) {
827
+            return new LockdownManager();
828
+        });
829
+
830
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
831
+            return new CloudIdManager();
832
+        });
833
+
834
+        /* To trick DI since we don't extend the DIContainer here */
835
+        $this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
836
+            return new CleanPreviewsBackgroundJob(
837
+                $c->getRootFolder(),
838
+                $c->getLogger(),
839
+                $c->getJobList(),
840
+                new TimeFactory()
841
+            );
842
+        });
843
+    }
844
+
845
+    /**
846
+     * @return \OCP\Contacts\IManager
847
+     */
848
+    public function getContactsManager() {
849
+        return $this->query('ContactsManager');
850
+    }
851
+
852
+    /**
853
+     * @return \OC\Encryption\Manager
854
+     */
855
+    public function getEncryptionManager() {
856
+        return $this->query('EncryptionManager');
857
+    }
858
+
859
+    /**
860
+     * @return \OC\Encryption\File
861
+     */
862
+    public function getEncryptionFilesHelper() {
863
+        return $this->query('EncryptionFileHelper');
864
+    }
865
+
866
+    /**
867
+     * @return \OCP\Encryption\Keys\IStorage
868
+     */
869
+    public function getEncryptionKeyStorage() {
870
+        return $this->query('EncryptionKeyStorage');
871
+    }
872
+
873
+    /**
874
+     * The current request object holding all information about the request
875
+     * currently being processed is returned from this method.
876
+     * In case the current execution was not initiated by a web request null is returned
877
+     *
878
+     * @return \OCP\IRequest
879
+     */
880
+    public function getRequest() {
881
+        return $this->query('Request');
882
+    }
883
+
884
+    /**
885
+     * Returns the preview manager which can create preview images for a given file
886
+     *
887
+     * @return \OCP\IPreview
888
+     */
889
+    public function getPreviewManager() {
890
+        return $this->query('PreviewManager');
891
+    }
892
+
893
+    /**
894
+     * Returns the tag manager which can get and set tags for different object types
895
+     *
896
+     * @see \OCP\ITagManager::load()
897
+     * @return \OCP\ITagManager
898
+     */
899
+    public function getTagManager() {
900
+        return $this->query('TagManager');
901
+    }
902
+
903
+    /**
904
+     * Returns the system-tag manager
905
+     *
906
+     * @return \OCP\SystemTag\ISystemTagManager
907
+     *
908
+     * @since 9.0.0
909
+     */
910
+    public function getSystemTagManager() {
911
+        return $this->query('SystemTagManager');
912
+    }
913
+
914
+    /**
915
+     * Returns the system-tag object mapper
916
+     *
917
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
918
+     *
919
+     * @since 9.0.0
920
+     */
921
+    public function getSystemTagObjectMapper() {
922
+        return $this->query('SystemTagObjectMapper');
923
+    }
924
+
925
+    /**
926
+     * Returns the avatar manager, used for avatar functionality
927
+     *
928
+     * @return \OCP\IAvatarManager
929
+     */
930
+    public function getAvatarManager() {
931
+        return $this->query('AvatarManager');
932
+    }
933
+
934
+    /**
935
+     * Returns the root folder of ownCloud's data directory
936
+     *
937
+     * @return \OCP\Files\IRootFolder
938
+     */
939
+    public function getRootFolder() {
940
+        return $this->query('LazyRootFolder');
941
+    }
942
+
943
+    /**
944
+     * Returns the root folder of ownCloud's data directory
945
+     * This is the lazy variant so this gets only initialized once it
946
+     * is actually used.
947
+     *
948
+     * @return \OCP\Files\IRootFolder
949
+     */
950
+    public function getLazyRootFolder() {
951
+        return $this->query('LazyRootFolder');
952
+    }
953
+
954
+    /**
955
+     * Returns a view to ownCloud's files folder
956
+     *
957
+     * @param string $userId user ID
958
+     * @return \OCP\Files\Folder|null
959
+     */
960
+    public function getUserFolder($userId = null) {
961
+        if ($userId === null) {
962
+            $user = $this->getUserSession()->getUser();
963
+            if (!$user) {
964
+                return null;
965
+            }
966
+            $userId = $user->getUID();
967
+        }
968
+        $root = $this->getRootFolder();
969
+        return $root->getUserFolder($userId);
970
+    }
971
+
972
+    /**
973
+     * Returns an app-specific view in ownClouds data directory
974
+     *
975
+     * @return \OCP\Files\Folder
976
+     * @deprecated since 9.2.0 use IAppData
977
+     */
978
+    public function getAppFolder() {
979
+        $dir = '/' . \OC_App::getCurrentApp();
980
+        $root = $this->getRootFolder();
981
+        if (!$root->nodeExists($dir)) {
982
+            $folder = $root->newFolder($dir);
983
+        } else {
984
+            $folder = $root->get($dir);
985
+        }
986
+        return $folder;
987
+    }
988
+
989
+    /**
990
+     * @return \OC\User\Manager
991
+     */
992
+    public function getUserManager() {
993
+        return $this->query('UserManager');
994
+    }
995
+
996
+    /**
997
+     * @return \OC\Group\Manager
998
+     */
999
+    public function getGroupManager() {
1000
+        return $this->query('GroupManager');
1001
+    }
1002
+
1003
+    /**
1004
+     * @return \OC\User\Session
1005
+     */
1006
+    public function getUserSession() {
1007
+        return $this->query('UserSession');
1008
+    }
1009
+
1010
+    /**
1011
+     * @return \OCP\ISession
1012
+     */
1013
+    public function getSession() {
1014
+        return $this->query('UserSession')->getSession();
1015
+    }
1016
+
1017
+    /**
1018
+     * @param \OCP\ISession $session
1019
+     */
1020
+    public function setSession(\OCP\ISession $session) {
1021
+        $this->query(SessionStorage::class)->setSession($session);
1022
+        $this->query('UserSession')->setSession($session);
1023
+        $this->query(Store::class)->setSession($session);
1024
+    }
1025
+
1026
+    /**
1027
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1028
+     */
1029
+    public function getTwoFactorAuthManager() {
1030
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1031
+    }
1032
+
1033
+    /**
1034
+     * @return \OC\NavigationManager
1035
+     */
1036
+    public function getNavigationManager() {
1037
+        return $this->query('NavigationManager');
1038
+    }
1039
+
1040
+    /**
1041
+     * @return \OCP\IConfig
1042
+     */
1043
+    public function getConfig() {
1044
+        return $this->query('AllConfig');
1045
+    }
1046
+
1047
+    /**
1048
+     * @internal For internal use only
1049
+     * @return \OC\SystemConfig
1050
+     */
1051
+    public function getSystemConfig() {
1052
+        return $this->query('SystemConfig');
1053
+    }
1054
+
1055
+    /**
1056
+     * Returns the app config manager
1057
+     *
1058
+     * @return \OCP\IAppConfig
1059
+     */
1060
+    public function getAppConfig() {
1061
+        return $this->query('AppConfig');
1062
+    }
1063
+
1064
+    /**
1065
+     * @return \OCP\L10N\IFactory
1066
+     */
1067
+    public function getL10NFactory() {
1068
+        return $this->query('L10NFactory');
1069
+    }
1070
+
1071
+    /**
1072
+     * get an L10N instance
1073
+     *
1074
+     * @param string $app appid
1075
+     * @param string $lang
1076
+     * @return IL10N
1077
+     */
1078
+    public function getL10N($app, $lang = null) {
1079
+        return $this->getL10NFactory()->get($app, $lang);
1080
+    }
1081
+
1082
+    /**
1083
+     * @return \OCP\IURLGenerator
1084
+     */
1085
+    public function getURLGenerator() {
1086
+        return $this->query('URLGenerator');
1087
+    }
1088
+
1089
+    /**
1090
+     * @return \OCP\IHelper
1091
+     */
1092
+    public function getHelper() {
1093
+        return $this->query('AppHelper');
1094
+    }
1095
+
1096
+    /**
1097
+     * @return AppFetcher
1098
+     */
1099
+    public function getAppFetcher() {
1100
+        return $this->query('AppFetcher');
1101
+    }
1102
+
1103
+    /**
1104
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1105
+     * getMemCacheFactory() instead.
1106
+     *
1107
+     * @return \OCP\ICache
1108
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1109
+     */
1110
+    public function getCache() {
1111
+        return $this->query('UserCache');
1112
+    }
1113
+
1114
+    /**
1115
+     * Returns an \OCP\CacheFactory instance
1116
+     *
1117
+     * @return \OCP\ICacheFactory
1118
+     */
1119
+    public function getMemCacheFactory() {
1120
+        return $this->query('MemCacheFactory');
1121
+    }
1122
+
1123
+    /**
1124
+     * Returns an \OC\RedisFactory instance
1125
+     *
1126
+     * @return \OC\RedisFactory
1127
+     */
1128
+    public function getGetRedisFactory() {
1129
+        return $this->query('RedisFactory');
1130
+    }
1131
+
1132
+
1133
+    /**
1134
+     * Returns the current session
1135
+     *
1136
+     * @return \OCP\IDBConnection
1137
+     */
1138
+    public function getDatabaseConnection() {
1139
+        return $this->query('DatabaseConnection');
1140
+    }
1141
+
1142
+    /**
1143
+     * Returns the activity manager
1144
+     *
1145
+     * @return \OCP\Activity\IManager
1146
+     */
1147
+    public function getActivityManager() {
1148
+        return $this->query('ActivityManager');
1149
+    }
1150
+
1151
+    /**
1152
+     * Returns an job list for controlling background jobs
1153
+     *
1154
+     * @return \OCP\BackgroundJob\IJobList
1155
+     */
1156
+    public function getJobList() {
1157
+        return $this->query('JobList');
1158
+    }
1159
+
1160
+    /**
1161
+     * Returns a logger instance
1162
+     *
1163
+     * @return \OCP\ILogger
1164
+     */
1165
+    public function getLogger() {
1166
+        return $this->query('Logger');
1167
+    }
1168
+
1169
+    /**
1170
+     * Returns a router for generating and matching urls
1171
+     *
1172
+     * @return \OCP\Route\IRouter
1173
+     */
1174
+    public function getRouter() {
1175
+        return $this->query('Router');
1176
+    }
1177
+
1178
+    /**
1179
+     * Returns a search instance
1180
+     *
1181
+     * @return \OCP\ISearch
1182
+     */
1183
+    public function getSearch() {
1184
+        return $this->query('Search');
1185
+    }
1186
+
1187
+    /**
1188
+     * Returns a SecureRandom instance
1189
+     *
1190
+     * @return \OCP\Security\ISecureRandom
1191
+     */
1192
+    public function getSecureRandom() {
1193
+        return $this->query('SecureRandom');
1194
+    }
1195
+
1196
+    /**
1197
+     * Returns a Crypto instance
1198
+     *
1199
+     * @return \OCP\Security\ICrypto
1200
+     */
1201
+    public function getCrypto() {
1202
+        return $this->query('Crypto');
1203
+    }
1204
+
1205
+    /**
1206
+     * Returns a Hasher instance
1207
+     *
1208
+     * @return \OCP\Security\IHasher
1209
+     */
1210
+    public function getHasher() {
1211
+        return $this->query('Hasher');
1212
+    }
1213
+
1214
+    /**
1215
+     * Returns a CredentialsManager instance
1216
+     *
1217
+     * @return \OCP\Security\ICredentialsManager
1218
+     */
1219
+    public function getCredentialsManager() {
1220
+        return $this->query('CredentialsManager');
1221
+    }
1222
+
1223
+    /**
1224
+     * Returns an instance of the HTTP helper class
1225
+     *
1226
+     * @deprecated Use getHTTPClientService()
1227
+     * @return \OC\HTTPHelper
1228
+     */
1229
+    public function getHTTPHelper() {
1230
+        return $this->query('HTTPHelper');
1231
+    }
1232
+
1233
+    /**
1234
+     * Get the certificate manager for the user
1235
+     *
1236
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1237
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1238
+     */
1239
+    public function getCertificateManager($userId = '') {
1240
+        if ($userId === '') {
1241
+            $userSession = $this->getUserSession();
1242
+            $user = $userSession->getUser();
1243
+            if (is_null($user)) {
1244
+                return null;
1245
+            }
1246
+            $userId = $user->getUID();
1247
+        }
1248
+        return new CertificateManager($userId, new View(), $this->getConfig(), $this->getLogger());
1249
+    }
1250
+
1251
+    /**
1252
+     * Returns an instance of the HTTP client service
1253
+     *
1254
+     * @return \OCP\Http\Client\IClientService
1255
+     */
1256
+    public function getHTTPClientService() {
1257
+        return $this->query('HttpClientService');
1258
+    }
1259
+
1260
+    /**
1261
+     * Create a new event source
1262
+     *
1263
+     * @return \OCP\IEventSource
1264
+     */
1265
+    public function createEventSource() {
1266
+        return new \OC_EventSource();
1267
+    }
1268
+
1269
+    /**
1270
+     * Get the active event logger
1271
+     *
1272
+     * The returned logger only logs data when debug mode is enabled
1273
+     *
1274
+     * @return \OCP\Diagnostics\IEventLogger
1275
+     */
1276
+    public function getEventLogger() {
1277
+        return $this->query('EventLogger');
1278
+    }
1279
+
1280
+    /**
1281
+     * Get the active query logger
1282
+     *
1283
+     * The returned logger only logs data when debug mode is enabled
1284
+     *
1285
+     * @return \OCP\Diagnostics\IQueryLogger
1286
+     */
1287
+    public function getQueryLogger() {
1288
+        return $this->query('QueryLogger');
1289
+    }
1290
+
1291
+    /**
1292
+     * Get the manager for temporary files and folders
1293
+     *
1294
+     * @return \OCP\ITempManager
1295
+     */
1296
+    public function getTempManager() {
1297
+        return $this->query('TempManager');
1298
+    }
1299
+
1300
+    /**
1301
+     * Get the app manager
1302
+     *
1303
+     * @return \OCP\App\IAppManager
1304
+     */
1305
+    public function getAppManager() {
1306
+        return $this->query('AppManager');
1307
+    }
1308
+
1309
+    /**
1310
+     * Creates a new mailer
1311
+     *
1312
+     * @return \OCP\Mail\IMailer
1313
+     */
1314
+    public function getMailer() {
1315
+        return $this->query('Mailer');
1316
+    }
1317
+
1318
+    /**
1319
+     * Get the webroot
1320
+     *
1321
+     * @return string
1322
+     */
1323
+    public function getWebRoot() {
1324
+        return $this->webRoot;
1325
+    }
1326
+
1327
+    /**
1328
+     * @return \OC\OCSClient
1329
+     */
1330
+    public function getOcsClient() {
1331
+        return $this->query('OcsClient');
1332
+    }
1333
+
1334
+    /**
1335
+     * @return \OCP\IDateTimeZone
1336
+     */
1337
+    public function getDateTimeZone() {
1338
+        return $this->query('DateTimeZone');
1339
+    }
1340
+
1341
+    /**
1342
+     * @return \OCP\IDateTimeFormatter
1343
+     */
1344
+    public function getDateTimeFormatter() {
1345
+        return $this->query('DateTimeFormatter');
1346
+    }
1347
+
1348
+    /**
1349
+     * @return \OCP\Files\Config\IMountProviderCollection
1350
+     */
1351
+    public function getMountProviderCollection() {
1352
+        return $this->query('MountConfigManager');
1353
+    }
1354
+
1355
+    /**
1356
+     * Get the IniWrapper
1357
+     *
1358
+     * @return IniGetWrapper
1359
+     */
1360
+    public function getIniWrapper() {
1361
+        return $this->query('IniWrapper');
1362
+    }
1363
+
1364
+    /**
1365
+     * @return \OCP\Command\IBus
1366
+     */
1367
+    public function getCommandBus() {
1368
+        return $this->query('AsyncCommandBus');
1369
+    }
1370
+
1371
+    /**
1372
+     * Get the trusted domain helper
1373
+     *
1374
+     * @return TrustedDomainHelper
1375
+     */
1376
+    public function getTrustedDomainHelper() {
1377
+        return $this->query('TrustedDomainHelper');
1378
+    }
1379
+
1380
+    /**
1381
+     * Get the locking provider
1382
+     *
1383
+     * @return \OCP\Lock\ILockingProvider
1384
+     * @since 8.1.0
1385
+     */
1386
+    public function getLockingProvider() {
1387
+        return $this->query('LockingProvider');
1388
+    }
1389
+
1390
+    /**
1391
+     * @return \OCP\Files\Mount\IMountManager
1392
+     **/
1393
+    function getMountManager() {
1394
+        return $this->query('MountManager');
1395
+    }
1396
+
1397
+    /** @return \OCP\Files\Config\IUserMountCache */
1398
+    function getUserMountCache() {
1399
+        return $this->query('UserMountCache');
1400
+    }
1401
+
1402
+    /**
1403
+     * Get the MimeTypeDetector
1404
+     *
1405
+     * @return \OCP\Files\IMimeTypeDetector
1406
+     */
1407
+    public function getMimeTypeDetector() {
1408
+        return $this->query('MimeTypeDetector');
1409
+    }
1410
+
1411
+    /**
1412
+     * Get the MimeTypeLoader
1413
+     *
1414
+     * @return \OCP\Files\IMimeTypeLoader
1415
+     */
1416
+    public function getMimeTypeLoader() {
1417
+        return $this->query('MimeTypeLoader');
1418
+    }
1419
+
1420
+    /**
1421
+     * Get the manager of all the capabilities
1422
+     *
1423
+     * @return \OC\CapabilitiesManager
1424
+     */
1425
+    public function getCapabilitiesManager() {
1426
+        return $this->query('CapabilitiesManager');
1427
+    }
1428
+
1429
+    /**
1430
+     * Get the EventDispatcher
1431
+     *
1432
+     * @return EventDispatcherInterface
1433
+     * @since 8.2.0
1434
+     */
1435
+    public function getEventDispatcher() {
1436
+        return $this->query('EventDispatcher');
1437
+    }
1438
+
1439
+    /**
1440
+     * Get the Notification Manager
1441
+     *
1442
+     * @return \OCP\Notification\IManager
1443
+     * @since 8.2.0
1444
+     */
1445
+    public function getNotificationManager() {
1446
+        return $this->query('NotificationManager');
1447
+    }
1448
+
1449
+    /**
1450
+     * @return \OCP\Comments\ICommentsManager
1451
+     */
1452
+    public function getCommentsManager() {
1453
+        return $this->query('CommentsManager');
1454
+    }
1455
+
1456
+    /**
1457
+     * @return \OC_Defaults
1458
+     */
1459
+    public function getThemingDefaults() {
1460
+        return $this->query('ThemingDefaults');
1461
+    }
1462
+
1463
+    /**
1464
+     * @return \OC\IntegrityCheck\Checker
1465
+     */
1466
+    public function getIntegrityCodeChecker() {
1467
+        return $this->query('IntegrityCodeChecker');
1468
+    }
1469
+
1470
+    /**
1471
+     * @return \OC\Session\CryptoWrapper
1472
+     */
1473
+    public function getSessionCryptoWrapper() {
1474
+        return $this->query('CryptoWrapper');
1475
+    }
1476
+
1477
+    /**
1478
+     * @return CsrfTokenManager
1479
+     */
1480
+    public function getCsrfTokenManager() {
1481
+        return $this->query('CsrfTokenManager');
1482
+    }
1483
+
1484
+    /**
1485
+     * @return Throttler
1486
+     */
1487
+    public function getBruteForceThrottler() {
1488
+        return $this->query('Throttler');
1489
+    }
1490
+
1491
+    /**
1492
+     * @return IContentSecurityPolicyManager
1493
+     */
1494
+    public function getContentSecurityPolicyManager() {
1495
+        return $this->query('ContentSecurityPolicyManager');
1496
+    }
1497
+
1498
+    /**
1499
+     * @return ContentSecurityPolicyNonceManager
1500
+     */
1501
+    public function getContentSecurityPolicyNonceManager() {
1502
+        return $this->query('ContentSecurityPolicyNonceManager');
1503
+    }
1504
+
1505
+    /**
1506
+     * Not a public API as of 8.2, wait for 9.0
1507
+     *
1508
+     * @return \OCA\Files_External\Service\BackendService
1509
+     */
1510
+    public function getStoragesBackendService() {
1511
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1512
+    }
1513
+
1514
+    /**
1515
+     * Not a public API as of 8.2, wait for 9.0
1516
+     *
1517
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1518
+     */
1519
+    public function getGlobalStoragesService() {
1520
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1521
+    }
1522
+
1523
+    /**
1524
+     * Not a public API as of 8.2, wait for 9.0
1525
+     *
1526
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1527
+     */
1528
+    public function getUserGlobalStoragesService() {
1529
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1530
+    }
1531
+
1532
+    /**
1533
+     * Not a public API as of 8.2, wait for 9.0
1534
+     *
1535
+     * @return \OCA\Files_External\Service\UserStoragesService
1536
+     */
1537
+    public function getUserStoragesService() {
1538
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1539
+    }
1540
+
1541
+    /**
1542
+     * @return \OCP\Share\IManager
1543
+     */
1544
+    public function getShareManager() {
1545
+        return $this->query('ShareManager');
1546
+    }
1547
+
1548
+    /**
1549
+     * Returns the LDAP Provider
1550
+     *
1551
+     * @return \OCP\LDAP\ILDAPProvider
1552
+     */
1553
+    public function getLDAPProvider() {
1554
+        return $this->query('LDAPProvider');
1555
+    }
1556
+
1557
+    /**
1558
+     * @return \OCP\Settings\IManager
1559
+     */
1560
+    public function getSettingsManager() {
1561
+        return $this->query('SettingsManager');
1562
+    }
1563
+
1564
+    /**
1565
+     * @return \OCP\Files\IAppData
1566
+     */
1567
+    public function getAppDataDir($app) {
1568
+        /** @var \OC\Files\AppData\Factory $factory */
1569
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1570
+        return $factory->get($app);
1571
+    }
1572
+
1573
+    /**
1574
+     * @return \OCP\Lockdown\ILockdownManager
1575
+     */
1576
+    public function getLockdownManager() {
1577
+        return $this->query('LockdownManager');
1578
+    }
1579
+
1580
+    /**
1581
+     * @return \OCP\Federation\ICloudIdManager
1582
+     */
1583
+    public function getCloudIdManager() {
1584
+        return $this->query(ICloudIdManager::class);
1585
+    }
1586 1586
 }
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($c->getConfig());
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) {
@@ -816,23 +816,23 @@  discard block
 block discarded – undo
816 816
 			);
817 817
 			return $manager;
818 818
 		});
819
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
819
+		$this->registerService(\OC\Files\AppData\Factory::class, function(Server $c) {
820 820
 			return new \OC\Files\AppData\Factory(
821 821
 				$c->getRootFolder(),
822 822
 				$c->getSystemConfig()
823 823
 			);
824 824
 		});
825 825
 
826
-		$this->registerService('LockdownManager', function (Server $c) {
826
+		$this->registerService('LockdownManager', function(Server $c) {
827 827
 			return new LockdownManager();
828 828
 		});
829 829
 
830
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
830
+		$this->registerService(ICloudIdManager::class, function(Server $c) {
831 831
 			return new CloudIdManager();
832 832
 		});
833 833
 
834 834
 		/* To trick DI since we don't extend the DIContainer here */
835
-		$this->registerService(CleanPreviewsBackgroundJob::class, function (Server $c) {
835
+		$this->registerService(CleanPreviewsBackgroundJob::class, function(Server $c) {
836 836
 			return new CleanPreviewsBackgroundJob(
837 837
 				$c->getRootFolder(),
838 838
 				$c->getLogger(),
@@ -976,7 +976,7 @@  discard block
 block discarded – undo
976 976
 	 * @deprecated since 9.2.0 use IAppData
977 977
 	 */
978 978
 	public function getAppFolder() {
979
-		$dir = '/' . \OC_App::getCurrentApp();
979
+		$dir = '/'.\OC_App::getCurrentApp();
980 980
 		$root = $this->getRootFolder();
981 981
 		if (!$root->nodeExists($dir)) {
982 982
 			$folder = $root->newFolder($dir);
Please login to merge, or discard this patch.