Completed
Pull Request — master (#5367)
by Joas
15:26
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
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
173
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
174
-			// We expect a valid user as sharedWith for user shares
175
-			if (!$this->userManager->userExists($share->getSharedWith())) {
176
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
177
-			}
178
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
179
-			// We expect a valid group as sharedWith for group shares
180
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
181
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
182
-			}
183
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
184
-			if ($share->getSharedWith() !== null) {
185
-				throw new \InvalidArgumentException('SharedWith should be empty');
186
-			}
187
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
-			if ($share->getSharedWith() === null) {
189
-				throw new \InvalidArgumentException('SharedWith should not be empty');
190
-			}
191
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
-			if ($share->getSharedWith() === null) {
193
-				throw new \InvalidArgumentException('SharedWith should not be empty');
194
-			}
195
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
196
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
197
-			if ($circle === null) {
198
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
199
-			}
200
-		} else {
201
-			// We can't handle other types yet
202
-			throw new \InvalidArgumentException('unknown share type');
203
-		}
204
-
205
-		// Verify the initiator of the share is set
206
-		if ($share->getSharedBy() === null) {
207
-			throw new \InvalidArgumentException('SharedBy should be set');
208
-		}
209
-
210
-		// Cannot share with yourself
211
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
212
-			$share->getSharedWith() === $share->getSharedBy()) {
213
-			throw new \InvalidArgumentException('Can\'t share with yourself');
214
-		}
215
-
216
-		// The path should be set
217
-		if ($share->getNode() === null) {
218
-			throw new \InvalidArgumentException('Path should be set');
219
-		}
220
-
221
-		// And it should be a file or a folder
222
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
223
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
224
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
225
-		}
226
-
227
-		// And you can't share your rootfolder
228
-		if ($this->userManager->userExists($share->getSharedBy())) {
229
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
230
-		} else {
231
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
232
-		}
233
-		if ($sharedPath === $share->getNode()->getPath()) {
234
-			throw new \InvalidArgumentException('You can\'t share your root folder');
235
-		}
236
-
237
-		// Check if we actually have share permissions
238
-		if (!$share->getNode()->isShareable()) {
239
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
240
-			throw new GenericShareException($message_t, $message_t, 404);
241
-		}
242
-
243
-		// Permissions should be set
244
-		if ($share->getPermissions() === null) {
245
-			throw new \InvalidArgumentException('A share requires permissions');
246
-		}
247
-
248
-		/*
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
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
173
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
174
+            // We expect a valid user as sharedWith for user shares
175
+            if (!$this->userManager->userExists($share->getSharedWith())) {
176
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
177
+            }
178
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
179
+            // We expect a valid group as sharedWith for group shares
180
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
181
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
182
+            }
183
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
184
+            if ($share->getSharedWith() !== null) {
185
+                throw new \InvalidArgumentException('SharedWith should be empty');
186
+            }
187
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
+            if ($share->getSharedWith() === null) {
189
+                throw new \InvalidArgumentException('SharedWith should not be empty');
190
+            }
191
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
+            if ($share->getSharedWith() === null) {
193
+                throw new \InvalidArgumentException('SharedWith should not be empty');
194
+            }
195
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
196
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
197
+            if ($circle === null) {
198
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
199
+            }
200
+        } else {
201
+            // We can't handle other types yet
202
+            throw new \InvalidArgumentException('unknown share type');
203
+        }
204
+
205
+        // Verify the initiator of the share is set
206
+        if ($share->getSharedBy() === null) {
207
+            throw new \InvalidArgumentException('SharedBy should be set');
208
+        }
209
+
210
+        // Cannot share with yourself
211
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
212
+            $share->getSharedWith() === $share->getSharedBy()) {
213
+            throw new \InvalidArgumentException('Can\'t share with yourself');
214
+        }
215
+
216
+        // The path should be set
217
+        if ($share->getNode() === null) {
218
+            throw new \InvalidArgumentException('Path should be set');
219
+        }
220
+
221
+        // And it should be a file or a folder
222
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
223
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
224
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
225
+        }
226
+
227
+        // And you can't share your rootfolder
228
+        if ($this->userManager->userExists($share->getSharedBy())) {
229
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
230
+        } else {
231
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
232
+        }
233
+        if ($sharedPath === $share->getNode()->getPath()) {
234
+            throw new \InvalidArgumentException('You can\'t share your root folder');
235
+        }
236
+
237
+        // Check if we actually have share permissions
238
+        if (!$share->getNode()->isShareable()) {
239
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
240
+            throw new GenericShareException($message_t, $message_t, 404);
241
+        }
242
+
243
+        // Permissions should be set
244
+        if ($share->getPermissions() === null) {
245
+            throw new \InvalidArgumentException('A share requires permissions');
246
+        }
247
+
248
+        /*
249 249
 		 * Quick fix for #23536
250 250
 		 * Non moveable mount points do not have update and delete permissions
251 251
 		 * while we 'most likely' do have that on the storage.
252 252
 		 */
253
-		$permissions = $share->getNode()->getPermissions();
254
-		$mount = $share->getNode()->getMountPoint();
255
-		if (!($mount instanceof MoveableMount)) {
256
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
257
-		}
258
-
259
-		// Check that we do not share with more permissions than we have
260
-		if ($share->getPermissions() & ~$permissions) {
261
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
262
-			throw new GenericShareException($message_t, $message_t, 404);
263
-		}
264
-
265
-
266
-		// Check that read permissions are always set
267
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
268
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
269
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
270
-		if (!$noReadPermissionRequired &&
271
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
272
-			throw new \InvalidArgumentException('Shares need at least read permissions');
273
-		}
274
-
275
-		if ($share->getNode() instanceof \OCP\Files\File) {
276
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
277
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
278
-				throw new GenericShareException($message_t);
279
-			}
280
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
281
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
282
-				throw new GenericShareException($message_t);
283
-			}
284
-		}
285
-	}
286
-
287
-	/**
288
-	 * Validate if the expiration date fits the system settings
289
-	 *
290
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
291
-	 * @return \OCP\Share\IShare The modified share object
292
-	 * @throws GenericShareException
293
-	 * @throws \InvalidArgumentException
294
-	 * @throws \Exception
295
-	 */
296
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
297
-
298
-		$expirationDate = $share->getExpirationDate();
299
-
300
-		if ($expirationDate !== null) {
301
-			//Make sure the expiration date is a date
302
-			$expirationDate->setTime(0, 0, 0);
303
-
304
-			$date = new \DateTime();
305
-			$date->setTime(0, 0, 0);
306
-			if ($date >= $expirationDate) {
307
-				$message = $this->l->t('Expiration date is in the past');
308
-				throw new GenericShareException($message, $message, 404);
309
-			}
310
-		}
311
-
312
-		// If expiredate is empty set a default one if there is a default
313
-		$fullId = null;
314
-		try {
315
-			$fullId = $share->getFullId();
316
-		} catch (\UnexpectedValueException $e) {
317
-			// This is a new share
318
-		}
319
-
320
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
321
-			$expirationDate = new \DateTime();
322
-			$expirationDate->setTime(0,0,0);
323
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
324
-		}
325
-
326
-		// If we enforce the expiration date check that is does not exceed
327
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
328
-			if ($expirationDate === null) {
329
-				throw new \InvalidArgumentException('Expiration date is enforced');
330
-			}
331
-
332
-			$date = new \DateTime();
333
-			$date->setTime(0, 0, 0);
334
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
335
-			if ($date < $expirationDate) {
336
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
337
-				throw new GenericShareException($message, $message, 404);
338
-			}
339
-		}
340
-
341
-		$accepted = true;
342
-		$message = '';
343
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
344
-			'expirationDate' => &$expirationDate,
345
-			'accepted' => &$accepted,
346
-			'message' => &$message,
347
-			'passwordSet' => $share->getPassword() !== null,
348
-		]);
349
-
350
-		if (!$accepted) {
351
-			throw new \Exception($message);
352
-		}
353
-
354
-		$share->setExpirationDate($expirationDate);
355
-
356
-		return $share;
357
-	}
358
-
359
-	/**
360
-	 * Check for pre share requirements for user shares
361
-	 *
362
-	 * @param \OCP\Share\IShare $share
363
-	 * @throws \Exception
364
-	 */
365
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
366
-		// Check if we can share with group members only
367
-		if ($this->shareWithGroupMembersOnly()) {
368
-			$sharedBy = $this->userManager->get($share->getSharedBy());
369
-			$sharedWith = $this->userManager->get($share->getSharedWith());
370
-			// Verify we can share with this user
371
-			$groups = array_intersect(
372
-					$this->groupManager->getUserGroupIds($sharedBy),
373
-					$this->groupManager->getUserGroupIds($sharedWith)
374
-			);
375
-			if (empty($groups)) {
376
-				throw new \Exception('Only sharing with group members is allowed');
377
-			}
378
-		}
379
-
380
-		/*
253
+        $permissions = $share->getNode()->getPermissions();
254
+        $mount = $share->getNode()->getMountPoint();
255
+        if (!($mount instanceof MoveableMount)) {
256
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
257
+        }
258
+
259
+        // Check that we do not share with more permissions than we have
260
+        if ($share->getPermissions() & ~$permissions) {
261
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
262
+            throw new GenericShareException($message_t, $message_t, 404);
263
+        }
264
+
265
+
266
+        // Check that read permissions are always set
267
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
268
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
269
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
270
+        if (!$noReadPermissionRequired &&
271
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
272
+            throw new \InvalidArgumentException('Shares need at least read permissions');
273
+        }
274
+
275
+        if ($share->getNode() instanceof \OCP\Files\File) {
276
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
277
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
278
+                throw new GenericShareException($message_t);
279
+            }
280
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
281
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
282
+                throw new GenericShareException($message_t);
283
+            }
284
+        }
285
+    }
286
+
287
+    /**
288
+     * Validate if the expiration date fits the system settings
289
+     *
290
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
291
+     * @return \OCP\Share\IShare The modified share object
292
+     * @throws GenericShareException
293
+     * @throws \InvalidArgumentException
294
+     * @throws \Exception
295
+     */
296
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
297
+
298
+        $expirationDate = $share->getExpirationDate();
299
+
300
+        if ($expirationDate !== null) {
301
+            //Make sure the expiration date is a date
302
+            $expirationDate->setTime(0, 0, 0);
303
+
304
+            $date = new \DateTime();
305
+            $date->setTime(0, 0, 0);
306
+            if ($date >= $expirationDate) {
307
+                $message = $this->l->t('Expiration date is in the past');
308
+                throw new GenericShareException($message, $message, 404);
309
+            }
310
+        }
311
+
312
+        // If expiredate is empty set a default one if there is a default
313
+        $fullId = null;
314
+        try {
315
+            $fullId = $share->getFullId();
316
+        } catch (\UnexpectedValueException $e) {
317
+            // This is a new share
318
+        }
319
+
320
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
321
+            $expirationDate = new \DateTime();
322
+            $expirationDate->setTime(0,0,0);
323
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
324
+        }
325
+
326
+        // If we enforce the expiration date check that is does not exceed
327
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
328
+            if ($expirationDate === null) {
329
+                throw new \InvalidArgumentException('Expiration date is enforced');
330
+            }
331
+
332
+            $date = new \DateTime();
333
+            $date->setTime(0, 0, 0);
334
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
335
+            if ($date < $expirationDate) {
336
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
337
+                throw new GenericShareException($message, $message, 404);
338
+            }
339
+        }
340
+
341
+        $accepted = true;
342
+        $message = '';
343
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
344
+            'expirationDate' => &$expirationDate,
345
+            'accepted' => &$accepted,
346
+            'message' => &$message,
347
+            'passwordSet' => $share->getPassword() !== null,
348
+        ]);
349
+
350
+        if (!$accepted) {
351
+            throw new \Exception($message);
352
+        }
353
+
354
+        $share->setExpirationDate($expirationDate);
355
+
356
+        return $share;
357
+    }
358
+
359
+    /**
360
+     * Check for pre share requirements for user shares
361
+     *
362
+     * @param \OCP\Share\IShare $share
363
+     * @throws \Exception
364
+     */
365
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
366
+        // Check if we can share with group members only
367
+        if ($this->shareWithGroupMembersOnly()) {
368
+            $sharedBy = $this->userManager->get($share->getSharedBy());
369
+            $sharedWith = $this->userManager->get($share->getSharedWith());
370
+            // Verify we can share with this user
371
+            $groups = array_intersect(
372
+                    $this->groupManager->getUserGroupIds($sharedBy),
373
+                    $this->groupManager->getUserGroupIds($sharedWith)
374
+            );
375
+            if (empty($groups)) {
376
+                throw new \Exception('Only sharing with group members is allowed');
377
+            }
378
+        }
379
+
380
+        /*
381 381
 		 * TODO: Could be costly, fix
382 382
 		 *
383 383
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
384 384
 		 */
385
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
386
-		$existingShares = $provider->getSharesByPath($share->getNode());
387
-		foreach($existingShares as $existingShare) {
388
-			// Ignore if it is the same share
389
-			try {
390
-				if ($existingShare->getFullId() === $share->getFullId()) {
391
-					continue;
392
-				}
393
-			} catch (\UnexpectedValueException $e) {
394
-				//Shares are not identical
395
-			}
396
-
397
-			// Identical share already existst
398
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
399
-				throw new \Exception('Path already shared with this user');
400
-			}
401
-
402
-			// The share is already shared with this user via a group share
403
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
404
-				$group = $this->groupManager->get($existingShare->getSharedWith());
405
-				if (!is_null($group)) {
406
-					$user = $this->userManager->get($share->getSharedWith());
407
-
408
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
409
-						throw new \Exception('Path already shared with this user');
410
-					}
411
-				}
412
-			}
413
-		}
414
-	}
415
-
416
-	/**
417
-	 * Check for pre share requirements for group shares
418
-	 *
419
-	 * @param \OCP\Share\IShare $share
420
-	 * @throws \Exception
421
-	 */
422
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
423
-		// Verify group shares are allowed
424
-		if (!$this->allowGroupSharing()) {
425
-			throw new \Exception('Group sharing is now allowed');
426
-		}
427
-
428
-		// Verify if the user can share with this group
429
-		if ($this->shareWithGroupMembersOnly()) {
430
-			$sharedBy = $this->userManager->get($share->getSharedBy());
431
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
432
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
433
-				throw new \Exception('Only sharing within your own groups is allowed');
434
-			}
435
-		}
436
-
437
-		/*
385
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
386
+        $existingShares = $provider->getSharesByPath($share->getNode());
387
+        foreach($existingShares as $existingShare) {
388
+            // Ignore if it is the same share
389
+            try {
390
+                if ($existingShare->getFullId() === $share->getFullId()) {
391
+                    continue;
392
+                }
393
+            } catch (\UnexpectedValueException $e) {
394
+                //Shares are not identical
395
+            }
396
+
397
+            // Identical share already existst
398
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
399
+                throw new \Exception('Path already shared with this user');
400
+            }
401
+
402
+            // The share is already shared with this user via a group share
403
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
404
+                $group = $this->groupManager->get($existingShare->getSharedWith());
405
+                if (!is_null($group)) {
406
+                    $user = $this->userManager->get($share->getSharedWith());
407
+
408
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
409
+                        throw new \Exception('Path already shared with this user');
410
+                    }
411
+                }
412
+            }
413
+        }
414
+    }
415
+
416
+    /**
417
+     * Check for pre share requirements for group shares
418
+     *
419
+     * @param \OCP\Share\IShare $share
420
+     * @throws \Exception
421
+     */
422
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
423
+        // Verify group shares are allowed
424
+        if (!$this->allowGroupSharing()) {
425
+            throw new \Exception('Group sharing is now allowed');
426
+        }
427
+
428
+        // Verify if the user can share with this group
429
+        if ($this->shareWithGroupMembersOnly()) {
430
+            $sharedBy = $this->userManager->get($share->getSharedBy());
431
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
432
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
433
+                throw new \Exception('Only sharing within your own groups is allowed');
434
+            }
435
+        }
436
+
437
+        /*
438 438
 		 * TODO: Could be costly, fix
439 439
 		 *
440 440
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
441 441
 		 */
442
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
443
-		$existingShares = $provider->getSharesByPath($share->getNode());
444
-		foreach($existingShares as $existingShare) {
445
-			try {
446
-				if ($existingShare->getFullId() === $share->getFullId()) {
447
-					continue;
448
-				}
449
-			} catch (\UnexpectedValueException $e) {
450
-				//It is a new share so just continue
451
-			}
452
-
453
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
454
-				throw new \Exception('Path already shared with this group');
455
-			}
456
-		}
457
-	}
458
-
459
-	/**
460
-	 * Check for pre share requirements for link shares
461
-	 *
462
-	 * @param \OCP\Share\IShare $share
463
-	 * @throws \Exception
464
-	 */
465
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
466
-		// Are link shares allowed?
467
-		if (!$this->shareApiAllowLinks()) {
468
-			throw new \Exception('Link sharing not allowed');
469
-		}
470
-
471
-		// Link shares by definition can't have share permissions
472
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
473
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
474
-		}
475
-
476
-		// Check if public upload is allowed
477
-		if (!$this->shareApiLinkAllowPublicUpload() &&
478
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
479
-			throw new \InvalidArgumentException('Public upload not allowed');
480
-		}
481
-	}
482
-
483
-	/**
484
-	 * To make sure we don't get invisible link shares we set the parent
485
-	 * of a link if it is a reshare. This is a quick word around
486
-	 * until we can properly display multiple link shares in the UI
487
-	 *
488
-	 * See: https://github.com/owncloud/core/issues/22295
489
-	 *
490
-	 * FIXME: Remove once multiple link shares can be properly displayed
491
-	 *
492
-	 * @param \OCP\Share\IShare $share
493
-	 */
494
-	protected function setLinkParent(\OCP\Share\IShare $share) {
495
-
496
-		// No sense in checking if the method is not there.
497
-		if (method_exists($share, 'setParent')) {
498
-			$storage = $share->getNode()->getStorage();
499
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
500
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
501
-				$share->setParent($storage->getShareId());
502
-			}
503
-		};
504
-	}
505
-
506
-	/**
507
-	 * @param File|Folder $path
508
-	 */
509
-	protected function pathCreateChecks($path) {
510
-		// Make sure that we do not share a path that contains a shared mountpoint
511
-		if ($path instanceof \OCP\Files\Folder) {
512
-			$mounts = $this->mountManager->findIn($path->getPath());
513
-			foreach($mounts as $mount) {
514
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
515
-					throw new \InvalidArgumentException('Path contains files shared with you');
516
-				}
517
-			}
518
-		}
519
-	}
520
-
521
-	/**
522
-	 * Check if the user that is sharing can actually share
523
-	 *
524
-	 * @param \OCP\Share\IShare $share
525
-	 * @throws \Exception
526
-	 */
527
-	protected function canShare(\OCP\Share\IShare $share) {
528
-		if (!$this->shareApiEnabled()) {
529
-			throw new \Exception('The share API is disabled');
530
-		}
531
-
532
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
533
-			throw new \Exception('You are not allowed to share');
534
-		}
535
-	}
536
-
537
-	/**
538
-	 * Share a path
539
-	 *
540
-	 * @param \OCP\Share\IShare $share
541
-	 * @return Share The share object
542
-	 * @throws \Exception
543
-	 *
544
-	 * TODO: handle link share permissions or check them
545
-	 */
546
-	public function createShare(\OCP\Share\IShare $share) {
547
-		$this->canShare($share);
548
-
549
-		$this->generalCreateChecks($share);
550
-
551
-		// Verify if there are any issues with the path
552
-		$this->pathCreateChecks($share->getNode());
553
-
554
-		/*
442
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
443
+        $existingShares = $provider->getSharesByPath($share->getNode());
444
+        foreach($existingShares as $existingShare) {
445
+            try {
446
+                if ($existingShare->getFullId() === $share->getFullId()) {
447
+                    continue;
448
+                }
449
+            } catch (\UnexpectedValueException $e) {
450
+                //It is a new share so just continue
451
+            }
452
+
453
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
454
+                throw new \Exception('Path already shared with this group');
455
+            }
456
+        }
457
+    }
458
+
459
+    /**
460
+     * Check for pre share requirements for link shares
461
+     *
462
+     * @param \OCP\Share\IShare $share
463
+     * @throws \Exception
464
+     */
465
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
466
+        // Are link shares allowed?
467
+        if (!$this->shareApiAllowLinks()) {
468
+            throw new \Exception('Link sharing not allowed');
469
+        }
470
+
471
+        // Link shares by definition can't have share permissions
472
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
473
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
474
+        }
475
+
476
+        // Check if public upload is allowed
477
+        if (!$this->shareApiLinkAllowPublicUpload() &&
478
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
479
+            throw new \InvalidArgumentException('Public upload not allowed');
480
+        }
481
+    }
482
+
483
+    /**
484
+     * To make sure we don't get invisible link shares we set the parent
485
+     * of a link if it is a reshare. This is a quick word around
486
+     * until we can properly display multiple link shares in the UI
487
+     *
488
+     * See: https://github.com/owncloud/core/issues/22295
489
+     *
490
+     * FIXME: Remove once multiple link shares can be properly displayed
491
+     *
492
+     * @param \OCP\Share\IShare $share
493
+     */
494
+    protected function setLinkParent(\OCP\Share\IShare $share) {
495
+
496
+        // No sense in checking if the method is not there.
497
+        if (method_exists($share, 'setParent')) {
498
+            $storage = $share->getNode()->getStorage();
499
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
500
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
501
+                $share->setParent($storage->getShareId());
502
+            }
503
+        };
504
+    }
505
+
506
+    /**
507
+     * @param File|Folder $path
508
+     */
509
+    protected function pathCreateChecks($path) {
510
+        // Make sure that we do not share a path that contains a shared mountpoint
511
+        if ($path instanceof \OCP\Files\Folder) {
512
+            $mounts = $this->mountManager->findIn($path->getPath());
513
+            foreach($mounts as $mount) {
514
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
515
+                    throw new \InvalidArgumentException('Path contains files shared with you');
516
+                }
517
+            }
518
+        }
519
+    }
520
+
521
+    /**
522
+     * Check if the user that is sharing can actually share
523
+     *
524
+     * @param \OCP\Share\IShare $share
525
+     * @throws \Exception
526
+     */
527
+    protected function canShare(\OCP\Share\IShare $share) {
528
+        if (!$this->shareApiEnabled()) {
529
+            throw new \Exception('The share API is disabled');
530
+        }
531
+
532
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
533
+            throw new \Exception('You are not allowed to share');
534
+        }
535
+    }
536
+
537
+    /**
538
+     * Share a path
539
+     *
540
+     * @param \OCP\Share\IShare $share
541
+     * @return Share The share object
542
+     * @throws \Exception
543
+     *
544
+     * TODO: handle link share permissions or check them
545
+     */
546
+    public function createShare(\OCP\Share\IShare $share) {
547
+        $this->canShare($share);
548
+
549
+        $this->generalCreateChecks($share);
550
+
551
+        // Verify if there are any issues with the path
552
+        $this->pathCreateChecks($share->getNode());
553
+
554
+        /*
555 555
 		 * On creation of a share the owner is always the owner of the path
556 556
 		 * Except for mounted federated shares.
557 557
 		 */
558
-		$storage = $share->getNode()->getStorage();
559
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
560
-			$parent = $share->getNode()->getParent();
561
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
-				$parent = $parent->getParent();
563
-			}
564
-			$share->setShareOwner($parent->getOwner()->getUID());
565
-		} else {
566
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
567
-		}
568
-
569
-		//Verify share type
570
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
571
-			$this->userCreateChecks($share);
572
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
573
-			$this->groupCreateChecks($share);
574
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
575
-			$this->linkCreateChecks($share);
576
-			$this->setLinkParent($share);
577
-
578
-			/*
558
+        $storage = $share->getNode()->getStorage();
559
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
560
+            $parent = $share->getNode()->getParent();
561
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
562
+                $parent = $parent->getParent();
563
+            }
564
+            $share->setShareOwner($parent->getOwner()->getUID());
565
+        } else {
566
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
567
+        }
568
+
569
+        //Verify share type
570
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
571
+            $this->userCreateChecks($share);
572
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
573
+            $this->groupCreateChecks($share);
574
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
575
+            $this->linkCreateChecks($share);
576
+            $this->setLinkParent($share);
577
+
578
+            /*
579 579
 			 * For now ignore a set token.
580 580
 			 */
581
-			$share->setToken(
582
-				$this->secureRandom->generate(
583
-					\OC\Share\Constants::TOKEN_LENGTH,
584
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
585
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
586
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
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_LOWER.
605
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
606
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
607
-				)
608
-			);
609
-		}
610
-
611
-		// Cannot share with the owner
612
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
613
-			$share->getSharedWith() === $share->getShareOwner()) {
614
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
615
-		}
616
-
617
-		// Generate the target
618
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
619
-		$target = \OC\Files\Filesystem::normalizePath($target);
620
-		$share->setTarget($target);
621
-
622
-		// Pre share hook
623
-		$run = true;
624
-		$error = '';
625
-		$preHookData = [
626
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
627
-			'itemSource' => $share->getNode()->getId(),
628
-			'shareType' => $share->getShareType(),
629
-			'uidOwner' => $share->getSharedBy(),
630
-			'permissions' => $share->getPermissions(),
631
-			'fileSource' => $share->getNode()->getId(),
632
-			'expiration' => $share->getExpirationDate(),
633
-			'token' => $share->getToken(),
634
-			'itemTarget' => $share->getTarget(),
635
-			'shareWith' => $share->getSharedWith(),
636
-			'run' => &$run,
637
-			'error' => &$error,
638
-		];
639
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
640
-
641
-		if ($run === false) {
642
-			throw new \Exception($error);
643
-		}
644
-
645
-		$oldShare = $share;
646
-		$provider = $this->factory->getProviderForType($share->getShareType());
647
-		$share = $provider->create($share);
648
-		//reuse the node we already have
649
-		$share->setNode($oldShare->getNode());
650
-
651
-		// Post share hook
652
-		$postHookData = [
653
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
654
-			'itemSource' => $share->getNode()->getId(),
655
-			'shareType' => $share->getShareType(),
656
-			'uidOwner' => $share->getSharedBy(),
657
-			'permissions' => $share->getPermissions(),
658
-			'fileSource' => $share->getNode()->getId(),
659
-			'expiration' => $share->getExpirationDate(),
660
-			'token' => $share->getToken(),
661
-			'id' => $share->getId(),
662
-			'shareWith' => $share->getSharedWith(),
663
-			'itemTarget' => $share->getTarget(),
664
-			'fileTarget' => $share->getTarget(),
665
-		];
666
-
667
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
668
-
669
-		return $share;
670
-	}
671
-
672
-	/**
673
-	 * Update a share
674
-	 *
675
-	 * @param \OCP\Share\IShare $share
676
-	 * @return \OCP\Share\IShare The share object
677
-	 * @throws \InvalidArgumentException
678
-	 */
679
-	public function updateShare(\OCP\Share\IShare $share) {
680
-		$expirationDateUpdated = false;
681
-
682
-		$this->canShare($share);
683
-
684
-		try {
685
-			$originalShare = $this->getShareById($share->getFullId());
686
-		} catch (\UnexpectedValueException $e) {
687
-			throw new \InvalidArgumentException('Share does not have a full id');
688
-		}
689
-
690
-		// We can't change the share type!
691
-		if ($share->getShareType() !== $originalShare->getShareType()) {
692
-			throw new \InvalidArgumentException('Can\'t change share type');
693
-		}
694
-
695
-		// We can only change the recipient on user shares
696
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
697
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
698
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
699
-		}
700
-
701
-		// Cannot share with the owner
702
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
703
-			$share->getSharedWith() === $share->getShareOwner()) {
704
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
705
-		}
706
-
707
-		$this->generalCreateChecks($share);
708
-
709
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
710
-			$this->userCreateChecks($share);
711
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
712
-			$this->groupCreateChecks($share);
713
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
714
-			$this->linkCreateChecks($share);
715
-
716
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
717
-
718
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
719
-				//Verify the expiration date
720
-				$this->validateExpirationDate($share);
721
-				$expirationDateUpdated = true;
722
-			}
723
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
724
-			$plainTextPassword = $share->getPassword();
725
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
726
-				$plainTextPassword = null;
727
-			}
728
-		}
729
-
730
-		$this->pathCreateChecks($share->getNode());
731
-
732
-		// Now update the share!
733
-		$provider = $this->factory->getProviderForType($share->getShareType());
734
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
735
-			$share = $provider->update($share, $plainTextPassword);
736
-		} else {
737
-			$share = $provider->update($share);
738
-		}
739
-
740
-		if ($expirationDateUpdated === true) {
741
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
742
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
743
-				'itemSource' => $share->getNode()->getId(),
744
-				'date' => $share->getExpirationDate(),
745
-				'uidOwner' => $share->getSharedBy(),
746
-			]);
747
-		}
748
-
749
-		if ($share->getPassword() !== $originalShare->getPassword()) {
750
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
751
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
752
-				'itemSource' => $share->getNode()->getId(),
753
-				'uidOwner' => $share->getSharedBy(),
754
-				'token' => $share->getToken(),
755
-				'disabled' => is_null($share->getPassword()),
756
-			]);
757
-		}
758
-
759
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
760
-			if ($this->userManager->userExists($share->getShareOwner())) {
761
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
762
-			} else {
763
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
764
-			}
765
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
766
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
767
-				'itemSource' => $share->getNode()->getId(),
768
-				'shareType' => $share->getShareType(),
769
-				'shareWith' => $share->getSharedWith(),
770
-				'uidOwner' => $share->getSharedBy(),
771
-				'permissions' => $share->getPermissions(),
772
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
773
-			));
774
-		}
775
-
776
-		return $share;
777
-	}
778
-
779
-	/**
780
-	 * Updates the password of the given share if it is not the same as the
781
-	 * password of the original share.
782
-	 *
783
-	 * @param \OCP\Share\IShare $share the share to update its password.
784
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
785
-	 *        password with.
786
-	 * @return boolean whether the password was updated or not.
787
-	 */
788
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
789
-		// Password updated.
790
-		if ($share->getPassword() !== $originalShare->getPassword()) {
791
-			//Verify the password
792
-			$this->verifyPassword($share->getPassword());
793
-
794
-			// If a password is set. Hash it!
795
-			if ($share->getPassword() !== null) {
796
-				$share->setPassword($this->hasher->hash($share->getPassword()));
797
-
798
-				return true;
799
-			}
800
-		}
801
-
802
-		return false;
803
-	}
804
-
805
-	/**
806
-	 * Delete all the children of this share
807
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
808
-	 *
809
-	 * @param \OCP\Share\IShare $share
810
-	 * @return \OCP\Share\IShare[] List of deleted shares
811
-	 */
812
-	protected function deleteChildren(\OCP\Share\IShare $share) {
813
-		$deletedShares = [];
814
-
815
-		$provider = $this->factory->getProviderForType($share->getShareType());
816
-
817
-		foreach ($provider->getChildren($share) as $child) {
818
-			$deletedChildren = $this->deleteChildren($child);
819
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
820
-
821
-			$provider->delete($child);
822
-			$deletedShares[] = $child;
823
-		}
824
-
825
-		return $deletedShares;
826
-	}
827
-
828
-	/**
829
-	 * Delete a share
830
-	 *
831
-	 * @param \OCP\Share\IShare $share
832
-	 * @throws ShareNotFound
833
-	 * @throws \InvalidArgumentException
834
-	 */
835
-	public function deleteShare(\OCP\Share\IShare $share) {
836
-
837
-		try {
838
-			$share->getFullId();
839
-		} catch (\UnexpectedValueException $e) {
840
-			throw new \InvalidArgumentException('Share does not have a full id');
841
-		}
842
-
843
-		$event = new GenericEvent($share);
844
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
845
-
846
-		// Get all children and delete them as well
847
-		$deletedShares = $this->deleteChildren($share);
848
-
849
-		// Do the actual delete
850
-		$provider = $this->factory->getProviderForType($share->getShareType());
851
-		$provider->delete($share);
852
-
853
-		// All the deleted shares caused by this delete
854
-		$deletedShares[] = $share;
855
-
856
-		// Emit post hook
857
-		$event->setArgument('deletedShares', $deletedShares);
858
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
859
-	}
860
-
861
-
862
-	/**
863
-	 * Unshare a file as the recipient.
864
-	 * This can be different from a regular delete for example when one of
865
-	 * the users in a groups deletes that share. But the provider should
866
-	 * handle this.
867
-	 *
868
-	 * @param \OCP\Share\IShare $share
869
-	 * @param string $recipientId
870
-	 */
871
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
872
-		list($providerId, ) = $this->splitFullId($share->getFullId());
873
-		$provider = $this->factory->getProvider($providerId);
874
-
875
-		$provider->deleteFromSelf($share, $recipientId);
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
-		/*
581
+            $share->setToken(
582
+                $this->secureRandom->generate(
583
+                    \OC\Share\Constants::TOKEN_LENGTH,
584
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
585
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
586
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
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_LOWER.
605
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
606
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
607
+                )
608
+            );
609
+        }
610
+
611
+        // Cannot share with the owner
612
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
613
+            $share->getSharedWith() === $share->getShareOwner()) {
614
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
615
+        }
616
+
617
+        // Generate the target
618
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
619
+        $target = \OC\Files\Filesystem::normalizePath($target);
620
+        $share->setTarget($target);
621
+
622
+        // Pre share hook
623
+        $run = true;
624
+        $error = '';
625
+        $preHookData = [
626
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
627
+            'itemSource' => $share->getNode()->getId(),
628
+            'shareType' => $share->getShareType(),
629
+            'uidOwner' => $share->getSharedBy(),
630
+            'permissions' => $share->getPermissions(),
631
+            'fileSource' => $share->getNode()->getId(),
632
+            'expiration' => $share->getExpirationDate(),
633
+            'token' => $share->getToken(),
634
+            'itemTarget' => $share->getTarget(),
635
+            'shareWith' => $share->getSharedWith(),
636
+            'run' => &$run,
637
+            'error' => &$error,
638
+        ];
639
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
640
+
641
+        if ($run === false) {
642
+            throw new \Exception($error);
643
+        }
644
+
645
+        $oldShare = $share;
646
+        $provider = $this->factory->getProviderForType($share->getShareType());
647
+        $share = $provider->create($share);
648
+        //reuse the node we already have
649
+        $share->setNode($oldShare->getNode());
650
+
651
+        // Post share hook
652
+        $postHookData = [
653
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
654
+            'itemSource' => $share->getNode()->getId(),
655
+            'shareType' => $share->getShareType(),
656
+            'uidOwner' => $share->getSharedBy(),
657
+            'permissions' => $share->getPermissions(),
658
+            'fileSource' => $share->getNode()->getId(),
659
+            'expiration' => $share->getExpirationDate(),
660
+            'token' => $share->getToken(),
661
+            'id' => $share->getId(),
662
+            'shareWith' => $share->getSharedWith(),
663
+            'itemTarget' => $share->getTarget(),
664
+            'fileTarget' => $share->getTarget(),
665
+        ];
666
+
667
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
668
+
669
+        return $share;
670
+    }
671
+
672
+    /**
673
+     * Update a share
674
+     *
675
+     * @param \OCP\Share\IShare $share
676
+     * @return \OCP\Share\IShare The share object
677
+     * @throws \InvalidArgumentException
678
+     */
679
+    public function updateShare(\OCP\Share\IShare $share) {
680
+        $expirationDateUpdated = false;
681
+
682
+        $this->canShare($share);
683
+
684
+        try {
685
+            $originalShare = $this->getShareById($share->getFullId());
686
+        } catch (\UnexpectedValueException $e) {
687
+            throw new \InvalidArgumentException('Share does not have a full id');
688
+        }
689
+
690
+        // We can't change the share type!
691
+        if ($share->getShareType() !== $originalShare->getShareType()) {
692
+            throw new \InvalidArgumentException('Can\'t change share type');
693
+        }
694
+
695
+        // We can only change the recipient on user shares
696
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
697
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
698
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
699
+        }
700
+
701
+        // Cannot share with the owner
702
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
703
+            $share->getSharedWith() === $share->getShareOwner()) {
704
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
705
+        }
706
+
707
+        $this->generalCreateChecks($share);
708
+
709
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
710
+            $this->userCreateChecks($share);
711
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
712
+            $this->groupCreateChecks($share);
713
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
714
+            $this->linkCreateChecks($share);
715
+
716
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
717
+
718
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
719
+                //Verify the expiration date
720
+                $this->validateExpirationDate($share);
721
+                $expirationDateUpdated = true;
722
+            }
723
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
724
+            $plainTextPassword = $share->getPassword();
725
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
726
+                $plainTextPassword = null;
727
+            }
728
+        }
729
+
730
+        $this->pathCreateChecks($share->getNode());
731
+
732
+        // Now update the share!
733
+        $provider = $this->factory->getProviderForType($share->getShareType());
734
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
735
+            $share = $provider->update($share, $plainTextPassword);
736
+        } else {
737
+            $share = $provider->update($share);
738
+        }
739
+
740
+        if ($expirationDateUpdated === true) {
741
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
742
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
743
+                'itemSource' => $share->getNode()->getId(),
744
+                'date' => $share->getExpirationDate(),
745
+                'uidOwner' => $share->getSharedBy(),
746
+            ]);
747
+        }
748
+
749
+        if ($share->getPassword() !== $originalShare->getPassword()) {
750
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
751
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
752
+                'itemSource' => $share->getNode()->getId(),
753
+                'uidOwner' => $share->getSharedBy(),
754
+                'token' => $share->getToken(),
755
+                'disabled' => is_null($share->getPassword()),
756
+            ]);
757
+        }
758
+
759
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
760
+            if ($this->userManager->userExists($share->getShareOwner())) {
761
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
762
+            } else {
763
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
764
+            }
765
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
766
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
767
+                'itemSource' => $share->getNode()->getId(),
768
+                'shareType' => $share->getShareType(),
769
+                'shareWith' => $share->getSharedWith(),
770
+                'uidOwner' => $share->getSharedBy(),
771
+                'permissions' => $share->getPermissions(),
772
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
773
+            ));
774
+        }
775
+
776
+        return $share;
777
+    }
778
+
779
+    /**
780
+     * Updates the password of the given share if it is not the same as the
781
+     * password of the original share.
782
+     *
783
+     * @param \OCP\Share\IShare $share the share to update its password.
784
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
785
+     *        password with.
786
+     * @return boolean whether the password was updated or not.
787
+     */
788
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
789
+        // Password updated.
790
+        if ($share->getPassword() !== $originalShare->getPassword()) {
791
+            //Verify the password
792
+            $this->verifyPassword($share->getPassword());
793
+
794
+            // If a password is set. Hash it!
795
+            if ($share->getPassword() !== null) {
796
+                $share->setPassword($this->hasher->hash($share->getPassword()));
797
+
798
+                return true;
799
+            }
800
+        }
801
+
802
+        return false;
803
+    }
804
+
805
+    /**
806
+     * Delete all the children of this share
807
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
808
+     *
809
+     * @param \OCP\Share\IShare $share
810
+     * @return \OCP\Share\IShare[] List of deleted shares
811
+     */
812
+    protected function deleteChildren(\OCP\Share\IShare $share) {
813
+        $deletedShares = [];
814
+
815
+        $provider = $this->factory->getProviderForType($share->getShareType());
816
+
817
+        foreach ($provider->getChildren($share) as $child) {
818
+            $deletedChildren = $this->deleteChildren($child);
819
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
820
+
821
+            $provider->delete($child);
822
+            $deletedShares[] = $child;
823
+        }
824
+
825
+        return $deletedShares;
826
+    }
827
+
828
+    /**
829
+     * Delete a share
830
+     *
831
+     * @param \OCP\Share\IShare $share
832
+     * @throws ShareNotFound
833
+     * @throws \InvalidArgumentException
834
+     */
835
+    public function deleteShare(\OCP\Share\IShare $share) {
836
+
837
+        try {
838
+            $share->getFullId();
839
+        } catch (\UnexpectedValueException $e) {
840
+            throw new \InvalidArgumentException('Share does not have a full id');
841
+        }
842
+
843
+        $event = new GenericEvent($share);
844
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
845
+
846
+        // Get all children and delete them as well
847
+        $deletedShares = $this->deleteChildren($share);
848
+
849
+        // Do the actual delete
850
+        $provider = $this->factory->getProviderForType($share->getShareType());
851
+        $provider->delete($share);
852
+
853
+        // All the deleted shares caused by this delete
854
+        $deletedShares[] = $share;
855
+
856
+        // Emit post hook
857
+        $event->setArgument('deletedShares', $deletedShares);
858
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
859
+    }
860
+
861
+
862
+    /**
863
+     * Unshare a file as the recipient.
864
+     * This can be different from a regular delete for example when one of
865
+     * the users in a groups deletes that share. But the provider should
866
+     * handle this.
867
+     *
868
+     * @param \OCP\Share\IShare $share
869
+     * @param string $recipientId
870
+     */
871
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
872
+        list($providerId, ) = $this->splitFullId($share->getFullId());
873
+        $provider = $this->factory->getProvider($providerId);
874
+
875
+        $provider->deleteFromSelf($share, $recipientId);
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.