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