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