Passed
Push — master ( d32af3...6846a8 )
by Roeland
14:56 queued 11s
created
lib/private/Share20/Manager.php 1 patch
Indentation   +1802 added lines, -1802 removed lines patch added patch discarded remove patch
@@ -77,1829 +77,1829 @@
 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
-				throw new \Exception('Sharing is only allowed with group members');
546
-			}
547
-		}
548
-
549
-		/*
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
+                throw new \Exception('Sharing is only allowed with group members');
546
+            }
547
+        }
548
+
549
+        /*
550 550
 		 * TODO: Could be costly, fix
551 551
 		 *
552 552
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
553 553
 		 */
554
-		$provider = $this->factory->getProviderForType(IShare::TYPE_USER);
555
-		$existingShares = $provider->getSharesByPath($share->getNode());
556
-		foreach ($existingShares as $existingShare) {
557
-			// Ignore if it is the same share
558
-			try {
559
-				if ($existingShare->getFullId() === $share->getFullId()) {
560
-					continue;
561
-				}
562
-			} catch (\UnexpectedValueException $e) {
563
-				//Shares are not identical
564
-			}
565
-
566
-			// Identical share already existst
567
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
568
-				throw new \Exception('Path is already shared with this user');
569
-			}
570
-
571
-			// The share is already shared with this user via a group share
572
-			if ($existingShare->getShareType() === IShare::TYPE_GROUP) {
573
-				$group = $this->groupManager->get($existingShare->getSharedWith());
574
-				if (!is_null($group)) {
575
-					$user = $this->userManager->get($share->getSharedWith());
576
-
577
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
578
-						throw new \Exception('Path is already shared with this user');
579
-					}
580
-				}
581
-			}
582
-		}
583
-	}
584
-
585
-	/**
586
-	 * Check for pre share requirements for group shares
587
-	 *
588
-	 * @param IShare $share
589
-	 * @throws \Exception
590
-	 */
591
-	protected function groupCreateChecks(IShare $share) {
592
-		// Verify group shares are allowed
593
-		if (!$this->allowGroupSharing()) {
594
-			throw new \Exception('Group sharing is now allowed');
595
-		}
596
-
597
-		// Verify if the user can share with this group
598
-		if ($this->shareWithGroupMembersOnly()) {
599
-			$sharedBy = $this->userManager->get($share->getSharedBy());
600
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
601
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
602
-				throw new \Exception('Sharing is only allowed within your own groups');
603
-			}
604
-		}
605
-
606
-		/*
554
+        $provider = $this->factory->getProviderForType(IShare::TYPE_USER);
555
+        $existingShares = $provider->getSharesByPath($share->getNode());
556
+        foreach ($existingShares as $existingShare) {
557
+            // Ignore if it is the same share
558
+            try {
559
+                if ($existingShare->getFullId() === $share->getFullId()) {
560
+                    continue;
561
+                }
562
+            } catch (\UnexpectedValueException $e) {
563
+                //Shares are not identical
564
+            }
565
+
566
+            // Identical share already existst
567
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
568
+                throw new \Exception('Path is already shared with this user');
569
+            }
570
+
571
+            // The share is already shared with this user via a group share
572
+            if ($existingShare->getShareType() === IShare::TYPE_GROUP) {
573
+                $group = $this->groupManager->get($existingShare->getSharedWith());
574
+                if (!is_null($group)) {
575
+                    $user = $this->userManager->get($share->getSharedWith());
576
+
577
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
578
+                        throw new \Exception('Path is already shared with this user');
579
+                    }
580
+                }
581
+            }
582
+        }
583
+    }
584
+
585
+    /**
586
+     * Check for pre share requirements for group shares
587
+     *
588
+     * @param IShare $share
589
+     * @throws \Exception
590
+     */
591
+    protected function groupCreateChecks(IShare $share) {
592
+        // Verify group shares are allowed
593
+        if (!$this->allowGroupSharing()) {
594
+            throw new \Exception('Group sharing is now allowed');
595
+        }
596
+
597
+        // Verify if the user can share with this group
598
+        if ($this->shareWithGroupMembersOnly()) {
599
+            $sharedBy = $this->userManager->get($share->getSharedBy());
600
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
601
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
602
+                throw new \Exception('Sharing is only allowed within your own groups');
603
+            }
604
+        }
605
+
606
+        /*
607 607
 		 * TODO: Could be costly, fix
608 608
 		 *
609 609
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
610 610
 		 */
611
-		$provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
612
-		$existingShares = $provider->getSharesByPath($share->getNode());
613
-		foreach ($existingShares as $existingShare) {
614
-			try {
615
-				if ($existingShare->getFullId() === $share->getFullId()) {
616
-					continue;
617
-				}
618
-			} catch (\UnexpectedValueException $e) {
619
-				//It is a new share so just continue
620
-			}
621
-
622
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
623
-				throw new \Exception('Path is already shared with this group');
624
-			}
625
-		}
626
-	}
627
-
628
-	/**
629
-	 * Check for pre share requirements for link shares
630
-	 *
631
-	 * @param IShare $share
632
-	 * @throws \Exception
633
-	 */
634
-	protected function linkCreateChecks(IShare $share) {
635
-		// Are link shares allowed?
636
-		if (!$this->shareApiAllowLinks()) {
637
-			throw new \Exception('Link sharing is not allowed');
638
-		}
639
-
640
-		// Check if public upload is allowed
641
-		if (!$this->shareApiLinkAllowPublicUpload() &&
642
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
643
-			throw new \InvalidArgumentException('Public upload is not allowed');
644
-		}
645
-	}
646
-
647
-	/**
648
-	 * To make sure we don't get invisible link shares we set the parent
649
-	 * of a link if it is a reshare. This is a quick word around
650
-	 * until we can properly display multiple link shares in the UI
651
-	 *
652
-	 * See: https://github.com/owncloud/core/issues/22295
653
-	 *
654
-	 * FIXME: Remove once multiple link shares can be properly displayed
655
-	 *
656
-	 * @param IShare $share
657
-	 */
658
-	protected function setLinkParent(IShare $share) {
659
-
660
-		// No sense in checking if the method is not there.
661
-		if (method_exists($share, 'setParent')) {
662
-			$storage = $share->getNode()->getStorage();
663
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
664
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
665
-				$share->setParent($storage->getShareId());
666
-			}
667
-		}
668
-	}
669
-
670
-	/**
671
-	 * @param File|Folder $path
672
-	 */
673
-	protected function pathCreateChecks($path) {
674
-		// Make sure that we do not share a path that contains a shared mountpoint
675
-		if ($path instanceof \OCP\Files\Folder) {
676
-			$mounts = $this->mountManager->findIn($path->getPath());
677
-			foreach ($mounts as $mount) {
678
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
679
-					throw new \InvalidArgumentException('Path contains files shared with you');
680
-				}
681
-			}
682
-		}
683
-	}
684
-
685
-	/**
686
-	 * Check if the user that is sharing can actually share
687
-	 *
688
-	 * @param IShare $share
689
-	 * @throws \Exception
690
-	 */
691
-	protected function canShare(IShare $share) {
692
-		if (!$this->shareApiEnabled()) {
693
-			throw new \Exception('Sharing is disabled');
694
-		}
695
-
696
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
697
-			throw new \Exception('Sharing is disabled for you');
698
-		}
699
-	}
700
-
701
-	/**
702
-	 * Share a path
703
-	 *
704
-	 * @param IShare $share
705
-	 * @return IShare The share object
706
-	 * @throws \Exception
707
-	 *
708
-	 * TODO: handle link share permissions or check them
709
-	 */
710
-	public function createShare(IShare $share) {
711
-		$this->canShare($share);
712
-
713
-		$this->generalCreateChecks($share);
714
-
715
-		// Verify if there are any issues with the path
716
-		$this->pathCreateChecks($share->getNode());
717
-
718
-		/*
611
+        $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
612
+        $existingShares = $provider->getSharesByPath($share->getNode());
613
+        foreach ($existingShares as $existingShare) {
614
+            try {
615
+                if ($existingShare->getFullId() === $share->getFullId()) {
616
+                    continue;
617
+                }
618
+            } catch (\UnexpectedValueException $e) {
619
+                //It is a new share so just continue
620
+            }
621
+
622
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
623
+                throw new \Exception('Path is already shared with this group');
624
+            }
625
+        }
626
+    }
627
+
628
+    /**
629
+     * Check for pre share requirements for link shares
630
+     *
631
+     * @param IShare $share
632
+     * @throws \Exception
633
+     */
634
+    protected function linkCreateChecks(IShare $share) {
635
+        // Are link shares allowed?
636
+        if (!$this->shareApiAllowLinks()) {
637
+            throw new \Exception('Link sharing is not allowed');
638
+        }
639
+
640
+        // Check if public upload is allowed
641
+        if (!$this->shareApiLinkAllowPublicUpload() &&
642
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
643
+            throw new \InvalidArgumentException('Public upload is not allowed');
644
+        }
645
+    }
646
+
647
+    /**
648
+     * To make sure we don't get invisible link shares we set the parent
649
+     * of a link if it is a reshare. This is a quick word around
650
+     * until we can properly display multiple link shares in the UI
651
+     *
652
+     * See: https://github.com/owncloud/core/issues/22295
653
+     *
654
+     * FIXME: Remove once multiple link shares can be properly displayed
655
+     *
656
+     * @param IShare $share
657
+     */
658
+    protected function setLinkParent(IShare $share) {
659
+
660
+        // No sense in checking if the method is not there.
661
+        if (method_exists($share, 'setParent')) {
662
+            $storage = $share->getNode()->getStorage();
663
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
664
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
665
+                $share->setParent($storage->getShareId());
666
+            }
667
+        }
668
+    }
669
+
670
+    /**
671
+     * @param File|Folder $path
672
+     */
673
+    protected function pathCreateChecks($path) {
674
+        // Make sure that we do not share a path that contains a shared mountpoint
675
+        if ($path instanceof \OCP\Files\Folder) {
676
+            $mounts = $this->mountManager->findIn($path->getPath());
677
+            foreach ($mounts as $mount) {
678
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
679
+                    throw new \InvalidArgumentException('Path contains files shared with you');
680
+                }
681
+            }
682
+        }
683
+    }
684
+
685
+    /**
686
+     * Check if the user that is sharing can actually share
687
+     *
688
+     * @param IShare $share
689
+     * @throws \Exception
690
+     */
691
+    protected function canShare(IShare $share) {
692
+        if (!$this->shareApiEnabled()) {
693
+            throw new \Exception('Sharing is disabled');
694
+        }
695
+
696
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
697
+            throw new \Exception('Sharing is disabled for you');
698
+        }
699
+    }
700
+
701
+    /**
702
+     * Share a path
703
+     *
704
+     * @param IShare $share
705
+     * @return IShare The share object
706
+     * @throws \Exception
707
+     *
708
+     * TODO: handle link share permissions or check them
709
+     */
710
+    public function createShare(IShare $share) {
711
+        $this->canShare($share);
712
+
713
+        $this->generalCreateChecks($share);
714
+
715
+        // Verify if there are any issues with the path
716
+        $this->pathCreateChecks($share->getNode());
717
+
718
+        /*
719 719
 		 * On creation of a share the owner is always the owner of the path
720 720
 		 * Except for mounted federated shares.
721 721
 		 */
722
-		$storage = $share->getNode()->getStorage();
723
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
724
-			$parent = $share->getNode()->getParent();
725
-			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
726
-				$parent = $parent->getParent();
727
-			}
728
-			$share->setShareOwner($parent->getOwner()->getUID());
729
-		} else {
730
-			if ($share->getNode()->getOwner()) {
731
-				$share->setShareOwner($share->getNode()->getOwner()->getUID());
732
-			} else {
733
-				$share->setShareOwner($share->getSharedBy());
734
-			}
735
-		}
736
-
737
-		//Verify share type
738
-		if ($share->getShareType() === IShare::TYPE_USER) {
739
-			$this->userCreateChecks($share);
740
-
741
-			//Verify the expiration date
742
-			$share = $this->validateExpirationDateInternal($share);
743
-		} elseif ($share->getShareType() === IShare::TYPE_GROUP) {
744
-			$this->groupCreateChecks($share);
745
-
746
-			//Verify the expiration date
747
-			$share = $this->validateExpirationDateInternal($share);
748
-		} elseif ($share->getShareType() === IShare::TYPE_LINK) {
749
-			$this->linkCreateChecks($share);
750
-			$this->setLinkParent($share);
751
-
752
-			/*
722
+        $storage = $share->getNode()->getStorage();
723
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
724
+            $parent = $share->getNode()->getParent();
725
+            while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
726
+                $parent = $parent->getParent();
727
+            }
728
+            $share->setShareOwner($parent->getOwner()->getUID());
729
+        } else {
730
+            if ($share->getNode()->getOwner()) {
731
+                $share->setShareOwner($share->getNode()->getOwner()->getUID());
732
+            } else {
733
+                $share->setShareOwner($share->getSharedBy());
734
+            }
735
+        }
736
+
737
+        //Verify share type
738
+        if ($share->getShareType() === IShare::TYPE_USER) {
739
+            $this->userCreateChecks($share);
740
+
741
+            //Verify the expiration date
742
+            $share = $this->validateExpirationDateInternal($share);
743
+        } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
744
+            $this->groupCreateChecks($share);
745
+
746
+            //Verify the expiration date
747
+            $share = $this->validateExpirationDateInternal($share);
748
+        } elseif ($share->getShareType() === IShare::TYPE_LINK) {
749
+            $this->linkCreateChecks($share);
750
+            $this->setLinkParent($share);
751
+
752
+            /*
753 753
 			 * For now ignore a set token.
754 754
 			 */
755
-			$share->setToken(
756
-				$this->secureRandom->generate(
757
-					\OC\Share\Constants::TOKEN_LENGTH,
758
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
-				)
760
-			);
761
-
762
-			//Verify the expiration date
763
-			$share = $this->validateExpirationDate($share);
764
-
765
-			//Verify the password
766
-			$this->verifyPassword($share->getPassword());
767
-
768
-			// If a password is set. Hash it!
769
-			if ($share->getPassword() !== null) {
770
-				$share->setPassword($this->hasher->hash($share->getPassword()));
771
-			}
772
-		} elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
773
-			$share->setToken(
774
-				$this->secureRandom->generate(
775
-					\OC\Share\Constants::TOKEN_LENGTH,
776
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
777
-				)
778
-			);
779
-		}
780
-
781
-		// Cannot share with the owner
782
-		if ($share->getShareType() === IShare::TYPE_USER &&
783
-			$share->getSharedWith() === $share->getShareOwner()) {
784
-			throw new \InvalidArgumentException('Can’t share with the share owner');
785
-		}
786
-
787
-		// Generate the target
788
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
789
-		$target = \OC\Files\Filesystem::normalizePath($target);
790
-		$share->setTarget($target);
791
-
792
-		// Pre share event
793
-		$event = new GenericEvent($share);
794
-		$this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
795
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
796
-			throw new \Exception($event->getArgument('error'));
797
-		}
798
-
799
-		$oldShare = $share;
800
-		$provider = $this->factory->getProviderForType($share->getShareType());
801
-		$share = $provider->create($share);
802
-		//reuse the node we already have
803
-		$share->setNode($oldShare->getNode());
804
-
805
-		// Reset the target if it is null for the new share
806
-		if ($share->getTarget() === '') {
807
-			$share->setTarget($target);
808
-		}
809
-
810
-		// Post share event
811
-		$event = new GenericEvent($share);
812
-		$this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
813
-
814
-		$this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
815
-
816
-		if ($this->config->getSystemValueBool('sharing.enable_share_mail', true)
817
-			&& $share->getShareType() === IShare::TYPE_USER) {
818
-			$mailSend = $share->getMailSend();
819
-			if ($mailSend === true) {
820
-				$user = $this->userManager->get($share->getSharedWith());
821
-				if ($user !== null) {
822
-					$emailAddress = $user->getEMailAddress();
823
-					if ($emailAddress !== null && $emailAddress !== '') {
824
-						$userLang = $this->l10nFactory->getUserLanguage($user);
825
-						$l = $this->l10nFactory->get('lib', $userLang);
826
-						$this->sendMailNotification(
827
-							$l,
828
-							$share->getNode()->getName(),
829
-							$this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
830
-							$share->getSharedBy(),
831
-							$emailAddress,
832
-							$share->getExpirationDate()
833
-						);
834
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
835
-					} else {
836
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
837
-					}
838
-				} else {
839
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
840
-				}
841
-			} else {
842
-				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
843
-			}
844
-		}
845
-
846
-		return $share;
847
-	}
848
-
849
-	/**
850
-	 * Send mail notifications
851
-	 *
852
-	 * This method will catch and log mail transmission errors
853
-	 *
854
-	 * @param IL10N $l Language of the recipient
855
-	 * @param string $filename file/folder name
856
-	 * @param string $link link to the file/folder
857
-	 * @param string $initiator user ID of share sender
858
-	 * @param string $shareWith email address of share receiver
859
-	 * @param \DateTime|null $expiration
860
-	 */
861
-	protected function sendMailNotification(IL10N $l,
862
-											$filename,
863
-											$link,
864
-											$initiator,
865
-											$shareWith,
866
-											\DateTime $expiration = null) {
867
-		$initiatorUser = $this->userManager->get($initiator);
868
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
869
-
870
-		$message = $this->mailer->createMessage();
871
-
872
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
873
-			'filename' => $filename,
874
-			'link' => $link,
875
-			'initiator' => $initiatorDisplayName,
876
-			'expiration' => $expiration,
877
-			'shareWith' => $shareWith,
878
-		]);
879
-
880
-		$emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
881
-		$emailTemplate->addHeader();
882
-		$emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
883
-		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
884
-
885
-		$emailTemplate->addBodyText(
886
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
887
-			$text
888
-		);
889
-		$emailTemplate->addBodyButton(
890
-			$l->t('Open »%s«', [$filename]),
891
-			$link
892
-		);
893
-
894
-		$message->setTo([$shareWith]);
895
-
896
-		// The "From" contains the sharers name
897
-		$instanceName = $this->defaults->getName();
898
-		$senderName = $l->t(
899
-			'%1$s via %2$s',
900
-			[
901
-				$initiatorDisplayName,
902
-				$instanceName
903
-			]
904
-		);
905
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
906
-
907
-		// The "Reply-To" is set to the sharer if an mail address is configured
908
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
909
-		$initiatorEmail = $initiatorUser->getEMailAddress();
910
-		if ($initiatorEmail !== null) {
911
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
912
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : ''));
913
-		} else {
914
-			$emailTemplate->addFooter('', $l->getLanguageCode());
915
-		}
916
-
917
-		$message->useTemplate($emailTemplate);
918
-		try {
919
-			$failedRecipients = $this->mailer->send($message);
920
-			if (!empty($failedRecipients)) {
921
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
922
-				return;
923
-			}
924
-		} catch (\Exception $e) {
925
-			$this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
926
-		}
927
-	}
928
-
929
-	/**
930
-	 * Update a share
931
-	 *
932
-	 * @param IShare $share
933
-	 * @return IShare The share object
934
-	 * @throws \InvalidArgumentException
935
-	 */
936
-	public function updateShare(IShare $share) {
937
-		$expirationDateUpdated = false;
938
-
939
-		$this->canShare($share);
940
-
941
-		try {
942
-			$originalShare = $this->getShareById($share->getFullId());
943
-		} catch (\UnexpectedValueException $e) {
944
-			throw new \InvalidArgumentException('Share does not have a full id');
945
-		}
946
-
947
-		// We can't change the share type!
948
-		if ($share->getShareType() !== $originalShare->getShareType()) {
949
-			throw new \InvalidArgumentException('Can’t change share type');
950
-		}
951
-
952
-		// We can only change the recipient on user shares
953
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
954
-			$share->getShareType() !== IShare::TYPE_USER) {
955
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
956
-		}
957
-
958
-		// Cannot share with the owner
959
-		if ($share->getShareType() === IShare::TYPE_USER &&
960
-			$share->getSharedWith() === $share->getShareOwner()) {
961
-			throw new \InvalidArgumentException('Can’t share with the share owner');
962
-		}
963
-
964
-		$this->generalCreateChecks($share);
965
-
966
-		if ($share->getShareType() === IShare::TYPE_USER) {
967
-			$this->userCreateChecks($share);
968
-
969
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
970
-				//Verify the expiration date
971
-				$this->validateExpirationDate($share);
972
-				$expirationDateUpdated = true;
973
-			}
974
-		} elseif ($share->getShareType() === IShare::TYPE_GROUP) {
975
-			$this->groupCreateChecks($share);
976
-
977
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
978
-				//Verify the expiration date
979
-				$this->validateExpirationDate($share);
980
-				$expirationDateUpdated = true;
981
-			}
982
-		} elseif ($share->getShareType() === IShare::TYPE_LINK) {
983
-			$this->linkCreateChecks($share);
984
-
985
-			$plainTextPassword = $share->getPassword();
986
-
987
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
988
-
989
-			if (empty($plainTextPassword) && $share->getSendPasswordByTalk()) {
990
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk with an empty password');
991
-			}
992
-
993
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
994
-				//Verify the expiration date
995
-				$this->validateExpirationDate($share);
996
-				$expirationDateUpdated = true;
997
-			}
998
-		} elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
999
-			// The new password is not set again if it is the same as the old
1000
-			// one.
1001
-			$plainTextPassword = $share->getPassword();
1002
-			if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare)) {
1003
-				$plainTextPassword = null;
1004
-			}
1005
-			if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
1006
-				// If the same password was already sent by mail the recipient
1007
-				// would already have access to the share without having to call
1008
-				// the sharer to verify her identity
1009
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
1010
-			} elseif (empty($plainTextPassword) && $originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()) {
1011
-				throw new \InvalidArgumentException('Can’t disable sending the password by Talk without setting a new password');
1012
-			}
1013
-		}
1014
-
1015
-		$this->pathCreateChecks($share->getNode());
1016
-
1017
-		// Now update the share!
1018
-		$provider = $this->factory->getProviderForType($share->getShareType());
1019
-		if ($share->getShareType() === IShare::TYPE_EMAIL) {
1020
-			$share = $provider->update($share, $plainTextPassword);
1021
-		} else {
1022
-			$share = $provider->update($share);
1023
-		}
1024
-
1025
-		if ($expirationDateUpdated === true) {
1026
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1027
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1028
-				'itemSource' => $share->getNode()->getId(),
1029
-				'date' => $share->getExpirationDate(),
1030
-				'uidOwner' => $share->getSharedBy(),
1031
-			]);
1032
-		}
1033
-
1034
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1035
-			\OC_Hook::emit(Share::class, 'post_update_password', [
1036
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1037
-				'itemSource' => $share->getNode()->getId(),
1038
-				'uidOwner' => $share->getSharedBy(),
1039
-				'token' => $share->getToken(),
1040
-				'disabled' => is_null($share->getPassword()),
1041
-			]);
1042
-		}
1043
-
1044
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
1045
-			if ($this->userManager->userExists($share->getShareOwner())) {
1046
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1047
-			} else {
1048
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1049
-			}
1050
-			\OC_Hook::emit(Share::class, 'post_update_permissions', [
1051
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1052
-				'itemSource' => $share->getNode()->getId(),
1053
-				'shareType' => $share->getShareType(),
1054
-				'shareWith' => $share->getSharedWith(),
1055
-				'uidOwner' => $share->getSharedBy(),
1056
-				'permissions' => $share->getPermissions(),
1057
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1058
-			]);
1059
-		}
1060
-
1061
-		return $share;
1062
-	}
1063
-
1064
-	/**
1065
-	 * Accept a share.
1066
-	 *
1067
-	 * @param IShare $share
1068
-	 * @param string $recipientId
1069
-	 * @return IShare The share object
1070
-	 * @throws \InvalidArgumentException
1071
-	 * @since 9.0.0
1072
-	 */
1073
-	public function acceptShare(IShare $share, string $recipientId): IShare {
1074
-		[$providerId, ] = $this->splitFullId($share->getFullId());
1075
-		$provider = $this->factory->getProvider($providerId);
1076
-
1077
-		if (!method_exists($provider, 'acceptShare')) {
1078
-			// TODO FIX ME
1079
-			throw new \InvalidArgumentException('Share provider does not support accepting');
1080
-		}
1081
-		$provider->acceptShare($share, $recipientId);
1082
-		$event = new GenericEvent($share);
1083
-		$this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1084
-
1085
-		return $share;
1086
-	}
1087
-
1088
-	/**
1089
-	 * Updates the password of the given share if it is not the same as the
1090
-	 * password of the original share.
1091
-	 *
1092
-	 * @param IShare $share the share to update its password.
1093
-	 * @param IShare $originalShare the original share to compare its
1094
-	 *        password with.
1095
-	 * @return boolean whether the password was updated or not.
1096
-	 */
1097
-	private function updateSharePasswordIfNeeded(IShare $share, IShare $originalShare) {
1098
-		$passwordsAreDifferent = ($share->getPassword() !== $originalShare->getPassword()) &&
1099
-									(($share->getPassword() !== null && $originalShare->getPassword() === null) ||
1100
-									 ($share->getPassword() === null && $originalShare->getPassword() !== null) ||
1101
-									 ($share->getPassword() !== null && $originalShare->getPassword() !== null &&
1102
-										!$this->hasher->verify($share->getPassword(), $originalShare->getPassword())));
1103
-
1104
-		// Password updated.
1105
-		if ($passwordsAreDifferent) {
1106
-			//Verify the password
1107
-			$this->verifyPassword($share->getPassword());
1108
-
1109
-			// If a password is set. Hash it!
1110
-			if ($share->getPassword() !== null) {
1111
-				$share->setPassword($this->hasher->hash($share->getPassword()));
1112
-
1113
-				return true;
1114
-			}
1115
-		} else {
1116
-			// Reset the password to the original one, as it is either the same
1117
-			// as the "new" password or a hashed version of it.
1118
-			$share->setPassword($originalShare->getPassword());
1119
-		}
1120
-
1121
-		return false;
1122
-	}
1123
-
1124
-	/**
1125
-	 * Delete all the children of this share
1126
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1127
-	 *
1128
-	 * @param IShare $share
1129
-	 * @return IShare[] List of deleted shares
1130
-	 */
1131
-	protected function deleteChildren(IShare $share) {
1132
-		$deletedShares = [];
1133
-
1134
-		$provider = $this->factory->getProviderForType($share->getShareType());
1135
-
1136
-		foreach ($provider->getChildren($share) as $child) {
1137
-			$deletedChildren = $this->deleteChildren($child);
1138
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
1139
-
1140
-			$provider->delete($child);
1141
-			$this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($child));
1142
-			$deletedShares[] = $child;
1143
-		}
1144
-
1145
-		return $deletedShares;
1146
-	}
1147
-
1148
-	/**
1149
-	 * Delete a share
1150
-	 *
1151
-	 * @param IShare $share
1152
-	 * @throws ShareNotFound
1153
-	 * @throws \InvalidArgumentException
1154
-	 */
1155
-	public function deleteShare(IShare $share) {
1156
-		try {
1157
-			$share->getFullId();
1158
-		} catch (\UnexpectedValueException $e) {
1159
-			throw new \InvalidArgumentException('Share does not have a full id');
1160
-		}
1161
-
1162
-		$event = new GenericEvent($share);
1163
-		$this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1164
-
1165
-		// Get all children and delete them as well
1166
-		$deletedShares = $this->deleteChildren($share);
1167
-
1168
-		// Do the actual delete
1169
-		$provider = $this->factory->getProviderForType($share->getShareType());
1170
-		$provider->delete($share);
1171
-
1172
-		$this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($share));
1173
-
1174
-		// All the deleted shares caused by this delete
1175
-		$deletedShares[] = $share;
1176
-
1177
-		// Emit post hook
1178
-		$event->setArgument('deletedShares', $deletedShares);
1179
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1180
-	}
1181
-
1182
-
1183
-	/**
1184
-	 * Unshare a file as the recipient.
1185
-	 * This can be different from a regular delete for example when one of
1186
-	 * the users in a groups deletes that share. But the provider should
1187
-	 * handle this.
1188
-	 *
1189
-	 * @param IShare $share
1190
-	 * @param string $recipientId
1191
-	 */
1192
-	public function deleteFromSelf(IShare $share, $recipientId) {
1193
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1194
-		$provider = $this->factory->getProvider($providerId);
1195
-
1196
-		$provider->deleteFromSelf($share, $recipientId);
1197
-		$event = new GenericEvent($share);
1198
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1199
-	}
1200
-
1201
-	public function restoreShare(IShare $share, string $recipientId): IShare {
1202
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1203
-		$provider = $this->factory->getProvider($providerId);
1204
-
1205
-		return $provider->restore($share, $recipientId);
1206
-	}
1207
-
1208
-	/**
1209
-	 * @inheritdoc
1210
-	 */
1211
-	public function moveShare(IShare $share, $recipientId) {
1212
-		if ($share->getShareType() === IShare::TYPE_LINK) {
1213
-			throw new \InvalidArgumentException('Can’t change target of link share');
1214
-		}
1215
-
1216
-		if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) {
1217
-			throw new \InvalidArgumentException('Invalid recipient');
1218
-		}
1219
-
1220
-		if ($share->getShareType() === IShare::TYPE_GROUP) {
1221
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1222
-			if (is_null($sharedWith)) {
1223
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1224
-			}
1225
-			$recipient = $this->userManager->get($recipientId);
1226
-			if (!$sharedWith->inGroup($recipient)) {
1227
-				throw new \InvalidArgumentException('Invalid recipient');
1228
-			}
1229
-		}
1230
-
1231
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1232
-		$provider = $this->factory->getProvider($providerId);
1233
-
1234
-		return $provider->move($share, $recipientId);
1235
-	}
1236
-
1237
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1238
-		$providers = $this->factory->getAllProviders();
1239
-
1240
-		return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1241
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1242
-			foreach ($newShares as $fid => $data) {
1243
-				if (!isset($shares[$fid])) {
1244
-					$shares[$fid] = [];
1245
-				}
1246
-
1247
-				$shares[$fid] = array_merge($shares[$fid], $data);
1248
-			}
1249
-			return $shares;
1250
-		}, []);
1251
-	}
1252
-
1253
-	/**
1254
-	 * @inheritdoc
1255
-	 */
1256
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1257
-		if ($path !== null &&
1258
-				!($path instanceof \OCP\Files\File) &&
1259
-				!($path instanceof \OCP\Files\Folder)) {
1260
-			throw new \InvalidArgumentException('invalid path');
1261
-		}
1262
-
1263
-		try {
1264
-			$provider = $this->factory->getProviderForType($shareType);
1265
-		} catch (ProviderException $e) {
1266
-			return [];
1267
-		}
1268
-
1269
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1270
-
1271
-		/*
755
+            $share->setToken(
756
+                $this->secureRandom->generate(
757
+                    \OC\Share\Constants::TOKEN_LENGTH,
758
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
+                )
760
+            );
761
+
762
+            //Verify the expiration date
763
+            $share = $this->validateExpirationDate($share);
764
+
765
+            //Verify the password
766
+            $this->verifyPassword($share->getPassword());
767
+
768
+            // If a password is set. Hash it!
769
+            if ($share->getPassword() !== null) {
770
+                $share->setPassword($this->hasher->hash($share->getPassword()));
771
+            }
772
+        } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
773
+            $share->setToken(
774
+                $this->secureRandom->generate(
775
+                    \OC\Share\Constants::TOKEN_LENGTH,
776
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
777
+                )
778
+            );
779
+        }
780
+
781
+        // Cannot share with the owner
782
+        if ($share->getShareType() === IShare::TYPE_USER &&
783
+            $share->getSharedWith() === $share->getShareOwner()) {
784
+            throw new \InvalidArgumentException('Can’t share with the share owner');
785
+        }
786
+
787
+        // Generate the target
788
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
789
+        $target = \OC\Files\Filesystem::normalizePath($target);
790
+        $share->setTarget($target);
791
+
792
+        // Pre share event
793
+        $event = new GenericEvent($share);
794
+        $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
795
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
796
+            throw new \Exception($event->getArgument('error'));
797
+        }
798
+
799
+        $oldShare = $share;
800
+        $provider = $this->factory->getProviderForType($share->getShareType());
801
+        $share = $provider->create($share);
802
+        //reuse the node we already have
803
+        $share->setNode($oldShare->getNode());
804
+
805
+        // Reset the target if it is null for the new share
806
+        if ($share->getTarget() === '') {
807
+            $share->setTarget($target);
808
+        }
809
+
810
+        // Post share event
811
+        $event = new GenericEvent($share);
812
+        $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
813
+
814
+        $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
815
+
816
+        if ($this->config->getSystemValueBool('sharing.enable_share_mail', true)
817
+            && $share->getShareType() === IShare::TYPE_USER) {
818
+            $mailSend = $share->getMailSend();
819
+            if ($mailSend === true) {
820
+                $user = $this->userManager->get($share->getSharedWith());
821
+                if ($user !== null) {
822
+                    $emailAddress = $user->getEMailAddress();
823
+                    if ($emailAddress !== null && $emailAddress !== '') {
824
+                        $userLang = $this->l10nFactory->getUserLanguage($user);
825
+                        $l = $this->l10nFactory->get('lib', $userLang);
826
+                        $this->sendMailNotification(
827
+                            $l,
828
+                            $share->getNode()->getName(),
829
+                            $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
830
+                            $share->getSharedBy(),
831
+                            $emailAddress,
832
+                            $share->getExpirationDate()
833
+                        );
834
+                        $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
835
+                    } else {
836
+                        $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
837
+                    }
838
+                } else {
839
+                    $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
840
+                }
841
+            } else {
842
+                $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
843
+            }
844
+        }
845
+
846
+        return $share;
847
+    }
848
+
849
+    /**
850
+     * Send mail notifications
851
+     *
852
+     * This method will catch and log mail transmission errors
853
+     *
854
+     * @param IL10N $l Language of the recipient
855
+     * @param string $filename file/folder name
856
+     * @param string $link link to the file/folder
857
+     * @param string $initiator user ID of share sender
858
+     * @param string $shareWith email address of share receiver
859
+     * @param \DateTime|null $expiration
860
+     */
861
+    protected function sendMailNotification(IL10N $l,
862
+                                            $filename,
863
+                                            $link,
864
+                                            $initiator,
865
+                                            $shareWith,
866
+                                            \DateTime $expiration = null) {
867
+        $initiatorUser = $this->userManager->get($initiator);
868
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
869
+
870
+        $message = $this->mailer->createMessage();
871
+
872
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
873
+            'filename' => $filename,
874
+            'link' => $link,
875
+            'initiator' => $initiatorDisplayName,
876
+            'expiration' => $expiration,
877
+            'shareWith' => $shareWith,
878
+        ]);
879
+
880
+        $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
881
+        $emailTemplate->addHeader();
882
+        $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
883
+        $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
884
+
885
+        $emailTemplate->addBodyText(
886
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
887
+            $text
888
+        );
889
+        $emailTemplate->addBodyButton(
890
+            $l->t('Open »%s«', [$filename]),
891
+            $link
892
+        );
893
+
894
+        $message->setTo([$shareWith]);
895
+
896
+        // The "From" contains the sharers name
897
+        $instanceName = $this->defaults->getName();
898
+        $senderName = $l->t(
899
+            '%1$s via %2$s',
900
+            [
901
+                $initiatorDisplayName,
902
+                $instanceName
903
+            ]
904
+        );
905
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
906
+
907
+        // The "Reply-To" is set to the sharer if an mail address is configured
908
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
909
+        $initiatorEmail = $initiatorUser->getEMailAddress();
910
+        if ($initiatorEmail !== null) {
911
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
912
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan($l->getLanguageCode()) !== '' ? ' - ' . $this->defaults->getSlogan($l->getLanguageCode()) : ''));
913
+        } else {
914
+            $emailTemplate->addFooter('', $l->getLanguageCode());
915
+        }
916
+
917
+        $message->useTemplate($emailTemplate);
918
+        try {
919
+            $failedRecipients = $this->mailer->send($message);
920
+            if (!empty($failedRecipients)) {
921
+                $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
922
+                return;
923
+            }
924
+        } catch (\Exception $e) {
925
+            $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
926
+        }
927
+    }
928
+
929
+    /**
930
+     * Update a share
931
+     *
932
+     * @param IShare $share
933
+     * @return IShare The share object
934
+     * @throws \InvalidArgumentException
935
+     */
936
+    public function updateShare(IShare $share) {
937
+        $expirationDateUpdated = false;
938
+
939
+        $this->canShare($share);
940
+
941
+        try {
942
+            $originalShare = $this->getShareById($share->getFullId());
943
+        } catch (\UnexpectedValueException $e) {
944
+            throw new \InvalidArgumentException('Share does not have a full id');
945
+        }
946
+
947
+        // We can't change the share type!
948
+        if ($share->getShareType() !== $originalShare->getShareType()) {
949
+            throw new \InvalidArgumentException('Can’t change share type');
950
+        }
951
+
952
+        // We can only change the recipient on user shares
953
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
954
+            $share->getShareType() !== IShare::TYPE_USER) {
955
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
956
+        }
957
+
958
+        // Cannot share with the owner
959
+        if ($share->getShareType() === IShare::TYPE_USER &&
960
+            $share->getSharedWith() === $share->getShareOwner()) {
961
+            throw new \InvalidArgumentException('Can’t share with the share owner');
962
+        }
963
+
964
+        $this->generalCreateChecks($share);
965
+
966
+        if ($share->getShareType() === IShare::TYPE_USER) {
967
+            $this->userCreateChecks($share);
968
+
969
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
970
+                //Verify the expiration date
971
+                $this->validateExpirationDate($share);
972
+                $expirationDateUpdated = true;
973
+            }
974
+        } elseif ($share->getShareType() === IShare::TYPE_GROUP) {
975
+            $this->groupCreateChecks($share);
976
+
977
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
978
+                //Verify the expiration date
979
+                $this->validateExpirationDate($share);
980
+                $expirationDateUpdated = true;
981
+            }
982
+        } elseif ($share->getShareType() === IShare::TYPE_LINK) {
983
+            $this->linkCreateChecks($share);
984
+
985
+            $plainTextPassword = $share->getPassword();
986
+
987
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
988
+
989
+            if (empty($plainTextPassword) && $share->getSendPasswordByTalk()) {
990
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk with an empty password');
991
+            }
992
+
993
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
994
+                //Verify the expiration date
995
+                $this->validateExpirationDate($share);
996
+                $expirationDateUpdated = true;
997
+            }
998
+        } elseif ($share->getShareType() === IShare::TYPE_EMAIL) {
999
+            // The new password is not set again if it is the same as the old
1000
+            // one.
1001
+            $plainTextPassword = $share->getPassword();
1002
+            if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare)) {
1003
+                $plainTextPassword = null;
1004
+            }
1005
+            if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
1006
+                // If the same password was already sent by mail the recipient
1007
+                // would already have access to the share without having to call
1008
+                // the sharer to verify her identity
1009
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
1010
+            } elseif (empty($plainTextPassword) && $originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk()) {
1011
+                throw new \InvalidArgumentException('Can’t disable sending the password by Talk without setting a new password');
1012
+            }
1013
+        }
1014
+
1015
+        $this->pathCreateChecks($share->getNode());
1016
+
1017
+        // Now update the share!
1018
+        $provider = $this->factory->getProviderForType($share->getShareType());
1019
+        if ($share->getShareType() === IShare::TYPE_EMAIL) {
1020
+            $share = $provider->update($share, $plainTextPassword);
1021
+        } else {
1022
+            $share = $provider->update($share);
1023
+        }
1024
+
1025
+        if ($expirationDateUpdated === true) {
1026
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1027
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1028
+                'itemSource' => $share->getNode()->getId(),
1029
+                'date' => $share->getExpirationDate(),
1030
+                'uidOwner' => $share->getSharedBy(),
1031
+            ]);
1032
+        }
1033
+
1034
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1035
+            \OC_Hook::emit(Share::class, 'post_update_password', [
1036
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1037
+                'itemSource' => $share->getNode()->getId(),
1038
+                'uidOwner' => $share->getSharedBy(),
1039
+                'token' => $share->getToken(),
1040
+                'disabled' => is_null($share->getPassword()),
1041
+            ]);
1042
+        }
1043
+
1044
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
1045
+            if ($this->userManager->userExists($share->getShareOwner())) {
1046
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1047
+            } else {
1048
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1049
+            }
1050
+            \OC_Hook::emit(Share::class, 'post_update_permissions', [
1051
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1052
+                'itemSource' => $share->getNode()->getId(),
1053
+                'shareType' => $share->getShareType(),
1054
+                'shareWith' => $share->getSharedWith(),
1055
+                'uidOwner' => $share->getSharedBy(),
1056
+                'permissions' => $share->getPermissions(),
1057
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1058
+            ]);
1059
+        }
1060
+
1061
+        return $share;
1062
+    }
1063
+
1064
+    /**
1065
+     * Accept a share.
1066
+     *
1067
+     * @param IShare $share
1068
+     * @param string $recipientId
1069
+     * @return IShare The share object
1070
+     * @throws \InvalidArgumentException
1071
+     * @since 9.0.0
1072
+     */
1073
+    public function acceptShare(IShare $share, string $recipientId): IShare {
1074
+        [$providerId, ] = $this->splitFullId($share->getFullId());
1075
+        $provider = $this->factory->getProvider($providerId);
1076
+
1077
+        if (!method_exists($provider, 'acceptShare')) {
1078
+            // TODO FIX ME
1079
+            throw new \InvalidArgumentException('Share provider does not support accepting');
1080
+        }
1081
+        $provider->acceptShare($share, $recipientId);
1082
+        $event = new GenericEvent($share);
1083
+        $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1084
+
1085
+        return $share;
1086
+    }
1087
+
1088
+    /**
1089
+     * Updates the password of the given share if it is not the same as the
1090
+     * password of the original share.
1091
+     *
1092
+     * @param IShare $share the share to update its password.
1093
+     * @param IShare $originalShare the original share to compare its
1094
+     *        password with.
1095
+     * @return boolean whether the password was updated or not.
1096
+     */
1097
+    private function updateSharePasswordIfNeeded(IShare $share, IShare $originalShare) {
1098
+        $passwordsAreDifferent = ($share->getPassword() !== $originalShare->getPassword()) &&
1099
+                                    (($share->getPassword() !== null && $originalShare->getPassword() === null) ||
1100
+                                     ($share->getPassword() === null && $originalShare->getPassword() !== null) ||
1101
+                                     ($share->getPassword() !== null && $originalShare->getPassword() !== null &&
1102
+                                        !$this->hasher->verify($share->getPassword(), $originalShare->getPassword())));
1103
+
1104
+        // Password updated.
1105
+        if ($passwordsAreDifferent) {
1106
+            //Verify the password
1107
+            $this->verifyPassword($share->getPassword());
1108
+
1109
+            // If a password is set. Hash it!
1110
+            if ($share->getPassword() !== null) {
1111
+                $share->setPassword($this->hasher->hash($share->getPassword()));
1112
+
1113
+                return true;
1114
+            }
1115
+        } else {
1116
+            // Reset the password to the original one, as it is either the same
1117
+            // as the "new" password or a hashed version of it.
1118
+            $share->setPassword($originalShare->getPassword());
1119
+        }
1120
+
1121
+        return false;
1122
+    }
1123
+
1124
+    /**
1125
+     * Delete all the children of this share
1126
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1127
+     *
1128
+     * @param IShare $share
1129
+     * @return IShare[] List of deleted shares
1130
+     */
1131
+    protected function deleteChildren(IShare $share) {
1132
+        $deletedShares = [];
1133
+
1134
+        $provider = $this->factory->getProviderForType($share->getShareType());
1135
+
1136
+        foreach ($provider->getChildren($share) as $child) {
1137
+            $deletedChildren = $this->deleteChildren($child);
1138
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
1139
+
1140
+            $provider->delete($child);
1141
+            $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($child));
1142
+            $deletedShares[] = $child;
1143
+        }
1144
+
1145
+        return $deletedShares;
1146
+    }
1147
+
1148
+    /**
1149
+     * Delete a share
1150
+     *
1151
+     * @param IShare $share
1152
+     * @throws ShareNotFound
1153
+     * @throws \InvalidArgumentException
1154
+     */
1155
+    public function deleteShare(IShare $share) {
1156
+        try {
1157
+            $share->getFullId();
1158
+        } catch (\UnexpectedValueException $e) {
1159
+            throw new \InvalidArgumentException('Share does not have a full id');
1160
+        }
1161
+
1162
+        $event = new GenericEvent($share);
1163
+        $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1164
+
1165
+        // Get all children and delete them as well
1166
+        $deletedShares = $this->deleteChildren($share);
1167
+
1168
+        // Do the actual delete
1169
+        $provider = $this->factory->getProviderForType($share->getShareType());
1170
+        $provider->delete($share);
1171
+
1172
+        $this->dispatcher->dispatchTyped(new Share\Events\ShareDeletedEvent($share));
1173
+
1174
+        // All the deleted shares caused by this delete
1175
+        $deletedShares[] = $share;
1176
+
1177
+        // Emit post hook
1178
+        $event->setArgument('deletedShares', $deletedShares);
1179
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1180
+    }
1181
+
1182
+
1183
+    /**
1184
+     * Unshare a file as the recipient.
1185
+     * This can be different from a regular delete for example when one of
1186
+     * the users in a groups deletes that share. But the provider should
1187
+     * handle this.
1188
+     *
1189
+     * @param IShare $share
1190
+     * @param string $recipientId
1191
+     */
1192
+    public function deleteFromSelf(IShare $share, $recipientId) {
1193
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1194
+        $provider = $this->factory->getProvider($providerId);
1195
+
1196
+        $provider->deleteFromSelf($share, $recipientId);
1197
+        $event = new GenericEvent($share);
1198
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1199
+    }
1200
+
1201
+    public function restoreShare(IShare $share, string $recipientId): IShare {
1202
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1203
+        $provider = $this->factory->getProvider($providerId);
1204
+
1205
+        return $provider->restore($share, $recipientId);
1206
+    }
1207
+
1208
+    /**
1209
+     * @inheritdoc
1210
+     */
1211
+    public function moveShare(IShare $share, $recipientId) {
1212
+        if ($share->getShareType() === IShare::TYPE_LINK) {
1213
+            throw new \InvalidArgumentException('Can’t change target of link share');
1214
+        }
1215
+
1216
+        if ($share->getShareType() === IShare::TYPE_USER && $share->getSharedWith() !== $recipientId) {
1217
+            throw new \InvalidArgumentException('Invalid recipient');
1218
+        }
1219
+
1220
+        if ($share->getShareType() === IShare::TYPE_GROUP) {
1221
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1222
+            if (is_null($sharedWith)) {
1223
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1224
+            }
1225
+            $recipient = $this->userManager->get($recipientId);
1226
+            if (!$sharedWith->inGroup($recipient)) {
1227
+                throw new \InvalidArgumentException('Invalid recipient');
1228
+            }
1229
+        }
1230
+
1231
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1232
+        $provider = $this->factory->getProvider($providerId);
1233
+
1234
+        return $provider->move($share, $recipientId);
1235
+    }
1236
+
1237
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1238
+        $providers = $this->factory->getAllProviders();
1239
+
1240
+        return array_reduce($providers, function ($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1241
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1242
+            foreach ($newShares as $fid => $data) {
1243
+                if (!isset($shares[$fid])) {
1244
+                    $shares[$fid] = [];
1245
+                }
1246
+
1247
+                $shares[$fid] = array_merge($shares[$fid], $data);
1248
+            }
1249
+            return $shares;
1250
+        }, []);
1251
+    }
1252
+
1253
+    /**
1254
+     * @inheritdoc
1255
+     */
1256
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1257
+        if ($path !== null &&
1258
+                !($path instanceof \OCP\Files\File) &&
1259
+                !($path instanceof \OCP\Files\Folder)) {
1260
+            throw new \InvalidArgumentException('invalid path');
1261
+        }
1262
+
1263
+        try {
1264
+            $provider = $this->factory->getProviderForType($shareType);
1265
+        } catch (ProviderException $e) {
1266
+            return [];
1267
+        }
1268
+
1269
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1270
+
1271
+        /*
1272 1272
 		 * Work around so we don't return expired shares but still follow
1273 1273
 		 * proper pagination.
1274 1274
 		 */
1275 1275
 
1276
-		$shares2 = [];
1277
-
1278
-		while (true) {
1279
-			$added = 0;
1280
-			foreach ($shares as $share) {
1281
-				try {
1282
-					$this->checkExpireDate($share);
1283
-				} catch (ShareNotFound $e) {
1284
-					//Ignore since this basically means the share is deleted
1285
-					continue;
1286
-				}
1287
-
1288
-				$added++;
1289
-				$shares2[] = $share;
1290
-
1291
-				if (count($shares2) === $limit) {
1292
-					break;
1293
-				}
1294
-			}
1295
-
1296
-			// If we did not fetch more shares than the limit then there are no more shares
1297
-			if (count($shares) < $limit) {
1298
-				break;
1299
-			}
1300
-
1301
-			if (count($shares2) === $limit) {
1302
-				break;
1303
-			}
1304
-
1305
-			// If there was no limit on the select we are done
1306
-			if ($limit === -1) {
1307
-				break;
1308
-			}
1309
-
1310
-			$offset += $added;
1311
-
1312
-			// Fetch again $limit shares
1313
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1314
-
1315
-			// No more shares means we are done
1316
-			if (empty($shares)) {
1317
-				break;
1318
-			}
1319
-		}
1320
-
1321
-		$shares = $shares2;
1322
-
1323
-		return $shares;
1324
-	}
1325
-
1326
-	/**
1327
-	 * @inheritdoc
1328
-	 */
1329
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1330
-		try {
1331
-			$provider = $this->factory->getProviderForType($shareType);
1332
-		} catch (ProviderException $e) {
1333
-			return [];
1334
-		}
1335
-
1336
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1337
-
1338
-		// remove all shares which are already expired
1339
-		foreach ($shares as $key => $share) {
1340
-			try {
1341
-				$this->checkExpireDate($share);
1342
-			} catch (ShareNotFound $e) {
1343
-				unset($shares[$key]);
1344
-			}
1345
-		}
1346
-
1347
-		return $shares;
1348
-	}
1349
-
1350
-	/**
1351
-	 * @inheritdoc
1352
-	 */
1353
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1354
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1355
-
1356
-		// Only get deleted shares
1357
-		$shares = array_filter($shares, function (IShare $share) {
1358
-			return $share->getPermissions() === 0;
1359
-		});
1360
-
1361
-		// Only get shares where the owner still exists
1362
-		$shares = array_filter($shares, function (IShare $share) {
1363
-			return $this->userManager->userExists($share->getShareOwner());
1364
-		});
1365
-
1366
-		return $shares;
1367
-	}
1368
-
1369
-	/**
1370
-	 * @inheritdoc
1371
-	 */
1372
-	public function getShareById($id, $recipient = null) {
1373
-		if ($id === null) {
1374
-			throw new ShareNotFound();
1375
-		}
1376
-
1377
-		list($providerId, $id) = $this->splitFullId($id);
1378
-
1379
-		try {
1380
-			$provider = $this->factory->getProvider($providerId);
1381
-		} catch (ProviderException $e) {
1382
-			throw new ShareNotFound();
1383
-		}
1384
-
1385
-		$share = $provider->getShareById($id, $recipient);
1386
-
1387
-		$this->checkExpireDate($share);
1388
-
1389
-		return $share;
1390
-	}
1391
-
1392
-	/**
1393
-	 * Get all the shares for a given path
1394
-	 *
1395
-	 * @param \OCP\Files\Node $path
1396
-	 * @param int $page
1397
-	 * @param int $perPage
1398
-	 *
1399
-	 * @return Share[]
1400
-	 */
1401
-	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1402
-		return [];
1403
-	}
1404
-
1405
-	/**
1406
-	 * Get the share by token possible with password
1407
-	 *
1408
-	 * @param string $token
1409
-	 * @return IShare
1410
-	 *
1411
-	 * @throws ShareNotFound
1412
-	 */
1413
-	public function getShareByToken($token) {
1414
-		// tokens can't be valid local user names
1415
-		if ($this->userManager->userExists($token)) {
1416
-			throw new ShareNotFound();
1417
-		}
1418
-		$share = null;
1419
-		try {
1420
-			if ($this->shareApiAllowLinks()) {
1421
-				$provider = $this->factory->getProviderForType(IShare::TYPE_LINK);
1422
-				$share = $provider->getShareByToken($token);
1423
-			}
1424
-		} catch (ProviderException $e) {
1425
-		} catch (ShareNotFound $e) {
1426
-		}
1427
-
1428
-
1429
-		// If it is not a link share try to fetch a federated share by token
1430
-		if ($share === null) {
1431
-			try {
1432
-				$provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE);
1433
-				$share = $provider->getShareByToken($token);
1434
-			} catch (ProviderException $e) {
1435
-			} catch (ShareNotFound $e) {
1436
-			}
1437
-		}
1438
-
1439
-		// If it is not a link share try to fetch a mail share by token
1440
-		if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) {
1441
-			try {
1442
-				$provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL);
1443
-				$share = $provider->getShareByToken($token);
1444
-			} catch (ProviderException $e) {
1445
-			} catch (ShareNotFound $e) {
1446
-			}
1447
-		}
1448
-
1449
-		if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) {
1450
-			try {
1451
-				$provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE);
1452
-				$share = $provider->getShareByToken($token);
1453
-			} catch (ProviderException $e) {
1454
-			} catch (ShareNotFound $e) {
1455
-			}
1456
-		}
1457
-
1458
-		if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) {
1459
-			try {
1460
-				$provider = $this->factory->getProviderForType(IShare::TYPE_ROOM);
1461
-				$share = $provider->getShareByToken($token);
1462
-			} catch (ProviderException $e) {
1463
-			} catch (ShareNotFound $e) {
1464
-			}
1465
-		}
1466
-
1467
-		if ($share === null) {
1468
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1469
-		}
1470
-
1471
-		$this->checkExpireDate($share);
1472
-
1473
-		/*
1276
+        $shares2 = [];
1277
+
1278
+        while (true) {
1279
+            $added = 0;
1280
+            foreach ($shares as $share) {
1281
+                try {
1282
+                    $this->checkExpireDate($share);
1283
+                } catch (ShareNotFound $e) {
1284
+                    //Ignore since this basically means the share is deleted
1285
+                    continue;
1286
+                }
1287
+
1288
+                $added++;
1289
+                $shares2[] = $share;
1290
+
1291
+                if (count($shares2) === $limit) {
1292
+                    break;
1293
+                }
1294
+            }
1295
+
1296
+            // If we did not fetch more shares than the limit then there are no more shares
1297
+            if (count($shares) < $limit) {
1298
+                break;
1299
+            }
1300
+
1301
+            if (count($shares2) === $limit) {
1302
+                break;
1303
+            }
1304
+
1305
+            // If there was no limit on the select we are done
1306
+            if ($limit === -1) {
1307
+                break;
1308
+            }
1309
+
1310
+            $offset += $added;
1311
+
1312
+            // Fetch again $limit shares
1313
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1314
+
1315
+            // No more shares means we are done
1316
+            if (empty($shares)) {
1317
+                break;
1318
+            }
1319
+        }
1320
+
1321
+        $shares = $shares2;
1322
+
1323
+        return $shares;
1324
+    }
1325
+
1326
+    /**
1327
+     * @inheritdoc
1328
+     */
1329
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1330
+        try {
1331
+            $provider = $this->factory->getProviderForType($shareType);
1332
+        } catch (ProviderException $e) {
1333
+            return [];
1334
+        }
1335
+
1336
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1337
+
1338
+        // remove all shares which are already expired
1339
+        foreach ($shares as $key => $share) {
1340
+            try {
1341
+                $this->checkExpireDate($share);
1342
+            } catch (ShareNotFound $e) {
1343
+                unset($shares[$key]);
1344
+            }
1345
+        }
1346
+
1347
+        return $shares;
1348
+    }
1349
+
1350
+    /**
1351
+     * @inheritdoc
1352
+     */
1353
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1354
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1355
+
1356
+        // Only get deleted shares
1357
+        $shares = array_filter($shares, function (IShare $share) {
1358
+            return $share->getPermissions() === 0;
1359
+        });
1360
+
1361
+        // Only get shares where the owner still exists
1362
+        $shares = array_filter($shares, function (IShare $share) {
1363
+            return $this->userManager->userExists($share->getShareOwner());
1364
+        });
1365
+
1366
+        return $shares;
1367
+    }
1368
+
1369
+    /**
1370
+     * @inheritdoc
1371
+     */
1372
+    public function getShareById($id, $recipient = null) {
1373
+        if ($id === null) {
1374
+            throw new ShareNotFound();
1375
+        }
1376
+
1377
+        list($providerId, $id) = $this->splitFullId($id);
1378
+
1379
+        try {
1380
+            $provider = $this->factory->getProvider($providerId);
1381
+        } catch (ProviderException $e) {
1382
+            throw new ShareNotFound();
1383
+        }
1384
+
1385
+        $share = $provider->getShareById($id, $recipient);
1386
+
1387
+        $this->checkExpireDate($share);
1388
+
1389
+        return $share;
1390
+    }
1391
+
1392
+    /**
1393
+     * Get all the shares for a given path
1394
+     *
1395
+     * @param \OCP\Files\Node $path
1396
+     * @param int $page
1397
+     * @param int $perPage
1398
+     *
1399
+     * @return Share[]
1400
+     */
1401
+    public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1402
+        return [];
1403
+    }
1404
+
1405
+    /**
1406
+     * Get the share by token possible with password
1407
+     *
1408
+     * @param string $token
1409
+     * @return IShare
1410
+     *
1411
+     * @throws ShareNotFound
1412
+     */
1413
+    public function getShareByToken($token) {
1414
+        // tokens can't be valid local user names
1415
+        if ($this->userManager->userExists($token)) {
1416
+            throw new ShareNotFound();
1417
+        }
1418
+        $share = null;
1419
+        try {
1420
+            if ($this->shareApiAllowLinks()) {
1421
+                $provider = $this->factory->getProviderForType(IShare::TYPE_LINK);
1422
+                $share = $provider->getShareByToken($token);
1423
+            }
1424
+        } catch (ProviderException $e) {
1425
+        } catch (ShareNotFound $e) {
1426
+        }
1427
+
1428
+
1429
+        // If it is not a link share try to fetch a federated share by token
1430
+        if ($share === null) {
1431
+            try {
1432
+                $provider = $this->factory->getProviderForType(IShare::TYPE_REMOTE);
1433
+                $share = $provider->getShareByToken($token);
1434
+            } catch (ProviderException $e) {
1435
+            } catch (ShareNotFound $e) {
1436
+            }
1437
+        }
1438
+
1439
+        // If it is not a link share try to fetch a mail share by token
1440
+        if ($share === null && $this->shareProviderExists(IShare::TYPE_EMAIL)) {
1441
+            try {
1442
+                $provider = $this->factory->getProviderForType(IShare::TYPE_EMAIL);
1443
+                $share = $provider->getShareByToken($token);
1444
+            } catch (ProviderException $e) {
1445
+            } catch (ShareNotFound $e) {
1446
+            }
1447
+        }
1448
+
1449
+        if ($share === null && $this->shareProviderExists(IShare::TYPE_CIRCLE)) {
1450
+            try {
1451
+                $provider = $this->factory->getProviderForType(IShare::TYPE_CIRCLE);
1452
+                $share = $provider->getShareByToken($token);
1453
+            } catch (ProviderException $e) {
1454
+            } catch (ShareNotFound $e) {
1455
+            }
1456
+        }
1457
+
1458
+        if ($share === null && $this->shareProviderExists(IShare::TYPE_ROOM)) {
1459
+            try {
1460
+                $provider = $this->factory->getProviderForType(IShare::TYPE_ROOM);
1461
+                $share = $provider->getShareByToken($token);
1462
+            } catch (ProviderException $e) {
1463
+            } catch (ShareNotFound $e) {
1464
+            }
1465
+        }
1466
+
1467
+        if ($share === null) {
1468
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1469
+        }
1470
+
1471
+        $this->checkExpireDate($share);
1472
+
1473
+        /*
1474 1474
 		 * Reduce the permissions for link shares if public upload is not enabled
1475 1475
 		 */
1476
-		if ($share->getShareType() === IShare::TYPE_LINK &&
1477
-			!$this->shareApiLinkAllowPublicUpload()) {
1478
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1479
-		}
1480
-
1481
-		return $share;
1482
-	}
1483
-
1484
-	protected function checkExpireDate($share) {
1485
-		if ($share->isExpired()) {
1486
-			$this->deleteShare($share);
1487
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1488
-		}
1489
-	}
1490
-
1491
-	/**
1492
-	 * Verify the password of a public share
1493
-	 *
1494
-	 * @param IShare $share
1495
-	 * @param string $password
1496
-	 * @return bool
1497
-	 */
1498
-	public function checkPassword(IShare $share, $password) {
1499
-		$passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1500
-							 || $share->getShareType() !== IShare::TYPE_EMAIL
1501
-							 || $share->getShareType() !== IShare::TYPE_CIRCLE;
1502
-		if (!$passwordProtected) {
1503
-			//TODO maybe exception?
1504
-			return false;
1505
-		}
1506
-
1507
-		if ($password === null || $share->getPassword() === null) {
1508
-			return false;
1509
-		}
1510
-
1511
-		$newHash = '';
1512
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1513
-			return false;
1514
-		}
1515
-
1516
-		if (!empty($newHash)) {
1517
-			$share->setPassword($newHash);
1518
-			$provider = $this->factory->getProviderForType($share->getShareType());
1519
-			$provider->update($share);
1520
-		}
1521
-
1522
-		return true;
1523
-	}
1524
-
1525
-	/**
1526
-	 * @inheritdoc
1527
-	 */
1528
-	public function userDeleted($uid) {
1529
-		$types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL];
1530
-
1531
-		foreach ($types as $type) {
1532
-			try {
1533
-				$provider = $this->factory->getProviderForType($type);
1534
-			} catch (ProviderException $e) {
1535
-				continue;
1536
-			}
1537
-			$provider->userDeleted($uid, $type);
1538
-		}
1539
-	}
1540
-
1541
-	/**
1542
-	 * @inheritdoc
1543
-	 */
1544
-	public function groupDeleted($gid) {
1545
-		$provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
1546
-		$provider->groupDeleted($gid);
1547
-
1548
-		$excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1549
-		if ($excludedGroups === '') {
1550
-			return;
1551
-		}
1552
-
1553
-		$excludedGroups = json_decode($excludedGroups, true);
1554
-		if (json_last_error() !== JSON_ERROR_NONE) {
1555
-			return;
1556
-		}
1557
-
1558
-		$excludedGroups = array_diff($excludedGroups, [$gid]);
1559
-		$this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups));
1560
-	}
1561
-
1562
-	/**
1563
-	 * @inheritdoc
1564
-	 */
1565
-	public function userDeletedFromGroup($uid, $gid) {
1566
-		$provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
1567
-		$provider->userDeletedFromGroup($uid, $gid);
1568
-	}
1569
-
1570
-	/**
1571
-	 * Get access list to a path. This means
1572
-	 * all the users that can access a given path.
1573
-	 *
1574
-	 * Consider:
1575
-	 * -root
1576
-	 * |-folder1 (23)
1577
-	 *  |-folder2 (32)
1578
-	 *   |-fileA (42)
1579
-	 *
1580
-	 * fileA is shared with user1 and user1@server1
1581
-	 * folder2 is shared with group2 (user4 is a member of group2)
1582
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1583
-	 *
1584
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1585
-	 * [
1586
-	 *  users  => [
1587
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1588
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1589
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1590
-	 *  ],
1591
-	 *  remote => [
1592
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1593
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1594
-	 *  ],
1595
-	 *  public => bool
1596
-	 *  mail => bool
1597
-	 * ]
1598
-	 *
1599
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1600
-	 * [
1601
-	 *  users  => ['user1', 'user2', 'user4'],
1602
-	 *  remote => bool,
1603
-	 *  public => bool
1604
-	 *  mail => bool
1605
-	 * ]
1606
-	 *
1607
-	 * This is required for encryption/activity
1608
-	 *
1609
-	 * @param \OCP\Files\Node $path
1610
-	 * @param bool $recursive Should we check all parent folders as well
1611
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1612
-	 * @return array
1613
-	 */
1614
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1615
-		$owner = $path->getOwner();
1616
-
1617
-		if ($owner === null) {
1618
-			return [];
1619
-		}
1620
-
1621
-		$owner = $owner->getUID();
1622
-
1623
-		if ($currentAccess) {
1624
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1625
-		} else {
1626
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1627
-		}
1628
-		if (!$this->userManager->userExists($owner)) {
1629
-			return $al;
1630
-		}
1631
-
1632
-		//Get node for the owner and correct the owner in case of external storages
1633
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1634
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1635
-			$nodes = $userFolder->getById($path->getId());
1636
-			$path = array_shift($nodes);
1637
-			if ($path->getOwner() === null) {
1638
-				return [];
1639
-			}
1640
-			$owner = $path->getOwner()->getUID();
1641
-		}
1642
-
1643
-		$providers = $this->factory->getAllProviders();
1644
-
1645
-		/** @var Node[] $nodes */
1646
-		$nodes = [];
1647
-
1648
-
1649
-		if ($currentAccess) {
1650
-			$ownerPath = $path->getPath();
1651
-			$ownerPath = explode('/', $ownerPath, 4);
1652
-			if (count($ownerPath) < 4) {
1653
-				$ownerPath = '';
1654
-			} else {
1655
-				$ownerPath = $ownerPath[3];
1656
-			}
1657
-			$al['users'][$owner] = [
1658
-				'node_id' => $path->getId(),
1659
-				'node_path' => '/' . $ownerPath,
1660
-			];
1661
-		} else {
1662
-			$al['users'][] = $owner;
1663
-		}
1664
-
1665
-		// Collect all the shares
1666
-		while ($path->getPath() !== $userFolder->getPath()) {
1667
-			$nodes[] = $path;
1668
-			if (!$recursive) {
1669
-				break;
1670
-			}
1671
-			$path = $path->getParent();
1672
-		}
1673
-
1674
-		foreach ($providers as $provider) {
1675
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1676
-
1677
-			foreach ($tmp as $k => $v) {
1678
-				if (isset($al[$k])) {
1679
-					if (is_array($al[$k])) {
1680
-						if ($currentAccess) {
1681
-							$al[$k] += $v;
1682
-						} else {
1683
-							$al[$k] = array_merge($al[$k], $v);
1684
-							$al[$k] = array_unique($al[$k]);
1685
-							$al[$k] = array_values($al[$k]);
1686
-						}
1687
-					} else {
1688
-						$al[$k] = $al[$k] || $v;
1689
-					}
1690
-				} else {
1691
-					$al[$k] = $v;
1692
-				}
1693
-			}
1694
-		}
1695
-
1696
-		return $al;
1697
-	}
1698
-
1699
-	/**
1700
-	 * Create a new share
1701
-	 *
1702
-	 * @return IShare
1703
-	 */
1704
-	public function newShare() {
1705
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1706
-	}
1707
-
1708
-	/**
1709
-	 * Is the share API enabled
1710
-	 *
1711
-	 * @return bool
1712
-	 */
1713
-	public function shareApiEnabled() {
1714
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1715
-	}
1716
-
1717
-	/**
1718
-	 * Is public link sharing enabled
1719
-	 *
1720
-	 * @return bool
1721
-	 */
1722
-	public function shareApiAllowLinks() {
1723
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1724
-	}
1725
-
1726
-	/**
1727
-	 * Is password on public link requires
1728
-	 *
1729
-	 * @return bool
1730
-	 */
1731
-	public function shareApiLinkEnforcePassword() {
1732
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1733
-	}
1734
-
1735
-	/**
1736
-	 * Is default link expire date enabled
1737
-	 *
1738
-	 * @return bool
1739
-	 */
1740
-	public function shareApiLinkDefaultExpireDate() {
1741
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1742
-	}
1743
-
1744
-	/**
1745
-	 * Is default link expire date enforced
1746
-	 *`
1747
-	 * @return bool
1748
-	 */
1749
-	public function shareApiLinkDefaultExpireDateEnforced() {
1750
-		return $this->shareApiLinkDefaultExpireDate() &&
1751
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1752
-	}
1753
-
1754
-
1755
-	/**
1756
-	 * Number of default link expire days
1757
-	 * @return int
1758
-	 */
1759
-	public function shareApiLinkDefaultExpireDays() {
1760
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1761
-	}
1762
-
1763
-	/**
1764
-	 * Is default internal expire date enabled
1765
-	 *
1766
-	 * @return bool
1767
-	 */
1768
-	public function shareApiInternalDefaultExpireDate(): bool {
1769
-		return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1770
-	}
1771
-
1772
-	/**
1773
-	 * Is default expire date enforced
1774
-	 *`
1775
-	 * @return bool
1776
-	 */
1777
-	public function shareApiInternalDefaultExpireDateEnforced(): bool {
1778
-		return $this->shareApiInternalDefaultExpireDate() &&
1779
-			$this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1780
-	}
1781
-
1782
-
1783
-	/**
1784
-	 * Number of default expire days
1785
-	 * @return int
1786
-	 */
1787
-	public function shareApiInternalDefaultExpireDays(): int {
1788
-		return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1789
-	}
1790
-
1791
-	/**
1792
-	 * Allow public upload on link shares
1793
-	 *
1794
-	 * @return bool
1795
-	 */
1796
-	public function shareApiLinkAllowPublicUpload() {
1797
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1798
-	}
1799
-
1800
-	/**
1801
-	 * check if user can only share with group members
1802
-	 * @return bool
1803
-	 */
1804
-	public function shareWithGroupMembersOnly() {
1805
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1806
-	}
1807
-
1808
-	/**
1809
-	 * Check if users can share with groups
1810
-	 * @return bool
1811
-	 */
1812
-	public function allowGroupSharing() {
1813
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1814
-	}
1815
-
1816
-	public function allowEnumeration(): bool {
1817
-		return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1818
-	}
1819
-
1820
-	public function limitEnumerationToGroups(): bool {
1821
-		return $this->allowEnumeration() &&
1822
-			$this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1823
-	}
1824
-
1825
-	/**
1826
-	 * Copied from \OC_Util::isSharingDisabledForUser
1827
-	 *
1828
-	 * TODO: Deprecate fuction from OC_Util
1829
-	 *
1830
-	 * @param string $userId
1831
-	 * @return bool
1832
-	 */
1833
-	public function sharingDisabledForUser($userId) {
1834
-		if ($userId === null) {
1835
-			return false;
1836
-		}
1837
-
1838
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1839
-			return $this->sharingDisabledForUsersCache[$userId];
1840
-		}
1841
-
1842
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1843
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1844
-			$excludedGroups = json_decode($groupsList);
1845
-			if (is_null($excludedGroups)) {
1846
-				$excludedGroups = explode(',', $groupsList);
1847
-				$newValue = json_encode($excludedGroups);
1848
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1849
-			}
1850
-			$user = $this->userManager->get($userId);
1851
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1852
-			if (!empty($usersGroups)) {
1853
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1854
-				// if the user is only in groups which are disabled for sharing then
1855
-				// sharing is also disabled for the user
1856
-				if (empty($remainingGroups)) {
1857
-					$this->sharingDisabledForUsersCache[$userId] = true;
1858
-					return true;
1859
-				}
1860
-			}
1861
-		}
1862
-
1863
-		$this->sharingDisabledForUsersCache[$userId] = false;
1864
-		return false;
1865
-	}
1866
-
1867
-	/**
1868
-	 * @inheritdoc
1869
-	 */
1870
-	public function outgoingServer2ServerSharesAllowed() {
1871
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1872
-	}
1873
-
1874
-	/**
1875
-	 * @inheritdoc
1876
-	 */
1877
-	public function outgoingServer2ServerGroupSharesAllowed() {
1878
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1879
-	}
1880
-
1881
-	/**
1882
-	 * @inheritdoc
1883
-	 */
1884
-	public function shareProviderExists($shareType) {
1885
-		try {
1886
-			$this->factory->getProviderForType($shareType);
1887
-		} catch (ProviderException $e) {
1888
-			return false;
1889
-		}
1890
-
1891
-		return true;
1892
-	}
1893
-
1894
-	public function registerShareProvider(string $shareProviderClass): void {
1895
-		$this->factory->registerProvider($shareProviderClass);
1896
-	}
1897
-
1898
-	public function getAllShares(): iterable {
1899
-		$providers = $this->factory->getAllProviders();
1900
-
1901
-		foreach ($providers as $provider) {
1902
-			yield from $provider->getAllShares();
1903
-		}
1904
-	}
1476
+        if ($share->getShareType() === IShare::TYPE_LINK &&
1477
+            !$this->shareApiLinkAllowPublicUpload()) {
1478
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1479
+        }
1480
+
1481
+        return $share;
1482
+    }
1483
+
1484
+    protected function checkExpireDate($share) {
1485
+        if ($share->isExpired()) {
1486
+            $this->deleteShare($share);
1487
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1488
+        }
1489
+    }
1490
+
1491
+    /**
1492
+     * Verify the password of a public share
1493
+     *
1494
+     * @param IShare $share
1495
+     * @param string $password
1496
+     * @return bool
1497
+     */
1498
+    public function checkPassword(IShare $share, $password) {
1499
+        $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1500
+                             || $share->getShareType() !== IShare::TYPE_EMAIL
1501
+                             || $share->getShareType() !== IShare::TYPE_CIRCLE;
1502
+        if (!$passwordProtected) {
1503
+            //TODO maybe exception?
1504
+            return false;
1505
+        }
1506
+
1507
+        if ($password === null || $share->getPassword() === null) {
1508
+            return false;
1509
+        }
1510
+
1511
+        $newHash = '';
1512
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1513
+            return false;
1514
+        }
1515
+
1516
+        if (!empty($newHash)) {
1517
+            $share->setPassword($newHash);
1518
+            $provider = $this->factory->getProviderForType($share->getShareType());
1519
+            $provider->update($share);
1520
+        }
1521
+
1522
+        return true;
1523
+    }
1524
+
1525
+    /**
1526
+     * @inheritdoc
1527
+     */
1528
+    public function userDeleted($uid) {
1529
+        $types = [IShare::TYPE_USER, IShare::TYPE_GROUP, IShare::TYPE_LINK, IShare::TYPE_REMOTE, IShare::TYPE_EMAIL];
1530
+
1531
+        foreach ($types as $type) {
1532
+            try {
1533
+                $provider = $this->factory->getProviderForType($type);
1534
+            } catch (ProviderException $e) {
1535
+                continue;
1536
+            }
1537
+            $provider->userDeleted($uid, $type);
1538
+        }
1539
+    }
1540
+
1541
+    /**
1542
+     * @inheritdoc
1543
+     */
1544
+    public function groupDeleted($gid) {
1545
+        $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
1546
+        $provider->groupDeleted($gid);
1547
+
1548
+        $excludedGroups = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1549
+        if ($excludedGroups === '') {
1550
+            return;
1551
+        }
1552
+
1553
+        $excludedGroups = json_decode($excludedGroups, true);
1554
+        if (json_last_error() !== JSON_ERROR_NONE) {
1555
+            return;
1556
+        }
1557
+
1558
+        $excludedGroups = array_diff($excludedGroups, [$gid]);
1559
+        $this->config->setAppValue('core', 'shareapi_exclude_groups_list', json_encode($excludedGroups));
1560
+    }
1561
+
1562
+    /**
1563
+     * @inheritdoc
1564
+     */
1565
+    public function userDeletedFromGroup($uid, $gid) {
1566
+        $provider = $this->factory->getProviderForType(IShare::TYPE_GROUP);
1567
+        $provider->userDeletedFromGroup($uid, $gid);
1568
+    }
1569
+
1570
+    /**
1571
+     * Get access list to a path. This means
1572
+     * all the users that can access a given path.
1573
+     *
1574
+     * Consider:
1575
+     * -root
1576
+     * |-folder1 (23)
1577
+     *  |-folder2 (32)
1578
+     *   |-fileA (42)
1579
+     *
1580
+     * fileA is shared with user1 and user1@server1
1581
+     * folder2 is shared with group2 (user4 is a member of group2)
1582
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1583
+     *
1584
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1585
+     * [
1586
+     *  users  => [
1587
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1588
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1589
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1590
+     *  ],
1591
+     *  remote => [
1592
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1593
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1594
+     *  ],
1595
+     *  public => bool
1596
+     *  mail => bool
1597
+     * ]
1598
+     *
1599
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1600
+     * [
1601
+     *  users  => ['user1', 'user2', 'user4'],
1602
+     *  remote => bool,
1603
+     *  public => bool
1604
+     *  mail => bool
1605
+     * ]
1606
+     *
1607
+     * This is required for encryption/activity
1608
+     *
1609
+     * @param \OCP\Files\Node $path
1610
+     * @param bool $recursive Should we check all parent folders as well
1611
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1612
+     * @return array
1613
+     */
1614
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1615
+        $owner = $path->getOwner();
1616
+
1617
+        if ($owner === null) {
1618
+            return [];
1619
+        }
1620
+
1621
+        $owner = $owner->getUID();
1622
+
1623
+        if ($currentAccess) {
1624
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1625
+        } else {
1626
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1627
+        }
1628
+        if (!$this->userManager->userExists($owner)) {
1629
+            return $al;
1630
+        }
1631
+
1632
+        //Get node for the owner and correct the owner in case of external storages
1633
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1634
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1635
+            $nodes = $userFolder->getById($path->getId());
1636
+            $path = array_shift($nodes);
1637
+            if ($path->getOwner() === null) {
1638
+                return [];
1639
+            }
1640
+            $owner = $path->getOwner()->getUID();
1641
+        }
1642
+
1643
+        $providers = $this->factory->getAllProviders();
1644
+
1645
+        /** @var Node[] $nodes */
1646
+        $nodes = [];
1647
+
1648
+
1649
+        if ($currentAccess) {
1650
+            $ownerPath = $path->getPath();
1651
+            $ownerPath = explode('/', $ownerPath, 4);
1652
+            if (count($ownerPath) < 4) {
1653
+                $ownerPath = '';
1654
+            } else {
1655
+                $ownerPath = $ownerPath[3];
1656
+            }
1657
+            $al['users'][$owner] = [
1658
+                'node_id' => $path->getId(),
1659
+                'node_path' => '/' . $ownerPath,
1660
+            ];
1661
+        } else {
1662
+            $al['users'][] = $owner;
1663
+        }
1664
+
1665
+        // Collect all the shares
1666
+        while ($path->getPath() !== $userFolder->getPath()) {
1667
+            $nodes[] = $path;
1668
+            if (!$recursive) {
1669
+                break;
1670
+            }
1671
+            $path = $path->getParent();
1672
+        }
1673
+
1674
+        foreach ($providers as $provider) {
1675
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1676
+
1677
+            foreach ($tmp as $k => $v) {
1678
+                if (isset($al[$k])) {
1679
+                    if (is_array($al[$k])) {
1680
+                        if ($currentAccess) {
1681
+                            $al[$k] += $v;
1682
+                        } else {
1683
+                            $al[$k] = array_merge($al[$k], $v);
1684
+                            $al[$k] = array_unique($al[$k]);
1685
+                            $al[$k] = array_values($al[$k]);
1686
+                        }
1687
+                    } else {
1688
+                        $al[$k] = $al[$k] || $v;
1689
+                    }
1690
+                } else {
1691
+                    $al[$k] = $v;
1692
+                }
1693
+            }
1694
+        }
1695
+
1696
+        return $al;
1697
+    }
1698
+
1699
+    /**
1700
+     * Create a new share
1701
+     *
1702
+     * @return IShare
1703
+     */
1704
+    public function newShare() {
1705
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1706
+    }
1707
+
1708
+    /**
1709
+     * Is the share API enabled
1710
+     *
1711
+     * @return bool
1712
+     */
1713
+    public function shareApiEnabled() {
1714
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1715
+    }
1716
+
1717
+    /**
1718
+     * Is public link sharing enabled
1719
+     *
1720
+     * @return bool
1721
+     */
1722
+    public function shareApiAllowLinks() {
1723
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1724
+    }
1725
+
1726
+    /**
1727
+     * Is password on public link requires
1728
+     *
1729
+     * @return bool
1730
+     */
1731
+    public function shareApiLinkEnforcePassword() {
1732
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1733
+    }
1734
+
1735
+    /**
1736
+     * Is default link expire date enabled
1737
+     *
1738
+     * @return bool
1739
+     */
1740
+    public function shareApiLinkDefaultExpireDate() {
1741
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1742
+    }
1743
+
1744
+    /**
1745
+     * Is default link expire date enforced
1746
+     *`
1747
+     * @return bool
1748
+     */
1749
+    public function shareApiLinkDefaultExpireDateEnforced() {
1750
+        return $this->shareApiLinkDefaultExpireDate() &&
1751
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1752
+    }
1753
+
1754
+
1755
+    /**
1756
+     * Number of default link expire days
1757
+     * @return int
1758
+     */
1759
+    public function shareApiLinkDefaultExpireDays() {
1760
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1761
+    }
1762
+
1763
+    /**
1764
+     * Is default internal expire date enabled
1765
+     *
1766
+     * @return bool
1767
+     */
1768
+    public function shareApiInternalDefaultExpireDate(): bool {
1769
+        return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1770
+    }
1771
+
1772
+    /**
1773
+     * Is default expire date enforced
1774
+     *`
1775
+     * @return bool
1776
+     */
1777
+    public function shareApiInternalDefaultExpireDateEnforced(): bool {
1778
+        return $this->shareApiInternalDefaultExpireDate() &&
1779
+            $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1780
+    }
1781
+
1782
+
1783
+    /**
1784
+     * Number of default expire days
1785
+     * @return int
1786
+     */
1787
+    public function shareApiInternalDefaultExpireDays(): int {
1788
+        return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1789
+    }
1790
+
1791
+    /**
1792
+     * Allow public upload on link shares
1793
+     *
1794
+     * @return bool
1795
+     */
1796
+    public function shareApiLinkAllowPublicUpload() {
1797
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1798
+    }
1799
+
1800
+    /**
1801
+     * check if user can only share with group members
1802
+     * @return bool
1803
+     */
1804
+    public function shareWithGroupMembersOnly() {
1805
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1806
+    }
1807
+
1808
+    /**
1809
+     * Check if users can share with groups
1810
+     * @return bool
1811
+     */
1812
+    public function allowGroupSharing() {
1813
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1814
+    }
1815
+
1816
+    public function allowEnumeration(): bool {
1817
+        return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1818
+    }
1819
+
1820
+    public function limitEnumerationToGroups(): bool {
1821
+        return $this->allowEnumeration() &&
1822
+            $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1823
+    }
1824
+
1825
+    /**
1826
+     * Copied from \OC_Util::isSharingDisabledForUser
1827
+     *
1828
+     * TODO: Deprecate fuction from OC_Util
1829
+     *
1830
+     * @param string $userId
1831
+     * @return bool
1832
+     */
1833
+    public function sharingDisabledForUser($userId) {
1834
+        if ($userId === null) {
1835
+            return false;
1836
+        }
1837
+
1838
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1839
+            return $this->sharingDisabledForUsersCache[$userId];
1840
+        }
1841
+
1842
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1843
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1844
+            $excludedGroups = json_decode($groupsList);
1845
+            if (is_null($excludedGroups)) {
1846
+                $excludedGroups = explode(',', $groupsList);
1847
+                $newValue = json_encode($excludedGroups);
1848
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1849
+            }
1850
+            $user = $this->userManager->get($userId);
1851
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1852
+            if (!empty($usersGroups)) {
1853
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1854
+                // if the user is only in groups which are disabled for sharing then
1855
+                // sharing is also disabled for the user
1856
+                if (empty($remainingGroups)) {
1857
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1858
+                    return true;
1859
+                }
1860
+            }
1861
+        }
1862
+
1863
+        $this->sharingDisabledForUsersCache[$userId] = false;
1864
+        return false;
1865
+    }
1866
+
1867
+    /**
1868
+     * @inheritdoc
1869
+     */
1870
+    public function outgoingServer2ServerSharesAllowed() {
1871
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1872
+    }
1873
+
1874
+    /**
1875
+     * @inheritdoc
1876
+     */
1877
+    public function outgoingServer2ServerGroupSharesAllowed() {
1878
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1879
+    }
1880
+
1881
+    /**
1882
+     * @inheritdoc
1883
+     */
1884
+    public function shareProviderExists($shareType) {
1885
+        try {
1886
+            $this->factory->getProviderForType($shareType);
1887
+        } catch (ProviderException $e) {
1888
+            return false;
1889
+        }
1890
+
1891
+        return true;
1892
+    }
1893
+
1894
+    public function registerShareProvider(string $shareProviderClass): void {
1895
+        $this->factory->registerProvider($shareProviderClass);
1896
+    }
1897
+
1898
+    public function getAllShares(): iterable {
1899
+        $providers = $this->factory->getAllProviders();
1900
+
1901
+        foreach ($providers as $provider) {
1902
+            yield from $provider->getAllShares();
1903
+        }
1904
+    }
1905 1905
 }
Please login to merge, or discard this patch.
lib/public/Share/Events/ShareDeletedEvent.php 1 patch
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -34,27 +34,27 @@
 block discarded – undo
34 34
  */
35 35
 class ShareDeletedEvent extends Event {
36 36
 
37
-	/** @var IShare */
38
-	private $share;
39
-
40
-	/**
41
-	 *
42
-	 * @param IShare $share
43
-	 * @param IShare[] $children
44
-	 *
45
-	 * @since 21.0.0
46
-	 */
47
-	public function __construct(IShare $share) {
48
-		parent::__construct();
49
-
50
-		$this->share = $share;
51
-	}
52
-
53
-	/**
54
-	 * @return IShare
55
-	 * @since 21.0.0
56
-	 */
57
-	public function getShare(): IShare {
58
-		return $this->share;
59
-	}
37
+    /** @var IShare */
38
+    private $share;
39
+
40
+    /**
41
+     *
42
+     * @param IShare $share
43
+     * @param IShare[] $children
44
+     *
45
+     * @since 21.0.0
46
+     */
47
+    public function __construct(IShare $share) {
48
+        parent::__construct();
49
+
50
+        $this->share = $share;
51
+    }
52
+
53
+    /**
54
+     * @return IShare
55
+     * @since 21.0.0
56
+     */
57
+    public function getShare(): IShare {
58
+        return $this->share;
59
+    }
60 60
 }
Please login to merge, or discard this patch.