Manager.php 36.5 KB
Newer Older
1
2
<?php
/**
Lukas Reschke's avatar
Lukas Reschke committed
3
4
 * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
 * @author Björn Schießle <bjoern@schiessle.org>
Lukas Reschke's avatar
Lukas Reschke committed
5
 * @author Joas Schilling <nickvergessen@owncloud.com>
6
7
 * @author Roeland Jago Douma <rullzer@owncloud.com>
 *
Thomas Müller's avatar
Thomas Müller committed
8
 * @copyright Copyright (c) 2016, ownCloud, Inc.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 * @license AGPL-3.0
 *
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
24

25
26
namespace OC\Share20;

27
use OC\Cache\CappedMemoryCache;
28
use OC\Files\Mount\MoveableMount;
29
30
use OCP\Files\File;
use OCP\Files\Folder;
31
use OCP\Files\IRootFolder;
32
use OCP\Files\Mount\IMountManager;
Roeland Jago Douma's avatar
Roeland Jago Douma committed
33
use OCP\Files\NotFoundException;
34
use OCP\IConfig;
35
use OCP\IGroupManager;
36
use OCP\IL10N;
37
use OCP\ILogger;
38
use OCP\IUserManager;
39
use OCP\Security\IHasher;
40
use OCP\Security\ISecureRandom;
41
use OCP\Share\Exceptions\GenericShareException;
42
43
44
use OCP\Share\Exceptions\ShareNotFound;
use OCP\Share\IManager;
use OCP\Share\IProviderFactory;
45
46
47
48

/**
 * This class is the communication hub for all sharing related operations.
 */
49
class Manager implements IManager {
50

51
52
	/** @var IProviderFactory */
	private $factory;
53
54
	/** @var ILogger */
	private $logger;
55
56
57
58
59
60
61
62
63
64
	/** @var IConfig */
	private $config;
	/** @var ISecureRandom */
	private $secureRandom;
	/** @var IHasher */
	private $hasher;
	/** @var IMountManager */
	private $mountManager;
	/** @var IGroupManager */
	private $groupManager;
65
66
	/** @var IL10N */
	private $l;
67
68
	/** @var IUserManager */
	private $userManager;
69
70
	/** @var IRootFolder */
	private $rootFolder;
71
72
73
	/** @var CappedMemoryCache */
	private $sharingDisabledForUsersCache;

74

75
76
77
78
	/**
	 * Manager constructor.
	 *
	 * @param ILogger $logger
79
80
81
82
83
	 * @param IConfig $config
	 * @param ISecureRandom $secureRandom
	 * @param IHasher $hasher
	 * @param IMountManager $mountManager
	 * @param IGroupManager $groupManager
84
	 * @param IL10N $l
85
	 * @param IProviderFactory $factory
86
	 * @param IUserManager $userManager
Roeland Jago Douma's avatar
Roeland Jago Douma committed
87
	 * @param IRootFolder $rootFolder
88
	 */
89
90
	public function __construct(
			ILogger $logger,
91
92
93
94
			IConfig $config,
			ISecureRandom $secureRandom,
			IHasher $hasher,
			IMountManager $mountManager,
95
			IGroupManager $groupManager,
96
			IL10N $l,
97
			IProviderFactory $factory,
98
99
			IUserManager $userManager,
			IRootFolder $rootFolder
100
	) {
101
		$this->logger = $logger;
102
103
104
105
106
		$this->config = $config;
		$this->secureRandom = $secureRandom;
		$this->hasher = $hasher;
		$this->mountManager = $mountManager;
		$this->groupManager = $groupManager;
107
		$this->l = $l;
108
		$this->factory = $factory;
109
		$this->userManager = $userManager;
110
		$this->rootFolder = $rootFolder;
111
		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
112
	}
113

114
115
116
117
118
119
120
121
122
123
	/**
	 * Convert from a full share id to a tuple (providerId, shareId)
	 *
	 * @param string $id
	 * @return string[]
	 */
	private function splitFullId($id) {
		return explode(':', $id, 2);
	}

124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
	/**
	 * Verify if a password meets all requirements
	 *
	 * @param string $password
	 * @throws \Exception
	 */
	protected function verifyPassword($password) {
		if ($password === null) {
			// No password is set, check if this is allowed.
			if ($this->shareApiLinkEnforcePassword()) {
				throw new \InvalidArgumentException('Passwords are enforced for link shares');
			}

			return;
		}

		// Let others verify the password
		$accepted = true;
		$message = '';
		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
				'password' => $password,
				'accepted' => &$accepted,
				'message' => &$message
		]);

		if (!$accepted) {
			throw new \Exception($message);
		}
	}

	/**
	 * Check for generic requirements before creating a share
	 *
157
	 * @param \OCP\Share\IShare $share
158
159
	 * @throws \InvalidArgumentException
	 * @throws GenericShareException
160
	 */
161
	protected function generalCreateChecks(\OCP\Share\IShare $share) {
162
163
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
			// We expect a valid user as sharedWith for user shares
164
165
			if (!$this->userManager->userExists($share->getSharedWith())) {
				throw new \InvalidArgumentException('SharedWith is not a valid user');
166
167
168
			}
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
			// We expect a valid group as sharedWith for group shares
169
170
			if (!$this->groupManager->groupExists($share->getSharedWith())) {
				throw new \InvalidArgumentException('SharedWith is not a valid group');
171
172
173
174
175
			}
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
			if ($share->getSharedWith() !== null) {
				throw new \InvalidArgumentException('SharedWith should be empty');
			}
176
177
178
179
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
			if ($share->getSharedWith() === null) {
				throw new \InvalidArgumentException('SharedWith should not be empty');
			}
180
181
182
183
184
		} else {
			// We can't handle other types yet
			throw new \InvalidArgumentException('unkown share type');
		}

185
		// Verify the initiator of the share is set
186
187
188
189
190
		if ($share->getSharedBy() === null) {
			throw new \InvalidArgumentException('SharedBy should be set');
		}

		// Cannot share with yourself
191
192
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
			$share->getSharedWith() === $share->getSharedBy()) {
193
194
195
196
			throw new \InvalidArgumentException('Can\'t share with yourself');
		}

		// The path should be set
197
		if ($share->getNode() === null) {
198
199
			throw new \InvalidArgumentException('Path should be set');
		}
200

201
		// And it should be a file or a folder
202
203
		if (!($share->getNode() instanceof \OCP\Files\File) &&
				!($share->getNode() instanceof \OCP\Files\Folder)) {
204
205
206
			throw new \InvalidArgumentException('Path should be either a file or a folder');
		}

207
		// And you can't share your rootfolder
208
209
210
211
212
213
		if ($this->userManager->userExists($share->getSharedBy())) {
			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
		} else {
			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
		}
		if ($sharedPath === $share->getNode()->getPath()) {
214
215
216
			throw new \InvalidArgumentException('You can\'t share your root folder');
		}

217
		// Check if we actually have share permissions
218
219
		if (!$share->getNode()->isShareable()) {
			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
220
			throw new GenericShareException($message_t, $message_t, 404);
221
222
223
224
225
226
227
		}

		// Permissions should be set
		if ($share->getPermissions() === null) {
			throw new \InvalidArgumentException('A share requires permissions');
		}

228
229
230
231
232
233
234
235
236
237
238
		/*
		 * Quick fix for #23536
		 * Non moveable mount points do not have update and delete permissions
		 * while we 'most likely' do have that on the storage.
		 */
		$permissions = $share->getNode()->getPermissions();
		$mount = $share->getNode()->getMountPoint();
		if (!($mount instanceof MoveableMount)) {
			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
		}

239
		// Check that we do not share with more permissions than we have
240
		if ($share->getPermissions() & ~$permissions) {
241
			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
242
			throw new GenericShareException($message_t, $message_t, 404);
243
244
245
246
247
248
		}

		// Check that read permissions are always set
		if (($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
			throw new \InvalidArgumentException('Shares need at least read permissions');
		}
Roeland Jago Douma's avatar
Roeland Jago Douma committed
249
250
251
252
253
254
255
256
257
258
259

		if ($share->getNode() instanceof \OCP\Files\File) {
			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
				throw new GenericShareException($message_t);
			}
			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
				$message_t = $this->l->t('Files can\'t be shared with create permissions');
				throw new GenericShareException($message_t);
			}
		}
260
261
262
263
264
	}

	/**
	 * Validate if the expiration date fits the system settings
	 *
265
	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
266
	 * @return \OCP\Share\IShare The modified share object
267
268
269
	 * @throws GenericShareException
	 * @throws \InvalidArgumentException
	 * @throws \Exception
270
	 */
271
272
273
	protected function validateExpirationDate(\OCP\Share\IShare $share) {

		$expirationDate = $share->getExpirationDate();
274

Roeland Jago Douma's avatar
Roeland Jago Douma committed
275
		if ($expirationDate !== null) {
276
			//Make sure the expiration date is a date
Roeland Jago Douma's avatar
Roeland Jago Douma committed
277
			$expirationDate->setTime(0, 0, 0);
278
279
280

			$date = new \DateTime();
			$date->setTime(0, 0, 0);
Roeland Jago Douma's avatar
Roeland Jago Douma committed
281
			if ($date >= $expirationDate) {
282
				$message = $this->l->t('Expiration date is in the past');
283
				throw new GenericShareException($message, $message, 404);
284
285
286
			}
		}

287
288
289
290
291
292
293
294
295
296
297
298
299
300
		// If expiredate is empty set a default one if there is a default
		$fullId = null;
		try {
			$fullId = $share->getFullId();
		} catch (\UnexpectedValueException $e) {
			// This is a new share
		}

		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
			$expirationDate = new \DateTime();
			$expirationDate->setTime(0,0,0);
			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
		}

301
302
		// If we enforce the expiration date check that is does not exceed
		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
303
			if ($expirationDate === null) {
304
305
306
307
308
309
				throw new \InvalidArgumentException('Expiration date is enforced');
			}

			$date = new \DateTime();
			$date->setTime(0, 0, 0);
			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
Roeland Jago Douma's avatar
Roeland Jago Douma committed
310
			if ($date < $expirationDate) {
311
				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
312
				throw new GenericShareException($message, $message, 404);
313
314
315
			}
		}

316
317
318
319
320
321
		$accepted = true;
		$message = '';
		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
			'expirationDate' => &$expirationDate,
			'accepted' => &$accepted,
			'message' => &$message,
322
			'passwordSet' => $share->getPassword() !== null,
323
324
325
326
		]);

		if (!$accepted) {
			throw new \Exception($message);
327
328
		}

329
330
		$share->setExpirationDate($expirationDate);

331
		return $share;
332
333
334
	}

	/**
335
	 * Check for pre share requirements for user shares
336
	 *
337
	 * @param \OCP\Share\IShare $share
338
339
	 * @throws \Exception
	 */
340
	protected function userCreateChecks(\OCP\Share\IShare $share) {
341
342
		// Check if we can share with group members only
		if ($this->shareWithGroupMembersOnly()) {
343
344
			$sharedBy = $this->userManager->get($share->getSharedBy());
			$sharedWith = $this->userManager->get($share->getSharedWith());
345
346
			// Verify we can share with this user
			$groups = array_intersect(
347
348
					$this->groupManager->getUserGroupIds($sharedBy),
					$this->groupManager->getUserGroupIds($sharedWith)
349
350
351
352
353
354
355
356
357
358
359
			);
			if (empty($groups)) {
				throw new \Exception('Only sharing with group members is allowed');
			}
		}

		/*
		 * TODO: Could be costly, fix
		 *
		 * Also this is not what we want in the future.. then we want to squash identical shares.
		 */
360
		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
361
		$existingShares = $provider->getSharesByPath($share->getNode());
362
		foreach($existingShares as $existingShare) {
363
			// Ignore if it is the same share
Roeland Jago Douma's avatar
Roeland Jago Douma committed
364
365
366
367
368
369
			try {
				if ($existingShare->getFullId() === $share->getFullId()) {
					continue;
				}
			} catch (\UnexpectedValueException $e) {
				//Shares are not identical
370
371
			}

372
373
374
375
376
377
			// Identical share already existst
			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
				throw new \Exception('Path already shared with this user');
			}

			// The share is already shared with this user via a group share
378
379
380
381
382
383
384
			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
				$group = $this->groupManager->get($existingShare->getSharedWith());
				$user = $this->userManager->get($share->getSharedWith());

				if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
					throw new \Exception('Path already shared with this user');
				}
385
386
387
388
389
390
391
			}
		}
	}

	/**
	 * Check for pre share requirements for group shares
	 *
392
	 * @param \OCP\Share\IShare $share
393
394
	 * @throws \Exception
	 */
395
	protected function groupCreateChecks(\OCP\Share\IShare $share) {
396
397
398
399
400
		// Verify group shares are allowed
		if (!$this->allowGroupSharing()) {
			throw new \Exception('Group sharing is now allowed');
		}

401
402
		// Verify if the user can share with this group
		if ($this->shareWithGroupMembersOnly()) {
403
404
405
			$sharedBy = $this->userManager->get($share->getSharedBy());
			$sharedWith = $this->groupManager->get($share->getSharedWith());
			if (!$sharedWith->inGroup($sharedBy)) {
406
407
408
409
410
411
412
413
414
				throw new \Exception('Only sharing within your own groups is allowed');
			}
		}

		/*
		 * TODO: Could be costly, fix
		 *
		 * Also this is not what we want in the future.. then we want to squash identical shares.
		 */
415
		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
416
		$existingShares = $provider->getSharesByPath($share->getNode());
417
		foreach($existingShares as $existingShare) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
418
419
420
421
422
423
			try {
				if ($existingShare->getFullId() === $share->getFullId()) {
					continue;
				}
			} catch (\UnexpectedValueException $e) {
				//It is a new share so just continue
424
425
			}

426
427
428
429
430
431
432
433
434
			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
				throw new \Exception('Path already shared with this group');
			}
		}
	}

	/**
	 * Check for pre share requirements for link shares
	 *
435
	 * @param \OCP\Share\IShare $share
436
437
	 * @throws \Exception
	 */
438
	protected function linkCreateChecks(\OCP\Share\IShare $share) {
439
440
441
442
443
444
445
446
447
448
449
450
		// Are link shares allowed?
		if (!$this->shareApiAllowLinks()) {
			throw new \Exception('Link sharing not allowed');
		}

		// Link shares by definition can't have share permissions
		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
		}

		// Check if public upload is allowed
		if (!$this->shareApiLinkAllowPublicUpload() &&
451
			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
452
453
454
455
			throw new \InvalidArgumentException('Public upload not allowed');
		}
	}

456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
	/**
	 * To make sure we don't get invisible link shares we set the parent
	 * of a link if it is a reshare. This is a quick word around
	 * until we can properly display multiple link shares in the UI
	 *
	 * See: https://github.com/owncloud/core/issues/22295
	 *
	 * FIXME: Remove once multiple link shares can be properly displayed
	 *
	 * @param \OCP\Share\IShare $share
	 */
	protected function setLinkParent(\OCP\Share\IShare $share) {

		// No sense in checking if the method is not there.
		if (method_exists($share, 'setParent')) {
			$storage = $share->getNode()->getStorage();
			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
				$share->setParent($storage->getShareId());
			}
		};
	}

478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
	/**
	 * @param File|Folder $path
	 */
	protected function pathCreateChecks($path) {
		// Make sure that we do not share a path that contains a shared mountpoint
		if ($path instanceof \OCP\Files\Folder) {
			$mounts = $this->mountManager->findIn($path->getPath());
			foreach($mounts as $mount) {
				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
					throw new \InvalidArgumentException('Path contains files shared with you');
				}
			}
		}
	}

	/**
	 * Check if the user that is sharing can actually share
	 *
496
	 * @param \OCP\Share\IShare $share
497
	 * @throws \Exception
498
	 */
499
	protected function canShare(\OCP\Share\IShare $share) {
500
		if (!$this->shareApiEnabled()) {
501
			throw new \Exception('The share API is disabled');
502
503
		}

504
		if ($this->sharingDisabledForUser($share->getSharedBy())) {
505
			throw new \Exception('You are not allowed to share');
506
507
508
		}
	}

509
510
	/**
	 * Share a path
511
	 *
512
	 * @param \OCP\Share\IShare $share
513
	 * @return Share The share object
514
515
516
	 * @throws \Exception
	 *
	 * TODO: handle link share permissions or check them
517
	 */
518
	public function createShare(\OCP\Share\IShare $share) {
519
		$this->canShare($share);
520
521
522

		$this->generalCreateChecks($share);

Roeland Jago Douma's avatar
Roeland Jago Douma committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
		// Verify if there are any issues with the path
		$this->pathCreateChecks($share->getNode());

		/*
		 * On creation of a share the owner is always the owner of the path
		 * Except for mounted federated shares.
		 */
		$storage = $share->getNode()->getStorage();
		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
			$parent = $share->getNode()->getParent();
			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
				$parent = $parent->getParent();
			}
			$share->setShareOwner($parent->getOwner()->getUID());
		} else {
			$share->setShareOwner($share->getNode()->getOwner()->getUID());
		}

541
542
543
544
545
546
547
		//Verify share type
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
			$this->userCreateChecks($share);
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
			$this->groupCreateChecks($share);
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
			$this->linkCreateChecks($share);
548
			$this->setLinkParent($share);
549
550
551
552
553

			/*
			 * For now ignore a set token.
			 */
			$share->setToken(
554
				$this->secureRandom->generate(
555
556
557
558
559
560
561
562
					\OC\Share\Constants::TOKEN_LENGTH,
					\OCP\Security\ISecureRandom::CHAR_LOWER.
					\OCP\Security\ISecureRandom::CHAR_UPPER.
					\OCP\Security\ISecureRandom::CHAR_DIGITS
				)
			);

			//Verify the expiration date
563
			$this->validateExpirationDate($share);
564
565
566
567
568
569
570
571
572
573

			//Verify the password
			$this->verifyPassword($share->getPassword());

			// If a password is set. Hash it!
			if ($share->getPassword() !== null) {
				$share->setPassword($this->hasher->hash($share->getPassword()));
			}
		}

574
		// Cannot share with the owner
575
576
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
			$share->getSharedWith() === $share->getShareOwner()) {
577
578
579
			throw new \InvalidArgumentException('Can\'t share with the share owner');
		}

580
		// Generate the target
581
		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
582
583
584
585
586
587
588
		$target = \OC\Files\Filesystem::normalizePath($target);
		$share->setTarget($target);

		// Pre share hook
		$run = true;
		$error = '';
		$preHookData = [
589
590
			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
			'itemSource' => $share->getNode()->getId(),
591
			'shareType' => $share->getShareType(),
592
			'uidOwner' => $share->getSharedBy(),
593
			'permissions' => $share->getPermissions(),
594
			'fileSource' => $share->getNode()->getId(),
595
596
			'expiration' => $share->getExpirationDate(),
			'token' => $share->getToken(),
597
			'itemTarget' => $share->getTarget(),
598
			'shareWith' => $share->getSharedWith(),
599
			'run' => &$run,
600
			'error' => &$error,
601
602
603
604
605
606
607
		];
		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);

		if ($run === false) {
			throw new \Exception($error);
		}

608
		$provider = $this->factory->getProviderForType($share->getShareType());
609
		$share = $provider->create($share);
610
611
612

		// Post share hook
		$postHookData = [
613
614
			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
			'itemSource' => $share->getNode()->getId(),
615
			'shareType' => $share->getShareType(),
616
			'uidOwner' => $share->getSharedBy(),
617
			'permissions' => $share->getPermissions(),
618
			'fileSource' => $share->getNode()->getId(),
619
620
621
			'expiration' => $share->getExpirationDate(),
			'token' => $share->getToken(),
			'id' => $share->getId(),
622
			'shareWith' => $share->getSharedWith(),
623
624
			'itemTarget' => $share->getTarget(),
			'fileTarget' => $share->getTarget(),
625
		];
626

627
628
629
		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);

		return $share;
630
631
632
633
634
	}

	/**
	 * Update a share
	 *
635
636
	 * @param \OCP\Share\IShare $share
	 * @return \OCP\Share\IShare The share object
637
	 * @throws \InvalidArgumentException
638
	 */
639
	public function updateShare(\OCP\Share\IShare $share) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
640
641
		$expirationDateUpdated = false;

642
		$this->canShare($share);
643

Roeland Jago Douma's avatar
Roeland Jago Douma committed
644
645
646
647
648
		try {
			$originalShare = $this->getShareById($share->getFullId());
		} catch (\UnexpectedValueException $e) {
			throw new \InvalidArgumentException('Share does not have a full id');
		}
649
650
651

		// We can't change the share type!
		if ($share->getShareType() !== $originalShare->getShareType()) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
652
			throw new \InvalidArgumentException('Can\'t change share type');
653
654
655
656
657
		}

		// We can only change the recipient on user shares
		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
658
			throw new \InvalidArgumentException('Can only update recipient on user shares');
659
660
661
		}

		// Cannot share with the owner
662
663
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
			$share->getSharedWith() === $share->getShareOwner()) {
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
			throw new \InvalidArgumentException('Can\'t share with the share owner');
		}

		$this->generalCreateChecks($share);

		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
			$this->userCreateChecks($share);
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
			$this->groupCreateChecks($share);
		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
			$this->linkCreateChecks($share);

			// Password updated.
			if ($share->getPassword() !== $originalShare->getPassword()) {
				//Verify the password
				$this->verifyPassword($share->getPassword());

				// If a password is set. Hash it!
				if ($share->getPassword() !== null) {
					$share->setPassword($this->hasher->hash($share->getPassword()));
				}
			}

687
			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
688
				//Verify the expiration date
689
				$this->validateExpirationDate($share);
Roeland Jago Douma's avatar
Roeland Jago Douma committed
690
691
				$expirationDateUpdated = true;
			}
692
693
		}

694
		$this->pathCreateChecks($share->getNode());
695
696
697

		// Now update the share!
		$provider = $this->factory->getProviderForType($share->getShareType());
Roeland Jago Douma's avatar
Roeland Jago Douma committed
698
699
700
701
		$share = $provider->update($share);

		if ($expirationDateUpdated === true) {
			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
702
703
				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
				'itemSource' => $share->getNode()->getId(),
Roeland Jago Douma's avatar
Roeland Jago Douma committed
704
				'date' => $share->getExpirationDate(),
705
				'uidOwner' => $share->getSharedBy(),
Roeland Jago Douma's avatar
Roeland Jago Douma committed
706
707
708
			]);
		}

709
710
711
712
713
714
715
716
717
718
		if ($share->getPassword() !== $originalShare->getPassword()) {
			\OC_Hook::emit('OCP\Share', 'post_update_password', [
				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
				'itemSource' => $share->getNode()->getId(),
				'uidOwner' => $share->getSharedBy(),
				'token' => $share->getToken(),
				'disabled' => is_null($share->getPassword()),
			]);
		}

719
		if ($share->getPermissions() !== $originalShare->getPermissions()) {
720
721
722
723
724
			if ($this->userManager->userExists($share->getShareOwner())) {
				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
			} else {
				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
			}
725
726
727
728
729
730
731
			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
				'itemSource' => $share->getNode()->getId(),
				'shareType' => $share->getShareType(),
				'shareWith' => $share->getSharedWith(),
				'uidOwner' => $share->getSharedBy(),
				'permissions' => $share->getPermissions(),
Roeland Jago Douma's avatar
Roeland Jago Douma committed
732
				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
733
734
735
			));
		}

Roeland Jago Douma's avatar
Roeland Jago Douma committed
736
		return $share;
737
738
	}

739
740
	/**
	 * Delete all the children of this share
741
	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
742
	 *
743
744
	 * @param \OCP\Share\IShare $share
	 * @return \OCP\Share\IShare[] List of deleted shares
745
	 */
746
	protected function deleteChildren(\OCP\Share\IShare $share) {
747
748
		$deletedShares = [];

749
		$provider = $this->factory->getProviderForType($share->getShareType());
750

751
752
753
		foreach ($provider->getChildren($share) as $child) {
			$deletedChildren = $this->deleteChildren($child);
			$deletedShares = array_merge($deletedShares, $deletedChildren);
754

755
756
			$provider->delete($child);
			$deletedShares[] = $child;
757
758
759
760
761
		}

		return $deletedShares;
	}

762
763
764
	/**
	 * Delete a share
	 *
765
	 * @param \OCP\Share\IShare $share
766
	 * @throws ShareNotFound
Roeland Jago Douma's avatar
Roeland Jago Douma committed
767
	 * @throws \InvalidArgumentException
768
	 */
769
	public function deleteShare(\OCP\Share\IShare $share) {
770

Roeland Jago Douma's avatar
Roeland Jago Douma committed
771
		try {
772
			$share->getFullId();
Roeland Jago Douma's avatar
Roeland Jago Douma committed
773
774
775
		} catch (\UnexpectedValueException $e) {
			throw new \InvalidArgumentException('Share does not have a full id');
		}
776

777
		$formatHookParams = function(\OCP\Share\IShare $share) {
778
779
780
781
			// Prepare hook
			$shareType = $share->getShareType();
			$sharedWith = '';
			if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
782
				$sharedWith = $share->getSharedWith();
783
			} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
784
				$sharedWith = $share->getSharedWith();
785
786
787
788
789
790
			} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
				$sharedWith = $share->getSharedWith();
			}

			$hookParams = [
				'id'         => $share->getId(),
791
792
				'itemType'   => $share->getNodeType(),
				'itemSource' => $share->getNodeId(),
793
794
				'shareType'  => $shareType,
				'shareWith'  => $sharedWith,
795
				'itemparent' => method_exists($share, 'getParent') ? $share->getParent() : '',
796
				'uidOwner'   => $share->getSharedBy(),
797
				'fileSource' => $share->getNodeId(),
798
799
800
801
802
803
804
805
806
807
808
809
810
811
				'fileTarget' => $share->getTarget()
			];
			return $hookParams;
		};

		$hookParams = $formatHookParams($share);

		// Emit pre-hook
		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);

		// Get all children and delete them as well
		$deletedShares = $this->deleteChildren($share);

		// Do the actual delete
812
		$provider = $this->factory->getProviderForType($share->getShareType());
813
		$provider->delete($share);
814
815
816
817
818
819
820
821
822
823
824
825
826

		// All the deleted shares caused by this delete
		$deletedShares[] = $share;

		//Format hook info
		$formattedDeletedShares = array_map(function($share) use ($formatHookParams) {
			return $formatHookParams($share);
		}, $deletedShares);

		$hookParams['deletedShares'] = $formattedDeletedShares;

		// Emit post hook
		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
827
828
	}

829

830
831
832
833
834
835
	/**
	 * Unshare a file as the recipient.
	 * This can be different from a regular delete for example when one of
	 * the users in a groups deletes that share. But the provider should
	 * handle this.
	 *
836
	 * @param \OCP\Share\IShare $share
837
	 * @param string $recipientId
838
	 */
839
	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
840
		list($providerId, ) = $this->splitFullId($share->getFullId());
841
842
		$provider = $this->factory->getProvider($providerId);

843
		$provider->deleteFromSelf($share, $recipientId);
844
845
	}

846
847
848
	/**
	 * @inheritdoc
	 */
849
	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
850
851
852
853
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
			throw new \InvalidArgumentException('Can\'t change target of link share');
		}

854
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
855
856
857
			throw new \InvalidArgumentException('Invalid recipient');
		}

858
859
860
861
862
863
864
865
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
			$sharedWith = $this->groupManager->get($share->getSharedWith());
			$recipient = $this->userManager->get($recipientId);
			if (!$sharedWith->inGroup($recipient)) {
				throw new \InvalidArgumentException('Invalid recipient');
			}
		}

Roeland Jago Douma's avatar
Roeland Jago Douma committed
866
		list($providerId, ) = $this->splitFullId($share->getFullId());
867
868
		$provider = $this->factory->getProvider($providerId);

869
		$provider->move($share, $recipientId);
870
871
	}

872
	/**
873
	 * @inheritdoc
874
	 */
875
	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
876
877
878
879
880
881
882
883
		if ($path !== null &&
				!($path instanceof \OCP\Files\File) &&
				!($path instanceof \OCP\Files\Folder)) {
			throw new \InvalidArgumentException('invalid path');
		}

		$provider = $this->factory->getProviderForType($shareType);

884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);

		/*
		 * Work around so we don't return expired shares but still follow
		 * proper pagination.
		 */
		if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
			$shares2 = [];
			$today = new \DateTime();

			while(true) {
				$added = 0;
				foreach ($shares as $share) {
					// Check if the share is expired and if so delete it
					if ($share->getExpirationDate() !== null &&
						$share->getExpirationDate() <= $today
					) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
901
902
903
904
905
						try {
							$this->deleteShare($share);
						} catch (NotFoundException $e) {
							//Ignore since this basically means the share is deleted
						}
906
907
908
909
910
911
912
913
914
915
916
917
918
919
						continue;
					}
					$added++;
					$shares2[] = $share;

					if (count($shares2) === $limit) {
						break;
					}
				}

				if (count($shares2) === $limit) {
					break;
				}

920
921
922
923
924
				// If there was no limit on the select we are done
				if ($limit === -1) {
					break;
				}

925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
				$offset += $added;

				// Fetch again $limit shares
				$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);

				// No more shares means we are done
				if (empty($shares)) {
					break;
				}
			}

			$shares = $shares2;
		}

		return $shares;
940
941
	}

942
	/**
943
	 * @inheritdoc
944
	 */
945
	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
946
947
		$provider = $this->factory->getProviderForType($shareType);

948
		return $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
949
950
951
	}

	/**
952
	 * @inheritdoc
953
	 */
954
	public function getShareById($id, $recipient = null) {
955
956
957
958
		if ($id === null) {
			throw new ShareNotFound();
		}

959
		list($providerId, $id) = $this->splitFullId($id);
960
		$provider = $this->factory->getProvider($providerId);
961

962
		$share = $provider->getShareById($id, $recipient);
963

964
965
966
967
968
969
970
971
		// Validate link shares expiration date
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
			$share->getExpirationDate() !== null &&
			$share->getExpirationDate() <= new \DateTime()) {
			$this->deleteShare($share);
			throw new ShareNotFound();
		}

972
		return $share;
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
	}

	/**
	 * Get all the shares for a given path
	 *
	 * @param \OCP\Files\Node $path
	 * @param int $page
	 * @param int $perPage
	 *
	 * @return Share[]
	 */
	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
	}

	/**
	 * Get the share by token possible with password
	 *
	 * @param string $token
	 * @return Share
	 *
993
	 * @throws ShareNotFound
994
	 */
995
996
997
	public function getShareByToken($token) {
		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);

998
999
1000
		try {
			$share = $provider->getShareByToken($token);
		} catch (ShareNotFound $e) {
1001
			$share = null;
1002
1003
1004
1005
1006
1007
1008
		}

		// If it is not a link share try to fetch a federated share by token
		if ($share === null) {
			$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
			$share = $provider->getShareByToken($token);
		}
1009

1010
1011
1012
1013
1014
		if ($share->getExpirationDate() !== null &&
			$share->getExpirationDate() <= new \DateTime()) {
			$this->deleteShare($share);
			throw new ShareNotFound();
		}
1015

1016
1017
1018
1019
1020
1021
1022
1023
		/*
		 * Reduce the permissions for link shares if public upload is not enabled
		 */
		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
			!$this->shareApiLinkAllowPublicUpload()) {
			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
		}

1024
1025
1026
1027
1028
1029
		return $share;
	}

	/**
	 * Verify the password of a public share
	 *
1030
	 * @param \OCP\Share\IShare $share
1031
1032
1033
	 * @param string $password
	 * @return bool
	 */
1034
	public function checkPassword(\OCP\Share\IShare $share, $password) {
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
		if ($share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK) {
			//TODO maybe exception?
			return false;
		}

		if ($password === null || $share->getPassword() === null) {
			return false;
		}

		$newHash = '';
		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
			return false;
		}

		if (!empty($newHash)) {
1050
1051
1052
			$share->setPassword($newHash);
			$provider = $this->factory->getProviderForType($share->getShareType());
			$provider->update($share);
1053
1054
1055
		}

		return true;
1056
1057
	}

1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
	/**
	 * @inheritdoc
	 */
	public function userDeleted($uid) {
		$types = [\OCP\Share::SHARE_TYPE_USER, \OCP\Share::SHARE_TYPE_GROUP, \OCP\Share::SHARE_TYPE_LINK, \OCP\Share::SHARE_TYPE_REMOTE];

		foreach ($types as $type) {
			$provider = $this->factory->getProviderForType($type);
			$provider->userDeleted($uid, $type);
		}
	}

1070
1071
1072
1073
1074
1075
1076
1077
	/**
	 * @inheritdoc
	 */
	public function groupDeleted($gid) {
		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
		$provider->groupDeleted($gid);
	}

1078
1079
1080
1081
1082
1083
1084
1085
	/**
	 * @inheritdoc
	 */
	public function userDeletedFromGroup($uid, $gid) {
		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
		$provider->userDeletedFromGroup($uid, $gid);
	}

1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
	/**
	 * Get access list to a path. This means
	 * all the users and groups that can access a given path.
	 *
	 * Consider:
	 * -root
	 * |-folder1
	 *  |-folder2
	 *   |-fileA
	 *
	 * fileA is shared with user1
	 * folder2 is shared with group2
	 * folder1 is shared with user2
	 *
	 * Then the access list will to '/folder1/folder2/fileA' is:
	 * [
	 * 	'users' => ['user1', 'user2'],
	 *  'groups' => ['group2']
	 * ]
	 *
	 * This is required for encryption
	 *
	 * @param \OCP\Files\Node $path
	 */
	public function getAccessList(\OCP\Files\Node $path) {
	}
1112
1113
1114

	/**
	 * Create a new share
1115
	 * @return \OCP\Share\IShare;
1116
1117
	 */
	public function newShare() {
1118
		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
	}

	/**
	 * Is the share API enabled
	 *
	 * @return bool
	 */
	public function shareApiEnabled() {
		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
	}

	/**
	 * Is public link sharing enabled
	 *
	 * @return bool
	 */
	public function shareApiAllowLinks() {
		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
	}

	/**
	 * Is password on public link requires
	 *
	 * @return bool
	 */
	public function shareApiLinkEnforcePassword() {
		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
	}

	/**
	 * Is default expire date enabled
	 *
	 * @return bool
	 */
	public function shareApiLinkDefaultExpireDate() {
		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
	}

	/**
	 * Is default expire date enforced
	 *`
	 * @return bool
	 */
	public function shareApiLinkDefaultExpireDateEnforced() {
1163
1164
		return $this->shareApiLinkDefaultExpireDate() &&
			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
	}

	/**
	 * Number of default expire days
	 *shareApiLinkAllowPublicUpload
	 * @return int
	 */
	public function shareApiLinkDefaultExpireDays() {
		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
	}

	/**
	 * Allow public upload on link shares
	 *
	 * @return bool
	 */
	public function shareApiLinkAllowPublicUpload() {
		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
	}

	/**
	 * check if user can only share with group members
	 * @return bool
	 */
	public function shareWithGroupMembersOnly() {
		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
	}

1193
1194
1195
1196
1197
1198
1199
	/**
	 * Check if users can share with groups
	 * @return bool
	 */
	public function allowGroupSharing() {
		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
	}
1200
1201
1202
1203
1204
1205

	/**
	 * Copied from \OC_Util::isSharingDisabledForUser
	 *
	 * TODO: Deprecate fuction from OC_Util
	 *
1206
	 * @param string $userId
1207
1208
	 * @return bool
	 */
1209
	public function sharingDisabledForUser($userId) {
Roeland Jago Douma's avatar
Roeland Jago Douma committed
1210
1211
1212
1213
		if ($userId === null) {
			return false;
		}

1214
1215
1216
1217
		if (isset($this->sharingDisabledForUsersCache[$userId])) {
			return $this->sharingDisabledForUsersCache[$userId];
		}

1218
1219
1220
1221
1222
1223
1224
1225
		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
			$excludedGroups = json_decode($groupsList);
			if (is_null($excludedGroups)) {
				$excludedGroups = explode(',', $groupsList);
				$newValue = json_encode($excludedGroups);
				$this->config->setAppValue<