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