Passed
Push — master ( 21b7e5...813bdc )
by Christoph
12:53 queued 10s
created
lib/private/Security/TrustedDomainHelper.php 1 patch
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -35,73 +35,73 @@
 block discarded – undo
35 35
  * @package OC\Security
36 36
  */
37 37
 class TrustedDomainHelper {
38
-	/** @var IConfig */
39
-	private $config;
38
+    /** @var IConfig */
39
+    private $config;
40 40
 
41
-	/**
42
-	 * @param IConfig $config
43
-	 */
44
-	public function __construct(IConfig $config) {
45
-		$this->config = $config;
46
-	}
41
+    /**
42
+     * @param IConfig $config
43
+     */
44
+    public function __construct(IConfig $config) {
45
+        $this->config = $config;
46
+    }
47 47
 
48
-	/**
49
-	 * Strips a potential port from a domain (in format domain:port)
50
-	 * @param string $host
51
-	 * @return string $host without appended port
52
-	 */
53
-	private function getDomainWithoutPort($host) {
54
-		$pos = strrpos($host, ':');
55
-		if ($pos !== false) {
56
-			$port = substr($host, $pos + 1);
57
-			if (is_numeric($port)) {
58
-				$host = substr($host, 0, $pos);
59
-			}
60
-		}
61
-		return $host;
62
-	}
48
+    /**
49
+     * Strips a potential port from a domain (in format domain:port)
50
+     * @param string $host
51
+     * @return string $host without appended port
52
+     */
53
+    private function getDomainWithoutPort($host) {
54
+        $pos = strrpos($host, ':');
55
+        if ($pos !== false) {
56
+            $port = substr($host, $pos + 1);
57
+            if (is_numeric($port)) {
58
+                $host = substr($host, 0, $pos);
59
+            }
60
+        }
61
+        return $host;
62
+    }
63 63
 
64
-	/**
65
-	 * Checks whether a domain is considered as trusted from the list
66
-	 * of trusted domains. If no trusted domains have been configured, returns
67
-	 * true.
68
-	 * This is used to prevent Host Header Poisoning.
69
-	 * @param string $domainWithPort
70
-	 * @return bool true if the given domain is trusted or if no trusted domains
71
-	 * have been configured
72
-	 */
73
-	public function isTrustedDomain($domainWithPort) {
74
-		// overwritehost is always trusted
75
-		if ($this->config->getSystemValue('overwritehost') !== '') {
76
-			return true;
77
-		}
64
+    /**
65
+     * Checks whether a domain is considered as trusted from the list
66
+     * of trusted domains. If no trusted domains have been configured, returns
67
+     * true.
68
+     * This is used to prevent Host Header Poisoning.
69
+     * @param string $domainWithPort
70
+     * @return bool true if the given domain is trusted or if no trusted domains
71
+     * have been configured
72
+     */
73
+    public function isTrustedDomain($domainWithPort) {
74
+        // overwritehost is always trusted
75
+        if ($this->config->getSystemValue('overwritehost') !== '') {
76
+            return true;
77
+        }
78 78
 
79
-		$domain = $this->getDomainWithoutPort($domainWithPort);
79
+        $domain = $this->getDomainWithoutPort($domainWithPort);
80 80
 
81
-		// Read trusted domains from config
82
-		$trustedList = $this->config->getSystemValue('trusted_domains', []);
83
-		if (!is_array($trustedList)) {
84
-			return false;
85
-		}
81
+        // Read trusted domains from config
82
+        $trustedList = $this->config->getSystemValue('trusted_domains', []);
83
+        if (!is_array($trustedList)) {
84
+            return false;
85
+        }
86 86
 
87
-		// Always allow access from localhost
88
-		if (preg_match(Request::REGEX_LOCALHOST, $domain) === 1) {
89
-			return true;
90
-		}
91
-		// Reject misformed domains in any case
92
-		if (strpos($domain,'-') === 0 || strpos($domain,'..') !== false) {
93
-			return false;
94
-		}
95
-		// Match, allowing for * wildcards
96
-		foreach ($trustedList as $trusted) {
97
-			if (gettype($trusted) !== 'string') {
98
-				break;
99
-			}
100
-			$regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function($v) { return preg_quote($v, '/'); }, explode('*', $trusted))) . '$/i';
101
-			if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) {
102
-				return true;
103
-			}
104
-		}
105
-		return false;
106
-	}
87
+        // Always allow access from localhost
88
+        if (preg_match(Request::REGEX_LOCALHOST, $domain) === 1) {
89
+            return true;
90
+        }
91
+        // Reject misformed domains in any case
92
+        if (strpos($domain,'-') === 0 || strpos($domain,'..') !== false) {
93
+            return false;
94
+        }
95
+        // Match, allowing for * wildcards
96
+        foreach ($trustedList as $trusted) {
97
+            if (gettype($trusted) !== 'string') {
98
+                break;
99
+            }
100
+            $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function($v) { return preg_quote($v, '/'); }, explode('*', $trusted))) . '$/i';
101
+            if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) {
102
+                return true;
103
+            }
104
+        }
105
+        return false;
106
+    }
107 107
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1749 added lines, -1749 removed lines patch added patch discarded remove patch
@@ -77,1776 +77,1776 @@
 block discarded – undo
77 77
  */
78 78
 class Manager implements IManager {
79 79
 
80
-	/** @var IProviderFactory */
81
-	private $factory;
82
-	/** @var ILogger */
83
-	private $logger;
84
-	/** @var IConfig */
85
-	private $config;
86
-	/** @var ISecureRandom */
87
-	private $secureRandom;
88
-	/** @var IHasher */
89
-	private $hasher;
90
-	/** @var IMountManager */
91
-	private $mountManager;
92
-	/** @var IGroupManager */
93
-	private $groupManager;
94
-	/** @var IL10N */
95
-	private $l;
96
-	/** @var IFactory */
97
-	private $l10nFactory;
98
-	/** @var IUserManager */
99
-	private $userManager;
100
-	/** @var IRootFolder */
101
-	private $rootFolder;
102
-	/** @var CappedMemoryCache */
103
-	private $sharingDisabledForUsersCache;
104
-	/** @var EventDispatcherInterface */
105
-	private $legacyDispatcher;
106
-	/** @var LegacyHooks */
107
-	private $legacyHooks;
108
-	/** @var IMailer */
109
-	private $mailer;
110
-	/** @var IURLGenerator */
111
-	private $urlGenerator;
112
-	/** @var \OC_Defaults */
113
-	private $defaults;
114
-	/** @var IEventDispatcher */
115
-	private $dispatcher;
116
-
117
-
118
-	/**
119
-	 * Manager constructor.
120
-	 *
121
-	 * @param ILogger $logger
122
-	 * @param IConfig $config
123
-	 * @param ISecureRandom $secureRandom
124
-	 * @param IHasher $hasher
125
-	 * @param IMountManager $mountManager
126
-	 * @param IGroupManager $groupManager
127
-	 * @param IL10N $l
128
-	 * @param IFactory $l10nFactory
129
-	 * @param IProviderFactory $factory
130
-	 * @param IUserManager $userManager
131
-	 * @param IRootFolder $rootFolder
132
-	 * @param EventDispatcherInterface $eventDispatcher
133
-	 * @param IMailer $mailer
134
-	 * @param IURLGenerator $urlGenerator
135
-	 * @param \OC_Defaults $defaults
136
-	 */
137
-	public function __construct(
138
-			ILogger $logger,
139
-			IConfig $config,
140
-			ISecureRandom $secureRandom,
141
-			IHasher $hasher,
142
-			IMountManager $mountManager,
143
-			IGroupManager $groupManager,
144
-			IL10N $l,
145
-			IFactory $l10nFactory,
146
-			IProviderFactory $factory,
147
-			IUserManager $userManager,
148
-			IRootFolder $rootFolder,
149
-			EventDispatcherInterface $legacyDispatcher,
150
-			IMailer $mailer,
151
-			IURLGenerator $urlGenerator,
152
-			\OC_Defaults $defaults,
153
-			IEventDispatcher $dispatcher
154
-	) {
155
-		$this->logger = $logger;
156
-		$this->config = $config;
157
-		$this->secureRandom = $secureRandom;
158
-		$this->hasher = $hasher;
159
-		$this->mountManager = $mountManager;
160
-		$this->groupManager = $groupManager;
161
-		$this->l = $l;
162
-		$this->l10nFactory = $l10nFactory;
163
-		$this->factory = $factory;
164
-		$this->userManager = $userManager;
165
-		$this->rootFolder = $rootFolder;
166
-		$this->legacyDispatcher = $legacyDispatcher;
167
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
168
-		$this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
169
-		$this->mailer = $mailer;
170
-		$this->urlGenerator = $urlGenerator;
171
-		$this->defaults = $defaults;
172
-		$this->dispatcher = $dispatcher;
173
-	}
174
-
175
-	/**
176
-	 * Convert from a full share id to a tuple (providerId, shareId)
177
-	 *
178
-	 * @param string $id
179
-	 * @return string[]
180
-	 */
181
-	private function splitFullId($id) {
182
-		return explode(':', $id, 2);
183
-	}
184
-
185
-	/**
186
-	 * Verify if a password meets all requirements
187
-	 *
188
-	 * @param string $password
189
-	 * @throws \Exception
190
-	 */
191
-	protected function verifyPassword($password) {
192
-		if ($password === null) {
193
-			// No password is set, check if this is allowed.
194
-			if ($this->shareApiLinkEnforcePassword()) {
195
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
196
-			}
197
-
198
-			return;
199
-		}
200
-
201
-		// Let others verify the password
202
-		try {
203
-			$this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
204
-		} catch (HintException $e) {
205
-			throw new \Exception($e->getHint());
206
-		}
207
-	}
208
-
209
-	/**
210
-	 * Check for generic requirements before creating a share
211
-	 *
212
-	 * @param \OCP\Share\IShare $share
213
-	 * @throws \InvalidArgumentException
214
-	 * @throws GenericShareException
215
-	 *
216
-	 * @suppress PhanUndeclaredClassMethod
217
-	 */
218
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
219
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
220
-			// We expect a valid user as sharedWith for user shares
221
-			if (!$this->userManager->userExists($share->getSharedWith())) {
222
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
223
-			}
224
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
225
-			// We expect a valid group as sharedWith for group shares
226
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
227
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
228
-			}
229
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
230
-			if ($share->getSharedWith() !== null) {
231
-				throw new \InvalidArgumentException('SharedWith should be empty');
232
-			}
233
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
234
-			if ($share->getSharedWith() === null) {
235
-				throw new \InvalidArgumentException('SharedWith should not be empty');
236
-			}
237
-		}  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238
-			if ($share->getSharedWith() === null) {
239
-				throw new \InvalidArgumentException('SharedWith should not be empty');
240
-			}
241
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
242
-			if ($share->getSharedWith() === null) {
243
-				throw new \InvalidArgumentException('SharedWith should not be empty');
244
-			}
245
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
246
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
247
-			if ($circle === null) {
248
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
249
-			}
250
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
251
-		} else {
252
-			// We can't handle other types yet
253
-			throw new \InvalidArgumentException('unknown share type');
254
-		}
255
-
256
-		// Verify the initiator of the share is set
257
-		if ($share->getSharedBy() === null) {
258
-			throw new \InvalidArgumentException('SharedBy should be set');
259
-		}
260
-
261
-		// Cannot share with yourself
262
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
263
-			$share->getSharedWith() === $share->getSharedBy()) {
264
-			throw new \InvalidArgumentException('Can’t share with yourself');
265
-		}
266
-
267
-		// The path should be set
268
-		if ($share->getNode() === null) {
269
-			throw new \InvalidArgumentException('Path should be set');
270
-		}
271
-
272
-		// And it should be a file or a folder
273
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
274
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
275
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
276
-		}
277
-
278
-		// And you can't share your rootfolder
279
-		if ($this->userManager->userExists($share->getSharedBy())) {
280
-			$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
281
-			$userFolderPath = $userFolder->getPath();
282
-		} else {
283
-			$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
284
-			$userFolderPath = $userFolder->getPath();
285
-		}
286
-		if ($userFolderPath === $share->getNode()->getPath()) {
287
-			throw new \InvalidArgumentException('You can’t share your root folder');
288
-		}
289
-
290
-		// Check if we actually have share permissions
291
-		if (!$share->getNode()->isShareable()) {
292
-			$path = $userFolder->getRelativePath($share->getNode()->getPath());
293
-			$message_t = $this->l->t('You are not allowed to share %s', [$path]);
294
-			throw new GenericShareException($message_t, $message_t, 404);
295
-		}
296
-
297
-		// Permissions should be set
298
-		if ($share->getPermissions() === null) {
299
-			throw new \InvalidArgumentException('A share requires permissions');
300
-		}
301
-
302
-		$isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
303
-		$permissions = 0;
304
-		$mount = $share->getNode()->getMountPoint();
305
-		if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
306
-			// When it's a reshare use the parent share permissions as maximum
307
-			$userMountPointId = $mount->getStorageRootId();
308
-			$userMountPoints = $userFolder->getById($userMountPointId);
309
-			$userMountPoint = array_shift($userMountPoints);
310
-
311
-			/* Check if this is an incoming share */
312
-			$incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
313
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
314
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
315
-			$incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
316
-
317
-			/** @var \OCP\Share\IShare[] $incomingShares */
318
-			if (!empty($incomingShares)) {
319
-				foreach ($incomingShares as $incomingShare) {
320
-					$permissions |= $incomingShare->getPermissions();
321
-				}
322
-			}
323
-		} else {
324
-			/*
80
+    /** @var IProviderFactory */
81
+    private $factory;
82
+    /** @var ILogger */
83
+    private $logger;
84
+    /** @var IConfig */
85
+    private $config;
86
+    /** @var ISecureRandom */
87
+    private $secureRandom;
88
+    /** @var IHasher */
89
+    private $hasher;
90
+    /** @var IMountManager */
91
+    private $mountManager;
92
+    /** @var IGroupManager */
93
+    private $groupManager;
94
+    /** @var IL10N */
95
+    private $l;
96
+    /** @var IFactory */
97
+    private $l10nFactory;
98
+    /** @var IUserManager */
99
+    private $userManager;
100
+    /** @var IRootFolder */
101
+    private $rootFolder;
102
+    /** @var CappedMemoryCache */
103
+    private $sharingDisabledForUsersCache;
104
+    /** @var EventDispatcherInterface */
105
+    private $legacyDispatcher;
106
+    /** @var LegacyHooks */
107
+    private $legacyHooks;
108
+    /** @var IMailer */
109
+    private $mailer;
110
+    /** @var IURLGenerator */
111
+    private $urlGenerator;
112
+    /** @var \OC_Defaults */
113
+    private $defaults;
114
+    /** @var IEventDispatcher */
115
+    private $dispatcher;
116
+
117
+
118
+    /**
119
+     * Manager constructor.
120
+     *
121
+     * @param ILogger $logger
122
+     * @param IConfig $config
123
+     * @param ISecureRandom $secureRandom
124
+     * @param IHasher $hasher
125
+     * @param IMountManager $mountManager
126
+     * @param IGroupManager $groupManager
127
+     * @param IL10N $l
128
+     * @param IFactory $l10nFactory
129
+     * @param IProviderFactory $factory
130
+     * @param IUserManager $userManager
131
+     * @param IRootFolder $rootFolder
132
+     * @param EventDispatcherInterface $eventDispatcher
133
+     * @param IMailer $mailer
134
+     * @param IURLGenerator $urlGenerator
135
+     * @param \OC_Defaults $defaults
136
+     */
137
+    public function __construct(
138
+            ILogger $logger,
139
+            IConfig $config,
140
+            ISecureRandom $secureRandom,
141
+            IHasher $hasher,
142
+            IMountManager $mountManager,
143
+            IGroupManager $groupManager,
144
+            IL10N $l,
145
+            IFactory $l10nFactory,
146
+            IProviderFactory $factory,
147
+            IUserManager $userManager,
148
+            IRootFolder $rootFolder,
149
+            EventDispatcherInterface $legacyDispatcher,
150
+            IMailer $mailer,
151
+            IURLGenerator $urlGenerator,
152
+            \OC_Defaults $defaults,
153
+            IEventDispatcher $dispatcher
154
+    ) {
155
+        $this->logger = $logger;
156
+        $this->config = $config;
157
+        $this->secureRandom = $secureRandom;
158
+        $this->hasher = $hasher;
159
+        $this->mountManager = $mountManager;
160
+        $this->groupManager = $groupManager;
161
+        $this->l = $l;
162
+        $this->l10nFactory = $l10nFactory;
163
+        $this->factory = $factory;
164
+        $this->userManager = $userManager;
165
+        $this->rootFolder = $rootFolder;
166
+        $this->legacyDispatcher = $legacyDispatcher;
167
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
168
+        $this->legacyHooks = new LegacyHooks($this->legacyDispatcher);
169
+        $this->mailer = $mailer;
170
+        $this->urlGenerator = $urlGenerator;
171
+        $this->defaults = $defaults;
172
+        $this->dispatcher = $dispatcher;
173
+    }
174
+
175
+    /**
176
+     * Convert from a full share id to a tuple (providerId, shareId)
177
+     *
178
+     * @param string $id
179
+     * @return string[]
180
+     */
181
+    private function splitFullId($id) {
182
+        return explode(':', $id, 2);
183
+    }
184
+
185
+    /**
186
+     * Verify if a password meets all requirements
187
+     *
188
+     * @param string $password
189
+     * @throws \Exception
190
+     */
191
+    protected function verifyPassword($password) {
192
+        if ($password === null) {
193
+            // No password is set, check if this is allowed.
194
+            if ($this->shareApiLinkEnforcePassword()) {
195
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
196
+            }
197
+
198
+            return;
199
+        }
200
+
201
+        // Let others verify the password
202
+        try {
203
+            $this->legacyDispatcher->dispatch(new ValidatePasswordPolicyEvent($password));
204
+        } catch (HintException $e) {
205
+            throw new \Exception($e->getHint());
206
+        }
207
+    }
208
+
209
+    /**
210
+     * Check for generic requirements before creating a share
211
+     *
212
+     * @param \OCP\Share\IShare $share
213
+     * @throws \InvalidArgumentException
214
+     * @throws GenericShareException
215
+     *
216
+     * @suppress PhanUndeclaredClassMethod
217
+     */
218
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
219
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
220
+            // We expect a valid user as sharedWith for user shares
221
+            if (!$this->userManager->userExists($share->getSharedWith())) {
222
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
223
+            }
224
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
225
+            // We expect a valid group as sharedWith for group shares
226
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
227
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
228
+            }
229
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
230
+            if ($share->getSharedWith() !== null) {
231
+                throw new \InvalidArgumentException('SharedWith should be empty');
232
+            }
233
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
234
+            if ($share->getSharedWith() === null) {
235
+                throw new \InvalidArgumentException('SharedWith should not be empty');
236
+            }
237
+        }  else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE_GROUP) {
238
+            if ($share->getSharedWith() === null) {
239
+                throw new \InvalidArgumentException('SharedWith should not be empty');
240
+            }
241
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
242
+            if ($share->getSharedWith() === null) {
243
+                throw new \InvalidArgumentException('SharedWith should not be empty');
244
+            }
245
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
246
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
247
+            if ($circle === null) {
248
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
249
+            }
250
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_ROOM) {
251
+        } else {
252
+            // We can't handle other types yet
253
+            throw new \InvalidArgumentException('unknown share type');
254
+        }
255
+
256
+        // Verify the initiator of the share is set
257
+        if ($share->getSharedBy() === null) {
258
+            throw new \InvalidArgumentException('SharedBy should be set');
259
+        }
260
+
261
+        // Cannot share with yourself
262
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
263
+            $share->getSharedWith() === $share->getSharedBy()) {
264
+            throw new \InvalidArgumentException('Can’t share with yourself');
265
+        }
266
+
267
+        // The path should be set
268
+        if ($share->getNode() === null) {
269
+            throw new \InvalidArgumentException('Path should be set');
270
+        }
271
+
272
+        // And it should be a file or a folder
273
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
274
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
275
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
276
+        }
277
+
278
+        // And you can't share your rootfolder
279
+        if ($this->userManager->userExists($share->getSharedBy())) {
280
+            $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
281
+            $userFolderPath = $userFolder->getPath();
282
+        } else {
283
+            $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
284
+            $userFolderPath = $userFolder->getPath();
285
+        }
286
+        if ($userFolderPath === $share->getNode()->getPath()) {
287
+            throw new \InvalidArgumentException('You can’t share your root folder');
288
+        }
289
+
290
+        // Check if we actually have share permissions
291
+        if (!$share->getNode()->isShareable()) {
292
+            $path = $userFolder->getRelativePath($share->getNode()->getPath());
293
+            $message_t = $this->l->t('You are not allowed to share %s', [$path]);
294
+            throw new GenericShareException($message_t, $message_t, 404);
295
+        }
296
+
297
+        // Permissions should be set
298
+        if ($share->getPermissions() === null) {
299
+            throw new \InvalidArgumentException('A share requires permissions');
300
+        }
301
+
302
+        $isFederatedShare = $share->getNode()->getStorage()->instanceOfStorage('\OCA\Files_Sharing\External\Storage');
303
+        $permissions = 0;
304
+        $mount = $share->getNode()->getMountPoint();
305
+        if (!$isFederatedShare && $share->getNode()->getOwner()->getUID() !== $share->getSharedBy()) {
306
+            // When it's a reshare use the parent share permissions as maximum
307
+            $userMountPointId = $mount->getStorageRootId();
308
+            $userMountPoints = $userFolder->getById($userMountPointId);
309
+            $userMountPoint = array_shift($userMountPoints);
310
+
311
+            /* Check if this is an incoming share */
312
+            $incomingShares = $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_USER, $userMountPoint, -1, 0);
313
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_GROUP, $userMountPoint, -1, 0));
314
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_CIRCLE, $userMountPoint, -1, 0));
315
+            $incomingShares = array_merge($incomingShares, $this->getSharedWith($share->getSharedBy(), Share::SHARE_TYPE_ROOM, $userMountPoint, -1, 0));
316
+
317
+            /** @var \OCP\Share\IShare[] $incomingShares */
318
+            if (!empty($incomingShares)) {
319
+                foreach ($incomingShares as $incomingShare) {
320
+                    $permissions |= $incomingShare->getPermissions();
321
+                }
322
+            }
323
+        } else {
324
+            /*
325 325
 			 * Quick fix for #23536
326 326
 			 * Non moveable mount points do not have update and delete permissions
327 327
 			 * while we 'most likely' do have that on the storage.
328 328
 			 */
329
-			$permissions = $share->getNode()->getPermissions();
330
-			if (!($mount instanceof MoveableMount)) {
331
-				$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
332
-			}
333
-		}
334
-
335
-		// Check that we do not share with more permissions than we have
336
-		if ($share->getPermissions() & ~$permissions) {
337
-			$path = $userFolder->getRelativePath($share->getNode()->getPath());
338
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$path]);
339
-			throw new GenericShareException($message_t, $message_t, 404);
340
-		}
341
-
342
-
343
-		// Check that read permissions are always set
344
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
345
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
346
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
347
-		if (!$noReadPermissionRequired &&
348
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
349
-			throw new \InvalidArgumentException('Shares need at least read permissions');
350
-		}
351
-
352
-		if ($share->getNode() instanceof \OCP\Files\File) {
353
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
354
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
355
-				throw new GenericShareException($message_t);
356
-			}
357
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
358
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
359
-				throw new GenericShareException($message_t);
360
-			}
361
-		}
362
-	}
363
-
364
-	/**
365
-	 * Validate if the expiration date fits the system settings
366
-	 *
367
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
368
-	 * @return \OCP\Share\IShare The modified share object
369
-	 * @throws GenericShareException
370
-	 * @throws \InvalidArgumentException
371
-	 * @throws \Exception
372
-	 */
373
-	protected function validateExpirationDateInternal(\OCP\Share\IShare $share) {
374
-		$expirationDate = $share->getExpirationDate();
375
-
376
-		if ($expirationDate !== null) {
377
-			//Make sure the expiration date is a date
378
-			$expirationDate->setTime(0, 0, 0);
379
-
380
-			$date = new \DateTime();
381
-			$date->setTime(0, 0, 0);
382
-			if ($date >= $expirationDate) {
383
-				$message = $this->l->t('Expiration date is in the past');
384
-				throw new GenericShareException($message, $message, 404);
385
-			}
386
-		}
387
-
388
-		// If expiredate is empty set a default one if there is a default
389
-		$fullId = null;
390
-		try {
391
-			$fullId = $share->getFullId();
392
-		} catch (\UnexpectedValueException $e) {
393
-			// This is a new share
394
-		}
395
-
396
-		if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397
-			$expirationDate = new \DateTime();
398
-			$expirationDate->setTime(0,0,0);
399
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400
-		}
401
-
402
-		// If we enforce the expiration date check that is does not exceed
403
-		if ($this->shareApiInternalDefaultExpireDateEnforced()) {
404
-			if ($expirationDate === null) {
405
-				throw new \InvalidArgumentException('Expiration date is enforced');
406
-			}
407
-
408
-			$date = new \DateTime();
409
-			$date->setTime(0, 0, 0);
410
-			$date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
411
-			if ($date < $expirationDate) {
412
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413
-				throw new GenericShareException($message, $message, 404);
414
-			}
415
-		}
416
-
417
-		$accepted = true;
418
-		$message = '';
419
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
420
-			'expirationDate' => &$expirationDate,
421
-			'accepted' => &$accepted,
422
-			'message' => &$message,
423
-			'passwordSet' => $share->getPassword() !== null,
424
-		]);
425
-
426
-		if (!$accepted) {
427
-			throw new \Exception($message);
428
-		}
429
-
430
-		$share->setExpirationDate($expirationDate);
431
-
432
-		return $share;
433
-	}
434
-
435
-	/**
436
-	 * Validate if the expiration date fits the system settings
437
-	 *
438
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
439
-	 * @return \OCP\Share\IShare The modified share object
440
-	 * @throws GenericShareException
441
-	 * @throws \InvalidArgumentException
442
-	 * @throws \Exception
443
-	 */
444
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
445
-
446
-		$expirationDate = $share->getExpirationDate();
447
-
448
-		if ($expirationDate !== null) {
449
-			//Make sure the expiration date is a date
450
-			$expirationDate->setTime(0, 0, 0);
451
-
452
-			$date = new \DateTime();
453
-			$date->setTime(0, 0, 0);
454
-			if ($date >= $expirationDate) {
455
-				$message = $this->l->t('Expiration date is in the past');
456
-				throw new GenericShareException($message, $message, 404);
457
-			}
458
-		}
459
-
460
-		// If expiredate is empty set a default one if there is a default
461
-		$fullId = null;
462
-		try {
463
-			$fullId = $share->getFullId();
464
-		} catch (\UnexpectedValueException $e) {
465
-			// This is a new share
466
-		}
467
-
468
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469
-			$expirationDate = new \DateTime();
470
-			$expirationDate->setTime(0,0,0);
471
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472
-		}
473
-
474
-		// If we enforce the expiration date check that is does not exceed
475
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
476
-			if ($expirationDate === null) {
477
-				throw new \InvalidArgumentException('Expiration date is enforced');
478
-			}
479
-
480
-			$date = new \DateTime();
481
-			$date->setTime(0, 0, 0);
482
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
483
-			if ($date < $expirationDate) {
484
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485
-				throw new GenericShareException($message, $message, 404);
486
-			}
487
-		}
488
-
489
-		$accepted = true;
490
-		$message = '';
491
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
492
-			'expirationDate' => &$expirationDate,
493
-			'accepted' => &$accepted,
494
-			'message' => &$message,
495
-			'passwordSet' => $share->getPassword() !== null,
496
-		]);
497
-
498
-		if (!$accepted) {
499
-			throw new \Exception($message);
500
-		}
501
-
502
-		$share->setExpirationDate($expirationDate);
503
-
504
-		return $share;
505
-	}
506
-
507
-	/**
508
-	 * Check for pre share requirements for user shares
509
-	 *
510
-	 * @param \OCP\Share\IShare $share
511
-	 * @throws \Exception
512
-	 */
513
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
514
-		// Check if we can share with group members only
515
-		if ($this->shareWithGroupMembersOnly()) {
516
-			$sharedBy = $this->userManager->get($share->getSharedBy());
517
-			$sharedWith = $this->userManager->get($share->getSharedWith());
518
-			// Verify we can share with this user
519
-			$groups = array_intersect(
520
-					$this->groupManager->getUserGroupIds($sharedBy),
521
-					$this->groupManager->getUserGroupIds($sharedWith)
522
-			);
523
-			if (empty($groups)) {
524
-				throw new \Exception('Sharing is only allowed with group members');
525
-			}
526
-		}
527
-
528
-		/*
329
+            $permissions = $share->getNode()->getPermissions();
330
+            if (!($mount instanceof MoveableMount)) {
331
+                $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
332
+            }
333
+        }
334
+
335
+        // Check that we do not share with more permissions than we have
336
+        if ($share->getPermissions() & ~$permissions) {
337
+            $path = $userFolder->getRelativePath($share->getNode()->getPath());
338
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$path]);
339
+            throw new GenericShareException($message_t, $message_t, 404);
340
+        }
341
+
342
+
343
+        // Check that read permissions are always set
344
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
345
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
346
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
347
+        if (!$noReadPermissionRequired &&
348
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
349
+            throw new \InvalidArgumentException('Shares need at least read permissions');
350
+        }
351
+
352
+        if ($share->getNode() instanceof \OCP\Files\File) {
353
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
354
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
355
+                throw new GenericShareException($message_t);
356
+            }
357
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
358
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
359
+                throw new GenericShareException($message_t);
360
+            }
361
+        }
362
+    }
363
+
364
+    /**
365
+     * Validate if the expiration date fits the system settings
366
+     *
367
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
368
+     * @return \OCP\Share\IShare The modified share object
369
+     * @throws GenericShareException
370
+     * @throws \InvalidArgumentException
371
+     * @throws \Exception
372
+     */
373
+    protected function validateExpirationDateInternal(\OCP\Share\IShare $share) {
374
+        $expirationDate = $share->getExpirationDate();
375
+
376
+        if ($expirationDate !== null) {
377
+            //Make sure the expiration date is a date
378
+            $expirationDate->setTime(0, 0, 0);
379
+
380
+            $date = new \DateTime();
381
+            $date->setTime(0, 0, 0);
382
+            if ($date >= $expirationDate) {
383
+                $message = $this->l->t('Expiration date is in the past');
384
+                throw new GenericShareException($message, $message, 404);
385
+            }
386
+        }
387
+
388
+        // If expiredate is empty set a default one if there is a default
389
+        $fullId = null;
390
+        try {
391
+            $fullId = $share->getFullId();
392
+        } catch (\UnexpectedValueException $e) {
393
+            // This is a new share
394
+        }
395
+
396
+        if ($fullId === null && $expirationDate === null && $this->shareApiInternalDefaultExpireDate()) {
397
+            $expirationDate = new \DateTime();
398
+            $expirationDate->setTime(0,0,0);
399
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiInternalDefaultExpireDays().'D'));
400
+        }
401
+
402
+        // If we enforce the expiration date check that is does not exceed
403
+        if ($this->shareApiInternalDefaultExpireDateEnforced()) {
404
+            if ($expirationDate === null) {
405
+                throw new \InvalidArgumentException('Expiration date is enforced');
406
+            }
407
+
408
+            $date = new \DateTime();
409
+            $date->setTime(0, 0, 0);
410
+            $date->add(new \DateInterval('P' . $this->shareApiInternalDefaultExpireDays() . 'D'));
411
+            if ($date < $expirationDate) {
412
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiInternalDefaultExpireDays()]);
413
+                throw new GenericShareException($message, $message, 404);
414
+            }
415
+        }
416
+
417
+        $accepted = true;
418
+        $message = '';
419
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
420
+            'expirationDate' => &$expirationDate,
421
+            'accepted' => &$accepted,
422
+            'message' => &$message,
423
+            'passwordSet' => $share->getPassword() !== null,
424
+        ]);
425
+
426
+        if (!$accepted) {
427
+            throw new \Exception($message);
428
+        }
429
+
430
+        $share->setExpirationDate($expirationDate);
431
+
432
+        return $share;
433
+    }
434
+
435
+    /**
436
+     * Validate if the expiration date fits the system settings
437
+     *
438
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
439
+     * @return \OCP\Share\IShare The modified share object
440
+     * @throws GenericShareException
441
+     * @throws \InvalidArgumentException
442
+     * @throws \Exception
443
+     */
444
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
445
+
446
+        $expirationDate = $share->getExpirationDate();
447
+
448
+        if ($expirationDate !== null) {
449
+            //Make sure the expiration date is a date
450
+            $expirationDate->setTime(0, 0, 0);
451
+
452
+            $date = new \DateTime();
453
+            $date->setTime(0, 0, 0);
454
+            if ($date >= $expirationDate) {
455
+                $message = $this->l->t('Expiration date is in the past');
456
+                throw new GenericShareException($message, $message, 404);
457
+            }
458
+        }
459
+
460
+        // If expiredate is empty set a default one if there is a default
461
+        $fullId = null;
462
+        try {
463
+            $fullId = $share->getFullId();
464
+        } catch (\UnexpectedValueException $e) {
465
+            // This is a new share
466
+        }
467
+
468
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
469
+            $expirationDate = new \DateTime();
470
+            $expirationDate->setTime(0,0,0);
471
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
472
+        }
473
+
474
+        // If we enforce the expiration date check that is does not exceed
475
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
476
+            if ($expirationDate === null) {
477
+                throw new \InvalidArgumentException('Expiration date is enforced');
478
+            }
479
+
480
+            $date = new \DateTime();
481
+            $date->setTime(0, 0, 0);
482
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
483
+            if ($date < $expirationDate) {
484
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
485
+                throw new GenericShareException($message, $message, 404);
486
+            }
487
+        }
488
+
489
+        $accepted = true;
490
+        $message = '';
491
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
492
+            'expirationDate' => &$expirationDate,
493
+            'accepted' => &$accepted,
494
+            'message' => &$message,
495
+            'passwordSet' => $share->getPassword() !== null,
496
+        ]);
497
+
498
+        if (!$accepted) {
499
+            throw new \Exception($message);
500
+        }
501
+
502
+        $share->setExpirationDate($expirationDate);
503
+
504
+        return $share;
505
+    }
506
+
507
+    /**
508
+     * Check for pre share requirements for user shares
509
+     *
510
+     * @param \OCP\Share\IShare $share
511
+     * @throws \Exception
512
+     */
513
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
514
+        // Check if we can share with group members only
515
+        if ($this->shareWithGroupMembersOnly()) {
516
+            $sharedBy = $this->userManager->get($share->getSharedBy());
517
+            $sharedWith = $this->userManager->get($share->getSharedWith());
518
+            // Verify we can share with this user
519
+            $groups = array_intersect(
520
+                    $this->groupManager->getUserGroupIds($sharedBy),
521
+                    $this->groupManager->getUserGroupIds($sharedWith)
522
+            );
523
+            if (empty($groups)) {
524
+                throw new \Exception('Sharing is only allowed with group members');
525
+            }
526
+        }
527
+
528
+        /*
529 529
 		 * TODO: Could be costly, fix
530 530
 		 *
531 531
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
532 532
 		 */
533
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534
-		$existingShares = $provider->getSharesByPath($share->getNode());
535
-		foreach($existingShares as $existingShare) {
536
-			// Ignore if it is the same share
537
-			try {
538
-				if ($existingShare->getFullId() === $share->getFullId()) {
539
-					continue;
540
-				}
541
-			} catch (\UnexpectedValueException $e) {
542
-				//Shares are not identical
543
-			}
544
-
545
-			// Identical share already existst
546
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
547
-				throw new \Exception('Path is already shared with this user');
548
-			}
549
-
550
-			// The share is already shared with this user via a group share
551
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
552
-				$group = $this->groupManager->get($existingShare->getSharedWith());
553
-				if (!is_null($group)) {
554
-					$user = $this->userManager->get($share->getSharedWith());
555
-
556
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
557
-						throw new \Exception('Path is already shared with this user');
558
-					}
559
-				}
560
-			}
561
-		}
562
-	}
563
-
564
-	/**
565
-	 * Check for pre share requirements for group shares
566
-	 *
567
-	 * @param \OCP\Share\IShare $share
568
-	 * @throws \Exception
569
-	 */
570
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
571
-		// Verify group shares are allowed
572
-		if (!$this->allowGroupSharing()) {
573
-			throw new \Exception('Group sharing is now allowed');
574
-		}
575
-
576
-		// Verify if the user can share with this group
577
-		if ($this->shareWithGroupMembersOnly()) {
578
-			$sharedBy = $this->userManager->get($share->getSharedBy());
579
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
580
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
581
-				throw new \Exception('Sharing is only allowed within your own groups');
582
-			}
583
-		}
584
-
585
-		/*
533
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
534
+        $existingShares = $provider->getSharesByPath($share->getNode());
535
+        foreach($existingShares as $existingShare) {
536
+            // Ignore if it is the same share
537
+            try {
538
+                if ($existingShare->getFullId() === $share->getFullId()) {
539
+                    continue;
540
+                }
541
+            } catch (\UnexpectedValueException $e) {
542
+                //Shares are not identical
543
+            }
544
+
545
+            // Identical share already existst
546
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
547
+                throw new \Exception('Path is already shared with this user');
548
+            }
549
+
550
+            // The share is already shared with this user via a group share
551
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
552
+                $group = $this->groupManager->get($existingShare->getSharedWith());
553
+                if (!is_null($group)) {
554
+                    $user = $this->userManager->get($share->getSharedWith());
555
+
556
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
557
+                        throw new \Exception('Path is already shared with this user');
558
+                    }
559
+                }
560
+            }
561
+        }
562
+    }
563
+
564
+    /**
565
+     * Check for pre share requirements for group shares
566
+     *
567
+     * @param \OCP\Share\IShare $share
568
+     * @throws \Exception
569
+     */
570
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
571
+        // Verify group shares are allowed
572
+        if (!$this->allowGroupSharing()) {
573
+            throw new \Exception('Group sharing is now allowed');
574
+        }
575
+
576
+        // Verify if the user can share with this group
577
+        if ($this->shareWithGroupMembersOnly()) {
578
+            $sharedBy = $this->userManager->get($share->getSharedBy());
579
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
580
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
581
+                throw new \Exception('Sharing is only allowed within your own groups');
582
+            }
583
+        }
584
+
585
+        /*
586 586
 		 * TODO: Could be costly, fix
587 587
 		 *
588 588
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
589 589
 		 */
590
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591
-		$existingShares = $provider->getSharesByPath($share->getNode());
592
-		foreach($existingShares as $existingShare) {
593
-			try {
594
-				if ($existingShare->getFullId() === $share->getFullId()) {
595
-					continue;
596
-				}
597
-			} catch (\UnexpectedValueException $e) {
598
-				//It is a new share so just continue
599
-			}
600
-
601
-			if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
602
-				throw new \Exception('Path is already shared with this group');
603
-			}
604
-		}
605
-	}
606
-
607
-	/**
608
-	 * Check for pre share requirements for link shares
609
-	 *
610
-	 * @param \OCP\Share\IShare $share
611
-	 * @throws \Exception
612
-	 */
613
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
614
-		// Are link shares allowed?
615
-		if (!$this->shareApiAllowLinks()) {
616
-			throw new \Exception('Link sharing is not allowed');
617
-		}
618
-
619
-		// Link shares by definition can't have share permissions
620
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
621
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
622
-		}
623
-
624
-		// Check if public upload is allowed
625
-		if (!$this->shareApiLinkAllowPublicUpload() &&
626
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
627
-			throw new \InvalidArgumentException('Public upload is not allowed');
628
-		}
629
-	}
630
-
631
-	/**
632
-	 * To make sure we don't get invisible link shares we set the parent
633
-	 * of a link if it is a reshare. This is a quick word around
634
-	 * until we can properly display multiple link shares in the UI
635
-	 *
636
-	 * See: https://github.com/owncloud/core/issues/22295
637
-	 *
638
-	 * FIXME: Remove once multiple link shares can be properly displayed
639
-	 *
640
-	 * @param \OCP\Share\IShare $share
641
-	 */
642
-	protected function setLinkParent(\OCP\Share\IShare $share) {
643
-
644
-		// No sense in checking if the method is not there.
645
-		if (method_exists($share, 'setParent')) {
646
-			$storage = $share->getNode()->getStorage();
647
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
648
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
649
-				$share->setParent($storage->getShareId());
650
-			}
651
-		}
652
-	}
653
-
654
-	/**
655
-	 * @param File|Folder $path
656
-	 */
657
-	protected function pathCreateChecks($path) {
658
-		// Make sure that we do not share a path that contains a shared mountpoint
659
-		if ($path instanceof \OCP\Files\Folder) {
660
-			$mounts = $this->mountManager->findIn($path->getPath());
661
-			foreach($mounts as $mount) {
662
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663
-					throw new \InvalidArgumentException('Path contains files shared with you');
664
-				}
665
-			}
666
-		}
667
-	}
668
-
669
-	/**
670
-	 * Check if the user that is sharing can actually share
671
-	 *
672
-	 * @param \OCP\Share\IShare $share
673
-	 * @throws \Exception
674
-	 */
675
-	protected function canShare(\OCP\Share\IShare $share) {
676
-		if (!$this->shareApiEnabled()) {
677
-			throw new \Exception('Sharing is disabled');
678
-		}
679
-
680
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
681
-			throw new \Exception('Sharing is disabled for you');
682
-		}
683
-	}
684
-
685
-	/**
686
-	 * Share a path
687
-	 *
688
-	 * @param \OCP\Share\IShare $share
689
-	 * @return Share The share object
690
-	 * @throws \Exception
691
-	 *
692
-	 * TODO: handle link share permissions or check them
693
-	 */
694
-	public function createShare(\OCP\Share\IShare $share) {
695
-		$this->canShare($share);
696
-
697
-		$this->generalCreateChecks($share);
698
-
699
-		// Verify if there are any issues with the path
700
-		$this->pathCreateChecks($share->getNode());
701
-
702
-		/*
590
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
591
+        $existingShares = $provider->getSharesByPath($share->getNode());
592
+        foreach($existingShares as $existingShare) {
593
+            try {
594
+                if ($existingShare->getFullId() === $share->getFullId()) {
595
+                    continue;
596
+                }
597
+            } catch (\UnexpectedValueException $e) {
598
+                //It is a new share so just continue
599
+            }
600
+
601
+            if ($existingShare->getSharedWith() === $share->getSharedWith() && $existingShare->getShareType() === $share->getShareType()) {
602
+                throw new \Exception('Path is already shared with this group');
603
+            }
604
+        }
605
+    }
606
+
607
+    /**
608
+     * Check for pre share requirements for link shares
609
+     *
610
+     * @param \OCP\Share\IShare $share
611
+     * @throws \Exception
612
+     */
613
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
614
+        // Are link shares allowed?
615
+        if (!$this->shareApiAllowLinks()) {
616
+            throw new \Exception('Link sharing is not allowed');
617
+        }
618
+
619
+        // Link shares by definition can't have share permissions
620
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
621
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
622
+        }
623
+
624
+        // Check if public upload is allowed
625
+        if (!$this->shareApiLinkAllowPublicUpload() &&
626
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
627
+            throw new \InvalidArgumentException('Public upload is not allowed');
628
+        }
629
+    }
630
+
631
+    /**
632
+     * To make sure we don't get invisible link shares we set the parent
633
+     * of a link if it is a reshare. This is a quick word around
634
+     * until we can properly display multiple link shares in the UI
635
+     *
636
+     * See: https://github.com/owncloud/core/issues/22295
637
+     *
638
+     * FIXME: Remove once multiple link shares can be properly displayed
639
+     *
640
+     * @param \OCP\Share\IShare $share
641
+     */
642
+    protected function setLinkParent(\OCP\Share\IShare $share) {
643
+
644
+        // No sense in checking if the method is not there.
645
+        if (method_exists($share, 'setParent')) {
646
+            $storage = $share->getNode()->getStorage();
647
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
648
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
649
+                $share->setParent($storage->getShareId());
650
+            }
651
+        }
652
+    }
653
+
654
+    /**
655
+     * @param File|Folder $path
656
+     */
657
+    protected function pathCreateChecks($path) {
658
+        // Make sure that we do not share a path that contains a shared mountpoint
659
+        if ($path instanceof \OCP\Files\Folder) {
660
+            $mounts = $this->mountManager->findIn($path->getPath());
661
+            foreach($mounts as $mount) {
662
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
663
+                    throw new \InvalidArgumentException('Path contains files shared with you');
664
+                }
665
+            }
666
+        }
667
+    }
668
+
669
+    /**
670
+     * Check if the user that is sharing can actually share
671
+     *
672
+     * @param \OCP\Share\IShare $share
673
+     * @throws \Exception
674
+     */
675
+    protected function canShare(\OCP\Share\IShare $share) {
676
+        if (!$this->shareApiEnabled()) {
677
+            throw new \Exception('Sharing is disabled');
678
+        }
679
+
680
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
681
+            throw new \Exception('Sharing is disabled for you');
682
+        }
683
+    }
684
+
685
+    /**
686
+     * Share a path
687
+     *
688
+     * @param \OCP\Share\IShare $share
689
+     * @return Share The share object
690
+     * @throws \Exception
691
+     *
692
+     * TODO: handle link share permissions or check them
693
+     */
694
+    public function createShare(\OCP\Share\IShare $share) {
695
+        $this->canShare($share);
696
+
697
+        $this->generalCreateChecks($share);
698
+
699
+        // Verify if there are any issues with the path
700
+        $this->pathCreateChecks($share->getNode());
701
+
702
+        /*
703 703
 		 * On creation of a share the owner is always the owner of the path
704 704
 		 * Except for mounted federated shares.
705 705
 		 */
706
-		$storage = $share->getNode()->getStorage();
707
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708
-			$parent = $share->getNode()->getParent();
709
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710
-				$parent = $parent->getParent();
711
-			}
712
-			$share->setShareOwner($parent->getOwner()->getUID());
713
-		} else {
714
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
715
-		}
716
-
717
-		//Verify share type
718
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
719
-			$this->userCreateChecks($share);
720
-
721
-			//Verify the expiration date
722
-			$share = $this->validateExpirationDateInternal($share);
723
-
724
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
725
-			$this->groupCreateChecks($share);
726
-
727
-			//Verify the expiration date
728
-			$share = $this->validateExpirationDateInternal($share);
729
-
730
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
731
-			$this->linkCreateChecks($share);
732
-			$this->setLinkParent($share);
733
-
734
-			/*
706
+        $storage = $share->getNode()->getStorage();
707
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
708
+            $parent = $share->getNode()->getParent();
709
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
710
+                $parent = $parent->getParent();
711
+            }
712
+            $share->setShareOwner($parent->getOwner()->getUID());
713
+        } else {
714
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
715
+        }
716
+
717
+        //Verify share type
718
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
719
+            $this->userCreateChecks($share);
720
+
721
+            //Verify the expiration date
722
+            $share = $this->validateExpirationDateInternal($share);
723
+
724
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
725
+            $this->groupCreateChecks($share);
726
+
727
+            //Verify the expiration date
728
+            $share = $this->validateExpirationDateInternal($share);
729
+
730
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
731
+            $this->linkCreateChecks($share);
732
+            $this->setLinkParent($share);
733
+
734
+            /*
735 735
 			 * For now ignore a set token.
736 736
 			 */
737
-			$share->setToken(
738
-				$this->secureRandom->generate(
739
-					\OC\Share\Constants::TOKEN_LENGTH,
740
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
741
-				)
742
-			);
743
-
744
-			//Verify the expiration date
745
-			$share = $this->validateExpirationDate($share);
746
-
747
-			//Verify the password
748
-			$this->verifyPassword($share->getPassword());
749
-
750
-			// If a password is set. Hash it!
751
-			if ($share->getPassword() !== null) {
752
-				$share->setPassword($this->hasher->hash($share->getPassword()));
753
-			}
754
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
-			$share->setToken(
756
-				$this->secureRandom->generate(
757
-					\OC\Share\Constants::TOKEN_LENGTH,
758
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
-				)
760
-			);
761
-		}
762
-
763
-		// Cannot share with the owner
764
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
765
-			$share->getSharedWith() === $share->getShareOwner()) {
766
-			throw new \InvalidArgumentException('Can’t share with the share owner');
767
-		}
768
-
769
-		// Generate the target
770
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
771
-		$target = \OC\Files\Filesystem::normalizePath($target);
772
-		$share->setTarget($target);
773
-
774
-		// Pre share event
775
-		$event = new GenericEvent($share);
776
-		$this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
777
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
778
-			throw new \Exception($event->getArgument('error'));
779
-		}
780
-
781
-		$oldShare = $share;
782
-		$provider = $this->factory->getProviderForType($share->getShareType());
783
-		$share = $provider->create($share);
784
-		//reuse the node we already have
785
-		$share->setNode($oldShare->getNode());
786
-
787
-		// Reset the target if it is null for the new share
788
-		if ($share->getTarget() === '') {
789
-			$share->setTarget($target);
790
-		}
791
-
792
-		// Post share event
793
-		$event = new GenericEvent($share);
794
-		$this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
795
-
796
-		$this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
797
-
798
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799
-			$mailSend = $share->getMailSend();
800
-			if($mailSend === true) {
801
-				$user = $this->userManager->get($share->getSharedWith());
802
-				if ($user !== null) {
803
-					$emailAddress = $user->getEMailAddress();
804
-					if ($emailAddress !== null && $emailAddress !== '') {
805
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
806
-						$l = $this->l10nFactory->get('lib', $userLang);
807
-						$this->sendMailNotification(
808
-							$l,
809
-							$share->getNode()->getName(),
810
-							$this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
811
-							$share->getSharedBy(),
812
-							$emailAddress,
813
-							$share->getExpirationDate()
814
-						);
815
-						$this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
816
-					} else {
817
-						$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
818
-					}
819
-				} else {
820
-					$this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
821
-				}
822
-			} else {
823
-				$this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
824
-			}
825
-		}
826
-
827
-		return $share;
828
-	}
829
-
830
-	/**
831
-	 * Send mail notifications
832
-	 *
833
-	 * This method will catch and log mail transmission errors
834
-	 *
835
-	 * @param IL10N $l Language of the recipient
836
-	 * @param string $filename file/folder name
837
-	 * @param string $link link to the file/folder
838
-	 * @param string $initiator user ID of share sender
839
-	 * @param string $shareWith email address of share receiver
840
-	 * @param \DateTime|null $expiration
841
-	 */
842
-	protected function sendMailNotification(IL10N $l,
843
-											$filename,
844
-											$link,
845
-											$initiator,
846
-											$shareWith,
847
-											\DateTime $expiration = null) {
848
-		$initiatorUser = $this->userManager->get($initiator);
849
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
850
-
851
-		$message = $this->mailer->createMessage();
852
-
853
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
854
-			'filename' => $filename,
855
-			'link' => $link,
856
-			'initiator' => $initiatorDisplayName,
857
-			'expiration' => $expiration,
858
-			'shareWith' => $shareWith,
859
-		]);
860
-
861
-		$emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
862
-		$emailTemplate->addHeader();
863
-		$emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
864
-		$text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865
-
866
-		$emailTemplate->addBodyText(
867
-			htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
868
-			$text
869
-		);
870
-		$emailTemplate->addBodyButton(
871
-			$l->t('Open »%s«', [$filename]),
872
-			$link
873
-		);
874
-
875
-		$message->setTo([$shareWith]);
876
-
877
-		// The "From" contains the sharers name
878
-		$instanceName = $this->defaults->getName();
879
-		$senderName = $l->t(
880
-			'%1$s via %2$s',
881
-			[
882
-				$initiatorDisplayName,
883
-				$instanceName
884
-			]
885
-		);
886
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
887
-
888
-		// The "Reply-To" is set to the sharer if an mail address is configured
889
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
890
-		$initiatorEmail = $initiatorUser->getEMailAddress();
891
-		if($initiatorEmail !== null) {
892
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
894
-		} else {
895
-			$emailTemplate->addFooter();
896
-		}
897
-
898
-		$message->useTemplate($emailTemplate);
899
-		try {
900
-			$failedRecipients = $this->mailer->send($message);
901
-			if(!empty($failedRecipients)) {
902
-				$this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
903
-				return;
904
-			}
905
-		} catch (\Exception $e) {
906
-			$this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
907
-		}
908
-	}
909
-
910
-	/**
911
-	 * Update a share
912
-	 *
913
-	 * @param \OCP\Share\IShare $share
914
-	 * @return \OCP\Share\IShare The share object
915
-	 * @throws \InvalidArgumentException
916
-	 */
917
-	public function updateShare(\OCP\Share\IShare $share) {
918
-		$expirationDateUpdated = false;
919
-
920
-		$this->canShare($share);
921
-
922
-		try {
923
-			$originalShare = $this->getShareById($share->getFullId());
924
-		} catch (\UnexpectedValueException $e) {
925
-			throw new \InvalidArgumentException('Share does not have a full id');
926
-		}
927
-
928
-		// We can't change the share type!
929
-		if ($share->getShareType() !== $originalShare->getShareType()) {
930
-			throw new \InvalidArgumentException('Can’t change share type');
931
-		}
932
-
933
-		// We can only change the recipient on user shares
934
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
935
-			$share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
936
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
937
-		}
938
-
939
-		// Cannot share with the owner
940
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
941
-			$share->getSharedWith() === $share->getShareOwner()) {
942
-			throw new \InvalidArgumentException('Can’t share with the share owner');
943
-		}
944
-
945
-		$this->generalCreateChecks($share);
946
-
947
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
948
-			$this->userCreateChecks($share);
949
-
950
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
951
-				//Verify the expiration date
952
-				$this->validateExpirationDate($share);
953
-				$expirationDateUpdated = true;
954
-			}
955
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
956
-			$this->groupCreateChecks($share);
957
-
958
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
959
-				//Verify the expiration date
960
-				$this->validateExpirationDate($share);
961
-				$expirationDateUpdated = true;
962
-			}
963
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
964
-			$this->linkCreateChecks($share);
965
-
966
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
967
-
968
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
969
-				//Verify the expiration date
970
-				$this->validateExpirationDate($share);
971
-				$expirationDateUpdated = true;
972
-			}
973
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
974
-			// The new password is not set again if it is the same as the old
975
-			// one, unless when switching from sending by Talk to sending by
976
-			// mail.
977
-			$plainTextPassword = $share->getPassword();
978
-			if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
979
-					!($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
980
-				$plainTextPassword = null;
981
-			}
982
-			if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
983
-				// If the same password was already sent by mail the recipient
984
-				// would already have access to the share without having to call
985
-				// the sharer to verify her identity
986
-				throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
987
-			}
988
-		}
989
-
990
-		$this->pathCreateChecks($share->getNode());
991
-
992
-		// Now update the share!
993
-		$provider = $this->factory->getProviderForType($share->getShareType());
994
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
995
-			$share = $provider->update($share, $plainTextPassword);
996
-		} else {
997
-			$share = $provider->update($share);
998
-		}
999
-
1000
-		if ($expirationDateUpdated === true) {
1001
-			\OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1002
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1003
-				'itemSource' => $share->getNode()->getId(),
1004
-				'date' => $share->getExpirationDate(),
1005
-				'uidOwner' => $share->getSharedBy(),
1006
-			]);
1007
-		}
1008
-
1009
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1010
-			\OC_Hook::emit(Share::class, 'post_update_password', [
1011
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1012
-				'itemSource' => $share->getNode()->getId(),
1013
-				'uidOwner' => $share->getSharedBy(),
1014
-				'token' => $share->getToken(),
1015
-				'disabled' => is_null($share->getPassword()),
1016
-			]);
1017
-		}
1018
-
1019
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
1020
-			if ($this->userManager->userExists($share->getShareOwner())) {
1021
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1022
-			} else {
1023
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1024
-			}
1025
-			\OC_Hook::emit(Share::class, 'post_update_permissions', [
1026
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1027
-				'itemSource' => $share->getNode()->getId(),
1028
-				'shareType' => $share->getShareType(),
1029
-				'shareWith' => $share->getSharedWith(),
1030
-				'uidOwner' => $share->getSharedBy(),
1031
-				'permissions' => $share->getPermissions(),
1032
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1033
-			]);
1034
-		}
1035
-
1036
-		return $share;
1037
-	}
1038
-
1039
-	/**
1040
-	 * Accept a share.
1041
-	 *
1042
-	 * @param IShare $share
1043
-	 * @param string $recipientId
1044
-	 * @return IShare The share object
1045
-	 * @throws \InvalidArgumentException
1046
-	 * @since 9.0.0
1047
-	 */
1048
-	public function acceptShare(IShare $share, string $recipientId): IShare {
1049
-		[$providerId, ] = $this->splitFullId($share->getFullId());
1050
-		$provider = $this->factory->getProvider($providerId);
1051
-
1052
-		if (!method_exists($provider, 'acceptShare')) {
1053
-			// TODO FIX ME
1054
-			throw new \InvalidArgumentException('Share provider does not support accepting');
1055
-		}
1056
-		$provider->acceptShare($share, $recipientId);
1057
-		$event = new GenericEvent($share);
1058
-		$this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1059
-
1060
-		return $share;
1061
-	}
1062
-
1063
-	/**
1064
-	 * Updates the password of the given share if it is not the same as the
1065
-	 * password of the original share.
1066
-	 *
1067
-	 * @param \OCP\Share\IShare $share the share to update its password.
1068
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
1069
-	 *        password with.
1070
-	 * @return boolean whether the password was updated or not.
1071
-	 */
1072
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
1073
-		// Password updated.
1074
-		if ($share->getPassword() !== $originalShare->getPassword()) {
1075
-			//Verify the password
1076
-			$this->verifyPassword($share->getPassword());
1077
-
1078
-			// If a password is set. Hash it!
1079
-			if ($share->getPassword() !== null) {
1080
-				$share->setPassword($this->hasher->hash($share->getPassword()));
1081
-
1082
-				return true;
1083
-			}
1084
-		}
1085
-
1086
-		return false;
1087
-	}
1088
-
1089
-	/**
1090
-	 * Delete all the children of this share
1091
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1092
-	 *
1093
-	 * @param \OCP\Share\IShare $share
1094
-	 * @return \OCP\Share\IShare[] List of deleted shares
1095
-	 */
1096
-	protected function deleteChildren(\OCP\Share\IShare $share) {
1097
-		$deletedShares = [];
1098
-
1099
-		$provider = $this->factory->getProviderForType($share->getShareType());
1100
-
1101
-		foreach ($provider->getChildren($share) as $child) {
1102
-			$deletedChildren = $this->deleteChildren($child);
1103
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
1104
-
1105
-			$provider->delete($child);
1106
-			$deletedShares[] = $child;
1107
-		}
1108
-
1109
-		return $deletedShares;
1110
-	}
1111
-
1112
-	/**
1113
-	 * Delete a share
1114
-	 *
1115
-	 * @param \OCP\Share\IShare $share
1116
-	 * @throws ShareNotFound
1117
-	 * @throws \InvalidArgumentException
1118
-	 */
1119
-	public function deleteShare(\OCP\Share\IShare $share) {
1120
-
1121
-		try {
1122
-			$share->getFullId();
1123
-		} catch (\UnexpectedValueException $e) {
1124
-			throw new \InvalidArgumentException('Share does not have a full id');
1125
-		}
1126
-
1127
-		$event = new GenericEvent($share);
1128
-		$this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1129
-
1130
-		// Get all children and delete them as well
1131
-		$deletedShares = $this->deleteChildren($share);
1132
-
1133
-		// Do the actual delete
1134
-		$provider = $this->factory->getProviderForType($share->getShareType());
1135
-		$provider->delete($share);
1136
-
1137
-		// All the deleted shares caused by this delete
1138
-		$deletedShares[] = $share;
1139
-
1140
-		// Emit post hook
1141
-		$event->setArgument('deletedShares', $deletedShares);
1142
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1143
-	}
1144
-
1145
-
1146
-	/**
1147
-	 * Unshare a file as the recipient.
1148
-	 * This can be different from a regular delete for example when one of
1149
-	 * the users in a groups deletes that share. But the provider should
1150
-	 * handle this.
1151
-	 *
1152
-	 * @param \OCP\Share\IShare $share
1153
-	 * @param string $recipientId
1154
-	 */
1155
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1157
-		$provider = $this->factory->getProvider($providerId);
1158
-
1159
-		$provider->deleteFromSelf($share, $recipientId);
1160
-		$event = new GenericEvent($share);
1161
-		$this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1162
-	}
1163
-
1164
-	public function restoreShare(IShare $share, string $recipientId): IShare {
1165
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1166
-		$provider = $this->factory->getProvider($providerId);
1167
-
1168
-		return $provider->restore($share, $recipientId);
1169
-	}
1170
-
1171
-	/**
1172
-	 * @inheritdoc
1173
-	 */
1174
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1175
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1176
-			throw new \InvalidArgumentException('Can’t change target of link share');
1177
-		}
1178
-
1179
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1180
-			throw new \InvalidArgumentException('Invalid recipient');
1181
-		}
1182
-
1183
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
1185
-			if (is_null($sharedWith)) {
1186
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1187
-			}
1188
-			$recipient = $this->userManager->get($recipientId);
1189
-			if (!$sharedWith->inGroup($recipient)) {
1190
-				throw new \InvalidArgumentException('Invalid recipient');
1191
-			}
1192
-		}
1193
-
1194
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1195
-		$provider = $this->factory->getProvider($providerId);
1196
-
1197
-		$provider->move($share, $recipientId);
1198
-	}
1199
-
1200
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201
-		$providers = $this->factory->getAllProviders();
1202
-
1203
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205
-			foreach ($newShares as $fid => $data) {
1206
-				if (!isset($shares[$fid])) {
1207
-					$shares[$fid] = [];
1208
-				}
1209
-
1210
-				$shares[$fid] = array_merge($shares[$fid], $data);
1211
-			}
1212
-			return $shares;
1213
-		}, []);
1214
-	}
1215
-
1216
-	/**
1217
-	 * @inheritdoc
1218
-	 */
1219
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1220
-		if ($path !== null &&
1221
-				!($path instanceof \OCP\Files\File) &&
1222
-				!($path instanceof \OCP\Files\Folder)) {
1223
-			throw new \InvalidArgumentException('invalid path');
1224
-		}
1225
-
1226
-		try {
1227
-			$provider = $this->factory->getProviderForType($shareType);
1228
-		} catch (ProviderException $e) {
1229
-			return [];
1230
-		}
1231
-
1232
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1233
-
1234
-		/*
737
+            $share->setToken(
738
+                $this->secureRandom->generate(
739
+                    \OC\Share\Constants::TOKEN_LENGTH,
740
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
741
+                )
742
+            );
743
+
744
+            //Verify the expiration date
745
+            $share = $this->validateExpirationDate($share);
746
+
747
+            //Verify the password
748
+            $this->verifyPassword($share->getPassword());
749
+
750
+            // If a password is set. Hash it!
751
+            if ($share->getPassword() !== null) {
752
+                $share->setPassword($this->hasher->hash($share->getPassword()));
753
+            }
754
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
+            $share->setToken(
756
+                $this->secureRandom->generate(
757
+                    \OC\Share\Constants::TOKEN_LENGTH,
758
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
759
+                )
760
+            );
761
+        }
762
+
763
+        // Cannot share with the owner
764
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
765
+            $share->getSharedWith() === $share->getShareOwner()) {
766
+            throw new \InvalidArgumentException('Can’t share with the share owner');
767
+        }
768
+
769
+        // Generate the target
770
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
771
+        $target = \OC\Files\Filesystem::normalizePath($target);
772
+        $share->setTarget($target);
773
+
774
+        // Pre share event
775
+        $event = new GenericEvent($share);
776
+        $this->legacyDispatcher->dispatch('OCP\Share::preShare', $event);
777
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
778
+            throw new \Exception($event->getArgument('error'));
779
+        }
780
+
781
+        $oldShare = $share;
782
+        $provider = $this->factory->getProviderForType($share->getShareType());
783
+        $share = $provider->create($share);
784
+        //reuse the node we already have
785
+        $share->setNode($oldShare->getNode());
786
+
787
+        // Reset the target if it is null for the new share
788
+        if ($share->getTarget() === '') {
789
+            $share->setTarget($target);
790
+        }
791
+
792
+        // Post share event
793
+        $event = new GenericEvent($share);
794
+        $this->legacyDispatcher->dispatch('OCP\Share::postShare', $event);
795
+
796
+        $this->dispatcher->dispatchTyped(new Share\Events\ShareCreatedEvent($share));
797
+
798
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
799
+            $mailSend = $share->getMailSend();
800
+            if($mailSend === true) {
801
+                $user = $this->userManager->get($share->getSharedWith());
802
+                if ($user !== null) {
803
+                    $emailAddress = $user->getEMailAddress();
804
+                    if ($emailAddress !== null && $emailAddress !== '') {
805
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
806
+                        $l = $this->l10nFactory->get('lib', $userLang);
807
+                        $this->sendMailNotification(
808
+                            $l,
809
+                            $share->getNode()->getName(),
810
+                            $this->urlGenerator->linkToRouteAbsolute('files_sharing.Accept.accept', ['shareId' => $share->getFullId()]),
811
+                            $share->getSharedBy(),
812
+                            $emailAddress,
813
+                            $share->getExpirationDate()
814
+                        );
815
+                        $this->logger->debug('Sent share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
816
+                    } else {
817
+                        $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
818
+                    }
819
+                } else {
820
+                    $this->logger->debug('Share notification not sent to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
821
+                }
822
+            } else {
823
+                $this->logger->debug('Share notification not sent because mailsend is false.', ['app' => 'share']);
824
+            }
825
+        }
826
+
827
+        return $share;
828
+    }
829
+
830
+    /**
831
+     * Send mail notifications
832
+     *
833
+     * This method will catch and log mail transmission errors
834
+     *
835
+     * @param IL10N $l Language of the recipient
836
+     * @param string $filename file/folder name
837
+     * @param string $link link to the file/folder
838
+     * @param string $initiator user ID of share sender
839
+     * @param string $shareWith email address of share receiver
840
+     * @param \DateTime|null $expiration
841
+     */
842
+    protected function sendMailNotification(IL10N $l,
843
+                                            $filename,
844
+                                            $link,
845
+                                            $initiator,
846
+                                            $shareWith,
847
+                                            \DateTime $expiration = null) {
848
+        $initiatorUser = $this->userManager->get($initiator);
849
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
850
+
851
+        $message = $this->mailer->createMessage();
852
+
853
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
854
+            'filename' => $filename,
855
+            'link' => $link,
856
+            'initiator' => $initiatorDisplayName,
857
+            'expiration' => $expiration,
858
+            'shareWith' => $shareWith,
859
+        ]);
860
+
861
+        $emailTemplate->setSubject($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]));
862
+        $emailTemplate->addHeader();
863
+        $emailTemplate->addHeading($l->t('%1$s shared »%2$s« with you', [$initiatorDisplayName, $filename]), false);
864
+        $text = $l->t('%1$s shared »%2$s« with you.', [$initiatorDisplayName, $filename]);
865
+
866
+        $emailTemplate->addBodyText(
867
+            htmlspecialchars($text . ' ' . $l->t('Click the button below to open it.')),
868
+            $text
869
+        );
870
+        $emailTemplate->addBodyButton(
871
+            $l->t('Open »%s«', [$filename]),
872
+            $link
873
+        );
874
+
875
+        $message->setTo([$shareWith]);
876
+
877
+        // The "From" contains the sharers name
878
+        $instanceName = $this->defaults->getName();
879
+        $senderName = $l->t(
880
+            '%1$s via %2$s',
881
+            [
882
+                $initiatorDisplayName,
883
+                $instanceName
884
+            ]
885
+        );
886
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
887
+
888
+        // The "Reply-To" is set to the sharer if an mail address is configured
889
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
890
+        $initiatorEmail = $initiatorUser->getEMailAddress();
891
+        if($initiatorEmail !== null) {
892
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
893
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
894
+        } else {
895
+            $emailTemplate->addFooter();
896
+        }
897
+
898
+        $message->useTemplate($emailTemplate);
899
+        try {
900
+            $failedRecipients = $this->mailer->send($message);
901
+            if(!empty($failedRecipients)) {
902
+                $this->logger->error('Share notification mail could not be sent to: ' . implode(', ', $failedRecipients));
903
+                return;
904
+            }
905
+        } catch (\Exception $e) {
906
+            $this->logger->logException($e, ['message' => 'Share notification mail could not be sent']);
907
+        }
908
+    }
909
+
910
+    /**
911
+     * Update a share
912
+     *
913
+     * @param \OCP\Share\IShare $share
914
+     * @return \OCP\Share\IShare The share object
915
+     * @throws \InvalidArgumentException
916
+     */
917
+    public function updateShare(\OCP\Share\IShare $share) {
918
+        $expirationDateUpdated = false;
919
+
920
+        $this->canShare($share);
921
+
922
+        try {
923
+            $originalShare = $this->getShareById($share->getFullId());
924
+        } catch (\UnexpectedValueException $e) {
925
+            throw new \InvalidArgumentException('Share does not have a full id');
926
+        }
927
+
928
+        // We can't change the share type!
929
+        if ($share->getShareType() !== $originalShare->getShareType()) {
930
+            throw new \InvalidArgumentException('Can’t change share type');
931
+        }
932
+
933
+        // We can only change the recipient on user shares
934
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
935
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
936
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
937
+        }
938
+
939
+        // Cannot share with the owner
940
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
941
+            $share->getSharedWith() === $share->getShareOwner()) {
942
+            throw new \InvalidArgumentException('Can’t share with the share owner');
943
+        }
944
+
945
+        $this->generalCreateChecks($share);
946
+
947
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
948
+            $this->userCreateChecks($share);
949
+
950
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
951
+                //Verify the expiration date
952
+                $this->validateExpirationDate($share);
953
+                $expirationDateUpdated = true;
954
+            }
955
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
956
+            $this->groupCreateChecks($share);
957
+
958
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
959
+                //Verify the expiration date
960
+                $this->validateExpirationDate($share);
961
+                $expirationDateUpdated = true;
962
+            }
963
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
964
+            $this->linkCreateChecks($share);
965
+
966
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
967
+
968
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
969
+                //Verify the expiration date
970
+                $this->validateExpirationDate($share);
971
+                $expirationDateUpdated = true;
972
+            }
973
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
974
+            // The new password is not set again if it is the same as the old
975
+            // one, unless when switching from sending by Talk to sending by
976
+            // mail.
977
+            $plainTextPassword = $share->getPassword();
978
+            if (!empty($plainTextPassword) && !$this->updateSharePasswordIfNeeded($share, $originalShare) &&
979
+                    !($originalShare->getSendPasswordByTalk() && !$share->getSendPasswordByTalk())) {
980
+                $plainTextPassword = null;
981
+            }
982
+            if (empty($plainTextPassword) && !$originalShare->getSendPasswordByTalk() && $share->getSendPasswordByTalk()) {
983
+                // If the same password was already sent by mail the recipient
984
+                // would already have access to the share without having to call
985
+                // the sharer to verify her identity
986
+                throw new \InvalidArgumentException('Can’t enable sending the password by Talk without setting a new password');
987
+            }
988
+        }
989
+
990
+        $this->pathCreateChecks($share->getNode());
991
+
992
+        // Now update the share!
993
+        $provider = $this->factory->getProviderForType($share->getShareType());
994
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
995
+            $share = $provider->update($share, $plainTextPassword);
996
+        } else {
997
+            $share = $provider->update($share);
998
+        }
999
+
1000
+        if ($expirationDateUpdated === true) {
1001
+            \OC_Hook::emit(Share::class, 'post_set_expiration_date', [
1002
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1003
+                'itemSource' => $share->getNode()->getId(),
1004
+                'date' => $share->getExpirationDate(),
1005
+                'uidOwner' => $share->getSharedBy(),
1006
+            ]);
1007
+        }
1008
+
1009
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1010
+            \OC_Hook::emit(Share::class, 'post_update_password', [
1011
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1012
+                'itemSource' => $share->getNode()->getId(),
1013
+                'uidOwner' => $share->getSharedBy(),
1014
+                'token' => $share->getToken(),
1015
+                'disabled' => is_null($share->getPassword()),
1016
+            ]);
1017
+        }
1018
+
1019
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
1020
+            if ($this->userManager->userExists($share->getShareOwner())) {
1021
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
1022
+            } else {
1023
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
1024
+            }
1025
+            \OC_Hook::emit(Share::class, 'post_update_permissions', [
1026
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
1027
+                'itemSource' => $share->getNode()->getId(),
1028
+                'shareType' => $share->getShareType(),
1029
+                'shareWith' => $share->getSharedWith(),
1030
+                'uidOwner' => $share->getSharedBy(),
1031
+                'permissions' => $share->getPermissions(),
1032
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
1033
+            ]);
1034
+        }
1035
+
1036
+        return $share;
1037
+    }
1038
+
1039
+    /**
1040
+     * Accept a share.
1041
+     *
1042
+     * @param IShare $share
1043
+     * @param string $recipientId
1044
+     * @return IShare The share object
1045
+     * @throws \InvalidArgumentException
1046
+     * @since 9.0.0
1047
+     */
1048
+    public function acceptShare(IShare $share, string $recipientId): IShare {
1049
+        [$providerId, ] = $this->splitFullId($share->getFullId());
1050
+        $provider = $this->factory->getProvider($providerId);
1051
+
1052
+        if (!method_exists($provider, 'acceptShare')) {
1053
+            // TODO FIX ME
1054
+            throw new \InvalidArgumentException('Share provider does not support accepting');
1055
+        }
1056
+        $provider->acceptShare($share, $recipientId);
1057
+        $event = new GenericEvent($share);
1058
+        $this->legacyDispatcher->dispatch('OCP\Share::postAcceptShare', $event);
1059
+
1060
+        return $share;
1061
+    }
1062
+
1063
+    /**
1064
+     * Updates the password of the given share if it is not the same as the
1065
+     * password of the original share.
1066
+     *
1067
+     * @param \OCP\Share\IShare $share the share to update its password.
1068
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
1069
+     *        password with.
1070
+     * @return boolean whether the password was updated or not.
1071
+     */
1072
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
1073
+        // Password updated.
1074
+        if ($share->getPassword() !== $originalShare->getPassword()) {
1075
+            //Verify the password
1076
+            $this->verifyPassword($share->getPassword());
1077
+
1078
+            // If a password is set. Hash it!
1079
+            if ($share->getPassword() !== null) {
1080
+                $share->setPassword($this->hasher->hash($share->getPassword()));
1081
+
1082
+                return true;
1083
+            }
1084
+        }
1085
+
1086
+        return false;
1087
+    }
1088
+
1089
+    /**
1090
+     * Delete all the children of this share
1091
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
1092
+     *
1093
+     * @param \OCP\Share\IShare $share
1094
+     * @return \OCP\Share\IShare[] List of deleted shares
1095
+     */
1096
+    protected function deleteChildren(\OCP\Share\IShare $share) {
1097
+        $deletedShares = [];
1098
+
1099
+        $provider = $this->factory->getProviderForType($share->getShareType());
1100
+
1101
+        foreach ($provider->getChildren($share) as $child) {
1102
+            $deletedChildren = $this->deleteChildren($child);
1103
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
1104
+
1105
+            $provider->delete($child);
1106
+            $deletedShares[] = $child;
1107
+        }
1108
+
1109
+        return $deletedShares;
1110
+    }
1111
+
1112
+    /**
1113
+     * Delete a share
1114
+     *
1115
+     * @param \OCP\Share\IShare $share
1116
+     * @throws ShareNotFound
1117
+     * @throws \InvalidArgumentException
1118
+     */
1119
+    public function deleteShare(\OCP\Share\IShare $share) {
1120
+
1121
+        try {
1122
+            $share->getFullId();
1123
+        } catch (\UnexpectedValueException $e) {
1124
+            throw new \InvalidArgumentException('Share does not have a full id');
1125
+        }
1126
+
1127
+        $event = new GenericEvent($share);
1128
+        $this->legacyDispatcher->dispatch('OCP\Share::preUnshare', $event);
1129
+
1130
+        // Get all children and delete them as well
1131
+        $deletedShares = $this->deleteChildren($share);
1132
+
1133
+        // Do the actual delete
1134
+        $provider = $this->factory->getProviderForType($share->getShareType());
1135
+        $provider->delete($share);
1136
+
1137
+        // All the deleted shares caused by this delete
1138
+        $deletedShares[] = $share;
1139
+
1140
+        // Emit post hook
1141
+        $event->setArgument('deletedShares', $deletedShares);
1142
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshare', $event);
1143
+    }
1144
+
1145
+
1146
+    /**
1147
+     * Unshare a file as the recipient.
1148
+     * This can be different from a regular delete for example when one of
1149
+     * the users in a groups deletes that share. But the provider should
1150
+     * handle this.
1151
+     *
1152
+     * @param \OCP\Share\IShare $share
1153
+     * @param string $recipientId
1154
+     */
1155
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
1156
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1157
+        $provider = $this->factory->getProvider($providerId);
1158
+
1159
+        $provider->deleteFromSelf($share, $recipientId);
1160
+        $event = new GenericEvent($share);
1161
+        $this->legacyDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
1162
+    }
1163
+
1164
+    public function restoreShare(IShare $share, string $recipientId): IShare {
1165
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1166
+        $provider = $this->factory->getProvider($providerId);
1167
+
1168
+        return $provider->restore($share, $recipientId);
1169
+    }
1170
+
1171
+    /**
1172
+     * @inheritdoc
1173
+     */
1174
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
1175
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1176
+            throw new \InvalidArgumentException('Can’t change target of link share');
1177
+        }
1178
+
1179
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
1180
+            throw new \InvalidArgumentException('Invalid recipient');
1181
+        }
1182
+
1183
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1184
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
1185
+            if (is_null($sharedWith)) {
1186
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
1187
+            }
1188
+            $recipient = $this->userManager->get($recipientId);
1189
+            if (!$sharedWith->inGroup($recipient)) {
1190
+                throw new \InvalidArgumentException('Invalid recipient');
1191
+            }
1192
+        }
1193
+
1194
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1195
+        $provider = $this->factory->getProvider($providerId);
1196
+
1197
+        $provider->move($share, $recipientId);
1198
+    }
1199
+
1200
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1201
+        $providers = $this->factory->getAllProviders();
1202
+
1203
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1204
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1205
+            foreach ($newShares as $fid => $data) {
1206
+                if (!isset($shares[$fid])) {
1207
+                    $shares[$fid] = [];
1208
+                }
1209
+
1210
+                $shares[$fid] = array_merge($shares[$fid], $data);
1211
+            }
1212
+            return $shares;
1213
+        }, []);
1214
+    }
1215
+
1216
+    /**
1217
+     * @inheritdoc
1218
+     */
1219
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1220
+        if ($path !== null &&
1221
+                !($path instanceof \OCP\Files\File) &&
1222
+                !($path instanceof \OCP\Files\Folder)) {
1223
+            throw new \InvalidArgumentException('invalid path');
1224
+        }
1225
+
1226
+        try {
1227
+            $provider = $this->factory->getProviderForType($shareType);
1228
+        } catch (ProviderException $e) {
1229
+            return [];
1230
+        }
1231
+
1232
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1233
+
1234
+        /*
1235 1235
 		 * Work around so we don't return expired shares but still follow
1236 1236
 		 * proper pagination.
1237 1237
 		 */
1238 1238
 
1239
-		$shares2 = [];
1240
-
1241
-		while(true) {
1242
-			$added = 0;
1243
-			foreach ($shares as $share) {
1244
-
1245
-				try {
1246
-					$this->checkExpireDate($share);
1247
-				} catch (ShareNotFound $e) {
1248
-					//Ignore since this basically means the share is deleted
1249
-					continue;
1250
-				}
1251
-
1252
-				$added++;
1253
-				$shares2[] = $share;
1254
-
1255
-				if (count($shares2) === $limit) {
1256
-					break;
1257
-				}
1258
-			}
1259
-
1260
-			// If we did not fetch more shares than the limit then there are no more shares
1261
-			if (count($shares) < $limit) {
1262
-				break;
1263
-			}
1264
-
1265
-			if (count($shares2) === $limit) {
1266
-				break;
1267
-			}
1268
-
1269
-			// If there was no limit on the select we are done
1270
-			if ($limit === -1) {
1271
-				break;
1272
-			}
1273
-
1274
-			$offset += $added;
1275
-
1276
-			// Fetch again $limit shares
1277
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1278
-
1279
-			// No more shares means we are done
1280
-			if (empty($shares)) {
1281
-				break;
1282
-			}
1283
-		}
1284
-
1285
-		$shares = $shares2;
1286
-
1287
-		return $shares;
1288
-	}
1289
-
1290
-	/**
1291
-	 * @inheritdoc
1292
-	 */
1293
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1294
-		try {
1295
-			$provider = $this->factory->getProviderForType($shareType);
1296
-		} catch (ProviderException $e) {
1297
-			return [];
1298
-		}
1299
-
1300
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1301
-
1302
-		// remove all shares which are already expired
1303
-		foreach ($shares as $key => $share) {
1304
-			try {
1305
-				$this->checkExpireDate($share);
1306
-			} catch (ShareNotFound $e) {
1307
-				unset($shares[$key]);
1308
-			}
1309
-		}
1310
-
1311
-		return $shares;
1312
-	}
1313
-
1314
-	/**
1315
-	 * @inheritdoc
1316
-	 */
1317
-	public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1318
-		$shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319
-
1320
-		// Only get deleted shares
1321
-		$shares = array_filter($shares, function(IShare $share) {
1322
-			return $share->getPermissions() === 0;
1323
-		});
1324
-
1325
-		// Only get shares where the owner still exists
1326
-		$shares = array_filter($shares, function (IShare $share) {
1327
-			return $this->userManager->userExists($share->getShareOwner());
1328
-		});
1329
-
1330
-		return $shares;
1331
-	}
1332
-
1333
-	/**
1334
-	 * @inheritdoc
1335
-	 */
1336
-	public function getShareById($id, $recipient = null) {
1337
-		if ($id === null) {
1338
-			throw new ShareNotFound();
1339
-		}
1340
-
1341
-		list($providerId, $id) = $this->splitFullId($id);
1342
-
1343
-		try {
1344
-			$provider = $this->factory->getProvider($providerId);
1345
-		} catch (ProviderException $e) {
1346
-			throw new ShareNotFound();
1347
-		}
1348
-
1349
-		$share = $provider->getShareById($id, $recipient);
1350
-
1351
-		$this->checkExpireDate($share);
1352
-
1353
-		return $share;
1354
-	}
1355
-
1356
-	/**
1357
-	 * Get all the shares for a given path
1358
-	 *
1359
-	 * @param \OCP\Files\Node $path
1360
-	 * @param int $page
1361
-	 * @param int $perPage
1362
-	 *
1363
-	 * @return Share[]
1364
-	 */
1365
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1366
-		return [];
1367
-	}
1368
-
1369
-	/**
1370
-	 * Get the share by token possible with password
1371
-	 *
1372
-	 * @param string $token
1373
-	 * @return Share
1374
-	 *
1375
-	 * @throws ShareNotFound
1376
-	 */
1377
-	public function getShareByToken($token) {
1378
-		// tokens can't be valid local user names
1379
-		if ($this->userManager->userExists($token)) {
1380
-			throw new ShareNotFound();
1381
-		}
1382
-		$share = null;
1383
-		try {
1384
-			if($this->shareApiAllowLinks()) {
1385
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386
-				$share = $provider->getShareByToken($token);
1387
-			}
1388
-		} catch (ProviderException $e) {
1389
-		} catch (ShareNotFound $e) {
1390
-		}
1391
-
1392
-
1393
-		// If it is not a link share try to fetch a federated share by token
1394
-		if ($share === null) {
1395
-			try {
1396
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1397
-				$share = $provider->getShareByToken($token);
1398
-			} catch (ProviderException $e) {
1399
-			} catch (ShareNotFound $e) {
1400
-			}
1401
-		}
1402
-
1403
-		// If it is not a link share try to fetch a mail share by token
1404
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1405
-			try {
1406
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1407
-				$share = $provider->getShareByToken($token);
1408
-			} catch (ProviderException $e) {
1409
-			} catch (ShareNotFound $e) {
1410
-			}
1411
-		}
1412
-
1413
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1414
-			try {
1415
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1416
-				$share = $provider->getShareByToken($token);
1417
-			} catch (ProviderException $e) {
1418
-			} catch (ShareNotFound $e) {
1419
-			}
1420
-		}
1421
-
1422
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1423
-			try {
1424
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1425
-				$share = $provider->getShareByToken($token);
1426
-			} catch (ProviderException $e) {
1427
-			} catch (ShareNotFound $e) {
1428
-			}
1429
-		}
1430
-
1431
-		if ($share === null) {
1432
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1433
-		}
1434
-
1435
-		$this->checkExpireDate($share);
1436
-
1437
-		/*
1239
+        $shares2 = [];
1240
+
1241
+        while(true) {
1242
+            $added = 0;
1243
+            foreach ($shares as $share) {
1244
+
1245
+                try {
1246
+                    $this->checkExpireDate($share);
1247
+                } catch (ShareNotFound $e) {
1248
+                    //Ignore since this basically means the share is deleted
1249
+                    continue;
1250
+                }
1251
+
1252
+                $added++;
1253
+                $shares2[] = $share;
1254
+
1255
+                if (count($shares2) === $limit) {
1256
+                    break;
1257
+                }
1258
+            }
1259
+
1260
+            // If we did not fetch more shares than the limit then there are no more shares
1261
+            if (count($shares) < $limit) {
1262
+                break;
1263
+            }
1264
+
1265
+            if (count($shares2) === $limit) {
1266
+                break;
1267
+            }
1268
+
1269
+            // If there was no limit on the select we are done
1270
+            if ($limit === -1) {
1271
+                break;
1272
+            }
1273
+
1274
+            $offset += $added;
1275
+
1276
+            // Fetch again $limit shares
1277
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1278
+
1279
+            // No more shares means we are done
1280
+            if (empty($shares)) {
1281
+                break;
1282
+            }
1283
+        }
1284
+
1285
+        $shares = $shares2;
1286
+
1287
+        return $shares;
1288
+    }
1289
+
1290
+    /**
1291
+     * @inheritdoc
1292
+     */
1293
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1294
+        try {
1295
+            $provider = $this->factory->getProviderForType($shareType);
1296
+        } catch (ProviderException $e) {
1297
+            return [];
1298
+        }
1299
+
1300
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1301
+
1302
+        // remove all shares which are already expired
1303
+        foreach ($shares as $key => $share) {
1304
+            try {
1305
+                $this->checkExpireDate($share);
1306
+            } catch (ShareNotFound $e) {
1307
+                unset($shares[$key]);
1308
+            }
1309
+        }
1310
+
1311
+        return $shares;
1312
+    }
1313
+
1314
+    /**
1315
+     * @inheritdoc
1316
+     */
1317
+    public function getDeletedSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1318
+        $shares = $this->getSharedWith($userId, $shareType, $node, $limit, $offset);
1319
+
1320
+        // Only get deleted shares
1321
+        $shares = array_filter($shares, function(IShare $share) {
1322
+            return $share->getPermissions() === 0;
1323
+        });
1324
+
1325
+        // Only get shares where the owner still exists
1326
+        $shares = array_filter($shares, function (IShare $share) {
1327
+            return $this->userManager->userExists($share->getShareOwner());
1328
+        });
1329
+
1330
+        return $shares;
1331
+    }
1332
+
1333
+    /**
1334
+     * @inheritdoc
1335
+     */
1336
+    public function getShareById($id, $recipient = null) {
1337
+        if ($id === null) {
1338
+            throw new ShareNotFound();
1339
+        }
1340
+
1341
+        list($providerId, $id) = $this->splitFullId($id);
1342
+
1343
+        try {
1344
+            $provider = $this->factory->getProvider($providerId);
1345
+        } catch (ProviderException $e) {
1346
+            throw new ShareNotFound();
1347
+        }
1348
+
1349
+        $share = $provider->getShareById($id, $recipient);
1350
+
1351
+        $this->checkExpireDate($share);
1352
+
1353
+        return $share;
1354
+    }
1355
+
1356
+    /**
1357
+     * Get all the shares for a given path
1358
+     *
1359
+     * @param \OCP\Files\Node $path
1360
+     * @param int $page
1361
+     * @param int $perPage
1362
+     *
1363
+     * @return Share[]
1364
+     */
1365
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1366
+        return [];
1367
+    }
1368
+
1369
+    /**
1370
+     * Get the share by token possible with password
1371
+     *
1372
+     * @param string $token
1373
+     * @return Share
1374
+     *
1375
+     * @throws ShareNotFound
1376
+     */
1377
+    public function getShareByToken($token) {
1378
+        // tokens can't be valid local user names
1379
+        if ($this->userManager->userExists($token)) {
1380
+            throw new ShareNotFound();
1381
+        }
1382
+        $share = null;
1383
+        try {
1384
+            if($this->shareApiAllowLinks()) {
1385
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1386
+                $share = $provider->getShareByToken($token);
1387
+            }
1388
+        } catch (ProviderException $e) {
1389
+        } catch (ShareNotFound $e) {
1390
+        }
1391
+
1392
+
1393
+        // If it is not a link share try to fetch a federated share by token
1394
+        if ($share === null) {
1395
+            try {
1396
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1397
+                $share = $provider->getShareByToken($token);
1398
+            } catch (ProviderException $e) {
1399
+            } catch (ShareNotFound $e) {
1400
+            }
1401
+        }
1402
+
1403
+        // If it is not a link share try to fetch a mail share by token
1404
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1405
+            try {
1406
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1407
+                $share = $provider->getShareByToken($token);
1408
+            } catch (ProviderException $e) {
1409
+            } catch (ShareNotFound $e) {
1410
+            }
1411
+        }
1412
+
1413
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1414
+            try {
1415
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1416
+                $share = $provider->getShareByToken($token);
1417
+            } catch (ProviderException $e) {
1418
+            } catch (ShareNotFound $e) {
1419
+            }
1420
+        }
1421
+
1422
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_ROOM)) {
1423
+            try {
1424
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_ROOM);
1425
+                $share = $provider->getShareByToken($token);
1426
+            } catch (ProviderException $e) {
1427
+            } catch (ShareNotFound $e) {
1428
+            }
1429
+        }
1430
+
1431
+        if ($share === null) {
1432
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1433
+        }
1434
+
1435
+        $this->checkExpireDate($share);
1436
+
1437
+        /*
1438 1438
 		 * Reduce the permissions for link shares if public upload is not enabled
1439 1439
 		 */
1440
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1441
-			!$this->shareApiLinkAllowPublicUpload()) {
1442
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1443
-		}
1444
-
1445
-		return $share;
1446
-	}
1447
-
1448
-	protected function checkExpireDate($share) {
1449
-		if ($share->isExpired()) {
1450
-			$this->deleteShare($share);
1451
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1452
-		}
1453
-
1454
-	}
1455
-
1456
-	/**
1457
-	 * Verify the password of a public share
1458
-	 *
1459
-	 * @param \OCP\Share\IShare $share
1460
-	 * @param string $password
1461
-	 * @return bool
1462
-	 */
1463
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1464
-		$passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1465
-							 || $share->getShareType() !== IShare::TYPE_EMAIL
1466
-							 || $share->getShareType() !== IShare::TYPE_CIRCLE;
1467
-		if (!$passwordProtected) {
1468
-			//TODO maybe exception?
1469
-			return false;
1470
-		}
1471
-
1472
-		if ($password === null || $share->getPassword() === null) {
1473
-			return false;
1474
-		}
1475
-
1476
-		$newHash = '';
1477
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1478
-			return false;
1479
-		}
1480
-
1481
-		if (!empty($newHash)) {
1482
-			$share->setPassword($newHash);
1483
-			$provider = $this->factory->getProviderForType($share->getShareType());
1484
-			$provider->update($share);
1485
-		}
1486
-
1487
-		return true;
1488
-	}
1489
-
1490
-	/**
1491
-	 * @inheritdoc
1492
-	 */
1493
-	public function userDeleted($uid) {
1494
-		$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];
1495
-
1496
-		foreach ($types as $type) {
1497
-			try {
1498
-				$provider = $this->factory->getProviderForType($type);
1499
-			} catch (ProviderException $e) {
1500
-				continue;
1501
-			}
1502
-			$provider->userDeleted($uid, $type);
1503
-		}
1504
-	}
1505
-
1506
-	/**
1507
-	 * @inheritdoc
1508
-	 */
1509
-	public function groupDeleted($gid) {
1510
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1511
-		$provider->groupDeleted($gid);
1512
-	}
1513
-
1514
-	/**
1515
-	 * @inheritdoc
1516
-	 */
1517
-	public function userDeletedFromGroup($uid, $gid) {
1518
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1519
-		$provider->userDeletedFromGroup($uid, $gid);
1520
-	}
1521
-
1522
-	/**
1523
-	 * Get access list to a path. This means
1524
-	 * all the users that can access a given path.
1525
-	 *
1526
-	 * Consider:
1527
-	 * -root
1528
-	 * |-folder1 (23)
1529
-	 *  |-folder2 (32)
1530
-	 *   |-fileA (42)
1531
-	 *
1532
-	 * fileA is shared with user1 and user1@server1
1533
-	 * folder2 is shared with group2 (user4 is a member of group2)
1534
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1535
-	 *
1536
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1537
-	 * [
1538
-	 *  users  => [
1539
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1540
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1541
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1542
-	 *  ],
1543
-	 *  remote => [
1544
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1545
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1546
-	 *  ],
1547
-	 *  public => bool
1548
-	 *  mail => bool
1549
-	 * ]
1550
-	 *
1551
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1552
-	 * [
1553
-	 *  users  => ['user1', 'user2', 'user4'],
1554
-	 *  remote => bool,
1555
-	 *  public => bool
1556
-	 *  mail => bool
1557
-	 * ]
1558
-	 *
1559
-	 * This is required for encryption/activity
1560
-	 *
1561
-	 * @param \OCP\Files\Node $path
1562
-	 * @param bool $recursive Should we check all parent folders as well
1563
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1564
-	 * @return array
1565
-	 */
1566
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1567
-		$owner = $path->getOwner();
1568
-
1569
-		if ($owner === null) {
1570
-			return [];
1571
-		}
1572
-
1573
-		$owner = $owner->getUID();
1574
-
1575
-		if ($currentAccess) {
1576
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1577
-		} else {
1578
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1579
-		}
1580
-		if (!$this->userManager->userExists($owner)) {
1581
-			return $al;
1582
-		}
1583
-
1584
-		//Get node for the owner and correct the owner in case of external storages
1585
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1586
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1587
-			$nodes = $userFolder->getById($path->getId());
1588
-			$path = array_shift($nodes);
1589
-			if ($path->getOwner() === null) {
1590
-				return [];
1591
-			}
1592
-			$owner = $path->getOwner()->getUID();
1593
-		}
1594
-
1595
-		$providers = $this->factory->getAllProviders();
1596
-
1597
-		/** @var Node[] $nodes */
1598
-		$nodes = [];
1599
-
1600
-
1601
-		if ($currentAccess) {
1602
-			$ownerPath = $path->getPath();
1603
-			$ownerPath = explode('/', $ownerPath, 4);
1604
-			if (count($ownerPath) < 4) {
1605
-				$ownerPath = '';
1606
-			} else {
1607
-				$ownerPath = $ownerPath[3];
1608
-			}
1609
-			$al['users'][$owner] = [
1610
-				'node_id' => $path->getId(),
1611
-				'node_path' => '/' . $ownerPath,
1612
-			];
1613
-		} else {
1614
-			$al['users'][] = $owner;
1615
-		}
1616
-
1617
-		// Collect all the shares
1618
-		while ($path->getPath() !== $userFolder->getPath()) {
1619
-			$nodes[] = $path;
1620
-			if (!$recursive) {
1621
-				break;
1622
-			}
1623
-			$path = $path->getParent();
1624
-		}
1625
-
1626
-		foreach ($providers as $provider) {
1627
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1628
-
1629
-			foreach ($tmp as $k => $v) {
1630
-				if (isset($al[$k])) {
1631
-					if (is_array($al[$k])) {
1632
-						if ($currentAccess) {
1633
-							$al[$k] += $v;
1634
-						} else {
1635
-							$al[$k] = array_merge($al[$k], $v);
1636
-							$al[$k] = array_unique($al[$k]);
1637
-							$al[$k] = array_values($al[$k]);
1638
-						}
1639
-					} else {
1640
-						$al[$k] = $al[$k] || $v;
1641
-					}
1642
-				} else {
1643
-					$al[$k] = $v;
1644
-				}
1645
-			}
1646
-		}
1647
-
1648
-		return $al;
1649
-	}
1650
-
1651
-	/**
1652
-	 * Create a new share
1653
-	 * @return \OCP\Share\IShare
1654
-	 */
1655
-	public function newShare() {
1656
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1657
-	}
1658
-
1659
-	/**
1660
-	 * Is the share API enabled
1661
-	 *
1662
-	 * @return bool
1663
-	 */
1664
-	public function shareApiEnabled() {
1665
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1666
-	}
1667
-
1668
-	/**
1669
-	 * Is public link sharing enabled
1670
-	 *
1671
-	 * @return bool
1672
-	 */
1673
-	public function shareApiAllowLinks() {
1674
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1675
-	}
1676
-
1677
-	/**
1678
-	 * Is password on public link requires
1679
-	 *
1680
-	 * @return bool
1681
-	 */
1682
-	public function shareApiLinkEnforcePassword() {
1683
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1684
-	}
1685
-
1686
-	/**
1687
-	 * Is default link expire date enabled
1688
-	 *
1689
-	 * @return bool
1690
-	 */
1691
-	public function shareApiLinkDefaultExpireDate() {
1692
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1693
-	}
1694
-
1695
-	/**
1696
-	 * Is default link expire date enforced
1697
-	 *`
1698
-	 * @return bool
1699
-	 */
1700
-	public function shareApiLinkDefaultExpireDateEnforced() {
1701
-		return $this->shareApiLinkDefaultExpireDate() &&
1702
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1703
-	}
1704
-
1705
-
1706
-	/**
1707
-	 * Number of default link expire days
1708
-	 * @return int
1709
-	 */
1710
-	public function shareApiLinkDefaultExpireDays() {
1711
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712
-	}
1713
-
1714
-	/**
1715
-	 * Is default internal expire date enabled
1716
-	 *
1717
-	 * @return bool
1718
-	 */
1719
-	public function shareApiInternalDefaultExpireDate(): bool {
1720
-		return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1721
-	}
1722
-
1723
-	/**
1724
-	 * Is default expire date enforced
1725
-	 *`
1726
-	 * @return bool
1727
-	 */
1728
-	public function shareApiInternalDefaultExpireDateEnforced(): bool {
1729
-		return $this->shareApiInternalDefaultExpireDate() &&
1730
-			$this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1731
-	}
1732
-
1733
-
1734
-	/**
1735
-	 * Number of default expire days
1736
-	 * @return int
1737
-	 */
1738
-	public function shareApiInternalDefaultExpireDays(): int {
1739
-		return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740
-	}
1741
-
1742
-	/**
1743
-	 * Allow public upload on link shares
1744
-	 *
1745
-	 * @return bool
1746
-	 */
1747
-	public function shareApiLinkAllowPublicUpload() {
1748
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1749
-	}
1750
-
1751
-	/**
1752
-	 * check if user can only share with group members
1753
-	 * @return bool
1754
-	 */
1755
-	public function shareWithGroupMembersOnly() {
1756
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1757
-	}
1758
-
1759
-	/**
1760
-	 * Check if users can share with groups
1761
-	 * @return bool
1762
-	 */
1763
-	public function allowGroupSharing() {
1764
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1765
-	}
1766
-
1767
-	public function allowEnumeration(): bool {
1768
-		return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1769
-	}
1770
-
1771
-	public function limitEnumerationToGroups(): bool {
1772
-		return $this->allowEnumeration() &&
1773
-			$this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1774
-	}
1775
-
1776
-	/**
1777
-	 * Copied from \OC_Util::isSharingDisabledForUser
1778
-	 *
1779
-	 * TODO: Deprecate fuction from OC_Util
1780
-	 *
1781
-	 * @param string $userId
1782
-	 * @return bool
1783
-	 */
1784
-	public function sharingDisabledForUser($userId) {
1785
-		if ($userId === null) {
1786
-			return false;
1787
-		}
1788
-
1789
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1790
-			return $this->sharingDisabledForUsersCache[$userId];
1791
-		}
1792
-
1793
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1794
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1795
-			$excludedGroups = json_decode($groupsList);
1796
-			if (is_null($excludedGroups)) {
1797
-				$excludedGroups = explode(',', $groupsList);
1798
-				$newValue = json_encode($excludedGroups);
1799
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1800
-			}
1801
-			$user = $this->userManager->get($userId);
1802
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1803
-			if (!empty($usersGroups)) {
1804
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1805
-				// if the user is only in groups which are disabled for sharing then
1806
-				// sharing is also disabled for the user
1807
-				if (empty($remainingGroups)) {
1808
-					$this->sharingDisabledForUsersCache[$userId] = true;
1809
-					return true;
1810
-				}
1811
-			}
1812
-		}
1813
-
1814
-		$this->sharingDisabledForUsersCache[$userId] = false;
1815
-		return false;
1816
-	}
1817
-
1818
-	/**
1819
-	 * @inheritdoc
1820
-	 */
1821
-	public function outgoingServer2ServerSharesAllowed() {
1822
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1823
-	}
1824
-
1825
-	/**
1826
-	 * @inheritdoc
1827
-	 */
1828
-	public function outgoingServer2ServerGroupSharesAllowed() {
1829
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1830
-	}
1831
-
1832
-	/**
1833
-	 * @inheritdoc
1834
-	 */
1835
-	public function shareProviderExists($shareType) {
1836
-		try {
1837
-			$this->factory->getProviderForType($shareType);
1838
-		} catch (ProviderException $e) {
1839
-			return false;
1840
-		}
1841
-
1842
-		return true;
1843
-	}
1844
-
1845
-	public function getAllShares(): iterable {
1846
-		$providers = $this->factory->getAllProviders();
1847
-
1848
-		foreach ($providers as $provider) {
1849
-			yield from $provider->getAllShares();
1850
-		}
1851
-	}
1440
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1441
+            !$this->shareApiLinkAllowPublicUpload()) {
1442
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1443
+        }
1444
+
1445
+        return $share;
1446
+    }
1447
+
1448
+    protected function checkExpireDate($share) {
1449
+        if ($share->isExpired()) {
1450
+            $this->deleteShare($share);
1451
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1452
+        }
1453
+
1454
+    }
1455
+
1456
+    /**
1457
+     * Verify the password of a public share
1458
+     *
1459
+     * @param \OCP\Share\IShare $share
1460
+     * @param string $password
1461
+     * @return bool
1462
+     */
1463
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1464
+        $passwordProtected = $share->getShareType() !== IShare::TYPE_LINK
1465
+                             || $share->getShareType() !== IShare::TYPE_EMAIL
1466
+                             || $share->getShareType() !== IShare::TYPE_CIRCLE;
1467
+        if (!$passwordProtected) {
1468
+            //TODO maybe exception?
1469
+            return false;
1470
+        }
1471
+
1472
+        if ($password === null || $share->getPassword() === null) {
1473
+            return false;
1474
+        }
1475
+
1476
+        $newHash = '';
1477
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1478
+            return false;
1479
+        }
1480
+
1481
+        if (!empty($newHash)) {
1482
+            $share->setPassword($newHash);
1483
+            $provider = $this->factory->getProviderForType($share->getShareType());
1484
+            $provider->update($share);
1485
+        }
1486
+
1487
+        return true;
1488
+    }
1489
+
1490
+    /**
1491
+     * @inheritdoc
1492
+     */
1493
+    public function userDeleted($uid) {
1494
+        $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];
1495
+
1496
+        foreach ($types as $type) {
1497
+            try {
1498
+                $provider = $this->factory->getProviderForType($type);
1499
+            } catch (ProviderException $e) {
1500
+                continue;
1501
+            }
1502
+            $provider->userDeleted($uid, $type);
1503
+        }
1504
+    }
1505
+
1506
+    /**
1507
+     * @inheritdoc
1508
+     */
1509
+    public function groupDeleted($gid) {
1510
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1511
+        $provider->groupDeleted($gid);
1512
+    }
1513
+
1514
+    /**
1515
+     * @inheritdoc
1516
+     */
1517
+    public function userDeletedFromGroup($uid, $gid) {
1518
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1519
+        $provider->userDeletedFromGroup($uid, $gid);
1520
+    }
1521
+
1522
+    /**
1523
+     * Get access list to a path. This means
1524
+     * all the users that can access a given path.
1525
+     *
1526
+     * Consider:
1527
+     * -root
1528
+     * |-folder1 (23)
1529
+     *  |-folder2 (32)
1530
+     *   |-fileA (42)
1531
+     *
1532
+     * fileA is shared with user1 and user1@server1
1533
+     * folder2 is shared with group2 (user4 is a member of group2)
1534
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1535
+     *
1536
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1537
+     * [
1538
+     *  users  => [
1539
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1540
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1541
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1542
+     *  ],
1543
+     *  remote => [
1544
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1545
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1546
+     *  ],
1547
+     *  public => bool
1548
+     *  mail => bool
1549
+     * ]
1550
+     *
1551
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1552
+     * [
1553
+     *  users  => ['user1', 'user2', 'user4'],
1554
+     *  remote => bool,
1555
+     *  public => bool
1556
+     *  mail => bool
1557
+     * ]
1558
+     *
1559
+     * This is required for encryption/activity
1560
+     *
1561
+     * @param \OCP\Files\Node $path
1562
+     * @param bool $recursive Should we check all parent folders as well
1563
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1564
+     * @return array
1565
+     */
1566
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1567
+        $owner = $path->getOwner();
1568
+
1569
+        if ($owner === null) {
1570
+            return [];
1571
+        }
1572
+
1573
+        $owner = $owner->getUID();
1574
+
1575
+        if ($currentAccess) {
1576
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1577
+        } else {
1578
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1579
+        }
1580
+        if (!$this->userManager->userExists($owner)) {
1581
+            return $al;
1582
+        }
1583
+
1584
+        //Get node for the owner and correct the owner in case of external storages
1585
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1586
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1587
+            $nodes = $userFolder->getById($path->getId());
1588
+            $path = array_shift($nodes);
1589
+            if ($path->getOwner() === null) {
1590
+                return [];
1591
+            }
1592
+            $owner = $path->getOwner()->getUID();
1593
+        }
1594
+
1595
+        $providers = $this->factory->getAllProviders();
1596
+
1597
+        /** @var Node[] $nodes */
1598
+        $nodes = [];
1599
+
1600
+
1601
+        if ($currentAccess) {
1602
+            $ownerPath = $path->getPath();
1603
+            $ownerPath = explode('/', $ownerPath, 4);
1604
+            if (count($ownerPath) < 4) {
1605
+                $ownerPath = '';
1606
+            } else {
1607
+                $ownerPath = $ownerPath[3];
1608
+            }
1609
+            $al['users'][$owner] = [
1610
+                'node_id' => $path->getId(),
1611
+                'node_path' => '/' . $ownerPath,
1612
+            ];
1613
+        } else {
1614
+            $al['users'][] = $owner;
1615
+        }
1616
+
1617
+        // Collect all the shares
1618
+        while ($path->getPath() !== $userFolder->getPath()) {
1619
+            $nodes[] = $path;
1620
+            if (!$recursive) {
1621
+                break;
1622
+            }
1623
+            $path = $path->getParent();
1624
+        }
1625
+
1626
+        foreach ($providers as $provider) {
1627
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1628
+
1629
+            foreach ($tmp as $k => $v) {
1630
+                if (isset($al[$k])) {
1631
+                    if (is_array($al[$k])) {
1632
+                        if ($currentAccess) {
1633
+                            $al[$k] += $v;
1634
+                        } else {
1635
+                            $al[$k] = array_merge($al[$k], $v);
1636
+                            $al[$k] = array_unique($al[$k]);
1637
+                            $al[$k] = array_values($al[$k]);
1638
+                        }
1639
+                    } else {
1640
+                        $al[$k] = $al[$k] || $v;
1641
+                    }
1642
+                } else {
1643
+                    $al[$k] = $v;
1644
+                }
1645
+            }
1646
+        }
1647
+
1648
+        return $al;
1649
+    }
1650
+
1651
+    /**
1652
+     * Create a new share
1653
+     * @return \OCP\Share\IShare
1654
+     */
1655
+    public function newShare() {
1656
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1657
+    }
1658
+
1659
+    /**
1660
+     * Is the share API enabled
1661
+     *
1662
+     * @return bool
1663
+     */
1664
+    public function shareApiEnabled() {
1665
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1666
+    }
1667
+
1668
+    /**
1669
+     * Is public link sharing enabled
1670
+     *
1671
+     * @return bool
1672
+     */
1673
+    public function shareApiAllowLinks() {
1674
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1675
+    }
1676
+
1677
+    /**
1678
+     * Is password on public link requires
1679
+     *
1680
+     * @return bool
1681
+     */
1682
+    public function shareApiLinkEnforcePassword() {
1683
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1684
+    }
1685
+
1686
+    /**
1687
+     * Is default link expire date enabled
1688
+     *
1689
+     * @return bool
1690
+     */
1691
+    public function shareApiLinkDefaultExpireDate() {
1692
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1693
+    }
1694
+
1695
+    /**
1696
+     * Is default link expire date enforced
1697
+     *`
1698
+     * @return bool
1699
+     */
1700
+    public function shareApiLinkDefaultExpireDateEnforced() {
1701
+        return $this->shareApiLinkDefaultExpireDate() &&
1702
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1703
+    }
1704
+
1705
+
1706
+    /**
1707
+     * Number of default link expire days
1708
+     * @return int
1709
+     */
1710
+    public function shareApiLinkDefaultExpireDays() {
1711
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1712
+    }
1713
+
1714
+    /**
1715
+     * Is default internal expire date enabled
1716
+     *
1717
+     * @return bool
1718
+     */
1719
+    public function shareApiInternalDefaultExpireDate(): bool {
1720
+        return $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
1721
+    }
1722
+
1723
+    /**
1724
+     * Is default expire date enforced
1725
+     *`
1726
+     * @return bool
1727
+     */
1728
+    public function shareApiInternalDefaultExpireDateEnforced(): bool {
1729
+        return $this->shareApiInternalDefaultExpireDate() &&
1730
+            $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
1731
+    }
1732
+
1733
+
1734
+    /**
1735
+     * Number of default expire days
1736
+     * @return int
1737
+     */
1738
+    public function shareApiInternalDefaultExpireDays(): int {
1739
+        return (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
1740
+    }
1741
+
1742
+    /**
1743
+     * Allow public upload on link shares
1744
+     *
1745
+     * @return bool
1746
+     */
1747
+    public function shareApiLinkAllowPublicUpload() {
1748
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1749
+    }
1750
+
1751
+    /**
1752
+     * check if user can only share with group members
1753
+     * @return bool
1754
+     */
1755
+    public function shareWithGroupMembersOnly() {
1756
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1757
+    }
1758
+
1759
+    /**
1760
+     * Check if users can share with groups
1761
+     * @return bool
1762
+     */
1763
+    public function allowGroupSharing() {
1764
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1765
+    }
1766
+
1767
+    public function allowEnumeration(): bool {
1768
+        return $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes';
1769
+    }
1770
+
1771
+    public function limitEnumerationToGroups(): bool {
1772
+        return $this->allowEnumeration() &&
1773
+            $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes';
1774
+    }
1775
+
1776
+    /**
1777
+     * Copied from \OC_Util::isSharingDisabledForUser
1778
+     *
1779
+     * TODO: Deprecate fuction from OC_Util
1780
+     *
1781
+     * @param string $userId
1782
+     * @return bool
1783
+     */
1784
+    public function sharingDisabledForUser($userId) {
1785
+        if ($userId === null) {
1786
+            return false;
1787
+        }
1788
+
1789
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1790
+            return $this->sharingDisabledForUsersCache[$userId];
1791
+        }
1792
+
1793
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1794
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1795
+            $excludedGroups = json_decode($groupsList);
1796
+            if (is_null($excludedGroups)) {
1797
+                $excludedGroups = explode(',', $groupsList);
1798
+                $newValue = json_encode($excludedGroups);
1799
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1800
+            }
1801
+            $user = $this->userManager->get($userId);
1802
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1803
+            if (!empty($usersGroups)) {
1804
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1805
+                // if the user is only in groups which are disabled for sharing then
1806
+                // sharing is also disabled for the user
1807
+                if (empty($remainingGroups)) {
1808
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1809
+                    return true;
1810
+                }
1811
+            }
1812
+        }
1813
+
1814
+        $this->sharingDisabledForUsersCache[$userId] = false;
1815
+        return false;
1816
+    }
1817
+
1818
+    /**
1819
+     * @inheritdoc
1820
+     */
1821
+    public function outgoingServer2ServerSharesAllowed() {
1822
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1823
+    }
1824
+
1825
+    /**
1826
+     * @inheritdoc
1827
+     */
1828
+    public function outgoingServer2ServerGroupSharesAllowed() {
1829
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_group_share_enabled', 'no') === 'yes';
1830
+    }
1831
+
1832
+    /**
1833
+     * @inheritdoc
1834
+     */
1835
+    public function shareProviderExists($shareType) {
1836
+        try {
1837
+            $this->factory->getProviderForType($shareType);
1838
+        } catch (ProviderException $e) {
1839
+            return false;
1840
+        }
1841
+
1842
+        return true;
1843
+    }
1844
+
1845
+    public function getAllShares(): iterable {
1846
+        $providers = $this->factory->getAllProviders();
1847
+
1848
+        foreach ($providers as $provider) {
1849
+            yield from $provider->getAllShares();
1850
+        }
1851
+    }
1852 1852
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 1 patch
Indentation   +1405 added lines, -1405 removed lines patch added patch discarded remove patch
@@ -62,1445 +62,1445 @@
 block discarded – undo
62 62
  */
63 63
 class DefaultShareProvider implements IShareProvider {
64 64
 
65
-	// Special share type for user modified group shares
66
-	const SHARE_TYPE_USERGROUP = 2;
67
-
68
-	/** @var IDBConnection */
69
-	private $dbConn;
70
-
71
-	/** @var IUserManager */
72
-	private $userManager;
73
-
74
-	/** @var IGroupManager */
75
-	private $groupManager;
76
-
77
-	/** @var IRootFolder */
78
-	private $rootFolder;
79
-
80
-	/** @var IMailer */
81
-	private $mailer;
82
-
83
-	/** @var Defaults */
84
-	private $defaults;
85
-
86
-	/** @var IL10N */
87
-	private $l;
88
-
89
-	/** @var IURLGenerator */
90
-	private $urlGenerator;
91
-
92
-	/**
93
-	 * DefaultShareProvider constructor.
94
-	 *
95
-	 * @param IDBConnection $connection
96
-	 * @param IUserManager $userManager
97
-	 * @param IGroupManager $groupManager
98
-	 * @param IRootFolder $rootFolder
99
-	 * @param IMailer $mailer ;
100
-	 * @param Defaults $defaults
101
-	 * @param IL10N $l
102
-	 * @param IURLGenerator $urlGenerator
103
-	 */
104
-	public function __construct(
105
-			IDBConnection $connection,
106
-			IUserManager $userManager,
107
-			IGroupManager $groupManager,
108
-			IRootFolder $rootFolder,
109
-			IMailer $mailer,
110
-			Defaults $defaults,
111
-			IL10N $l,
112
-			IURLGenerator $urlGenerator) {
113
-		$this->dbConn = $connection;
114
-		$this->userManager = $userManager;
115
-		$this->groupManager = $groupManager;
116
-		$this->rootFolder = $rootFolder;
117
-		$this->mailer = $mailer;
118
-		$this->defaults = $defaults;
119
-		$this->l = $l;
120
-		$this->urlGenerator = $urlGenerator;
121
-	}
122
-
123
-	/**
124
-	 * Return the identifier of this provider.
125
-	 *
126
-	 * @return string Containing only [a-zA-Z0-9]
127
-	 */
128
-	public function identifier() {
129
-		return 'ocinternal';
130
-	}
131
-
132
-	/**
133
-	 * Share a path
134
-	 *
135
-	 * @param \OCP\Share\IShare $share
136
-	 * @return \OCP\Share\IShare The share object
137
-	 * @throws ShareNotFound
138
-	 * @throws \Exception
139
-	 */
140
-	public function create(\OCP\Share\IShare $share) {
141
-		$qb = $this->dbConn->getQueryBuilder();
142
-
143
-		$qb->insert('share');
144
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
145
-
146
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
147
-			//Set the UID of the user we share with
148
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
149
-			$qb->setValue('accepted', $qb->createNamedParameter(IShare::STATUS_PENDING));
150
-
151
-			//If an expiration date is set store it
152
-			if ($share->getExpirationDate() !== null) {
153
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
154
-			}
155
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
156
-			//Set the GID of the group we share with
157
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
158
-
159
-			//If an expiration date is set store it
160
-			if ($share->getExpirationDate() !== null) {
161
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
162
-			}
163
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
164
-			//set label for public link
165
-			$qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
166
-			//Set the token of the share
167
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
168
-
169
-			//If a password is set store it
170
-			if ($share->getPassword() !== null) {
171
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
172
-			}
173
-
174
-			$qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
175
-
176
-			//If an expiration date is set store it
177
-			if ($share->getExpirationDate() !== null) {
178
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
179
-			}
180
-
181
-			if (method_exists($share, 'getParent')) {
182
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
183
-			}
184
-		} else {
185
-			throw new \Exception('invalid share type!');
186
-		}
187
-
188
-		// Set what is shares
189
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
190
-		if ($share->getNode() instanceof \OCP\Files\File) {
191
-			$qb->setParameter('itemType', 'file');
192
-		} else {
193
-			$qb->setParameter('itemType', 'folder');
194
-		}
195
-
196
-		// Set the file id
197
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
198
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
199
-
200
-		// set the permissions
201
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
202
-
203
-		// Set who created this share
204
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
205
-
206
-		// Set who is the owner of this file/folder (and this the owner of the share)
207
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
208
-
209
-		// Set the file target
210
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
211
-
212
-		// Set the time this share was created
213
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
214
-
215
-		// insert the data and fetch the id of the share
216
-		$this->dbConn->beginTransaction();
217
-		$qb->execute();
218
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
219
-
220
-		// Now fetch the inserted share and create a complete share object
221
-		$qb = $this->dbConn->getQueryBuilder();
222
-		$qb->select('*')
223
-			->from('share')
224
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
225
-
226
-		$cursor = $qb->execute();
227
-		$data = $cursor->fetch();
228
-		$this->dbConn->commit();
229
-		$cursor->closeCursor();
230
-
231
-		if ($data === false) {
232
-			throw new ShareNotFound();
233
-		}
234
-
235
-		$mailSendValue = $share->getMailSend();
236
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
237
-
238
-		$share = $this->createShare($data);
239
-		return $share;
240
-	}
241
-
242
-	/**
243
-	 * Update a share
244
-	 *
245
-	 * @param \OCP\Share\IShare $share
246
-	 * @return \OCP\Share\IShare The share object
247
-	 * @throws ShareNotFound
248
-	 * @throws \OCP\Files\InvalidPathException
249
-	 * @throws \OCP\Files\NotFoundException
250
-	 */
251
-	public function update(\OCP\Share\IShare $share) {
252
-
253
-		$originalShare = $this->getShareById($share->getId());
254
-
255
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
256
-			/*
65
+    // Special share type for user modified group shares
66
+    const SHARE_TYPE_USERGROUP = 2;
67
+
68
+    /** @var IDBConnection */
69
+    private $dbConn;
70
+
71
+    /** @var IUserManager */
72
+    private $userManager;
73
+
74
+    /** @var IGroupManager */
75
+    private $groupManager;
76
+
77
+    /** @var IRootFolder */
78
+    private $rootFolder;
79
+
80
+    /** @var IMailer */
81
+    private $mailer;
82
+
83
+    /** @var Defaults */
84
+    private $defaults;
85
+
86
+    /** @var IL10N */
87
+    private $l;
88
+
89
+    /** @var IURLGenerator */
90
+    private $urlGenerator;
91
+
92
+    /**
93
+     * DefaultShareProvider constructor.
94
+     *
95
+     * @param IDBConnection $connection
96
+     * @param IUserManager $userManager
97
+     * @param IGroupManager $groupManager
98
+     * @param IRootFolder $rootFolder
99
+     * @param IMailer $mailer ;
100
+     * @param Defaults $defaults
101
+     * @param IL10N $l
102
+     * @param IURLGenerator $urlGenerator
103
+     */
104
+    public function __construct(
105
+            IDBConnection $connection,
106
+            IUserManager $userManager,
107
+            IGroupManager $groupManager,
108
+            IRootFolder $rootFolder,
109
+            IMailer $mailer,
110
+            Defaults $defaults,
111
+            IL10N $l,
112
+            IURLGenerator $urlGenerator) {
113
+        $this->dbConn = $connection;
114
+        $this->userManager = $userManager;
115
+        $this->groupManager = $groupManager;
116
+        $this->rootFolder = $rootFolder;
117
+        $this->mailer = $mailer;
118
+        $this->defaults = $defaults;
119
+        $this->l = $l;
120
+        $this->urlGenerator = $urlGenerator;
121
+    }
122
+
123
+    /**
124
+     * Return the identifier of this provider.
125
+     *
126
+     * @return string Containing only [a-zA-Z0-9]
127
+     */
128
+    public function identifier() {
129
+        return 'ocinternal';
130
+    }
131
+
132
+    /**
133
+     * Share a path
134
+     *
135
+     * @param \OCP\Share\IShare $share
136
+     * @return \OCP\Share\IShare The share object
137
+     * @throws ShareNotFound
138
+     * @throws \Exception
139
+     */
140
+    public function create(\OCP\Share\IShare $share) {
141
+        $qb = $this->dbConn->getQueryBuilder();
142
+
143
+        $qb->insert('share');
144
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
145
+
146
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
147
+            //Set the UID of the user we share with
148
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
149
+            $qb->setValue('accepted', $qb->createNamedParameter(IShare::STATUS_PENDING));
150
+
151
+            //If an expiration date is set store it
152
+            if ($share->getExpirationDate() !== null) {
153
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
154
+            }
155
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
156
+            //Set the GID of the group we share with
157
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
158
+
159
+            //If an expiration date is set store it
160
+            if ($share->getExpirationDate() !== null) {
161
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
162
+            }
163
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
164
+            //set label for public link
165
+            $qb->setValue('label', $qb->createNamedParameter($share->getLabel()));
166
+            //Set the token of the share
167
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
168
+
169
+            //If a password is set store it
170
+            if ($share->getPassword() !== null) {
171
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
172
+            }
173
+
174
+            $qb->setValue('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL));
175
+
176
+            //If an expiration date is set store it
177
+            if ($share->getExpirationDate() !== null) {
178
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
179
+            }
180
+
181
+            if (method_exists($share, 'getParent')) {
182
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
183
+            }
184
+        } else {
185
+            throw new \Exception('invalid share type!');
186
+        }
187
+
188
+        // Set what is shares
189
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
190
+        if ($share->getNode() instanceof \OCP\Files\File) {
191
+            $qb->setParameter('itemType', 'file');
192
+        } else {
193
+            $qb->setParameter('itemType', 'folder');
194
+        }
195
+
196
+        // Set the file id
197
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
198
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
199
+
200
+        // set the permissions
201
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
202
+
203
+        // Set who created this share
204
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
205
+
206
+        // Set who is the owner of this file/folder (and this the owner of the share)
207
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
208
+
209
+        // Set the file target
210
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
211
+
212
+        // Set the time this share was created
213
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
214
+
215
+        // insert the data and fetch the id of the share
216
+        $this->dbConn->beginTransaction();
217
+        $qb->execute();
218
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
219
+
220
+        // Now fetch the inserted share and create a complete share object
221
+        $qb = $this->dbConn->getQueryBuilder();
222
+        $qb->select('*')
223
+            ->from('share')
224
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
225
+
226
+        $cursor = $qb->execute();
227
+        $data = $cursor->fetch();
228
+        $this->dbConn->commit();
229
+        $cursor->closeCursor();
230
+
231
+        if ($data === false) {
232
+            throw new ShareNotFound();
233
+        }
234
+
235
+        $mailSendValue = $share->getMailSend();
236
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
237
+
238
+        $share = $this->createShare($data);
239
+        return $share;
240
+    }
241
+
242
+    /**
243
+     * Update a share
244
+     *
245
+     * @param \OCP\Share\IShare $share
246
+     * @return \OCP\Share\IShare The share object
247
+     * @throws ShareNotFound
248
+     * @throws \OCP\Files\InvalidPathException
249
+     * @throws \OCP\Files\NotFoundException
250
+     */
251
+    public function update(\OCP\Share\IShare $share) {
252
+
253
+        $originalShare = $this->getShareById($share->getId());
254
+
255
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
256
+            /*
257 257
 			 * We allow updating the recipient on user shares.
258 258
 			 */
259
-			$qb = $this->dbConn->getQueryBuilder();
260
-			$qb->update('share')
261
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
262
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
263
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
264
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
265
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
266
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
267
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
268
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
269
-				->set('note', $qb->createNamedParameter($share->getNote()))
270
-				->set('accepted', $qb->createNamedParameter($share->getStatus()))
271
-				->execute();
272
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
273
-			$qb = $this->dbConn->getQueryBuilder();
274
-			$qb->update('share')
275
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
276
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
277
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
278
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
279
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
280
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
281
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
282
-				->set('note', $qb->createNamedParameter($share->getNote()))
283
-				->execute();
284
-
285
-			/*
259
+            $qb = $this->dbConn->getQueryBuilder();
260
+            $qb->update('share')
261
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
262
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
263
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
264
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
265
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
266
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
267
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
268
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
269
+                ->set('note', $qb->createNamedParameter($share->getNote()))
270
+                ->set('accepted', $qb->createNamedParameter($share->getStatus()))
271
+                ->execute();
272
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
273
+            $qb = $this->dbConn->getQueryBuilder();
274
+            $qb->update('share')
275
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
276
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
277
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
278
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
279
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
280
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
281
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
282
+                ->set('note', $qb->createNamedParameter($share->getNote()))
283
+                ->execute();
284
+
285
+            /*
286 286
 			 * Update all user defined group shares
287 287
 			 */
288
-			$qb = $this->dbConn->getQueryBuilder();
289
-			$qb->update('share')
290
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
291
-				->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
292
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
293
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
294
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
295
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
296
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
297
-				->set('note', $qb->createNamedParameter($share->getNote()))
298
-				->execute();
299
-
300
-			/*
288
+            $qb = $this->dbConn->getQueryBuilder();
289
+            $qb->update('share')
290
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
291
+                ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
292
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
293
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
294
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
295
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
296
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
297
+                ->set('note', $qb->createNamedParameter($share->getNote()))
298
+                ->execute();
299
+
300
+            /*
301 301
 			 * Now update the permissions for all children that have not set it to 0
302 302
 			 */
303
-			$qb = $this->dbConn->getQueryBuilder();
304
-			$qb->update('share')
305
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
306
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
307
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
308
-				->execute();
309
-
310
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
311
-			$qb = $this->dbConn->getQueryBuilder();
312
-			$qb->update('share')
313
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
314
-				->set('password', $qb->createNamedParameter($share->getPassword()))
315
-				->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
316
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
317
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
318
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
319
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
320
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
321
-				->set('token', $qb->createNamedParameter($share->getToken()))
322
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
323
-				->set('note', $qb->createNamedParameter($share->getNote()))
324
-				->set('label', $qb->createNamedParameter($share->getLabel()))
325
-				->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
326
-				->execute();
327
-		}
328
-
329
-		if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
330
-			$this->propagateNote($share);
331
-		}
332
-
333
-
334
-		return $share;
335
-	}
336
-
337
-	/**
338
-	 * Accept a share.
339
-	 *
340
-	 * @param IShare $share
341
-	 * @param string $recipient
342
-	 * @return IShare The share object
343
-	 * @since 9.0.0
344
-	 */
345
-	public function acceptShare(IShare $share, string $recipient): IShare {
346
-		if ($share->getShareType() === IShare::TYPE_GROUP) {
347
-			$group = $this->groupManager->get($share->getSharedWith());
348
-			$user = $this->userManager->get($recipient);
349
-
350
-			if (is_null($group)) {
351
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
352
-			}
353
-
354
-			if (!$group->inGroup($user)) {
355
-				throw new ProviderException('Recipient not in receiving group');
356
-			}
357
-
358
-			// Try to fetch user specific share
359
-			$qb = $this->dbConn->getQueryBuilder();
360
-			$stmt = $qb->select('*')
361
-				->from('share')
362
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
363
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
364
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
365
-				->andWhere($qb->expr()->orX(
366
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
367
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
368
-				))
369
-				->execute();
370
-
371
-			$data = $stmt->fetch();
372
-			$stmt->closeCursor();
373
-
374
-			/*
303
+            $qb = $this->dbConn->getQueryBuilder();
304
+            $qb->update('share')
305
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
306
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
307
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
308
+                ->execute();
309
+
310
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
311
+            $qb = $this->dbConn->getQueryBuilder();
312
+            $qb->update('share')
313
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
314
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
315
+                ->set('password_by_talk', $qb->createNamedParameter($share->getSendPasswordByTalk(), IQueryBuilder::PARAM_BOOL))
316
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
317
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
318
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
319
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
320
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
321
+                ->set('token', $qb->createNamedParameter($share->getToken()))
322
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
323
+                ->set('note', $qb->createNamedParameter($share->getNote()))
324
+                ->set('label', $qb->createNamedParameter($share->getLabel()))
325
+                ->set('hide_download', $qb->createNamedParameter($share->getHideDownload() ? 1 : 0), IQueryBuilder::PARAM_INT)
326
+                ->execute();
327
+        }
328
+
329
+        if ($originalShare->getNote() !== $share->getNote() && $share->getNote() !== '') {
330
+            $this->propagateNote($share);
331
+        }
332
+
333
+
334
+        return $share;
335
+    }
336
+
337
+    /**
338
+     * Accept a share.
339
+     *
340
+     * @param IShare $share
341
+     * @param string $recipient
342
+     * @return IShare The share object
343
+     * @since 9.0.0
344
+     */
345
+    public function acceptShare(IShare $share, string $recipient): IShare {
346
+        if ($share->getShareType() === IShare::TYPE_GROUP) {
347
+            $group = $this->groupManager->get($share->getSharedWith());
348
+            $user = $this->userManager->get($recipient);
349
+
350
+            if (is_null($group)) {
351
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
352
+            }
353
+
354
+            if (!$group->inGroup($user)) {
355
+                throw new ProviderException('Recipient not in receiving group');
356
+            }
357
+
358
+            // Try to fetch user specific share
359
+            $qb = $this->dbConn->getQueryBuilder();
360
+            $stmt = $qb->select('*')
361
+                ->from('share')
362
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
363
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
364
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
365
+                ->andWhere($qb->expr()->orX(
366
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
367
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
368
+                ))
369
+                ->execute();
370
+
371
+            $data = $stmt->fetch();
372
+            $stmt->closeCursor();
373
+
374
+            /*
375 375
 			 * Check if there already is a user specific group share.
376 376
 			 * If there is update it (if required).
377 377
 			 */
378
-			if ($data === false) {
379
-				$id = $this->createUserSpecificGroupShare($share, $recipient);
380
-			} else {
381
-				$id = $data['id'];
382
-			}
383
-
384
-		} else if ($share->getShareType() === IShare::TYPE_USER) {
385
-			if ($share->getSharedWith() !== $recipient) {
386
-				throw new ProviderException('Recipient does not match');
387
-			}
388
-
389
-			$id = $share->getId();
390
-		} else {
391
-			throw new ProviderException('Invalid shareType');
392
-		}
393
-
394
-		$qb = $this->dbConn->getQueryBuilder();
395
-		$qb->update('share')
396
-			->set('accepted', $qb->createNamedParameter(IShare::STATUS_ACCEPTED))
397
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
398
-			->execute();
399
-
400
-		return $share;
401
-	}
402
-
403
-	/**
404
-	 * Get all children of this share
405
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
406
-	 *
407
-	 * @param \OCP\Share\IShare $parent
408
-	 * @return \OCP\Share\IShare[]
409
-	 */
410
-	public function getChildren(\OCP\Share\IShare $parent) {
411
-		$children = [];
412
-
413
-		$qb = $this->dbConn->getQueryBuilder();
414
-		$qb->select('*')
415
-			->from('share')
416
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
417
-			->andWhere(
418
-				$qb->expr()->in(
419
-					'share_type',
420
-					$qb->createNamedParameter([
421
-						\OCP\Share::SHARE_TYPE_USER,
422
-						\OCP\Share::SHARE_TYPE_GROUP,
423
-						\OCP\Share::SHARE_TYPE_LINK,
424
-					], IQueryBuilder::PARAM_INT_ARRAY)
425
-				)
426
-			)
427
-			->andWhere($qb->expr()->orX(
428
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-			))
431
-			->orderBy('id');
432
-
433
-		$cursor = $qb->execute();
434
-		while($data = $cursor->fetch()) {
435
-			$children[] = $this->createShare($data);
436
-		}
437
-		$cursor->closeCursor();
438
-
439
-		return $children;
440
-	}
441
-
442
-	/**
443
-	 * Delete a share
444
-	 *
445
-	 * @param \OCP\Share\IShare $share
446
-	 */
447
-	public function delete(\OCP\Share\IShare $share) {
448
-		$qb = $this->dbConn->getQueryBuilder();
449
-		$qb->delete('share')
450
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
451
-
452
-		/*
378
+            if ($data === false) {
379
+                $id = $this->createUserSpecificGroupShare($share, $recipient);
380
+            } else {
381
+                $id = $data['id'];
382
+            }
383
+
384
+        } else if ($share->getShareType() === IShare::TYPE_USER) {
385
+            if ($share->getSharedWith() !== $recipient) {
386
+                throw new ProviderException('Recipient does not match');
387
+            }
388
+
389
+            $id = $share->getId();
390
+        } else {
391
+            throw new ProviderException('Invalid shareType');
392
+        }
393
+
394
+        $qb = $this->dbConn->getQueryBuilder();
395
+        $qb->update('share')
396
+            ->set('accepted', $qb->createNamedParameter(IShare::STATUS_ACCEPTED))
397
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
398
+            ->execute();
399
+
400
+        return $share;
401
+    }
402
+
403
+    /**
404
+     * Get all children of this share
405
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
406
+     *
407
+     * @param \OCP\Share\IShare $parent
408
+     * @return \OCP\Share\IShare[]
409
+     */
410
+    public function getChildren(\OCP\Share\IShare $parent) {
411
+        $children = [];
412
+
413
+        $qb = $this->dbConn->getQueryBuilder();
414
+        $qb->select('*')
415
+            ->from('share')
416
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
417
+            ->andWhere(
418
+                $qb->expr()->in(
419
+                    'share_type',
420
+                    $qb->createNamedParameter([
421
+                        \OCP\Share::SHARE_TYPE_USER,
422
+                        \OCP\Share::SHARE_TYPE_GROUP,
423
+                        \OCP\Share::SHARE_TYPE_LINK,
424
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
425
+                )
426
+            )
427
+            ->andWhere($qb->expr()->orX(
428
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+            ))
431
+            ->orderBy('id');
432
+
433
+        $cursor = $qb->execute();
434
+        while($data = $cursor->fetch()) {
435
+            $children[] = $this->createShare($data);
436
+        }
437
+        $cursor->closeCursor();
438
+
439
+        return $children;
440
+    }
441
+
442
+    /**
443
+     * Delete a share
444
+     *
445
+     * @param \OCP\Share\IShare $share
446
+     */
447
+    public function delete(\OCP\Share\IShare $share) {
448
+        $qb = $this->dbConn->getQueryBuilder();
449
+        $qb->delete('share')
450
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
451
+
452
+        /*
453 453
 		 * If the share is a group share delete all possible
454 454
 		 * user defined groups shares.
455 455
 		 */
456
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
457
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
458
-		}
459
-
460
-		$qb->execute();
461
-	}
462
-
463
-	/**
464
-	 * Unshare a share from the recipient. If this is a group share
465
-	 * this means we need a special entry in the share db.
466
-	 *
467
-	 * @param IShare $share
468
-	 * @param string $recipient UserId of recipient
469
-	 * @throws BackendError
470
-	 * @throws ProviderException
471
-	 */
472
-	public function deleteFromSelf(IShare $share, $recipient) {
473
-		if ($share->getShareType() === IShare::TYPE_GROUP) {
474
-
475
-			$group = $this->groupManager->get($share->getSharedWith());
476
-			$user = $this->userManager->get($recipient);
477
-
478
-			if (is_null($group)) {
479
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
480
-			}
481
-
482
-			if (!$group->inGroup($user)) {
483
-				throw new ProviderException('Recipient not in receiving group');
484
-			}
485
-
486
-			// Try to fetch user specific share
487
-			$qb = $this->dbConn->getQueryBuilder();
488
-			$stmt = $qb->select('*')
489
-				->from('share')
490
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
491
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
492
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
493
-				->andWhere($qb->expr()->orX(
494
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
495
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
496
-				))
497
-				->execute();
498
-
499
-			$data = $stmt->fetch();
500
-
501
-			/*
456
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
457
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
458
+        }
459
+
460
+        $qb->execute();
461
+    }
462
+
463
+    /**
464
+     * Unshare a share from the recipient. If this is a group share
465
+     * this means we need a special entry in the share db.
466
+     *
467
+     * @param IShare $share
468
+     * @param string $recipient UserId of recipient
469
+     * @throws BackendError
470
+     * @throws ProviderException
471
+     */
472
+    public function deleteFromSelf(IShare $share, $recipient) {
473
+        if ($share->getShareType() === IShare::TYPE_GROUP) {
474
+
475
+            $group = $this->groupManager->get($share->getSharedWith());
476
+            $user = $this->userManager->get($recipient);
477
+
478
+            if (is_null($group)) {
479
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
480
+            }
481
+
482
+            if (!$group->inGroup($user)) {
483
+                throw new ProviderException('Recipient not in receiving group');
484
+            }
485
+
486
+            // Try to fetch user specific share
487
+            $qb = $this->dbConn->getQueryBuilder();
488
+            $stmt = $qb->select('*')
489
+                ->from('share')
490
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
491
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
492
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
493
+                ->andWhere($qb->expr()->orX(
494
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
495
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
496
+                ))
497
+                ->execute();
498
+
499
+            $data = $stmt->fetch();
500
+
501
+            /*
502 502
 			 * Check if there already is a user specific group share.
503 503
 			 * If there is update it (if required).
504 504
 			 */
505
-			if ($data === false) {
506
-				$id = $this->createUserSpecificGroupShare($share, $recipient);
507
-				$permissions = $share->getPermissions();
508
-			} else {
509
-				$permissions = $data['permissions'];
510
-				$id = $data['id'];
511
-			}
512
-
513
-			if ($permissions !== 0) {
514
-				// Update existing usergroup share
515
-				$qb = $this->dbConn->getQueryBuilder();
516
-				$qb->update('share')
517
-					->set('permissions', $qb->createNamedParameter(0))
518
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
519
-					->execute();
520
-			}
521
-
522
-		} else if ($share->getShareType() === IShare::TYPE_USER) {
523
-
524
-			if ($share->getSharedWith() !== $recipient) {
525
-				throw new ProviderException('Recipient does not match');
526
-			}
527
-
528
-			// We can just delete user and link shares
529
-			$this->delete($share);
530
-		} else {
531
-			throw new ProviderException('Invalid shareType');
532
-		}
533
-	}
534
-
535
-	protected function createUserSpecificGroupShare(IShare $share, string $recipient): int {
536
-		$type = $share->getNodeType();
537
-
538
-		$qb = $this->dbConn->getQueryBuilder();
539
-		$qb->insert('share')
540
-			->values([
541
-				'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
542
-				'share_with' => $qb->createNamedParameter($recipient),
543
-				'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
544
-				'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
545
-				'parent' => $qb->createNamedParameter($share->getId()),
546
-				'item_type' => $qb->createNamedParameter($type),
547
-				'item_source' => $qb->createNamedParameter($share->getNodeId()),
548
-				'file_source' => $qb->createNamedParameter($share->getNodeId()),
549
-				'file_target' => $qb->createNamedParameter($share->getTarget()),
550
-				'permissions' => $qb->createNamedParameter($share->getPermissions()),
551
-				'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
552
-			])->execute();
553
-
554
-		return $qb->getLastInsertId();
555
-	}
556
-
557
-	/**
558
-	 * @inheritdoc
559
-	 *
560
-	 * For now this only works for group shares
561
-	 * If this gets implemented for normal shares we have to extend it
562
-	 */
563
-	public function restore(IShare $share, string $recipient): IShare {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-		$qb->select('permissions')
566
-			->from('share')
567
-			->where(
568
-				$qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
569
-			);
570
-		$cursor = $qb->execute();
571
-		$data = $cursor->fetch();
572
-		$cursor->closeCursor();
573
-
574
-		$originalPermission = $data['permissions'];
575
-
576
-		$qb = $this->dbConn->getQueryBuilder();
577
-		$qb->update('share')
578
-			->set('permissions', $qb->createNamedParameter($originalPermission))
579
-			->where(
580
-				$qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
581
-			)->andWhere(
582
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
583
-			)->andWhere(
584
-				$qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
585
-			);
586
-
587
-		$qb->execute();
588
-
589
-		return $this->getShareById($share->getId(), $recipient);
590
-	}
591
-
592
-	/**
593
-	 * @inheritdoc
594
-	 */
595
-	public function move(\OCP\Share\IShare $share, $recipient) {
596
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
-			// Just update the target
598
-			$qb = $this->dbConn->getQueryBuilder();
599
-			$qb->update('share')
600
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
601
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
602
-				->execute();
603
-
604
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
605
-
606
-			// Check if there is a usergroup share
607
-			$qb = $this->dbConn->getQueryBuilder();
608
-			$stmt = $qb->select('id')
609
-				->from('share')
610
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
611
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
612
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
613
-				->andWhere($qb->expr()->orX(
614
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
615
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
616
-				))
617
-				->setMaxResults(1)
618
-				->execute();
619
-
620
-			$data = $stmt->fetch();
621
-			$stmt->closeCursor();
622
-
623
-			if ($data === false) {
624
-				// No usergroup share yet. Create one.
625
-				$qb = $this->dbConn->getQueryBuilder();
626
-				$qb->insert('share')
627
-					->values([
628
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
629
-						'share_with' => $qb->createNamedParameter($recipient),
630
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
631
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
632
-						'parent' => $qb->createNamedParameter($share->getId()),
633
-						'item_type' => $qb->createNamedParameter($share->getNodeType()),
634
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
635
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
636
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
637
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
638
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
639
-					])->execute();
640
-			} else {
641
-				// Already a usergroup share. Update it.
642
-				$qb = $this->dbConn->getQueryBuilder();
643
-				$qb->update('share')
644
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
645
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
646
-					->execute();
647
-			}
648
-		}
649
-
650
-		return $share;
651
-	}
652
-
653
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
654
-		$qb = $this->dbConn->getQueryBuilder();
655
-		$qb->select('*')
656
-			->from('share', 's')
657
-			->andWhere($qb->expr()->orX(
658
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
659
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
660
-			));
661
-
662
-		$qb->andWhere($qb->expr()->orX(
663
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
664
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
665
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
666
-		));
667
-
668
-		/**
669
-		 * Reshares for this user are shares where they are the owner.
670
-		 */
671
-		if ($reshares === false) {
672
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
673
-		} else {
674
-			$qb->andWhere(
675
-				$qb->expr()->orX(
676
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
677
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
678
-				)
679
-			);
680
-		}
681
-
682
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
683
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
684
-
685
-		$qb->orderBy('id');
686
-
687
-		$cursor = $qb->execute();
688
-		$shares = [];
689
-		while ($data = $cursor->fetch()) {
690
-			$shares[$data['fileid']][] = $this->createShare($data);
691
-		}
692
-		$cursor->closeCursor();
693
-
694
-		return $shares;
695
-	}
696
-
697
-	/**
698
-	 * @inheritdoc
699
-	 */
700
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
701
-		$qb = $this->dbConn->getQueryBuilder();
702
-		$qb->select('*')
703
-			->from('share')
704
-			->andWhere($qb->expr()->orX(
705
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
706
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
707
-			));
708
-
709
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
710
-
711
-		/**
712
-		 * Reshares for this user are shares where they are the owner.
713
-		 */
714
-		if ($reshares === false) {
715
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
716
-		} else {
717
-			if ($node === null) {
718
-				$qb->andWhere(
719
-					$qb->expr()->orX(
720
-						$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
721
-						$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
722
-					)
723
-				);
724
-			}
725
-		}
726
-
727
-		if ($node !== null) {
728
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
729
-		}
730
-
731
-		if ($limit !== -1) {
732
-			$qb->setMaxResults($limit);
733
-		}
734
-
735
-		$qb->setFirstResult($offset);
736
-		$qb->orderBy('id');
737
-
738
-		$cursor = $qb->execute();
739
-		$shares = [];
740
-		while($data = $cursor->fetch()) {
741
-			$shares[] = $this->createShare($data);
742
-		}
743
-		$cursor->closeCursor();
744
-
745
-		return $shares;
746
-	}
747
-
748
-	/**
749
-	 * @inheritdoc
750
-	 */
751
-	public function getShareById($id, $recipientId = null) {
752
-		$qb = $this->dbConn->getQueryBuilder();
753
-
754
-		$qb->select('*')
755
-			->from('share')
756
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
757
-			->andWhere(
758
-				$qb->expr()->in(
759
-					'share_type',
760
-					$qb->createNamedParameter([
761
-						\OCP\Share::SHARE_TYPE_USER,
762
-						\OCP\Share::SHARE_TYPE_GROUP,
763
-						\OCP\Share::SHARE_TYPE_LINK,
764
-					], IQueryBuilder::PARAM_INT_ARRAY)
765
-				)
766
-			)
767
-			->andWhere($qb->expr()->orX(
768
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
769
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
770
-			));
771
-
772
-		$cursor = $qb->execute();
773
-		$data = $cursor->fetch();
774
-		$cursor->closeCursor();
775
-
776
-		if ($data === false) {
777
-			throw new ShareNotFound();
778
-		}
779
-
780
-		try {
781
-			$share = $this->createShare($data);
782
-		} catch (InvalidShare $e) {
783
-			throw new ShareNotFound();
784
-		}
785
-
786
-		// If the recipient is set for a group share resolve to that user
787
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
788
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
789
-		}
790
-
791
-		return $share;
792
-	}
793
-
794
-	/**
795
-	 * Get shares for a given path
796
-	 *
797
-	 * @param \OCP\Files\Node $path
798
-	 * @return \OCP\Share\IShare[]
799
-	 */
800
-	public function getSharesByPath(Node $path) {
801
-		$qb = $this->dbConn->getQueryBuilder();
802
-
803
-		$cursor = $qb->select('*')
804
-			->from('share')
805
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
806
-			->andWhere(
807
-				$qb->expr()->orX(
808
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
809
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
810
-				)
811
-			)
812
-			->andWhere($qb->expr()->orX(
813
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
814
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
815
-			))
816
-			->execute();
817
-
818
-		$shares = [];
819
-		while($data = $cursor->fetch()) {
820
-			$shares[] = $this->createShare($data);
821
-		}
822
-		$cursor->closeCursor();
823
-
824
-		return $shares;
825
-	}
826
-
827
-	/**
828
-	 * Returns whether the given database result can be interpreted as
829
-	 * a share with accessible file (not trashed, not deleted)
830
-	 */
831
-	private function isAccessibleResult($data) {
832
-		// exclude shares leading to deleted file entries
833
-		if ($data['fileid'] === null) {
834
-			return false;
835
-		}
836
-
837
-		// exclude shares leading to trashbin on home storages
838
-		$pathSections = explode('/', $data['path'], 2);
839
-		// FIXME: would not detect rare md5'd home storage case properly
840
-		if ($pathSections[0] !== 'files'
841
-				&& in_array(explode(':', $data['storage_string_id'], 2)[0], ['home', 'object'])) {
842
-			return false;
843
-		}
844
-		return true;
845
-	}
846
-
847
-	/**
848
-	 * @inheritdoc
849
-	 */
850
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
851
-		/** @var Share[] $shares */
852
-		$shares = [];
853
-
854
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
855
-			//Get shares directly with this user
856
-			$qb = $this->dbConn->getQueryBuilder();
857
-			$qb->select('s.*',
858
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
859
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
860
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
861
-			)
862
-				->selectAlias('st.id', 'storage_string_id')
863
-				->from('share', 's')
864
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
865
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
866
-
867
-			// Order by id
868
-			$qb->orderBy('s.id');
869
-
870
-			// Set limit and offset
871
-			if ($limit !== -1) {
872
-				$qb->setMaxResults($limit);
873
-			}
874
-			$qb->setFirstResult($offset);
875
-
876
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
877
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
878
-				->andWhere($qb->expr()->orX(
879
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
880
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
881
-				));
882
-
883
-			// Filter by node if provided
884
-			if ($node !== null) {
885
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
886
-			}
887
-
888
-			$cursor = $qb->execute();
889
-
890
-			while($data = $cursor->fetch()) {
891
-				if ($this->isAccessibleResult($data)) {
892
-					$shares[] = $this->createShare($data);
893
-				}
894
-			}
895
-			$cursor->closeCursor();
896
-
897
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
898
-			$user = $this->userManager->get($userId);
899
-			$allGroups = $this->groupManager->getUserGroups($user);
900
-
901
-			/** @var Share[] $shares2 */
902
-			$shares2 = [];
903
-
904
-			$start = 0;
905
-			while(true) {
906
-				$groups = array_slice($allGroups, $start, 100);
907
-				$start += 100;
908
-
909
-				if ($groups === []) {
910
-					break;
911
-				}
912
-
913
-				$qb = $this->dbConn->getQueryBuilder();
914
-				$qb->select('s.*',
915
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
916
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
917
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
918
-				)
919
-					->selectAlias('st.id', 'storage_string_id')
920
-					->from('share', 's')
921
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
922
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
923
-					->orderBy('s.id')
924
-					->setFirstResult(0);
925
-
926
-				if ($limit !== -1) {
927
-					$qb->setMaxResults($limit - count($shares));
928
-				}
929
-
930
-				// Filter by node if provided
931
-				if ($node !== null) {
932
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
933
-				}
934
-
935
-
936
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
937
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
938
-
939
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
940
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
941
-						$groups,
942
-						IQueryBuilder::PARAM_STR_ARRAY
943
-					)))
944
-					->andWhere($qb->expr()->orX(
945
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
946
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
947
-					));
948
-
949
-				$cursor = $qb->execute();
950
-				while($data = $cursor->fetch()) {
951
-					if ($offset > 0) {
952
-						$offset--;
953
-						continue;
954
-					}
955
-
956
-					if ($this->isAccessibleResult($data)) {
957
-						$shares2[] = $this->createShare($data);
958
-					}
959
-				}
960
-				$cursor->closeCursor();
961
-			}
962
-
963
-			/*
505
+            if ($data === false) {
506
+                $id = $this->createUserSpecificGroupShare($share, $recipient);
507
+                $permissions = $share->getPermissions();
508
+            } else {
509
+                $permissions = $data['permissions'];
510
+                $id = $data['id'];
511
+            }
512
+
513
+            if ($permissions !== 0) {
514
+                // Update existing usergroup share
515
+                $qb = $this->dbConn->getQueryBuilder();
516
+                $qb->update('share')
517
+                    ->set('permissions', $qb->createNamedParameter(0))
518
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
519
+                    ->execute();
520
+            }
521
+
522
+        } else if ($share->getShareType() === IShare::TYPE_USER) {
523
+
524
+            if ($share->getSharedWith() !== $recipient) {
525
+                throw new ProviderException('Recipient does not match');
526
+            }
527
+
528
+            // We can just delete user and link shares
529
+            $this->delete($share);
530
+        } else {
531
+            throw new ProviderException('Invalid shareType');
532
+        }
533
+    }
534
+
535
+    protected function createUserSpecificGroupShare(IShare $share, string $recipient): int {
536
+        $type = $share->getNodeType();
537
+
538
+        $qb = $this->dbConn->getQueryBuilder();
539
+        $qb->insert('share')
540
+            ->values([
541
+                'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
542
+                'share_with' => $qb->createNamedParameter($recipient),
543
+                'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
544
+                'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
545
+                'parent' => $qb->createNamedParameter($share->getId()),
546
+                'item_type' => $qb->createNamedParameter($type),
547
+                'item_source' => $qb->createNamedParameter($share->getNodeId()),
548
+                'file_source' => $qb->createNamedParameter($share->getNodeId()),
549
+                'file_target' => $qb->createNamedParameter($share->getTarget()),
550
+                'permissions' => $qb->createNamedParameter($share->getPermissions()),
551
+                'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
552
+            ])->execute();
553
+
554
+        return $qb->getLastInsertId();
555
+    }
556
+
557
+    /**
558
+     * @inheritdoc
559
+     *
560
+     * For now this only works for group shares
561
+     * If this gets implemented for normal shares we have to extend it
562
+     */
563
+    public function restore(IShare $share, string $recipient): IShare {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+        $qb->select('permissions')
566
+            ->from('share')
567
+            ->where(
568
+                $qb->expr()->eq('id', $qb->createNamedParameter($share->getId()))
569
+            );
570
+        $cursor = $qb->execute();
571
+        $data = $cursor->fetch();
572
+        $cursor->closeCursor();
573
+
574
+        $originalPermission = $data['permissions'];
575
+
576
+        $qb = $this->dbConn->getQueryBuilder();
577
+        $qb->update('share')
578
+            ->set('permissions', $qb->createNamedParameter($originalPermission))
579
+            ->where(
580
+                $qb->expr()->eq('parent', $qb->createNamedParameter($share->getParent()))
581
+            )->andWhere(
582
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
583
+            )->andWhere(
584
+                $qb->expr()->eq('share_with', $qb->createNamedParameter($recipient))
585
+            );
586
+
587
+        $qb->execute();
588
+
589
+        return $this->getShareById($share->getId(), $recipient);
590
+    }
591
+
592
+    /**
593
+     * @inheritdoc
594
+     */
595
+    public function move(\OCP\Share\IShare $share, $recipient) {
596
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
597
+            // Just update the target
598
+            $qb = $this->dbConn->getQueryBuilder();
599
+            $qb->update('share')
600
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
601
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
602
+                ->execute();
603
+
604
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
605
+
606
+            // Check if there is a usergroup share
607
+            $qb = $this->dbConn->getQueryBuilder();
608
+            $stmt = $qb->select('id')
609
+                ->from('share')
610
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
611
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
612
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
613
+                ->andWhere($qb->expr()->orX(
614
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
615
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
616
+                ))
617
+                ->setMaxResults(1)
618
+                ->execute();
619
+
620
+            $data = $stmt->fetch();
621
+            $stmt->closeCursor();
622
+
623
+            if ($data === false) {
624
+                // No usergroup share yet. Create one.
625
+                $qb = $this->dbConn->getQueryBuilder();
626
+                $qb->insert('share')
627
+                    ->values([
628
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
629
+                        'share_with' => $qb->createNamedParameter($recipient),
630
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
631
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
632
+                        'parent' => $qb->createNamedParameter($share->getId()),
633
+                        'item_type' => $qb->createNamedParameter($share->getNodeType()),
634
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
635
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
636
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
637
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
638
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
639
+                    ])->execute();
640
+            } else {
641
+                // Already a usergroup share. Update it.
642
+                $qb = $this->dbConn->getQueryBuilder();
643
+                $qb->update('share')
644
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
645
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
646
+                    ->execute();
647
+            }
648
+        }
649
+
650
+        return $share;
651
+    }
652
+
653
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
654
+        $qb = $this->dbConn->getQueryBuilder();
655
+        $qb->select('*')
656
+            ->from('share', 's')
657
+            ->andWhere($qb->expr()->orX(
658
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
659
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
660
+            ));
661
+
662
+        $qb->andWhere($qb->expr()->orX(
663
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
664
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
665
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
666
+        ));
667
+
668
+        /**
669
+         * Reshares for this user are shares where they are the owner.
670
+         */
671
+        if ($reshares === false) {
672
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
673
+        } else {
674
+            $qb->andWhere(
675
+                $qb->expr()->orX(
676
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
677
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
678
+                )
679
+            );
680
+        }
681
+
682
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
683
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
684
+
685
+        $qb->orderBy('id');
686
+
687
+        $cursor = $qb->execute();
688
+        $shares = [];
689
+        while ($data = $cursor->fetch()) {
690
+            $shares[$data['fileid']][] = $this->createShare($data);
691
+        }
692
+        $cursor->closeCursor();
693
+
694
+        return $shares;
695
+    }
696
+
697
+    /**
698
+     * @inheritdoc
699
+     */
700
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
701
+        $qb = $this->dbConn->getQueryBuilder();
702
+        $qb->select('*')
703
+            ->from('share')
704
+            ->andWhere($qb->expr()->orX(
705
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
706
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
707
+            ));
708
+
709
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
710
+
711
+        /**
712
+         * Reshares for this user are shares where they are the owner.
713
+         */
714
+        if ($reshares === false) {
715
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
716
+        } else {
717
+            if ($node === null) {
718
+                $qb->andWhere(
719
+                    $qb->expr()->orX(
720
+                        $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
721
+                        $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
722
+                    )
723
+                );
724
+            }
725
+        }
726
+
727
+        if ($node !== null) {
728
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
729
+        }
730
+
731
+        if ($limit !== -1) {
732
+            $qb->setMaxResults($limit);
733
+        }
734
+
735
+        $qb->setFirstResult($offset);
736
+        $qb->orderBy('id');
737
+
738
+        $cursor = $qb->execute();
739
+        $shares = [];
740
+        while($data = $cursor->fetch()) {
741
+            $shares[] = $this->createShare($data);
742
+        }
743
+        $cursor->closeCursor();
744
+
745
+        return $shares;
746
+    }
747
+
748
+    /**
749
+     * @inheritdoc
750
+     */
751
+    public function getShareById($id, $recipientId = null) {
752
+        $qb = $this->dbConn->getQueryBuilder();
753
+
754
+        $qb->select('*')
755
+            ->from('share')
756
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
757
+            ->andWhere(
758
+                $qb->expr()->in(
759
+                    'share_type',
760
+                    $qb->createNamedParameter([
761
+                        \OCP\Share::SHARE_TYPE_USER,
762
+                        \OCP\Share::SHARE_TYPE_GROUP,
763
+                        \OCP\Share::SHARE_TYPE_LINK,
764
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
765
+                )
766
+            )
767
+            ->andWhere($qb->expr()->orX(
768
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
769
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
770
+            ));
771
+
772
+        $cursor = $qb->execute();
773
+        $data = $cursor->fetch();
774
+        $cursor->closeCursor();
775
+
776
+        if ($data === false) {
777
+            throw new ShareNotFound();
778
+        }
779
+
780
+        try {
781
+            $share = $this->createShare($data);
782
+        } catch (InvalidShare $e) {
783
+            throw new ShareNotFound();
784
+        }
785
+
786
+        // If the recipient is set for a group share resolve to that user
787
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
788
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
789
+        }
790
+
791
+        return $share;
792
+    }
793
+
794
+    /**
795
+     * Get shares for a given path
796
+     *
797
+     * @param \OCP\Files\Node $path
798
+     * @return \OCP\Share\IShare[]
799
+     */
800
+    public function getSharesByPath(Node $path) {
801
+        $qb = $this->dbConn->getQueryBuilder();
802
+
803
+        $cursor = $qb->select('*')
804
+            ->from('share')
805
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
806
+            ->andWhere(
807
+                $qb->expr()->orX(
808
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
809
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
810
+                )
811
+            )
812
+            ->andWhere($qb->expr()->orX(
813
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
814
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
815
+            ))
816
+            ->execute();
817
+
818
+        $shares = [];
819
+        while($data = $cursor->fetch()) {
820
+            $shares[] = $this->createShare($data);
821
+        }
822
+        $cursor->closeCursor();
823
+
824
+        return $shares;
825
+    }
826
+
827
+    /**
828
+     * Returns whether the given database result can be interpreted as
829
+     * a share with accessible file (not trashed, not deleted)
830
+     */
831
+    private function isAccessibleResult($data) {
832
+        // exclude shares leading to deleted file entries
833
+        if ($data['fileid'] === null) {
834
+            return false;
835
+        }
836
+
837
+        // exclude shares leading to trashbin on home storages
838
+        $pathSections = explode('/', $data['path'], 2);
839
+        // FIXME: would not detect rare md5'd home storage case properly
840
+        if ($pathSections[0] !== 'files'
841
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], ['home', 'object'])) {
842
+            return false;
843
+        }
844
+        return true;
845
+    }
846
+
847
+    /**
848
+     * @inheritdoc
849
+     */
850
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
851
+        /** @var Share[] $shares */
852
+        $shares = [];
853
+
854
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
855
+            //Get shares directly with this user
856
+            $qb = $this->dbConn->getQueryBuilder();
857
+            $qb->select('s.*',
858
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
859
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
860
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
861
+            )
862
+                ->selectAlias('st.id', 'storage_string_id')
863
+                ->from('share', 's')
864
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
865
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
866
+
867
+            // Order by id
868
+            $qb->orderBy('s.id');
869
+
870
+            // Set limit and offset
871
+            if ($limit !== -1) {
872
+                $qb->setMaxResults($limit);
873
+            }
874
+            $qb->setFirstResult($offset);
875
+
876
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
877
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
878
+                ->andWhere($qb->expr()->orX(
879
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
880
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
881
+                ));
882
+
883
+            // Filter by node if provided
884
+            if ($node !== null) {
885
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
886
+            }
887
+
888
+            $cursor = $qb->execute();
889
+
890
+            while($data = $cursor->fetch()) {
891
+                if ($this->isAccessibleResult($data)) {
892
+                    $shares[] = $this->createShare($data);
893
+                }
894
+            }
895
+            $cursor->closeCursor();
896
+
897
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
898
+            $user = $this->userManager->get($userId);
899
+            $allGroups = $this->groupManager->getUserGroups($user);
900
+
901
+            /** @var Share[] $shares2 */
902
+            $shares2 = [];
903
+
904
+            $start = 0;
905
+            while(true) {
906
+                $groups = array_slice($allGroups, $start, 100);
907
+                $start += 100;
908
+
909
+                if ($groups === []) {
910
+                    break;
911
+                }
912
+
913
+                $qb = $this->dbConn->getQueryBuilder();
914
+                $qb->select('s.*',
915
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
916
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
917
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
918
+                )
919
+                    ->selectAlias('st.id', 'storage_string_id')
920
+                    ->from('share', 's')
921
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
922
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
923
+                    ->orderBy('s.id')
924
+                    ->setFirstResult(0);
925
+
926
+                if ($limit !== -1) {
927
+                    $qb->setMaxResults($limit - count($shares));
928
+                }
929
+
930
+                // Filter by node if provided
931
+                if ($node !== null) {
932
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
933
+                }
934
+
935
+
936
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
937
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
938
+
939
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
940
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
941
+                        $groups,
942
+                        IQueryBuilder::PARAM_STR_ARRAY
943
+                    )))
944
+                    ->andWhere($qb->expr()->orX(
945
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
946
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
947
+                    ));
948
+
949
+                $cursor = $qb->execute();
950
+                while($data = $cursor->fetch()) {
951
+                    if ($offset > 0) {
952
+                        $offset--;
953
+                        continue;
954
+                    }
955
+
956
+                    if ($this->isAccessibleResult($data)) {
957
+                        $shares2[] = $this->createShare($data);
958
+                    }
959
+                }
960
+                $cursor->closeCursor();
961
+            }
962
+
963
+            /*
964 964
 			 * Resolve all group shares to user specific shares
965 965
 			 */
966
-			$shares = $this->resolveGroupShares($shares2, $userId);
967
-		} else {
968
-			throw new BackendError('Invalid backend');
969
-		}
970
-
971
-
972
-		return $shares;
973
-	}
974
-
975
-	/**
976
-	 * Get a share by token
977
-	 *
978
-	 * @param string $token
979
-	 * @return \OCP\Share\IShare
980
-	 * @throws ShareNotFound
981
-	 */
982
-	public function getShareByToken($token) {
983
-		$qb = $this->dbConn->getQueryBuilder();
984
-
985
-		$cursor = $qb->select('*')
986
-			->from('share')
987
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
988
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
989
-			->andWhere($qb->expr()->orX(
990
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
991
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
992
-			))
993
-			->execute();
994
-
995
-		$data = $cursor->fetch();
996
-
997
-		if ($data === false) {
998
-			throw new ShareNotFound();
999
-		}
1000
-
1001
-		try {
1002
-			$share = $this->createShare($data);
1003
-		} catch (InvalidShare $e) {
1004
-			throw new ShareNotFound();
1005
-		}
1006
-
1007
-		return $share;
1008
-	}
1009
-
1010
-	/**
1011
-	 * Create a share object from an database row
1012
-	 *
1013
-	 * @param mixed[] $data
1014
-	 * @return \OCP\Share\IShare
1015
-	 * @throws InvalidShare
1016
-	 */
1017
-	private function createShare($data) {
1018
-		$share = new Share($this->rootFolder, $this->userManager);
1019
-		$share->setId((int)$data['id'])
1020
-			->setShareType((int)$data['share_type'])
1021
-			->setPermissions((int)$data['permissions'])
1022
-			->setTarget($data['file_target'])
1023
-			->setNote($data['note'])
1024
-			->setMailSend((bool)$data['mail_send'])
1025
-			->setStatus((int)$data['accepted'])
1026
-			->setLabel($data['label']);
1027
-
1028
-		$shareTime = new \DateTime();
1029
-		$shareTime->setTimestamp((int)$data['stime']);
1030
-		$share->setShareTime($shareTime);
1031
-
1032
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1033
-			$share->setSharedWith($data['share_with']);
1034
-			$user = $this->userManager->get($data['share_with']);
1035
-			if ($user !== null) {
1036
-				$share->setSharedWithDisplayName($user->getDisplayName());
1037
-			}
1038
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1039
-			$share->setSharedWith($data['share_with']);
1040
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1041
-			$share->setPassword($data['password']);
1042
-			$share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1043
-			$share->setToken($data['token']);
1044
-		}
1045
-
1046
-		$share->setSharedBy($data['uid_initiator']);
1047
-		$share->setShareOwner($data['uid_owner']);
1048
-
1049
-		$share->setNodeId((int)$data['file_source']);
1050
-		$share->setNodeType($data['item_type']);
1051
-
1052
-		if ($data['expiration'] !== null) {
1053
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1054
-			$share->setExpirationDate($expiration);
1055
-		}
1056
-
1057
-		if (isset($data['f_permissions'])) {
1058
-			$entryData = $data;
1059
-			$entryData['permissions'] = $entryData['f_permissions'];
1060
-			$entryData['parent'] = $entryData['f_parent'];
1061
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
1062
-				\OC::$server->getMimeTypeLoader()));
1063
-		}
1064
-
1065
-		$share->setProviderId($this->identifier());
1066
-		$share->setHideDownload((int)$data['hide_download'] === 1);
1067
-
1068
-		return $share;
1069
-	}
1070
-
1071
-	/**
1072
-	 * @param Share[] $shares
1073
-	 * @param $userId
1074
-	 * @return Share[] The updates shares if no update is found for a share return the original
1075
-	 */
1076
-	private function resolveGroupShares($shares, $userId) {
1077
-		$result = [];
1078
-
1079
-		$start = 0;
1080
-		while(true) {
1081
-			/** @var Share[] $shareSlice */
1082
-			$shareSlice = array_slice($shares, $start, 100);
1083
-			$start += 100;
1084
-
1085
-			if ($shareSlice === []) {
1086
-				break;
1087
-			}
1088
-
1089
-			/** @var int[] $ids */
1090
-			$ids = [];
1091
-			/** @var Share[] $shareMap */
1092
-			$shareMap = [];
1093
-
1094
-			foreach ($shareSlice as $share) {
1095
-				$ids[] = (int)$share->getId();
1096
-				$shareMap[$share->getId()] = $share;
1097
-			}
1098
-
1099
-			$qb = $this->dbConn->getQueryBuilder();
1100
-
1101
-			$query = $qb->select('*')
1102
-				->from('share')
1103
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1104
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
1105
-				->andWhere($qb->expr()->orX(
1106
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
-				));
1109
-
1110
-			$stmt = $query->execute();
1111
-
1112
-			while($data = $stmt->fetch()) {
1113
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1114
-				$shareMap[$data['parent']]->setStatus((int)$data['accepted']);
1115
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
1116
-				$shareMap[$data['parent']]->setParent($data['parent']);
1117
-			}
1118
-
1119
-			$stmt->closeCursor();
1120
-
1121
-			foreach ($shareMap as $share) {
1122
-				$result[] = $share;
1123
-			}
1124
-		}
1125
-
1126
-		return $result;
1127
-	}
1128
-
1129
-	/**
1130
-	 * A user is deleted from the system
1131
-	 * So clean up the relevant shares.
1132
-	 *
1133
-	 * @param string $uid
1134
-	 * @param int $shareType
1135
-	 */
1136
-	public function userDeleted($uid, $shareType) {
1137
-		$qb = $this->dbConn->getQueryBuilder();
1138
-
1139
-		$qb->delete('share');
1140
-
1141
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1142
-			/*
966
+            $shares = $this->resolveGroupShares($shares2, $userId);
967
+        } else {
968
+            throw new BackendError('Invalid backend');
969
+        }
970
+
971
+
972
+        return $shares;
973
+    }
974
+
975
+    /**
976
+     * Get a share by token
977
+     *
978
+     * @param string $token
979
+     * @return \OCP\Share\IShare
980
+     * @throws ShareNotFound
981
+     */
982
+    public function getShareByToken($token) {
983
+        $qb = $this->dbConn->getQueryBuilder();
984
+
985
+        $cursor = $qb->select('*')
986
+            ->from('share')
987
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
988
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
989
+            ->andWhere($qb->expr()->orX(
990
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
991
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
992
+            ))
993
+            ->execute();
994
+
995
+        $data = $cursor->fetch();
996
+
997
+        if ($data === false) {
998
+            throw new ShareNotFound();
999
+        }
1000
+
1001
+        try {
1002
+            $share = $this->createShare($data);
1003
+        } catch (InvalidShare $e) {
1004
+            throw new ShareNotFound();
1005
+        }
1006
+
1007
+        return $share;
1008
+    }
1009
+
1010
+    /**
1011
+     * Create a share object from an database row
1012
+     *
1013
+     * @param mixed[] $data
1014
+     * @return \OCP\Share\IShare
1015
+     * @throws InvalidShare
1016
+     */
1017
+    private function createShare($data) {
1018
+        $share = new Share($this->rootFolder, $this->userManager);
1019
+        $share->setId((int)$data['id'])
1020
+            ->setShareType((int)$data['share_type'])
1021
+            ->setPermissions((int)$data['permissions'])
1022
+            ->setTarget($data['file_target'])
1023
+            ->setNote($data['note'])
1024
+            ->setMailSend((bool)$data['mail_send'])
1025
+            ->setStatus((int)$data['accepted'])
1026
+            ->setLabel($data['label']);
1027
+
1028
+        $shareTime = new \DateTime();
1029
+        $shareTime->setTimestamp((int)$data['stime']);
1030
+        $share->setShareTime($shareTime);
1031
+
1032
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1033
+            $share->setSharedWith($data['share_with']);
1034
+            $user = $this->userManager->get($data['share_with']);
1035
+            if ($user !== null) {
1036
+                $share->setSharedWithDisplayName($user->getDisplayName());
1037
+            }
1038
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1039
+            $share->setSharedWith($data['share_with']);
1040
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
1041
+            $share->setPassword($data['password']);
1042
+            $share->setSendPasswordByTalk((bool)$data['password_by_talk']);
1043
+            $share->setToken($data['token']);
1044
+        }
1045
+
1046
+        $share->setSharedBy($data['uid_initiator']);
1047
+        $share->setShareOwner($data['uid_owner']);
1048
+
1049
+        $share->setNodeId((int)$data['file_source']);
1050
+        $share->setNodeType($data['item_type']);
1051
+
1052
+        if ($data['expiration'] !== null) {
1053
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
1054
+            $share->setExpirationDate($expiration);
1055
+        }
1056
+
1057
+        if (isset($data['f_permissions'])) {
1058
+            $entryData = $data;
1059
+            $entryData['permissions'] = $entryData['f_permissions'];
1060
+            $entryData['parent'] = $entryData['f_parent'];
1061
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
1062
+                \OC::$server->getMimeTypeLoader()));
1063
+        }
1064
+
1065
+        $share->setProviderId($this->identifier());
1066
+        $share->setHideDownload((int)$data['hide_download'] === 1);
1067
+
1068
+        return $share;
1069
+    }
1070
+
1071
+    /**
1072
+     * @param Share[] $shares
1073
+     * @param $userId
1074
+     * @return Share[] The updates shares if no update is found for a share return the original
1075
+     */
1076
+    private function resolveGroupShares($shares, $userId) {
1077
+        $result = [];
1078
+
1079
+        $start = 0;
1080
+        while(true) {
1081
+            /** @var Share[] $shareSlice */
1082
+            $shareSlice = array_slice($shares, $start, 100);
1083
+            $start += 100;
1084
+
1085
+            if ($shareSlice === []) {
1086
+                break;
1087
+            }
1088
+
1089
+            /** @var int[] $ids */
1090
+            $ids = [];
1091
+            /** @var Share[] $shareMap */
1092
+            $shareMap = [];
1093
+
1094
+            foreach ($shareSlice as $share) {
1095
+                $ids[] = (int)$share->getId();
1096
+                $shareMap[$share->getId()] = $share;
1097
+            }
1098
+
1099
+            $qb = $this->dbConn->getQueryBuilder();
1100
+
1101
+            $query = $qb->select('*')
1102
+                ->from('share')
1103
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1104
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
1105
+                ->andWhere($qb->expr()->orX(
1106
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
+                ));
1109
+
1110
+            $stmt = $query->execute();
1111
+
1112
+            while($data = $stmt->fetch()) {
1113
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
1114
+                $shareMap[$data['parent']]->setStatus((int)$data['accepted']);
1115
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
1116
+                $shareMap[$data['parent']]->setParent($data['parent']);
1117
+            }
1118
+
1119
+            $stmt->closeCursor();
1120
+
1121
+            foreach ($shareMap as $share) {
1122
+                $result[] = $share;
1123
+            }
1124
+        }
1125
+
1126
+        return $result;
1127
+    }
1128
+
1129
+    /**
1130
+     * A user is deleted from the system
1131
+     * So clean up the relevant shares.
1132
+     *
1133
+     * @param string $uid
1134
+     * @param int $shareType
1135
+     */
1136
+    public function userDeleted($uid, $shareType) {
1137
+        $qb = $this->dbConn->getQueryBuilder();
1138
+
1139
+        $qb->delete('share');
1140
+
1141
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
1142
+            /*
1143 1143
 			 * Delete all user shares that are owned by this user
1144 1144
 			 * or that are received by this user
1145 1145
 			 */
1146 1146
 
1147
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1147
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
1148 1148
 
1149
-			$qb->andWhere(
1150
-				$qb->expr()->orX(
1151
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1152
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1153
-				)
1154
-			);
1155
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1156
-			/*
1149
+            $qb->andWhere(
1150
+                $qb->expr()->orX(
1151
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1152
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1153
+                )
1154
+            );
1155
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
1156
+            /*
1157 1157
 			 * Delete all group shares that are owned by this user
1158 1158
 			 * Or special user group shares that are received by this user
1159 1159
 			 */
1160
-			$qb->where(
1161
-				$qb->expr()->andX(
1162
-					$qb->expr()->orX(
1163
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1164
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1165
-					),
1166
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1167
-				)
1168
-			);
1169
-
1170
-			$qb->orWhere(
1171
-				$qb->expr()->andX(
1172
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1173
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1174
-				)
1175
-			);
1176
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1177
-			/*
1160
+            $qb->where(
1161
+                $qb->expr()->andX(
1162
+                    $qb->expr()->orX(
1163
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1164
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
1165
+                    ),
1166
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
1167
+                )
1168
+            );
1169
+
1170
+            $qb->orWhere(
1171
+                $qb->expr()->andX(
1172
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
1173
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
1174
+                )
1175
+            );
1176
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
1177
+            /*
1178 1178
 			 * Delete all link shares owned by this user.
1179 1179
 			 * And all link shares initiated by this user (until #22327 is in)
1180 1180
 			 */
1181
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1182
-
1183
-			$qb->andWhere(
1184
-				$qb->expr()->orX(
1185
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1186
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1187
-				)
1188
-			);
1189
-		} else {
1190
-			\OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType));
1191
-			return;
1192
-		}
1193
-
1194
-		$qb->execute();
1195
-	}
1196
-
1197
-	/**
1198
-	 * Delete all shares received by this group. As well as any custom group
1199
-	 * shares for group members.
1200
-	 *
1201
-	 * @param string $gid
1202
-	 */
1203
-	public function groupDeleted($gid) {
1204
-		/*
1181
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
1182
+
1183
+            $qb->andWhere(
1184
+                $qb->expr()->orX(
1185
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
1186
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
1187
+                )
1188
+            );
1189
+        } else {
1190
+            \OC::$server->getLogger()->logException(new \InvalidArgumentException('Default share provider tried to delete all shares for type: ' . $shareType));
1191
+            return;
1192
+        }
1193
+
1194
+        $qb->execute();
1195
+    }
1196
+
1197
+    /**
1198
+     * Delete all shares received by this group. As well as any custom group
1199
+     * shares for group members.
1200
+     *
1201
+     * @param string $gid
1202
+     */
1203
+    public function groupDeleted($gid) {
1204
+        /*
1205 1205
 		 * First delete all custom group shares for group members
1206 1206
 		 */
1207
-		$qb = $this->dbConn->getQueryBuilder();
1208
-		$qb->select('id')
1209
-			->from('share')
1210
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1211
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1212
-
1213
-		$cursor = $qb->execute();
1214
-		$ids = [];
1215
-		while($row = $cursor->fetch()) {
1216
-			$ids[] = (int)$row['id'];
1217
-		}
1218
-		$cursor->closeCursor();
1219
-
1220
-		if (!empty($ids)) {
1221
-			$chunks = array_chunk($ids, 100);
1222
-			foreach ($chunks as $chunk) {
1223
-				$qb->delete('share')
1224
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1225
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1226
-				$qb->execute();
1227
-			}
1228
-		}
1229
-
1230
-		/*
1207
+        $qb = $this->dbConn->getQueryBuilder();
1208
+        $qb->select('id')
1209
+            ->from('share')
1210
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1211
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1212
+
1213
+        $cursor = $qb->execute();
1214
+        $ids = [];
1215
+        while($row = $cursor->fetch()) {
1216
+            $ids[] = (int)$row['id'];
1217
+        }
1218
+        $cursor->closeCursor();
1219
+
1220
+        if (!empty($ids)) {
1221
+            $chunks = array_chunk($ids, 100);
1222
+            foreach ($chunks as $chunk) {
1223
+                $qb->delete('share')
1224
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1225
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1226
+                $qb->execute();
1227
+            }
1228
+        }
1229
+
1230
+        /*
1231 1231
 		 * Now delete all the group shares
1232 1232
 		 */
1233
-		$qb = $this->dbConn->getQueryBuilder();
1234
-		$qb->delete('share')
1235
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1236
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1237
-		$qb->execute();
1238
-	}
1239
-
1240
-	/**
1241
-	 * Delete custom group shares to this group for this user
1242
-	 *
1243
-	 * @param string $uid
1244
-	 * @param string $gid
1245
-	 */
1246
-	public function userDeletedFromGroup($uid, $gid) {
1247
-		/*
1233
+        $qb = $this->dbConn->getQueryBuilder();
1234
+        $qb->delete('share')
1235
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1236
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1237
+        $qb->execute();
1238
+    }
1239
+
1240
+    /**
1241
+     * Delete custom group shares to this group for this user
1242
+     *
1243
+     * @param string $uid
1244
+     * @param string $gid
1245
+     */
1246
+    public function userDeletedFromGroup($uid, $gid) {
1247
+        /*
1248 1248
 		 * Get all group shares
1249 1249
 		 */
1250
-		$qb = $this->dbConn->getQueryBuilder();
1251
-		$qb->select('id')
1252
-			->from('share')
1253
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1254
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1255
-
1256
-		$cursor = $qb->execute();
1257
-		$ids = [];
1258
-		while($row = $cursor->fetch()) {
1259
-			$ids[] = (int)$row['id'];
1260
-		}
1261
-		$cursor->closeCursor();
1262
-
1263
-		if (!empty($ids)) {
1264
-			$chunks = array_chunk($ids, 100);
1265
-			foreach ($chunks as $chunk) {
1266
-				/*
1250
+        $qb = $this->dbConn->getQueryBuilder();
1251
+        $qb->select('id')
1252
+            ->from('share')
1253
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1254
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1255
+
1256
+        $cursor = $qb->execute();
1257
+        $ids = [];
1258
+        while($row = $cursor->fetch()) {
1259
+            $ids[] = (int)$row['id'];
1260
+        }
1261
+        $cursor->closeCursor();
1262
+
1263
+        if (!empty($ids)) {
1264
+            $chunks = array_chunk($ids, 100);
1265
+            foreach ($chunks as $chunk) {
1266
+                /*
1267 1267
 				 * Delete all special shares wit this users for the found group shares
1268 1268
 				 */
1269
-				$qb->delete('share')
1270
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1271
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1272
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1273
-				$qb->execute();
1274
-			}
1275
-		}
1276
-	}
1277
-
1278
-	/**
1279
-	 * @inheritdoc
1280
-	 */
1281
-	public function getAccessList($nodes, $currentAccess) {
1282
-		$ids = [];
1283
-		foreach ($nodes as $node) {
1284
-			$ids[] = $node->getId();
1285
-		}
1286
-
1287
-		$qb = $this->dbConn->getQueryBuilder();
1288
-
1289
-		$or = $qb->expr()->orX(
1290
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1291
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1292
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1293
-		);
1294
-
1295
-		if ($currentAccess) {
1296
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1297
-		}
1298
-
1299
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1300
-			->from('share')
1301
-			->where(
1302
-				$or
1303
-			)
1304
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1305
-			->andWhere($qb->expr()->orX(
1306
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1307
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1308
-			));
1309
-		$cursor = $qb->execute();
1310
-
1311
-		$users = [];
1312
-		$link = false;
1313
-		while($row = $cursor->fetch()) {
1314
-			$type = (int)$row['share_type'];
1315
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1316
-				$uid = $row['share_with'];
1317
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1318
-				$users[$uid][$row['id']] = $row;
1319
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1320
-				$gid = $row['share_with'];
1321
-				$group = $this->groupManager->get($gid);
1322
-
1323
-				if ($group === null) {
1324
-					continue;
1325
-				}
1326
-
1327
-				$userList = $group->getUsers();
1328
-				foreach ($userList as $user) {
1329
-					$uid = $user->getUID();
1330
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1331
-					$users[$uid][$row['id']] = $row;
1332
-				}
1333
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1334
-				$link = true;
1335
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1336
-				$uid = $row['share_with'];
1337
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1338
-				$users[$uid][$row['id']] = $row;
1339
-			}
1340
-		}
1341
-		$cursor->closeCursor();
1342
-
1343
-		if ($currentAccess === true) {
1344
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1345
-			$users = array_filter($users);
1346
-		} else {
1347
-			$users = array_keys($users);
1348
-		}
1349
-
1350
-		return ['users' => $users, 'public' => $link];
1351
-	}
1352
-
1353
-	/**
1354
-	 * For each user the path with the fewest slashes is returned
1355
-	 * @param array $shares
1356
-	 * @return array
1357
-	 */
1358
-	protected function filterSharesOfUser(array $shares) {
1359
-		// Group shares when the user has a share exception
1360
-		foreach ($shares as $id => $share) {
1361
-			$type = (int) $share['share_type'];
1362
-			$permissions = (int) $share['permissions'];
1363
-
1364
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1365
-				unset($shares[$share['parent']]);
1366
-
1367
-				if ($permissions === 0) {
1368
-					unset($shares[$id]);
1369
-				}
1370
-			}
1371
-		}
1372
-
1373
-		$best = [];
1374
-		$bestDepth = 0;
1375
-		foreach ($shares as $id => $share) {
1376
-			$depth = substr_count($share['file_target'], '/');
1377
-			if (empty($best) || $depth < $bestDepth) {
1378
-				$bestDepth = $depth;
1379
-				$best = [
1380
-					'node_id' => $share['file_source'],
1381
-					'node_path' => $share['file_target'],
1382
-				];
1383
-			}
1384
-		}
1385
-
1386
-		return $best;
1387
-	}
1388
-
1389
-	/**
1390
-	 * propagate notes to the recipients
1391
-	 *
1392
-	 * @param IShare $share
1393
-	 * @throws \OCP\Files\NotFoundException
1394
-	 */
1395
-	private function propagateNote(IShare $share) {
1396
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1397
-			$user = $this->userManager->get($share->getSharedWith());
1398
-			$this->sendNote([$user], $share);
1399
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1400
-			$group = $this->groupManager->get($share->getSharedWith());
1401
-			$groupMembers = $group->getUsers();
1402
-			$this->sendNote($groupMembers, $share);
1403
-		}
1404
-	}
1405
-
1406
-	/**
1407
-	 * send note by mail
1408
-	 *
1409
-	 * @param array $recipients
1410
-	 * @param IShare $share
1411
-	 * @throws \OCP\Files\NotFoundException
1412
-	 */
1413
-	private function sendNote(array $recipients, IShare $share) {
1414
-
1415
-		$toList = [];
1416
-
1417
-		foreach ($recipients as $recipient) {
1418
-			/** @var IUser $recipient */
1419
-			$email = $recipient->getEMailAddress();
1420
-			if ($email) {
1421
-				$toList[$email] = $recipient->getDisplayName();
1422
-			}
1423
-		}
1424
-
1425
-		if (!empty($toList)) {
1426
-
1427
-			$filename = $share->getNode()->getName();
1428
-			$initiator = $share->getSharedBy();
1429
-			$note = $share->getNote();
1430
-
1431
-			$initiatorUser = $this->userManager->get($initiator);
1432
-			$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1433
-			$initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1434
-			$plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1435
-			$htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1436
-			$message = $this->mailer->createMessage();
1437
-
1438
-			$emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1439
-
1440
-			$emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1441
-			$emailTemplate->addHeader();
1442
-			$emailTemplate->addHeading($htmlHeading, $plainHeading);
1443
-			$emailTemplate->addBodyText(htmlspecialchars($note), $note);
1444
-
1445
-			$link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1446
-			$emailTemplate->addBodyButton(
1447
-				$this->l->t('Open »%s«', [$filename]),
1448
-				$link
1449
-			);
1450
-
1451
-
1452
-			// The "From" contains the sharers name
1453
-			$instanceName = $this->defaults->getName();
1454
-			$senderName = $this->l->t(
1455
-				'%1$s via %2$s',
1456
-				[
1457
-					$initiatorDisplayName,
1458
-					$instanceName
1459
-				]
1460
-			);
1461
-			$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1462
-			if ($initiatorEmailAddress !== null) {
1463
-				$message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1464
-				$emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1465
-			} else {
1466
-				$emailTemplate->addFooter();
1467
-			}
1468
-
1469
-			if (count($toList) === 1) {
1470
-				$message->setTo($toList);
1471
-			} else {
1472
-				$message->setTo([]);
1473
-				$message->setBcc($toList);
1474
-			}
1475
-			$message->useTemplate($emailTemplate);
1476
-			$this->mailer->send($message);
1477
-		}
1478
-
1479
-	}
1480
-
1481
-	public function getAllShares(): iterable {
1482
-		$qb = $this->dbConn->getQueryBuilder();
1483
-
1484
-		$qb->select('*')
1485
-			->from('share')
1486
-			->where(
1487
-				$qb->expr()->orX(
1488
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
1489
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
1490
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
1491
-				)
1492
-			);
1493
-
1494
-		$cursor = $qb->execute();
1495
-		while($data = $cursor->fetch()) {
1496
-			try {
1497
-				$share = $this->createShare($data);
1498
-			} catch (InvalidShare $e) {
1499
-				continue;
1500
-			}
1501
-
1502
-			yield $share;
1503
-		}
1504
-		$cursor->closeCursor();
1505
-	}
1269
+                $qb->delete('share')
1270
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1271
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1272
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1273
+                $qb->execute();
1274
+            }
1275
+        }
1276
+    }
1277
+
1278
+    /**
1279
+     * @inheritdoc
1280
+     */
1281
+    public function getAccessList($nodes, $currentAccess) {
1282
+        $ids = [];
1283
+        foreach ($nodes as $node) {
1284
+            $ids[] = $node->getId();
1285
+        }
1286
+
1287
+        $qb = $this->dbConn->getQueryBuilder();
1288
+
1289
+        $or = $qb->expr()->orX(
1290
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1291
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1292
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1293
+        );
1294
+
1295
+        if ($currentAccess) {
1296
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1297
+        }
1298
+
1299
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1300
+            ->from('share')
1301
+            ->where(
1302
+                $or
1303
+            )
1304
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1305
+            ->andWhere($qb->expr()->orX(
1306
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1307
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1308
+            ));
1309
+        $cursor = $qb->execute();
1310
+
1311
+        $users = [];
1312
+        $link = false;
1313
+        while($row = $cursor->fetch()) {
1314
+            $type = (int)$row['share_type'];
1315
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1316
+                $uid = $row['share_with'];
1317
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1318
+                $users[$uid][$row['id']] = $row;
1319
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1320
+                $gid = $row['share_with'];
1321
+                $group = $this->groupManager->get($gid);
1322
+
1323
+                if ($group === null) {
1324
+                    continue;
1325
+                }
1326
+
1327
+                $userList = $group->getUsers();
1328
+                foreach ($userList as $user) {
1329
+                    $uid = $user->getUID();
1330
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1331
+                    $users[$uid][$row['id']] = $row;
1332
+                }
1333
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1334
+                $link = true;
1335
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1336
+                $uid = $row['share_with'];
1337
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1338
+                $users[$uid][$row['id']] = $row;
1339
+            }
1340
+        }
1341
+        $cursor->closeCursor();
1342
+
1343
+        if ($currentAccess === true) {
1344
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1345
+            $users = array_filter($users);
1346
+        } else {
1347
+            $users = array_keys($users);
1348
+        }
1349
+
1350
+        return ['users' => $users, 'public' => $link];
1351
+    }
1352
+
1353
+    /**
1354
+     * For each user the path with the fewest slashes is returned
1355
+     * @param array $shares
1356
+     * @return array
1357
+     */
1358
+    protected function filterSharesOfUser(array $shares) {
1359
+        // Group shares when the user has a share exception
1360
+        foreach ($shares as $id => $share) {
1361
+            $type = (int) $share['share_type'];
1362
+            $permissions = (int) $share['permissions'];
1363
+
1364
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1365
+                unset($shares[$share['parent']]);
1366
+
1367
+                if ($permissions === 0) {
1368
+                    unset($shares[$id]);
1369
+                }
1370
+            }
1371
+        }
1372
+
1373
+        $best = [];
1374
+        $bestDepth = 0;
1375
+        foreach ($shares as $id => $share) {
1376
+            $depth = substr_count($share['file_target'], '/');
1377
+            if (empty($best) || $depth < $bestDepth) {
1378
+                $bestDepth = $depth;
1379
+                $best = [
1380
+                    'node_id' => $share['file_source'],
1381
+                    'node_path' => $share['file_target'],
1382
+                ];
1383
+            }
1384
+        }
1385
+
1386
+        return $best;
1387
+    }
1388
+
1389
+    /**
1390
+     * propagate notes to the recipients
1391
+     *
1392
+     * @param IShare $share
1393
+     * @throws \OCP\Files\NotFoundException
1394
+     */
1395
+    private function propagateNote(IShare $share) {
1396
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
1397
+            $user = $this->userManager->get($share->getSharedWith());
1398
+            $this->sendNote([$user], $share);
1399
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
1400
+            $group = $this->groupManager->get($share->getSharedWith());
1401
+            $groupMembers = $group->getUsers();
1402
+            $this->sendNote($groupMembers, $share);
1403
+        }
1404
+    }
1405
+
1406
+    /**
1407
+     * send note by mail
1408
+     *
1409
+     * @param array $recipients
1410
+     * @param IShare $share
1411
+     * @throws \OCP\Files\NotFoundException
1412
+     */
1413
+    private function sendNote(array $recipients, IShare $share) {
1414
+
1415
+        $toList = [];
1416
+
1417
+        foreach ($recipients as $recipient) {
1418
+            /** @var IUser $recipient */
1419
+            $email = $recipient->getEMailAddress();
1420
+            if ($email) {
1421
+                $toList[$email] = $recipient->getDisplayName();
1422
+            }
1423
+        }
1424
+
1425
+        if (!empty($toList)) {
1426
+
1427
+            $filename = $share->getNode()->getName();
1428
+            $initiator = $share->getSharedBy();
1429
+            $note = $share->getNote();
1430
+
1431
+            $initiatorUser = $this->userManager->get($initiator);
1432
+            $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
1433
+            $initiatorEmailAddress = ($initiatorUser instanceof IUser) ? $initiatorUser->getEMailAddress() : null;
1434
+            $plainHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add:', [$initiatorDisplayName, $filename]);
1435
+            $htmlHeading = $this->l->t('%1$s shared »%2$s« with you and wants to add', [$initiatorDisplayName, $filename]);
1436
+            $message = $this->mailer->createMessage();
1437
+
1438
+            $emailTemplate = $this->mailer->createEMailTemplate('defaultShareProvider.sendNote');
1439
+
1440
+            $emailTemplate->setSubject($this->l->t('»%s« added a note to a file shared with you', [$initiatorDisplayName]));
1441
+            $emailTemplate->addHeader();
1442
+            $emailTemplate->addHeading($htmlHeading, $plainHeading);
1443
+            $emailTemplate->addBodyText(htmlspecialchars($note), $note);
1444
+
1445
+            $link = $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]);
1446
+            $emailTemplate->addBodyButton(
1447
+                $this->l->t('Open »%s«', [$filename]),
1448
+                $link
1449
+            );
1450
+
1451
+
1452
+            // The "From" contains the sharers name
1453
+            $instanceName = $this->defaults->getName();
1454
+            $senderName = $this->l->t(
1455
+                '%1$s via %2$s',
1456
+                [
1457
+                    $initiatorDisplayName,
1458
+                    $instanceName
1459
+                ]
1460
+            );
1461
+            $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
1462
+            if ($initiatorEmailAddress !== null) {
1463
+                $message->setReplyTo([$initiatorEmailAddress => $initiatorDisplayName]);
1464
+                $emailTemplate->addFooter($instanceName . ' - ' . $this->defaults->getSlogan());
1465
+            } else {
1466
+                $emailTemplate->addFooter();
1467
+            }
1468
+
1469
+            if (count($toList) === 1) {
1470
+                $message->setTo($toList);
1471
+            } else {
1472
+                $message->setTo([]);
1473
+                $message->setBcc($toList);
1474
+            }
1475
+            $message->useTemplate($emailTemplate);
1476
+            $this->mailer->send($message);
1477
+        }
1478
+
1479
+    }
1480
+
1481
+    public function getAllShares(): iterable {
1482
+        $qb = $this->dbConn->getQueryBuilder();
1483
+
1484
+        $qb->select('*')
1485
+            ->from('share')
1486
+            ->where(
1487
+                $qb->expr()->orX(
1488
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_USER)),
1489
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_GROUP)),
1490
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share\IShare::TYPE_LINK))
1491
+                )
1492
+            );
1493
+
1494
+        $cursor = $qb->execute();
1495
+        while($data = $cursor->fetch()) {
1496
+            try {
1497
+                $share = $this->createShare($data);
1498
+            } catch (InvalidShare $e) {
1499
+                continue;
1500
+            }
1501
+
1502
+            yield $share;
1503
+        }
1504
+        $cursor->closeCursor();
1505
+    }
1506 1506
 }
Please login to merge, or discard this patch.
lib/private/Comments/Comment.php 1 patch
Indentation   +422 added lines, -422 removed lines patch added patch discarded remove patch
@@ -31,426 +31,426 @@
 block discarded – undo
31 31
 
32 32
 class Comment implements IComment {
33 33
 
34
-	protected $data = [
35
-		'id'              => '',
36
-		'parentId'        => '0',
37
-		'topmostParentId' => '0',
38
-		'childrenCount'   => '0',
39
-		'message'         => '',
40
-		'verb'            => '',
41
-		'actorType'       => '',
42
-		'actorId'         => '',
43
-		'objectType'      => '',
44
-		'objectId'        => '',
45
-		'referenceId'     => null,
46
-		'creationDT'      => null,
47
-		'latestChildDT'   => null,
48
-	];
49
-
50
-	/**
51
-	 * Comment constructor.
52
-	 *
53
-	 * @param array $data	optional, array with keys according to column names from
54
-	 * 						the comments database scheme
55
-	 */
56
-	public function __construct(array $data = null) {
57
-		if(is_array($data)) {
58
-			$this->fromArray($data);
59
-		}
60
-	}
61
-
62
-	/**
63
-	 * returns the ID of the comment
64
-	 *
65
-	 * It may return an empty string, if the comment was not stored.
66
-	 * It is expected that the concrete Comment implementation gives an ID
67
-	 * by itself (e.g. after saving).
68
-	 *
69
-	 * @return string
70
-	 * @since 9.0.0
71
-	 */
72
-	public function getId() {
73
-		return $this->data['id'];
74
-	}
75
-
76
-	/**
77
-	 * sets the ID of the comment and returns itself
78
-	 *
79
-	 * It is only allowed to set the ID only, if the current id is an empty
80
-	 * string (which means it is not stored in a database, storage or whatever
81
-	 * the concrete implementation does), or vice versa. Changing a given ID is
82
-	 * not permitted and must result in an IllegalIDChangeException.
83
-	 *
84
-	 * @param string $id
85
-	 * @return IComment
86
-	 * @throws IllegalIDChangeException
87
-	 * @since 9.0.0
88
-	 */
89
-	public function setId($id) {
90
-		if(!is_string($id)) {
91
-			throw new \InvalidArgumentException('String expected.');
92
-		}
93
-
94
-		$id = trim($id);
95
-		if($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) {
96
-			$this->data['id'] = $id;
97
-			return $this;
98
-		}
99
-
100
-		throw new IllegalIDChangeException('Not allowed to assign a new ID to an already saved comment.');
101
-	}
102
-
103
-	/**
104
-	 * returns the parent ID of the comment
105
-	 *
106
-	 * @return string
107
-	 * @since 9.0.0
108
-	 */
109
-	public function getParentId() {
110
-		return $this->data['parentId'];
111
-	}
112
-
113
-	/**
114
-	 * sets the parent ID and returns itself
115
-	 *
116
-	 * @param string $parentId
117
-	 * @return IComment
118
-	 * @since 9.0.0
119
-	 */
120
-	public function setParentId($parentId) {
121
-		if(!is_string($parentId)) {
122
-			throw new \InvalidArgumentException('String expected.');
123
-		}
124
-		$this->data['parentId'] = trim($parentId);
125
-		return $this;
126
-	}
127
-
128
-	/**
129
-	 * returns the topmost parent ID of the comment
130
-	 *
131
-	 * @return string
132
-	 * @since 9.0.0
133
-	 */
134
-	public function getTopmostParentId() {
135
-		return $this->data['topmostParentId'];
136
-	}
137
-
138
-
139
-	/**
140
-	 * sets the topmost parent ID and returns itself
141
-	 *
142
-	 * @param string $id
143
-	 * @return IComment
144
-	 * @since 9.0.0
145
-	 */
146
-	public function setTopmostParentId($id) {
147
-		if(!is_string($id)) {
148
-			throw new \InvalidArgumentException('String expected.');
149
-		}
150
-		$this->data['topmostParentId'] = trim($id);
151
-		return $this;
152
-	}
153
-
154
-	/**
155
-	 * returns the number of children
156
-	 *
157
-	 * @return int
158
-	 * @since 9.0.0
159
-	 */
160
-	public function getChildrenCount() {
161
-		return $this->data['childrenCount'];
162
-	}
163
-
164
-	/**
165
-	 * sets the number of children
166
-	 *
167
-	 * @param int $count
168
-	 * @return IComment
169
-	 * @since 9.0.0
170
-	 */
171
-	public function setChildrenCount($count) {
172
-		if(!is_int($count)) {
173
-			throw new \InvalidArgumentException('Integer expected.');
174
-		}
175
-		$this->data['childrenCount'] = $count;
176
-		return $this;
177
-	}
178
-
179
-	/**
180
-	 * returns the message of the comment
181
-	 *
182
-	 * @return string
183
-	 * @since 9.0.0
184
-	 */
185
-	public function getMessage() {
186
-		return $this->data['message'];
187
-	}
188
-
189
-	/**
190
-	 * sets the message of the comment and returns itself
191
-	 *
192
-	 * @param string $message
193
-	 * @param int $maxLength
194
-	 * @return IComment
195
-	 * @throws MessageTooLongException
196
-	 * @since 9.0.0
197
-	 */
198
-	public function setMessage($message, $maxLength = self::MAX_MESSAGE_LENGTH) {
199
-		if(!is_string($message)) {
200
-			throw new \InvalidArgumentException('String expected.');
201
-		}
202
-		$message = trim($message);
203
-		if ($maxLength && mb_strlen($message, 'UTF-8') > $maxLength) {
204
-			throw new MessageTooLongException('Comment message must not exceed ' . $maxLength. ' characters');
205
-		}
206
-		$this->data['message'] = $message;
207
-		return $this;
208
-	}
209
-
210
-	/**
211
-	 * returns an array containing mentions that are included in the comment
212
-	 *
213
-	 * @return array each mention provides a 'type' and an 'id', see example below
214
-	 * @since 11.0.0
215
-	 *
216
-	 * The return array looks like:
217
-	 * [
218
-	 *   [
219
-	 *     'type' => 'user',
220
-	 *     'id' => 'citizen4'
221
-	 *   ],
222
-	 *   [
223
-	 *     'type' => 'group',
224
-	 *     'id' => 'media'
225
-	 *   ],
226
-	 *   …
227
-	 * ]
228
-	 *
229
-	 */
230
-	public function getMentions() {
231
-		$ok = preg_match_all("/\B(?<![^a-z0-9_\-@\.\'\s])@(\"guest\/[a-f0-9]+\"|\"[a-z0-9_\-@\.\' ]+\"|[a-z0-9_\-@\.\']+)/i", $this->getMessage(), $mentions);
232
-		if(!$ok || !isset($mentions[0]) || !is_array($mentions[0])) {
233
-			return [];
234
-		}
235
-		$uids = array_unique($mentions[0]);
236
-		$result = [];
237
-		foreach ($uids as $uid) {
238
-			$cleanUid = trim(substr($uid, 1), '"');
239
-			if (strpos($cleanUid, 'guest/') === 0) {
240
-				$result[] = ['type' => 'guest', 'id' => $cleanUid];
241
-			} else {
242
-				$result[] = ['type' => 'user', 'id' => $cleanUid];
243
-			}
244
-		}
245
-		return $result;
246
-	}
247
-
248
-	/**
249
-	 * returns the verb of the comment
250
-	 *
251
-	 * @return string
252
-	 * @since 9.0.0
253
-	 */
254
-	public function getVerb() {
255
-		return $this->data['verb'];
256
-	}
257
-
258
-	/**
259
-	 * sets the verb of the comment, e.g. 'comment' or 'like'
260
-	 *
261
-	 * @param string $verb
262
-	 * @return IComment
263
-	 * @since 9.0.0
264
-	 */
265
-	public function setVerb($verb) {
266
-		if(!is_string($verb) || !trim($verb)) {
267
-			throw new \InvalidArgumentException('Non-empty String expected.');
268
-		}
269
-		$this->data['verb'] = trim($verb);
270
-		return $this;
271
-	}
272
-
273
-	/**
274
-	 * returns the actor type
275
-	 *
276
-	 * @return string
277
-	 * @since 9.0.0
278
-	 */
279
-	public function getActorType() {
280
-		return $this->data['actorType'];
281
-	}
282
-
283
-	/**
284
-	 * returns the actor ID
285
-	 *
286
-	 * @return string
287
-	 * @since 9.0.0
288
-	 */
289
-	public function getActorId() {
290
-		return $this->data['actorId'];
291
-	}
292
-
293
-	/**
294
-	 * sets (overwrites) the actor type and id
295
-	 *
296
-	 * @param string $actorType e.g. 'users'
297
-	 * @param string $actorId e.g. 'zombie234'
298
-	 * @return IComment
299
-	 * @since 9.0.0
300
-	 */
301
-	public function setActor($actorType, $actorId) {
302
-		if(
303
-			   !is_string($actorType) || !trim($actorType)
304
-			|| !is_string($actorId)   || $actorId === ''
305
-		) {
306
-			throw new \InvalidArgumentException('String expected.');
307
-		}
308
-		$this->data['actorType'] = trim($actorType);
309
-		$this->data['actorId']   = $actorId;
310
-		return $this;
311
-	}
312
-
313
-	/**
314
-	 * returns the creation date of the comment.
315
-	 *
316
-	 * If not explicitly set, it shall default to the time of initialization.
317
-	 *
318
-	 * @return \DateTime
319
-	 * @since 9.0.0
320
-	 */
321
-	public function getCreationDateTime() {
322
-		return $this->data['creationDT'];
323
-	}
324
-
325
-	/**
326
-	 * sets the creation date of the comment and returns itself
327
-	 *
328
-	 * @param \DateTime $timestamp
329
-	 * @return IComment
330
-	 * @since 9.0.0
331
-	 */
332
-	public function setCreationDateTime(\DateTime $timestamp) {
333
-		$this->data['creationDT'] = $timestamp;
334
-		return $this;
335
-	}
336
-
337
-	/**
338
-	 * returns the DateTime of the most recent child, if set, otherwise null
339
-	 *
340
-	 * @return \DateTime|null
341
-	 * @since 9.0.0
342
-	 */
343
-	public function getLatestChildDateTime() {
344
-		return $this->data['latestChildDT'];
345
-	}
346
-
347
-	/**
348
-	 * sets the date of the most recent child
349
-	 *
350
-	 * @param \DateTime $dateTime
351
-	 * @return IComment
352
-	 * @since 9.0.0
353
-	 */
354
-	public function setLatestChildDateTime(\DateTime $dateTime = null) {
355
-		$this->data['latestChildDT'] = $dateTime;
356
-		return $this;
357
-	}
358
-
359
-	/**
360
-	 * returns the object type the comment is attached to
361
-	 *
362
-	 * @return string
363
-	 * @since 9.0.0
364
-	 */
365
-	public function getObjectType() {
366
-		return $this->data['objectType'];
367
-	}
368
-
369
-	/**
370
-	 * returns the object id the comment is attached to
371
-	 *
372
-	 * @return string
373
-	 * @since 9.0.0
374
-	 */
375
-	public function getObjectId() {
376
-		return $this->data['objectId'];
377
-	}
378
-
379
-	/**
380
-	 * sets (overwrites) the object of the comment
381
-	 *
382
-	 * @param string $objectType e.g. 'files'
383
-	 * @param string $objectId e.g. '16435'
384
-	 * @return IComment
385
-	 * @since 9.0.0
386
-	 */
387
-	public function setObject($objectType, $objectId) {
388
-		if(
389
-			   !is_string($objectType) || !trim($objectType)
390
-			|| !is_string($objectId)   || trim($objectId) === ''
391
-		) {
392
-			throw new \InvalidArgumentException('String expected.');
393
-		}
394
-		$this->data['objectType'] = trim($objectType);
395
-		$this->data['objectId']   = trim($objectId);
396
-		return $this;
397
-	}
398
-
399
-	/**
400
-	 * returns the reference id of the comment
401
-	 *
402
-	 * @return string|null
403
-	 * @since 19.0.0
404
-	 */
405
-	public function getReferenceId(): ?string {
406
-		return $this->data['referenceId'];
407
-	}
408
-
409
-	/**
410
-	 * sets (overwrites) the reference id of the comment
411
-	 *
412
-	 * @param string $referenceId e.g. sha256 hash sum
413
-	 * @return IComment
414
-	 * @since 19.0.0
415
-	 */
416
-	public function setReferenceId(?string $referenceId): IComment {
417
-		if ($referenceId === null) {
418
-			$this->data['referenceId'] = $referenceId;
419
-		} else {
420
-			$referenceId = trim($referenceId);
421
-			if ($referenceId === '') {
422
-				throw new \InvalidArgumentException('Non empty string expected.');
423
-			}
424
-			$this->data['referenceId'] = $referenceId;
425
-		}
426
-		return $this;
427
-	}
428
-
429
-	/**
430
-	 * sets the comment data based on an array with keys as taken from the
431
-	 * database.
432
-	 *
433
-	 * @param array $data
434
-	 * @return IComment
435
-	 */
436
-	protected function fromArray($data) {
437
-		foreach(array_keys($data) as $key) {
438
-			// translate DB keys to internal setter names
439
-			$setter = 'set' . implode('', array_map('ucfirst', explode('_', $key)));
440
-			$setter = str_replace('Timestamp', 'DateTime', $setter);
441
-
442
-			if(method_exists($this, $setter)) {
443
-				$this->$setter($data[$key]);
444
-			}
445
-		}
446
-
447
-		foreach(['actor', 'object'] as $role) {
448
-			if(isset($data[$role . '_type']) && isset($data[$role . '_id'])) {
449
-				$setter = 'set' . ucfirst($role);
450
-				$this->$setter($data[$role . '_type'], $data[$role . '_id']);
451
-			}
452
-		}
453
-
454
-		return $this;
455
-	}
34
+    protected $data = [
35
+        'id'              => '',
36
+        'parentId'        => '0',
37
+        'topmostParentId' => '0',
38
+        'childrenCount'   => '0',
39
+        'message'         => '',
40
+        'verb'            => '',
41
+        'actorType'       => '',
42
+        'actorId'         => '',
43
+        'objectType'      => '',
44
+        'objectId'        => '',
45
+        'referenceId'     => null,
46
+        'creationDT'      => null,
47
+        'latestChildDT'   => null,
48
+    ];
49
+
50
+    /**
51
+     * Comment constructor.
52
+     *
53
+     * @param array $data	optional, array with keys according to column names from
54
+     * 						the comments database scheme
55
+     */
56
+    public function __construct(array $data = null) {
57
+        if(is_array($data)) {
58
+            $this->fromArray($data);
59
+        }
60
+    }
61
+
62
+    /**
63
+     * returns the ID of the comment
64
+     *
65
+     * It may return an empty string, if the comment was not stored.
66
+     * It is expected that the concrete Comment implementation gives an ID
67
+     * by itself (e.g. after saving).
68
+     *
69
+     * @return string
70
+     * @since 9.0.0
71
+     */
72
+    public function getId() {
73
+        return $this->data['id'];
74
+    }
75
+
76
+    /**
77
+     * sets the ID of the comment and returns itself
78
+     *
79
+     * It is only allowed to set the ID only, if the current id is an empty
80
+     * string (which means it is not stored in a database, storage or whatever
81
+     * the concrete implementation does), or vice versa. Changing a given ID is
82
+     * not permitted and must result in an IllegalIDChangeException.
83
+     *
84
+     * @param string $id
85
+     * @return IComment
86
+     * @throws IllegalIDChangeException
87
+     * @since 9.0.0
88
+     */
89
+    public function setId($id) {
90
+        if(!is_string($id)) {
91
+            throw new \InvalidArgumentException('String expected.');
92
+        }
93
+
94
+        $id = trim($id);
95
+        if($this->data['id'] === '' || ($this->data['id'] !== '' && $id === '')) {
96
+            $this->data['id'] = $id;
97
+            return $this;
98
+        }
99
+
100
+        throw new IllegalIDChangeException('Not allowed to assign a new ID to an already saved comment.');
101
+    }
102
+
103
+    /**
104
+     * returns the parent ID of the comment
105
+     *
106
+     * @return string
107
+     * @since 9.0.0
108
+     */
109
+    public function getParentId() {
110
+        return $this->data['parentId'];
111
+    }
112
+
113
+    /**
114
+     * sets the parent ID and returns itself
115
+     *
116
+     * @param string $parentId
117
+     * @return IComment
118
+     * @since 9.0.0
119
+     */
120
+    public function setParentId($parentId) {
121
+        if(!is_string($parentId)) {
122
+            throw new \InvalidArgumentException('String expected.');
123
+        }
124
+        $this->data['parentId'] = trim($parentId);
125
+        return $this;
126
+    }
127
+
128
+    /**
129
+     * returns the topmost parent ID of the comment
130
+     *
131
+     * @return string
132
+     * @since 9.0.0
133
+     */
134
+    public function getTopmostParentId() {
135
+        return $this->data['topmostParentId'];
136
+    }
137
+
138
+
139
+    /**
140
+     * sets the topmost parent ID and returns itself
141
+     *
142
+     * @param string $id
143
+     * @return IComment
144
+     * @since 9.0.0
145
+     */
146
+    public function setTopmostParentId($id) {
147
+        if(!is_string($id)) {
148
+            throw new \InvalidArgumentException('String expected.');
149
+        }
150
+        $this->data['topmostParentId'] = trim($id);
151
+        return $this;
152
+    }
153
+
154
+    /**
155
+     * returns the number of children
156
+     *
157
+     * @return int
158
+     * @since 9.0.0
159
+     */
160
+    public function getChildrenCount() {
161
+        return $this->data['childrenCount'];
162
+    }
163
+
164
+    /**
165
+     * sets the number of children
166
+     *
167
+     * @param int $count
168
+     * @return IComment
169
+     * @since 9.0.0
170
+     */
171
+    public function setChildrenCount($count) {
172
+        if(!is_int($count)) {
173
+            throw new \InvalidArgumentException('Integer expected.');
174
+        }
175
+        $this->data['childrenCount'] = $count;
176
+        return $this;
177
+    }
178
+
179
+    /**
180
+     * returns the message of the comment
181
+     *
182
+     * @return string
183
+     * @since 9.0.0
184
+     */
185
+    public function getMessage() {
186
+        return $this->data['message'];
187
+    }
188
+
189
+    /**
190
+     * sets the message of the comment and returns itself
191
+     *
192
+     * @param string $message
193
+     * @param int $maxLength
194
+     * @return IComment
195
+     * @throws MessageTooLongException
196
+     * @since 9.0.0
197
+     */
198
+    public function setMessage($message, $maxLength = self::MAX_MESSAGE_LENGTH) {
199
+        if(!is_string($message)) {
200
+            throw new \InvalidArgumentException('String expected.');
201
+        }
202
+        $message = trim($message);
203
+        if ($maxLength && mb_strlen($message, 'UTF-8') > $maxLength) {
204
+            throw new MessageTooLongException('Comment message must not exceed ' . $maxLength. ' characters');
205
+        }
206
+        $this->data['message'] = $message;
207
+        return $this;
208
+    }
209
+
210
+    /**
211
+     * returns an array containing mentions that are included in the comment
212
+     *
213
+     * @return array each mention provides a 'type' and an 'id', see example below
214
+     * @since 11.0.0
215
+     *
216
+     * The return array looks like:
217
+     * [
218
+     *   [
219
+     *     'type' => 'user',
220
+     *     'id' => 'citizen4'
221
+     *   ],
222
+     *   [
223
+     *     'type' => 'group',
224
+     *     'id' => 'media'
225
+     *   ],
226
+     *   …
227
+     * ]
228
+     *
229
+     */
230
+    public function getMentions() {
231
+        $ok = preg_match_all("/\B(?<![^a-z0-9_\-@\.\'\s])@(\"guest\/[a-f0-9]+\"|\"[a-z0-9_\-@\.\' ]+\"|[a-z0-9_\-@\.\']+)/i", $this->getMessage(), $mentions);
232
+        if(!$ok || !isset($mentions[0]) || !is_array($mentions[0])) {
233
+            return [];
234
+        }
235
+        $uids = array_unique($mentions[0]);
236
+        $result = [];
237
+        foreach ($uids as $uid) {
238
+            $cleanUid = trim(substr($uid, 1), '"');
239
+            if (strpos($cleanUid, 'guest/') === 0) {
240
+                $result[] = ['type' => 'guest', 'id' => $cleanUid];
241
+            } else {
242
+                $result[] = ['type' => 'user', 'id' => $cleanUid];
243
+            }
244
+        }
245
+        return $result;
246
+    }
247
+
248
+    /**
249
+     * returns the verb of the comment
250
+     *
251
+     * @return string
252
+     * @since 9.0.0
253
+     */
254
+    public function getVerb() {
255
+        return $this->data['verb'];
256
+    }
257
+
258
+    /**
259
+     * sets the verb of the comment, e.g. 'comment' or 'like'
260
+     *
261
+     * @param string $verb
262
+     * @return IComment
263
+     * @since 9.0.0
264
+     */
265
+    public function setVerb($verb) {
266
+        if(!is_string($verb) || !trim($verb)) {
267
+            throw new \InvalidArgumentException('Non-empty String expected.');
268
+        }
269
+        $this->data['verb'] = trim($verb);
270
+        return $this;
271
+    }
272
+
273
+    /**
274
+     * returns the actor type
275
+     *
276
+     * @return string
277
+     * @since 9.0.0
278
+     */
279
+    public function getActorType() {
280
+        return $this->data['actorType'];
281
+    }
282
+
283
+    /**
284
+     * returns the actor ID
285
+     *
286
+     * @return string
287
+     * @since 9.0.0
288
+     */
289
+    public function getActorId() {
290
+        return $this->data['actorId'];
291
+    }
292
+
293
+    /**
294
+     * sets (overwrites) the actor type and id
295
+     *
296
+     * @param string $actorType e.g. 'users'
297
+     * @param string $actorId e.g. 'zombie234'
298
+     * @return IComment
299
+     * @since 9.0.0
300
+     */
301
+    public function setActor($actorType, $actorId) {
302
+        if(
303
+                !is_string($actorType) || !trim($actorType)
304
+            || !is_string($actorId)   || $actorId === ''
305
+        ) {
306
+            throw new \InvalidArgumentException('String expected.');
307
+        }
308
+        $this->data['actorType'] = trim($actorType);
309
+        $this->data['actorId']   = $actorId;
310
+        return $this;
311
+    }
312
+
313
+    /**
314
+     * returns the creation date of the comment.
315
+     *
316
+     * If not explicitly set, it shall default to the time of initialization.
317
+     *
318
+     * @return \DateTime
319
+     * @since 9.0.0
320
+     */
321
+    public function getCreationDateTime() {
322
+        return $this->data['creationDT'];
323
+    }
324
+
325
+    /**
326
+     * sets the creation date of the comment and returns itself
327
+     *
328
+     * @param \DateTime $timestamp
329
+     * @return IComment
330
+     * @since 9.0.0
331
+     */
332
+    public function setCreationDateTime(\DateTime $timestamp) {
333
+        $this->data['creationDT'] = $timestamp;
334
+        return $this;
335
+    }
336
+
337
+    /**
338
+     * returns the DateTime of the most recent child, if set, otherwise null
339
+     *
340
+     * @return \DateTime|null
341
+     * @since 9.0.0
342
+     */
343
+    public function getLatestChildDateTime() {
344
+        return $this->data['latestChildDT'];
345
+    }
346
+
347
+    /**
348
+     * sets the date of the most recent child
349
+     *
350
+     * @param \DateTime $dateTime
351
+     * @return IComment
352
+     * @since 9.0.0
353
+     */
354
+    public function setLatestChildDateTime(\DateTime $dateTime = null) {
355
+        $this->data['latestChildDT'] = $dateTime;
356
+        return $this;
357
+    }
358
+
359
+    /**
360
+     * returns the object type the comment is attached to
361
+     *
362
+     * @return string
363
+     * @since 9.0.0
364
+     */
365
+    public function getObjectType() {
366
+        return $this->data['objectType'];
367
+    }
368
+
369
+    /**
370
+     * returns the object id the comment is attached to
371
+     *
372
+     * @return string
373
+     * @since 9.0.0
374
+     */
375
+    public function getObjectId() {
376
+        return $this->data['objectId'];
377
+    }
378
+
379
+    /**
380
+     * sets (overwrites) the object of the comment
381
+     *
382
+     * @param string $objectType e.g. 'files'
383
+     * @param string $objectId e.g. '16435'
384
+     * @return IComment
385
+     * @since 9.0.0
386
+     */
387
+    public function setObject($objectType, $objectId) {
388
+        if(
389
+                !is_string($objectType) || !trim($objectType)
390
+            || !is_string($objectId)   || trim($objectId) === ''
391
+        ) {
392
+            throw new \InvalidArgumentException('String expected.');
393
+        }
394
+        $this->data['objectType'] = trim($objectType);
395
+        $this->data['objectId']   = trim($objectId);
396
+        return $this;
397
+    }
398
+
399
+    /**
400
+     * returns the reference id of the comment
401
+     *
402
+     * @return string|null
403
+     * @since 19.0.0
404
+     */
405
+    public function getReferenceId(): ?string {
406
+        return $this->data['referenceId'];
407
+    }
408
+
409
+    /**
410
+     * sets (overwrites) the reference id of the comment
411
+     *
412
+     * @param string $referenceId e.g. sha256 hash sum
413
+     * @return IComment
414
+     * @since 19.0.0
415
+     */
416
+    public function setReferenceId(?string $referenceId): IComment {
417
+        if ($referenceId === null) {
418
+            $this->data['referenceId'] = $referenceId;
419
+        } else {
420
+            $referenceId = trim($referenceId);
421
+            if ($referenceId === '') {
422
+                throw new \InvalidArgumentException('Non empty string expected.');
423
+            }
424
+            $this->data['referenceId'] = $referenceId;
425
+        }
426
+        return $this;
427
+    }
428
+
429
+    /**
430
+     * sets the comment data based on an array with keys as taken from the
431
+     * database.
432
+     *
433
+     * @param array $data
434
+     * @return IComment
435
+     */
436
+    protected function fromArray($data) {
437
+        foreach(array_keys($data) as $key) {
438
+            // translate DB keys to internal setter names
439
+            $setter = 'set' . implode('', array_map('ucfirst', explode('_', $key)));
440
+            $setter = str_replace('Timestamp', 'DateTime', $setter);
441
+
442
+            if(method_exists($this, $setter)) {
443
+                $this->$setter($data[$key]);
444
+            }
445
+        }
446
+
447
+        foreach(['actor', 'object'] as $role) {
448
+            if(isset($data[$role . '_type']) && isset($data[$role . '_id'])) {
449
+                $setter = 'set' . ucfirst($role);
450
+                $this->$setter($data[$role . '_type'], $data[$role . '_id']);
451
+            }
452
+        }
453
+
454
+        return $this;
455
+    }
456 456
 }
Please login to merge, or discard this patch.
lib/private/Authentication/TwoFactorAuth/Manager.php 1 patch
Indentation   +334 added lines, -334 removed lines patch added patch discarded remove patch
@@ -47,342 +47,342 @@
 block discarded – undo
47 47
 
48 48
 class Manager {
49 49
 
50
-	const SESSION_UID_KEY = 'two_factor_auth_uid';
51
-	const SESSION_UID_DONE = 'two_factor_auth_passed';
52
-	const REMEMBER_LOGIN = 'two_factor_remember_login';
53
-	const BACKUP_CODES_PROVIDER_ID = 'backup_codes';
54
-
55
-	/** @var ProviderLoader */
56
-	private $providerLoader;
57
-
58
-	/** @var IRegistry */
59
-	private $providerRegistry;
60
-
61
-	/** @var MandatoryTwoFactor */
62
-	private $mandatoryTwoFactor;
63
-
64
-	/** @var ISession */
65
-	private $session;
66
-
67
-	/** @var IConfig */
68
-	private $config;
69
-
70
-	/** @var IManager */
71
-	private $activityManager;
72
-
73
-	/** @var ILogger */
74
-	private $logger;
75
-
76
-	/** @var TokenProvider */
77
-	private $tokenProvider;
78
-
79
-	/** @var ITimeFactory */
80
-	private $timeFactory;
81
-
82
-	/** @var EventDispatcherInterface */
83
-	private $dispatcher;
84
-
85
-	public function __construct(ProviderLoader $providerLoader,
86
-								IRegistry $providerRegistry,
87
-								MandatoryTwoFactor $mandatoryTwoFactor,
88
-								ISession $session, IConfig $config,
89
-								IManager $activityManager, ILogger $logger, TokenProvider $tokenProvider,
90
-								ITimeFactory $timeFactory, EventDispatcherInterface $eventDispatcher) {
91
-		$this->providerLoader = $providerLoader;
92
-		$this->providerRegistry = $providerRegistry;
93
-		$this->mandatoryTwoFactor = $mandatoryTwoFactor;
94
-		$this->session = $session;
95
-		$this->config = $config;
96
-		$this->activityManager = $activityManager;
97
-		$this->logger = $logger;
98
-		$this->tokenProvider = $tokenProvider;
99
-		$this->timeFactory = $timeFactory;
100
-		$this->dispatcher = $eventDispatcher;
101
-	}
102
-
103
-	/**
104
-	 * Determine whether the user must provide a second factor challenge
105
-	 *
106
-	 * @param IUser $user
107
-	 * @return boolean
108
-	 */
109
-	public function isTwoFactorAuthenticated(IUser $user): bool {
110
-		if ($this->mandatoryTwoFactor->isEnforcedFor($user)) {
111
-			return true;
112
-		}
113
-
114
-		$providerStates = $this->providerRegistry->getProviderStates($user);
115
-		$providers = $this->providerLoader->getProviders($user);
116
-		$fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
117
-		$enabled = array_filter($fixedStates);
118
-		$providerIds = array_keys($enabled);
119
-		$providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);
120
-
121
-		return !empty($providerIdsWithoutBackupCodes);
122
-	}
123
-
124
-	/**
125
-	 * Get a 2FA provider by its ID
126
-	 *
127
-	 * @param IUser $user
128
-	 * @param string $challengeProviderId
129
-	 * @return IProvider|null
130
-	 */
131
-	public function getProvider(IUser $user, string $challengeProviderId) {
132
-		$providers = $this->getProviderSet($user)->getProviders();
133
-		return $providers[$challengeProviderId] ?? null;
134
-	}
135
-
136
-	/**
137
-	 * @param IUser $user
138
-	 * @return IActivatableAtLogin[]
139
-	 * @throws Exception
140
-	 */
141
-	public function getLoginSetupProviders(IUser $user): array {
142
-		$providers = $this->providerLoader->getProviders($user);
143
-		return array_filter($providers, function(IProvider $provider) {
144
-			return ($provider instanceof IActivatableAtLogin);
145
-		});
146
-	}
147
-
148
-	/**
149
-	 * Check if the persistant mapping of enabled/disabled state of each available
150
-	 * provider is missing an entry and add it to the registry in that case.
151
-	 *
152
-	 * @todo remove in Nextcloud 17 as by then all providers should have been updated
153
-	 *
154
-	 * @param string[] $providerStates
155
-	 * @param IProvider[] $providers
156
-	 * @param IUser $user
157
-	 * @return string[] the updated $providerStates variable
158
-	 */
159
-	private function fixMissingProviderStates(array $providerStates,
160
-		array $providers, IUser $user): array {
161
-
162
-		foreach ($providers as $provider) {
163
-			if (isset($providerStates[$provider->getId()])) {
164
-				// All good
165
-				continue;
166
-			}
167
-
168
-			$enabled = $provider->isTwoFactorAuthEnabledForUser($user);
169
-			if ($enabled) {
170
-				$this->providerRegistry->enableProviderFor($provider, $user);
171
-			} else {
172
-				$this->providerRegistry->disableProviderFor($provider, $user);
173
-			}
174
-			$providerStates[$provider->getId()] = $enabled;
175
-		}
176
-
177
-		return $providerStates;
178
-	}
179
-
180
-	/**
181
-	 * @param array $states
182
-	 * @param IProvider[] $providers
183
-	 */
184
-	private function isProviderMissing(array $states, array $providers): bool {
185
-		$indexed = [];
186
-		foreach ($providers as $provider) {
187
-			$indexed[$provider->getId()] = $provider;
188
-		}
189
-
190
-		$missing = [];
191
-		foreach ($states as $providerId => $enabled) {
192
-			if (!$enabled) {
193
-				// Don't care
194
-				continue;
195
-			}
196
-
197
-			if (!isset($indexed[$providerId])) {
198
-				$missing[] = $providerId;
199
-				$this->logger->alert("two-factor auth provider '$providerId' failed to load",
200
-					[
201
-						'app' => 'core',
202
-					]);
203
-			}
204
-		}
205
-
206
-		if (!empty($missing)) {
207
-			// There was at least one provider missing
208
-			$this->logger->alert(count($missing) . " two-factor auth providers failed to load", ['app' => 'core']);
209
-
210
-			return true;
211
-		}
212
-
213
-		// If we reach this, there was not a single provider missing
214
-		return false;
215
-	}
216
-
217
-	/**
218
-	 * Get the list of 2FA providers for the given user
219
-	 *
220
-	 * @param IUser $user
221
-	 * @throws Exception
222
-	 */
223
-	public function getProviderSet(IUser $user): ProviderSet {
224
-		$providerStates = $this->providerRegistry->getProviderStates($user);
225
-		$providers = $this->providerLoader->getProviders($user);
226
-
227
-		$fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
228
-		$isProviderMissing = $this->isProviderMissing($fixedStates, $providers);
229
-
230
-		$enabled = array_filter($providers, function (IProvider $provider) use ($fixedStates) {
231
-			return $fixedStates[$provider->getId()];
232
-		});
233
-		return new ProviderSet($enabled, $isProviderMissing);
234
-	}
235
-
236
-	/**
237
-	 * Verify the given challenge
238
-	 *
239
-	 * @param string $providerId
240
-	 * @param IUser $user
241
-	 * @param string $challenge
242
-	 * @return boolean
243
-	 */
244
-	public function verifyChallenge(string $providerId, IUser $user, string $challenge): bool {
245
-		$provider = $this->getProvider($user, $providerId);
246
-		if ($provider === null) {
247
-			return false;
248
-		}
249
-
250
-		$passed = $provider->verifyChallenge($user, $challenge);
251
-		if ($passed) {
252
-			if ($this->session->get(self::REMEMBER_LOGIN) === true) {
253
-				// TODO: resolve cyclic dependency and use DI
254
-				\OC::$server->getUserSession()->createRememberMeToken($user);
255
-			}
256
-			$this->session->remove(self::SESSION_UID_KEY);
257
-			$this->session->remove(self::REMEMBER_LOGIN);
258
-			$this->session->set(self::SESSION_UID_DONE, $user->getUID());
259
-
260
-			// Clear token from db
261
-			$sessionId = $this->session->getId();
262
-			$token = $this->tokenProvider->getToken($sessionId);
263
-			$tokenId = $token->getId();
264
-			$this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $tokenId);
265
-
266
-			$dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
267
-			$this->dispatcher->dispatch(IProvider::EVENT_SUCCESS, $dispatchEvent);
268
-
269
-			$this->publishEvent($user, 'twofactor_success', [
270
-				'provider' => $provider->getDisplayName(),
271
-			]);
272
-		} else {
273
-			$dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
274
-			$this->dispatcher->dispatch(IProvider::EVENT_FAILED, $dispatchEvent);
275
-
276
-			$this->publishEvent($user, 'twofactor_failed', [
277
-				'provider' => $provider->getDisplayName(),
278
-			]);
279
-		}
280
-		return $passed;
281
-	}
282
-
283
-	/**
284
-	 * Push a 2fa event the user's activity stream
285
-	 *
286
-	 * @param IUser $user
287
-	 * @param string $event
288
-	 * @param array $params
289
-	 */
290
-	private function publishEvent(IUser $user, string $event, array $params) {
291
-		$activity = $this->activityManager->generateEvent();
292
-		$activity->setApp('core')
293
-			->setType('security')
294
-			->setAuthor($user->getUID())
295
-			->setAffectedUser($user->getUID())
296
-			->setSubject($event, $params);
297
-		try {
298
-			$this->activityManager->publish($activity);
299
-		} catch (BadMethodCallException $e) {
300
-			$this->logger->warning('could not publish activity', ['app' => 'core']);
301
-			$this->logger->logException($e, ['app' => 'core']);
302
-		}
303
-	}
304
-
305
-	/**
306
-	 * Check if the currently logged in user needs to pass 2FA
307
-	 *
308
-	 * @param IUser $user the currently logged in user
309
-	 * @return boolean
310
-	 */
311
-	public function needsSecondFactor(IUser $user = null): bool {
312
-		if ($user === null) {
313
-			return false;
314
-		}
315
-
316
-		// If we are authenticated using an app password skip all this
317
-		if ($this->session->exists('app_password')) {
318
-			return false;
319
-		}
320
-
321
-		// First check if the session tells us we should do 2FA (99% case)
322
-		if (!$this->session->exists(self::SESSION_UID_KEY)) {
323
-
324
-			// Check if the session tells us it is 2FA authenticated already
325
-			if ($this->session->exists(self::SESSION_UID_DONE) &&
326
-				$this->session->get(self::SESSION_UID_DONE) === $user->getUID()) {
327
-				return false;
328
-			}
329
-
330
-			/*
50
+    const SESSION_UID_KEY = 'two_factor_auth_uid';
51
+    const SESSION_UID_DONE = 'two_factor_auth_passed';
52
+    const REMEMBER_LOGIN = 'two_factor_remember_login';
53
+    const BACKUP_CODES_PROVIDER_ID = 'backup_codes';
54
+
55
+    /** @var ProviderLoader */
56
+    private $providerLoader;
57
+
58
+    /** @var IRegistry */
59
+    private $providerRegistry;
60
+
61
+    /** @var MandatoryTwoFactor */
62
+    private $mandatoryTwoFactor;
63
+
64
+    /** @var ISession */
65
+    private $session;
66
+
67
+    /** @var IConfig */
68
+    private $config;
69
+
70
+    /** @var IManager */
71
+    private $activityManager;
72
+
73
+    /** @var ILogger */
74
+    private $logger;
75
+
76
+    /** @var TokenProvider */
77
+    private $tokenProvider;
78
+
79
+    /** @var ITimeFactory */
80
+    private $timeFactory;
81
+
82
+    /** @var EventDispatcherInterface */
83
+    private $dispatcher;
84
+
85
+    public function __construct(ProviderLoader $providerLoader,
86
+                                IRegistry $providerRegistry,
87
+                                MandatoryTwoFactor $mandatoryTwoFactor,
88
+                                ISession $session, IConfig $config,
89
+                                IManager $activityManager, ILogger $logger, TokenProvider $tokenProvider,
90
+                                ITimeFactory $timeFactory, EventDispatcherInterface $eventDispatcher) {
91
+        $this->providerLoader = $providerLoader;
92
+        $this->providerRegistry = $providerRegistry;
93
+        $this->mandatoryTwoFactor = $mandatoryTwoFactor;
94
+        $this->session = $session;
95
+        $this->config = $config;
96
+        $this->activityManager = $activityManager;
97
+        $this->logger = $logger;
98
+        $this->tokenProvider = $tokenProvider;
99
+        $this->timeFactory = $timeFactory;
100
+        $this->dispatcher = $eventDispatcher;
101
+    }
102
+
103
+    /**
104
+     * Determine whether the user must provide a second factor challenge
105
+     *
106
+     * @param IUser $user
107
+     * @return boolean
108
+     */
109
+    public function isTwoFactorAuthenticated(IUser $user): bool {
110
+        if ($this->mandatoryTwoFactor->isEnforcedFor($user)) {
111
+            return true;
112
+        }
113
+
114
+        $providerStates = $this->providerRegistry->getProviderStates($user);
115
+        $providers = $this->providerLoader->getProviders($user);
116
+        $fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
117
+        $enabled = array_filter($fixedStates);
118
+        $providerIds = array_keys($enabled);
119
+        $providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);
120
+
121
+        return !empty($providerIdsWithoutBackupCodes);
122
+    }
123
+
124
+    /**
125
+     * Get a 2FA provider by its ID
126
+     *
127
+     * @param IUser $user
128
+     * @param string $challengeProviderId
129
+     * @return IProvider|null
130
+     */
131
+    public function getProvider(IUser $user, string $challengeProviderId) {
132
+        $providers = $this->getProviderSet($user)->getProviders();
133
+        return $providers[$challengeProviderId] ?? null;
134
+    }
135
+
136
+    /**
137
+     * @param IUser $user
138
+     * @return IActivatableAtLogin[]
139
+     * @throws Exception
140
+     */
141
+    public function getLoginSetupProviders(IUser $user): array {
142
+        $providers = $this->providerLoader->getProviders($user);
143
+        return array_filter($providers, function(IProvider $provider) {
144
+            return ($provider instanceof IActivatableAtLogin);
145
+        });
146
+    }
147
+
148
+    /**
149
+     * Check if the persistant mapping of enabled/disabled state of each available
150
+     * provider is missing an entry and add it to the registry in that case.
151
+     *
152
+     * @todo remove in Nextcloud 17 as by then all providers should have been updated
153
+     *
154
+     * @param string[] $providerStates
155
+     * @param IProvider[] $providers
156
+     * @param IUser $user
157
+     * @return string[] the updated $providerStates variable
158
+     */
159
+    private function fixMissingProviderStates(array $providerStates,
160
+        array $providers, IUser $user): array {
161
+
162
+        foreach ($providers as $provider) {
163
+            if (isset($providerStates[$provider->getId()])) {
164
+                // All good
165
+                continue;
166
+            }
167
+
168
+            $enabled = $provider->isTwoFactorAuthEnabledForUser($user);
169
+            if ($enabled) {
170
+                $this->providerRegistry->enableProviderFor($provider, $user);
171
+            } else {
172
+                $this->providerRegistry->disableProviderFor($provider, $user);
173
+            }
174
+            $providerStates[$provider->getId()] = $enabled;
175
+        }
176
+
177
+        return $providerStates;
178
+    }
179
+
180
+    /**
181
+     * @param array $states
182
+     * @param IProvider[] $providers
183
+     */
184
+    private function isProviderMissing(array $states, array $providers): bool {
185
+        $indexed = [];
186
+        foreach ($providers as $provider) {
187
+            $indexed[$provider->getId()] = $provider;
188
+        }
189
+
190
+        $missing = [];
191
+        foreach ($states as $providerId => $enabled) {
192
+            if (!$enabled) {
193
+                // Don't care
194
+                continue;
195
+            }
196
+
197
+            if (!isset($indexed[$providerId])) {
198
+                $missing[] = $providerId;
199
+                $this->logger->alert("two-factor auth provider '$providerId' failed to load",
200
+                    [
201
+                        'app' => 'core',
202
+                    ]);
203
+            }
204
+        }
205
+
206
+        if (!empty($missing)) {
207
+            // There was at least one provider missing
208
+            $this->logger->alert(count($missing) . " two-factor auth providers failed to load", ['app' => 'core']);
209
+
210
+            return true;
211
+        }
212
+
213
+        // If we reach this, there was not a single provider missing
214
+        return false;
215
+    }
216
+
217
+    /**
218
+     * Get the list of 2FA providers for the given user
219
+     *
220
+     * @param IUser $user
221
+     * @throws Exception
222
+     */
223
+    public function getProviderSet(IUser $user): ProviderSet {
224
+        $providerStates = $this->providerRegistry->getProviderStates($user);
225
+        $providers = $this->providerLoader->getProviders($user);
226
+
227
+        $fixedStates = $this->fixMissingProviderStates($providerStates, $providers, $user);
228
+        $isProviderMissing = $this->isProviderMissing($fixedStates, $providers);
229
+
230
+        $enabled = array_filter($providers, function (IProvider $provider) use ($fixedStates) {
231
+            return $fixedStates[$provider->getId()];
232
+        });
233
+        return new ProviderSet($enabled, $isProviderMissing);
234
+    }
235
+
236
+    /**
237
+     * Verify the given challenge
238
+     *
239
+     * @param string $providerId
240
+     * @param IUser $user
241
+     * @param string $challenge
242
+     * @return boolean
243
+     */
244
+    public function verifyChallenge(string $providerId, IUser $user, string $challenge): bool {
245
+        $provider = $this->getProvider($user, $providerId);
246
+        if ($provider === null) {
247
+            return false;
248
+        }
249
+
250
+        $passed = $provider->verifyChallenge($user, $challenge);
251
+        if ($passed) {
252
+            if ($this->session->get(self::REMEMBER_LOGIN) === true) {
253
+                // TODO: resolve cyclic dependency and use DI
254
+                \OC::$server->getUserSession()->createRememberMeToken($user);
255
+            }
256
+            $this->session->remove(self::SESSION_UID_KEY);
257
+            $this->session->remove(self::REMEMBER_LOGIN);
258
+            $this->session->set(self::SESSION_UID_DONE, $user->getUID());
259
+
260
+            // Clear token from db
261
+            $sessionId = $this->session->getId();
262
+            $token = $this->tokenProvider->getToken($sessionId);
263
+            $tokenId = $token->getId();
264
+            $this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $tokenId);
265
+
266
+            $dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
267
+            $this->dispatcher->dispatch(IProvider::EVENT_SUCCESS, $dispatchEvent);
268
+
269
+            $this->publishEvent($user, 'twofactor_success', [
270
+                'provider' => $provider->getDisplayName(),
271
+            ]);
272
+        } else {
273
+            $dispatchEvent = new GenericEvent($user, ['provider' => $provider->getDisplayName()]);
274
+            $this->dispatcher->dispatch(IProvider::EVENT_FAILED, $dispatchEvent);
275
+
276
+            $this->publishEvent($user, 'twofactor_failed', [
277
+                'provider' => $provider->getDisplayName(),
278
+            ]);
279
+        }
280
+        return $passed;
281
+    }
282
+
283
+    /**
284
+     * Push a 2fa event the user's activity stream
285
+     *
286
+     * @param IUser $user
287
+     * @param string $event
288
+     * @param array $params
289
+     */
290
+    private function publishEvent(IUser $user, string $event, array $params) {
291
+        $activity = $this->activityManager->generateEvent();
292
+        $activity->setApp('core')
293
+            ->setType('security')
294
+            ->setAuthor($user->getUID())
295
+            ->setAffectedUser($user->getUID())
296
+            ->setSubject($event, $params);
297
+        try {
298
+            $this->activityManager->publish($activity);
299
+        } catch (BadMethodCallException $e) {
300
+            $this->logger->warning('could not publish activity', ['app' => 'core']);
301
+            $this->logger->logException($e, ['app' => 'core']);
302
+        }
303
+    }
304
+
305
+    /**
306
+     * Check if the currently logged in user needs to pass 2FA
307
+     *
308
+     * @param IUser $user the currently logged in user
309
+     * @return boolean
310
+     */
311
+    public function needsSecondFactor(IUser $user = null): bool {
312
+        if ($user === null) {
313
+            return false;
314
+        }
315
+
316
+        // If we are authenticated using an app password skip all this
317
+        if ($this->session->exists('app_password')) {
318
+            return false;
319
+        }
320
+
321
+        // First check if the session tells us we should do 2FA (99% case)
322
+        if (!$this->session->exists(self::SESSION_UID_KEY)) {
323
+
324
+            // Check if the session tells us it is 2FA authenticated already
325
+            if ($this->session->exists(self::SESSION_UID_DONE) &&
326
+                $this->session->get(self::SESSION_UID_DONE) === $user->getUID()) {
327
+                return false;
328
+            }
329
+
330
+            /*
331 331
 			 * If the session is expired check if we are not logged in by a token
332 332
 			 * that still needs 2FA auth
333 333
 			 */
334
-			try {
335
-				$sessionId = $this->session->getId();
336
-				$token = $this->tokenProvider->getToken($sessionId);
337
-				$tokenId = $token->getId();
338
-				$tokensNeeding2FA = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
339
-
340
-				if (!\in_array($tokenId, $tokensNeeding2FA, true)) {
341
-					$this->session->set(self::SESSION_UID_DONE, $user->getUID());
342
-					return false;
343
-				}
344
-			} catch (InvalidTokenException $e) {
345
-			}
346
-		}
347
-
348
-		if (!$this->isTwoFactorAuthenticated($user)) {
349
-			// There is no second factor any more -> let the user pass
350
-			//   This prevents infinite redirect loops when a user is about
351
-			//   to solve the 2FA challenge, and the provider app is
352
-			//   disabled the same time
353
-			$this->session->remove(self::SESSION_UID_KEY);
354
-
355
-			$keys = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
356
-			foreach ($keys as $key) {
357
-				$this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $key);
358
-			}
359
-			return false;
360
-		}
361
-
362
-		return true;
363
-	}
364
-
365
-	/**
366
-	 * Prepare the 2FA login
367
-	 *
368
-	 * @param IUser $user
369
-	 * @param boolean $rememberMe
370
-	 */
371
-	public function prepareTwoFactorLogin(IUser $user, bool $rememberMe) {
372
-		$this->session->set(self::SESSION_UID_KEY, $user->getUID());
373
-		$this->session->set(self::REMEMBER_LOGIN, $rememberMe);
374
-
375
-		$id = $this->session->getId();
376
-		$token = $this->tokenProvider->getToken($id);
377
-		$this->config->setUserValue($user->getUID(), 'login_token_2fa', $token->getId(), $this->timeFactory->getTime());
378
-	}
379
-
380
-	public function clearTwoFactorPending(string $userId) {
381
-		$tokensNeeding2FA = $this->config->getUserKeys($userId, 'login_token_2fa');
382
-
383
-		foreach ($tokensNeeding2FA as $tokenId) {
384
-			$this->tokenProvider->invalidateTokenById($userId, $tokenId);
385
-		}
386
-	}
334
+            try {
335
+                $sessionId = $this->session->getId();
336
+                $token = $this->tokenProvider->getToken($sessionId);
337
+                $tokenId = $token->getId();
338
+                $tokensNeeding2FA = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
339
+
340
+                if (!\in_array($tokenId, $tokensNeeding2FA, true)) {
341
+                    $this->session->set(self::SESSION_UID_DONE, $user->getUID());
342
+                    return false;
343
+                }
344
+            } catch (InvalidTokenException $e) {
345
+            }
346
+        }
347
+
348
+        if (!$this->isTwoFactorAuthenticated($user)) {
349
+            // There is no second factor any more -> let the user pass
350
+            //   This prevents infinite redirect loops when a user is about
351
+            //   to solve the 2FA challenge, and the provider app is
352
+            //   disabled the same time
353
+            $this->session->remove(self::SESSION_UID_KEY);
354
+
355
+            $keys = $this->config->getUserKeys($user->getUID(), 'login_token_2fa');
356
+            foreach ($keys as $key) {
357
+                $this->config->deleteUserValue($user->getUID(), 'login_token_2fa', $key);
358
+            }
359
+            return false;
360
+        }
361
+
362
+        return true;
363
+    }
364
+
365
+    /**
366
+     * Prepare the 2FA login
367
+     *
368
+     * @param IUser $user
369
+     * @param boolean $rememberMe
370
+     */
371
+    public function prepareTwoFactorLogin(IUser $user, bool $rememberMe) {
372
+        $this->session->set(self::SESSION_UID_KEY, $user->getUID());
373
+        $this->session->set(self::REMEMBER_LOGIN, $rememberMe);
374
+
375
+        $id = $this->session->getId();
376
+        $token = $this->tokenProvider->getToken($id);
377
+        $this->config->setUserValue($user->getUID(), 'login_token_2fa', $token->getId(), $this->timeFactory->getTime());
378
+    }
379
+
380
+    public function clearTwoFactorPending(string $userId) {
381
+        $tokensNeeding2FA = $this->config->getUserKeys($userId, 'login_token_2fa');
382
+
383
+        foreach ($tokensNeeding2FA as $tokenId) {
384
+            $this->tokenProvider->invalidateTokenById($userId, $tokenId);
385
+        }
386
+    }
387 387
 
388 388
 }
Please login to merge, or discard this patch.
lib/private/DB/MySQLMigrator.php 1 patch
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -30,48 +30,48 @@
 block discarded – undo
30 30
 use Doctrine\DBAL\Schema\Table;
31 31
 
32 32
 class MySQLMigrator extends Migrator {
33
-	/**
34
-	 * @param Schema $targetSchema
35
-	 * @param \Doctrine\DBAL\Connection $connection
36
-	 * @return \Doctrine\DBAL\Schema\SchemaDiff
37
-	 */
38
-	protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
39
-		$platform = $connection->getDatabasePlatform();
40
-		$platform->registerDoctrineTypeMapping('enum', 'string');
41
-		$platform->registerDoctrineTypeMapping('bit', 'string');
33
+    /**
34
+     * @param Schema $targetSchema
35
+     * @param \Doctrine\DBAL\Connection $connection
36
+     * @return \Doctrine\DBAL\Schema\SchemaDiff
37
+     */
38
+    protected function getDiff(Schema $targetSchema, \Doctrine\DBAL\Connection $connection) {
39
+        $platform = $connection->getDatabasePlatform();
40
+        $platform->registerDoctrineTypeMapping('enum', 'string');
41
+        $platform->registerDoctrineTypeMapping('bit', 'string');
42 42
 
43
-		$schemaDiff = parent::getDiff($targetSchema, $connection);
43
+        $schemaDiff = parent::getDiff($targetSchema, $connection);
44 44
 
45
-		// identifiers need to be quoted for mysql
46
-		foreach ($schemaDiff->changedTables as $tableDiff) {
47
-			$tableDiff->name = $this->connection->quoteIdentifier($tableDiff->name);
48
-			foreach ($tableDiff->changedColumns as $column) {
49
-				$column->oldColumnName = $this->connection->quoteIdentifier($column->oldColumnName);
50
-			}
51
-		}
45
+        // identifiers need to be quoted for mysql
46
+        foreach ($schemaDiff->changedTables as $tableDiff) {
47
+            $tableDiff->name = $this->connection->quoteIdentifier($tableDiff->name);
48
+            foreach ($tableDiff->changedColumns as $column) {
49
+                $column->oldColumnName = $this->connection->quoteIdentifier($column->oldColumnName);
50
+            }
51
+        }
52 52
 
53
-		return $schemaDiff;
54
-	}
53
+        return $schemaDiff;
54
+    }
55 55
 
56
-		/**
57
-		 * Speed up migration test by disabling autocommit and unique indexes check
58
-		 *
59
-		 * @param \Doctrine\DBAL\Schema\Table $table
60
-		 * @throws \OC\DB\MigrationException
61
-		 */
62
-		protected function checkTableMigrate(Table $table) {
63
-				$this->connection->exec('SET autocommit=0');
64
-				$this->connection->exec('SET unique_checks=0');
56
+        /**
57
+         * Speed up migration test by disabling autocommit and unique indexes check
58
+         *
59
+         * @param \Doctrine\DBAL\Schema\Table $table
60
+         * @throws \OC\DB\MigrationException
61
+         */
62
+        protected function checkTableMigrate(Table $table) {
63
+                $this->connection->exec('SET autocommit=0');
64
+                $this->connection->exec('SET unique_checks=0');
65 65
 
66
-				try {
67
-						parent::checkTableMigrate($table);
68
-				} catch (\Exception $e) {
69
-						$this->connection->exec('SET unique_checks=1');
70
-						$this->connection->exec('SET autocommit=1');
71
-						throw new MigrationException($table->getName(), $e->getMessage());
72
-				}
73
-				$this->connection->exec('SET unique_checks=1');
74
-				$this->connection->exec('SET autocommit=1');
75
-		}
66
+                try {
67
+                        parent::checkTableMigrate($table);
68
+                } catch (\Exception $e) {
69
+                        $this->connection->exec('SET unique_checks=1');
70
+                        $this->connection->exec('SET autocommit=1');
71
+                        throw new MigrationException($table->getName(), $e->getMessage());
72
+                }
73
+                $this->connection->exec('SET unique_checks=1');
74
+                $this->connection->exec('SET autocommit=1');
75
+        }
76 76
 
77 77
 }
Please login to merge, or discard this patch.
lib/private/Tagging/Tag.php 1 patch
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -38,54 +38,54 @@
 block discarded – undo
38 38
  */
39 39
 class Tag extends Entity {
40 40
 
41
-	protected $owner;
42
-	protected $type;
43
-	protected $name;
41
+    protected $owner;
42
+    protected $type;
43
+    protected $name;
44 44
 
45
-	/**
46
-	 * Constructor.
47
-	 *
48
-	 * @param string $owner The tag's owner
49
-	 * @param string $type The type of item this tag is used for
50
-	 * @param string $name The tag's name
51
-	 */
52
-	public function __construct($owner = null, $type = null, $name = null) {
53
-		$this->setOwner($owner);
54
-		$this->setType($type);
55
-		$this->setName($name);
56
-	}
45
+    /**
46
+     * Constructor.
47
+     *
48
+     * @param string $owner The tag's owner
49
+     * @param string $type The type of item this tag is used for
50
+     * @param string $name The tag's name
51
+     */
52
+    public function __construct($owner = null, $type = null, $name = null) {
53
+        $this->setOwner($owner);
54
+        $this->setType($type);
55
+        $this->setName($name);
56
+    }
57 57
 
58
-	/**
59
-	 * Transform a database columnname to a property
60
-	 *
61
-	 * @param string $columnName the name of the column
62
-	 * @return string the property name
63
-	 * @todo migrate existing database columns to the correct names
64
-	 * to be able to drop this direct mapping
65
-	 */
66
-	public function columnToProperty($columnName){
67
-		if ($columnName === 'category') {
68
-			return 'name';
69
-		} elseif ($columnName === 'uid') {
70
-			return 'owner';
71
-		} else {
72
-			return parent::columnToProperty($columnName);
73
-		}
74
-	}
58
+    /**
59
+     * Transform a database columnname to a property
60
+     *
61
+     * @param string $columnName the name of the column
62
+     * @return string the property name
63
+     * @todo migrate existing database columns to the correct names
64
+     * to be able to drop this direct mapping
65
+     */
66
+    public function columnToProperty($columnName){
67
+        if ($columnName === 'category') {
68
+            return 'name';
69
+        } elseif ($columnName === 'uid') {
70
+            return 'owner';
71
+        } else {
72
+            return parent::columnToProperty($columnName);
73
+        }
74
+    }
75 75
 
76
-	/**
77
-	 * Transform a property to a database column name
78
-	 *
79
-	 * @param string $property the name of the property
80
-	 * @return string the column name
81
-	 */
82
-	public function propertyToColumn($property){
83
-		if ($property === 'name') {
84
-			return 'category';
85
-		} elseif ($property === 'owner') {
86
-			return 'uid';
87
-		} else {
88
-			return parent::propertyToColumn($property);
89
-		}
90
-	}
76
+    /**
77
+     * Transform a property to a database column name
78
+     *
79
+     * @param string $property the name of the property
80
+     * @return string the column name
81
+     */
82
+    public function propertyToColumn($property){
83
+        if ($property === 'name') {
84
+            return 'category';
85
+        } elseif ($property === 'owner') {
86
+            return 'uid';
87
+        } else {
88
+            return parent::propertyToColumn($property);
89
+        }
90
+    }
91 91
 }
Please login to merge, or discard this patch.
lib/private/User/Database.php 1 patch
Indentation   +419 added lines, -419 removed lines patch added patch discarded remove patch
@@ -77,423 +77,423 @@
 block discarded – undo
77 77
  * Class for user management in a SQL Database (e.g. MySQL, SQLite)
78 78
  */
79 79
 class Database extends ABackend
80
-	implements ICreateUserBackend,
81
-			   ISetPasswordBackend,
82
-			   ISetDisplayNameBackend,
83
-			   IGetDisplayNameBackend,
84
-			   ICheckPasswordBackend,
85
-			   IGetHomeBackend,
86
-			   ICountUsersBackend,
87
-			   IGetRealUIDBackend {
88
-	/** @var CappedMemoryCache */
89
-	private $cache;
90
-
91
-	/** @var IEventDispatcher */
92
-	private $eventDispatcher;
93
-
94
-	/** @var IDBConnection */
95
-	private $dbConn;
96
-
97
-	/** @var string */
98
-	private $table;
99
-
100
-	/**
101
-	 * \OC\User\Database constructor.
102
-	 *
103
-	 * @param IEventDispatcher $eventDispatcher
104
-	 * @param string $table
105
-	 */
106
-	public function __construct($eventDispatcher = null, $table = 'users') {
107
-		$this->cache = new CappedMemoryCache();
108
-		$this->table = $table;
109
-		$this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->query(IEventDispatcher::class);
110
-	}
111
-
112
-	/**
113
-	 * FIXME: This function should not be required!
114
-	 */
115
-	private function fixDI() {
116
-		if ($this->dbConn === null) {
117
-			$this->dbConn = \OC::$server->getDatabaseConnection();
118
-		}
119
-	}
120
-
121
-	/**
122
-	 * Create a new user
123
-	 *
124
-	 * @param string $uid The username of the user to create
125
-	 * @param string $password The password of the new user
126
-	 * @return bool
127
-	 *
128
-	 * Creates a new user. Basic checking of username is done in OC_User
129
-	 * itself, not in its subclasses.
130
-	 */
131
-	public function createUser(string $uid, string $password): bool {
132
-		$this->fixDI();
133
-
134
-		if (!$this->userExists($uid)) {
135
-			$this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
136
-
137
-			$qb = $this->dbConn->getQueryBuilder();
138
-			$qb->insert($this->table)
139
-				->values([
140
-					'uid' => $qb->createNamedParameter($uid),
141
-					'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
142
-					'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
143
-				]);
144
-
145
-			$result = $qb->execute();
146
-
147
-			// Clear cache
148
-			unset($this->cache[$uid]);
149
-
150
-			return $result ? true : false;
151
-		}
152
-
153
-		return false;
154
-	}
155
-
156
-	/**
157
-	 * delete a user
158
-	 *
159
-	 * @param string $uid The username of the user to delete
160
-	 * @return bool
161
-	 *
162
-	 * Deletes a user
163
-	 */
164
-	public function deleteUser($uid) {
165
-		$this->fixDI();
166
-
167
-		// Delete user-group-relation
168
-		$query = $this->dbConn->getQueryBuilder();
169
-		$query->delete($this->table)
170
-			->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
171
-		$result = $query->execute();
172
-
173
-		if (isset($this->cache[$uid])) {
174
-			unset($this->cache[$uid]);
175
-		}
176
-
177
-		return $result ? true : false;
178
-	}
179
-
180
-	private function updatePassword(string $uid, string $passwordHash): bool {
181
-		$query = $this->dbConn->getQueryBuilder();
182
-		$query->update($this->table)
183
-			->set('password', $query->createNamedParameter($passwordHash))
184
-			->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
185
-		$result = $query->execute();
186
-
187
-		return $result ? true : false;
188
-	}
189
-
190
-	/**
191
-	 * Set password
192
-	 *
193
-	 * @param string $uid The username
194
-	 * @param string $password The new password
195
-	 * @return bool
196
-	 *
197
-	 * Change the password of a user
198
-	 */
199
-	public function setPassword(string $uid, string $password): bool {
200
-		$this->fixDI();
201
-
202
-		if ($this->userExists($uid)) {
203
-			$this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
204
-
205
-			$hasher = \OC::$server->getHasher();
206
-			$hashedPassword = $hasher->hash($password);
207
-
208
-			return $this->updatePassword($uid, $hashedPassword);
209
-		}
210
-
211
-		return false;
212
-	}
213
-
214
-	/**
215
-	 * Set display name
216
-	 *
217
-	 * @param string $uid The username
218
-	 * @param string $displayName The new display name
219
-	 * @return bool
220
-	 *
221
-	 * Change the display name of a user
222
-	 */
223
-	public function setDisplayName(string $uid, string $displayName): bool {
224
-		$this->fixDI();
225
-
226
-		if ($this->userExists($uid)) {
227
-			$query = $this->dbConn->getQueryBuilder();
228
-			$query->update($this->table)
229
-				->set('displayname', $query->createNamedParameter($displayName))
230
-				->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
231
-			$query->execute();
232
-
233
-			$this->cache[$uid]['displayname'] = $displayName;
234
-
235
-			return true;
236
-		}
237
-
238
-		return false;
239
-	}
240
-
241
-	/**
242
-	 * get display name of the user
243
-	 *
244
-	 * @param string $uid user ID of the user
245
-	 * @return string display name
246
-	 */
247
-	public function getDisplayName($uid): string {
248
-		$uid = (string)$uid;
249
-		$this->loadUser($uid);
250
-		return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
251
-	}
252
-
253
-	/**
254
-	 * Get a list of all display names and user ids.
255
-	 *
256
-	 * @param string $search
257
-	 * @param string|null $limit
258
-	 * @param string|null $offset
259
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
260
-	 */
261
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
262
-		$limit = $this->fixLimit($limit);
263
-
264
-		$this->fixDI();
265
-
266
-		$query = $this->dbConn->getQueryBuilder();
267
-
268
-		$query->select('uid', 'displayname')
269
-			->from($this->table, 'u')
270
-			->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
271
-				$query->expr()->eq('userid', 'uid'),
272
-				$query->expr()->eq('appid', $query->expr()->literal('settings')),
273
-				$query->expr()->eq('configkey', $query->expr()->literal('email')))
274
-			)
275
-			// sqlite doesn't like re-using a single named parameter here
276
-			->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
277
-			->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
278
-			->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
279
-			->orderBy($query->func()->lower('displayname'), 'ASC')
280
-			->orderBy('uid_lower', 'ASC')
281
-			->setMaxResults($limit)
282
-			->setFirstResult($offset);
283
-
284
-		$result = $query->execute();
285
-		$displayNames = [];
286
-		while ($row = $result->fetch()) {
287
-			$displayNames[(string)$row['uid']] = (string)$row['displayname'];
288
-		}
289
-
290
-		return $displayNames;
291
-	}
292
-
293
-	/**
294
-	 * Check if the password is correct
295
-	 *
296
-	 * @param string $uid The username
297
-	 * @param string $password The password
298
-	 * @return string
299
-	 *
300
-	 * Check if the password is correct without logging in the user
301
-	 * returns the user id or false
302
-	 */
303
-	public function checkPassword(string $uid, string $password) {
304
-		$this->fixDI();
305
-
306
-		$qb = $this->dbConn->getQueryBuilder();
307
-		$qb->select('uid', 'password')
308
-			->from($this->table)
309
-			->where(
310
-				$qb->expr()->eq(
311
-					'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
312
-				)
313
-			);
314
-		$result = $qb->execute();
315
-		$row = $result->fetch();
316
-		$result->closeCursor();
317
-
318
-		if ($row) {
319
-			$storedHash = $row['password'];
320
-			$newHash = '';
321
-			if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
322
-				if (!empty($newHash)) {
323
-					$this->updatePassword($uid, $newHash);
324
-				}
325
-				return (string)$row['uid'];
326
-			}
327
-
328
-		}
329
-
330
-		return false;
331
-	}
332
-
333
-	/**
334
-	 * Load an user in the cache
335
-	 *
336
-	 * @param string $uid the username
337
-	 * @return boolean true if user was found, false otherwise
338
-	 */
339
-	private function loadUser($uid) {
340
-		$this->fixDI();
341
-
342
-		$uid = (string)$uid;
343
-		if (!isset($this->cache[$uid])) {
344
-			//guests $uid could be NULL or ''
345
-			if ($uid === '') {
346
-				$this->cache[$uid] = false;
347
-				return true;
348
-			}
349
-
350
-			$qb = $this->dbConn->getQueryBuilder();
351
-			$qb->select('uid', 'displayname')
352
-				->from($this->table)
353
-				->where(
354
-					$qb->expr()->eq(
355
-						'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
356
-					)
357
-				);
358
-			$result = $qb->execute();
359
-			$row = $result->fetch();
360
-			$result->closeCursor();
361
-
362
-			$this->cache[$uid] = false;
363
-
364
-			// "uid" is primary key, so there can only be a single result
365
-			if ($row !== false) {
366
-				$this->cache[$uid]['uid'] = (string)$row['uid'];
367
-				$this->cache[$uid]['displayname'] = (string)$row['displayname'];
368
-			} else {
369
-				return false;
370
-			}
371
-		}
372
-
373
-		return true;
374
-	}
375
-
376
-	/**
377
-	 * Get a list of all users
378
-	 *
379
-	 * @param string $search
380
-	 * @param null|int $limit
381
-	 * @param null|int $offset
382
-	 * @return string[] an array of all uids
383
-	 */
384
-	public function getUsers($search = '', $limit = null, $offset = null) {
385
-		$limit = $this->fixLimit($limit);
386
-
387
-		$users = $this->getDisplayNames($search, $limit, $offset);
388
-		$userIds = array_map(function ($uid) {
389
-			return (string)$uid;
390
-		}, array_keys($users));
391
-		sort($userIds, SORT_STRING | SORT_FLAG_CASE);
392
-		return $userIds;
393
-	}
394
-
395
-	/**
396
-	 * check if a user exists
397
-	 *
398
-	 * @param string $uid the username
399
-	 * @return boolean
400
-	 */
401
-	public function userExists($uid) {
402
-		$this->loadUser($uid);
403
-		return $this->cache[$uid] !== false;
404
-	}
405
-
406
-	/**
407
-	 * get the user's home directory
408
-	 *
409
-	 * @param string $uid the username
410
-	 * @return string|false
411
-	 */
412
-	public function getHome(string $uid) {
413
-		if ($this->userExists($uid)) {
414
-			return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
415
-		}
416
-
417
-		return false;
418
-	}
419
-
420
-	/**
421
-	 * @return bool
422
-	 */
423
-	public function hasUserListings() {
424
-		return true;
425
-	}
426
-
427
-	/**
428
-	 * counts the users in the database
429
-	 *
430
-	 * @return int|bool
431
-	 */
432
-	public function countUsers() {
433
-		$this->fixDI();
434
-
435
-		$query = $this->dbConn->getQueryBuilder();
436
-		$query->select($query->func()->count('uid'))
437
-			->from($this->table);
438
-		$result = $query->execute();
439
-
440
-		return $result->fetchColumn();
441
-	}
442
-
443
-	/**
444
-	 * returns the username for the given login name in the correct casing
445
-	 *
446
-	 * @param string $loginName
447
-	 * @return string|false
448
-	 */
449
-	public function loginName2UserName($loginName) {
450
-		if ($this->userExists($loginName)) {
451
-			return $this->cache[$loginName]['uid'];
452
-		}
453
-
454
-		return false;
455
-	}
456
-
457
-	/**
458
-	 * Backend name to be shown in user management
459
-	 *
460
-	 * @return string the name of the backend to be shown
461
-	 */
462
-	public function getBackendName() {
463
-		return 'Database';
464
-	}
465
-
466
-	public static function preLoginNameUsedAsUserName($param) {
467
-		if (!isset($param['uid'])) {
468
-			throw new \Exception('key uid is expected to be set in $param');
469
-		}
470
-
471
-		$backends = \OC::$server->getUserManager()->getBackends();
472
-		foreach ($backends as $backend) {
473
-			if ($backend instanceof Database) {
474
-				/** @var \OC\User\Database $backend */
475
-				$uid = $backend->loginName2UserName($param['uid']);
476
-				if ($uid !== false) {
477
-					$param['uid'] = $uid;
478
-					return;
479
-				}
480
-			}
481
-		}
482
-	}
483
-
484
-	public function getRealUID(string $uid): string {
485
-		if (!$this->userExists($uid)) {
486
-			throw new \RuntimeException($uid . ' does not exist');
487
-		}
488
-
489
-		return $this->cache[$uid]['uid'];
490
-	}
491
-
492
-	private function fixLimit($limit) {
493
-		if (is_int($limit) && $limit >= 0) {
494
-			return $limit;
495
-		}
496
-
497
-		return null;
498
-	}
80
+    implements ICreateUserBackend,
81
+                ISetPasswordBackend,
82
+                ISetDisplayNameBackend,
83
+                IGetDisplayNameBackend,
84
+                ICheckPasswordBackend,
85
+                IGetHomeBackend,
86
+                ICountUsersBackend,
87
+                IGetRealUIDBackend {
88
+    /** @var CappedMemoryCache */
89
+    private $cache;
90
+
91
+    /** @var IEventDispatcher */
92
+    private $eventDispatcher;
93
+
94
+    /** @var IDBConnection */
95
+    private $dbConn;
96
+
97
+    /** @var string */
98
+    private $table;
99
+
100
+    /**
101
+     * \OC\User\Database constructor.
102
+     *
103
+     * @param IEventDispatcher $eventDispatcher
104
+     * @param string $table
105
+     */
106
+    public function __construct($eventDispatcher = null, $table = 'users') {
107
+        $this->cache = new CappedMemoryCache();
108
+        $this->table = $table;
109
+        $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->query(IEventDispatcher::class);
110
+    }
111
+
112
+    /**
113
+     * FIXME: This function should not be required!
114
+     */
115
+    private function fixDI() {
116
+        if ($this->dbConn === null) {
117
+            $this->dbConn = \OC::$server->getDatabaseConnection();
118
+        }
119
+    }
120
+
121
+    /**
122
+     * Create a new user
123
+     *
124
+     * @param string $uid The username of the user to create
125
+     * @param string $password The password of the new user
126
+     * @return bool
127
+     *
128
+     * Creates a new user. Basic checking of username is done in OC_User
129
+     * itself, not in its subclasses.
130
+     */
131
+    public function createUser(string $uid, string $password): bool {
132
+        $this->fixDI();
133
+
134
+        if (!$this->userExists($uid)) {
135
+            $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
136
+
137
+            $qb = $this->dbConn->getQueryBuilder();
138
+            $qb->insert($this->table)
139
+                ->values([
140
+                    'uid' => $qb->createNamedParameter($uid),
141
+                    'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
142
+                    'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
143
+                ]);
144
+
145
+            $result = $qb->execute();
146
+
147
+            // Clear cache
148
+            unset($this->cache[$uid]);
149
+
150
+            return $result ? true : false;
151
+        }
152
+
153
+        return false;
154
+    }
155
+
156
+    /**
157
+     * delete a user
158
+     *
159
+     * @param string $uid The username of the user to delete
160
+     * @return bool
161
+     *
162
+     * Deletes a user
163
+     */
164
+    public function deleteUser($uid) {
165
+        $this->fixDI();
166
+
167
+        // Delete user-group-relation
168
+        $query = $this->dbConn->getQueryBuilder();
169
+        $query->delete($this->table)
170
+            ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
171
+        $result = $query->execute();
172
+
173
+        if (isset($this->cache[$uid])) {
174
+            unset($this->cache[$uid]);
175
+        }
176
+
177
+        return $result ? true : false;
178
+    }
179
+
180
+    private function updatePassword(string $uid, string $passwordHash): bool {
181
+        $query = $this->dbConn->getQueryBuilder();
182
+        $query->update($this->table)
183
+            ->set('password', $query->createNamedParameter($passwordHash))
184
+            ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
185
+        $result = $query->execute();
186
+
187
+        return $result ? true : false;
188
+    }
189
+
190
+    /**
191
+     * Set password
192
+     *
193
+     * @param string $uid The username
194
+     * @param string $password The new password
195
+     * @return bool
196
+     *
197
+     * Change the password of a user
198
+     */
199
+    public function setPassword(string $uid, string $password): bool {
200
+        $this->fixDI();
201
+
202
+        if ($this->userExists($uid)) {
203
+            $this->eventDispatcher->dispatchTyped(new ValidatePasswordPolicyEvent($password));
204
+
205
+            $hasher = \OC::$server->getHasher();
206
+            $hashedPassword = $hasher->hash($password);
207
+
208
+            return $this->updatePassword($uid, $hashedPassword);
209
+        }
210
+
211
+        return false;
212
+    }
213
+
214
+    /**
215
+     * Set display name
216
+     *
217
+     * @param string $uid The username
218
+     * @param string $displayName The new display name
219
+     * @return bool
220
+     *
221
+     * Change the display name of a user
222
+     */
223
+    public function setDisplayName(string $uid, string $displayName): bool {
224
+        $this->fixDI();
225
+
226
+        if ($this->userExists($uid)) {
227
+            $query = $this->dbConn->getQueryBuilder();
228
+            $query->update($this->table)
229
+                ->set('displayname', $query->createNamedParameter($displayName))
230
+                ->where($query->expr()->eq('uid_lower', $query->createNamedParameter(mb_strtolower($uid))));
231
+            $query->execute();
232
+
233
+            $this->cache[$uid]['displayname'] = $displayName;
234
+
235
+            return true;
236
+        }
237
+
238
+        return false;
239
+    }
240
+
241
+    /**
242
+     * get display name of the user
243
+     *
244
+     * @param string $uid user ID of the user
245
+     * @return string display name
246
+     */
247
+    public function getDisplayName($uid): string {
248
+        $uid = (string)$uid;
249
+        $this->loadUser($uid);
250
+        return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
251
+    }
252
+
253
+    /**
254
+     * Get a list of all display names and user ids.
255
+     *
256
+     * @param string $search
257
+     * @param string|null $limit
258
+     * @param string|null $offset
259
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
260
+     */
261
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
262
+        $limit = $this->fixLimit($limit);
263
+
264
+        $this->fixDI();
265
+
266
+        $query = $this->dbConn->getQueryBuilder();
267
+
268
+        $query->select('uid', 'displayname')
269
+            ->from($this->table, 'u')
270
+            ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
271
+                $query->expr()->eq('userid', 'uid'),
272
+                $query->expr()->eq('appid', $query->expr()->literal('settings')),
273
+                $query->expr()->eq('configkey', $query->expr()->literal('email')))
274
+            )
275
+            // sqlite doesn't like re-using a single named parameter here
276
+            ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
277
+            ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
278
+            ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
279
+            ->orderBy($query->func()->lower('displayname'), 'ASC')
280
+            ->orderBy('uid_lower', 'ASC')
281
+            ->setMaxResults($limit)
282
+            ->setFirstResult($offset);
283
+
284
+        $result = $query->execute();
285
+        $displayNames = [];
286
+        while ($row = $result->fetch()) {
287
+            $displayNames[(string)$row['uid']] = (string)$row['displayname'];
288
+        }
289
+
290
+        return $displayNames;
291
+    }
292
+
293
+    /**
294
+     * Check if the password is correct
295
+     *
296
+     * @param string $uid The username
297
+     * @param string $password The password
298
+     * @return string
299
+     *
300
+     * Check if the password is correct without logging in the user
301
+     * returns the user id or false
302
+     */
303
+    public function checkPassword(string $uid, string $password) {
304
+        $this->fixDI();
305
+
306
+        $qb = $this->dbConn->getQueryBuilder();
307
+        $qb->select('uid', 'password')
308
+            ->from($this->table)
309
+            ->where(
310
+                $qb->expr()->eq(
311
+                    'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
312
+                )
313
+            );
314
+        $result = $qb->execute();
315
+        $row = $result->fetch();
316
+        $result->closeCursor();
317
+
318
+        if ($row) {
319
+            $storedHash = $row['password'];
320
+            $newHash = '';
321
+            if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
322
+                if (!empty($newHash)) {
323
+                    $this->updatePassword($uid, $newHash);
324
+                }
325
+                return (string)$row['uid'];
326
+            }
327
+
328
+        }
329
+
330
+        return false;
331
+    }
332
+
333
+    /**
334
+     * Load an user in the cache
335
+     *
336
+     * @param string $uid the username
337
+     * @return boolean true if user was found, false otherwise
338
+     */
339
+    private function loadUser($uid) {
340
+        $this->fixDI();
341
+
342
+        $uid = (string)$uid;
343
+        if (!isset($this->cache[$uid])) {
344
+            //guests $uid could be NULL or ''
345
+            if ($uid === '') {
346
+                $this->cache[$uid] = false;
347
+                return true;
348
+            }
349
+
350
+            $qb = $this->dbConn->getQueryBuilder();
351
+            $qb->select('uid', 'displayname')
352
+                ->from($this->table)
353
+                ->where(
354
+                    $qb->expr()->eq(
355
+                        'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
356
+                    )
357
+                );
358
+            $result = $qb->execute();
359
+            $row = $result->fetch();
360
+            $result->closeCursor();
361
+
362
+            $this->cache[$uid] = false;
363
+
364
+            // "uid" is primary key, so there can only be a single result
365
+            if ($row !== false) {
366
+                $this->cache[$uid]['uid'] = (string)$row['uid'];
367
+                $this->cache[$uid]['displayname'] = (string)$row['displayname'];
368
+            } else {
369
+                return false;
370
+            }
371
+        }
372
+
373
+        return true;
374
+    }
375
+
376
+    /**
377
+     * Get a list of all users
378
+     *
379
+     * @param string $search
380
+     * @param null|int $limit
381
+     * @param null|int $offset
382
+     * @return string[] an array of all uids
383
+     */
384
+    public function getUsers($search = '', $limit = null, $offset = null) {
385
+        $limit = $this->fixLimit($limit);
386
+
387
+        $users = $this->getDisplayNames($search, $limit, $offset);
388
+        $userIds = array_map(function ($uid) {
389
+            return (string)$uid;
390
+        }, array_keys($users));
391
+        sort($userIds, SORT_STRING | SORT_FLAG_CASE);
392
+        return $userIds;
393
+    }
394
+
395
+    /**
396
+     * check if a user exists
397
+     *
398
+     * @param string $uid the username
399
+     * @return boolean
400
+     */
401
+    public function userExists($uid) {
402
+        $this->loadUser($uid);
403
+        return $this->cache[$uid] !== false;
404
+    }
405
+
406
+    /**
407
+     * get the user's home directory
408
+     *
409
+     * @param string $uid the username
410
+     * @return string|false
411
+     */
412
+    public function getHome(string $uid) {
413
+        if ($this->userExists($uid)) {
414
+            return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
415
+        }
416
+
417
+        return false;
418
+    }
419
+
420
+    /**
421
+     * @return bool
422
+     */
423
+    public function hasUserListings() {
424
+        return true;
425
+    }
426
+
427
+    /**
428
+     * counts the users in the database
429
+     *
430
+     * @return int|bool
431
+     */
432
+    public function countUsers() {
433
+        $this->fixDI();
434
+
435
+        $query = $this->dbConn->getQueryBuilder();
436
+        $query->select($query->func()->count('uid'))
437
+            ->from($this->table);
438
+        $result = $query->execute();
439
+
440
+        return $result->fetchColumn();
441
+    }
442
+
443
+    /**
444
+     * returns the username for the given login name in the correct casing
445
+     *
446
+     * @param string $loginName
447
+     * @return string|false
448
+     */
449
+    public function loginName2UserName($loginName) {
450
+        if ($this->userExists($loginName)) {
451
+            return $this->cache[$loginName]['uid'];
452
+        }
453
+
454
+        return false;
455
+    }
456
+
457
+    /**
458
+     * Backend name to be shown in user management
459
+     *
460
+     * @return string the name of the backend to be shown
461
+     */
462
+    public function getBackendName() {
463
+        return 'Database';
464
+    }
465
+
466
+    public static function preLoginNameUsedAsUserName($param) {
467
+        if (!isset($param['uid'])) {
468
+            throw new \Exception('key uid is expected to be set in $param');
469
+        }
470
+
471
+        $backends = \OC::$server->getUserManager()->getBackends();
472
+        foreach ($backends as $backend) {
473
+            if ($backend instanceof Database) {
474
+                /** @var \OC\User\Database $backend */
475
+                $uid = $backend->loginName2UserName($param['uid']);
476
+                if ($uid !== false) {
477
+                    $param['uid'] = $uid;
478
+                    return;
479
+                }
480
+            }
481
+        }
482
+    }
483
+
484
+    public function getRealUID(string $uid): string {
485
+        if (!$this->userExists($uid)) {
486
+            throw new \RuntimeException($uid . ' does not exist');
487
+        }
488
+
489
+        return $this->cache[$uid]['uid'];
490
+    }
491
+
492
+    private function fixLimit($limit) {
493
+        if (is_int($limit) && $limit >= 0) {
494
+            return $limit;
495
+        }
496
+
497
+        return null;
498
+    }
499 499
 }
Please login to merge, or discard this patch.
lib/private/Group/MetaData.php 1 patch
Indentation   +172 added lines, -172 removed lines patch added patch discarded remove patch
@@ -35,176 +35,176 @@
 block discarded – undo
35 35
 use OCP\IUserSession;
36 36
 
37 37
 class MetaData {
38
-	const SORT_NONE = 0;
39
-	const SORT_USERCOUNT = 1; // May have performance issues on LDAP backends
40
-	const SORT_GROUPNAME = 2;
41
-
42
-	/** @var string */
43
-	protected $user;
44
-	/** @var bool */
45
-	protected $isAdmin;
46
-	/** @var array */
47
-	protected $metaData = [];
48
-	/** @var IGroupManager */
49
-	protected $groupManager;
50
-	/** @var bool */
51
-	protected $sorting = false;
52
-	/** @var IUserSession */
53
-	protected $userSession;
54
-
55
-	/**
56
-	 * @param string $user the uid of the current user
57
-	 * @param bool $isAdmin whether the current users is an admin
58
-	 * @param IGroupManager $groupManager
59
-	 * @param IUserManager $userManager
60
-	 * @param IUserSession $userSession
61
-	 */
62
-	public function __construct(
63
-			$user,
64
-			$isAdmin,
65
-			IGroupManager $groupManager,
66
-			IUserSession $userSession
67
-			) {
68
-		$this->user = $user;
69
-		$this->isAdmin = (bool)$isAdmin;
70
-		$this->groupManager = $groupManager;
71
-		$this->userSession = $userSession;
72
-	}
73
-
74
-	/**
75
-	 * returns an array with meta data about all available groups
76
-	 * the array is structured as follows:
77
-	 * [0] array containing meta data about admin groups
78
-	 * [1] array containing meta data about unprivileged groups
79
-	 * @param string $groupSearch only effective when instance was created with
80
-	 * isAdmin being true
81
-	 * @param string $userSearch the pattern users are search for
82
-	 * @return array
83
-	 */
84
-	public function get($groupSearch = '', $userSearch = '') {
85
-		$key = $groupSearch . '::' . $userSearch;
86
-		if(isset($this->metaData[$key])) {
87
-			return $this->metaData[$key];
88
-		}
89
-
90
-		$adminGroups = [];
91
-		$groups = [];
92
-		$sortGroupsIndex = 0;
93
-		$sortGroupsKeys = [];
94
-		$sortAdminGroupsIndex = 0;
95
-		$sortAdminGroupsKeys = [];
96
-
97
-		foreach($this->getGroups($groupSearch) as $group) {
98
-			$groupMetaData = $this->generateGroupMetaData($group, $userSearch);
99
-			if (strtolower($group->getGID()) !== 'admin') {
100
-				$this->addEntry(
101
-					$groups,
102
-					$sortGroupsKeys,
103
-					$sortGroupsIndex,
104
-					$groupMetaData);
105
-			} else {
106
-				//admin group is hard coded to 'admin' for now. In future,
107
-				//backends may define admin groups too. Then the if statement
108
-				//has to be adjusted accordingly.
109
-				$this->addEntry(
110
-					$adminGroups,
111
-					$sortAdminGroupsKeys,
112
-					$sortAdminGroupsIndex,
113
-					$groupMetaData);
114
-			}
115
-		}
116
-
117
-		//whether sorting is necessary is will be checked in sort()
118
-		$this->sort($groups, $sortGroupsKeys);
119
-		$this->sort($adminGroups, $sortAdminGroupsKeys);
120
-
121
-		$this->metaData[$key] = [$adminGroups, $groups];
122
-		return $this->metaData[$key];
123
-	}
124
-
125
-	/**
126
-	 * sets the sort mode, see SORT_* constants for supported modes
127
-	 *
128
-	 * @param int $sortMode
129
-	 */
130
-	public function setSorting($sortMode) {
131
-		switch ($sortMode) {
132
-			case self::SORT_USERCOUNT:
133
-			case self::SORT_GROUPNAME:
134
-				$this->sorting = $sortMode;
135
-				break;
136
-
137
-			default:
138
-				$this->sorting = self::SORT_NONE;
139
-		}
140
-	}
141
-
142
-	/**
143
-	 * adds an group entry to the resulting array
144
-	 * @param array $entries the resulting array, by reference
145
-	 * @param array $sortKeys the sort key array, by reference
146
-	 * @param int $sortIndex the sort key index, by reference
147
-	 * @param array $data the group's meta data as returned by generateGroupMetaData()
148
-	 */
149
-	private function addEntry(&$entries, &$sortKeys, &$sortIndex, $data) {
150
-		$entries[] = $data;
151
-		if ($this->sorting === self::SORT_USERCOUNT) {
152
-			$sortKeys[$sortIndex] = $data['usercount'];
153
-			$sortIndex++;
154
-		} else if ($this->sorting === self::SORT_GROUPNAME) {
155
-			$sortKeys[$sortIndex] = $data['name'];
156
-			$sortIndex++;
157
-		}
158
-	}
159
-
160
-	/**
161
-	 * creates an array containing the group meta data
162
-	 * @param \OCP\IGroup $group
163
-	 * @param string $userSearch
164
-	 * @return array with the keys 'id', 'name', 'usercount' and 'disabled'
165
-	 */
166
-	private function generateGroupMetaData(\OCP\IGroup $group, $userSearch) {
167
-		return [
168
-			'id' => $group->getGID(),
169
-			'name' => $group->getDisplayName(),
170
-			'usercount' => $this->sorting === self::SORT_USERCOUNT ? $group->count($userSearch) : 0,
171
-			'disabled' => $group->countDisabled(),
172
-			'canAdd' => $group->canAddUser(),
173
-			'canRemove' => $group->canRemoveUser(),
174
-		];
175
-	}
176
-
177
-	/**
178
-	 * sorts the result array, if applicable
179
-	 * @param array $entries the result array, by reference
180
-	 * @param array $sortKeys the array containing the sort keys
181
-	 * @param return null
182
-	 */
183
-	private function sort(&$entries, $sortKeys) {
184
-		if ($this->sorting === self::SORT_USERCOUNT) {
185
-			array_multisort($sortKeys, SORT_DESC, $entries);
186
-		} else if ($this->sorting === self::SORT_GROUPNAME) {
187
-			array_multisort($sortKeys, SORT_ASC, $entries);
188
-		}
189
-	}
190
-
191
-	/**
192
-	 * returns the available groups
193
-	 * @param string $search a search string
194
-	 * @return \OCP\IGroup[]
195
-	 */
196
-	public function getGroups($search = '') {
197
-		if($this->isAdmin) {
198
-			return $this->groupManager->search($search);
199
-		} else {
200
-			$userObject = $this->userSession->getUser();
201
-			if($userObject !== null) {
202
-				$groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($userObject);
203
-			} else {
204
-				$groups = [];
205
-			}
206
-
207
-			return $groups;
208
-		}
209
-	}
38
+    const SORT_NONE = 0;
39
+    const SORT_USERCOUNT = 1; // May have performance issues on LDAP backends
40
+    const SORT_GROUPNAME = 2;
41
+
42
+    /** @var string */
43
+    protected $user;
44
+    /** @var bool */
45
+    protected $isAdmin;
46
+    /** @var array */
47
+    protected $metaData = [];
48
+    /** @var IGroupManager */
49
+    protected $groupManager;
50
+    /** @var bool */
51
+    protected $sorting = false;
52
+    /** @var IUserSession */
53
+    protected $userSession;
54
+
55
+    /**
56
+     * @param string $user the uid of the current user
57
+     * @param bool $isAdmin whether the current users is an admin
58
+     * @param IGroupManager $groupManager
59
+     * @param IUserManager $userManager
60
+     * @param IUserSession $userSession
61
+     */
62
+    public function __construct(
63
+            $user,
64
+            $isAdmin,
65
+            IGroupManager $groupManager,
66
+            IUserSession $userSession
67
+            ) {
68
+        $this->user = $user;
69
+        $this->isAdmin = (bool)$isAdmin;
70
+        $this->groupManager = $groupManager;
71
+        $this->userSession = $userSession;
72
+    }
73
+
74
+    /**
75
+     * returns an array with meta data about all available groups
76
+     * the array is structured as follows:
77
+     * [0] array containing meta data about admin groups
78
+     * [1] array containing meta data about unprivileged groups
79
+     * @param string $groupSearch only effective when instance was created with
80
+     * isAdmin being true
81
+     * @param string $userSearch the pattern users are search for
82
+     * @return array
83
+     */
84
+    public function get($groupSearch = '', $userSearch = '') {
85
+        $key = $groupSearch . '::' . $userSearch;
86
+        if(isset($this->metaData[$key])) {
87
+            return $this->metaData[$key];
88
+        }
89
+
90
+        $adminGroups = [];
91
+        $groups = [];
92
+        $sortGroupsIndex = 0;
93
+        $sortGroupsKeys = [];
94
+        $sortAdminGroupsIndex = 0;
95
+        $sortAdminGroupsKeys = [];
96
+
97
+        foreach($this->getGroups($groupSearch) as $group) {
98
+            $groupMetaData = $this->generateGroupMetaData($group, $userSearch);
99
+            if (strtolower($group->getGID()) !== 'admin') {
100
+                $this->addEntry(
101
+                    $groups,
102
+                    $sortGroupsKeys,
103
+                    $sortGroupsIndex,
104
+                    $groupMetaData);
105
+            } else {
106
+                //admin group is hard coded to 'admin' for now. In future,
107
+                //backends may define admin groups too. Then the if statement
108
+                //has to be adjusted accordingly.
109
+                $this->addEntry(
110
+                    $adminGroups,
111
+                    $sortAdminGroupsKeys,
112
+                    $sortAdminGroupsIndex,
113
+                    $groupMetaData);
114
+            }
115
+        }
116
+
117
+        //whether sorting is necessary is will be checked in sort()
118
+        $this->sort($groups, $sortGroupsKeys);
119
+        $this->sort($adminGroups, $sortAdminGroupsKeys);
120
+
121
+        $this->metaData[$key] = [$adminGroups, $groups];
122
+        return $this->metaData[$key];
123
+    }
124
+
125
+    /**
126
+     * sets the sort mode, see SORT_* constants for supported modes
127
+     *
128
+     * @param int $sortMode
129
+     */
130
+    public function setSorting($sortMode) {
131
+        switch ($sortMode) {
132
+            case self::SORT_USERCOUNT:
133
+            case self::SORT_GROUPNAME:
134
+                $this->sorting = $sortMode;
135
+                break;
136
+
137
+            default:
138
+                $this->sorting = self::SORT_NONE;
139
+        }
140
+    }
141
+
142
+    /**
143
+     * adds an group entry to the resulting array
144
+     * @param array $entries the resulting array, by reference
145
+     * @param array $sortKeys the sort key array, by reference
146
+     * @param int $sortIndex the sort key index, by reference
147
+     * @param array $data the group's meta data as returned by generateGroupMetaData()
148
+     */
149
+    private function addEntry(&$entries, &$sortKeys, &$sortIndex, $data) {
150
+        $entries[] = $data;
151
+        if ($this->sorting === self::SORT_USERCOUNT) {
152
+            $sortKeys[$sortIndex] = $data['usercount'];
153
+            $sortIndex++;
154
+        } else if ($this->sorting === self::SORT_GROUPNAME) {
155
+            $sortKeys[$sortIndex] = $data['name'];
156
+            $sortIndex++;
157
+        }
158
+    }
159
+
160
+    /**
161
+     * creates an array containing the group meta data
162
+     * @param \OCP\IGroup $group
163
+     * @param string $userSearch
164
+     * @return array with the keys 'id', 'name', 'usercount' and 'disabled'
165
+     */
166
+    private function generateGroupMetaData(\OCP\IGroup $group, $userSearch) {
167
+        return [
168
+            'id' => $group->getGID(),
169
+            'name' => $group->getDisplayName(),
170
+            'usercount' => $this->sorting === self::SORT_USERCOUNT ? $group->count($userSearch) : 0,
171
+            'disabled' => $group->countDisabled(),
172
+            'canAdd' => $group->canAddUser(),
173
+            'canRemove' => $group->canRemoveUser(),
174
+        ];
175
+    }
176
+
177
+    /**
178
+     * sorts the result array, if applicable
179
+     * @param array $entries the result array, by reference
180
+     * @param array $sortKeys the array containing the sort keys
181
+     * @param return null
182
+     */
183
+    private function sort(&$entries, $sortKeys) {
184
+        if ($this->sorting === self::SORT_USERCOUNT) {
185
+            array_multisort($sortKeys, SORT_DESC, $entries);
186
+        } else if ($this->sorting === self::SORT_GROUPNAME) {
187
+            array_multisort($sortKeys, SORT_ASC, $entries);
188
+        }
189
+    }
190
+
191
+    /**
192
+     * returns the available groups
193
+     * @param string $search a search string
194
+     * @return \OCP\IGroup[]
195
+     */
196
+    public function getGroups($search = '') {
197
+        if($this->isAdmin) {
198
+            return $this->groupManager->search($search);
199
+        } else {
200
+            $userObject = $this->userSession->getUser();
201
+            if($userObject !== null) {
202
+                $groups = $this->groupManager->getSubAdmin()->getSubAdminsGroups($userObject);
203
+            } else {
204
+                $groups = [];
205
+            }
206
+
207
+            return $groups;
208
+        }
209
+    }
210 210
 }
Please login to merge, or discard this patch.