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