Passed
Push — master ( d2f9de...0532f8 )
by Roeland
11:53 queued 14s
created
lib/private/Share20/Manager.php 1 patch
Indentation   +1607 added lines, -1607 removed lines patch added patch discarded remove patch
@@ -73,1634 +73,1634 @@
 block discarded – undo
73 73
  */
74 74
 class Manager implements IManager {
75 75
 
76
-	/** @var IProviderFactory */
77
-	private $factory;
78
-	/** @var ILogger */
79
-	private $logger;
80
-	/** @var IConfig */
81
-	private $config;
82
-	/** @var ISecureRandom */
83
-	private $secureRandom;
84
-	/** @var IHasher */
85
-	private $hasher;
86
-	/** @var IMountManager */
87
-	private $mountManager;
88
-	/** @var IGroupManager */
89
-	private $groupManager;
90
-	/** @var IL10N */
91
-	private $l;
92
-	/** @var IFactory */
93
-	private $l10nFactory;
94
-	/** @var IUserManager */
95
-	private $userManager;
96
-	/** @var IRootFolder */
97
-	private $rootFolder;
98
-	/** @var CappedMemoryCache */
99
-	private $sharingDisabledForUsersCache;
100
-	/** @var EventDispatcherInterface */
101
-	private $eventDispatcher;
102
-	/** @var LegacyHooks */
103
-	private $legacyHooks;
104
-	/** @var IMailer */
105
-	private $mailer;
106
-	/** @var IURLGenerator */
107
-	private $urlGenerator;
108
-	/** @var \OC_Defaults */
109
-	private $defaults;
110
-
111
-
112
-	/**
113
-	 * Manager constructor.
114
-	 *
115
-	 * @param ILogger $logger
116
-	 * @param IConfig $config
117
-	 * @param ISecureRandom $secureRandom
118
-	 * @param IHasher $hasher
119
-	 * @param IMountManager $mountManager
120
-	 * @param IGroupManager $groupManager
121
-	 * @param IL10N $l
122
-	 * @param IFactory $l10nFactory
123
-	 * @param IProviderFactory $factory
124
-	 * @param IUserManager $userManager
125
-	 * @param IRootFolder $rootFolder
126
-	 * @param EventDispatcherInterface $eventDispatcher
127
-	 * @param IMailer $mailer
128
-	 * @param IURLGenerator $urlGenerator
129
-	 * @param \OC_Defaults $defaults
130
-	 */
131
-	public function __construct(
132
-			ILogger $logger,
133
-			IConfig $config,
134
-			ISecureRandom $secureRandom,
135
-			IHasher $hasher,
136
-			IMountManager $mountManager,
137
-			IGroupManager $groupManager,
138
-			IL10N $l,
139
-			IFactory $l10nFactory,
140
-			IProviderFactory $factory,
141
-			IUserManager $userManager,
142
-			IRootFolder $rootFolder,
143
-			EventDispatcherInterface $eventDispatcher,
144
-			IMailer $mailer,
145
-			IURLGenerator $urlGenerator,
146
-			\OC_Defaults $defaults
147
-	) {
148
-		$this->logger = $logger;
149
-		$this->config = $config;
150
-		$this->secureRandom = $secureRandom;
151
-		$this->hasher = $hasher;
152
-		$this->mountManager = $mountManager;
153
-		$this->groupManager = $groupManager;
154
-		$this->l = $l;
155
-		$this->l10nFactory = $l10nFactory;
156
-		$this->factory = $factory;
157
-		$this->userManager = $userManager;
158
-		$this->rootFolder = $rootFolder;
159
-		$this->eventDispatcher = $eventDispatcher;
160
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
161
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
162
-		$this->mailer = $mailer;
163
-		$this->urlGenerator = $urlGenerator;
164
-		$this->defaults = $defaults;
165
-	}
166
-
167
-	/**
168
-	 * Convert from a full share id to a tuple (providerId, shareId)
169
-	 *
170
-	 * @param string $id
171
-	 * @return string[]
172
-	 */
173
-	private function splitFullId($id) {
174
-		return explode(':', $id, 2);
175
-	}
176
-
177
-	/**
178
-	 * Verify if a password meets all requirements
179
-	 *
180
-	 * @param string $password
181
-	 * @throws \Exception
182
-	 */
183
-	protected function verifyPassword($password) {
184
-		if ($password === null) {
185
-			// No password is set, check if this is allowed.
186
-			if ($this->shareApiLinkEnforcePassword()) {
187
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
188
-			}
189
-
190
-			return;
191
-		}
192
-
193
-		// Let others verify the password
194
-		try {
195
-			$this->eventDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
196
-		} catch (HintException $e) {
197
-			throw new \Exception($e->getHint());
198
-		}
199
-	}
200
-
201
-	/**
202
-	 * Check for generic requirements before creating a share
203
-	 *
204
-	 * @param \OCP\Share\IShare $share
205
-	 * @throws \InvalidArgumentException
206
-	 * @throws GenericShareException
207
-	 *
208
-	 * @suppress PhanUndeclaredClassMethod
209
-	 */
210
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
211
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
212
-			// We expect a valid user as sharedWith for user shares
213
-			if (!$this->userManager->userExists($share->getSharedWith())) {
214
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
215
-			}
216
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
217
-			// We expect a valid group as sharedWith for group shares
218
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
219
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
220
-			}
221
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
222
-			if ($share->getSharedWith() !== null) {
223
-				throw new \InvalidArgumentException('SharedWith should be empty');
224
-			}
225
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
226
-			if ($share->getSharedWith() === null) {
227
-				throw new \InvalidArgumentException('SharedWith should not be empty');
228
-			}
229
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230
-			if ($share->getSharedWith() === null) {
231
-				throw new \InvalidArgumentException('SharedWith should not be empty');
232
-			}
233
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
234
-			if ($share->getSharedWith() === null) {
235
-				throw new \InvalidArgumentException('SharedWith should not be empty');
236
-			}
237
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
239
-			if ($circle === null) {
240
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
241
-			}
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
243
-		} else {
244
-			// We can't handle other types yet
245
-			throw new \InvalidArgumentException('unknown share type');
246
-		}
247
-
248
-		// Verify the initiator of the share is set
249
-		if ($share->getSharedBy() === null) {
250
-			throw new \InvalidArgumentException('SharedBy should be set');
251
-		}
252
-
253
-		// Cannot share with yourself
254
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
255
-			$share->getSharedWith() === $share->getSharedBy()) {
256
-			throw new \InvalidArgumentException('Can’t share with yourself');
257
-		}
258
-
259
-		// The path should be set
260
-		if ($share->getNode() === null) {
261
-			throw new \InvalidArgumentException('Path should be set');
262
-		}
263
-
264
-		// And it should be a file or a folder
265
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
266
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
267
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
268
-		}
269
-
270
-		// And you can't share your rootfolder
271
-		if ($this->userManager->userExists($share->getSharedBy())) {
272
-			$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
273
-			$userFolderPath = $userFolder->getPath();
274
-		} else {
275
-			$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
276
-			$userFolderPath = $userFolder->getPath();
277
-		}
278
-		if ($userFolderPath === $share->getNode()->getPath()) {
279
-			throw new \InvalidArgumentException('You can’t share your root folder');
280
-		}
281
-
282
-		// Check if we actually have share permissions
283
-		if (!$share->getNode()->isShareable()) {
284
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
285
-			throw new GenericShareException($message_t, $message_t, 404);
286
-		}
287
-
288
-		// Permissions should be set
289
-		if ($share->getPermissions() === null) {
290
-			throw new \InvalidArgumentException('A share requires permissions');
291
-		}
292
-
293
-		$isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
294
-		$permissions = 0;
295
-		$mount = $share->getNode()->getMountPoint();
296
-		if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
297
-			// When it's a reshare use the parent share permissions as maximum
298
-			$userMountPointId = $mount->getStorageRootId();
299
-			$userMountPoints = $userFolder->getById($userMountPointId);
300
-			$userMountPoint = array_shift($userMountPoints);
301
-
302
-			/* Check if this is an incoming share */
303
-			$incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
304
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
305
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
306
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
307
-
308
-			/** @var \OCP\Share\IShare[] $incomingShares */
309
-			if (!empty($incomingShares)) {
310
-				foreach ($incomingShares as $incomingShare) {
311
-					$permissions |= $incomingShare->getPermissions();
312
-				}
313
-			}
314
-		} else {
315
-			/*
76
+    /** @var IProviderFactory */
77
+    private $factory;
78
+    /** @var ILogger */
79
+    private $logger;
80
+    /** @var IConfig */
81
+    private $config;
82
+    /** @var ISecureRandom */
83
+    private $secureRandom;
84
+    /** @var IHasher */
85
+    private $hasher;
86
+    /** @var IMountManager */
87
+    private $mountManager;
88
+    /** @var IGroupManager */
89
+    private $groupManager;
90
+    /** @var IL10N */
91
+    private $l;
92
+    /** @var IFactory */
93
+    private $l10nFactory;
94
+    /** @var IUserManager */
95
+    private $userManager;
96
+    /** @var IRootFolder */
97
+    private $rootFolder;
98
+    /** @var CappedMemoryCache */
99
+    private $sharingDisabledForUsersCache;
100
+    /** @var EventDispatcherInterface */
101
+    private $eventDispatcher;
102
+    /** @var LegacyHooks */
103
+    private $legacyHooks;
104
+    /** @var IMailer */
105
+    private $mailer;
106
+    /** @var IURLGenerator */
107
+    private $urlGenerator;
108
+    /** @var \OC_Defaults */
109
+    private $defaults;
110
+
111
+
112
+    /**
113
+     * Manager constructor.
114
+     *
115
+     * @param ILogger $logger
116
+     * @param IConfig $config
117
+     * @param ISecureRandom $secureRandom
118
+     * @param IHasher $hasher
119
+     * @param IMountManager $mountManager
120
+     * @param IGroupManager $groupManager
121
+     * @param IL10N $l
122
+     * @param IFactory $l10nFactory
123
+     * @param IProviderFactory $factory
124
+     * @param IUserManager $userManager
125
+     * @param IRootFolder $rootFolder
126
+     * @param EventDispatcherInterface $eventDispatcher
127
+     * @param IMailer $mailer
128
+     * @param IURLGenerator $urlGenerator
129
+     * @param \OC_Defaults $defaults
130
+     */
131
+    public function __construct(
132
+            ILogger $logger,
133
+            IConfig $config,
134
+            ISecureRandom $secureRandom,
135
+            IHasher $hasher,
136
+            IMountManager $mountManager,
137
+            IGroupManager $groupManager,
138
+            IL10N $l,
139
+            IFactory $l10nFactory,
140
+            IProviderFactory $factory,
141
+            IUserManager $userManager,
142
+            IRootFolder $rootFolder,
143
+            EventDispatcherInterface $eventDispatcher,
144
+            IMailer $mailer,
145
+            IURLGenerator $urlGenerator,
146
+            \OC_Defaults $defaults
147
+    ) {
148
+        $this->logger = $logger;
149
+        $this->config = $config;
150
+        $this->secureRandom = $secureRandom;
151
+        $this->hasher = $hasher;
152
+        $this->mountManager = $mountManager;
153
+        $this->groupManager = $groupManager;
154
+        $this->l = $l;
155
+        $this->l10nFactory = $l10nFactory;
156
+        $this->factory = $factory;
157
+        $this->userManager = $userManager;
158
+        $this->rootFolder = $rootFolder;
159
+        $this->eventDispatcher = $eventDispatcher;
160
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
161
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
162
+        $this->mailer = $mailer;
163
+        $this->urlGenerator = $urlGenerator;
164
+        $this->defaults = $defaults;
165
+    }
166
+
167
+    /**
168
+     * Convert from a full share id to a tuple (providerId, shareId)
169
+     *
170
+     * @param string $id
171
+     * @return string[]
172
+     */
173
+    private function splitFullId($id) {
174
+        return explode(':', $id, 2);
175
+    }
176
+
177
+    /**
178
+     * Verify if a password meets all requirements
179
+     *
180
+     * @param string $password
181
+     * @throws \Exception
182
+     */
183
+    protected function verifyPassword($password) {
184
+        if ($password === null) {
185
+            // No password is set, check if this is allowed.
186
+            if ($this->shareApiLinkEnforcePassword()) {
187
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
188
+            }
189
+
190
+            return;
191
+        }
192
+
193
+        // Let others verify the password
194
+        try {
195
+            $this->eventDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
196
+        } catch (HintException $e) {
197
+            throw new \Exception($e->getHint());
198
+        }
199
+    }
200
+
201
+    /**
202
+     * Check for generic requirements before creating a share
203
+     *
204
+     * @param \OCP\Share\IShare $share
205
+     * @throws \InvalidArgumentException
206
+     * @throws GenericShareException
207
+     *
208
+     * @suppress PhanUndeclaredClassMethod
209
+     */
210
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
211
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
212
+            // We expect a valid user as sharedWith for user shares
213
+            if (!$this->userManager->userExists($share->getSharedWith())) {
214
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
215
+            }
216
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
217
+            // We expect a valid group as sharedWith for group shares
218
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
219
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
220
+            }
221
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
222
+            if ($share->getSharedWith() !== null) {
223
+                throw new \InvalidArgumentException('SharedWith should be empty');
224
+            }
225
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
226
+            if ($share->getSharedWith() === null) {
227
+                throw new \InvalidArgumentException('SharedWith should not be empty');
228
+            }
229
+        }  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
230
+            if ($share->getSharedWith() === null) {
231
+                throw new \InvalidArgumentException('SharedWith should not be empty');
232
+            }
233
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
234
+            if ($share->getSharedWith() === null) {
235
+                throw new \InvalidArgumentException('SharedWith should not be empty');
236
+            }
237
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
238
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
239
+            if ($circle === null) {
240
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
241
+            }
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
243
+        } else {
244
+            // We can't handle other types yet
245
+            throw new \InvalidArgumentException('unknown share type');
246
+        }
247
+
248
+        // Verify the initiator of the share is set
249
+        if ($share->getSharedBy() === null) {
250
+            throw new \InvalidArgumentException('SharedBy should be set');
251
+        }
252
+
253
+        // Cannot share with yourself
254
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
255
+            $share->getSharedWith() === $share->getSharedBy()) {
256
+            throw new \InvalidArgumentException('Can’t share with yourself');
257
+        }
258
+
259
+        // The path should be set
260
+        if ($share->getNode() === null) {
261
+            throw new \InvalidArgumentException('Path should be set');
262
+        }
263
+
264
+        // And it should be a file or a folder
265
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
266
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
267
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
268
+        }
269
+
270
+        // And you can't share your rootfolder
271
+        if ($this->userManager->userExists($share->getSharedBy())) {
272
+            $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
273
+            $userFolderPath = $userFolder->getPath();
274
+        } else {
275
+            $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
276
+            $userFolderPath = $userFolder->getPath();
277
+        }
278
+        if ($userFolderPath === $share->getNode()->getPath()) {
279
+            throw new \InvalidArgumentException('You can’t share your root folder');
280
+        }
281
+
282
+        // Check if we actually have share permissions
283
+        if (!$share->getNode()->isShareable()) {
284
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
285
+            throw new GenericShareException($message_t, $message_t, 404);
286
+        }
287
+
288
+        // Permissions should be set
289
+        if ($share->getPermissions() === null) {
290
+            throw new \InvalidArgumentException('A share requires permissions');
291
+        }
292
+
293
+        $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
294
+        $permissions = 0;
295
+        $mount = $share->getNode()->getMountPoint();
296
+        if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
297
+            // When it's a reshare use the parent share permissions as maximum
298
+            $userMountPointId = $mount->getStorageRootId();
299
+            $userMountPoints = $userFolder->getById($userMountPointId);
300
+            $userMountPoint = array_shift($userMountPoints);
301
+
302
+            /* Check if this is an incoming share */
303
+            $incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
304
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
305
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
306
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
307
+
308
+            /** @var \OCP\Share\IShare[] $incomingShares */
309
+            if (!empty($incomingShares)) {
310
+                foreach ($incomingShares as $incomingShare) {
311
+                    $permissions |= $incomingShare->getPermissions();
312
+                }
313
+            }
314
+        } else {
315
+            /*
316 316
 			 * Quick fix for #23536
317 317
 			 * Non moveable mount points do not have update and delete permissions
318 318
 			 * while we 'most likely' do have that on the storage.
319 319
 			 */
320
-			$permissions = $share->getNode()->getPermissions();
321
-			if (!($mount instanceof MoveableMount)) {
322
-				$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
323
-			}
324
-		}
325
-
326
-		// Check that we do not share with more permissions than we have
327
-		if ($share->getPermissions() & ~$permissions) {
328
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
329
-			throw new GenericShareException($message_t, $message_t, 404);
330
-		}
331
-
332
-
333
-		// Check that read permissions are always set
334
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
335
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
336
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
337
-		if (!$noReadPermissionRequired &&
338
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
339
-			throw new \InvalidArgumentException('Shares need at least read permissions');
340
-		}
341
-
342
-		if ($share->getNode() instanceof \OCP\Files\File) {
343
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
344
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
345
-				throw new GenericShareException($message_t);
346
-			}
347
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
348
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
349
-				throw new GenericShareException($message_t);
350
-			}
351
-		}
352
-	}
353
-
354
-	/**
355
-	 * Validate if the expiration date fits the system settings
356
-	 *
357
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
358
-	 * @return \OCP\Share\IShare The modified share object
359
-	 * @throws GenericShareException
360
-	 * @throws \InvalidArgumentException
361
-	 * @throws \Exception
362
-	 */
363
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
364
-
365
-		$expirationDate = $share->getExpirationDate();
366
-
367
-		if ($expirationDate !== null) {
368
-			//Make sure the expiration date is a date
369
-			$expirationDate->setTime(0, 0, 0);
370
-
371
-			$date = new \DateTime();
372
-			$date->setTime(0, 0, 0);
373
-			if ($date >= $expirationDate) {
374
-				$message = $this->l->t('Expiration date is in the past');
375
-				throw new GenericShareException($message, $message, 404);
376
-			}
377
-		}
378
-
379
-		// If expiredate is empty set a default one if there is a default
380
-		$fullId = null;
381
-		try {
382
-			$fullId = $share->getFullId();
383
-		} catch (\UnexpectedValueException $e) {
384
-			// This is a new share
385
-		}
386
-
387
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
388
-			$expirationDate = new \DateTime();
389
-			$expirationDate->setTime(0,0,0);
390
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
391
-		}
392
-
393
-		// If we enforce the expiration date check that is does not exceed
394
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
395
-			if ($expirationDate === null) {
396
-				throw new \InvalidArgumentException('Expiration date is enforced');
397
-			}
398
-
399
-			$date = new \DateTime();
400
-			$date->setTime(0, 0, 0);
401
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
402
-			if ($date < $expirationDate) {
403
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
404
-				throw new GenericShareException($message, $message, 404);
405
-			}
406
-		}
407
-
408
-		$accepted = true;
409
-		$message = '';
410
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
411
-			'expirationDate' => &$expirationDate,
412
-			'accepted' => &$accepted,
413
-			'message' => &$message,
414
-			'passwordSet' => $share->getPassword() !== null,
415
-		]);
416
-
417
-		if (!$accepted) {
418
-			throw new \Exception($message);
419
-		}
420
-
421
-		$share->setExpirationDate($expirationDate);
422
-
423
-		return $share;
424
-	}
425
-
426
-	/**
427
-	 * Check for pre share requirements for user shares
428
-	 *
429
-	 * @param \OCP\Share\IShare $share
430
-	 * @throws \Exception
431
-	 */
432
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
433
-		// Check if we can share with group members only
434
-		if ($this->shareWithGroupMembersOnly()) {
435
-			$sharedBy = $this->userManager->get($share->getSharedBy());
436
-			$sharedWith = $this->userManager->get($share->getSharedWith());
437
-			// Verify we can share with this user
438
-			$groups = array_intersect(
439
-					$this->groupManager->getUserGroupIds($sharedBy),
440
-					$this->groupManager->getUserGroupIds($sharedWith)
441
-			);
442
-			if (empty($groups)) {
443
-				throw new \Exception('Sharing is only allowed with group members');
444
-			}
445
-		}
446
-
447
-		/*
320
+            $permissions = $share->getNode()->getPermissions();
321
+            if (!($mount instanceof MoveableMount)) {
322
+                $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
323
+            }
324
+        }
325
+
326
+        // Check that we do not share with more permissions than we have
327
+        if ($share->getPermissions() & ~$permissions) {
328
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
329
+            throw new GenericShareException($message_t, $message_t, 404);
330
+        }
331
+
332
+
333
+        // Check that read permissions are always set
334
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
335
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
336
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
337
+        if (!$noReadPermissionRequired &&
338
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
339
+            throw new \InvalidArgumentException('Shares need at least read permissions');
340
+        }
341
+
342
+        if ($share->getNode() instanceof \OCP\Files\File) {
343
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
344
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
345
+                throw new GenericShareException($message_t);
346
+            }
347
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
348
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
349
+                throw new GenericShareException($message_t);
350
+            }
351
+        }
352
+    }
353
+
354
+    /**
355
+     * Validate if the expiration date fits the system settings
356
+     *
357
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
358
+     * @return \OCP\Share\IShare The modified share object
359
+     * @throws GenericShareException
360
+     * @throws \InvalidArgumentException
361
+     * @throws \Exception
362
+     */
363
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
364
+
365
+        $expirationDate = $share->getExpirationDate();
366
+
367
+        if ($expirationDate !== null) {
368
+            //Make sure the expiration date is a date
369
+            $expirationDate->setTime(0, 0, 0);
370
+
371
+            $date = new \DateTime();
372
+            $date->setTime(0, 0, 0);
373
+            if ($date >= $expirationDate) {
374
+                $message = $this->l->t('Expiration date is in the past');
375
+                throw new GenericShareException($message, $message, 404);
376
+            }
377
+        }
378
+
379
+        // If expiredate is empty set a default one if there is a default
380
+        $fullId = null;
381
+        try {
382
+            $fullId = $share->getFullId();
383
+        } catch (\UnexpectedValueException $e) {
384
+            // This is a new share
385
+        }
386
+
387
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
388
+            $expirationDate = new \DateTime();
389
+            $expirationDate->setTime(0,0,0);
390
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
391
+        }
392
+
393
+        // If we enforce the expiration date check that is does not exceed
394
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
395
+            if ($expirationDate === null) {
396
+                throw new \InvalidArgumentException('Expiration date is enforced');
397
+            }
398
+
399
+            $date = new \DateTime();
400
+            $date->setTime(0, 0, 0);
401
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
402
+            if ($date < $expirationDate) {
403
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
404
+                throw new GenericShareException($message, $message, 404);
405
+            }
406
+        }
407
+
408
+        $accepted = true;
409
+        $message = '';
410
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
411
+            'expirationDate' => &$expirationDate,
412
+            'accepted' => &$accepted,
413
+            'message' => &$message,
414
+            'passwordSet' => $share->getPassword() !== null,
415
+        ]);
416
+
417
+        if (!$accepted) {
418
+            throw new \Exception($message);
419
+        }
420
+
421
+        $share->setExpirationDate($expirationDate);
422
+
423
+        return $share;
424
+    }
425
+
426
+    /**
427
+     * Check for pre share requirements for user shares
428
+     *
429
+     * @param \OCP\Share\IShare $share
430
+     * @throws \Exception
431
+     */
432
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
433
+        // Check if we can share with group members only
434
+        if ($this->shareWithGroupMembersOnly()) {
435
+            $sharedBy = $this->userManager->get($share->getSharedBy());
436
+            $sharedWith = $this->userManager->get($share->getSharedWith());
437
+            // Verify we can share with this user
438
+            $groups = array_intersect(
439
+                    $this->groupManager->getUserGroupIds($sharedBy),
440
+                    $this->groupManager->getUserGroupIds($sharedWith)
441
+            );
442
+            if (empty($groups)) {
443
+                throw new \Exception('Sharing is only allowed with group members');
444
+            }
445
+        }
446
+
447
+        /*
448 448
 		 * TODO: Could be costly, fix
449 449
 		 *
450 450
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
451 451
 		 */
452
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
453
-		$existingShares = $provider->getSharesByPath($share->getNode());
454
-		foreach($existingShares as $existingShare) {
455
-			// Ignore if it is the same share
456
-			try {
457
-				if ($existingShare->getFullId() === $share->getFullId()) {
458
-					continue;
459
-				}
460
-			} catch (\UnexpectedValueException $e) {
461
-				//Shares are not identical
462
-			}
463
-
464
-			// Identical share already existst
465
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
466
-				throw new \Exception('Path is already shared with this user');
467
-			}
468
-
469
-			// The share is already shared with this user via a group share
470
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
471
-				$group = $this->groupManager->get($existingShare->getSharedWith());
472
-				if (!is_null($group)) {
473
-					$user = $this->userManager->get($share->getSharedWith());
474
-
475
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
476
-						throw new \Exception('Path is already shared with this user');
477
-					}
478
-				}
479
-			}
480
-		}
481
-	}
482
-
483
-	/**
484
-	 * Check for pre share requirements for group shares
485
-	 *
486
-	 * @param \OCP\Share\IShare $share
487
-	 * @throws \Exception
488
-	 */
489
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
490
-		// Verify group shares are allowed
491
-		if (!$this->allowGroupSharing()) {
492
-			throw new \Exception('Group sharing is now allowed');
493
-		}
494
-
495
-		// Verify if the user can share with this group
496
-		if ($this->shareWithGroupMembersOnly()) {
497
-			$sharedBy = $this->userManager->get($share->getSharedBy());
498
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
499
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
500
-				throw new \Exception('Sharing is only allowed within your own groups');
501
-			}
502
-		}
503
-
504
-		/*
452
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
453
+        $existingShares = $provider->getSharesByPath($share->getNode());
454
+        foreach($existingShares as $existingShare) {
455
+            // Ignore if it is the same share
456
+            try {
457
+                if ($existingShare->getFullId() === $share->getFullId()) {
458
+                    continue;
459
+                }
460
+            } catch (\UnexpectedValueException $e) {
461
+                //Shares are not identical
462
+            }
463
+
464
+            // Identical share already existst
465
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
466
+                throw new \Exception('Path is already shared with this user');
467
+            }
468
+
469
+            // The share is already shared with this user via a group share
470
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
471
+                $group = $this->groupManager->get($existingShare->getSharedWith());
472
+                if (!is_null($group)) {
473
+                    $user = $this->userManager->get($share->getSharedWith());
474
+
475
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
476
+                        throw new \Exception('Path is already shared with this user');
477
+                    }
478
+                }
479
+            }
480
+        }
481
+    }
482
+
483
+    /**
484
+     * Check for pre share requirements for group shares
485
+     *
486
+     * @param \OCP\Share\IShare $share
487
+     * @throws \Exception
488
+     */
489
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
490
+        // Verify group shares are allowed
491
+        if (!$this->allowGroupSharing()) {
492
+            throw new \Exception('Group sharing is now allowed');
493
+        }
494
+
495
+        // Verify if the user can share with this group
496
+        if ($this->shareWithGroupMembersOnly()) {
497
+            $sharedBy = $this->userManager->get($share->getSharedBy());
498
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
499
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
500
+                throw new \Exception('Sharing is only allowed within your own groups');
501
+            }
502
+        }
503
+
504
+        /*
505 505
 		 * TODO: Could be costly, fix
506 506
 		 *
507 507
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
508 508
 		 */
509
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
510
-		$existingShares = $provider->getSharesByPath($share->getNode());
511
-		foreach($existingShares as $existingShare) {
512
-			try {
513
-				if ($existingShare->getFullId() === $share->getFullId()) {
514
-					continue;
515
-				}
516
-			} catch (\UnexpectedValueException $e) {
517
-				//It is a new share so just continue
518
-			}
519
-
520
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
521
-				throw new \Exception('Path is already shared with this group');
522
-			}
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * Check for pre share requirements for link shares
528
-	 *
529
-	 * @param \OCP\Share\IShare $share
530
-	 * @throws \Exception
531
-	 */
532
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
533
-		// Are link shares allowed?
534
-		if (!$this->shareApiAllowLinks()) {
535
-			throw new \Exception('Link sharing is not allowed');
536
-		}
537
-
538
-		// Link shares by definition can't have share permissions
539
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
540
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
541
-		}
542
-
543
-		// Check if public upload is allowed
544
-		if (!$this->shareApiLinkAllowPublicUpload() &&
545
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
546
-			throw new \InvalidArgumentException('Public upload is not allowed');
547
-		}
548
-	}
549
-
550
-	/**
551
-	 * To make sure we don't get invisible link shares we set the parent
552
-	 * of a link if it is a reshare. This is a quick word around
553
-	 * until we can properly display multiple link shares in the UI
554
-	 *
555
-	 * See: https://github.com/owncloud/core/issues/22295
556
-	 *
557
-	 * FIXME: Remove once multiple link shares can be properly displayed
558
-	 *
559
-	 * @param \OCP\Share\IShare $share
560
-	 */
561
-	protected function setLinkParent(\OCP\Share\IShare $share) {
562
-
563
-		// No sense in checking if the method is not there.
564
-		if (method_exists($share, 'setParent')) {
565
-			$storage = $share->getNode()->getStorage();
566
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
567
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
568
-				$share->setParent($storage->getShareId());
569
-			}
570
-		}
571
-	}
572
-
573
-	/**
574
-	 * @param File|Folder $path
575
-	 */
576
-	protected function pathCreateChecks($path) {
577
-		// Make sure that we do not share a path that contains a shared mountpoint
578
-		if ($path instanceof \OCP\Files\Folder) {
579
-			$mounts = $this->mountManager->findIn($path->getPath());
580
-			foreach($mounts as $mount) {
581
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
582
-					throw new \InvalidArgumentException('Path contains files shared with you');
583
-				}
584
-			}
585
-		}
586
-	}
587
-
588
-	/**
589
-	 * Check if the user that is sharing can actually share
590
-	 *
591
-	 * @param \OCP\Share\IShare $share
592
-	 * @throws \Exception
593
-	 */
594
-	protected function canShare(\OCP\Share\IShare $share) {
595
-		if (!$this->shareApiEnabled()) {
596
-			throw new \Exception('Sharing is disabled');
597
-		}
598
-
599
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
600
-			throw new \Exception('Sharing is disabled for you');
601
-		}
602
-	}
603
-
604
-	/**
605
-	 * Share a path
606
-	 *
607
-	 * @param \OCP\Share\IShare $share
608
-	 * @return Share The share object
609
-	 * @throws \Exception
610
-	 *
611
-	 * TODO: handle link share permissions or check them
612
-	 */
613
-	public function createShare(\OCP\Share\IShare $share) {
614
-		$this->canShare($share);
615
-
616
-		$this->generalCreateChecks($share);
617
-
618
-		// Verify if there are any issues with the path
619
-		$this->pathCreateChecks($share->getNode());
620
-
621
-		/*
509
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
510
+        $existingShares = $provider->getSharesByPath($share->getNode());
511
+        foreach($existingShares as $existingShare) {
512
+            try {
513
+                if ($existingShare->getFullId() === $share->getFullId()) {
514
+                    continue;
515
+                }
516
+            } catch (\UnexpectedValueException $e) {
517
+                //It is a new share so just continue
518
+            }
519
+
520
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
521
+                throw new \Exception('Path is already shared with this group');
522
+            }
523
+        }
524
+    }
525
+
526
+    /**
527
+     * Check for pre share requirements for link shares
528
+     *
529
+     * @param \OCP\Share\IShare $share
530
+     * @throws \Exception
531
+     */
532
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
533
+        // Are link shares allowed?
534
+        if (!$this->shareApiAllowLinks()) {
535
+            throw new \Exception('Link sharing is not allowed');
536
+        }
537
+
538
+        // Link shares by definition can't have share permissions
539
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
540
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
541
+        }
542
+
543
+        // Check if public upload is allowed
544
+        if (!$this->shareApiLinkAllowPublicUpload() &&
545
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
546
+            throw new \InvalidArgumentException('Public upload is not allowed');
547
+        }
548
+    }
549
+
550
+    /**
551
+     * To make sure we don't get invisible link shares we set the parent
552
+     * of a link if it is a reshare. This is a quick word around
553
+     * until we can properly display multiple link shares in the UI
554
+     *
555
+     * See: https://github.com/owncloud/core/issues/22295
556
+     *
557
+     * FIXME: Remove once multiple link shares can be properly displayed
558
+     *
559
+     * @param \OCP\Share\IShare $share
560
+     */
561
+    protected function setLinkParent(\OCP\Share\IShare $share) {
562
+
563
+        // No sense in checking if the method is not there.
564
+        if (method_exists($share, 'setParent')) {
565
+            $storage = $share->getNode()->getStorage();
566
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
567
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
568
+                $share->setParent($storage->getShareId());
569
+            }
570
+        }
571
+    }
572
+
573
+    /**
574
+     * @param File|Folder $path
575
+     */
576
+    protected function pathCreateChecks($path) {
577
+        // Make sure that we do not share a path that contains a shared mountpoint
578
+        if ($path instanceof \OCP\Files\Folder) {
579
+            $mounts = $this->mountManager->findIn($path->getPath());
580
+            foreach($mounts as $mount) {
581
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
582
+                    throw new \InvalidArgumentException('Path contains files shared with you');
583
+                }
584
+            }
585
+        }
586
+    }
587
+
588
+    /**
589
+     * Check if the user that is sharing can actually share
590
+     *
591
+     * @param \OCP\Share\IShare $share
592
+     * @throws \Exception
593
+     */
594
+    protected function canShare(\OCP\Share\IShare $share) {
595
+        if (!$this->shareApiEnabled()) {
596
+            throw new \Exception('Sharing is disabled');
597
+        }
598
+
599
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
600
+            throw new \Exception('Sharing is disabled for you');
601
+        }
602
+    }
603
+
604
+    /**
605
+     * Share a path
606
+     *
607
+     * @param \OCP\Share\IShare $share
608
+     * @return Share The share object
609
+     * @throws \Exception
610
+     *
611
+     * TODO: handle link share permissions or check them
612
+     */
613
+    public function createShare(\OCP\Share\IShare $share) {
614
+        $this->canShare($share);
615
+
616
+        $this->generalCreateChecks($share);
617
+
618
+        // Verify if there are any issues with the path
619
+        $this->pathCreateChecks($share->getNode());
620
+
621
+        /*
622 622
 		 * On creation of a share the owner is always the owner of the path
623 623
 		 * Except for mounted federated shares.
624 624
 		 */
625
-		$storage = $share->getNode()->getStorage();
626
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
627
-			$parent = $share->getNode()->getParent();
628
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
629
-				$parent = $parent->getParent();
630
-			}
631
-			$share->setShareOwner($parent->getOwner()->getUID());
632
-		} else {
633
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
634
-		}
635
-
636
-		//Verify share type
637
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
638
-			$this->userCreateChecks($share);
639
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
640
-			$this->groupCreateChecks($share);
641
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
642
-			$this->linkCreateChecks($share);
643
-			$this->setLinkParent($share);
644
-
645
-			/*
625
+        $storage = $share->getNode()->getStorage();
626
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
627
+            $parent = $share->getNode()->getParent();
628
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
629
+                $parent = $parent->getParent();
630
+            }
631
+            $share->setShareOwner($parent->getOwner()->getUID());
632
+        } else {
633
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
634
+        }
635
+
636
+        //Verify share type
637
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
638
+            $this->userCreateChecks($share);
639
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
640
+            $this->groupCreateChecks($share);
641
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
642
+            $this->linkCreateChecks($share);
643
+            $this->setLinkParent($share);
644
+
645
+            /*
646 646
 			 * For now ignore a set token.
647 647
 			 */
648
-			$share->setToken(
649
-				$this->secureRandom->generate(
650
-					\OC\Share\Constants::TOKEN_LENGTH,
651
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
652
-				)
653
-			);
654
-
655
-			//Verify the expiration date
656
-			$this->validateExpirationDate($share);
657
-
658
-			//Verify the password
659
-			$this->verifyPassword($share->getPassword());
660
-
661
-			// If a password is set. Hash it!
662
-			if ($share->getPassword() !== null) {
663
-				$share->setPassword($this->hasher->hash($share->getPassword()));
664
-			}
665
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
666
-			$share->setToken(
667
-				$this->secureRandom->generate(
668
-					\OC\Share\Constants::TOKEN_LENGTH,
669
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
670
-				)
671
-			);
672
-		}
673
-
674
-		// Cannot share with the owner
675
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
676
-			$share->getSharedWith() === $share->getShareOwner()) {
677
-			throw new \InvalidArgumentException('Can’t share with the share owner');
678
-		}
679
-
680
-		// Generate the target
681
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
682
-		$target = \OC\Files\Filesystem::normalizePath($target);
683
-		$share->setTarget($target);
684
-
685
-		// Pre share event
686
-		$event = new GenericEvent($share);
687
-		$this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
688
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
689
-			throw new \Exception($event->getArgument('error'));
690
-		}
691
-
692
-		$oldShare = $share;
693
-		$provider = $this->factory->getProviderForType($share->getShareType());
694
-		$share = $provider->create($share);
695
-		//reuse the node we already have
696
-		$share->setNode($oldShare->getNode());
697
-
698
-		// Post share event
699
-		$event = new GenericEvent($share);
700
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
701
-
702
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
703
-			$mailSend = $share->getMailSend();
704
-			if($mailSend === true) {
705
-				$user = $this->userManager->get($share->getSharedWith());
706
-				if ($user !== null) {
707
-					$emailAddress = $user->getEMailAddress();
708
-					if ($emailAddress !== null && $emailAddress !== '') {
709
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
710
-						$l = $this->l10nFactory->get('lib', $userLang);
711
-						$this->sendMailNotification(
712
-							$l,
713
-							$share->getNode()->getName(),
714
-							$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
715
-							$share->getSharedBy(),
716
-							$emailAddress,
717
-							$share->getExpirationDate()
718
-						);
719
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
720
-					} else {
721
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
722
-					}
723
-				} else {
724
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
725
-				}
726
-			} else {
727
-				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
728
-			}
729
-		}
730
-
731
-		return $share;
732
-	}
733
-
734
-	/**
735
-	 * Send mail notifications
736
-	 *
737
-	 * This method will catch and log mail transmission errors
738
-	 *
739
-	 * @param IL10N $l Language of the recipient
740
-	 * @param string $filename file/folder name
741
-	 * @param string $link link to the file/folder
742
-	 * @param string $initiator user ID of share sender
743
-	 * @param string $shareWith email address of share receiver
744
-	 * @param \DateTime|null $expiration
745
-	 */
746
-	protected function sendMailNotification(IL10N $l,
747
-											$filename,
748
-											$link,
749
-											$initiator,
750
-											$shareWith,
751
-											\DateTime $expiration = null) {
752
-		$initiatorUser = $this->userManager->get($initiator);
753
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
754
-
755
-		$message = $this->mailer->createMessage();
756
-
757
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
758
-			'filename' => $filename,
759
-			'link' => $link,
760
-			'initiator' => $initiatorDisplayName,
761
-			'expiration' => $expiration,
762
-			'shareWith' => $shareWith,
763
-		]);
764
-
765
-		$emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
766
-		$emailTemplate->addHeader();
767
-		$emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
768
-		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
769
-
770
-		$emailTemplate->addBodyText(
771
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
772
-			$text
773
-		);
774
-		$emailTemplate->addBodyButton(
775
-			$l->t('Open »%s«', [$filename]),
776
-			$link
777
-		);
778
-
779
-		$message->setTo([$shareWith]);
780
-
781
-		// The "From" contains the sharers name
782
-		$instanceName = $this->defaults->getName();
783
-		$senderName = $l->t(
784
-			'%1$s via %2$s',
785
-			[
786
-				$initiatorDisplayName,
787
-				$instanceName
788
-			]
789
-		);
790
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
791
-
792
-		// The "Reply-To" is set to the sharer if an mail address is configured
793
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
794
-		$initiatorEmail = $initiatorUser->getEMailAddress();
795
-		if($initiatorEmail !== null) {
796
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
797
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
798
-		} else {
799
-			$emailTemplate->addFooter();
800
-		}
801
-
802
-		$message->useTemplate($emailTemplate);
803
-		try {
804
-			$failedRecipients = $this->mailer->send($message);
805
-			if(!empty($failedRecipients)) {
806
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
807
-				return;
808
-			}
809
-		} catch (\Exception $e) {
810
-			$this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
811
-		}
812
-	}
813
-
814
-	/**
815
-	 * Update a share
816
-	 *
817
-	 * @param \OCP\Share\IShare $share
818
-	 * @return \OCP\Share\IShare The share object
819
-	 * @throws \InvalidArgumentException
820
-	 */
821
-	public function updateShare(\OCP\Share\IShare $share) {
822
-		$expirationDateUpdated = false;
823
-
824
-		$this->canShare($share);
825
-
826
-		try {
827
-			$originalShare = $this->getShareById($share->getFullId());
828
-		} catch (\UnexpectedValueException $e) {
829
-			throw new \InvalidArgumentException('Share does not have a full id');
830
-		}
831
-
832
-		// We can't change the share type!
833
-		if ($share->getShareType() !== $originalShare->getShareType()) {
834
-			throw new \InvalidArgumentException('Can’t change share type');
835
-		}
836
-
837
-		// We can only change the recipient on user shares
838
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
839
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
840
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
841
-		}
842
-
843
-		// Cannot share with the owner
844
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
845
-			$share->getSharedWith() === $share->getShareOwner()) {
846
-			throw new \InvalidArgumentException('Can’t share with the share owner');
847
-		}
848
-
849
-		$this->generalCreateChecks($share);
850
-
851
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
852
-			$this->userCreateChecks($share);
853
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
854
-			$this->groupCreateChecks($share);
855
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
856
-			$this->linkCreateChecks($share);
857
-
858
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
859
-
860
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
861
-				//Verify the expiration date
862
-				$this->validateExpirationDate($share);
863
-				$expirationDateUpdated = true;
864
-			}
865
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
866
-			// The new password is not set again if it is the same as the old
867
-			// one, unless when switching from sending by Talk to sending by
868
-			// mail.
869
-			$plainTextPassword = $share->getPassword();
870
-			if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
871
-					!($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
872
-				$plainTextPassword = null;
873
-			}
874
-			if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
875
-				// If the same password was already sent by mail the recipient
876
-				// would already have access to the share without having to call
877
-				// the sharer to verify her identity
878
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
879
-			}
880
-		}
881
-
882
-		$this->pathCreateChecks($share->getNode());
883
-
884
-		// Now update the share!
885
-		$provider = $this->factory->getProviderForType($share->getShareType());
886
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
887
-			$share = $provider->update($share, $plainTextPassword);
888
-		} else {
889
-			$share = $provider->update($share);
890
-		}
891
-
892
-		if ($expirationDateUpdated === true) {
893
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
894
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
895
-				'itemSource' => $share->getNode()->getId(),
896
-				'date' => $share->getExpirationDate(),
897
-				'uidOwner' => $share->getSharedBy(),
898
-			]);
899
-		}
900
-
901
-		if ($share->getPassword() !== $originalShare->getPassword()) {
902
-			\OC_Hook::emit(Share::class, 'post_update_password', [
903
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
904
-				'itemSource' => $share->getNode()->getId(),
905
-				'uidOwner' => $share->getSharedBy(),
906
-				'token' => $share->getToken(),
907
-				'disabled' => is_null($share->getPassword()),
908
-			]);
909
-		}
910
-
911
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
912
-			if ($this->userManager->userExists($share->getShareOwner())) {
913
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
914
-			} else {
915
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
916
-			}
917
-			\OC_Hook::emit(Share::class, 'post_update_permissions', array(
918
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
919
-				'itemSource' => $share->getNode()->getId(),
920
-				'shareType' => $share->getShareType(),
921
-				'shareWith' => $share->getSharedWith(),
922
-				'uidOwner' => $share->getSharedBy(),
923
-				'permissions' => $share->getPermissions(),
924
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
925
-			));
926
-		}
927
-
928
-		return $share;
929
-	}
930
-
931
-	/**
932
-	 * Accept a share.
933
-	 *
934
-	 * @param IShare $share
935
-	 * @param string $recipientId
936
-	 * @return IShare The share object
937
-	 * @throws \InvalidArgumentException
938
-	 * @since 9.0.0
939
-	 */
940
-	public function acceptShare(IShare $share, string $recipientId): IShare {
941
-		[$providerId, ] = $this->splitFullId($share->getFullId());
942
-		$provider = $this->factory->getProvider($providerId);
943
-
944
-		if (!method_exists($provider, 'acceptShare')) {
945
-			// TODO FIX ME
946
-			throw new \InvalidArgumentException('Share provider does not support accepting');
947
-		}
948
-		$provider->acceptShare($share, $recipientId);
949
-		$event = new GenericEvent($share);
950
-		$this->eventDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
951
-
952
-		return $share;
953
-	}
954
-
955
-	/**
956
-	 * Updates the password of the given share if it is not the same as the
957
-	 * password of the original share.
958
-	 *
959
-	 * @param \OCP\Share\IShare $share the share to update its password.
960
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
961
-	 *        password with.
962
-	 * @return boolean whether the password was updated or not.
963
-	 */
964
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
965
-		// Password updated.
966
-		if ($share->getPassword() !== $originalShare->getPassword()) {
967
-			//Verify the password
968
-			$this->verifyPassword($share->getPassword());
969
-
970
-			// If a password is set. Hash it!
971
-			if ($share->getPassword() !== null) {
972
-				$share->setPassword($this->hasher->hash($share->getPassword()));
973
-
974
-				return true;
975
-			}
976
-		}
977
-
978
-		return false;
979
-	}
980
-
981
-	/**
982
-	 * Delete all the children of this share
983
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
984
-	 *
985
-	 * @param \OCP\Share\IShare $share
986
-	 * @return \OCP\Share\IShare[] List of deleted shares
987
-	 */
988
-	protected function deleteChildren(\OCP\Share\IShare $share) {
989
-		$deletedShares = [];
990
-
991
-		$provider = $this->factory->getProviderForType($share->getShareType());
992
-
993
-		foreach ($provider->getChildren($share) as $child) {
994
-			$deletedChildren = $this->deleteChildren($child);
995
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
996
-
997
-			$provider->delete($child);
998
-			$deletedShares[] = $child;
999
-		}
1000
-
1001
-		return $deletedShares;
1002
-	}
1003
-
1004
-	/**
1005
-	 * Delete a share
1006
-	 *
1007
-	 * @param \OCP\Share\IShare $share
1008
-	 * @throws ShareNotFound
1009
-	 * @throws \InvalidArgumentException
1010
-	 */
1011
-	public function deleteShare(\OCP\Share\IShare $share) {
1012
-
1013
-		try {
1014
-			$share->getFullId();
1015
-		} catch (\UnexpectedValueException $e) {
1016
-			throw new \InvalidArgumentException('Share does not have a full id');
1017
-		}
1018
-
1019
-		$event = new GenericEvent($share);
1020
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
1021
-
1022
-		// Get all children and delete them as well
1023
-		$deletedShares = $this->deleteChildren($share);
1024
-
1025
-		// Do the actual delete
1026
-		$provider = $this->factory->getProviderForType($share->getShareType());
1027
-		$provider->delete($share);
1028
-
1029
-		// All the deleted shares caused by this delete
1030
-		$deletedShares[] = $share;
1031
-
1032
-		// Emit post hook
1033
-		$event->setArgument('deletedShares', $deletedShares);
1034
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
1035
-	}
1036
-
1037
-
1038
-	/**
1039
-	 * Unshare a file as the recipient.
1040
-	 * This can be different from a regular delete for example when one of
1041
-	 * the users in a groups deletes that share. But the provider should
1042
-	 * handle this.
1043
-	 *
1044
-	 * @param \OCP\Share\IShare $share
1045
-	 * @param string $recipientId
1046
-	 */
1047
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1048
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1049
-		$provider = $this->factory->getProvider($providerId);
1050
-
1051
-		$provider->deleteFromSelf($share, $recipientId);
1052
-		$event = new GenericEvent($share);
1053
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1054
-	}
1055
-
1056
-	public function restoreShare(IShare $share, string $recipientId): IShare {
1057
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1058
-		$provider = $this->factory->getProvider($providerId);
1059
-
1060
-		return $provider->restore($share, $recipientId);
1061
-	}
1062
-
1063
-	/**
1064
-	 * @inheritdoc
1065
-	 */
1066
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1067
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1068
-			throw new \InvalidArgumentException('Can’t change target of link share');
1069
-		}
1070
-
1071
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1072
-			throw new \InvalidArgumentException('Invalid recipient');
1073
-		}
1074
-
1075
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1076
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1077
-			if (is_null($sharedWith)) {
1078
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1079
-			}
1080
-			$recipient = $this->userManager->get($recipientId);
1081
-			if (!$sharedWith->inGroup($recipient)) {
1082
-				throw new \InvalidArgumentException('Invalid recipient');
1083
-			}
1084
-		}
1085
-
1086
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1087
-		$provider = $this->factory->getProvider($providerId);
1088
-
1089
-		$provider->move($share, $recipientId);
1090
-	}
1091
-
1092
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1093
-		$providers = $this->factory->getAllProviders();
1094
-
1095
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1096
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1097
-			foreach ($newShares as $fid => $data) {
1098
-				if (!isset($shares[$fid])) {
1099
-					$shares[$fid] = [];
1100
-				}
1101
-
1102
-				$shares[$fid] = array_merge($shares[$fid], $data);
1103
-			}
1104
-			return $shares;
1105
-		}, []);
1106
-	}
1107
-
1108
-	/**
1109
-	 * @inheritdoc
1110
-	 */
1111
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1112
-		if ($path !== null &&
1113
-				!($path instanceof \OCP\Files\File) &&
1114
-				!($path instanceof \OCP\Files\Folder)) {
1115
-			throw new \InvalidArgumentException('invalid path');
1116
-		}
1117
-
1118
-		try {
1119
-			$provider = $this->factory->getProviderForType($shareType);
1120
-		} catch (ProviderException $e) {
1121
-			return [];
1122
-		}
1123
-
1124
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1125
-
1126
-		/*
648
+            $share->setToken(
649
+                $this->secureRandom->generate(
650
+                    \OC\Share\Constants::TOKEN_LENGTH,
651
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
652
+                )
653
+            );
654
+
655
+            //Verify the expiration date
656
+            $this->validateExpirationDate($share);
657
+
658
+            //Verify the password
659
+            $this->verifyPassword($share->getPassword());
660
+
661
+            // If a password is set. Hash it!
662
+            if ($share->getPassword() !== null) {
663
+                $share->setPassword($this->hasher->hash($share->getPassword()));
664
+            }
665
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
666
+            $share->setToken(
667
+                $this->secureRandom->generate(
668
+                    \OC\Share\Constants::TOKEN_LENGTH,
669
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
670
+                )
671
+            );
672
+        }
673
+
674
+        // Cannot share with the owner
675
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
676
+            $share->getSharedWith() === $share->getShareOwner()) {
677
+            throw new \InvalidArgumentException('Can’t share with the share owner');
678
+        }
679
+
680
+        // Generate the target
681
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
682
+        $target = \OC\Files\Filesystem::normalizePath($target);
683
+        $share->setTarget($target);
684
+
685
+        // Pre share event
686
+        $event = new GenericEvent($share);
687
+        $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
688
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
689
+            throw new \Exception($event->getArgument('error'));
690
+        }
691
+
692
+        $oldShare = $share;
693
+        $provider = $this->factory->getProviderForType($share->getShareType());
694
+        $share = $provider->create($share);
695
+        //reuse the node we already have
696
+        $share->setNode($oldShare->getNode());
697
+
698
+        // Post share event
699
+        $event = new GenericEvent($share);
700
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
701
+
702
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
703
+            $mailSend = $share->getMailSend();
704
+            if($mailSend === true) {
705
+                $user = $this->userManager->get($share->getSharedWith());
706
+                if ($user !== null) {
707
+                    $emailAddress = $user->getEMailAddress();
708
+                    if ($emailAddress !== null && $emailAddress !== '') {
709
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
710
+                        $l = $this->l10nFactory->get('lib', $userLang);
711
+                        $this->sendMailNotification(
712
+                            $l,
713
+                            $share->getNode()->getName(),
714
+                            $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
715
+                            $share->getSharedBy(),
716
+                            $emailAddress,
717
+                            $share->getExpirationDate()
718
+                        );
719
+                        $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
720
+                    } else {
721
+                        $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
722
+                    }
723
+                } else {
724
+                    $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
725
+                }
726
+            } else {
727
+                $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
728
+            }
729
+        }
730
+
731
+        return $share;
732
+    }
733
+
734
+    /**
735
+     * Send mail notifications
736
+     *
737
+     * This method will catch and log mail transmission errors
738
+     *
739
+     * @param IL10N $l Language of the recipient
740
+     * @param string $filename file/folder name
741
+     * @param string $link link to the file/folder
742
+     * @param string $initiator user ID of share sender
743
+     * @param string $shareWith email address of share receiver
744
+     * @param \DateTime|null $expiration
745
+     */
746
+    protected function sendMailNotification(IL10N $l,
747
+                                            $filename,
748
+                                            $link,
749
+                                            $initiator,
750
+                                            $shareWith,
751
+                                            \DateTime $expiration = null) {
752
+        $initiatorUser = $this->userManager->get($initiator);
753
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
754
+
755
+        $message = $this->mailer->createMessage();
756
+
757
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
758
+            'filename' => $filename,
759
+            'link' => $link,
760
+            'initiator' => $initiatorDisplayName,
761
+            'expiration' => $expiration,
762
+            'shareWith' => $shareWith,
763
+        ]);
764
+
765
+        $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', array($initiatorDisplayName, $filename)));
766
+        $emailTemplate->addHeader();
767
+        $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
768
+        $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
769
+
770
+        $emailTemplate->addBodyText(
771
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
772
+            $text
773
+        );
774
+        $emailTemplate->addBodyButton(
775
+            $l->t('Open »%s«', [$filename]),
776
+            $link
777
+        );
778
+
779
+        $message->setTo([$shareWith]);
780
+
781
+        // The "From" contains the sharers name
782
+        $instanceName = $this->defaults->getName();
783
+        $senderName = $l->t(
784
+            '%1$s via %2$s',
785
+            [
786
+                $initiatorDisplayName,
787
+                $instanceName
788
+            ]
789
+        );
790
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
791
+
792
+        // The "Reply-To" is set to the sharer if an mail address is configured
793
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
794
+        $initiatorEmail = $initiatorUser->getEMailAddress();
795
+        if($initiatorEmail !== null) {
796
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
797
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
798
+        } else {
799
+            $emailTemplate->addFooter();
800
+        }
801
+
802
+        $message->useTemplate($emailTemplate);
803
+        try {
804
+            $failedRecipients = $this->mailer->send($message);
805
+            if(!empty($failedRecipients)) {
806
+                $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
807
+                return;
808
+            }
809
+        } catch (\Exception $e) {
810
+            $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
811
+        }
812
+    }
813
+
814
+    /**
815
+     * Update a share
816
+     *
817
+     * @param \OCP\Share\IShare $share
818
+     * @return \OCP\Share\IShare The share object
819
+     * @throws \InvalidArgumentException
820
+     */
821
+    public function updateShare(\OCP\Share\IShare $share) {
822
+        $expirationDateUpdated = false;
823
+
824
+        $this->canShare($share);
825
+
826
+        try {
827
+            $originalShare = $this->getShareById($share->getFullId());
828
+        } catch (\UnexpectedValueException $e) {
829
+            throw new \InvalidArgumentException('Share does not have a full id');
830
+        }
831
+
832
+        // We can't change the share type!
833
+        if ($share->getShareType() !== $originalShare->getShareType()) {
834
+            throw new \InvalidArgumentException('Can’t change share type');
835
+        }
836
+
837
+        // We can only change the recipient on user shares
838
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
839
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
840
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
841
+        }
842
+
843
+        // Cannot share with the owner
844
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
845
+            $share->getSharedWith() === $share->getShareOwner()) {
846
+            throw new \InvalidArgumentException('Can’t share with the share owner');
847
+        }
848
+
849
+        $this->generalCreateChecks($share);
850
+
851
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
852
+            $this->userCreateChecks($share);
853
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
854
+            $this->groupCreateChecks($share);
855
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
856
+            $this->linkCreateChecks($share);
857
+
858
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
859
+
860
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
861
+                //Verify the expiration date
862
+                $this->validateExpirationDate($share);
863
+                $expirationDateUpdated = true;
864
+            }
865
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
866
+            // The new password is not set again if it is the same as the old
867
+            // one, unless when switching from sending by Talk to sending by
868
+            // mail.
869
+            $plainTextPassword = $share->getPassword();
870
+            if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
871
+                    !($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
872
+                $plainTextPassword = null;
873
+            }
874
+            if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
875
+                // If the same password was already sent by mail the recipient
876
+                // would already have access to the share without having to call
877
+                // the sharer to verify her identity
878
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
879
+            }
880
+        }
881
+
882
+        $this->pathCreateChecks($share->getNode());
883
+
884
+        // Now update the share!
885
+        $provider = $this->factory->getProviderForType($share->getShareType());
886
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
887
+            $share = $provider->update($share, $plainTextPassword);
888
+        } else {
889
+            $share = $provider->update($share);
890
+        }
891
+
892
+        if ($expirationDateUpdated === true) {
893
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
894
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
895
+                'itemSource' => $share->getNode()->getId(),
896
+                'date' => $share->getExpirationDate(),
897
+                'uidOwner' => $share->getSharedBy(),
898
+            ]);
899
+        }
900
+
901
+        if ($share->getPassword() !== $originalShare->getPassword()) {
902
+            \OC_Hook::emit(Share::class, 'post_update_password', [
903
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
904
+                'itemSource' => $share->getNode()->getId(),
905
+                'uidOwner' => $share->getSharedBy(),
906
+                'token' => $share->getToken(),
907
+                'disabled' => is_null($share->getPassword()),
908
+            ]);
909
+        }
910
+
911
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
912
+            if ($this->userManager->userExists($share->getShareOwner())) {
913
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
914
+            } else {
915
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
916
+            }
917
+            \OC_Hook::emit(Share::class, 'post_update_permissions', array(
918
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
919
+                'itemSource' => $share->getNode()->getId(),
920
+                'shareType' => $share->getShareType(),
921
+                'shareWith' => $share->getSharedWith(),
922
+                'uidOwner' => $share->getSharedBy(),
923
+                'permissions' => $share->getPermissions(),
924
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
925
+            ));
926
+        }
927
+
928
+        return $share;
929
+    }
930
+
931
+    /**
932
+     * Accept a share.
933
+     *
934
+     * @param IShare $share
935
+     * @param string $recipientId
936
+     * @return IShare The share object
937
+     * @throws \InvalidArgumentException
938
+     * @since 9.0.0
939
+     */
940
+    public function acceptShare(IShare $share, string $recipientId): IShare {
941
+        [$providerId, ] = $this->splitFullId($share->getFullId());
942
+        $provider = $this->factory->getProvider($providerId);
943
+
944
+        if (!method_exists($provider, 'acceptShare')) {
945
+            // TODO FIX ME
946
+            throw new \InvalidArgumentException('Share provider does not support accepting');
947
+        }
948
+        $provider->acceptShare($share, $recipientId);
949
+        $event = new GenericEvent($share);
950
+        $this->eventDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
951
+
952
+        return $share;
953
+    }
954
+
955
+    /**
956
+     * Updates the password of the given share if it is not the same as the
957
+     * password of the original share.
958
+     *
959
+     * @param \OCP\Share\IShare $share the share to update its password.
960
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
961
+     *        password with.
962
+     * @return boolean whether the password was updated or not.
963
+     */
964
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
965
+        // Password updated.
966
+        if ($share->getPassword() !== $originalShare->getPassword()) {
967
+            //Verify the password
968
+            $this->verifyPassword($share->getPassword());
969
+
970
+            // If a password is set. Hash it!
971
+            if ($share->getPassword() !== null) {
972
+                $share->setPassword($this->hasher->hash($share->getPassword()));
973
+
974
+                return true;
975
+            }
976
+        }
977
+
978
+        return false;
979
+    }
980
+
981
+    /**
982
+     * Delete all the children of this share
983
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
984
+     *
985
+     * @param \OCP\Share\IShare $share
986
+     * @return \OCP\Share\IShare[] List of deleted shares
987
+     */
988
+    protected function deleteChildren(\OCP\Share\IShare $share) {
989
+        $deletedShares = [];
990
+
991
+        $provider = $this->factory->getProviderForType($share->getShareType());
992
+
993
+        foreach ($provider->getChildren($share) as $child) {
994
+            $deletedChildren = $this->deleteChildren($child);
995
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
996
+
997
+            $provider->delete($child);
998
+            $deletedShares[] = $child;
999
+        }
1000
+
1001
+        return $deletedShares;
1002
+    }
1003
+
1004
+    /**
1005
+     * Delete a share
1006
+     *
1007
+     * @param \OCP\Share\IShare $share
1008
+     * @throws ShareNotFound
1009
+     * @throws \InvalidArgumentException
1010
+     */
1011
+    public function deleteShare(\OCP\Share\IShare $share) {
1012
+
1013
+        try {
1014
+            $share->getFullId();
1015
+        } catch (\UnexpectedValueException $e) {
1016
+            throw new \InvalidArgumentException('Share does not have a full id');
1017
+        }
1018
+
1019
+        $event = new GenericEvent($share);
1020
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
1021
+
1022
+        // Get all children and delete them as well
1023
+        $deletedShares = $this->deleteChildren($share);
1024
+
1025
+        // Do the actual delete
1026
+        $provider = $this->factory->getProviderForType($share->getShareType());
1027
+        $provider->delete($share);
1028
+
1029
+        // All the deleted shares caused by this delete
1030
+        $deletedShares[] = $share;
1031
+
1032
+        // Emit post hook
1033
+        $event->setArgument('deletedShares', $deletedShares);
1034
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
1035
+    }
1036
+
1037
+
1038
+    /**
1039
+     * Unshare a file as the recipient.
1040
+     * This can be different from a regular delete for example when one of
1041
+     * the users in a groups deletes that share. But the provider should
1042
+     * handle this.
1043
+     *
1044
+     * @param \OCP\Share\IShare $share
1045
+     * @param string $recipientId
1046
+     */
1047
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1048
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1049
+        $provider = $this->factory->getProvider($providerId);
1050
+
1051
+        $provider->deleteFromSelf($share, $recipientId);
1052
+        $event = new GenericEvent($share);
1053
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1054
+    }
1055
+
1056
+    public function restoreShare(IShare $share, string $recipientId): IShare {
1057
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1058
+        $provider = $this->factory->getProvider($providerId);
1059
+
1060
+        return $provider->restore($share, $recipientId);
1061
+    }
1062
+
1063
+    /**
1064
+     * @inheritdoc
1065
+     */
1066
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1067
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1068
+            throw new \InvalidArgumentException('Can’t change target of link share');
1069
+        }
1070
+
1071
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1072
+            throw new \InvalidArgumentException('Invalid recipient');
1073
+        }
1074
+
1075
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1076
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1077
+            if (is_null($sharedWith)) {
1078
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1079
+            }
1080
+            $recipient = $this->userManager->get($recipientId);
1081
+            if (!$sharedWith->inGroup($recipient)) {
1082
+                throw new \InvalidArgumentException('Invalid recipient');
1083
+            }
1084
+        }
1085
+
1086
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1087
+        $provider = $this->factory->getProvider($providerId);
1088
+
1089
+        $provider->move($share, $recipientId);
1090
+    }
1091
+
1092
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1093
+        $providers = $this->factory->getAllProviders();
1094
+
1095
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1096
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1097
+            foreach ($newShares as $fid => $data) {
1098
+                if (!isset($shares[$fid])) {
1099
+                    $shares[$fid] = [];
1100
+                }
1101
+
1102
+                $shares[$fid] = array_merge($shares[$fid], $data);
1103
+            }
1104
+            return $shares;
1105
+        }, []);
1106
+    }
1107
+
1108
+    /**
1109
+     * @inheritdoc
1110
+     */
1111
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1112
+        if ($path !== null &&
1113
+                !($path instanceof \OCP\Files\File) &&
1114
+                !($path instanceof \OCP\Files\Folder)) {
1115
+            throw new \InvalidArgumentException('invalid path');
1116
+        }
1117
+
1118
+        try {
1119
+            $provider = $this->factory->getProviderForType($shareType);
1120
+        } catch (ProviderException $e) {
1121
+            return [];
1122
+        }
1123
+
1124
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1125
+
1126
+        /*
1127 1127
 		 * Work around so we don't return expired shares but still follow
1128 1128
 		 * proper pagination.
1129 1129
 		 */
1130 1130
 
1131
-		$shares2 = [];
1132
-
1133
-		while(true) {
1134
-			$added = 0;
1135
-			foreach ($shares as $share) {
1136
-
1137
-				try {
1138
-					$this->checkExpireDate($share);
1139
-				} catch (ShareNotFound $e) {
1140
-					//Ignore since this basically means the share is deleted
1141
-					continue;
1142
-				}
1143
-
1144
-				$added++;
1145
-				$shares2[] = $share;
1146
-
1147
-				if (count($shares2) === $limit) {
1148
-					break;
1149
-				}
1150
-			}
1151
-
1152
-			// If we did not fetch more shares than the limit then there are no more shares
1153
-			if (count($shares) < $limit) {
1154
-				break;
1155
-			}
1156
-
1157
-			if (count($shares2) === $limit) {
1158
-				break;
1159
-			}
1160
-
1161
-			// If there was no limit on the select we are done
1162
-			if ($limit === -1) {
1163
-				break;
1164
-			}
1165
-
1166
-			$offset += $added;
1167
-
1168
-			// Fetch again $limit shares
1169
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1170
-
1171
-			// No more shares means we are done
1172
-			if (empty($shares)) {
1173
-				break;
1174
-			}
1175
-		}
1176
-
1177
-		$shares = $shares2;
1178
-
1179
-		return $shares;
1180
-	}
1181
-
1182
-	/**
1183
-	 * @inheritdoc
1184
-	 */
1185
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1186
-		try {
1187
-			$provider = $this->factory->getProviderForType($shareType);
1188
-		} catch (ProviderException $e) {
1189
-			return [];
1190
-		}
1191
-
1192
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1193
-
1194
-		// remove all shares which are already expired
1195
-		foreach ($shares as $key => $share) {
1196
-			try {
1197
-				$this->checkExpireDate($share);
1198
-			} catch (ShareNotFound $e) {
1199
-				unset($shares[$key]);
1200
-			}
1201
-		}
1202
-
1203
-		return $shares;
1204
-	}
1205
-
1206
-	/**
1207
-	 * @inheritdoc
1208
-	 */
1209
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1210
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1211
-
1212
-		// Only get deleted shares
1213
-		$shares = array_filter($shares, function(IShare $share) {
1214
-			return $share->getPermissions() === 0;
1215
-		});
1216
-
1217
-		// Only get shares where the owner still exists
1218
-		$shares = array_filter($shares, function (IShare $share) {
1219
-			return $this->userManager->userExists($share->getShareOwner());
1220
-		});
1221
-
1222
-		return $shares;
1223
-	}
1224
-
1225
-	/**
1226
-	 * @inheritdoc
1227
-	 */
1228
-	public function getShareById($id, $recipient = null) {
1229
-		if ($id === null) {
1230
-			throw new ShareNotFound();
1231
-		}
1232
-
1233
-		list($providerId, $id) = $this->splitFullId($id);
1234
-
1235
-		try {
1236
-			$provider = $this->factory->getProvider($providerId);
1237
-		} catch (ProviderException $e) {
1238
-			throw new ShareNotFound();
1239
-		}
1240
-
1241
-		$share = $provider->getShareById($id, $recipient);
1242
-
1243
-		$this->checkExpireDate($share);
1244
-
1245
-		return $share;
1246
-	}
1247
-
1248
-	/**
1249
-	 * Get all the shares for a given path
1250
-	 *
1251
-	 * @param \OCP\Files\Node $path
1252
-	 * @param int $page
1253
-	 * @param int $perPage
1254
-	 *
1255
-	 * @return Share[]
1256
-	 */
1257
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1258
-		return [];
1259
-	}
1260
-
1261
-	/**
1262
-	 * Get the share by token possible with password
1263
-	 *
1264
-	 * @param string $token
1265
-	 * @return Share
1266
-	 *
1267
-	 * @throws ShareNotFound
1268
-	 */
1269
-	public function getShareByToken($token) {
1270
-		// tokens can't be valid local user names
1271
-		if ($this->userManager->userExists($token)) {
1272
-			throw new ShareNotFound();
1273
-		}
1274
-		$share = null;
1275
-		try {
1276
-			if($this->shareApiAllowLinks()) {
1277
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1278
-				$share = $provider->getShareByToken($token);
1279
-			}
1280
-		} catch (ProviderException $e) {
1281
-		} catch (ShareNotFound $e) {
1282
-		}
1283
-
1284
-
1285
-		// If it is not a link share try to fetch a federated share by token
1286
-		if ($share === null) {
1287
-			try {
1288
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1289
-				$share = $provider->getShareByToken($token);
1290
-			} catch (ProviderException $e) {
1291
-			} catch (ShareNotFound $e) {
1292
-			}
1293
-		}
1294
-
1295
-		// If it is not a link share try to fetch a mail share by token
1296
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1297
-			try {
1298
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1299
-				$share = $provider->getShareByToken($token);
1300
-			} catch (ProviderException $e) {
1301
-			} catch (ShareNotFound $e) {
1302
-			}
1303
-		}
1304
-
1305
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1306
-			try {
1307
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1308
-				$share = $provider->getShareByToken($token);
1309
-			} catch (ProviderException $e) {
1310
-			} catch (ShareNotFound $e) {
1311
-			}
1312
-		}
1313
-
1314
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1315
-			try {
1316
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1317
-				$share = $provider->getShareByToken($token);
1318
-			} catch (ProviderException $e) {
1319
-			} catch (ShareNotFound $e) {
1320
-			}
1321
-		}
1322
-
1323
-		if ($share === null) {
1324
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1325
-		}
1326
-
1327
-		$this->checkExpireDate($share);
1328
-
1329
-		/*
1131
+        $shares2 = [];
1132
+
1133
+        while(true) {
1134
+            $added = 0;
1135
+            foreach ($shares as $share) {
1136
+
1137
+                try {
1138
+                    $this->checkExpireDate($share);
1139
+                } catch (ShareNotFound $e) {
1140
+                    //Ignore since this basically means the share is deleted
1141
+                    continue;
1142
+                }
1143
+
1144
+                $added++;
1145
+                $shares2[] = $share;
1146
+
1147
+                if (count($shares2) === $limit) {
1148
+                    break;
1149
+                }
1150
+            }
1151
+
1152
+            // If we did not fetch more shares than the limit then there are no more shares
1153
+            if (count($shares) < $limit) {
1154
+                break;
1155
+            }
1156
+
1157
+            if (count($shares2) === $limit) {
1158
+                break;
1159
+            }
1160
+
1161
+            // If there was no limit on the select we are done
1162
+            if ($limit === -1) {
1163
+                break;
1164
+            }
1165
+
1166
+            $offset += $added;
1167
+
1168
+            // Fetch again $limit shares
1169
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1170
+
1171
+            // No more shares means we are done
1172
+            if (empty($shares)) {
1173
+                break;
1174
+            }
1175
+        }
1176
+
1177
+        $shares = $shares2;
1178
+
1179
+        return $shares;
1180
+    }
1181
+
1182
+    /**
1183
+     * @inheritdoc
1184
+     */
1185
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1186
+        try {
1187
+            $provider = $this->factory->getProviderForType($shareType);
1188
+        } catch (ProviderException $e) {
1189
+            return [];
1190
+        }
1191
+
1192
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1193
+
1194
+        // remove all shares which are already expired
1195
+        foreach ($shares as $key => $share) {
1196
+            try {
1197
+                $this->checkExpireDate($share);
1198
+            } catch (ShareNotFound $e) {
1199
+                unset($shares[$key]);
1200
+            }
1201
+        }
1202
+
1203
+        return $shares;
1204
+    }
1205
+
1206
+    /**
1207
+     * @inheritdoc
1208
+     */
1209
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1210
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1211
+
1212
+        // Only get deleted shares
1213
+        $shares = array_filter($shares, function(IShare $share) {
1214
+            return $share->getPermissions() === 0;
1215
+        });
1216
+
1217
+        // Only get shares where the owner still exists
1218
+        $shares = array_filter($shares, function (IShare $share) {
1219
+            return $this->userManager->userExists($share->getShareOwner());
1220
+        });
1221
+
1222
+        return $shares;
1223
+    }
1224
+
1225
+    /**
1226
+     * @inheritdoc
1227
+     */
1228
+    public function getShareById($id, $recipient = null) {
1229
+        if ($id === null) {
1230
+            throw new ShareNotFound();
1231
+        }
1232
+
1233
+        list($providerId, $id) = $this->splitFullId($id);
1234
+
1235
+        try {
1236
+            $provider = $this->factory->getProvider($providerId);
1237
+        } catch (ProviderException $e) {
1238
+            throw new ShareNotFound();
1239
+        }
1240
+
1241
+        $share = $provider->getShareById($id, $recipient);
1242
+
1243
+        $this->checkExpireDate($share);
1244
+
1245
+        return $share;
1246
+    }
1247
+
1248
+    /**
1249
+     * Get all the shares for a given path
1250
+     *
1251
+     * @param \OCP\Files\Node $path
1252
+     * @param int $page
1253
+     * @param int $perPage
1254
+     *
1255
+     * @return Share[]
1256
+     */
1257
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1258
+        return [];
1259
+    }
1260
+
1261
+    /**
1262
+     * Get the share by token possible with password
1263
+     *
1264
+     * @param string $token
1265
+     * @return Share
1266
+     *
1267
+     * @throws ShareNotFound
1268
+     */
1269
+    public function getShareByToken($token) {
1270
+        // tokens can't be valid local user names
1271
+        if ($this->userManager->userExists($token)) {
1272
+            throw new ShareNotFound();
1273
+        }
1274
+        $share = null;
1275
+        try {
1276
+            if($this->shareApiAllowLinks()) {
1277
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1278
+                $share = $provider->getShareByToken($token);
1279
+            }
1280
+        } catch (ProviderException $e) {
1281
+        } catch (ShareNotFound $e) {
1282
+        }
1283
+
1284
+
1285
+        // If it is not a link share try to fetch a federated share by token
1286
+        if ($share === null) {
1287
+            try {
1288
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1289
+                $share = $provider->getShareByToken($token);
1290
+            } catch (ProviderException $e) {
1291
+            } catch (ShareNotFound $e) {
1292
+            }
1293
+        }
1294
+
1295
+        // If it is not a link share try to fetch a mail share by token
1296
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1297
+            try {
1298
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1299
+                $share = $provider->getShareByToken($token);
1300
+            } catch (ProviderException $e) {
1301
+            } catch (ShareNotFound $e) {
1302
+            }
1303
+        }
1304
+
1305
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1306
+            try {
1307
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1308
+                $share = $provider->getShareByToken($token);
1309
+            } catch (ProviderException $e) {
1310
+            } catch (ShareNotFound $e) {
1311
+            }
1312
+        }
1313
+
1314
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1315
+            try {
1316
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1317
+                $share = $provider->getShareByToken($token);
1318
+            } catch (ProviderException $e) {
1319
+            } catch (ShareNotFound $e) {
1320
+            }
1321
+        }
1322
+
1323
+        if ($share === null) {
1324
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1325
+        }
1326
+
1327
+        $this->checkExpireDate($share);
1328
+
1329
+        /*
1330 1330
 		 * Reduce the permissions for link shares if public upload is not enabled
1331 1331
 		 */
1332
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1333
-			!$this->shareApiLinkAllowPublicUpload()) {
1334
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1335
-		}
1336
-
1337
-		return $share;
1338
-	}
1339
-
1340
-	protected function checkExpireDate($share) {
1341
-		if ($share->isExpired()) {
1342
-			$this->deleteShare($share);
1343
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1344
-		}
1345
-
1346
-	}
1347
-
1348
-	/**
1349
-	 * Verify the password of a public share
1350
-	 *
1351
-	 * @param \OCP\Share\IShare $share
1352
-	 * @param string $password
1353
-	 * @return bool
1354
-	 */
1355
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1356
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1357
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1358
-		if (!$passwordProtected) {
1359
-			//TODO maybe exception?
1360
-			return false;
1361
-		}
1362
-
1363
-		if ($password === null || $share->getPassword() === null) {
1364
-			return false;
1365
-		}
1366
-
1367
-		$newHash = '';
1368
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1369
-			return false;
1370
-		}
1371
-
1372
-		if (!empty($newHash)) {
1373
-			$share->setPassword($newHash);
1374
-			$provider = $this->factory->getProviderForType($share->getShareType());
1375
-			$provider->update($share);
1376
-		}
1377
-
1378
-		return true;
1379
-	}
1380
-
1381
-	/**
1382
-	 * @inheritdoc
1383
-	 */
1384
-	public function userDeleted($uid) {
1385
-		$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];
1386
-
1387
-		foreach ($types as $type) {
1388
-			try {
1389
-				$provider = $this->factory->getProviderForType($type);
1390
-			} catch (ProviderException $e) {
1391
-				continue;
1392
-			}
1393
-			$provider->userDeleted($uid, $type);
1394
-		}
1395
-	}
1396
-
1397
-	/**
1398
-	 * @inheritdoc
1399
-	 */
1400
-	public function groupDeleted($gid) {
1401
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1402
-		$provider->groupDeleted($gid);
1403
-	}
1404
-
1405
-	/**
1406
-	 * @inheritdoc
1407
-	 */
1408
-	public function userDeletedFromGroup($uid, $gid) {
1409
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1410
-		$provider->userDeletedFromGroup($uid, $gid);
1411
-	}
1412
-
1413
-	/**
1414
-	 * Get access list to a path. This means
1415
-	 * all the users that can access a given path.
1416
-	 *
1417
-	 * Consider:
1418
-	 * -root
1419
-	 * |-folder1 (23)
1420
-	 *  |-folder2 (32)
1421
-	 *   |-fileA (42)
1422
-	 *
1423
-	 * fileA is shared with user1 and user1@server1
1424
-	 * folder2 is shared with group2 (user4 is a member of group2)
1425
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1426
-	 *
1427
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1428
-	 * [
1429
-	 *  users  => [
1430
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1431
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1432
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1433
-	 *  ],
1434
-	 *  remote => [
1435
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1436
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1437
-	 *  ],
1438
-	 *  public => bool
1439
-	 *  mail => bool
1440
-	 * ]
1441
-	 *
1442
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1443
-	 * [
1444
-	 *  users  => ['user1', 'user2', 'user4'],
1445
-	 *  remote => bool,
1446
-	 *  public => bool
1447
-	 *  mail => bool
1448
-	 * ]
1449
-	 *
1450
-	 * This is required for encryption/activity
1451
-	 *
1452
-	 * @param \OCP\Files\Node $path
1453
-	 * @param bool $recursive Should we check all parent folders as well
1454
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1455
-	 * @return array
1456
-	 */
1457
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1458
-		$owner = $path->getOwner();
1459
-
1460
-		if ($owner === null) {
1461
-			return [];
1462
-		}
1463
-
1464
-		$owner = $owner->getUID();
1465
-
1466
-		if ($currentAccess) {
1467
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1468
-		} else {
1469
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1470
-		}
1471
-		if (!$this->userManager->userExists($owner)) {
1472
-			return $al;
1473
-		}
1474
-
1475
-		//Get node for the owner and correct the owner in case of external storages
1476
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1477
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1478
-			$nodes = $userFolder->getById($path->getId());
1479
-			$path = array_shift($nodes);
1480
-			if ($path->getOwner() === null) {
1481
-				return [];
1482
-			}
1483
-			$owner = $path->getOwner()->getUID();
1484
-		}
1485
-
1486
-		$providers = $this->factory->getAllProviders();
1487
-
1488
-		/** @var Node[] $nodes */
1489
-		$nodes = [];
1490
-
1491
-
1492
-		if ($currentAccess) {
1493
-			$ownerPath = $path->getPath();
1494
-			$ownerPath = explode('/', $ownerPath, 4);
1495
-			if (count($ownerPath) < 4) {
1496
-				$ownerPath = '';
1497
-			} else {
1498
-				$ownerPath = $ownerPath[3];
1499
-			}
1500
-			$al['users'][$owner] = [
1501
-				'node_id' => $path->getId(),
1502
-				'node_path' => '/' . $ownerPath,
1503
-			];
1504
-		} else {
1505
-			$al['users'][] = $owner;
1506
-		}
1507
-
1508
-		// Collect all the shares
1509
-		while ($path->getPath() !== $userFolder->getPath()) {
1510
-			$nodes[] = $path;
1511
-			if (!$recursive) {
1512
-				break;
1513
-			}
1514
-			$path = $path->getParent();
1515
-		}
1516
-
1517
-		foreach ($providers as $provider) {
1518
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1519
-
1520
-			foreach ($tmp as $k => $v) {
1521
-				if (isset($al[$k])) {
1522
-					if (is_array($al[$k])) {
1523
-						if ($currentAccess) {
1524
-							$al[$k] += $v;
1525
-						} else {
1526
-							$al[$k] = array_merge($al[$k], $v);
1527
-							$al[$k] = array_unique($al[$k]);
1528
-							$al[$k] = array_values($al[$k]);
1529
-						}
1530
-					} else {
1531
-						$al[$k] = $al[$k] || $v;
1532
-					}
1533
-				} else {
1534
-					$al[$k] = $v;
1535
-				}
1536
-			}
1537
-		}
1538
-
1539
-		return $al;
1540
-	}
1541
-
1542
-	/**
1543
-	 * Create a new share
1544
-	 * @return \OCP\Share\IShare
1545
-	 */
1546
-	public function newShare() {
1547
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1548
-	}
1549
-
1550
-	/**
1551
-	 * Is the share API enabled
1552
-	 *
1553
-	 * @return bool
1554
-	 */
1555
-	public function shareApiEnabled() {
1556
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1557
-	}
1558
-
1559
-	/**
1560
-	 * Is public link sharing enabled
1561
-	 *
1562
-	 * @return bool
1563
-	 */
1564
-	public function shareApiAllowLinks() {
1565
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1566
-	}
1567
-
1568
-	/**
1569
-	 * Is password on public link requires
1570
-	 *
1571
-	 * @return bool
1572
-	 */
1573
-	public function shareApiLinkEnforcePassword() {
1574
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1575
-	}
1576
-
1577
-	/**
1578
-	 * Is default expire date enabled
1579
-	 *
1580
-	 * @return bool
1581
-	 */
1582
-	public function shareApiLinkDefaultExpireDate() {
1583
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1584
-	}
1585
-
1586
-	/**
1587
-	 * Is default expire date enforced
1588
-	 *`
1589
-	 * @return bool
1590
-	 */
1591
-	public function shareApiLinkDefaultExpireDateEnforced() {
1592
-		return $this->shareApiLinkDefaultExpireDate() &&
1593
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1594
-	}
1595
-
1596
-	/**
1597
-	 * Number of default expire days
1598
-	 *shareApiLinkAllowPublicUpload
1599
-	 * @return int
1600
-	 */
1601
-	public function shareApiLinkDefaultExpireDays() {
1602
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1603
-	}
1604
-
1605
-	/**
1606
-	 * Allow public upload on link shares
1607
-	 *
1608
-	 * @return bool
1609
-	 */
1610
-	public function shareApiLinkAllowPublicUpload() {
1611
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1612
-	}
1613
-
1614
-	/**
1615
-	 * check if user can only share with group members
1616
-	 * @return bool
1617
-	 */
1618
-	public function shareWithGroupMembersOnly() {
1619
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1620
-	}
1621
-
1622
-	/**
1623
-	 * Check if users can share with groups
1624
-	 * @return bool
1625
-	 */
1626
-	public function allowGroupSharing() {
1627
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1628
-	}
1629
-
1630
-	/**
1631
-	 * Copied from \OC_Util::isSharingDisabledForUser
1632
-	 *
1633
-	 * TODO: Deprecate fuction from OC_Util
1634
-	 *
1635
-	 * @param string $userId
1636
-	 * @return bool
1637
-	 */
1638
-	public function sharingDisabledForUser($userId) {
1639
-		if ($userId === null) {
1640
-			return false;
1641
-		}
1642
-
1643
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1644
-			return $this->sharingDisabledForUsersCache[$userId];
1645
-		}
1646
-
1647
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1648
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1649
-			$excludedGroups = json_decode($groupsList);
1650
-			if (is_null($excludedGroups)) {
1651
-				$excludedGroups = explode(',', $groupsList);
1652
-				$newValue = json_encode($excludedGroups);
1653
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1654
-			}
1655
-			$user = $this->userManager->get($userId);
1656
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1657
-			if (!empty($usersGroups)) {
1658
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1659
-				// if the user is only in groups which are disabled for sharing then
1660
-				// sharing is also disabled for the user
1661
-				if (empty($remainingGroups)) {
1662
-					$this->sharingDisabledForUsersCache[$userId] = true;
1663
-					return true;
1664
-				}
1665
-			}
1666
-		}
1667
-
1668
-		$this->sharingDisabledForUsersCache[$userId] = false;
1669
-		return false;
1670
-	}
1671
-
1672
-	/**
1673
-	 * @inheritdoc
1674
-	 */
1675
-	public function outgoingServer2ServerSharesAllowed() {
1676
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1677
-	}
1678
-
1679
-	/**
1680
-	 * @inheritdoc
1681
-	 */
1682
-	public function outgoingServer2ServerGroupSharesAllowed() {
1683
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1684
-	}
1685
-
1686
-	/**
1687
-	 * @inheritdoc
1688
-	 */
1689
-	public function shareProviderExists($shareType) {
1690
-		try {
1691
-			$this->factory->getProviderForType($shareType);
1692
-		} catch (ProviderException $e) {
1693
-			return false;
1694
-		}
1695
-
1696
-		return true;
1697
-	}
1698
-
1699
-	public function getAllShares(): iterable {
1700
-		$providers = $this->factory->getAllProviders();
1701
-
1702
-		foreach ($providers as $provider) {
1703
-			yield from $provider->getAllShares();
1704
-		}
1705
-	}
1332
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1333
+            !$this->shareApiLinkAllowPublicUpload()) {
1334
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1335
+        }
1336
+
1337
+        return $share;
1338
+    }
1339
+
1340
+    protected function checkExpireDate($share) {
1341
+        if ($share->isExpired()) {
1342
+            $this->deleteShare($share);
1343
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1344
+        }
1345
+
1346
+    }
1347
+
1348
+    /**
1349
+     * Verify the password of a public share
1350
+     *
1351
+     * @param \OCP\Share\IShare $share
1352
+     * @param string $password
1353
+     * @return bool
1354
+     */
1355
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1356
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1357
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1358
+        if (!$passwordProtected) {
1359
+            //TODO maybe exception?
1360
+            return false;
1361
+        }
1362
+
1363
+        if ($password === null || $share->getPassword() === null) {
1364
+            return false;
1365
+        }
1366
+
1367
+        $newHash = '';
1368
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1369
+            return false;
1370
+        }
1371
+
1372
+        if (!empty($newHash)) {
1373
+            $share->setPassword($newHash);
1374
+            $provider = $this->factory->getProviderForType($share->getShareType());
1375
+            $provider->update($share);
1376
+        }
1377
+
1378
+        return true;
1379
+    }
1380
+
1381
+    /**
1382
+     * @inheritdoc
1383
+     */
1384
+    public function userDeleted($uid) {
1385
+        $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];
1386
+
1387
+        foreach ($types as $type) {
1388
+            try {
1389
+                $provider = $this->factory->getProviderForType($type);
1390
+            } catch (ProviderException $e) {
1391
+                continue;
1392
+            }
1393
+            $provider->userDeleted($uid, $type);
1394
+        }
1395
+    }
1396
+
1397
+    /**
1398
+     * @inheritdoc
1399
+     */
1400
+    public function groupDeleted($gid) {
1401
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1402
+        $provider->groupDeleted($gid);
1403
+    }
1404
+
1405
+    /**
1406
+     * @inheritdoc
1407
+     */
1408
+    public function userDeletedFromGroup($uid, $gid) {
1409
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1410
+        $provider->userDeletedFromGroup($uid, $gid);
1411
+    }
1412
+
1413
+    /**
1414
+     * Get access list to a path. This means
1415
+     * all the users that can access a given path.
1416
+     *
1417
+     * Consider:
1418
+     * -root
1419
+     * |-folder1 (23)
1420
+     *  |-folder2 (32)
1421
+     *   |-fileA (42)
1422
+     *
1423
+     * fileA is shared with user1 and user1@server1
1424
+     * folder2 is shared with group2 (user4 is a member of group2)
1425
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1426
+     *
1427
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1428
+     * [
1429
+     *  users  => [
1430
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1431
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1432
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1433
+     *  ],
1434
+     *  remote => [
1435
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1436
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1437
+     *  ],
1438
+     *  public => bool
1439
+     *  mail => bool
1440
+     * ]
1441
+     *
1442
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1443
+     * [
1444
+     *  users  => ['user1', 'user2', 'user4'],
1445
+     *  remote => bool,
1446
+     *  public => bool
1447
+     *  mail => bool
1448
+     * ]
1449
+     *
1450
+     * This is required for encryption/activity
1451
+     *
1452
+     * @param \OCP\Files\Node $path
1453
+     * @param bool $recursive Should we check all parent folders as well
1454
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1455
+     * @return array
1456
+     */
1457
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1458
+        $owner = $path->getOwner();
1459
+
1460
+        if ($owner === null) {
1461
+            return [];
1462
+        }
1463
+
1464
+        $owner = $owner->getUID();
1465
+
1466
+        if ($currentAccess) {
1467
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1468
+        } else {
1469
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1470
+        }
1471
+        if (!$this->userManager->userExists($owner)) {
1472
+            return $al;
1473
+        }
1474
+
1475
+        //Get node for the owner and correct the owner in case of external storages
1476
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1477
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1478
+            $nodes = $userFolder->getById($path->getId());
1479
+            $path = array_shift($nodes);
1480
+            if ($path->getOwner() === null) {
1481
+                return [];
1482
+            }
1483
+            $owner = $path->getOwner()->getUID();
1484
+        }
1485
+
1486
+        $providers = $this->factory->getAllProviders();
1487
+
1488
+        /** @var Node[] $nodes */
1489
+        $nodes = [];
1490
+
1491
+
1492
+        if ($currentAccess) {
1493
+            $ownerPath = $path->getPath();
1494
+            $ownerPath = explode('/', $ownerPath, 4);
1495
+            if (count($ownerPath) < 4) {
1496
+                $ownerPath = '';
1497
+            } else {
1498
+                $ownerPath = $ownerPath[3];
1499
+            }
1500
+            $al['users'][$owner] = [
1501
+                'node_id' => $path->getId(),
1502
+                'node_path' => '/' . $ownerPath,
1503
+            ];
1504
+        } else {
1505
+            $al['users'][] = $owner;
1506
+        }
1507
+
1508
+        // Collect all the shares
1509
+        while ($path->getPath() !== $userFolder->getPath()) {
1510
+            $nodes[] = $path;
1511
+            if (!$recursive) {
1512
+                break;
1513
+            }
1514
+            $path = $path->getParent();
1515
+        }
1516
+
1517
+        foreach ($providers as $provider) {
1518
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1519
+
1520
+            foreach ($tmp as $k => $v) {
1521
+                if (isset($al[$k])) {
1522
+                    if (is_array($al[$k])) {
1523
+                        if ($currentAccess) {
1524
+                            $al[$k] += $v;
1525
+                        } else {
1526
+                            $al[$k] = array_merge($al[$k], $v);
1527
+                            $al[$k] = array_unique($al[$k]);
1528
+                            $al[$k] = array_values($al[$k]);
1529
+                        }
1530
+                    } else {
1531
+                        $al[$k] = $al[$k] || $v;
1532
+                    }
1533
+                } else {
1534
+                    $al[$k] = $v;
1535
+                }
1536
+            }
1537
+        }
1538
+
1539
+        return $al;
1540
+    }
1541
+
1542
+    /**
1543
+     * Create a new share
1544
+     * @return \OCP\Share\IShare
1545
+     */
1546
+    public function newShare() {
1547
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1548
+    }
1549
+
1550
+    /**
1551
+     * Is the share API enabled
1552
+     *
1553
+     * @return bool
1554
+     */
1555
+    public function shareApiEnabled() {
1556
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1557
+    }
1558
+
1559
+    /**
1560
+     * Is public link sharing enabled
1561
+     *
1562
+     * @return bool
1563
+     */
1564
+    public function shareApiAllowLinks() {
1565
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1566
+    }
1567
+
1568
+    /**
1569
+     * Is password on public link requires
1570
+     *
1571
+     * @return bool
1572
+     */
1573
+    public function shareApiLinkEnforcePassword() {
1574
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1575
+    }
1576
+
1577
+    /**
1578
+     * Is default expire date enabled
1579
+     *
1580
+     * @return bool
1581
+     */
1582
+    public function shareApiLinkDefaultExpireDate() {
1583
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1584
+    }
1585
+
1586
+    /**
1587
+     * Is default expire date enforced
1588
+     *`
1589
+     * @return bool
1590
+     */
1591
+    public function shareApiLinkDefaultExpireDateEnforced() {
1592
+        return $this->shareApiLinkDefaultExpireDate() &&
1593
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1594
+    }
1595
+
1596
+    /**
1597
+     * Number of default expire days
1598
+     *shareApiLinkAllowPublicUpload
1599
+     * @return int
1600
+     */
1601
+    public function shareApiLinkDefaultExpireDays() {
1602
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1603
+    }
1604
+
1605
+    /**
1606
+     * Allow public upload on link shares
1607
+     *
1608
+     * @return bool
1609
+     */
1610
+    public function shareApiLinkAllowPublicUpload() {
1611
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1612
+    }
1613
+
1614
+    /**
1615
+     * check if user can only share with group members
1616
+     * @return bool
1617
+     */
1618
+    public function shareWithGroupMembersOnly() {
1619
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1620
+    }
1621
+
1622
+    /**
1623
+     * Check if users can share with groups
1624
+     * @return bool
1625
+     */
1626
+    public function allowGroupSharing() {
1627
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1628
+    }
1629
+
1630
+    /**
1631
+     * Copied from \OC_Util::isSharingDisabledForUser
1632
+     *
1633
+     * TODO: Deprecate fuction from OC_Util
1634
+     *
1635
+     * @param string $userId
1636
+     * @return bool
1637
+     */
1638
+    public function sharingDisabledForUser($userId) {
1639
+        if ($userId === null) {
1640
+            return false;
1641
+        }
1642
+
1643
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1644
+            return $this->sharingDisabledForUsersCache[$userId];
1645
+        }
1646
+
1647
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1648
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1649
+            $excludedGroups = json_decode($groupsList);
1650
+            if (is_null($excludedGroups)) {
1651
+                $excludedGroups = explode(',', $groupsList);
1652
+                $newValue = json_encode($excludedGroups);
1653
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1654
+            }
1655
+            $user = $this->userManager->get($userId);
1656
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1657
+            if (!empty($usersGroups)) {
1658
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1659
+                // if the user is only in groups which are disabled for sharing then
1660
+                // sharing is also disabled for the user
1661
+                if (empty($remainingGroups)) {
1662
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1663
+                    return true;
1664
+                }
1665
+            }
1666
+        }
1667
+
1668
+        $this->sharingDisabledForUsersCache[$userId] = false;
1669
+        return false;
1670
+    }
1671
+
1672
+    /**
1673
+     * @inheritdoc
1674
+     */
1675
+    public function outgoingServer2ServerSharesAllowed() {
1676
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1677
+    }
1678
+
1679
+    /**
1680
+     * @inheritdoc
1681
+     */
1682
+    public function outgoingServer2ServerGroupSharesAllowed() {
1683
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1684
+    }
1685
+
1686
+    /**
1687
+     * @inheritdoc
1688
+     */
1689
+    public function shareProviderExists($shareType) {
1690
+        try {
1691
+            $this->factory->getProviderForType($shareType);
1692
+        } catch (ProviderException $e) {
1693
+            return false;
1694
+        }
1695
+
1696
+        return true;
1697
+    }
1698
+
1699
+    public function getAllShares(): iterable {
1700
+        $providers = $this->factory->getAllProviders();
1701
+
1702
+        foreach ($providers as $provider) {
1703
+            yield from $provider->getAllShares();
1704
+        }
1705
+    }
1706 1706
 }
Please login to merge, or discard this patch.
lib/private/User/Database.php 1 patch
Indentation   +419 added lines, -419 removed lines patch added patch discarded remove patch
@@ -76,423 +76,423 @@
 block discarded – undo
76 76
  * Class for user management in a SQL Database (e.g. MySQL, SQLite)
77 77
  */
78 78
 class Database extends ABackend
79
-	implements ICreateUserBackend,
80
-	           ISetPasswordBackend,
81
-	           ISetDisplayNameBackend,
82
-	           IGetDisplayNameBackend,
83
-	           ICheckPasswordBackend,
84
-	           IGetHomeBackend,
85
-	           ICountUsersBackend,
86
-	           IGetRealUIDBackend {
87
-	/** @var CappedMemoryCache */
88
-	private $cache;
89
-
90
-	/** @var IEventDispatcher */
91
-	private $eventDispatcher;
92
-
93
-	/** @var IDBConnection */
94
-	private $dbConn;
95
-
96
-	/** @var string */
97
-	private $table;
98
-
99
-	/**
100
-	 * \OC\User\Database constructor.
101
-	 *
102
-	 * @param IEventDispatcher $eventDispatcher
103
-	 * @param string $table
104
-	 */
105
-	public function __construct($eventDispatcher = null, $table = 'users') {
106
-		$this->cache = new CappedMemoryCache();
107
-		$this->table = $table;
108
-		$this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->query(IEventDispatcher::class);
109
-	}
110
-
111
-	/**
112
-	 * FIXME: This function should not be required!
113
-	 */
114
-	private function fixDI() {
115
-		if ($this->dbConn === null) {
116
-			$this->dbConn = \OC::$server->getDatabaseConnection();
117
-		}
118
-	}
119
-
120
-	/**
121
-	 * Create a new user
122
-	 *
123
-	 * @param string $uid The username of the user to create
124
-	 * @param string $password The password of the new user
125
-	 * @return bool
126
-	 *
127
-	 * Creates a new user. Basic checking of username is done in OC_User
128
-	 * itself, not in its subclasses.
129
-	 */
130
-	public function createUser(string $uid, string $password): bool {
131
-		$this->fixDI();
132
-
133
-		if (!$this->userExists($uid)) {
134
-			$this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
135
-
136
-			$qb = $this->dbConn->getQueryBuilder();
137
-			$qb->insert($this->table)
138
-				->values([
139
-					'uid' => $qb->createNamedParameter($uid),
140
-					'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
141
-					'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
142
-				]);
143
-
144
-			$result = $qb->execute();
145
-
146
-			// Clear cache
147
-			unset($this->cache[$uid]);
148
-
149
-			return $result ? true : false;
150
-		}
151
-
152
-		return false;
153
-	}
154
-
155
-	/**
156
-	 * delete a user
157
-	 *
158
-	 * @param string $uid The username of the user to delete
159
-	 * @return bool
160
-	 *
161
-	 * Deletes a user
162
-	 */
163
-	public function deleteUser($uid) {
164
-		$this->fixDI();
165
-
166
-		// Delete user-group-relation
167
-		$query = $this->dbConn->getQueryBuilder();
168
-		$query->delete($this->table)
169
-			->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
170
-		$result = $query->execute();
171
-
172
-		if (isset($this->cache[$uid])) {
173
-			unset($this->cache[$uid]);
174
-		}
175
-
176
-		return $result ? true : false;
177
-	}
178
-
179
-	private function updatePassword(string $uid, string $passwordHash): bool {
180
-		$query = $this->dbConn->getQueryBuilder();
181
-		$query->update($this->table)
182
-			->set('password', $query->createNamedParameter($passwordHash))
183
-			->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
184
-		$result = $query->execute();
185
-
186
-		return $result ? true : false;
187
-	}
188
-
189
-	/**
190
-	 * Set password
191
-	 *
192
-	 * @param string $uid The username
193
-	 * @param string $password The new password
194
-	 * @return bool
195
-	 *
196
-	 * Change the password of a user
197
-	 */
198
-	public function setPassword(string $uid, string $password): bool {
199
-		$this->fixDI();
200
-
201
-		if ($this->userExists($uid)) {
202
-			$this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
203
-
204
-			$hasher = \OC::$server->getHasher();
205
-			$hashedPassword = $hasher->hash($password);
206
-
207
-			return $this->updatePassword($uid, $hashedPassword);
208
-		}
209
-
210
-		return false;
211
-	}
212
-
213
-	/**
214
-	 * Set display name
215
-	 *
216
-	 * @param string $uid The username
217
-	 * @param string $displayName The new display name
218
-	 * @return bool
219
-	 *
220
-	 * Change the display name of a user
221
-	 */
222
-	public function setDisplayName(string $uid, string $displayName): bool {
223
-		$this->fixDI();
224
-
225
-		if ($this->userExists($uid)) {
226
-			$query = $this->dbConn->getQueryBuilder();
227
-			$query->update($this->table)
228
-				->set('displayname', $query->createNamedParameter($displayName))
229
-				->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
230
-			$query->execute();
231
-
232
-			$this->cache[$uid]['displayname'] = $displayName;
233
-
234
-			return true;
235
-		}
236
-
237
-		return false;
238
-	}
239
-
240
-	/**
241
-	 * get display name of the user
242
-	 *
243
-	 * @param string $uid user ID of the user
244
-	 * @return string display name
245
-	 */
246
-	public function getDisplayName($uid): string {
247
-		$uid = (string)$uid;
248
-		$this->loadUser($uid);
249
-		return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
250
-	}
251
-
252
-	/**
253
-	 * Get a list of all display names and user ids.
254
-	 *
255
-	 * @param string $search
256
-	 * @param string|null $limit
257
-	 * @param string|null $offset
258
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
259
-	 */
260
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
261
-		$limit = $this->fixLimit($limit);
262
-
263
-		$this->fixDI();
264
-
265
-		$query = $this->dbConn->getQueryBuilder();
266
-
267
-		$query->select('uid', 'displayname')
268
-			->from($this->table, 'u')
269
-			->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
270
-				$query->expr()->eq('userid', 'uid'),
271
-				$query->expr()->eq('appid', $query->expr()->literal('settings')),
272
-				$query->expr()->eq('configkey', $query->expr()->literal('email')))
273
-			)
274
-			// sqlite doesn't like re-using a single named parameter here
275
-			->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
276
-			->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
277
-			->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
278
-			->orderBy($query->func()->lower('displayname'), 'ASC')
279
-			->orderBy('uid_lower', 'ASC')
280
-			->setMaxResults($limit)
281
-			->setFirstResult($offset);
282
-
283
-		$result = $query->execute();
284
-		$displayNames = [];
285
-		while ($row = $result->fetch()) {
286
-			$displayNames[(string)$row['uid']] = (string)$row['displayname'];
287
-		}
288
-
289
-		return $displayNames;
290
-	}
291
-
292
-	/**
293
-	 * Check if the password is correct
294
-	 *
295
-	 * @param string $uid The username
296
-	 * @param string $password The password
297
-	 * @return string
298
-	 *
299
-	 * Check if the password is correct without logging in the user
300
-	 * returns the user id or false
301
-	 */
302
-	public function checkPassword(string $uid, string $password) {
303
-		$this->fixDI();
304
-
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->select('uid', 'password')
307
-			->from($this->table)
308
-			->where(
309
-				$qb->expr()->eq(
310
-					'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
311
-				)
312
-			);
313
-		$result = $qb->execute();
314
-		$row = $result->fetch();
315
-		$result->closeCursor();
316
-
317
-		if ($row) {
318
-			$storedHash = $row['password'];
319
-			$newHash = '';
320
-			if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
321
-				if (!empty($newHash)) {
322
-					$this->updatePassword($uid, $newHash);
323
-				}
324
-				return (string)$row['uid'];
325
-			}
326
-
327
-		}
328
-
329
-		return false;
330
-	}
331
-
332
-	/**
333
-	 * Load an user in the cache
334
-	 *
335
-	 * @param string $uid the username
336
-	 * @return boolean true if user was found, false otherwise
337
-	 */
338
-	private function loadUser($uid) {
339
-		$this->fixDI();
340
-
341
-		$uid = (string)$uid;
342
-		if (!isset($this->cache[$uid])) {
343
-			//guests $uid could be NULL or ''
344
-			if ($uid === '') {
345
-				$this->cache[$uid] = false;
346
-				return true;
347
-			}
348
-
349
-			$qb = $this->dbConn->getQueryBuilder();
350
-			$qb->select('uid', 'displayname')
351
-				->from($this->table)
352
-				->where(
353
-					$qb->expr()->eq(
354
-						'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
355
-					)
356
-				);
357
-			$result = $qb->execute();
358
-			$row = $result->fetch();
359
-			$result->closeCursor();
360
-
361
-			$this->cache[$uid] = false;
362
-
363
-			// "uid" is primary key, so there can only be a single result
364
-			if ($row !== false) {
365
-				$this->cache[$uid]['uid'] = (string)$row['uid'];
366
-				$this->cache[$uid]['displayname'] = (string)$row['displayname'];
367
-			} else {
368
-				return false;
369
-			}
370
-		}
371
-
372
-		return true;
373
-	}
374
-
375
-	/**
376
-	 * Get a list of all users
377
-	 *
378
-	 * @param string $search
379
-	 * @param null|int $limit
380
-	 * @param null|int $offset
381
-	 * @return string[] an array of all uids
382
-	 */
383
-	public function getUsers($search = '', $limit = null, $offset = null) {
384
-		$limit = $this->fixLimit($limit);
385
-
386
-		$users = $this->getDisplayNames($search, $limit, $offset);
387
-		$userIds = array_map(function ($uid) {
388
-			return (string)$uid;
389
-		}, array_keys($users));
390
-		sort($userIds, SORT_STRING | SORT_FLAG_CASE);
391
-		return $userIds;
392
-	}
393
-
394
-	/**
395
-	 * check if a user exists
396
-	 *
397
-	 * @param string $uid the username
398
-	 * @return boolean
399
-	 */
400
-	public function userExists($uid) {
401
-		$this->loadUser($uid);
402
-		return $this->cache[$uid] !== false;
403
-	}
404
-
405
-	/**
406
-	 * get the user's home directory
407
-	 *
408
-	 * @param string $uid the username
409
-	 * @return string|false
410
-	 */
411
-	public function getHome(string $uid) {
412
-		if ($this->userExists($uid)) {
413
-			return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
414
-		}
415
-
416
-		return false;
417
-	}
418
-
419
-	/**
420
-	 * @return bool
421
-	 */
422
-	public function hasUserListings() {
423
-		return true;
424
-	}
425
-
426
-	/**
427
-	 * counts the users in the database
428
-	 *
429
-	 * @return int|bool
430
-	 */
431
-	public function countUsers() {
432
-		$this->fixDI();
433
-
434
-		$query = $this->dbConn->getQueryBuilder();
435
-		$query->select($query->func()->count('uid'))
436
-			->from($this->table);
437
-		$result = $query->execute();
438
-
439
-		return $result->fetchColumn();
440
-	}
441
-
442
-	/**
443
-	 * returns the username for the given login name in the correct casing
444
-	 *
445
-	 * @param string $loginName
446
-	 * @return string|false
447
-	 */
448
-	public function loginName2UserName($loginName) {
449
-		if ($this->userExists($loginName)) {
450
-			return $this->cache[$loginName]['uid'];
451
-		}
452
-
453
-		return false;
454
-	}
455
-
456
-	/**
457
-	 * Backend name to be shown in user management
458
-	 *
459
-	 * @return string the name of the backend to be shown
460
-	 */
461
-	public function getBackendName() {
462
-		return 'Database';
463
-	}
464
-
465
-	public static function preLoginNameUsedAsUserName($param) {
466
-		if (!isset($param['uid'])) {
467
-			throw new \Exception('key uid is expected to be set in $param');
468
-		}
469
-
470
-		$backends = \OC::$server->getUserManager()->getBackends();
471
-		foreach ($backends as $backend) {
472
-			if ($backend instanceof Database) {
473
-				/** @var \OC\User\Database $backend */
474
-				$uid = $backend->loginName2UserName($param['uid']);
475
-				if ($uid !== false) {
476
-					$param['uid'] = $uid;
477
-					return;
478
-				}
479
-			}
480
-		}
481
-	}
482
-
483
-	public function getRealUID(string $uid): string {
484
-		if (!$this->userExists($uid)) {
485
-			throw new \RuntimeException($uid . ' does not exist');
486
-		}
487
-
488
-		return $this->cache[$uid]['uid'];
489
-	}
490
-
491
-	private function fixLimit($limit) {
492
-		if (is_int($limit) && $limit >= 0) {
493
-			return $limit;
494
-		}
495
-
496
-		return null;
497
-	}
79
+    implements ICreateUserBackend,
80
+                ISetPasswordBackend,
81
+                ISetDisplayNameBackend,
82
+                IGetDisplayNameBackend,
83
+                ICheckPasswordBackend,
84
+                IGetHomeBackend,
85
+                ICountUsersBackend,
86
+                IGetRealUIDBackend {
87
+    /** @var CappedMemoryCache */
88
+    private $cache;
89
+
90
+    /** @var IEventDispatcher */
91
+    private $eventDispatcher;
92
+
93
+    /** @var IDBConnection */
94
+    private $dbConn;
95
+
96
+    /** @var string */
97
+    private $table;
98
+
99
+    /**
100
+     * \OC\User\Database constructor.
101
+     *
102
+     * @param IEventDispatcher $eventDispatcher
103
+     * @param string $table
104
+     */
105
+    public function __construct($eventDispatcher = null, $table = 'users') {
106
+        $this->cache = new CappedMemoryCache();
107
+        $this->table = $table;
108
+        $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->query(IEventDispatcher::class);
109
+    }
110
+
111
+    /**
112
+     * FIXME: This function should not be required!
113
+     */
114
+    private function fixDI() {
115
+        if ($this->dbConn === null) {
116
+            $this->dbConn = \OC::$server->getDatabaseConnection();
117
+        }
118
+    }
119
+
120
+    /**
121
+     * Create a new user
122
+     *
123
+     * @param string $uid The username of the user to create
124
+     * @param string $password The password of the new user
125
+     * @return bool
126
+     *
127
+     * Creates a new user. Basic checking of username is done in OC_User
128
+     * itself, not in its subclasses.
129
+     */
130
+    public function createUser(string $uid, string $password): bool {
131
+        $this->fixDI();
132
+
133
+        if (!$this->userExists($uid)) {
134
+            $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
135
+
136
+            $qb = $this->dbConn->getQueryBuilder();
137
+            $qb->insert($this->table)
138
+                ->values([
139
+                    'uid' => $qb->createNamedParameter($uid),
140
+                    'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
141
+                    'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
142
+                ]);
143
+
144
+            $result = $qb->execute();
145
+
146
+            // Clear cache
147
+            unset($this->cache[$uid]);
148
+
149
+            return $result ? true : false;
150
+        }
151
+
152
+        return false;
153
+    }
154
+
155
+    /**
156
+     * delete a user
157
+     *
158
+     * @param string $uid The username of the user to delete
159
+     * @return bool
160
+     *
161
+     * Deletes a user
162
+     */
163
+    public function deleteUser($uid) {
164
+        $this->fixDI();
165
+
166
+        // Delete user-group-relation
167
+        $query = $this->dbConn->getQueryBuilder();
168
+        $query->delete($this->table)
169
+            ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
170
+        $result = $query->execute();
171
+
172
+        if (isset($this->cache[$uid])) {
173
+            unset($this->cache[$uid]);
174
+        }
175
+
176
+        return $result ? true : false;
177
+    }
178
+
179
+    private function updatePassword(string $uid, string $passwordHash): bool {
180
+        $query = $this->dbConn->getQueryBuilder();
181
+        $query->update($this->table)
182
+            ->set('password', $query->createNamedParameter($passwordHash))
183
+            ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
184
+        $result = $query->execute();
185
+
186
+        return $result ? true : false;
187
+    }
188
+
189
+    /**
190
+     * Set password
191
+     *
192
+     * @param string $uid The username
193
+     * @param string $password The new password
194
+     * @return bool
195
+     *
196
+     * Change the password of a user
197
+     */
198
+    public function setPassword(string $uid, string $password): bool {
199
+        $this->fixDI();
200
+
201
+        if ($this->userExists($uid)) {
202
+            $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
203
+
204
+            $hasher = \OC::$server->getHasher();
205
+            $hashedPassword = $hasher->hash($password);
206
+
207
+            return $this->updatePassword($uid, $hashedPassword);
208
+        }
209
+
210
+        return false;
211
+    }
212
+
213
+    /**
214
+     * Set display name
215
+     *
216
+     * @param string $uid The username
217
+     * @param string $displayName The new display name
218
+     * @return bool
219
+     *
220
+     * Change the display name of a user
221
+     */
222
+    public function setDisplayName(string $uid, string $displayName): bool {
223
+        $this->fixDI();
224
+
225
+        if ($this->userExists($uid)) {
226
+            $query = $this->dbConn->getQueryBuilder();
227
+            $query->update($this->table)
228
+                ->set('displayname', $query->createNamedParameter($displayName))
229
+                ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
230
+            $query->execute();
231
+
232
+            $this->cache[$uid]['displayname'] = $displayName;
233
+
234
+            return true;
235
+        }
236
+
237
+        return false;
238
+    }
239
+
240
+    /**
241
+     * get display name of the user
242
+     *
243
+     * @param string $uid user ID of the user
244
+     * @return string display name
245
+     */
246
+    public function getDisplayName($uid): string {
247
+        $uid = (string)$uid;
248
+        $this->loadUser($uid);
249
+        return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
250
+    }
251
+
252
+    /**
253
+     * Get a list of all display names and user ids.
254
+     *
255
+     * @param string $search
256
+     * @param string|null $limit
257
+     * @param string|null $offset
258
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
259
+     */
260
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
261
+        $limit = $this->fixLimit($limit);
262
+
263
+        $this->fixDI();
264
+
265
+        $query = $this->dbConn->getQueryBuilder();
266
+
267
+        $query->select('uid', 'displayname')
268
+            ->from($this->table, 'u')
269
+            ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
270
+                $query->expr()->eq('userid', 'uid'),
271
+                $query->expr()->eq('appid', $query->expr()->literal('settings')),
272
+                $query->expr()->eq('configkey', $query->expr()->literal('email')))
273
+            )
274
+            // sqlite doesn't like re-using a single named parameter here
275
+            ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
276
+            ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
277
+            ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
278
+            ->orderBy($query->func()->lower('displayname'), 'ASC')
279
+            ->orderBy('uid_lower', 'ASC')
280
+            ->setMaxResults($limit)
281
+            ->setFirstResult($offset);
282
+
283
+        $result = $query->execute();
284
+        $displayNames = [];
285
+        while ($row = $result->fetch()) {
286
+            $displayNames[(string)$row['uid']] = (string)$row['displayname'];
287
+        }
288
+
289
+        return $displayNames;
290
+    }
291
+
292
+    /**
293
+     * Check if the password is correct
294
+     *
295
+     * @param string $uid The username
296
+     * @param string $password The password
297
+     * @return string
298
+     *
299
+     * Check if the password is correct without logging in the user
300
+     * returns the user id or false
301
+     */
302
+    public function checkPassword(string $uid, string $password) {
303
+        $this->fixDI();
304
+
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->select('uid', 'password')
307
+            ->from($this->table)
308
+            ->where(
309
+                $qb->expr()->eq(
310
+                    'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
311
+                )
312
+            );
313
+        $result = $qb->execute();
314
+        $row = $result->fetch();
315
+        $result->closeCursor();
316
+
317
+        if ($row) {
318
+            $storedHash = $row['password'];
319
+            $newHash = '';
320
+            if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
321
+                if (!empty($newHash)) {
322
+                    $this->updatePassword($uid, $newHash);
323
+                }
324
+                return (string)$row['uid'];
325
+            }
326
+
327
+        }
328
+
329
+        return false;
330
+    }
331
+
332
+    /**
333
+     * Load an user in the cache
334
+     *
335
+     * @param string $uid the username
336
+     * @return boolean true if user was found, false otherwise
337
+     */
338
+    private function loadUser($uid) {
339
+        $this->fixDI();
340
+
341
+        $uid = (string)$uid;
342
+        if (!isset($this->cache[$uid])) {
343
+            //guests $uid could be NULL or ''
344
+            if ($uid === '') {
345
+                $this->cache[$uid] = false;
346
+                return true;
347
+            }
348
+
349
+            $qb = $this->dbConn->getQueryBuilder();
350
+            $qb->select('uid', 'displayname')
351
+                ->from($this->table)
352
+                ->where(
353
+                    $qb->expr()->eq(
354
+                        'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
355
+                    )
356
+                );
357
+            $result = $qb->execute();
358
+            $row = $result->fetch();
359
+            $result->closeCursor();
360
+
361
+            $this->cache[$uid] = false;
362
+
363
+            // "uid" is primary key, so there can only be a single result
364
+            if ($row !== false) {
365
+                $this->cache[$uid]['uid'] = (string)$row['uid'];
366
+                $this->cache[$uid]['displayname'] = (string)$row['displayname'];
367
+            } else {
368
+                return false;
369
+            }
370
+        }
371
+
372
+        return true;
373
+    }
374
+
375
+    /**
376
+     * Get a list of all users
377
+     *
378
+     * @param string $search
379
+     * @param null|int $limit
380
+     * @param null|int $offset
381
+     * @return string[] an array of all uids
382
+     */
383
+    public function getUsers($search = '', $limit = null, $offset = null) {
384
+        $limit = $this->fixLimit($limit);
385
+
386
+        $users = $this->getDisplayNames($search, $limit, $offset);
387
+        $userIds = array_map(function ($uid) {
388
+            return (string)$uid;
389
+        }, array_keys($users));
390
+        sort($userIds, SORT_STRING | SORT_FLAG_CASE);
391
+        return $userIds;
392
+    }
393
+
394
+    /**
395
+     * check if a user exists
396
+     *
397
+     * @param string $uid the username
398
+     * @return boolean
399
+     */
400
+    public function userExists($uid) {
401
+        $this->loadUser($uid);
402
+        return $this->cache[$uid] !== false;
403
+    }
404
+
405
+    /**
406
+     * get the user's home directory
407
+     *
408
+     * @param string $uid the username
409
+     * @return string|false
410
+     */
411
+    public function getHome(string $uid) {
412
+        if ($this->userExists($uid)) {
413
+            return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
414
+        }
415
+
416
+        return false;
417
+    }
418
+
419
+    /**
420
+     * @return bool
421
+     */
422
+    public function hasUserListings() {
423
+        return true;
424
+    }
425
+
426
+    /**
427
+     * counts the users in the database
428
+     *
429
+     * @return int|bool
430
+     */
431
+    public function countUsers() {
432
+        $this->fixDI();
433
+
434
+        $query = $this->dbConn->getQueryBuilder();
435
+        $query->select($query->func()->count('uid'))
436
+            ->from($this->table);
437
+        $result = $query->execute();
438
+
439
+        return $result->fetchColumn();
440
+    }
441
+
442
+    /**
443
+     * returns the username for the given login name in the correct casing
444
+     *
445
+     * @param string $loginName
446
+     * @return string|false
447
+     */
448
+    public function loginName2UserName($loginName) {
449
+        if ($this->userExists($loginName)) {
450
+            return $this->cache[$loginName]['uid'];
451
+        }
452
+
453
+        return false;
454
+    }
455
+
456
+    /**
457
+     * Backend name to be shown in user management
458
+     *
459
+     * @return string the name of the backend to be shown
460
+     */
461
+    public function getBackendName() {
462
+        return 'Database';
463
+    }
464
+
465
+    public static function preLoginNameUsedAsUserName($param) {
466
+        if (!isset($param['uid'])) {
467
+            throw new \Exception('key uid is expected to be set in $param');
468
+        }
469
+
470
+        $backends = \OC::$server->getUserManager()->getBackends();
471
+        foreach ($backends as $backend) {
472
+            if ($backend instanceof Database) {
473
+                /** @var \OC\User\Database $backend */
474
+                $uid = $backend->loginName2UserName($param['uid']);
475
+                if ($uid !== false) {
476
+                    $param['uid'] = $uid;
477
+                    return;
478
+                }
479
+            }
480
+        }
481
+    }
482
+
483
+    public function getRealUID(string $uid): string {
484
+        if (!$this->userExists($uid)) {
485
+            throw new \RuntimeException($uid . ' does not exist');
486
+        }
487
+
488
+        return $this->cache[$uid]['uid'];
489
+    }
490
+
491
+    private function fixLimit($limit) {
492
+        if (is_int($limit) && $limit >= 0) {
493
+            return $limit;
494
+        }
495
+
496
+        return null;
497
+    }
498 498
 }
Please login to merge, or discard this patch.
lib/public/Security/Events/ValidatePasswordPolicyEvent.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -30,22 +30,22 @@
 block discarded – undo
30 30
  */
31 31
 class ValidatePasswordPolicyEvent extends Event {
32 32
 
33
-	/** @var string */
34
-	private $password;
35
-
36
-	/**
37
-	 * @since 18.0.0
38
-	 */
39
-	public function __construct(string $password) {
40
-		parent::__construct();
41
-		$this->password = $password;
42
-	}
43
-
44
-	/**
45
-	 * @since 18.0.0
46
-	 */
47
-	public function getPassword(): string {
48
-		return $this->password;
49
-	}
33
+    /** @var string */
34
+    private $password;
35
+
36
+    /**
37
+     * @since 18.0.0
38
+     */
39
+    public function __construct(string $password) {
40
+        parent::__construct();
41
+        $this->password = $password;
42
+    }
43
+
44
+    /**
45
+     * @since 18.0.0
46
+     */
47
+    public function getPassword(): string {
48
+        return $this->password;
49
+    }
50 50
 
51 51
 }
Please login to merge, or discard this patch.
lib/public/Security/Events/GenerateSecurePasswordEvent.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -30,21 +30,21 @@
 block discarded – undo
30 30
  */
31 31
 class GenerateSecurePasswordEvent extends Event {
32 32
 
33
-	/** @var null|string */
34
-	private $password;
35
-
36
-	/**
37
-	 * @since 18.0.0
38
-	 */
39
-	public function getPassword(): ?string {
40
-		return $this->password;
41
-	}
42
-
43
-	/**
44
-	 * @since 18.0.0
45
-	 */
46
-	public function setPassword(string $password): void {
47
-		$this->password = $password;
48
-	}
33
+    /** @var null|string */
34
+    private $password;
35
+
36
+    /**
37
+     * @since 18.0.0
38
+     */
39
+    public function getPassword(): ?string {
40
+        return $this->password;
41
+    }
42
+
43
+    /**
44
+     * @since 18.0.0
45
+     */
46
+    public function setPassword(string $password): void {
47
+        $this->password = $password;
48
+    }
49 49
 
50 50
 }
Please login to merge, or discard this patch.