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