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