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