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