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