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