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