Completed
Pull Request — master (#7168)
by Joas
16:15
created
lib/private/Share20/Manager.php 1 patch
Indentation   +1459 added lines, -1459 removed lines patch added patch discarded remove patch
@@ -70,1487 +70,1487 @@
 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
-			$user = $this->userManager->get($share->getSharedWith());
673
-			if ($user !== null) {
674
-				$emailAddress = $user->getEMailAddress();
675
-				if ($emailAddress !== null && $emailAddress !== '') {
676
-					$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
677
-					$l = $this->l10nFactory->get('lib', $userLang);
678
-					$this->sendMailNotification(
679
-						$l,
680
-						$share->getNode()->getName(),
681
-						$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
682
-						$share->getSharedBy(),
683
-						$emailAddress,
684
-						$share->getExpirationDate()
685
-					);
686
-					$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
687
-				} else {
688
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
689
-				}
690
-			} else {
691
-				$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
692
-			}
693
-		}
694
-
695
-		return $share;
696
-	}
697
-
698
-	/**
699
-	 * @param IL10N $l Language of the recipient
700
-	 * @param string $filename file/folder name
701
-	 * @param string $link link to the file/folder
702
-	 * @param string $initiator user ID of share sender
703
-	 * @param string $shareWith email address of share receiver
704
-	 * @param \DateTime|null $expiration
705
-	 * @throws \Exception If mail couldn't be sent
706
-	 */
707
-	protected function sendMailNotification(IL10N $l,
708
-											$filename,
709
-											$link,
710
-											$initiator,
711
-											$shareWith,
712
-											\DateTime $expiration = null) {
713
-		$initiatorUser = $this->userManager->get($initiator);
714
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
715
-
716
-		$message = $this->mailer->createMessage();
717
-
718
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
719
-			'filename' => $filename,
720
-			'link' => $link,
721
-			'initiator' => $initiatorDisplayName,
722
-			'expiration' => $expiration,
723
-			'shareWith' => $shareWith,
724
-		]);
725
-
726
-		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
727
-		$emailTemplate->addHeader();
728
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
729
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
730
-
731
-		$emailTemplate->addBodyText(
732
-			$text . ' ' . $l->t('Click the button below to open it.'),
733
-			$text
734
-		);
735
-		$emailTemplate->addBodyButton(
736
-			$l->t('Open »%s«', [$filename]),
737
-			$link
738
-		);
739
-
740
-		$message->setTo([$shareWith]);
741
-
742
-		// The "From" contains the sharers name
743
-		$instanceName = $this->defaults->getName();
744
-		$senderName = $l->t(
745
-			'%s via %s',
746
-			[
747
-				$initiatorDisplayName,
748
-				$instanceName
749
-			]
750
-		);
751
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
752
-
753
-		// The "Reply-To" is set to the sharer if an mail address is configured
754
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
755
-		$initiatorEmail = $initiatorUser->getEMailAddress();
756
-		if($initiatorEmail !== null) {
757
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
758
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
759
-		} else {
760
-			$emailTemplate->addFooter();
761
-		}
762
-
763
-		$message->useTemplate($emailTemplate);
764
-		$this->mailer->send($message);
765
-	}
766
-
767
-	/**
768
-	 * Update a share
769
-	 *
770
-	 * @param \OCP\Share\IShare $share
771
-	 * @return \OCP\Share\IShare The share object
772
-	 * @throws \InvalidArgumentException
773
-	 */
774
-	public function updateShare(\OCP\Share\IShare $share) {
775
-		$expirationDateUpdated = false;
776
-
777
-		$this->canShare($share);
778
-
779
-		try {
780
-			$originalShare = $this->getShareById($share->getFullId());
781
-		} catch (\UnexpectedValueException $e) {
782
-			throw new \InvalidArgumentException('Share does not have a full id');
783
-		}
784
-
785
-		// We can't change the share type!
786
-		if ($share->getShareType() !== $originalShare->getShareType()) {
787
-			throw new \InvalidArgumentException('Can’t change share type');
788
-		}
789
-
790
-		// We can only change the recipient on user shares
791
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
792
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
793
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
794
-		}
795
-
796
-		// Cannot share with the owner
797
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
798
-			$share->getSharedWith() === $share->getShareOwner()) {
799
-			throw new \InvalidArgumentException('Can’t share with the share owner');
800
-		}
801
-
802
-		$this->generalCreateChecks($share);
803
-
804
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
805
-			$this->userCreateChecks($share);
806
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
807
-			$this->groupCreateChecks($share);
808
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
809
-			$this->linkCreateChecks($share);
810
-
811
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
812
-
813
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
814
-				//Verify the expiration date
815
-				$this->validateExpirationDate($share);
816
-				$expirationDateUpdated = true;
817
-			}
818
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
819
-			$plainTextPassword = $share->getPassword();
820
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
821
-				$plainTextPassword = null;
822
-			}
823
-		}
824
-
825
-		$this->pathCreateChecks($share->getNode());
826
-
827
-		// Now update the share!
828
-		$provider = $this->factory->getProviderForType($share->getShareType());
829
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
830
-			$share = $provider->update($share, $plainTextPassword);
831
-		} else {
832
-			$share = $provider->update($share);
833
-		}
834
-
835
-		if ($expirationDateUpdated === true) {
836
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
837
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
838
-				'itemSource' => $share->getNode()->getId(),
839
-				'date' => $share->getExpirationDate(),
840
-				'uidOwner' => $share->getSharedBy(),
841
-			]);
842
-		}
843
-
844
-		if ($share->getPassword() !== $originalShare->getPassword()) {
845
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
846
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
847
-				'itemSource' => $share->getNode()->getId(),
848
-				'uidOwner' => $share->getSharedBy(),
849
-				'token' => $share->getToken(),
850
-				'disabled' => is_null($share->getPassword()),
851
-			]);
852
-		}
853
-
854
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
855
-			if ($this->userManager->userExists($share->getShareOwner())) {
856
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
857
-			} else {
858
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
859
-			}
860
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
861
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
862
-				'itemSource' => $share->getNode()->getId(),
863
-				'shareType' => $share->getShareType(),
864
-				'shareWith' => $share->getSharedWith(),
865
-				'uidOwner' => $share->getSharedBy(),
866
-				'permissions' => $share->getPermissions(),
867
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
868
-			));
869
-		}
870
-
871
-		return $share;
872
-	}
873
-
874
-	/**
875
-	 * Updates the password of the given share if it is not the same as the
876
-	 * password of the original share.
877
-	 *
878
-	 * @param \OCP\Share\IShare $share the share to update its password.
879
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
880
-	 *        password with.
881
-	 * @return boolean whether the password was updated or not.
882
-	 */
883
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
884
-		// Password updated.
885
-		if ($share->getPassword() !== $originalShare->getPassword()) {
886
-			//Verify the password
887
-			$this->verifyPassword($share->getPassword());
888
-
889
-			// If a password is set. Hash it!
890
-			if ($share->getPassword() !== null) {
891
-				$share->setPassword($this->hasher->hash($share->getPassword()));
892
-
893
-				return true;
894
-			}
895
-		}
896
-
897
-		return false;
898
-	}
899
-
900
-	/**
901
-	 * Delete all the children of this share
902
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
903
-	 *
904
-	 * @param \OCP\Share\IShare $share
905
-	 * @return \OCP\Share\IShare[] List of deleted shares
906
-	 */
907
-	protected function deleteChildren(\OCP\Share\IShare $share) {
908
-		$deletedShares = [];
909
-
910
-		$provider = $this->factory->getProviderForType($share->getShareType());
911
-
912
-		foreach ($provider->getChildren($share) as $child) {
913
-			$deletedChildren = $this->deleteChildren($child);
914
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
915
-
916
-			$provider->delete($child);
917
-			$deletedShares[] = $child;
918
-		}
919
-
920
-		return $deletedShares;
921
-	}
922
-
923
-	/**
924
-	 * Delete a share
925
-	 *
926
-	 * @param \OCP\Share\IShare $share
927
-	 * @throws ShareNotFound
928
-	 * @throws \InvalidArgumentException
929
-	 */
930
-	public function deleteShare(\OCP\Share\IShare $share) {
931
-
932
-		try {
933
-			$share->getFullId();
934
-		} catch (\UnexpectedValueException $e) {
935
-			throw new \InvalidArgumentException('Share does not have a full id');
936
-		}
937
-
938
-		$event = new GenericEvent($share);
939
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
940
-
941
-		// Get all children and delete them as well
942
-		$deletedShares = $this->deleteChildren($share);
943
-
944
-		// Do the actual delete
945
-		$provider = $this->factory->getProviderForType($share->getShareType());
946
-		$provider->delete($share);
947
-
948
-		// All the deleted shares caused by this delete
949
-		$deletedShares[] = $share;
950
-
951
-		// Emit post hook
952
-		$event->setArgument('deletedShares', $deletedShares);
953
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
954
-	}
955
-
956
-
957
-	/**
958
-	 * Unshare a file as the recipient.
959
-	 * This can be different from a regular delete for example when one of
960
-	 * the users in a groups deletes that share. But the provider should
961
-	 * handle this.
962
-	 *
963
-	 * @param \OCP\Share\IShare $share
964
-	 * @param string $recipientId
965
-	 */
966
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
967
-		list($providerId, ) = $this->splitFullId($share->getFullId());
968
-		$provider = $this->factory->getProvider($providerId);
969
-
970
-		$provider->deleteFromSelf($share, $recipientId);
971
-		$event = new GenericEvent($share);
972
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
973
-	}
974
-
975
-	/**
976
-	 * @inheritdoc
977
-	 */
978
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
979
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
980
-			throw new \InvalidArgumentException('Can’t change target of link share');
981
-		}
982
-
983
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
984
-			throw new \InvalidArgumentException('Invalid recipient');
985
-		}
986
-
987
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
988
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
989
-			if (is_null($sharedWith)) {
990
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
991
-			}
992
-			$recipient = $this->userManager->get($recipientId);
993
-			if (!$sharedWith->inGroup($recipient)) {
994
-				throw new \InvalidArgumentException('Invalid recipient');
995
-			}
996
-		}
997
-
998
-		list($providerId, ) = $this->splitFullId($share->getFullId());
999
-		$provider = $this->factory->getProvider($providerId);
1000
-
1001
-		$provider->move($share, $recipientId);
1002
-	}
1003
-
1004
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1005
-		$providers = $this->factory->getAllProviders();
1006
-
1007
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1008
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1009
-			foreach ($newShares as $fid => $data) {
1010
-				if (!isset($shares[$fid])) {
1011
-					$shares[$fid] = [];
1012
-				}
1013
-
1014
-				$shares[$fid] = array_merge($shares[$fid], $data);
1015
-			}
1016
-			return $shares;
1017
-		}, []);
1018
-	}
1019
-
1020
-	/**
1021
-	 * @inheritdoc
1022
-	 */
1023
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1024
-		if ($path !== null &&
1025
-				!($path instanceof \OCP\Files\File) &&
1026
-				!($path instanceof \OCP\Files\Folder)) {
1027
-			throw new \InvalidArgumentException('invalid path');
1028
-		}
1029
-
1030
-		try {
1031
-			$provider = $this->factory->getProviderForType($shareType);
1032
-		} catch (ProviderException $e) {
1033
-			return [];
1034
-		}
1035
-
1036
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1037
-
1038
-		/*
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
+            $user = $this->userManager->get($share->getSharedWith());
673
+            if ($user !== null) {
674
+                $emailAddress = $user->getEMailAddress();
675
+                if ($emailAddress !== null && $emailAddress !== '') {
676
+                    $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
677
+                    $l = $this->l10nFactory->get('lib', $userLang);
678
+                    $this->sendMailNotification(
679
+                        $l,
680
+                        $share->getNode()->getName(),
681
+                        $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', [ 'fileid' => $share->getNode()->getId() ]),
682
+                        $share->getSharedBy(),
683
+                        $emailAddress,
684
+                        $share->getExpirationDate()
685
+                    );
686
+                    $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
687
+                } else {
688
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
689
+                }
690
+            } else {
691
+                $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
692
+            }
693
+        }
694
+
695
+        return $share;
696
+    }
697
+
698
+    /**
699
+     * @param IL10N $l Language of the recipient
700
+     * @param string $filename file/folder name
701
+     * @param string $link link to the file/folder
702
+     * @param string $initiator user ID of share sender
703
+     * @param string $shareWith email address of share receiver
704
+     * @param \DateTime|null $expiration
705
+     * @throws \Exception If mail couldn't be sent
706
+     */
707
+    protected function sendMailNotification(IL10N $l,
708
+                                            $filename,
709
+                                            $link,
710
+                                            $initiator,
711
+                                            $shareWith,
712
+                                            \DateTime $expiration = null) {
713
+        $initiatorUser = $this->userManager->get($initiator);
714
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
715
+
716
+        $message = $this->mailer->createMessage();
717
+
718
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
719
+            'filename' => $filename,
720
+            'link' => $link,
721
+            'initiator' => $initiatorDisplayName,
722
+            'expiration' => $expiration,
723
+            'shareWith' => $shareWith,
724
+        ]);
725
+
726
+        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
727
+        $emailTemplate->addHeader();
728
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
729
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
730
+
731
+        $emailTemplate->addBodyText(
732
+            $text . ' ' . $l->t('Click the button below to open it.'),
733
+            $text
734
+        );
735
+        $emailTemplate->addBodyButton(
736
+            $l->t('Open »%s«', [$filename]),
737
+            $link
738
+        );
739
+
740
+        $message->setTo([$shareWith]);
741
+
742
+        // The "From" contains the sharers name
743
+        $instanceName = $this->defaults->getName();
744
+        $senderName = $l->t(
745
+            '%s via %s',
746
+            [
747
+                $initiatorDisplayName,
748
+                $instanceName
749
+            ]
750
+        );
751
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
752
+
753
+        // The "Reply-To" is set to the sharer if an mail address is configured
754
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
755
+        $initiatorEmail = $initiatorUser->getEMailAddress();
756
+        if($initiatorEmail !== null) {
757
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
758
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
759
+        } else {
760
+            $emailTemplate->addFooter();
761
+        }
762
+
763
+        $message->useTemplate($emailTemplate);
764
+        $this->mailer->send($message);
765
+    }
766
+
767
+    /**
768
+     * Update a share
769
+     *
770
+     * @param \OCP\Share\IShare $share
771
+     * @return \OCP\Share\IShare The share object
772
+     * @throws \InvalidArgumentException
773
+     */
774
+    public function updateShare(\OCP\Share\IShare $share) {
775
+        $expirationDateUpdated = false;
776
+
777
+        $this->canShare($share);
778
+
779
+        try {
780
+            $originalShare = $this->getShareById($share->getFullId());
781
+        } catch (\UnexpectedValueException $e) {
782
+            throw new \InvalidArgumentException('Share does not have a full id');
783
+        }
784
+
785
+        // We can't change the share type!
786
+        if ($share->getShareType() !== $originalShare->getShareType()) {
787
+            throw new \InvalidArgumentException('Can’t change share type');
788
+        }
789
+
790
+        // We can only change the recipient on user shares
791
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
792
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
793
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
794
+        }
795
+
796
+        // Cannot share with the owner
797
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
798
+            $share->getSharedWith() === $share->getShareOwner()) {
799
+            throw new \InvalidArgumentException('Can’t share with the share owner');
800
+        }
801
+
802
+        $this->generalCreateChecks($share);
803
+
804
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
805
+            $this->userCreateChecks($share);
806
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
807
+            $this->groupCreateChecks($share);
808
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
809
+            $this->linkCreateChecks($share);
810
+
811
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
812
+
813
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
814
+                //Verify the expiration date
815
+                $this->validateExpirationDate($share);
816
+                $expirationDateUpdated = true;
817
+            }
818
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
819
+            $plainTextPassword = $share->getPassword();
820
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
821
+                $plainTextPassword = null;
822
+            }
823
+        }
824
+
825
+        $this->pathCreateChecks($share->getNode());
826
+
827
+        // Now update the share!
828
+        $provider = $this->factory->getProviderForType($share->getShareType());
829
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
830
+            $share = $provider->update($share, $plainTextPassword);
831
+        } else {
832
+            $share = $provider->update($share);
833
+        }
834
+
835
+        if ($expirationDateUpdated === true) {
836
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
837
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
838
+                'itemSource' => $share->getNode()->getId(),
839
+                'date' => $share->getExpirationDate(),
840
+                'uidOwner' => $share->getSharedBy(),
841
+            ]);
842
+        }
843
+
844
+        if ($share->getPassword() !== $originalShare->getPassword()) {
845
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
846
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
847
+                'itemSource' => $share->getNode()->getId(),
848
+                'uidOwner' => $share->getSharedBy(),
849
+                'token' => $share->getToken(),
850
+                'disabled' => is_null($share->getPassword()),
851
+            ]);
852
+        }
853
+
854
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
855
+            if ($this->userManager->userExists($share->getShareOwner())) {
856
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
857
+            } else {
858
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
859
+            }
860
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
861
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
862
+                'itemSource' => $share->getNode()->getId(),
863
+                'shareType' => $share->getShareType(),
864
+                'shareWith' => $share->getSharedWith(),
865
+                'uidOwner' => $share->getSharedBy(),
866
+                'permissions' => $share->getPermissions(),
867
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
868
+            ));
869
+        }
870
+
871
+        return $share;
872
+    }
873
+
874
+    /**
875
+     * Updates the password of the given share if it is not the same as the
876
+     * password of the original share.
877
+     *
878
+     * @param \OCP\Share\IShare $share the share to update its password.
879
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
880
+     *        password with.
881
+     * @return boolean whether the password was updated or not.
882
+     */
883
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
884
+        // Password updated.
885
+        if ($share->getPassword() !== $originalShare->getPassword()) {
886
+            //Verify the password
887
+            $this->verifyPassword($share->getPassword());
888
+
889
+            // If a password is set. Hash it!
890
+            if ($share->getPassword() !== null) {
891
+                $share->setPassword($this->hasher->hash($share->getPassword()));
892
+
893
+                return true;
894
+            }
895
+        }
896
+
897
+        return false;
898
+    }
899
+
900
+    /**
901
+     * Delete all the children of this share
902
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
903
+     *
904
+     * @param \OCP\Share\IShare $share
905
+     * @return \OCP\Share\IShare[] List of deleted shares
906
+     */
907
+    protected function deleteChildren(\OCP\Share\IShare $share) {
908
+        $deletedShares = [];
909
+
910
+        $provider = $this->factory->getProviderForType($share->getShareType());
911
+
912
+        foreach ($provider->getChildren($share) as $child) {
913
+            $deletedChildren = $this->deleteChildren($child);
914
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
915
+
916
+            $provider->delete($child);
917
+            $deletedShares[] = $child;
918
+        }
919
+
920
+        return $deletedShares;
921
+    }
922
+
923
+    /**
924
+     * Delete a share
925
+     *
926
+     * @param \OCP\Share\IShare $share
927
+     * @throws ShareNotFound
928
+     * @throws \InvalidArgumentException
929
+     */
930
+    public function deleteShare(\OCP\Share\IShare $share) {
931
+
932
+        try {
933
+            $share->getFullId();
934
+        } catch (\UnexpectedValueException $e) {
935
+            throw new \InvalidArgumentException('Share does not have a full id');
936
+        }
937
+
938
+        $event = new GenericEvent($share);
939
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
940
+
941
+        // Get all children and delete them as well
942
+        $deletedShares = $this->deleteChildren($share);
943
+
944
+        // Do the actual delete
945
+        $provider = $this->factory->getProviderForType($share->getShareType());
946
+        $provider->delete($share);
947
+
948
+        // All the deleted shares caused by this delete
949
+        $deletedShares[] = $share;
950
+
951
+        // Emit post hook
952
+        $event->setArgument('deletedShares', $deletedShares);
953
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
954
+    }
955
+
956
+
957
+    /**
958
+     * Unshare a file as the recipient.
959
+     * This can be different from a regular delete for example when one of
960
+     * the users in a groups deletes that share. But the provider should
961
+     * handle this.
962
+     *
963
+     * @param \OCP\Share\IShare $share
964
+     * @param string $recipientId
965
+     */
966
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
967
+        list($providerId, ) = $this->splitFullId($share->getFullId());
968
+        $provider = $this->factory->getProvider($providerId);
969
+
970
+        $provider->deleteFromSelf($share, $recipientId);
971
+        $event = new GenericEvent($share);
972
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
973
+    }
974
+
975
+    /**
976
+     * @inheritdoc
977
+     */
978
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
979
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
980
+            throw new \InvalidArgumentException('Can’t change target of link share');
981
+        }
982
+
983
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
984
+            throw new \InvalidArgumentException('Invalid recipient');
985
+        }
986
+
987
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
988
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
989
+            if (is_null($sharedWith)) {
990
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
991
+            }
992
+            $recipient = $this->userManager->get($recipientId);
993
+            if (!$sharedWith->inGroup($recipient)) {
994
+                throw new \InvalidArgumentException('Invalid recipient');
995
+            }
996
+        }
997
+
998
+        list($providerId, ) = $this->splitFullId($share->getFullId());
999
+        $provider = $this->factory->getProvider($providerId);
1000
+
1001
+        $provider->move($share, $recipientId);
1002
+    }
1003
+
1004
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1005
+        $providers = $this->factory->getAllProviders();
1006
+
1007
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1008
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1009
+            foreach ($newShares as $fid => $data) {
1010
+                if (!isset($shares[$fid])) {
1011
+                    $shares[$fid] = [];
1012
+                }
1013
+
1014
+                $shares[$fid] = array_merge($shares[$fid], $data);
1015
+            }
1016
+            return $shares;
1017
+        }, []);
1018
+    }
1019
+
1020
+    /**
1021
+     * @inheritdoc
1022
+     */
1023
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1024
+        if ($path !== null &&
1025
+                !($path instanceof \OCP\Files\File) &&
1026
+                !($path instanceof \OCP\Files\Folder)) {
1027
+            throw new \InvalidArgumentException('invalid path');
1028
+        }
1029
+
1030
+        try {
1031
+            $provider = $this->factory->getProviderForType($shareType);
1032
+        } catch (ProviderException $e) {
1033
+            return [];
1034
+        }
1035
+
1036
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1037
+
1038
+        /*
1039 1039
 		 * Work around so we don't return expired shares but still follow
1040 1040
 		 * proper pagination.
1041 1041
 		 */
1042 1042
 
1043
-		$shares2 = [];
1044
-
1045
-		while(true) {
1046
-			$added = 0;
1047
-			foreach ($shares as $share) {
1048
-
1049
-				try {
1050
-					$this->checkExpireDate($share);
1051
-				} catch (ShareNotFound $e) {
1052
-					//Ignore since this basically means the share is deleted
1053
-					continue;
1054
-				}
1055
-
1056
-				$added++;
1057
-				$shares2[] = $share;
1058
-
1059
-				if (count($shares2) === $limit) {
1060
-					break;
1061
-				}
1062
-			}
1063
-
1064
-			// If we did not fetch more shares than the limit then there are no more shares
1065
-			if (count($shares) < $limit) {
1066
-				break;
1067
-			}
1068
-
1069
-			if (count($shares2) === $limit) {
1070
-				break;
1071
-			}
1072
-
1073
-			// If there was no limit on the select we are done
1074
-			if ($limit === -1) {
1075
-				break;
1076
-			}
1077
-
1078
-			$offset += $added;
1079
-
1080
-			// Fetch again $limit shares
1081
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1082
-
1083
-			// No more shares means we are done
1084
-			if (empty($shares)) {
1085
-				break;
1086
-			}
1087
-		}
1088
-
1089
-		$shares = $shares2;
1090
-
1091
-		return $shares;
1092
-	}
1093
-
1094
-	/**
1095
-	 * @inheritdoc
1096
-	 */
1097
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1098
-		try {
1099
-			$provider = $this->factory->getProviderForType($shareType);
1100
-		} catch (ProviderException $e) {
1101
-			return [];
1102
-		}
1103
-
1104
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1105
-
1106
-		// remove all shares which are already expired
1107
-		foreach ($shares as $key => $share) {
1108
-			try {
1109
-				$this->checkExpireDate($share);
1110
-			} catch (ShareNotFound $e) {
1111
-				unset($shares[$key]);
1112
-			}
1113
-		}
1114
-
1115
-		return $shares;
1116
-	}
1117
-
1118
-	/**
1119
-	 * @inheritdoc
1120
-	 */
1121
-	public function getShareById($id, $recipient = null) {
1122
-		if ($id === null) {
1123
-			throw new ShareNotFound();
1124
-		}
1125
-
1126
-		list($providerId, $id) = $this->splitFullId($id);
1127
-
1128
-		try {
1129
-			$provider = $this->factory->getProvider($providerId);
1130
-		} catch (ProviderException $e) {
1131
-			throw new ShareNotFound();
1132
-		}
1133
-
1134
-		$share = $provider->getShareById($id, $recipient);
1135
-
1136
-		$this->checkExpireDate($share);
1137
-
1138
-		return $share;
1139
-	}
1140
-
1141
-	/**
1142
-	 * Get all the shares for a given path
1143
-	 *
1144
-	 * @param \OCP\Files\Node $path
1145
-	 * @param int $page
1146
-	 * @param int $perPage
1147
-	 *
1148
-	 * @return Share[]
1149
-	 */
1150
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1151
-		return [];
1152
-	}
1153
-
1154
-	/**
1155
-	 * Get the share by token possible with password
1156
-	 *
1157
-	 * @param string $token
1158
-	 * @return Share
1159
-	 *
1160
-	 * @throws ShareNotFound
1161
-	 */
1162
-	public function getShareByToken($token) {
1163
-		$share = null;
1164
-		try {
1165
-			if($this->shareApiAllowLinks()) {
1166
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1167
-				$share = $provider->getShareByToken($token);
1168
-			}
1169
-		} catch (ProviderException $e) {
1170
-		} catch (ShareNotFound $e) {
1171
-		}
1172
-
1173
-
1174
-		// If it is not a link share try to fetch a federated share by token
1175
-		if ($share === null) {
1176
-			try {
1177
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1178
-				$share = $provider->getShareByToken($token);
1179
-			} catch (ProviderException $e) {
1180
-			} catch (ShareNotFound $e) {
1181
-			}
1182
-		}
1183
-
1184
-		// If it is not a link share try to fetch a mail share by token
1185
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1186
-			try {
1187
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1188
-				$share = $provider->getShareByToken($token);
1189
-			} catch (ProviderException $e) {
1190
-			} catch (ShareNotFound $e) {
1191
-			}
1192
-		}
1193
-
1194
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1195
-			try {
1196
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1197
-				$share = $provider->getShareByToken($token);
1198
-			} catch (ProviderException $e) {
1199
-			} catch (ShareNotFound $e) {
1200
-			}
1201
-		}
1202
-
1203
-		if ($share === null) {
1204
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1205
-		}
1206
-
1207
-		$this->checkExpireDate($share);
1208
-
1209
-		/*
1043
+        $shares2 = [];
1044
+
1045
+        while(true) {
1046
+            $added = 0;
1047
+            foreach ($shares as $share) {
1048
+
1049
+                try {
1050
+                    $this->checkExpireDate($share);
1051
+                } catch (ShareNotFound $e) {
1052
+                    //Ignore since this basically means the share is deleted
1053
+                    continue;
1054
+                }
1055
+
1056
+                $added++;
1057
+                $shares2[] = $share;
1058
+
1059
+                if (count($shares2) === $limit) {
1060
+                    break;
1061
+                }
1062
+            }
1063
+
1064
+            // If we did not fetch more shares than the limit then there are no more shares
1065
+            if (count($shares) < $limit) {
1066
+                break;
1067
+            }
1068
+
1069
+            if (count($shares2) === $limit) {
1070
+                break;
1071
+            }
1072
+
1073
+            // If there was no limit on the select we are done
1074
+            if ($limit === -1) {
1075
+                break;
1076
+            }
1077
+
1078
+            $offset += $added;
1079
+
1080
+            // Fetch again $limit shares
1081
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1082
+
1083
+            // No more shares means we are done
1084
+            if (empty($shares)) {
1085
+                break;
1086
+            }
1087
+        }
1088
+
1089
+        $shares = $shares2;
1090
+
1091
+        return $shares;
1092
+    }
1093
+
1094
+    /**
1095
+     * @inheritdoc
1096
+     */
1097
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1098
+        try {
1099
+            $provider = $this->factory->getProviderForType($shareType);
1100
+        } catch (ProviderException $e) {
1101
+            return [];
1102
+        }
1103
+
1104
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1105
+
1106
+        // remove all shares which are already expired
1107
+        foreach ($shares as $key => $share) {
1108
+            try {
1109
+                $this->checkExpireDate($share);
1110
+            } catch (ShareNotFound $e) {
1111
+                unset($shares[$key]);
1112
+            }
1113
+        }
1114
+
1115
+        return $shares;
1116
+    }
1117
+
1118
+    /**
1119
+     * @inheritdoc
1120
+     */
1121
+    public function getShareById($id, $recipient = null) {
1122
+        if ($id === null) {
1123
+            throw new ShareNotFound();
1124
+        }
1125
+
1126
+        list($providerId, $id) = $this->splitFullId($id);
1127
+
1128
+        try {
1129
+            $provider = $this->factory->getProvider($providerId);
1130
+        } catch (ProviderException $e) {
1131
+            throw new ShareNotFound();
1132
+        }
1133
+
1134
+        $share = $provider->getShareById($id, $recipient);
1135
+
1136
+        $this->checkExpireDate($share);
1137
+
1138
+        return $share;
1139
+    }
1140
+
1141
+    /**
1142
+     * Get all the shares for a given path
1143
+     *
1144
+     * @param \OCP\Files\Node $path
1145
+     * @param int $page
1146
+     * @param int $perPage
1147
+     *
1148
+     * @return Share[]
1149
+     */
1150
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1151
+        return [];
1152
+    }
1153
+
1154
+    /**
1155
+     * Get the share by token possible with password
1156
+     *
1157
+     * @param string $token
1158
+     * @return Share
1159
+     *
1160
+     * @throws ShareNotFound
1161
+     */
1162
+    public function getShareByToken($token) {
1163
+        $share = null;
1164
+        try {
1165
+            if($this->shareApiAllowLinks()) {
1166
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1167
+                $share = $provider->getShareByToken($token);
1168
+            }
1169
+        } catch (ProviderException $e) {
1170
+        } catch (ShareNotFound $e) {
1171
+        }
1172
+
1173
+
1174
+        // If it is not a link share try to fetch a federated share by token
1175
+        if ($share === null) {
1176
+            try {
1177
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1178
+                $share = $provider->getShareByToken($token);
1179
+            } catch (ProviderException $e) {
1180
+            } catch (ShareNotFound $e) {
1181
+            }
1182
+        }
1183
+
1184
+        // If it is not a link share try to fetch a mail share by token
1185
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1186
+            try {
1187
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1188
+                $share = $provider->getShareByToken($token);
1189
+            } catch (ProviderException $e) {
1190
+            } catch (ShareNotFound $e) {
1191
+            }
1192
+        }
1193
+
1194
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1195
+            try {
1196
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1197
+                $share = $provider->getShareByToken($token);
1198
+            } catch (ProviderException $e) {
1199
+            } catch (ShareNotFound $e) {
1200
+            }
1201
+        }
1202
+
1203
+        if ($share === null) {
1204
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1205
+        }
1206
+
1207
+        $this->checkExpireDate($share);
1208
+
1209
+        /*
1210 1210
 		 * Reduce the permissions for link shares if public upload is not enabled
1211 1211
 		 */
1212
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1213
-			!$this->shareApiLinkAllowPublicUpload()) {
1214
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1215
-		}
1216
-
1217
-		return $share;
1218
-	}
1219
-
1220
-	protected function checkExpireDate($share) {
1221
-		if ($share->getExpirationDate() !== null &&
1222
-			$share->getExpirationDate() <= new \DateTime()) {
1223
-			$this->deleteShare($share);
1224
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1225
-		}
1226
-
1227
-	}
1228
-
1229
-	/**
1230
-	 * Verify the password of a public share
1231
-	 *
1232
-	 * @param \OCP\Share\IShare $share
1233
-	 * @param string $password
1234
-	 * @return bool
1235
-	 */
1236
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1237
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1238
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1239
-		if (!$passwordProtected) {
1240
-			//TODO maybe exception?
1241
-			return false;
1242
-		}
1243
-
1244
-		if ($password === null || $share->getPassword() === null) {
1245
-			return false;
1246
-		}
1247
-
1248
-		$newHash = '';
1249
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1250
-			return false;
1251
-		}
1252
-
1253
-		if (!empty($newHash)) {
1254
-			$share->setPassword($newHash);
1255
-			$provider = $this->factory->getProviderForType($share->getShareType());
1256
-			$provider->update($share);
1257
-		}
1258
-
1259
-		return true;
1260
-	}
1261
-
1262
-	/**
1263
-	 * @inheritdoc
1264
-	 */
1265
-	public function userDeleted($uid) {
1266
-		$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];
1267
-
1268
-		foreach ($types as $type) {
1269
-			try {
1270
-				$provider = $this->factory->getProviderForType($type);
1271
-			} catch (ProviderException $e) {
1272
-				continue;
1273
-			}
1274
-			$provider->userDeleted($uid, $type);
1275
-		}
1276
-	}
1277
-
1278
-	/**
1279
-	 * @inheritdoc
1280
-	 */
1281
-	public function groupDeleted($gid) {
1282
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1283
-		$provider->groupDeleted($gid);
1284
-	}
1285
-
1286
-	/**
1287
-	 * @inheritdoc
1288
-	 */
1289
-	public function userDeletedFromGroup($uid, $gid) {
1290
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1291
-		$provider->userDeletedFromGroup($uid, $gid);
1292
-	}
1293
-
1294
-	/**
1295
-	 * Get access list to a path. This means
1296
-	 * all the users that can access a given path.
1297
-	 *
1298
-	 * Consider:
1299
-	 * -root
1300
-	 * |-folder1 (23)
1301
-	 *  |-folder2 (32)
1302
-	 *   |-fileA (42)
1303
-	 *
1304
-	 * fileA is shared with user1 and user1@server1
1305
-	 * folder2 is shared with group2 (user4 is a member of group2)
1306
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1307
-	 *
1308
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1309
-	 * [
1310
-	 *  users  => [
1311
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1312
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1313
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1314
-	 *  ],
1315
-	 *  remote => [
1316
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1317
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1318
-	 *  ],
1319
-	 *  public => bool
1320
-	 *  mail => bool
1321
-	 * ]
1322
-	 *
1323
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1324
-	 * [
1325
-	 *  users  => ['user1', 'user2', 'user4'],
1326
-	 *  remote => bool,
1327
-	 *  public => bool
1328
-	 *  mail => bool
1329
-	 * ]
1330
-	 *
1331
-	 * This is required for encryption/activity
1332
-	 *
1333
-	 * @param \OCP\Files\Node $path
1334
-	 * @param bool $recursive Should we check all parent folders as well
1335
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1336
-	 * @return array
1337
-	 */
1338
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1339
-		$owner = $path->getOwner()->getUID();
1340
-
1341
-		if ($currentAccess) {
1342
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1343
-		} else {
1344
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1345
-		}
1346
-		if (!$this->userManager->userExists($owner)) {
1347
-			return $al;
1348
-		}
1349
-
1350
-		//Get node for the owner
1351
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1352
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1353
-			$path = $userFolder->getById($path->getId())[0];
1354
-		}
1355
-
1356
-		$providers = $this->factory->getAllProviders();
1357
-
1358
-		/** @var Node[] $nodes */
1359
-		$nodes = [];
1360
-
1361
-
1362
-		if ($currentAccess) {
1363
-			$ownerPath = $path->getPath();
1364
-			$ownerPath = explode('/', $ownerPath, 4);
1365
-			if (count($ownerPath) < 4) {
1366
-				$ownerPath = '';
1367
-			} else {
1368
-				$ownerPath = $ownerPath[3];
1369
-			}
1370
-			$al['users'][$owner] = [
1371
-				'node_id' => $path->getId(),
1372
-				'node_path' => '/' . $ownerPath,
1373
-			];
1374
-		} else {
1375
-			$al['users'][] = $owner;
1376
-		}
1377
-
1378
-		// Collect all the shares
1379
-		while ($path->getPath() !== $userFolder->getPath()) {
1380
-			$nodes[] = $path;
1381
-			if (!$recursive) {
1382
-				break;
1383
-			}
1384
-			$path = $path->getParent();
1385
-		}
1386
-
1387
-		foreach ($providers as $provider) {
1388
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1389
-
1390
-			foreach ($tmp as $k => $v) {
1391
-				if (isset($al[$k])) {
1392
-					if (is_array($al[$k])) {
1393
-						$al[$k] += $v;
1394
-					} else {
1395
-						$al[$k] = $al[$k] || $v;
1396
-					}
1397
-				} else {
1398
-					$al[$k] = $v;
1399
-				}
1400
-			}
1401
-		}
1402
-
1403
-		return $al;
1404
-	}
1405
-
1406
-	/**
1407
-	 * Create a new share
1408
-	 * @return \OCP\Share\IShare
1409
-	 */
1410
-	public function newShare() {
1411
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1412
-	}
1413
-
1414
-	/**
1415
-	 * Is the share API enabled
1416
-	 *
1417
-	 * @return bool
1418
-	 */
1419
-	public function shareApiEnabled() {
1420
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1421
-	}
1422
-
1423
-	/**
1424
-	 * Is public link sharing enabled
1425
-	 *
1426
-	 * @return bool
1427
-	 */
1428
-	public function shareApiAllowLinks() {
1429
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1430
-	}
1431
-
1432
-	/**
1433
-	 * Is password on public link requires
1434
-	 *
1435
-	 * @return bool
1436
-	 */
1437
-	public function shareApiLinkEnforcePassword() {
1438
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1439
-	}
1440
-
1441
-	/**
1442
-	 * Is default expire date enabled
1443
-	 *
1444
-	 * @return bool
1445
-	 */
1446
-	public function shareApiLinkDefaultExpireDate() {
1447
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1448
-	}
1449
-
1450
-	/**
1451
-	 * Is default expire date enforced
1452
-	 *`
1453
-	 * @return bool
1454
-	 */
1455
-	public function shareApiLinkDefaultExpireDateEnforced() {
1456
-		return $this->shareApiLinkDefaultExpireDate() &&
1457
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1458
-	}
1459
-
1460
-	/**
1461
-	 * Number of default expire days
1462
-	 *shareApiLinkAllowPublicUpload
1463
-	 * @return int
1464
-	 */
1465
-	public function shareApiLinkDefaultExpireDays() {
1466
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1467
-	}
1468
-
1469
-	/**
1470
-	 * Allow public upload on link shares
1471
-	 *
1472
-	 * @return bool
1473
-	 */
1474
-	public function shareApiLinkAllowPublicUpload() {
1475
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1476
-	}
1477
-
1478
-	/**
1479
-	 * check if user can only share with group members
1480
-	 * @return bool
1481
-	 */
1482
-	public function shareWithGroupMembersOnly() {
1483
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1484
-	}
1485
-
1486
-	/**
1487
-	 * Check if users can share with groups
1488
-	 * @return bool
1489
-	 */
1490
-	public function allowGroupSharing() {
1491
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1492
-	}
1493
-
1494
-	/**
1495
-	 * Copied from \OC_Util::isSharingDisabledForUser
1496
-	 *
1497
-	 * TODO: Deprecate fuction from OC_Util
1498
-	 *
1499
-	 * @param string $userId
1500
-	 * @return bool
1501
-	 */
1502
-	public function sharingDisabledForUser($userId) {
1503
-		if ($userId === null) {
1504
-			return false;
1505
-		}
1506
-
1507
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1508
-			return $this->sharingDisabledForUsersCache[$userId];
1509
-		}
1510
-
1511
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1512
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1513
-			$excludedGroups = json_decode($groupsList);
1514
-			if (is_null($excludedGroups)) {
1515
-				$excludedGroups = explode(',', $groupsList);
1516
-				$newValue = json_encode($excludedGroups);
1517
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1518
-			}
1519
-			$user = $this->userManager->get($userId);
1520
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1521
-			if (!empty($usersGroups)) {
1522
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1523
-				// if the user is only in groups which are disabled for sharing then
1524
-				// sharing is also disabled for the user
1525
-				if (empty($remainingGroups)) {
1526
-					$this->sharingDisabledForUsersCache[$userId] = true;
1527
-					return true;
1528
-				}
1529
-			}
1530
-		}
1531
-
1532
-		$this->sharingDisabledForUsersCache[$userId] = false;
1533
-		return false;
1534
-	}
1535
-
1536
-	/**
1537
-	 * @inheritdoc
1538
-	 */
1539
-	public function outgoingServer2ServerSharesAllowed() {
1540
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1541
-	}
1542
-
1543
-	/**
1544
-	 * @inheritdoc
1545
-	 */
1546
-	public function shareProviderExists($shareType) {
1547
-		try {
1548
-			$this->factory->getProviderForType($shareType);
1549
-		} catch (ProviderException $e) {
1550
-			return false;
1551
-		}
1552
-
1553
-		return true;
1554
-	}
1212
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1213
+            !$this->shareApiLinkAllowPublicUpload()) {
1214
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1215
+        }
1216
+
1217
+        return $share;
1218
+    }
1219
+
1220
+    protected function checkExpireDate($share) {
1221
+        if ($share->getExpirationDate() !== null &&
1222
+            $share->getExpirationDate() <= new \DateTime()) {
1223
+            $this->deleteShare($share);
1224
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1225
+        }
1226
+
1227
+    }
1228
+
1229
+    /**
1230
+     * Verify the password of a public share
1231
+     *
1232
+     * @param \OCP\Share\IShare $share
1233
+     * @param string $password
1234
+     * @return bool
1235
+     */
1236
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1237
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1238
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1239
+        if (!$passwordProtected) {
1240
+            //TODO maybe exception?
1241
+            return false;
1242
+        }
1243
+
1244
+        if ($password === null || $share->getPassword() === null) {
1245
+            return false;
1246
+        }
1247
+
1248
+        $newHash = '';
1249
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1250
+            return false;
1251
+        }
1252
+
1253
+        if (!empty($newHash)) {
1254
+            $share->setPassword($newHash);
1255
+            $provider = $this->factory->getProviderForType($share->getShareType());
1256
+            $provider->update($share);
1257
+        }
1258
+
1259
+        return true;
1260
+    }
1261
+
1262
+    /**
1263
+     * @inheritdoc
1264
+     */
1265
+    public function userDeleted($uid) {
1266
+        $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];
1267
+
1268
+        foreach ($types as $type) {
1269
+            try {
1270
+                $provider = $this->factory->getProviderForType($type);
1271
+            } catch (ProviderException $e) {
1272
+                continue;
1273
+            }
1274
+            $provider->userDeleted($uid, $type);
1275
+        }
1276
+    }
1277
+
1278
+    /**
1279
+     * @inheritdoc
1280
+     */
1281
+    public function groupDeleted($gid) {
1282
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1283
+        $provider->groupDeleted($gid);
1284
+    }
1285
+
1286
+    /**
1287
+     * @inheritdoc
1288
+     */
1289
+    public function userDeletedFromGroup($uid, $gid) {
1290
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1291
+        $provider->userDeletedFromGroup($uid, $gid);
1292
+    }
1293
+
1294
+    /**
1295
+     * Get access list to a path. This means
1296
+     * all the users that can access a given path.
1297
+     *
1298
+     * Consider:
1299
+     * -root
1300
+     * |-folder1 (23)
1301
+     *  |-folder2 (32)
1302
+     *   |-fileA (42)
1303
+     *
1304
+     * fileA is shared with user1 and user1@server1
1305
+     * folder2 is shared with group2 (user4 is a member of group2)
1306
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1307
+     *
1308
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1309
+     * [
1310
+     *  users  => [
1311
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1312
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1313
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1314
+     *  ],
1315
+     *  remote => [
1316
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1317
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1318
+     *  ],
1319
+     *  public => bool
1320
+     *  mail => bool
1321
+     * ]
1322
+     *
1323
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1324
+     * [
1325
+     *  users  => ['user1', 'user2', 'user4'],
1326
+     *  remote => bool,
1327
+     *  public => bool
1328
+     *  mail => bool
1329
+     * ]
1330
+     *
1331
+     * This is required for encryption/activity
1332
+     *
1333
+     * @param \OCP\Files\Node $path
1334
+     * @param bool $recursive Should we check all parent folders as well
1335
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1336
+     * @return array
1337
+     */
1338
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1339
+        $owner = $path->getOwner()->getUID();
1340
+
1341
+        if ($currentAccess) {
1342
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1343
+        } else {
1344
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1345
+        }
1346
+        if (!$this->userManager->userExists($owner)) {
1347
+            return $al;
1348
+        }
1349
+
1350
+        //Get node for the owner
1351
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1352
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1353
+            $path = $userFolder->getById($path->getId())[0];
1354
+        }
1355
+
1356
+        $providers = $this->factory->getAllProviders();
1357
+
1358
+        /** @var Node[] $nodes */
1359
+        $nodes = [];
1360
+
1361
+
1362
+        if ($currentAccess) {
1363
+            $ownerPath = $path->getPath();
1364
+            $ownerPath = explode('/', $ownerPath, 4);
1365
+            if (count($ownerPath) < 4) {
1366
+                $ownerPath = '';
1367
+            } else {
1368
+                $ownerPath = $ownerPath[3];
1369
+            }
1370
+            $al['users'][$owner] = [
1371
+                'node_id' => $path->getId(),
1372
+                'node_path' => '/' . $ownerPath,
1373
+            ];
1374
+        } else {
1375
+            $al['users'][] = $owner;
1376
+        }
1377
+
1378
+        // Collect all the shares
1379
+        while ($path->getPath() !== $userFolder->getPath()) {
1380
+            $nodes[] = $path;
1381
+            if (!$recursive) {
1382
+                break;
1383
+            }
1384
+            $path = $path->getParent();
1385
+        }
1386
+
1387
+        foreach ($providers as $provider) {
1388
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1389
+
1390
+            foreach ($tmp as $k => $v) {
1391
+                if (isset($al[$k])) {
1392
+                    if (is_array($al[$k])) {
1393
+                        $al[$k] += $v;
1394
+                    } else {
1395
+                        $al[$k] = $al[$k] || $v;
1396
+                    }
1397
+                } else {
1398
+                    $al[$k] = $v;
1399
+                }
1400
+            }
1401
+        }
1402
+
1403
+        return $al;
1404
+    }
1405
+
1406
+    /**
1407
+     * Create a new share
1408
+     * @return \OCP\Share\IShare
1409
+     */
1410
+    public function newShare() {
1411
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1412
+    }
1413
+
1414
+    /**
1415
+     * Is the share API enabled
1416
+     *
1417
+     * @return bool
1418
+     */
1419
+    public function shareApiEnabled() {
1420
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1421
+    }
1422
+
1423
+    /**
1424
+     * Is public link sharing enabled
1425
+     *
1426
+     * @return bool
1427
+     */
1428
+    public function shareApiAllowLinks() {
1429
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1430
+    }
1431
+
1432
+    /**
1433
+     * Is password on public link requires
1434
+     *
1435
+     * @return bool
1436
+     */
1437
+    public function shareApiLinkEnforcePassword() {
1438
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1439
+    }
1440
+
1441
+    /**
1442
+     * Is default expire date enabled
1443
+     *
1444
+     * @return bool
1445
+     */
1446
+    public function shareApiLinkDefaultExpireDate() {
1447
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1448
+    }
1449
+
1450
+    /**
1451
+     * Is default expire date enforced
1452
+     *`
1453
+     * @return bool
1454
+     */
1455
+    public function shareApiLinkDefaultExpireDateEnforced() {
1456
+        return $this->shareApiLinkDefaultExpireDate() &&
1457
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1458
+    }
1459
+
1460
+    /**
1461
+     * Number of default expire days
1462
+     *shareApiLinkAllowPublicUpload
1463
+     * @return int
1464
+     */
1465
+    public function shareApiLinkDefaultExpireDays() {
1466
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1467
+    }
1468
+
1469
+    /**
1470
+     * Allow public upload on link shares
1471
+     *
1472
+     * @return bool
1473
+     */
1474
+    public function shareApiLinkAllowPublicUpload() {
1475
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1476
+    }
1477
+
1478
+    /**
1479
+     * check if user can only share with group members
1480
+     * @return bool
1481
+     */
1482
+    public function shareWithGroupMembersOnly() {
1483
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1484
+    }
1485
+
1486
+    /**
1487
+     * Check if users can share with groups
1488
+     * @return bool
1489
+     */
1490
+    public function allowGroupSharing() {
1491
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1492
+    }
1493
+
1494
+    /**
1495
+     * Copied from \OC_Util::isSharingDisabledForUser
1496
+     *
1497
+     * TODO: Deprecate fuction from OC_Util
1498
+     *
1499
+     * @param string $userId
1500
+     * @return bool
1501
+     */
1502
+    public function sharingDisabledForUser($userId) {
1503
+        if ($userId === null) {
1504
+            return false;
1505
+        }
1506
+
1507
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1508
+            return $this->sharingDisabledForUsersCache[$userId];
1509
+        }
1510
+
1511
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1512
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1513
+            $excludedGroups = json_decode($groupsList);
1514
+            if (is_null($excludedGroups)) {
1515
+                $excludedGroups = explode(',', $groupsList);
1516
+                $newValue = json_encode($excludedGroups);
1517
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1518
+            }
1519
+            $user = $this->userManager->get($userId);
1520
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1521
+            if (!empty($usersGroups)) {
1522
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1523
+                // if the user is only in groups which are disabled for sharing then
1524
+                // sharing is also disabled for the user
1525
+                if (empty($remainingGroups)) {
1526
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1527
+                    return true;
1528
+                }
1529
+            }
1530
+        }
1531
+
1532
+        $this->sharingDisabledForUsersCache[$userId] = false;
1533
+        return false;
1534
+    }
1535
+
1536
+    /**
1537
+     * @inheritdoc
1538
+     */
1539
+    public function outgoingServer2ServerSharesAllowed() {
1540
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1541
+    }
1542
+
1543
+    /**
1544
+     * @inheritdoc
1545
+     */
1546
+    public function shareProviderExists($shareType) {
1547
+        try {
1548
+            $this->factory->getProviderForType($shareType);
1549
+        } catch (ProviderException $e) {
1550
+            return false;
1551
+        }
1552
+
1553
+        return true;
1554
+    }
1555 1555
 
1556 1556
 }
Please login to merge, or discard this patch.