Completed
Pull Request — master (#4136)
by Jan-Christoph
11:29
created
apps/files_sharing/appinfo/update.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -26,16 +26,16 @@
 block discarded – undo
26 26
 
27 27
 // Migration OC8.2 -> OC9
28 28
 if (version_compare($installedVersion, '0.9.1', '<')) {
29
-	$m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
30
-	$m->removeReShares();
31
-	$m->updateInitiatorInfo();
29
+    $m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
30
+    $m->removeReShares();
31
+    $m->updateInitiatorInfo();
32 32
 }
33 33
 
34 34
 if (version_compare($installedVersion, '1.1.1', '<')) {
35
-	$m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
35
+    $m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
36 36
 }
37 37
 
38 38
 if (version_compare($installedVersion, '1.4.0', '<')) {
39
-	$m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
40
-	$m->addPasswordColumn();
39
+    $m = new Migration(\OC::$server->getDatabaseConnection(), \OC::$server->getConfig());
40
+    $m->addPasswordColumn();
41 41
 }
Please login to merge, or discard this patch.
apps/sharebymail/templates/mailpassword.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -36,10 +36,10 @@
 block discarded – undo
36 36
 					<td width="20px">&nbsp;</td>
37 37
 					<td style="font-weight:normal; font-size:0.8em; line-height:1.2em; font-family:verdana,'arial',sans;">
38 38
 						<?php
39
-						print_unescaped($l->t('Hey there,<br><br>%s shared <i>%s</i> with you.<br>You should have already received a separate mail with a link to access it.<br><br>It is protected with the following password: %s<br><br>', [$_['initiator'], $_['filename'], $_['password']]));
40
-						// TRANSLATORS term at the end of a mail
41
-						p($l->t('Cheers!'));
42
-						?>
39
+                        print_unescaped($l->t('Hey there,<br><br>%s shared <i>%s</i> with you.<br>You should have already received a separate mail with a link to access it.<br><br>It is protected with the following password: %s<br><br>', [$_['initiator'], $_['filename'], $_['password']]));
40
+                        // TRANSLATORS term at the end of a mail
41
+                        p($l->t('Cheers!'));
42
+                        ?>
43 43
 					</td>
44 44
 				</tr>
45 45
 				<tr><td colspan="2">&nbsp;</td></tr>
Please login to merge, or discard this patch.
apps/files_sharing/lib/Migration.php 1 patch
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -39,270 +39,270 @@
 block discarded – undo
39 39
  */
40 40
 class Migration {
41 41
 
42
-	/** @var IDBConnection */
43
-	private $connection;
44
-
45
-	/** @var  IConfig */
46
-	private $config;
47
-
48
-	/** @var  ICache with all shares we already saw */
49
-	private $shareCache;
50
-
51
-	/** @var string */
52
-	private $table = 'share';
53
-
54
-	public function __construct(IDBConnection $connection, IConfig $config) {
55
-		$this->connection = $connection;
56
-		$this->config = $config;
57
-
58
-		// We cache up to 10k share items (~20MB)
59
-		$this->shareCache = new CappedMemoryCache(10000);
60
-	}
61
-
62
-	/**
63
-	 * move all re-shares to the owner in order to have a flat list of shares
64
-	 * upgrade from oC 8.2 to 9.0 with the new sharing
65
-	 */
66
-	public function removeReShares() {
67
-
68
-		$stmt = $this->getReShares();
69
-
70
-		$owners = [];
71
-		while($share = $stmt->fetch()) {
72
-
73
-			$this->shareCache[$share['id']] = $share;
74
-
75
-			$owners[$share['id']] = [
76
-					'owner' => $this->findOwner($share),
77
-					'initiator' => $share['uid_owner'],
78
-					'type' => $share['share_type'],
79
-			];
80
-
81
-			if (count($owners) === 1000) {
82
-				$this->updateOwners($owners);
83
-				$owners = [];
84
-			}
85
-		}
86
-
87
-		$stmt->closeCursor();
88
-
89
-		if (count($owners)) {
90
-			$this->updateOwners($owners);
91
-		}
92
-	}
93
-
94
-	/**
95
-	 * update all owner information so that all shares have an owner
96
-	 * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
97
-	 */
98
-	public function updateInitiatorInfo() {
99
-		while (true) {
100
-			$shares = $this->getMissingInitiator(1000);
101
-
102
-			if (empty($shares)) {
103
-				break;
104
-			}
105
-
106
-			$owners = [];
107
-			foreach ($shares as $share) {
108
-				$owners[$share['id']] = [
109
-					'owner' => $share['uid_owner'],
110
-					'initiator' => $share['uid_owner'],
111
-					'type' => $share['share_type'],
112
-				];
113
-			}
114
-			$this->updateOwners($owners);
115
-		}
116
-	}
117
-
118
-	/**
119
-	 * this was dropped for Nextcloud 11 in favour of share by mail
120
-	 */
121
-	public function removeSendMailOption() {
122
-		$this->config->deleteAppValue('core', 'shareapi_allow_mail_notification');
123
-		$this->config->deleteAppValue('core', 'shareapi_allow_public_notification');
124
-	}
125
-
126
-	public function addPasswordColumn() {
127
-		$query = $this->connection->getQueryBuilder();
128
-		$query
129
-			->update('share')
130
-			->set('password', 'share_with')
131
-			->where($query->expr()->eq('share_type', $query->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
132
-			->andWhere($query->expr()->isNotNull('share_with'));
133
-		$query->execute();
134
-
135
-		$clearQuery = $this->connection->getQueryBuilder();
136
-		$clearQuery
137
-			->update('share')->set('share_with', $clearQuery->createNamedParameter(null))
138
-			->where($clearQuery->expr()->eq('share_type', $clearQuery->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
139
-
140
-		$clearQuery->execute();
141
-
142
-	}
143
-
144
-	/**
145
-	 * find the owner of a re-shared file/folder
146
-	 *
147
-	 * @param array $share
148
-	 * @return array
149
-	 */
150
-	private function findOwner($share) {
151
-		$currentShare = $share;
152
-		while(!is_null($currentShare['parent'])) {
153
-			if (isset($this->shareCache[$currentShare['parent']])) {
154
-				$currentShare = $this->shareCache[$currentShare['parent']];
155
-			} else {
156
-				$currentShare = $this->getShare((int)$currentShare['parent']);
157
-				$this->shareCache[$currentShare['id']] = $currentShare;
158
-			}
159
-		}
160
-
161
-		return $currentShare['uid_owner'];
162
-	}
163
-
164
-	/**
165
-	 * Get $n re-shares from the database
166
-	 *
167
-	 * @param int $n The max number of shares to fetch
168
-	 * @return \Doctrine\DBAL\Driver\Statement
169
-	 */
170
-	private function getReShares() {
171
-		$query = $this->connection->getQueryBuilder();
172
-		$query->select(['id', 'parent', 'uid_owner', 'share_type'])
173
-			->from($this->table)
174
-			->where($query->expr()->in(
175
-				'share_type',
176
-				$query->createNamedParameter(
177
-					[
178
-						\OCP\Share::SHARE_TYPE_USER,
179
-						\OCP\Share::SHARE_TYPE_GROUP,
180
-						\OCP\Share::SHARE_TYPE_LINK,
181
-						\OCP\Share::SHARE_TYPE_REMOTE,
182
-					],
183
-					Connection::PARAM_INT_ARRAY
184
-				)
185
-			))
186
-			->andWhere($query->expr()->in(
187
-				'item_type',
188
-				$query->createNamedParameter(
189
-					['file', 'folder'],
190
-					Connection::PARAM_STR_ARRAY
191
-				)
192
-			))
193
-			->andWhere($query->expr()->isNotNull('parent'))
194
-			->orderBy('id', 'asc');
195
-		return $query->execute();
196
-
197
-
198
-		$shares = $result->fetchAll();
199
-		$result->closeCursor();
200
-
201
-		$ordered = [];
202
-		foreach ($shares as $share) {
203
-			$ordered[(int)$share['id']] = $share;
204
-		}
205
-
206
-		return $ordered;
207
-	}
208
-
209
-	/**
210
-	 * Get $n re-shares from the database
211
-	 *
212
-	 * @param int $n The max number of shares to fetch
213
-	 * @return array
214
-	 */
215
-	private function getMissingInitiator($n = 1000) {
216
-		$query = $this->connection->getQueryBuilder();
217
-		$query->select(['id', 'uid_owner', 'share_type'])
218
-			->from($this->table)
219
-			->where($query->expr()->in(
220
-				'share_type',
221
-				$query->createNamedParameter(
222
-					[
223
-						\OCP\Share::SHARE_TYPE_USER,
224
-						\OCP\Share::SHARE_TYPE_GROUP,
225
-						\OCP\Share::SHARE_TYPE_LINK,
226
-						\OCP\Share::SHARE_TYPE_REMOTE,
227
-					],
228
-					Connection::PARAM_INT_ARRAY
229
-				)
230
-			))
231
-			->andWhere($query->expr()->in(
232
-				'item_type',
233
-				$query->createNamedParameter(
234
-					['file', 'folder'],
235
-					Connection::PARAM_STR_ARRAY
236
-				)
237
-			))
238
-			->andWhere($query->expr()->isNull('uid_initiator'))
239
-			->orderBy('id', 'asc')
240
-			->setMaxResults($n);
241
-		$result = $query->execute();
242
-		$shares = $result->fetchAll();
243
-		$result->closeCursor();
244
-
245
-		$ordered = [];
246
-		foreach ($shares as $share) {
247
-			$ordered[(int)$share['id']] = $share;
248
-		}
249
-
250
-		return $ordered;
251
-	}
252
-
253
-	/**
254
-	 * get a specific share
255
-	 *
256
-	 * @param int $id
257
-	 * @return array
258
-	 */
259
-	private function getShare($id) {
260
-		$query = $this->connection->getQueryBuilder();
261
-		$query->select(['id', 'parent', 'uid_owner'])
262
-			->from($this->table)
263
-			->where($query->expr()->eq('id', $query->createNamedParameter($id)));
264
-		$result = $query->execute();
265
-		$share = $result->fetchAll();
266
-		$result->closeCursor();
267
-
268
-		return $share[0];
269
-	}
270
-
271
-	/**
272
-	 * update database with the new owners
273
-	 *
274
-	 * @param array $owners
275
-	 * @throws \Exception
276
-	 */
277
-	private function updateOwners($owners) {
278
-
279
-		$this->connection->beginTransaction();
280
-
281
-		try {
282
-
283
-			foreach ($owners as $id => $owner) {
284
-				$query = $this->connection->getQueryBuilder();
285
-				$query->update($this->table)
286
-					->set('uid_owner', $query->createNamedParameter($owner['owner']))
287
-					->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
288
-
289
-
290
-				if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
291
-					$query->set('parent', $query->createNamedParameter(null));
292
-				}
293
-
294
-				$query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
295
-
296
-				$query->execute();
297
-			}
298
-
299
-			$this->connection->commit();
300
-
301
-		} catch (\Exception $e) {
302
-			$this->connection->rollBack();
303
-			throw $e;
304
-		}
305
-
306
-	}
42
+    /** @var IDBConnection */
43
+    private $connection;
44
+
45
+    /** @var  IConfig */
46
+    private $config;
47
+
48
+    /** @var  ICache with all shares we already saw */
49
+    private $shareCache;
50
+
51
+    /** @var string */
52
+    private $table = 'share';
53
+
54
+    public function __construct(IDBConnection $connection, IConfig $config) {
55
+        $this->connection = $connection;
56
+        $this->config = $config;
57
+
58
+        // We cache up to 10k share items (~20MB)
59
+        $this->shareCache = new CappedMemoryCache(10000);
60
+    }
61
+
62
+    /**
63
+     * move all re-shares to the owner in order to have a flat list of shares
64
+     * upgrade from oC 8.2 to 9.0 with the new sharing
65
+     */
66
+    public function removeReShares() {
67
+
68
+        $stmt = $this->getReShares();
69
+
70
+        $owners = [];
71
+        while($share = $stmt->fetch()) {
72
+
73
+            $this->shareCache[$share['id']] = $share;
74
+
75
+            $owners[$share['id']] = [
76
+                    'owner' => $this->findOwner($share),
77
+                    'initiator' => $share['uid_owner'],
78
+                    'type' => $share['share_type'],
79
+            ];
80
+
81
+            if (count($owners) === 1000) {
82
+                $this->updateOwners($owners);
83
+                $owners = [];
84
+            }
85
+        }
86
+
87
+        $stmt->closeCursor();
88
+
89
+        if (count($owners)) {
90
+            $this->updateOwners($owners);
91
+        }
92
+    }
93
+
94
+    /**
95
+     * update all owner information so that all shares have an owner
96
+     * and an initiator for the upgrade from oC 8.2 to 9.0 with the new sharing
97
+     */
98
+    public function updateInitiatorInfo() {
99
+        while (true) {
100
+            $shares = $this->getMissingInitiator(1000);
101
+
102
+            if (empty($shares)) {
103
+                break;
104
+            }
105
+
106
+            $owners = [];
107
+            foreach ($shares as $share) {
108
+                $owners[$share['id']] = [
109
+                    'owner' => $share['uid_owner'],
110
+                    'initiator' => $share['uid_owner'],
111
+                    'type' => $share['share_type'],
112
+                ];
113
+            }
114
+            $this->updateOwners($owners);
115
+        }
116
+    }
117
+
118
+    /**
119
+     * this was dropped for Nextcloud 11 in favour of share by mail
120
+     */
121
+    public function removeSendMailOption() {
122
+        $this->config->deleteAppValue('core', 'shareapi_allow_mail_notification');
123
+        $this->config->deleteAppValue('core', 'shareapi_allow_public_notification');
124
+    }
125
+
126
+    public function addPasswordColumn() {
127
+        $query = $this->connection->getQueryBuilder();
128
+        $query
129
+            ->update('share')
130
+            ->set('password', 'share_with')
131
+            ->where($query->expr()->eq('share_type', $query->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
132
+            ->andWhere($query->expr()->isNotNull('share_with'));
133
+        $query->execute();
134
+
135
+        $clearQuery = $this->connection->getQueryBuilder();
136
+        $clearQuery
137
+            ->update('share')->set('share_with', $clearQuery->createNamedParameter(null))
138
+            ->where($clearQuery->expr()->eq('share_type', $clearQuery->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
139
+
140
+        $clearQuery->execute();
141
+
142
+    }
143
+
144
+    /**
145
+     * find the owner of a re-shared file/folder
146
+     *
147
+     * @param array $share
148
+     * @return array
149
+     */
150
+    private function findOwner($share) {
151
+        $currentShare = $share;
152
+        while(!is_null($currentShare['parent'])) {
153
+            if (isset($this->shareCache[$currentShare['parent']])) {
154
+                $currentShare = $this->shareCache[$currentShare['parent']];
155
+            } else {
156
+                $currentShare = $this->getShare((int)$currentShare['parent']);
157
+                $this->shareCache[$currentShare['id']] = $currentShare;
158
+            }
159
+        }
160
+
161
+        return $currentShare['uid_owner'];
162
+    }
163
+
164
+    /**
165
+     * Get $n re-shares from the database
166
+     *
167
+     * @param int $n The max number of shares to fetch
168
+     * @return \Doctrine\DBAL\Driver\Statement
169
+     */
170
+    private function getReShares() {
171
+        $query = $this->connection->getQueryBuilder();
172
+        $query->select(['id', 'parent', 'uid_owner', 'share_type'])
173
+            ->from($this->table)
174
+            ->where($query->expr()->in(
175
+                'share_type',
176
+                $query->createNamedParameter(
177
+                    [
178
+                        \OCP\Share::SHARE_TYPE_USER,
179
+                        \OCP\Share::SHARE_TYPE_GROUP,
180
+                        \OCP\Share::SHARE_TYPE_LINK,
181
+                        \OCP\Share::SHARE_TYPE_REMOTE,
182
+                    ],
183
+                    Connection::PARAM_INT_ARRAY
184
+                )
185
+            ))
186
+            ->andWhere($query->expr()->in(
187
+                'item_type',
188
+                $query->createNamedParameter(
189
+                    ['file', 'folder'],
190
+                    Connection::PARAM_STR_ARRAY
191
+                )
192
+            ))
193
+            ->andWhere($query->expr()->isNotNull('parent'))
194
+            ->orderBy('id', 'asc');
195
+        return $query->execute();
196
+
197
+
198
+        $shares = $result->fetchAll();
199
+        $result->closeCursor();
200
+
201
+        $ordered = [];
202
+        foreach ($shares as $share) {
203
+            $ordered[(int)$share['id']] = $share;
204
+        }
205
+
206
+        return $ordered;
207
+    }
208
+
209
+    /**
210
+     * Get $n re-shares from the database
211
+     *
212
+     * @param int $n The max number of shares to fetch
213
+     * @return array
214
+     */
215
+    private function getMissingInitiator($n = 1000) {
216
+        $query = $this->connection->getQueryBuilder();
217
+        $query->select(['id', 'uid_owner', 'share_type'])
218
+            ->from($this->table)
219
+            ->where($query->expr()->in(
220
+                'share_type',
221
+                $query->createNamedParameter(
222
+                    [
223
+                        \OCP\Share::SHARE_TYPE_USER,
224
+                        \OCP\Share::SHARE_TYPE_GROUP,
225
+                        \OCP\Share::SHARE_TYPE_LINK,
226
+                        \OCP\Share::SHARE_TYPE_REMOTE,
227
+                    ],
228
+                    Connection::PARAM_INT_ARRAY
229
+                )
230
+            ))
231
+            ->andWhere($query->expr()->in(
232
+                'item_type',
233
+                $query->createNamedParameter(
234
+                    ['file', 'folder'],
235
+                    Connection::PARAM_STR_ARRAY
236
+                )
237
+            ))
238
+            ->andWhere($query->expr()->isNull('uid_initiator'))
239
+            ->orderBy('id', 'asc')
240
+            ->setMaxResults($n);
241
+        $result = $query->execute();
242
+        $shares = $result->fetchAll();
243
+        $result->closeCursor();
244
+
245
+        $ordered = [];
246
+        foreach ($shares as $share) {
247
+            $ordered[(int)$share['id']] = $share;
248
+        }
249
+
250
+        return $ordered;
251
+    }
252
+
253
+    /**
254
+     * get a specific share
255
+     *
256
+     * @param int $id
257
+     * @return array
258
+     */
259
+    private function getShare($id) {
260
+        $query = $this->connection->getQueryBuilder();
261
+        $query->select(['id', 'parent', 'uid_owner'])
262
+            ->from($this->table)
263
+            ->where($query->expr()->eq('id', $query->createNamedParameter($id)));
264
+        $result = $query->execute();
265
+        $share = $result->fetchAll();
266
+        $result->closeCursor();
267
+
268
+        return $share[0];
269
+    }
270
+
271
+    /**
272
+     * update database with the new owners
273
+     *
274
+     * @param array $owners
275
+     * @throws \Exception
276
+     */
277
+    private function updateOwners($owners) {
278
+
279
+        $this->connection->beginTransaction();
280
+
281
+        try {
282
+
283
+            foreach ($owners as $id => $owner) {
284
+                $query = $this->connection->getQueryBuilder();
285
+                $query->update($this->table)
286
+                    ->set('uid_owner', $query->createNamedParameter($owner['owner']))
287
+                    ->set('uid_initiator', $query->createNamedParameter($owner['initiator']));
288
+
289
+
290
+                if ((int)$owner['type'] !== \OCP\Share::SHARE_TYPE_LINK) {
291
+                    $query->set('parent', $query->createNamedParameter(null));
292
+                }
293
+
294
+                $query->where($query->expr()->eq('id', $query->createNamedParameter($id)));
295
+
296
+                $query->execute();
297
+            }
298
+
299
+            $this->connection->commit();
300
+
301
+        } catch (\Exception $e) {
302
+            $this->connection->rollBack();
303
+            throw $e;
304
+        }
305
+
306
+    }
307 307
 
308 308
 }
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 1 patch
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -41,225 +41,225 @@
 block discarded – undo
41 41
  */
42 42
 class ProviderFactory implements IProviderFactory {
43 43
 
44
-	/** @var IServerContainer */
45
-	private $serverContainer;
46
-	/** @var DefaultShareProvider */
47
-	private $defaultProvider = null;
48
-	/** @var FederatedShareProvider */
49
-	private $federatedProvider = null;
50
-	/** @var  ShareByMailProvider */
51
-	private $shareByMailProvider;
52
-	/** @var  \OCA\Circles\ShareByCircleProvider;
53
-	 * ShareByCircleProvider */
54
-	private $shareByCircleProvider;
55
-
56
-	/**
57
-	 * IProviderFactory constructor.
58
-	 *
59
-	 * @param IServerContainer $serverContainer
60
-	 */
61
-	public function __construct(IServerContainer $serverContainer) {
62
-		$this->serverContainer = $serverContainer;
63
-	}
64
-
65
-	/**
66
-	 * Create the default share provider.
67
-	 *
68
-	 * @return DefaultShareProvider
69
-	 */
70
-	protected function defaultShareProvider() {
71
-		if ($this->defaultProvider === null) {
72
-			$this->defaultProvider = new DefaultShareProvider(
73
-				$this->serverContainer->getDatabaseConnection(),
74
-				$this->serverContainer->getUserManager(),
75
-				$this->serverContainer->getGroupManager(),
76
-				$this->serverContainer->getLazyRootFolder()
77
-			);
78
-		}
79
-
80
-		return $this->defaultProvider;
81
-	}
82
-
83
-	/**
84
-	 * Create the federated share provider
85
-	 *
86
-	 * @return FederatedShareProvider
87
-	 */
88
-	protected function federatedShareProvider() {
89
-		if ($this->federatedProvider === null) {
90
-			/*
44
+    /** @var IServerContainer */
45
+    private $serverContainer;
46
+    /** @var DefaultShareProvider */
47
+    private $defaultProvider = null;
48
+    /** @var FederatedShareProvider */
49
+    private $federatedProvider = null;
50
+    /** @var  ShareByMailProvider */
51
+    private $shareByMailProvider;
52
+    /** @var  \OCA\Circles\ShareByCircleProvider;
53
+     * ShareByCircleProvider */
54
+    private $shareByCircleProvider;
55
+
56
+    /**
57
+     * IProviderFactory constructor.
58
+     *
59
+     * @param IServerContainer $serverContainer
60
+     */
61
+    public function __construct(IServerContainer $serverContainer) {
62
+        $this->serverContainer = $serverContainer;
63
+    }
64
+
65
+    /**
66
+     * Create the default share provider.
67
+     *
68
+     * @return DefaultShareProvider
69
+     */
70
+    protected function defaultShareProvider() {
71
+        if ($this->defaultProvider === null) {
72
+            $this->defaultProvider = new DefaultShareProvider(
73
+                $this->serverContainer->getDatabaseConnection(),
74
+                $this->serverContainer->getUserManager(),
75
+                $this->serverContainer->getGroupManager(),
76
+                $this->serverContainer->getLazyRootFolder()
77
+            );
78
+        }
79
+
80
+        return $this->defaultProvider;
81
+    }
82
+
83
+    /**
84
+     * Create the federated share provider
85
+     *
86
+     * @return FederatedShareProvider
87
+     */
88
+    protected function federatedShareProvider() {
89
+        if ($this->federatedProvider === null) {
90
+            /*
91 91
 			 * Check if the app is enabled
92 92
 			 */
93
-			$appManager = $this->serverContainer->getAppManager();
94
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
95
-				return null;
96
-			}
93
+            $appManager = $this->serverContainer->getAppManager();
94
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
95
+                return null;
96
+            }
97 97
 
98
-			/*
98
+            /*
99 99
 			 * TODO: add factory to federated sharing app
100 100
 			 */
101
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
102
-			$addressHandler = new AddressHandler(
103
-				$this->serverContainer->getURLGenerator(),
104
-				$l,
105
-				$this->serverContainer->getCloudIdManager()
106
-			);
107
-			$discoveryManager = new DiscoveryManager(
108
-				$this->serverContainer->getMemCacheFactory(),
109
-				$this->serverContainer->getHTTPClientService()
110
-			);
111
-			$notifications = new Notifications(
112
-				$addressHandler,
113
-				$this->serverContainer->getHTTPClientService(),
114
-				$discoveryManager,
115
-				$this->serverContainer->getJobList()
116
-			);
117
-			$tokenHandler = new TokenHandler(
118
-				$this->serverContainer->getSecureRandom()
119
-			);
120
-
121
-			$this->federatedProvider = new FederatedShareProvider(
122
-				$this->serverContainer->getDatabaseConnection(),
123
-				$addressHandler,
124
-				$notifications,
125
-				$tokenHandler,
126
-				$l,
127
-				$this->serverContainer->getLogger(),
128
-				$this->serverContainer->getLazyRootFolder(),
129
-				$this->serverContainer->getConfig(),
130
-				$this->serverContainer->getUserManager(),
131
-				$this->serverContainer->getCloudIdManager()
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
-			/*
101
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
102
+            $addressHandler = new AddressHandler(
103
+                $this->serverContainer->getURLGenerator(),
104
+                $l,
105
+                $this->serverContainer->getCloudIdManager()
106
+            );
107
+            $discoveryManager = new DiscoveryManager(
108
+                $this->serverContainer->getMemCacheFactory(),
109
+                $this->serverContainer->getHTTPClientService()
110
+            );
111
+            $notifications = new Notifications(
112
+                $addressHandler,
113
+                $this->serverContainer->getHTTPClientService(),
114
+                $discoveryManager,
115
+                $this->serverContainer->getJobList()
116
+            );
117
+            $tokenHandler = new TokenHandler(
118
+                $this->serverContainer->getSecureRandom()
119
+            );
120
+
121
+            $this->federatedProvider = new FederatedShareProvider(
122
+                $this->serverContainer->getDatabaseConnection(),
123
+                $addressHandler,
124
+                $notifications,
125
+                $tokenHandler,
126
+                $l,
127
+                $this->serverContainer->getLogger(),
128
+                $this->serverContainer->getLazyRootFolder(),
129
+                $this->serverContainer->getConfig(),
130
+                $this->serverContainer->getUserManager(),
131
+                $this->serverContainer->getCloudIdManager()
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
-			);
167
-		}
168
-
169
-		return $this->shareByMailProvider;
170
-	}
171
-
172
-
173
-	/**
174
-	 * Create the circle share provider
175
-	 *
176
-	 * @return FederatedShareProvider
177
-	 */
178
-	protected function getShareByCircleProvider() {
179
-
180
-		$appManager = $this->serverContainer->getAppManager();
181
-		if (!$appManager->isEnabledForUser('circles')) {
182
-			return null;
183
-		}
184
-
185
-
186
-		if ($this->shareByCircleProvider === null) {
187
-
188
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
189
-				$this->serverContainer->getDatabaseConnection(),
190
-				$this->serverContainer->getSecureRandom(),
191
-				$this->serverContainer->getUserManager(),
192
-				$this->serverContainer->getLazyRootFolder(),
193
-				$this->serverContainer->getL10N('circles'),
194
-				$this->serverContainer->getLogger(),
195
-				$this->serverContainer->getURLGenerator()
196
-			);
197
-		}
198
-
199
-		return $this->shareByCircleProvider;
200
-	}
201
-
202
-
203
-	/**
204
-	 * @inheritdoc
205
-	 */
206
-	public function getProvider($id) {
207
-		$provider = null;
208
-		if ($id === 'ocinternal') {
209
-			$provider = $this->defaultShareProvider();
210
-		} else if ($id === 'ocFederatedSharing') {
211
-			$provider = $this->federatedShareProvider();
212
-		} else if ($id === 'ocMailShare') {
213
-			$provider = $this->getShareByMailProvider();
214
-		} else if ($id === 'ocCircleShare') {
215
-			$provider = $this->getShareByCircleProvider();
216
-		}
217
-
218
-		if ($provider === null) {
219
-			throw new ProviderException('No provider with id .' . $id . ' found.');
220
-		}
221
-
222
-		return $provider;
223
-	}
224
-
225
-	/**
226
-	 * @inheritdoc
227
-	 */
228
-	public function getProviderForType($shareType) {
229
-		$provider = null;
230
-
231
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
232
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
233
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
234
-		) {
235
-			$provider = $this->defaultShareProvider();
236
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
237
-			$provider = $this->federatedShareProvider();
238
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
239
-			$provider = $this->getShareByMailProvider();
240
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
241
-			$provider = $this->getShareByCircleProvider();
242
-		}
243
-
244
-
245
-		if ($provider === null) {
246
-			throw new ProviderException('No share provider for share type ' . $shareType);
247
-		}
248
-
249
-		return $provider;
250
-	}
251
-
252
-	public function getAllProviders() {
253
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
254
-		$shareByMail = $this->getShareByMailProvider();
255
-		if ($shareByMail !== null) {
256
-			$shares[] = $shareByMail;
257
-		}
258
-		$shareByCircle = $this->getShareByCircleProvider();
259
-		if ($shareByCircle !== null) {
260
-			$shares[] = $shareByCircle;
261
-		}
262
-
263
-		return $shares;
264
-	}
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
+            );
167
+        }
168
+
169
+        return $this->shareByMailProvider;
170
+    }
171
+
172
+
173
+    /**
174
+     * Create the circle share provider
175
+     *
176
+     * @return FederatedShareProvider
177
+     */
178
+    protected function getShareByCircleProvider() {
179
+
180
+        $appManager = $this->serverContainer->getAppManager();
181
+        if (!$appManager->isEnabledForUser('circles')) {
182
+            return null;
183
+        }
184
+
185
+
186
+        if ($this->shareByCircleProvider === null) {
187
+
188
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
189
+                $this->serverContainer->getDatabaseConnection(),
190
+                $this->serverContainer->getSecureRandom(),
191
+                $this->serverContainer->getUserManager(),
192
+                $this->serverContainer->getLazyRootFolder(),
193
+                $this->serverContainer->getL10N('circles'),
194
+                $this->serverContainer->getLogger(),
195
+                $this->serverContainer->getURLGenerator()
196
+            );
197
+        }
198
+
199
+        return $this->shareByCircleProvider;
200
+    }
201
+
202
+
203
+    /**
204
+     * @inheritdoc
205
+     */
206
+    public function getProvider($id) {
207
+        $provider = null;
208
+        if ($id === 'ocinternal') {
209
+            $provider = $this->defaultShareProvider();
210
+        } else if ($id === 'ocFederatedSharing') {
211
+            $provider = $this->federatedShareProvider();
212
+        } else if ($id === 'ocMailShare') {
213
+            $provider = $this->getShareByMailProvider();
214
+        } else if ($id === 'ocCircleShare') {
215
+            $provider = $this->getShareByCircleProvider();
216
+        }
217
+
218
+        if ($provider === null) {
219
+            throw new ProviderException('No provider with id .' . $id . ' found.');
220
+        }
221
+
222
+        return $provider;
223
+    }
224
+
225
+    /**
226
+     * @inheritdoc
227
+     */
228
+    public function getProviderForType($shareType) {
229
+        $provider = null;
230
+
231
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
232
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
233
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
234
+        ) {
235
+            $provider = $this->defaultShareProvider();
236
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
237
+            $provider = $this->federatedShareProvider();
238
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
239
+            $provider = $this->getShareByMailProvider();
240
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
241
+            $provider = $this->getShareByCircleProvider();
242
+        }
243
+
244
+
245
+        if ($provider === null) {
246
+            throw new ProviderException('No share provider for share type ' . $shareType);
247
+        }
248
+
249
+        return $provider;
250
+    }
251
+
252
+    public function getAllProviders() {
253
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
254
+        $shareByMail = $this->getShareByMailProvider();
255
+        if ($shareByMail !== null) {
256
+            $shares[] = $shareByMail;
257
+        }
258
+        $shareByCircle = $this->getShareByCircleProvider();
259
+        if ($shareByCircle !== null) {
260
+            $shares[] = $shareByCircle;
261
+        }
262
+
263
+        return $shares;
264
+    }
265 265
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings/Admin.php 1 patch
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -27,41 +27,41 @@
 block discarded – undo
27 27
 
28 28
 class Admin implements ISettings {
29 29
 
30
-	/** @var SettingsManager */
31
-	private $settingsManager;
30
+    /** @var SettingsManager */
31
+    private $settingsManager;
32 32
 
33
-	public function __construct(SettingsManager $settingsManager) {
34
-		$this->settingsManager = $settingsManager;
35
-	}
33
+    public function __construct(SettingsManager $settingsManager) {
34
+        $this->settingsManager = $settingsManager;
35
+    }
36 36
 
37
-	/**
38
-	 * @return TemplateResponse
39
-	 */
40
-	public function getForm() {
37
+    /**
38
+     * @return TemplateResponse
39
+     */
40
+    public function getForm() {
41 41
 
42
-		$parameters = [
43
-			'sendPasswordMail' => $this->settingsManager->sendPasswordByMail()
44
-		];
42
+        $parameters = [
43
+            'sendPasswordMail' => $this->settingsManager->sendPasswordByMail()
44
+        ];
45 45
 
46
-		return new TemplateResponse('sharebymail', 'settings-admin', $parameters, '');
47
-	}
46
+        return new TemplateResponse('sharebymail', 'settings-admin', $parameters, '');
47
+    }
48 48
 
49
-	/**
50
-	 * @return string the section ID, e.g. 'sharing'
51
-	 */
52
-	public function getSection() {
53
-		return 'sharing';
54
-	}
49
+    /**
50
+     * @return string the section ID, e.g. 'sharing'
51
+     */
52
+    public function getSection() {
53
+        return 'sharing';
54
+    }
55 55
 
56
-	/**
57
-	 * @return int whether the form should be rather on the top or bottom of
58
-	 * the admin section. The forms are arranged in ascending order of the
59
-	 * priority values. It is required to return a value between 0 and 100.
60
-	 *
61
-	 * E.g.: 70
62
-	 */
63
-	public function getPriority() {
64
-		return 40;
65
-	}
56
+    /**
57
+     * @return int whether the form should be rather on the top or bottom of
58
+     * the admin section. The forms are arranged in ascending order of the
59
+     * priority values. It is required to return a value between 0 and 100.
60
+     *
61
+     * E.g.: 70
62
+     */
63
+    public function getPriority() {
64
+        return 40;
65
+    }
66 66
 
67 67
 }
Please login to merge, or discard this patch.
apps/sharebymail/lib/Settings/SettingsManager.php 1 patch
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -27,23 +27,23 @@
 block discarded – undo
27 27
 
28 28
 class SettingsManager {
29 29
 
30
-	/** @var IConfig */
31
-	private $config;
32
-
33
-	private $defaultSetting = 'yes';
34
-
35
-	public function __construct(IConfig $config) {
36
-		$this->config = $config;
37
-	}
38
-
39
-	/**
40
-	 * should the password for a mail share be send to the recipient
41
-	 *
42
-	 * @return bool
43
-	 */
44
-	public function sendPasswordByMail() {
45
-		$sendPasswordByMail = $this->config->getAppValue('sharebymail', 'sendpasswordmail', $this->defaultSetting);
46
-		return $sendPasswordByMail === 'yes';
47
-	}
30
+    /** @var IConfig */
31
+    private $config;
32
+
33
+    private $defaultSetting = 'yes';
34
+
35
+    public function __construct(IConfig $config) {
36
+        $this->config = $config;
37
+    }
38
+
39
+    /**
40
+     * should the password for a mail share be send to the recipient
41
+     *
42
+     * @return bool
43
+     */
44
+    public function sendPasswordByMail() {
45
+        $sendPasswordByMail = $this->config->getAppValue('sharebymail', 'sendpasswordmail', $this->defaultSetting);
46
+        return $sendPasswordByMail === 'yes';
47
+    }
48 48
 
49 49
 }
Please login to merge, or discard this patch.
lib/private/Share20/DefaultShareProvider.php 1 patch
Indentation   +990 added lines, -990 removed lines patch added patch discarded remove patch
@@ -47,1027 +47,1027 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', 's.file_source = f.fileid');
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073 1073
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 1 patch
Indentation   +1270 added lines, -1270 removed lines patch added patch discarded remove patch
@@ -57,1298 +57,1298 @@
 block discarded – undo
57 57
  */
58 58
 class Manager implements IManager {
59 59
 
60
-	/** @var IProviderFactory */
61
-	private $factory;
62
-	/** @var ILogger */
63
-	private $logger;
64
-	/** @var IConfig */
65
-	private $config;
66
-	/** @var ISecureRandom */
67
-	private $secureRandom;
68
-	/** @var IHasher */
69
-	private $hasher;
70
-	/** @var IMountManager */
71
-	private $mountManager;
72
-	/** @var IGroupManager */
73
-	private $groupManager;
74
-	/** @var IL10N */
75
-	private $l;
76
-	/** @var IUserManager */
77
-	private $userManager;
78
-	/** @var IRootFolder */
79
-	private $rootFolder;
80
-	/** @var CappedMemoryCache */
81
-	private $sharingDisabledForUsersCache;
82
-	/** @var EventDispatcher */
83
-	private $eventDispatcher;
84
-	/** @var LegacyHooks */
85
-	private $legacyHooks;
86
-
87
-
88
-	/**
89
-	 * Manager constructor.
90
-	 *
91
-	 * @param ILogger $logger
92
-	 * @param IConfig $config
93
-	 * @param ISecureRandom $secureRandom
94
-	 * @param IHasher $hasher
95
-	 * @param IMountManager $mountManager
96
-	 * @param IGroupManager $groupManager
97
-	 * @param IL10N $l
98
-	 * @param IProviderFactory $factory
99
-	 * @param IUserManager $userManager
100
-	 * @param IRootFolder $rootFolder
101
-	 * @param EventDispatcher $eventDispatcher
102
-	 */
103
-	public function __construct(
104
-			ILogger $logger,
105
-			IConfig $config,
106
-			ISecureRandom $secureRandom,
107
-			IHasher $hasher,
108
-			IMountManager $mountManager,
109
-			IGroupManager $groupManager,
110
-			IL10N $l,
111
-			IProviderFactory $factory,
112
-			IUserManager $userManager,
113
-			IRootFolder $rootFolder,
114
-			EventDispatcher $eventDispatcher
115
-	) {
116
-		$this->logger = $logger;
117
-		$this->config = $config;
118
-		$this->secureRandom = $secureRandom;
119
-		$this->hasher = $hasher;
120
-		$this->mountManager = $mountManager;
121
-		$this->groupManager = $groupManager;
122
-		$this->l = $l;
123
-		$this->factory = $factory;
124
-		$this->userManager = $userManager;
125
-		$this->rootFolder = $rootFolder;
126
-		$this->eventDispatcher = $eventDispatcher;
127
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
128
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
129
-	}
130
-
131
-	/**
132
-	 * Convert from a full share id to a tuple (providerId, shareId)
133
-	 *
134
-	 * @param string $id
135
-	 * @return string[]
136
-	 */
137
-	private function splitFullId($id) {
138
-		return explode(':', $id, 2);
139
-	}
140
-
141
-	/**
142
-	 * Verify if a password meets all requirements
143
-	 *
144
-	 * @param string $password
145
-	 * @throws \Exception
146
-	 */
147
-	protected function verifyPassword($password) {
148
-		if ($password === null) {
149
-			// No password is set, check if this is allowed.
150
-			if ($this->shareApiLinkEnforcePassword()) {
151
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
152
-			}
153
-
154
-			return;
155
-		}
156
-
157
-		// Let others verify the password
158
-		try {
159
-			$event = new GenericEvent($password);
160
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
161
-		} catch (HintException $e) {
162
-			throw new \Exception($e->getHint());
163
-		}
164
-	}
165
-
166
-	/**
167
-	 * Check for generic requirements before creating a share
168
-	 *
169
-	 * @param \OCP\Share\IShare $share
170
-	 * @throws \InvalidArgumentException
171
-	 * @throws GenericShareException
172
-	 */
173
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
174
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
175
-			// We expect a valid user as sharedWith for user shares
176
-			if (!$this->userManager->userExists($share->getSharedWith())) {
177
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
178
-			}
179
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
180
-			// We expect a valid group as sharedWith for group shares
181
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
182
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
183
-			}
184
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
185
-			if ($share->getSharedWith() !== null) {
186
-				throw new \InvalidArgumentException('SharedWith should be empty');
187
-			}
188
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
189
-			if ($share->getSharedWith() === null) {
190
-				throw new \InvalidArgumentException('SharedWith should not be empty');
191
-			}
192
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
193
-			if ($share->getSharedWith() === null) {
194
-				throw new \InvalidArgumentException('SharedWith should not be empty');
195
-			}
196
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
198
-			if ($circle === null) {
199
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
200
-			}
201
-		} else {
202
-			// We can't handle other types yet
203
-			throw new \InvalidArgumentException('unknown share type');
204
-		}
205
-
206
-		// Verify the initiator of the share is set
207
-		if ($share->getSharedBy() === null) {
208
-			throw new \InvalidArgumentException('SharedBy should be set');
209
-		}
210
-
211
-		// Cannot share with yourself
212
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
213
-			$share->getSharedWith() === $share->getSharedBy()) {
214
-			throw new \InvalidArgumentException('Can\'t share with yourself');
215
-		}
216
-
217
-		// The path should be set
218
-		if ($share->getNode() === null) {
219
-			throw new \InvalidArgumentException('Path should be set');
220
-		}
221
-
222
-		// And it should be a file or a folder
223
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
224
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
225
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
226
-		}
227
-
228
-		// And you can't share your rootfolder
229
-		if ($this->userManager->userExists($share->getSharedBy())) {
230
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
231
-		} else {
232
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
233
-		}
234
-		if ($sharedPath === $share->getNode()->getPath()) {
235
-			throw new \InvalidArgumentException('You can\'t share your root folder');
236
-		}
237
-
238
-		// Check if we actually have share permissions
239
-		if (!$share->getNode()->isShareable()) {
240
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
241
-			throw new GenericShareException($message_t, $message_t, 404);
242
-		}
243
-
244
-		// Permissions should be set
245
-		if ($share->getPermissions() === null) {
246
-			throw new \InvalidArgumentException('A share requires permissions');
247
-		}
248
-
249
-		/*
60
+    /** @var IProviderFactory */
61
+    private $factory;
62
+    /** @var ILogger */
63
+    private $logger;
64
+    /** @var IConfig */
65
+    private $config;
66
+    /** @var ISecureRandom */
67
+    private $secureRandom;
68
+    /** @var IHasher */
69
+    private $hasher;
70
+    /** @var IMountManager */
71
+    private $mountManager;
72
+    /** @var IGroupManager */
73
+    private $groupManager;
74
+    /** @var IL10N */
75
+    private $l;
76
+    /** @var IUserManager */
77
+    private $userManager;
78
+    /** @var IRootFolder */
79
+    private $rootFolder;
80
+    /** @var CappedMemoryCache */
81
+    private $sharingDisabledForUsersCache;
82
+    /** @var EventDispatcher */
83
+    private $eventDispatcher;
84
+    /** @var LegacyHooks */
85
+    private $legacyHooks;
86
+
87
+
88
+    /**
89
+     * Manager constructor.
90
+     *
91
+     * @param ILogger $logger
92
+     * @param IConfig $config
93
+     * @param ISecureRandom $secureRandom
94
+     * @param IHasher $hasher
95
+     * @param IMountManager $mountManager
96
+     * @param IGroupManager $groupManager
97
+     * @param IL10N $l
98
+     * @param IProviderFactory $factory
99
+     * @param IUserManager $userManager
100
+     * @param IRootFolder $rootFolder
101
+     * @param EventDispatcher $eventDispatcher
102
+     */
103
+    public function __construct(
104
+            ILogger $logger,
105
+            IConfig $config,
106
+            ISecureRandom $secureRandom,
107
+            IHasher $hasher,
108
+            IMountManager $mountManager,
109
+            IGroupManager $groupManager,
110
+            IL10N $l,
111
+            IProviderFactory $factory,
112
+            IUserManager $userManager,
113
+            IRootFolder $rootFolder,
114
+            EventDispatcher $eventDispatcher
115
+    ) {
116
+        $this->logger = $logger;
117
+        $this->config = $config;
118
+        $this->secureRandom = $secureRandom;
119
+        $this->hasher = $hasher;
120
+        $this->mountManager = $mountManager;
121
+        $this->groupManager = $groupManager;
122
+        $this->l = $l;
123
+        $this->factory = $factory;
124
+        $this->userManager = $userManager;
125
+        $this->rootFolder = $rootFolder;
126
+        $this->eventDispatcher = $eventDispatcher;
127
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
128
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
129
+    }
130
+
131
+    /**
132
+     * Convert from a full share id to a tuple (providerId, shareId)
133
+     *
134
+     * @param string $id
135
+     * @return string[]
136
+     */
137
+    private function splitFullId($id) {
138
+        return explode(':', $id, 2);
139
+    }
140
+
141
+    /**
142
+     * Verify if a password meets all requirements
143
+     *
144
+     * @param string $password
145
+     * @throws \Exception
146
+     */
147
+    protected function verifyPassword($password) {
148
+        if ($password === null) {
149
+            // No password is set, check if this is allowed.
150
+            if ($this->shareApiLinkEnforcePassword()) {
151
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
152
+            }
153
+
154
+            return;
155
+        }
156
+
157
+        // Let others verify the password
158
+        try {
159
+            $event = new GenericEvent($password);
160
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
161
+        } catch (HintException $e) {
162
+            throw new \Exception($e->getHint());
163
+        }
164
+    }
165
+
166
+    /**
167
+     * Check for generic requirements before creating a share
168
+     *
169
+     * @param \OCP\Share\IShare $share
170
+     * @throws \InvalidArgumentException
171
+     * @throws GenericShareException
172
+     */
173
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
174
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
175
+            // We expect a valid user as sharedWith for user shares
176
+            if (!$this->userManager->userExists($share->getSharedWith())) {
177
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
178
+            }
179
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
180
+            // We expect a valid group as sharedWith for group shares
181
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
182
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
183
+            }
184
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
185
+            if ($share->getSharedWith() !== null) {
186
+                throw new \InvalidArgumentException('SharedWith should be empty');
187
+            }
188
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
189
+            if ($share->getSharedWith() === null) {
190
+                throw new \InvalidArgumentException('SharedWith should not be empty');
191
+            }
192
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
193
+            if ($share->getSharedWith() === null) {
194
+                throw new \InvalidArgumentException('SharedWith should not be empty');
195
+            }
196
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($share->getSharedWith());
198
+            if ($circle === null) {
199
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
200
+            }
201
+        } else {
202
+            // We can't handle other types yet
203
+            throw new \InvalidArgumentException('unknown share type');
204
+        }
205
+
206
+        // Verify the initiator of the share is set
207
+        if ($share->getSharedBy() === null) {
208
+            throw new \InvalidArgumentException('SharedBy should be set');
209
+        }
210
+
211
+        // Cannot share with yourself
212
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
213
+            $share->getSharedWith() === $share->getSharedBy()) {
214
+            throw new \InvalidArgumentException('Can\'t share with yourself');
215
+        }
216
+
217
+        // The path should be set
218
+        if ($share->getNode() === null) {
219
+            throw new \InvalidArgumentException('Path should be set');
220
+        }
221
+
222
+        // And it should be a file or a folder
223
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
224
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
225
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
226
+        }
227
+
228
+        // And you can't share your rootfolder
229
+        if ($this->userManager->userExists($share->getSharedBy())) {
230
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
231
+        } else {
232
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
233
+        }
234
+        if ($sharedPath === $share->getNode()->getPath()) {
235
+            throw new \InvalidArgumentException('You can\'t share your root folder');
236
+        }
237
+
238
+        // Check if we actually have share permissions
239
+        if (!$share->getNode()->isShareable()) {
240
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
241
+            throw new GenericShareException($message_t, $message_t, 404);
242
+        }
243
+
244
+        // Permissions should be set
245
+        if ($share->getPermissions() === null) {
246
+            throw new \InvalidArgumentException('A share requires permissions');
247
+        }
248
+
249
+        /*
250 250
 		 * Quick fix for #23536
251 251
 		 * Non moveable mount points do not have update and delete permissions
252 252
 		 * while we 'most likely' do have that on the storage.
253 253
 		 */
254
-		$permissions = $share->getNode()->getPermissions();
255
-		$mount = $share->getNode()->getMountPoint();
256
-		if (!($mount instanceof MoveableMount)) {
257
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
258
-		}
259
-
260
-		// Check that we do not share with more permissions than we have
261
-		if ($share->getPermissions() & ~$permissions) {
262
-			$message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
263
-			throw new GenericShareException($message_t, $message_t, 404);
264
-		}
265
-
266
-
267
-		// Check that read permissions are always set
268
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
269
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
270
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
271
-		if (!$noReadPermissionRequired &&
272
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
273
-			throw new \InvalidArgumentException('Shares need at least read permissions');
274
-		}
275
-
276
-		if ($share->getNode() instanceof \OCP\Files\File) {
277
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
278
-				$message_t = $this->l->t('Files can\'t be shared with delete permissions');
279
-				throw new GenericShareException($message_t);
280
-			}
281
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
282
-				$message_t = $this->l->t('Files can\'t be shared with create permissions');
283
-				throw new GenericShareException($message_t);
284
-			}
285
-		}
286
-	}
287
-
288
-	/**
289
-	 * Validate if the expiration date fits the system settings
290
-	 *
291
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
292
-	 * @return \OCP\Share\IShare The modified share object
293
-	 * @throws GenericShareException
294
-	 * @throws \InvalidArgumentException
295
-	 * @throws \Exception
296
-	 */
297
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
298
-
299
-		$expirationDate = $share->getExpirationDate();
300
-
301
-		if ($expirationDate !== null) {
302
-			//Make sure the expiration date is a date
303
-			$expirationDate->setTime(0, 0, 0);
304
-
305
-			$date = new \DateTime();
306
-			$date->setTime(0, 0, 0);
307
-			if ($date >= $expirationDate) {
308
-				$message = $this->l->t('Expiration date is in the past');
309
-				throw new GenericShareException($message, $message, 404);
310
-			}
311
-		}
312
-
313
-		// If expiredate is empty set a default one if there is a default
314
-		$fullId = null;
315
-		try {
316
-			$fullId = $share->getFullId();
317
-		} catch (\UnexpectedValueException $e) {
318
-			// This is a new share
319
-		}
320
-
321
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
322
-			$expirationDate = new \DateTime();
323
-			$expirationDate->setTime(0,0,0);
324
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
325
-		}
326
-
327
-		// If we enforce the expiration date check that is does not exceed
328
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
329
-			if ($expirationDate === null) {
330
-				throw new \InvalidArgumentException('Expiration date is enforced');
331
-			}
332
-
333
-			$date = new \DateTime();
334
-			$date->setTime(0, 0, 0);
335
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
336
-			if ($date < $expirationDate) {
337
-				$message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
338
-				throw new GenericShareException($message, $message, 404);
339
-			}
340
-		}
341
-
342
-		$accepted = true;
343
-		$message = '';
344
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
345
-			'expirationDate' => &$expirationDate,
346
-			'accepted' => &$accepted,
347
-			'message' => &$message,
348
-			'passwordSet' => $share->getPassword() !== null,
349
-		]);
350
-
351
-		if (!$accepted) {
352
-			throw new \Exception($message);
353
-		}
354
-
355
-		$share->setExpirationDate($expirationDate);
356
-
357
-		return $share;
358
-	}
359
-
360
-	/**
361
-	 * Check for pre share requirements for user shares
362
-	 *
363
-	 * @param \OCP\Share\IShare $share
364
-	 * @throws \Exception
365
-	 */
366
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
367
-		// Check if we can share with group members only
368
-		if ($this->shareWithGroupMembersOnly()) {
369
-			$sharedBy = $this->userManager->get($share->getSharedBy());
370
-			$sharedWith = $this->userManager->get($share->getSharedWith());
371
-			// Verify we can share with this user
372
-			$groups = array_intersect(
373
-					$this->groupManager->getUserGroupIds($sharedBy),
374
-					$this->groupManager->getUserGroupIds($sharedWith)
375
-			);
376
-			if (empty($groups)) {
377
-				throw new \Exception('Only sharing with group members is allowed');
378
-			}
379
-		}
380
-
381
-		/*
254
+        $permissions = $share->getNode()->getPermissions();
255
+        $mount = $share->getNode()->getMountPoint();
256
+        if (!($mount instanceof MoveableMount)) {
257
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
258
+        }
259
+
260
+        // Check that we do not share with more permissions than we have
261
+        if ($share->getPermissions() & ~$permissions) {
262
+            $message_t = $this->l->t('Cannot increase permissions of %s', [$share->getNode()->getPath()]);
263
+            throw new GenericShareException($message_t, $message_t, 404);
264
+        }
265
+
266
+
267
+        // Check that read permissions are always set
268
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
269
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
270
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
271
+        if (!$noReadPermissionRequired &&
272
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
273
+            throw new \InvalidArgumentException('Shares need at least read permissions');
274
+        }
275
+
276
+        if ($share->getNode() instanceof \OCP\Files\File) {
277
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
278
+                $message_t = $this->l->t('Files can\'t be shared with delete permissions');
279
+                throw new GenericShareException($message_t);
280
+            }
281
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
282
+                $message_t = $this->l->t('Files can\'t be shared with create permissions');
283
+                throw new GenericShareException($message_t);
284
+            }
285
+        }
286
+    }
287
+
288
+    /**
289
+     * Validate if the expiration date fits the system settings
290
+     *
291
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
292
+     * @return \OCP\Share\IShare The modified share object
293
+     * @throws GenericShareException
294
+     * @throws \InvalidArgumentException
295
+     * @throws \Exception
296
+     */
297
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
298
+
299
+        $expirationDate = $share->getExpirationDate();
300
+
301
+        if ($expirationDate !== null) {
302
+            //Make sure the expiration date is a date
303
+            $expirationDate->setTime(0, 0, 0);
304
+
305
+            $date = new \DateTime();
306
+            $date->setTime(0, 0, 0);
307
+            if ($date >= $expirationDate) {
308
+                $message = $this->l->t('Expiration date is in the past');
309
+                throw new GenericShareException($message, $message, 404);
310
+            }
311
+        }
312
+
313
+        // If expiredate is empty set a default one if there is a default
314
+        $fullId = null;
315
+        try {
316
+            $fullId = $share->getFullId();
317
+        } catch (\UnexpectedValueException $e) {
318
+            // This is a new share
319
+        }
320
+
321
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
322
+            $expirationDate = new \DateTime();
323
+            $expirationDate->setTime(0,0,0);
324
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
325
+        }
326
+
327
+        // If we enforce the expiration date check that is does not exceed
328
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
329
+            if ($expirationDate === null) {
330
+                throw new \InvalidArgumentException('Expiration date is enforced');
331
+            }
332
+
333
+            $date = new \DateTime();
334
+            $date->setTime(0, 0, 0);
335
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
336
+            if ($date < $expirationDate) {
337
+                $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
338
+                throw new GenericShareException($message, $message, 404);
339
+            }
340
+        }
341
+
342
+        $accepted = true;
343
+        $message = '';
344
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
345
+            'expirationDate' => &$expirationDate,
346
+            'accepted' => &$accepted,
347
+            'message' => &$message,
348
+            'passwordSet' => $share->getPassword() !== null,
349
+        ]);
350
+
351
+        if (!$accepted) {
352
+            throw new \Exception($message);
353
+        }
354
+
355
+        $share->setExpirationDate($expirationDate);
356
+
357
+        return $share;
358
+    }
359
+
360
+    /**
361
+     * Check for pre share requirements for user shares
362
+     *
363
+     * @param \OCP\Share\IShare $share
364
+     * @throws \Exception
365
+     */
366
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
367
+        // Check if we can share with group members only
368
+        if ($this->shareWithGroupMembersOnly()) {
369
+            $sharedBy = $this->userManager->get($share->getSharedBy());
370
+            $sharedWith = $this->userManager->get($share->getSharedWith());
371
+            // Verify we can share with this user
372
+            $groups = array_intersect(
373
+                    $this->groupManager->getUserGroupIds($sharedBy),
374
+                    $this->groupManager->getUserGroupIds($sharedWith)
375
+            );
376
+            if (empty($groups)) {
377
+                throw new \Exception('Only sharing with group members is allowed');
378
+            }
379
+        }
380
+
381
+        /*
382 382
 		 * TODO: Could be costly, fix
383 383
 		 *
384 384
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
385 385
 		 */
386
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
387
-		$existingShares = $provider->getSharesByPath($share->getNode());
388
-		foreach($existingShares as $existingShare) {
389
-			// Ignore if it is the same share
390
-			try {
391
-				if ($existingShare->getFullId() === $share->getFullId()) {
392
-					continue;
393
-				}
394
-			} catch (\UnexpectedValueException $e) {
395
-				//Shares are not identical
396
-			}
397
-
398
-			// Identical share already existst
399
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
400
-				throw new \Exception('Path already shared with this user');
401
-			}
402
-
403
-			// The share is already shared with this user via a group share
404
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
405
-				$group = $this->groupManager->get($existingShare->getSharedWith());
406
-				if (!is_null($group)) {
407
-					$user = $this->userManager->get($share->getSharedWith());
408
-
409
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
410
-						throw new \Exception('Path already shared with this user');
411
-					}
412
-				}
413
-			}
414
-		}
415
-	}
416
-
417
-	/**
418
-	 * Check for pre share requirements for group shares
419
-	 *
420
-	 * @param \OCP\Share\IShare $share
421
-	 * @throws \Exception
422
-	 */
423
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
424
-		// Verify group shares are allowed
425
-		if (!$this->allowGroupSharing()) {
426
-			throw new \Exception('Group sharing is now allowed');
427
-		}
428
-
429
-		// Verify if the user can share with this group
430
-		if ($this->shareWithGroupMembersOnly()) {
431
-			$sharedBy = $this->userManager->get($share->getSharedBy());
432
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
433
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
434
-				throw new \Exception('Only sharing within your own groups is allowed');
435
-			}
436
-		}
437
-
438
-		/*
386
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
387
+        $existingShares = $provider->getSharesByPath($share->getNode());
388
+        foreach($existingShares as $existingShare) {
389
+            // Ignore if it is the same share
390
+            try {
391
+                if ($existingShare->getFullId() === $share->getFullId()) {
392
+                    continue;
393
+                }
394
+            } catch (\UnexpectedValueException $e) {
395
+                //Shares are not identical
396
+            }
397
+
398
+            // Identical share already existst
399
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
400
+                throw new \Exception('Path already shared with this user');
401
+            }
402
+
403
+            // The share is already shared with this user via a group share
404
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
405
+                $group = $this->groupManager->get($existingShare->getSharedWith());
406
+                if (!is_null($group)) {
407
+                    $user = $this->userManager->get($share->getSharedWith());
408
+
409
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
410
+                        throw new \Exception('Path already shared with this user');
411
+                    }
412
+                }
413
+            }
414
+        }
415
+    }
416
+
417
+    /**
418
+     * Check for pre share requirements for group shares
419
+     *
420
+     * @param \OCP\Share\IShare $share
421
+     * @throws \Exception
422
+     */
423
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
424
+        // Verify group shares are allowed
425
+        if (!$this->allowGroupSharing()) {
426
+            throw new \Exception('Group sharing is now allowed');
427
+        }
428
+
429
+        // Verify if the user can share with this group
430
+        if ($this->shareWithGroupMembersOnly()) {
431
+            $sharedBy = $this->userManager->get($share->getSharedBy());
432
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
433
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
434
+                throw new \Exception('Only sharing within your own groups is allowed');
435
+            }
436
+        }
437
+
438
+        /*
439 439
 		 * TODO: Could be costly, fix
440 440
 		 *
441 441
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
442 442
 		 */
443
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
444
-		$existingShares = $provider->getSharesByPath($share->getNode());
445
-		foreach($existingShares as $existingShare) {
446
-			try {
447
-				if ($existingShare->getFullId() === $share->getFullId()) {
448
-					continue;
449
-				}
450
-			} catch (\UnexpectedValueException $e) {
451
-				//It is a new share so just continue
452
-			}
453
-
454
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
455
-				throw new \Exception('Path already shared with this group');
456
-			}
457
-		}
458
-	}
459
-
460
-	/**
461
-	 * Check for pre share requirements for link shares
462
-	 *
463
-	 * @param \OCP\Share\IShare $share
464
-	 * @throws \Exception
465
-	 */
466
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
467
-		// Are link shares allowed?
468
-		if (!$this->shareApiAllowLinks()) {
469
-			throw new \Exception('Link sharing not allowed');
470
-		}
471
-
472
-		// Link shares by definition can't have share permissions
473
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
474
-			throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
475
-		}
476
-
477
-		// Check if public upload is allowed
478
-		if (!$this->shareApiLinkAllowPublicUpload() &&
479
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
480
-			throw new \InvalidArgumentException('Public upload not allowed');
481
-		}
482
-	}
483
-
484
-	/**
485
-	 * To make sure we don't get invisible link shares we set the parent
486
-	 * of a link if it is a reshare. This is a quick word around
487
-	 * until we can properly display multiple link shares in the UI
488
-	 *
489
-	 * See: https://github.com/owncloud/core/issues/22295
490
-	 *
491
-	 * FIXME: Remove once multiple link shares can be properly displayed
492
-	 *
493
-	 * @param \OCP\Share\IShare $share
494
-	 */
495
-	protected function setLinkParent(\OCP\Share\IShare $share) {
496
-
497
-		// No sense in checking if the method is not there.
498
-		if (method_exists($share, 'setParent')) {
499
-			$storage = $share->getNode()->getStorage();
500
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
501
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
502
-				$share->setParent($storage->getShareId());
503
-			}
504
-		};
505
-	}
506
-
507
-	/**
508
-	 * @param File|Folder $path
509
-	 */
510
-	protected function pathCreateChecks($path) {
511
-		// Make sure that we do not share a path that contains a shared mountpoint
512
-		if ($path instanceof \OCP\Files\Folder) {
513
-			$mounts = $this->mountManager->findIn($path->getPath());
514
-			foreach($mounts as $mount) {
515
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
516
-					throw new \InvalidArgumentException('Path contains files shared with you');
517
-				}
518
-			}
519
-		}
520
-	}
521
-
522
-	/**
523
-	 * Check if the user that is sharing can actually share
524
-	 *
525
-	 * @param \OCP\Share\IShare $share
526
-	 * @throws \Exception
527
-	 */
528
-	protected function canShare(\OCP\Share\IShare $share) {
529
-		if (!$this->shareApiEnabled()) {
530
-			throw new \Exception('The share API is disabled');
531
-		}
532
-
533
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
534
-			throw new \Exception('You are not allowed to share');
535
-		}
536
-	}
537
-
538
-	/**
539
-	 * Share a path
540
-	 *
541
-	 * @param \OCP\Share\IShare $share
542
-	 * @return Share The share object
543
-	 * @throws \Exception
544
-	 *
545
-	 * TODO: handle link share permissions or check them
546
-	 */
547
-	public function createShare(\OCP\Share\IShare $share) {
548
-		$this->canShare($share);
549
-
550
-		$this->generalCreateChecks($share);
551
-
552
-		// Verify if there are any issues with the path
553
-		$this->pathCreateChecks($share->getNode());
554
-
555
-		/*
443
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
444
+        $existingShares = $provider->getSharesByPath($share->getNode());
445
+        foreach($existingShares as $existingShare) {
446
+            try {
447
+                if ($existingShare->getFullId() === $share->getFullId()) {
448
+                    continue;
449
+                }
450
+            } catch (\UnexpectedValueException $e) {
451
+                //It is a new share so just continue
452
+            }
453
+
454
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
455
+                throw new \Exception('Path already shared with this group');
456
+            }
457
+        }
458
+    }
459
+
460
+    /**
461
+     * Check for pre share requirements for link shares
462
+     *
463
+     * @param \OCP\Share\IShare $share
464
+     * @throws \Exception
465
+     */
466
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
467
+        // Are link shares allowed?
468
+        if (!$this->shareApiAllowLinks()) {
469
+            throw new \Exception('Link sharing not allowed');
470
+        }
471
+
472
+        // Link shares by definition can't have share permissions
473
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
474
+            throw new \InvalidArgumentException('Link shares can\'t have reshare permissions');
475
+        }
476
+
477
+        // Check if public upload is allowed
478
+        if (!$this->shareApiLinkAllowPublicUpload() &&
479
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
480
+            throw new \InvalidArgumentException('Public upload not allowed');
481
+        }
482
+    }
483
+
484
+    /**
485
+     * To make sure we don't get invisible link shares we set the parent
486
+     * of a link if it is a reshare. This is a quick word around
487
+     * until we can properly display multiple link shares in the UI
488
+     *
489
+     * See: https://github.com/owncloud/core/issues/22295
490
+     *
491
+     * FIXME: Remove once multiple link shares can be properly displayed
492
+     *
493
+     * @param \OCP\Share\IShare $share
494
+     */
495
+    protected function setLinkParent(\OCP\Share\IShare $share) {
496
+
497
+        // No sense in checking if the method is not there.
498
+        if (method_exists($share, 'setParent')) {
499
+            $storage = $share->getNode()->getStorage();
500
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
501
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
502
+                $share->setParent($storage->getShareId());
503
+            }
504
+        };
505
+    }
506
+
507
+    /**
508
+     * @param File|Folder $path
509
+     */
510
+    protected function pathCreateChecks($path) {
511
+        // Make sure that we do not share a path that contains a shared mountpoint
512
+        if ($path instanceof \OCP\Files\Folder) {
513
+            $mounts = $this->mountManager->findIn($path->getPath());
514
+            foreach($mounts as $mount) {
515
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
516
+                    throw new \InvalidArgumentException('Path contains files shared with you');
517
+                }
518
+            }
519
+        }
520
+    }
521
+
522
+    /**
523
+     * Check if the user that is sharing can actually share
524
+     *
525
+     * @param \OCP\Share\IShare $share
526
+     * @throws \Exception
527
+     */
528
+    protected function canShare(\OCP\Share\IShare $share) {
529
+        if (!$this->shareApiEnabled()) {
530
+            throw new \Exception('The share API is disabled');
531
+        }
532
+
533
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
534
+            throw new \Exception('You are not allowed to share');
535
+        }
536
+    }
537
+
538
+    /**
539
+     * Share a path
540
+     *
541
+     * @param \OCP\Share\IShare $share
542
+     * @return Share The share object
543
+     * @throws \Exception
544
+     *
545
+     * TODO: handle link share permissions or check them
546
+     */
547
+    public function createShare(\OCP\Share\IShare $share) {
548
+        $this->canShare($share);
549
+
550
+        $this->generalCreateChecks($share);
551
+
552
+        // Verify if there are any issues with the path
553
+        $this->pathCreateChecks($share->getNode());
554
+
555
+        /*
556 556
 		 * On creation of a share the owner is always the owner of the path
557 557
 		 * Except for mounted federated shares.
558 558
 		 */
559
-		$storage = $share->getNode()->getStorage();
560
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
561
-			$parent = $share->getNode()->getParent();
562
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
563
-				$parent = $parent->getParent();
564
-			}
565
-			$share->setShareOwner($parent->getOwner()->getUID());
566
-		} else {
567
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
568
-		}
569
-
570
-		//Verify share type
571
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
572
-			$this->userCreateChecks($share);
573
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
574
-			$this->groupCreateChecks($share);
575
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
576
-			$this->linkCreateChecks($share);
577
-			$this->setLinkParent($share);
578
-
579
-			/*
559
+        $storage = $share->getNode()->getStorage();
560
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
561
+            $parent = $share->getNode()->getParent();
562
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
563
+                $parent = $parent->getParent();
564
+            }
565
+            $share->setShareOwner($parent->getOwner()->getUID());
566
+        } else {
567
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
568
+        }
569
+
570
+        //Verify share type
571
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
572
+            $this->userCreateChecks($share);
573
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
574
+            $this->groupCreateChecks($share);
575
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
576
+            $this->linkCreateChecks($share);
577
+            $this->setLinkParent($share);
578
+
579
+            /*
580 580
 			 * For now ignore a set token.
581 581
 			 */
582
-			$share->setToken(
583
-				$this->secureRandom->generate(
584
-					\OC\Share\Constants::TOKEN_LENGTH,
585
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
586
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
587
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
588
-				)
589
-			);
590
-
591
-			//Verify the expiration date
592
-			$this->validateExpirationDate($share);
593
-
594
-			//Verify the password
595
-			$this->verifyPassword($share->getPassword());
596
-
597
-			// If a password is set. Hash it!
598
-			if ($share->getPassword() !== null) {
599
-				$share->setPassword($this->hasher->hash($share->getPassword()));
600
-			}
601
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
602
-			$share->setToken(
603
-				$this->secureRandom->generate(
604
-					\OC\Share\Constants::TOKEN_LENGTH,
605
-					\OCP\Security\ISecureRandom::CHAR_LOWER.
606
-					\OCP\Security\ISecureRandom::CHAR_UPPER.
607
-					\OCP\Security\ISecureRandom::CHAR_DIGITS
608
-				)
609
-			);
610
-		}
611
-
612
-		// Cannot share with the owner
613
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
614
-			$share->getSharedWith() === $share->getShareOwner()) {
615
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
616
-		}
617
-
618
-		// Generate the target
619
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
620
-		$target = \OC\Files\Filesystem::normalizePath($target);
621
-		$share->setTarget($target);
622
-
623
-		// Pre share hook
624
-		$run = true;
625
-		$error = '';
626
-		$preHookData = [
627
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
628
-			'itemSource' => $share->getNode()->getId(),
629
-			'shareType' => $share->getShareType(),
630
-			'uidOwner' => $share->getSharedBy(),
631
-			'permissions' => $share->getPermissions(),
632
-			'fileSource' => $share->getNode()->getId(),
633
-			'expiration' => $share->getExpirationDate(),
634
-			'token' => $share->getToken(),
635
-			'itemTarget' => $share->getTarget(),
636
-			'shareWith' => $share->getSharedWith(),
637
-			'run' => &$run,
638
-			'error' => &$error,
639
-		];
640
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
641
-
642
-		if ($run === false) {
643
-			throw new \Exception($error);
644
-		}
645
-
646
-		$oldShare = $share;
647
-		$provider = $this->factory->getProviderForType($share->getShareType());
648
-		$share = $provider->create($share);
649
-		//reuse the node we already have
650
-		$share->setNode($oldShare->getNode());
651
-
652
-		// Post share hook
653
-		$postHookData = [
654
-			'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
655
-			'itemSource' => $share->getNode()->getId(),
656
-			'shareType' => $share->getShareType(),
657
-			'uidOwner' => $share->getSharedBy(),
658
-			'permissions' => $share->getPermissions(),
659
-			'fileSource' => $share->getNode()->getId(),
660
-			'expiration' => $share->getExpirationDate(),
661
-			'token' => $share->getToken(),
662
-			'id' => $share->getId(),
663
-			'shareWith' => $share->getSharedWith(),
664
-			'itemTarget' => $share->getTarget(),
665
-			'fileTarget' => $share->getTarget(),
666
-		];
667
-
668
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
669
-
670
-		return $share;
671
-	}
672
-
673
-	/**
674
-	 * Update a share
675
-	 *
676
-	 * @param \OCP\Share\IShare $share
677
-	 * @return \OCP\Share\IShare The share object
678
-	 * @throws \InvalidArgumentException
679
-	 */
680
-	public function updateShare(\OCP\Share\IShare $share) {
681
-		$expirationDateUpdated = false;
682
-
683
-		$this->canShare($share);
684
-
685
-		try {
686
-			$originalShare = $this->getShareById($share->getFullId());
687
-		} catch (\UnexpectedValueException $e) {
688
-			throw new \InvalidArgumentException('Share does not have a full id');
689
-		}
690
-
691
-		// We can't change the share type!
692
-		if ($share->getShareType() !== $originalShare->getShareType()) {
693
-			throw new \InvalidArgumentException('Can\'t change share type');
694
-		}
695
-
696
-		// We can only change the recipient on user shares
697
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
698
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
699
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
700
-		}
701
-
702
-		// Cannot share with the owner
703
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
704
-			$share->getSharedWith() === $share->getShareOwner()) {
705
-			throw new \InvalidArgumentException('Can\'t share with the share owner');
706
-		}
707
-
708
-		$this->generalCreateChecks($share);
709
-
710
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
711
-			$this->userCreateChecks($share);
712
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
713
-			$this->groupCreateChecks($share);
714
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
715
-			$this->linkCreateChecks($share);
716
-
717
-			// Password updated.
718
-			if ($share->getPassword() !== $originalShare->getPassword()) {
719
-				//Verify the password
720
-				$this->verifyPassword($share->getPassword());
721
-
722
-				// If a password is set. Hash it!
723
-				if ($share->getPassword() !== null) {
724
-					$share->setPassword($this->hasher->hash($share->getPassword()));
725
-				}
726
-			}
727
-
728
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
729
-				//Verify the expiration date
730
-				$this->validateExpirationDate($share);
731
-				$expirationDateUpdated = true;
732
-			}
733
-		}
734
-
735
-		$plainTextPassword = null;
736
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
737
-			// Password updated.
738
-			if ($share->getPassword() !== $originalShare->getPassword()) {
739
-				//Verify the password
740
-				$this->verifyPassword($share->getPassword());
741
-
742
-				// If a password is set. Hash it!
743
-				if ($share->getPassword() !== null) {
744
-					$plainTextPassword = $share->getPassword();
745
-					$share->setPassword($this->hasher->hash($plainTextPassword));
746
-				}
747
-			}
748
-		}
749
-
750
-		$this->pathCreateChecks($share->getNode());
751
-
752
-		// Now update the share!
753
-		$provider = $this->factory->getProviderForType($share->getShareType());
754
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
-			$share = $provider->update($share, $plainTextPassword);
756
-		} else {
757
-			$share = $provider->update($share);
758
-		}
759
-
760
-		if ($expirationDateUpdated === true) {
761
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
762
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
763
-				'itemSource' => $share->getNode()->getId(),
764
-				'date' => $share->getExpirationDate(),
765
-				'uidOwner' => $share->getSharedBy(),
766
-			]);
767
-		}
768
-
769
-		if ($share->getPassword() !== $originalShare->getPassword()) {
770
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
771
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
772
-				'itemSource' => $share->getNode()->getId(),
773
-				'uidOwner' => $share->getSharedBy(),
774
-				'token' => $share->getToken(),
775
-				'disabled' => is_null($share->getPassword()),
776
-			]);
777
-		}
778
-
779
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
780
-			if ($this->userManager->userExists($share->getShareOwner())) {
781
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
782
-			} else {
783
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
784
-			}
785
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
786
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
787
-				'itemSource' => $share->getNode()->getId(),
788
-				'shareType' => $share->getShareType(),
789
-				'shareWith' => $share->getSharedWith(),
790
-				'uidOwner' => $share->getSharedBy(),
791
-				'permissions' => $share->getPermissions(),
792
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
793
-			));
794
-		}
795
-
796
-		return $share;
797
-	}
798
-
799
-	/**
800
-	 * Delete all the children of this share
801
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
802
-	 *
803
-	 * @param \OCP\Share\IShare $share
804
-	 * @return \OCP\Share\IShare[] List of deleted shares
805
-	 */
806
-	protected function deleteChildren(\OCP\Share\IShare $share) {
807
-		$deletedShares = [];
808
-
809
-		$provider = $this->factory->getProviderForType($share->getShareType());
810
-
811
-		foreach ($provider->getChildren($share) as $child) {
812
-			$deletedChildren = $this->deleteChildren($child);
813
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
814
-
815
-			$provider->delete($child);
816
-			$deletedShares[] = $child;
817
-		}
818
-
819
-		return $deletedShares;
820
-	}
821
-
822
-	/**
823
-	 * Delete a share
824
-	 *
825
-	 * @param \OCP\Share\IShare $share
826
-	 * @throws ShareNotFound
827
-	 * @throws \InvalidArgumentException
828
-	 */
829
-	public function deleteShare(\OCP\Share\IShare $share) {
830
-
831
-		try {
832
-			$share->getFullId();
833
-		} catch (\UnexpectedValueException $e) {
834
-			throw new \InvalidArgumentException('Share does not have a full id');
835
-		}
836
-
837
-		$event = new GenericEvent($share);
838
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
839
-
840
-		// Get all children and delete them as well
841
-		$deletedShares = $this->deleteChildren($share);
842
-
843
-		// Do the actual delete
844
-		$provider = $this->factory->getProviderForType($share->getShareType());
845
-		$provider->delete($share);
846
-
847
-		// All the deleted shares caused by this delete
848
-		$deletedShares[] = $share;
849
-
850
-		// Emit post hook
851
-		$event->setArgument('deletedShares', $deletedShares);
852
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
853
-	}
854
-
855
-
856
-	/**
857
-	 * Unshare a file as the recipient.
858
-	 * This can be different from a regular delete for example when one of
859
-	 * the users in a groups deletes that share. But the provider should
860
-	 * handle this.
861
-	 *
862
-	 * @param \OCP\Share\IShare $share
863
-	 * @param string $recipientId
864
-	 */
865
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
866
-		list($providerId, ) = $this->splitFullId($share->getFullId());
867
-		$provider = $this->factory->getProvider($providerId);
868
-
869
-		$provider->deleteFromSelf($share, $recipientId);
870
-	}
871
-
872
-	/**
873
-	 * @inheritdoc
874
-	 */
875
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
876
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
877
-			throw new \InvalidArgumentException('Can\'t change target of link share');
878
-		}
879
-
880
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
881
-			throw new \InvalidArgumentException('Invalid recipient');
882
-		}
883
-
884
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
885
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
886
-			if (is_null($sharedWith)) {
887
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
888
-			}
889
-			$recipient = $this->userManager->get($recipientId);
890
-			if (!$sharedWith->inGroup($recipient)) {
891
-				throw new \InvalidArgumentException('Invalid recipient');
892
-			}
893
-		}
894
-
895
-		list($providerId, ) = $this->splitFullId($share->getFullId());
896
-		$provider = $this->factory->getProvider($providerId);
897
-
898
-		$provider->move($share, $recipientId);
899
-	}
900
-
901
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
902
-		$providers = $this->factory->getAllProviders();
903
-
904
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
905
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
906
-			foreach ($newShares as $fid => $data) {
907
-				if (!isset($shares[$fid])) {
908
-					$shares[$fid] = [];
909
-				}
910
-
911
-				$shares[$fid] = array_merge($shares[$fid], $data);
912
-			}
913
-			return $shares;
914
-		}, []);
915
-	}
916
-
917
-	/**
918
-	 * @inheritdoc
919
-	 */
920
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
921
-		if ($path !== null &&
922
-				!($path instanceof \OCP\Files\File) &&
923
-				!($path instanceof \OCP\Files\Folder)) {
924
-			throw new \InvalidArgumentException('invalid path');
925
-		}
926
-
927
-		try {
928
-			$provider = $this->factory->getProviderForType($shareType);
929
-		} catch (ProviderException $e) {
930
-			return [];
931
-		}
932
-
933
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
934
-
935
-		/*
582
+            $share->setToken(
583
+                $this->secureRandom->generate(
584
+                    \OC\Share\Constants::TOKEN_LENGTH,
585
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
586
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
587
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
588
+                )
589
+            );
590
+
591
+            //Verify the expiration date
592
+            $this->validateExpirationDate($share);
593
+
594
+            //Verify the password
595
+            $this->verifyPassword($share->getPassword());
596
+
597
+            // If a password is set. Hash it!
598
+            if ($share->getPassword() !== null) {
599
+                $share->setPassword($this->hasher->hash($share->getPassword()));
600
+            }
601
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
602
+            $share->setToken(
603
+                $this->secureRandom->generate(
604
+                    \OC\Share\Constants::TOKEN_LENGTH,
605
+                    \OCP\Security\ISecureRandom::CHAR_LOWER.
606
+                    \OCP\Security\ISecureRandom::CHAR_UPPER.
607
+                    \OCP\Security\ISecureRandom::CHAR_DIGITS
608
+                )
609
+            );
610
+        }
611
+
612
+        // Cannot share with the owner
613
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
614
+            $share->getSharedWith() === $share->getShareOwner()) {
615
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
616
+        }
617
+
618
+        // Generate the target
619
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
620
+        $target = \OC\Files\Filesystem::normalizePath($target);
621
+        $share->setTarget($target);
622
+
623
+        // Pre share hook
624
+        $run = true;
625
+        $error = '';
626
+        $preHookData = [
627
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
628
+            'itemSource' => $share->getNode()->getId(),
629
+            'shareType' => $share->getShareType(),
630
+            'uidOwner' => $share->getSharedBy(),
631
+            'permissions' => $share->getPermissions(),
632
+            'fileSource' => $share->getNode()->getId(),
633
+            'expiration' => $share->getExpirationDate(),
634
+            'token' => $share->getToken(),
635
+            'itemTarget' => $share->getTarget(),
636
+            'shareWith' => $share->getSharedWith(),
637
+            'run' => &$run,
638
+            'error' => &$error,
639
+        ];
640
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
641
+
642
+        if ($run === false) {
643
+            throw new \Exception($error);
644
+        }
645
+
646
+        $oldShare = $share;
647
+        $provider = $this->factory->getProviderForType($share->getShareType());
648
+        $share = $provider->create($share);
649
+        //reuse the node we already have
650
+        $share->setNode($oldShare->getNode());
651
+
652
+        // Post share hook
653
+        $postHookData = [
654
+            'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
655
+            'itemSource' => $share->getNode()->getId(),
656
+            'shareType' => $share->getShareType(),
657
+            'uidOwner' => $share->getSharedBy(),
658
+            'permissions' => $share->getPermissions(),
659
+            'fileSource' => $share->getNode()->getId(),
660
+            'expiration' => $share->getExpirationDate(),
661
+            'token' => $share->getToken(),
662
+            'id' => $share->getId(),
663
+            'shareWith' => $share->getSharedWith(),
664
+            'itemTarget' => $share->getTarget(),
665
+            'fileTarget' => $share->getTarget(),
666
+        ];
667
+
668
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
669
+
670
+        return $share;
671
+    }
672
+
673
+    /**
674
+     * Update a share
675
+     *
676
+     * @param \OCP\Share\IShare $share
677
+     * @return \OCP\Share\IShare The share object
678
+     * @throws \InvalidArgumentException
679
+     */
680
+    public function updateShare(\OCP\Share\IShare $share) {
681
+        $expirationDateUpdated = false;
682
+
683
+        $this->canShare($share);
684
+
685
+        try {
686
+            $originalShare = $this->getShareById($share->getFullId());
687
+        } catch (\UnexpectedValueException $e) {
688
+            throw new \InvalidArgumentException('Share does not have a full id');
689
+        }
690
+
691
+        // We can't change the share type!
692
+        if ($share->getShareType() !== $originalShare->getShareType()) {
693
+            throw new \InvalidArgumentException('Can\'t change share type');
694
+        }
695
+
696
+        // We can only change the recipient on user shares
697
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
698
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
699
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
700
+        }
701
+
702
+        // Cannot share with the owner
703
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
704
+            $share->getSharedWith() === $share->getShareOwner()) {
705
+            throw new \InvalidArgumentException('Can\'t share with the share owner');
706
+        }
707
+
708
+        $this->generalCreateChecks($share);
709
+
710
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
711
+            $this->userCreateChecks($share);
712
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
713
+            $this->groupCreateChecks($share);
714
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
715
+            $this->linkCreateChecks($share);
716
+
717
+            // Password updated.
718
+            if ($share->getPassword() !== $originalShare->getPassword()) {
719
+                //Verify the password
720
+                $this->verifyPassword($share->getPassword());
721
+
722
+                // If a password is set. Hash it!
723
+                if ($share->getPassword() !== null) {
724
+                    $share->setPassword($this->hasher->hash($share->getPassword()));
725
+                }
726
+            }
727
+
728
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
729
+                //Verify the expiration date
730
+                $this->validateExpirationDate($share);
731
+                $expirationDateUpdated = true;
732
+            }
733
+        }
734
+
735
+        $plainTextPassword = null;
736
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
737
+            // Password updated.
738
+            if ($share->getPassword() !== $originalShare->getPassword()) {
739
+                //Verify the password
740
+                $this->verifyPassword($share->getPassword());
741
+
742
+                // If a password is set. Hash it!
743
+                if ($share->getPassword() !== null) {
744
+                    $plainTextPassword = $share->getPassword();
745
+                    $share->setPassword($this->hasher->hash($plainTextPassword));
746
+                }
747
+            }
748
+        }
749
+
750
+        $this->pathCreateChecks($share->getNode());
751
+
752
+        // Now update the share!
753
+        $provider = $this->factory->getProviderForType($share->getShareType());
754
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
755
+            $share = $provider->update($share, $plainTextPassword);
756
+        } else {
757
+            $share = $provider->update($share);
758
+        }
759
+
760
+        if ($expirationDateUpdated === true) {
761
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
762
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
763
+                'itemSource' => $share->getNode()->getId(),
764
+                'date' => $share->getExpirationDate(),
765
+                'uidOwner' => $share->getSharedBy(),
766
+            ]);
767
+        }
768
+
769
+        if ($share->getPassword() !== $originalShare->getPassword()) {
770
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
771
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
772
+                'itemSource' => $share->getNode()->getId(),
773
+                'uidOwner' => $share->getSharedBy(),
774
+                'token' => $share->getToken(),
775
+                'disabled' => is_null($share->getPassword()),
776
+            ]);
777
+        }
778
+
779
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
780
+            if ($this->userManager->userExists($share->getShareOwner())) {
781
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
782
+            } else {
783
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
784
+            }
785
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
786
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
787
+                'itemSource' => $share->getNode()->getId(),
788
+                'shareType' => $share->getShareType(),
789
+                'shareWith' => $share->getSharedWith(),
790
+                'uidOwner' => $share->getSharedBy(),
791
+                'permissions' => $share->getPermissions(),
792
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
793
+            ));
794
+        }
795
+
796
+        return $share;
797
+    }
798
+
799
+    /**
800
+     * Delete all the children of this share
801
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
802
+     *
803
+     * @param \OCP\Share\IShare $share
804
+     * @return \OCP\Share\IShare[] List of deleted shares
805
+     */
806
+    protected function deleteChildren(\OCP\Share\IShare $share) {
807
+        $deletedShares = [];
808
+
809
+        $provider = $this->factory->getProviderForType($share->getShareType());
810
+
811
+        foreach ($provider->getChildren($share) as $child) {
812
+            $deletedChildren = $this->deleteChildren($child);
813
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
814
+
815
+            $provider->delete($child);
816
+            $deletedShares[] = $child;
817
+        }
818
+
819
+        return $deletedShares;
820
+    }
821
+
822
+    /**
823
+     * Delete a share
824
+     *
825
+     * @param \OCP\Share\IShare $share
826
+     * @throws ShareNotFound
827
+     * @throws \InvalidArgumentException
828
+     */
829
+    public function deleteShare(\OCP\Share\IShare $share) {
830
+
831
+        try {
832
+            $share->getFullId();
833
+        } catch (\UnexpectedValueException $e) {
834
+            throw new \InvalidArgumentException('Share does not have a full id');
835
+        }
836
+
837
+        $event = new GenericEvent($share);
838
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
839
+
840
+        // Get all children and delete them as well
841
+        $deletedShares = $this->deleteChildren($share);
842
+
843
+        // Do the actual delete
844
+        $provider = $this->factory->getProviderForType($share->getShareType());
845
+        $provider->delete($share);
846
+
847
+        // All the deleted shares caused by this delete
848
+        $deletedShares[] = $share;
849
+
850
+        // Emit post hook
851
+        $event->setArgument('deletedShares', $deletedShares);
852
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
853
+    }
854
+
855
+
856
+    /**
857
+     * Unshare a file as the recipient.
858
+     * This can be different from a regular delete for example when one of
859
+     * the users in a groups deletes that share. But the provider should
860
+     * handle this.
861
+     *
862
+     * @param \OCP\Share\IShare $share
863
+     * @param string $recipientId
864
+     */
865
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
866
+        list($providerId, ) = $this->splitFullId($share->getFullId());
867
+        $provider = $this->factory->getProvider($providerId);
868
+
869
+        $provider->deleteFromSelf($share, $recipientId);
870
+    }
871
+
872
+    /**
873
+     * @inheritdoc
874
+     */
875
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
876
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
877
+            throw new \InvalidArgumentException('Can\'t change target of link share');
878
+        }
879
+
880
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
881
+            throw new \InvalidArgumentException('Invalid recipient');
882
+        }
883
+
884
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
885
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
886
+            if (is_null($sharedWith)) {
887
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
888
+            }
889
+            $recipient = $this->userManager->get($recipientId);
890
+            if (!$sharedWith->inGroup($recipient)) {
891
+                throw new \InvalidArgumentException('Invalid recipient');
892
+            }
893
+        }
894
+
895
+        list($providerId, ) = $this->splitFullId($share->getFullId());
896
+        $provider = $this->factory->getProvider($providerId);
897
+
898
+        $provider->move($share, $recipientId);
899
+    }
900
+
901
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
902
+        $providers = $this->factory->getAllProviders();
903
+
904
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
905
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
906
+            foreach ($newShares as $fid => $data) {
907
+                if (!isset($shares[$fid])) {
908
+                    $shares[$fid] = [];
909
+                }
910
+
911
+                $shares[$fid] = array_merge($shares[$fid], $data);
912
+            }
913
+            return $shares;
914
+        }, []);
915
+    }
916
+
917
+    /**
918
+     * @inheritdoc
919
+     */
920
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
921
+        if ($path !== null &&
922
+                !($path instanceof \OCP\Files\File) &&
923
+                !($path instanceof \OCP\Files\Folder)) {
924
+            throw new \InvalidArgumentException('invalid path');
925
+        }
926
+
927
+        try {
928
+            $provider = $this->factory->getProviderForType($shareType);
929
+        } catch (ProviderException $e) {
930
+            return [];
931
+        }
932
+
933
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
934
+
935
+        /*
936 936
 		 * Work around so we don't return expired shares but still follow
937 937
 		 * proper pagination.
938 938
 		 */
939 939
 
940
-		$shares2 = [];
941
-
942
-		while(true) {
943
-			$added = 0;
944
-			foreach ($shares as $share) {
945
-
946
-				try {
947
-					$this->checkExpireDate($share);
948
-				} catch (ShareNotFound $e) {
949
-					//Ignore since this basically means the share is deleted
950
-					continue;
951
-				}
952
-
953
-				$added++;
954
-				$shares2[] = $share;
955
-
956
-				if (count($shares2) === $limit) {
957
-					break;
958
-				}
959
-			}
960
-
961
-			if (count($shares2) === $limit) {
962
-				break;
963
-			}
964
-
965
-			// If there was no limit on the select we are done
966
-			if ($limit === -1) {
967
-				break;
968
-			}
969
-
970
-			$offset += $added;
971
-
972
-			// Fetch again $limit shares
973
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
974
-
975
-			// No more shares means we are done
976
-			if (empty($shares)) {
977
-				break;
978
-			}
979
-		}
980
-
981
-		$shares = $shares2;
982
-
983
-		return $shares;
984
-	}
985
-
986
-	/**
987
-	 * @inheritdoc
988
-	 */
989
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
990
-		try {
991
-			$provider = $this->factory->getProviderForType($shareType);
992
-		} catch (ProviderException $e) {
993
-			return [];
994
-		}
995
-
996
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
997
-
998
-		// remove all shares which are already expired
999
-		foreach ($shares as $key => $share) {
1000
-			try {
1001
-				$this->checkExpireDate($share);
1002
-			} catch (ShareNotFound $e) {
1003
-				unset($shares[$key]);
1004
-			}
1005
-		}
1006
-
1007
-		return $shares;
1008
-	}
1009
-
1010
-	/**
1011
-	 * @inheritdoc
1012
-	 */
1013
-	public function getShareById($id, $recipient = null) {
1014
-		if ($id === null) {
1015
-			throw new ShareNotFound();
1016
-		}
1017
-
1018
-		list($providerId, $id) = $this->splitFullId($id);
1019
-
1020
-		try {
1021
-			$provider = $this->factory->getProvider($providerId);
1022
-		} catch (ProviderException $e) {
1023
-			throw new ShareNotFound();
1024
-		}
1025
-
1026
-		$share = $provider->getShareById($id, $recipient);
1027
-
1028
-		$this->checkExpireDate($share);
1029
-
1030
-		return $share;
1031
-	}
1032
-
1033
-	/**
1034
-	 * Get all the shares for a given path
1035
-	 *
1036
-	 * @param \OCP\Files\Node $path
1037
-	 * @param int $page
1038
-	 * @param int $perPage
1039
-	 *
1040
-	 * @return Share[]
1041
-	 */
1042
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1043
-		return [];
1044
-	}
1045
-
1046
-	/**
1047
-	 * Get the share by token possible with password
1048
-	 *
1049
-	 * @param string $token
1050
-	 * @return Share
1051
-	 *
1052
-	 * @throws ShareNotFound
1053
-	 */
1054
-	public function getShareByToken($token) {
1055
-		$share = null;
1056
-		try {
1057
-			if($this->shareApiAllowLinks()) {
1058
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1059
-				$share = $provider->getShareByToken($token);
1060
-			}
1061
-		} catch (ProviderException $e) {
1062
-		} catch (ShareNotFound $e) {
1063
-		}
1064
-
1065
-
1066
-		// If it is not a link share try to fetch a federated share by token
1067
-		if ($share === null) {
1068
-			try {
1069
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1070
-				$share = $provider->getShareByToken($token);
1071
-			} catch (ProviderException $e) {
1072
-			} catch (ShareNotFound $e) {
1073
-			}
1074
-		}
1075
-
1076
-		// If it is not a link share try to fetch a mail share by token
1077
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1078
-			try {
1079
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1080
-				$share = $provider->getShareByToken($token);
1081
-			} catch (ProviderException $e) {
1082
-			} catch (ShareNotFound $e) {
1083
-			}
1084
-		}
1085
-
1086
-		if ($share === null) {
1087
-			throw new ShareNotFound();
1088
-		}
1089
-
1090
-		$this->checkExpireDate($share);
1091
-
1092
-		/*
940
+        $shares2 = [];
941
+
942
+        while(true) {
943
+            $added = 0;
944
+            foreach ($shares as $share) {
945
+
946
+                try {
947
+                    $this->checkExpireDate($share);
948
+                } catch (ShareNotFound $e) {
949
+                    //Ignore since this basically means the share is deleted
950
+                    continue;
951
+                }
952
+
953
+                $added++;
954
+                $shares2[] = $share;
955
+
956
+                if (count($shares2) === $limit) {
957
+                    break;
958
+                }
959
+            }
960
+
961
+            if (count($shares2) === $limit) {
962
+                break;
963
+            }
964
+
965
+            // If there was no limit on the select we are done
966
+            if ($limit === -1) {
967
+                break;
968
+            }
969
+
970
+            $offset += $added;
971
+
972
+            // Fetch again $limit shares
973
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
974
+
975
+            // No more shares means we are done
976
+            if (empty($shares)) {
977
+                break;
978
+            }
979
+        }
980
+
981
+        $shares = $shares2;
982
+
983
+        return $shares;
984
+    }
985
+
986
+    /**
987
+     * @inheritdoc
988
+     */
989
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
990
+        try {
991
+            $provider = $this->factory->getProviderForType($shareType);
992
+        } catch (ProviderException $e) {
993
+            return [];
994
+        }
995
+
996
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
997
+
998
+        // remove all shares which are already expired
999
+        foreach ($shares as $key => $share) {
1000
+            try {
1001
+                $this->checkExpireDate($share);
1002
+            } catch (ShareNotFound $e) {
1003
+                unset($shares[$key]);
1004
+            }
1005
+        }
1006
+
1007
+        return $shares;
1008
+    }
1009
+
1010
+    /**
1011
+     * @inheritdoc
1012
+     */
1013
+    public function getShareById($id, $recipient = null) {
1014
+        if ($id === null) {
1015
+            throw new ShareNotFound();
1016
+        }
1017
+
1018
+        list($providerId, $id) = $this->splitFullId($id);
1019
+
1020
+        try {
1021
+            $provider = $this->factory->getProvider($providerId);
1022
+        } catch (ProviderException $e) {
1023
+            throw new ShareNotFound();
1024
+        }
1025
+
1026
+        $share = $provider->getShareById($id, $recipient);
1027
+
1028
+        $this->checkExpireDate($share);
1029
+
1030
+        return $share;
1031
+    }
1032
+
1033
+    /**
1034
+     * Get all the shares for a given path
1035
+     *
1036
+     * @param \OCP\Files\Node $path
1037
+     * @param int $page
1038
+     * @param int $perPage
1039
+     *
1040
+     * @return Share[]
1041
+     */
1042
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1043
+        return [];
1044
+    }
1045
+
1046
+    /**
1047
+     * Get the share by token possible with password
1048
+     *
1049
+     * @param string $token
1050
+     * @return Share
1051
+     *
1052
+     * @throws ShareNotFound
1053
+     */
1054
+    public function getShareByToken($token) {
1055
+        $share = null;
1056
+        try {
1057
+            if($this->shareApiAllowLinks()) {
1058
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1059
+                $share = $provider->getShareByToken($token);
1060
+            }
1061
+        } catch (ProviderException $e) {
1062
+        } catch (ShareNotFound $e) {
1063
+        }
1064
+
1065
+
1066
+        // If it is not a link share try to fetch a federated share by token
1067
+        if ($share === null) {
1068
+            try {
1069
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1070
+                $share = $provider->getShareByToken($token);
1071
+            } catch (ProviderException $e) {
1072
+            } catch (ShareNotFound $e) {
1073
+            }
1074
+        }
1075
+
1076
+        // If it is not a link share try to fetch a mail share by token
1077
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1078
+            try {
1079
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1080
+                $share = $provider->getShareByToken($token);
1081
+            } catch (ProviderException $e) {
1082
+            } catch (ShareNotFound $e) {
1083
+            }
1084
+        }
1085
+
1086
+        if ($share === null) {
1087
+            throw new ShareNotFound();
1088
+        }
1089
+
1090
+        $this->checkExpireDate($share);
1091
+
1092
+        /*
1093 1093
 		 * Reduce the permissions for link shares if public upload is not enabled
1094 1094
 		 */
1095
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1096
-			!$this->shareApiLinkAllowPublicUpload()) {
1097
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1098
-		}
1099
-
1100
-		return $share;
1101
-	}
1102
-
1103
-	protected function checkExpireDate($share) {
1104
-		if ($share->getExpirationDate() !== null &&
1105
-			$share->getExpirationDate() <= new \DateTime()) {
1106
-			$this->deleteShare($share);
1107
-			throw new ShareNotFound();
1108
-		}
1109
-
1110
-	}
1111
-
1112
-	/**
1113
-	 * Verify the password of a public share
1114
-	 *
1115
-	 * @param \OCP\Share\IShare $share
1116
-	 * @param string $password
1117
-	 * @return bool
1118
-	 */
1119
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1120
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1121
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1122
-		if (!$passwordProtected) {
1123
-			//TODO maybe exception?
1124
-			return false;
1125
-		}
1126
-
1127
-		if ($password === null || $share->getPassword() === null) {
1128
-			return false;
1129
-		}
1130
-
1131
-		$newHash = '';
1132
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1133
-			return false;
1134
-		}
1135
-
1136
-		if (!empty($newHash)) {
1137
-			$share->setPassword($newHash);
1138
-			$provider = $this->factory->getProviderForType($share->getShareType());
1139
-			$provider->update($share);
1140
-		}
1141
-
1142
-		return true;
1143
-	}
1144
-
1145
-	/**
1146
-	 * @inheritdoc
1147
-	 */
1148
-	public function userDeleted($uid) {
1149
-		$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];
1150
-
1151
-		foreach ($types as $type) {
1152
-			try {
1153
-				$provider = $this->factory->getProviderForType($type);
1154
-			} catch (ProviderException $e) {
1155
-				continue;
1156
-			}
1157
-			$provider->userDeleted($uid, $type);
1158
-		}
1159
-	}
1160
-
1161
-	/**
1162
-	 * @inheritdoc
1163
-	 */
1164
-	public function groupDeleted($gid) {
1165
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1166
-		$provider->groupDeleted($gid);
1167
-	}
1168
-
1169
-	/**
1170
-	 * @inheritdoc
1171
-	 */
1172
-	public function userDeletedFromGroup($uid, $gid) {
1173
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1174
-		$provider->userDeletedFromGroup($uid, $gid);
1175
-	}
1176
-
1177
-	/**
1178
-	 * Get access list to a path. This means
1179
-	 * all the users and groups that can access a given path.
1180
-	 *
1181
-	 * Consider:
1182
-	 * -root
1183
-	 * |-folder1
1184
-	 *  |-folder2
1185
-	 *   |-fileA
1186
-	 *
1187
-	 * fileA is shared with user1
1188
-	 * folder2 is shared with group2
1189
-	 * folder1 is shared with user2
1190
-	 *
1191
-	 * Then the access list will to '/folder1/folder2/fileA' is:
1192
-	 * [
1193
-	 * 	'users' => ['user1', 'user2'],
1194
-	 *  'groups' => ['group2']
1195
-	 * ]
1196
-	 *
1197
-	 * This is required for encryption
1198
-	 *
1199
-	 * @param \OCP\Files\Node $path
1200
-	 */
1201
-	public function getAccessList(\OCP\Files\Node $path) {
1202
-	}
1203
-
1204
-	/**
1205
-	 * Create a new share
1206
-	 * @return \OCP\Share\IShare;
1207
-	 */
1208
-	public function newShare() {
1209
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1210
-	}
1211
-
1212
-	/**
1213
-	 * Is the share API enabled
1214
-	 *
1215
-	 * @return bool
1216
-	 */
1217
-	public function shareApiEnabled() {
1218
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1219
-	}
1220
-
1221
-	/**
1222
-	 * Is public link sharing enabled
1223
-	 *
1224
-	 * @return bool
1225
-	 */
1226
-	public function shareApiAllowLinks() {
1227
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1228
-	}
1229
-
1230
-	/**
1231
-	 * Is password on public link requires
1232
-	 *
1233
-	 * @return bool
1234
-	 */
1235
-	public function shareApiLinkEnforcePassword() {
1236
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1237
-	}
1238
-
1239
-	/**
1240
-	 * Is default expire date enabled
1241
-	 *
1242
-	 * @return bool
1243
-	 */
1244
-	public function shareApiLinkDefaultExpireDate() {
1245
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1246
-	}
1247
-
1248
-	/**
1249
-	 * Is default expire date enforced
1250
-	 *`
1251
-	 * @return bool
1252
-	 */
1253
-	public function shareApiLinkDefaultExpireDateEnforced() {
1254
-		return $this->shareApiLinkDefaultExpireDate() &&
1255
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1256
-	}
1257
-
1258
-	/**
1259
-	 * Number of default expire days
1260
-	 *shareApiLinkAllowPublicUpload
1261
-	 * @return int
1262
-	 */
1263
-	public function shareApiLinkDefaultExpireDays() {
1264
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1265
-	}
1266
-
1267
-	/**
1268
-	 * Allow public upload on link shares
1269
-	 *
1270
-	 * @return bool
1271
-	 */
1272
-	public function shareApiLinkAllowPublicUpload() {
1273
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1274
-	}
1275
-
1276
-	/**
1277
-	 * check if user can only share with group members
1278
-	 * @return bool
1279
-	 */
1280
-	public function shareWithGroupMembersOnly() {
1281
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1282
-	}
1283
-
1284
-	/**
1285
-	 * Check if users can share with groups
1286
-	 * @return bool
1287
-	 */
1288
-	public function allowGroupSharing() {
1289
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1290
-	}
1291
-
1292
-	/**
1293
-	 * Copied from \OC_Util::isSharingDisabledForUser
1294
-	 *
1295
-	 * TODO: Deprecate fuction from OC_Util
1296
-	 *
1297
-	 * @param string $userId
1298
-	 * @return bool
1299
-	 */
1300
-	public function sharingDisabledForUser($userId) {
1301
-		if ($userId === null) {
1302
-			return false;
1303
-		}
1304
-
1305
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1306
-			return $this->sharingDisabledForUsersCache[$userId];
1307
-		}
1308
-
1309
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1310
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1311
-			$excludedGroups = json_decode($groupsList);
1312
-			if (is_null($excludedGroups)) {
1313
-				$excludedGroups = explode(',', $groupsList);
1314
-				$newValue = json_encode($excludedGroups);
1315
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1316
-			}
1317
-			$user = $this->userManager->get($userId);
1318
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1319
-			if (!empty($usersGroups)) {
1320
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1321
-				// if the user is only in groups which are disabled for sharing then
1322
-				// sharing is also disabled for the user
1323
-				if (empty($remainingGroups)) {
1324
-					$this->sharingDisabledForUsersCache[$userId] = true;
1325
-					return true;
1326
-				}
1327
-			}
1328
-		}
1329
-
1330
-		$this->sharingDisabledForUsersCache[$userId] = false;
1331
-		return false;
1332
-	}
1333
-
1334
-	/**
1335
-	 * @inheritdoc
1336
-	 */
1337
-	public function outgoingServer2ServerSharesAllowed() {
1338
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1339
-	}
1340
-
1341
-	/**
1342
-	 * @inheritdoc
1343
-	 */
1344
-	public function shareProviderExists($shareType) {
1345
-		try {
1346
-			$this->factory->getProviderForType($shareType);
1347
-		} catch (ProviderException $e) {
1348
-			return false;
1349
-		}
1350
-
1351
-		return true;
1352
-	}
1095
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1096
+            !$this->shareApiLinkAllowPublicUpload()) {
1097
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1098
+        }
1099
+
1100
+        return $share;
1101
+    }
1102
+
1103
+    protected function checkExpireDate($share) {
1104
+        if ($share->getExpirationDate() !== null &&
1105
+            $share->getExpirationDate() <= new \DateTime()) {
1106
+            $this->deleteShare($share);
1107
+            throw new ShareNotFound();
1108
+        }
1109
+
1110
+    }
1111
+
1112
+    /**
1113
+     * Verify the password of a public share
1114
+     *
1115
+     * @param \OCP\Share\IShare $share
1116
+     * @param string $password
1117
+     * @return bool
1118
+     */
1119
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1120
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1121
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1122
+        if (!$passwordProtected) {
1123
+            //TODO maybe exception?
1124
+            return false;
1125
+        }
1126
+
1127
+        if ($password === null || $share->getPassword() === null) {
1128
+            return false;
1129
+        }
1130
+
1131
+        $newHash = '';
1132
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1133
+            return false;
1134
+        }
1135
+
1136
+        if (!empty($newHash)) {
1137
+            $share->setPassword($newHash);
1138
+            $provider = $this->factory->getProviderForType($share->getShareType());
1139
+            $provider->update($share);
1140
+        }
1141
+
1142
+        return true;
1143
+    }
1144
+
1145
+    /**
1146
+     * @inheritdoc
1147
+     */
1148
+    public function userDeleted($uid) {
1149
+        $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];
1150
+
1151
+        foreach ($types as $type) {
1152
+            try {
1153
+                $provider = $this->factory->getProviderForType($type);
1154
+            } catch (ProviderException $e) {
1155
+                continue;
1156
+            }
1157
+            $provider->userDeleted($uid, $type);
1158
+        }
1159
+    }
1160
+
1161
+    /**
1162
+     * @inheritdoc
1163
+     */
1164
+    public function groupDeleted($gid) {
1165
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1166
+        $provider->groupDeleted($gid);
1167
+    }
1168
+
1169
+    /**
1170
+     * @inheritdoc
1171
+     */
1172
+    public function userDeletedFromGroup($uid, $gid) {
1173
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1174
+        $provider->userDeletedFromGroup($uid, $gid);
1175
+    }
1176
+
1177
+    /**
1178
+     * Get access list to a path. This means
1179
+     * all the users and groups that can access a given path.
1180
+     *
1181
+     * Consider:
1182
+     * -root
1183
+     * |-folder1
1184
+     *  |-folder2
1185
+     *   |-fileA
1186
+     *
1187
+     * fileA is shared with user1
1188
+     * folder2 is shared with group2
1189
+     * folder1 is shared with user2
1190
+     *
1191
+     * Then the access list will to '/folder1/folder2/fileA' is:
1192
+     * [
1193
+     * 	'users' => ['user1', 'user2'],
1194
+     *  'groups' => ['group2']
1195
+     * ]
1196
+     *
1197
+     * This is required for encryption
1198
+     *
1199
+     * @param \OCP\Files\Node $path
1200
+     */
1201
+    public function getAccessList(\OCP\Files\Node $path) {
1202
+    }
1203
+
1204
+    /**
1205
+     * Create a new share
1206
+     * @return \OCP\Share\IShare;
1207
+     */
1208
+    public function newShare() {
1209
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1210
+    }
1211
+
1212
+    /**
1213
+     * Is the share API enabled
1214
+     *
1215
+     * @return bool
1216
+     */
1217
+    public function shareApiEnabled() {
1218
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1219
+    }
1220
+
1221
+    /**
1222
+     * Is public link sharing enabled
1223
+     *
1224
+     * @return bool
1225
+     */
1226
+    public function shareApiAllowLinks() {
1227
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1228
+    }
1229
+
1230
+    /**
1231
+     * Is password on public link requires
1232
+     *
1233
+     * @return bool
1234
+     */
1235
+    public function shareApiLinkEnforcePassword() {
1236
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1237
+    }
1238
+
1239
+    /**
1240
+     * Is default expire date enabled
1241
+     *
1242
+     * @return bool
1243
+     */
1244
+    public function shareApiLinkDefaultExpireDate() {
1245
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1246
+    }
1247
+
1248
+    /**
1249
+     * Is default expire date enforced
1250
+     *`
1251
+     * @return bool
1252
+     */
1253
+    public function shareApiLinkDefaultExpireDateEnforced() {
1254
+        return $this->shareApiLinkDefaultExpireDate() &&
1255
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1256
+    }
1257
+
1258
+    /**
1259
+     * Number of default expire days
1260
+     *shareApiLinkAllowPublicUpload
1261
+     * @return int
1262
+     */
1263
+    public function shareApiLinkDefaultExpireDays() {
1264
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1265
+    }
1266
+
1267
+    /**
1268
+     * Allow public upload on link shares
1269
+     *
1270
+     * @return bool
1271
+     */
1272
+    public function shareApiLinkAllowPublicUpload() {
1273
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1274
+    }
1275
+
1276
+    /**
1277
+     * check if user can only share with group members
1278
+     * @return bool
1279
+     */
1280
+    public function shareWithGroupMembersOnly() {
1281
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1282
+    }
1283
+
1284
+    /**
1285
+     * Check if users can share with groups
1286
+     * @return bool
1287
+     */
1288
+    public function allowGroupSharing() {
1289
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1290
+    }
1291
+
1292
+    /**
1293
+     * Copied from \OC_Util::isSharingDisabledForUser
1294
+     *
1295
+     * TODO: Deprecate fuction from OC_Util
1296
+     *
1297
+     * @param string $userId
1298
+     * @return bool
1299
+     */
1300
+    public function sharingDisabledForUser($userId) {
1301
+        if ($userId === null) {
1302
+            return false;
1303
+        }
1304
+
1305
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1306
+            return $this->sharingDisabledForUsersCache[$userId];
1307
+        }
1308
+
1309
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1310
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1311
+            $excludedGroups = json_decode($groupsList);
1312
+            if (is_null($excludedGroups)) {
1313
+                $excludedGroups = explode(',', $groupsList);
1314
+                $newValue = json_encode($excludedGroups);
1315
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1316
+            }
1317
+            $user = $this->userManager->get($userId);
1318
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1319
+            if (!empty($usersGroups)) {
1320
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1321
+                // if the user is only in groups which are disabled for sharing then
1322
+                // sharing is also disabled for the user
1323
+                if (empty($remainingGroups)) {
1324
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1325
+                    return true;
1326
+                }
1327
+            }
1328
+        }
1329
+
1330
+        $this->sharingDisabledForUsersCache[$userId] = false;
1331
+        return false;
1332
+    }
1333
+
1334
+    /**
1335
+     * @inheritdoc
1336
+     */
1337
+    public function outgoingServer2ServerSharesAllowed() {
1338
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1339
+    }
1340
+
1341
+    /**
1342
+     * @inheritdoc
1343
+     */
1344
+    public function shareProviderExists($shareType) {
1345
+        try {
1346
+            $this->factory->getProviderForType($shareType);
1347
+        } catch (ProviderException $e) {
1348
+            return false;
1349
+        }
1350
+
1351
+        return true;
1352
+    }
1353 1353
 
1354 1354
 }
Please login to merge, or discard this patch.
apps/files_sharing/lib/Controller/ShareAPIController.php 1 patch
Indentation   +866 added lines, -866 removed lines patch added patch discarded remove patch
@@ -51,879 +51,879 @@
 block discarded – undo
51 51
  */
52 52
 class ShareAPIController extends OCSController {
53 53
 
54
-	/** @var IManager */
55
-	private $shareManager;
56
-	/** @var IGroupManager */
57
-	private $groupManager;
58
-	/** @var IUserManager */
59
-	private $userManager;
60
-	/** @var IRequest */
61
-	protected $request;
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-	/** @var IURLGenerator */
65
-	private $urlGenerator;
66
-	/** @var string */
67
-	private $currentUser;
68
-	/** @var IL10N */
69
-	private $l;
70
-	/** @var \OCP\Files\Node */
71
-	private $lockedNode;
72
-
73
-	/**
74
-	 * Share20OCS constructor.
75
-	 *
76
-	 * @param string $appName
77
-	 * @param IRequest $request
78
-	 * @param IManager $shareManager
79
-	 * @param IGroupManager $groupManager
80
-	 * @param IUserManager $userManager
81
-	 * @param IRootFolder $rootFolder
82
-	 * @param IURLGenerator $urlGenerator
83
-	 * @param string $userId
84
-	 * @param IL10N $l10n
85
-	 */
86
-	public function __construct(
87
-		$appName,
88
-		IRequest $request,
89
-		IManager $shareManager,
90
-		IGroupManager $groupManager,
91
-		IUserManager $userManager,
92
-		IRootFolder $rootFolder,
93
-		IURLGenerator $urlGenerator,
94
-		$userId,
95
-		IL10N $l10n
96
-	) {
97
-		parent::__construct($appName, $request);
98
-
99
-		$this->shareManager = $shareManager;
100
-		$this->userManager = $userManager;
101
-		$this->groupManager = $groupManager;
102
-		$this->request = $request;
103
-		$this->rootFolder = $rootFolder;
104
-		$this->urlGenerator = $urlGenerator;
105
-		$this->currentUser = $userId;
106
-		$this->l = $l10n;
107
-	}
108
-
109
-	/**
110
-	 * Convert an IShare to an array for OCS output
111
-	 *
112
-	 * @param \OCP\Share\IShare $share
113
-	 * @param Node|null $recipientNode
114
-	 * @return array
115
-	 * @throws NotFoundException In case the node can't be resolved.
116
-	 */
117
-	protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
118
-		$sharedBy = $this->userManager->get($share->getSharedBy());
119
-		$shareOwner = $this->userManager->get($share->getShareOwner());
120
-
121
-		$result = [
122
-			'id' => $share->getId(),
123
-			'share_type' => $share->getShareType(),
124
-			'uid_owner' => $share->getSharedBy(),
125
-			'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
126
-			'permissions' => $share->getPermissions(),
127
-			'stime' => $share->getShareTime()->getTimestamp(),
128
-			'parent' => null,
129
-			'expiration' => null,
130
-			'token' => null,
131
-			'uid_file_owner' => $share->getShareOwner(),
132
-			'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
133
-		];
134
-
135
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
136
-		if ($recipientNode) {
137
-			$node = $recipientNode;
138
-		} else {
139
-			$nodes = $userFolder->getById($share->getNodeId());
140
-
141
-			if (empty($nodes)) {
142
-				// fallback to guessing the path
143
-				$node = $userFolder->get($share->getTarget());
144
-				if ($node === null) {
145
-					throw new NotFoundException();
146
-				}
147
-			} else {
148
-				$node = $nodes[0];
149
-			}
150
-		}
151
-
152
-		$result['path'] = $userFolder->getRelativePath($node->getPath());
153
-		if ($node instanceOf \OCP\Files\Folder) {
154
-			$result['item_type'] = 'folder';
155
-		} else {
156
-			$result['item_type'] = 'file';
157
-		}
158
-		$result['mimetype'] = $node->getMimetype();
159
-		$result['storage_id'] = $node->getStorage()->getId();
160
-		$result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
161
-		$result['item_source'] = $node->getId();
162
-		$result['file_source'] = $node->getId();
163
-		$result['file_parent'] = $node->getParent()->getId();
164
-		$result['file_target'] = $share->getTarget();
165
-
166
-		$expiration = $share->getExpirationDate();
167
-		if ($expiration !== null) {
168
-			$result['expiration'] = $expiration->format('Y-m-d 00:00:00');
169
-		}
170
-
171
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
172
-			$sharedWith = $this->userManager->get($share->getSharedWith());
173
-			$result['share_with'] = $share->getSharedWith();
174
-			$result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
175
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
176
-			$group = $this->groupManager->get($share->getSharedWith());
177
-			$result['share_with'] = $share->getSharedWith();
178
-			$result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
179
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
180
-
181
-			$result['share_with'] = $share->getPassword();
182
-			$result['share_with_displayname'] = $share->getPassword();
183
-
184
-			$result['token'] = $share->getToken();
185
-			$result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
186
-
187
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
-			$result['share_with'] = $share->getSharedWith();
189
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
190
-			$result['token'] = $share->getToken();
191
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
-			$result['share_with'] = $share->getSharedWith();
193
-			$result['password'] = $share->getPassword();
194
-			$result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
195
-			$result['token'] = $share->getToken();
196
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
-			$result['share_with_displayname'] = $share->getSharedWith();
198
-			$result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
199
-		}
200
-
201
-
202
-		$result['mail_send'] = $share->getMailSend() ? 1 : 0;
203
-
204
-		return $result;
205
-	}
206
-
207
-	/**
208
-	 * Check if one of the users address books knows the exact property, if
209
-	 * yes we return the full name.
210
-	 *
211
-	 * @param string $query
212
-	 * @param string $property
213
-	 * @return string
214
-	 */
215
-	private function getDisplayNameFromAddressBook($query, $property) {
216
-		// FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
217
-		$result = \OC::$server->getContactsManager()->search($query, [$property]);
218
-		foreach ($result as $r) {
219
-			foreach($r[$property] as $value) {
220
-				if ($value === $query) {
221
-					return $r['FN'];
222
-				}
223
-			}
224
-		}
225
-
226
-		return $query;
227
-	}
228
-
229
-	/**
230
-	 * Get a specific share by id
231
-	 *
232
-	 * @NoAdminRequired
233
-	 *
234
-	 * @param string $id
235
-	 * @return DataResponse
236
-	 * @throws OCSNotFoundException
237
-	 */
238
-	public function getShare($id) {
239
-		try {
240
-			$share = $this->getShareById($id);
241
-		} catch (ShareNotFound $e) {
242
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
243
-		}
244
-
245
-		if ($this->canAccessShare($share)) {
246
-			try {
247
-				$share = $this->formatShare($share);
248
-				return new DataResponse([$share]);
249
-			} catch (NotFoundException $e) {
250
-				//Fall trough
251
-			}
252
-		}
253
-
254
-		throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
255
-	}
256
-
257
-	/**
258
-	 * Delete a share
259
-	 *
260
-	 * @NoAdminRequired
261
-	 *
262
-	 * @param string $id
263
-	 * @return DataResponse
264
-	 * @throws OCSNotFoundException
265
-	 */
266
-	public function deleteShare($id) {
267
-		try {
268
-			$share = $this->getShareById($id);
269
-		} catch (ShareNotFound $e) {
270
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
271
-		}
272
-
273
-		try {
274
-			$this->lock($share->getNode());
275
-		} catch (LockedException $e) {
276
-			throw new OCSNotFoundException($this->l->t('could not delete share'));
277
-		}
278
-
279
-		if (!$this->canAccessShare($share)) {
280
-			throw new OCSNotFoundException($this->l->t('Could not delete share'));
281
-		}
282
-
283
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
284
-			$share->getShareOwner() !== $this->currentUser &&
285
-			$share->getSharedBy() !== $this->currentUser) {
286
-			$this->shareManager->deleteFromSelf($share, $this->currentUser);
287
-		} else {
288
-			$this->shareManager->deleteShare($share);
289
-		}
290
-
291
-		return new DataResponse();
292
-	}
293
-
294
-	/**
295
-	 * @NoAdminRequired
296
-	 *
297
-	 * @param string $path
298
-	 * @param int $permissions
299
-	 * @param int $shareType
300
-	 * @param string $shareWith
301
-	 * @param string $publicUpload
302
-	 * @param string $password
303
-	 * @param string $expireDate
304
-	 *
305
-	 * @return DataResponse
306
-	 * @throws OCSNotFoundException
307
-	 * @throws OCSForbiddenException
308
-	 * @throws OCSBadRequestException
309
-	 * @throws OCSException
310
-	 */
311
-	public function createShare(
312
-		$path = null,
313
-		$permissions = \OCP\Constants::PERMISSION_ALL,
314
-		$shareType = -1,
315
-		$shareWith = null,
316
-		$publicUpload = 'false',
317
-		$password = '',
318
-		$expireDate = ''
319
-	) {
320
-		$share = $this->shareManager->newShare();
321
-
322
-		// Verify path
323
-		if ($path === null) {
324
-			throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
325
-		}
326
-
327
-		$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
328
-		try {
329
-			$path = $userFolder->get($path);
330
-		} catch (NotFoundException $e) {
331
-			throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
332
-		}
333
-
334
-		$share->setNode($path);
335
-
336
-		try {
337
-			$this->lock($share->getNode());
338
-		} catch (LockedException $e) {
339
-			throw new OCSNotFoundException($this->l->t('Could not create share'));
340
-		}
341
-
342
-		if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
343
-			throw new OCSNotFoundException($this->l->t('invalid permissions'));
344
-		}
345
-
346
-		// Shares always require read permissions
347
-		$permissions |= \OCP\Constants::PERMISSION_READ;
348
-
349
-		if ($path instanceof \OCP\Files\File) {
350
-			// Single file shares should never have delete or create permissions
351
-			$permissions &= ~\OCP\Constants::PERMISSION_DELETE;
352
-			$permissions &= ~\OCP\Constants::PERMISSION_CREATE;
353
-		}
354
-
355
-		/*
54
+    /** @var IManager */
55
+    private $shareManager;
56
+    /** @var IGroupManager */
57
+    private $groupManager;
58
+    /** @var IUserManager */
59
+    private $userManager;
60
+    /** @var IRequest */
61
+    protected $request;
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+    /** @var IURLGenerator */
65
+    private $urlGenerator;
66
+    /** @var string */
67
+    private $currentUser;
68
+    /** @var IL10N */
69
+    private $l;
70
+    /** @var \OCP\Files\Node */
71
+    private $lockedNode;
72
+
73
+    /**
74
+     * Share20OCS constructor.
75
+     *
76
+     * @param string $appName
77
+     * @param IRequest $request
78
+     * @param IManager $shareManager
79
+     * @param IGroupManager $groupManager
80
+     * @param IUserManager $userManager
81
+     * @param IRootFolder $rootFolder
82
+     * @param IURLGenerator $urlGenerator
83
+     * @param string $userId
84
+     * @param IL10N $l10n
85
+     */
86
+    public function __construct(
87
+        $appName,
88
+        IRequest $request,
89
+        IManager $shareManager,
90
+        IGroupManager $groupManager,
91
+        IUserManager $userManager,
92
+        IRootFolder $rootFolder,
93
+        IURLGenerator $urlGenerator,
94
+        $userId,
95
+        IL10N $l10n
96
+    ) {
97
+        parent::__construct($appName, $request);
98
+
99
+        $this->shareManager = $shareManager;
100
+        $this->userManager = $userManager;
101
+        $this->groupManager = $groupManager;
102
+        $this->request = $request;
103
+        $this->rootFolder = $rootFolder;
104
+        $this->urlGenerator = $urlGenerator;
105
+        $this->currentUser = $userId;
106
+        $this->l = $l10n;
107
+    }
108
+
109
+    /**
110
+     * Convert an IShare to an array for OCS output
111
+     *
112
+     * @param \OCP\Share\IShare $share
113
+     * @param Node|null $recipientNode
114
+     * @return array
115
+     * @throws NotFoundException In case the node can't be resolved.
116
+     */
117
+    protected function formatShare(\OCP\Share\IShare $share, Node $recipientNode = null) {
118
+        $sharedBy = $this->userManager->get($share->getSharedBy());
119
+        $shareOwner = $this->userManager->get($share->getShareOwner());
120
+
121
+        $result = [
122
+            'id' => $share->getId(),
123
+            'share_type' => $share->getShareType(),
124
+            'uid_owner' => $share->getSharedBy(),
125
+            'displayname_owner' => $sharedBy !== null ? $sharedBy->getDisplayName() : $share->getSharedBy(),
126
+            'permissions' => $share->getPermissions(),
127
+            'stime' => $share->getShareTime()->getTimestamp(),
128
+            'parent' => null,
129
+            'expiration' => null,
130
+            'token' => null,
131
+            'uid_file_owner' => $share->getShareOwner(),
132
+            'displayname_file_owner' => $shareOwner !== null ? $shareOwner->getDisplayName() : $share->getShareOwner(),
133
+        ];
134
+
135
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
136
+        if ($recipientNode) {
137
+            $node = $recipientNode;
138
+        } else {
139
+            $nodes = $userFolder->getById($share->getNodeId());
140
+
141
+            if (empty($nodes)) {
142
+                // fallback to guessing the path
143
+                $node = $userFolder->get($share->getTarget());
144
+                if ($node === null) {
145
+                    throw new NotFoundException();
146
+                }
147
+            } else {
148
+                $node = $nodes[0];
149
+            }
150
+        }
151
+
152
+        $result['path'] = $userFolder->getRelativePath($node->getPath());
153
+        if ($node instanceOf \OCP\Files\Folder) {
154
+            $result['item_type'] = 'folder';
155
+        } else {
156
+            $result['item_type'] = 'file';
157
+        }
158
+        $result['mimetype'] = $node->getMimetype();
159
+        $result['storage_id'] = $node->getStorage()->getId();
160
+        $result['storage'] = $node->getStorage()->getCache()->getNumericStorageId();
161
+        $result['item_source'] = $node->getId();
162
+        $result['file_source'] = $node->getId();
163
+        $result['file_parent'] = $node->getParent()->getId();
164
+        $result['file_target'] = $share->getTarget();
165
+
166
+        $expiration = $share->getExpirationDate();
167
+        if ($expiration !== null) {
168
+            $result['expiration'] = $expiration->format('Y-m-d 00:00:00');
169
+        }
170
+
171
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
172
+            $sharedWith = $this->userManager->get($share->getSharedWith());
173
+            $result['share_with'] = $share->getSharedWith();
174
+            $result['share_with_displayname'] = $sharedWith !== null ? $sharedWith->getDisplayName() : $share->getSharedWith();
175
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
176
+            $group = $this->groupManager->get($share->getSharedWith());
177
+            $result['share_with'] = $share->getSharedWith();
178
+            $result['share_with_displayname'] = $group !== null ? $group->getDisplayName() : $share->getSharedWith();
179
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
180
+
181
+            $result['share_with'] = $share->getPassword();
182
+            $result['share_with_displayname'] = $share->getPassword();
183
+
184
+            $result['token'] = $share->getToken();
185
+            $result['url'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share->getToken()]);
186
+
187
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
188
+            $result['share_with'] = $share->getSharedWith();
189
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'CLOUD');
190
+            $result['token'] = $share->getToken();
191
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
192
+            $result['share_with'] = $share->getSharedWith();
193
+            $result['password'] = $share->getPassword();
194
+            $result['share_with_displayname'] = $this->getDisplayNameFromAddressBook($share->getSharedWith(), 'EMAIL');
195
+            $result['token'] = $share->getToken();
196
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
197
+            $result['share_with_displayname'] = $share->getSharedWith();
198
+            $result['share_with'] = explode(' ', $share->getSharedWith(), 2)[0];
199
+        }
200
+
201
+
202
+        $result['mail_send'] = $share->getMailSend() ? 1 : 0;
203
+
204
+        return $result;
205
+    }
206
+
207
+    /**
208
+     * Check if one of the users address books knows the exact property, if
209
+     * yes we return the full name.
210
+     *
211
+     * @param string $query
212
+     * @param string $property
213
+     * @return string
214
+     */
215
+    private function getDisplayNameFromAddressBook($query, $property) {
216
+        // FIXME: If we inject the contacts manager it gets initialized bofore any address books are registered
217
+        $result = \OC::$server->getContactsManager()->search($query, [$property]);
218
+        foreach ($result as $r) {
219
+            foreach($r[$property] as $value) {
220
+                if ($value === $query) {
221
+                    return $r['FN'];
222
+                }
223
+            }
224
+        }
225
+
226
+        return $query;
227
+    }
228
+
229
+    /**
230
+     * Get a specific share by id
231
+     *
232
+     * @NoAdminRequired
233
+     *
234
+     * @param string $id
235
+     * @return DataResponse
236
+     * @throws OCSNotFoundException
237
+     */
238
+    public function getShare($id) {
239
+        try {
240
+            $share = $this->getShareById($id);
241
+        } catch (ShareNotFound $e) {
242
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
243
+        }
244
+
245
+        if ($this->canAccessShare($share)) {
246
+            try {
247
+                $share = $this->formatShare($share);
248
+                return new DataResponse([$share]);
249
+            } catch (NotFoundException $e) {
250
+                //Fall trough
251
+            }
252
+        }
253
+
254
+        throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
255
+    }
256
+
257
+    /**
258
+     * Delete a share
259
+     *
260
+     * @NoAdminRequired
261
+     *
262
+     * @param string $id
263
+     * @return DataResponse
264
+     * @throws OCSNotFoundException
265
+     */
266
+    public function deleteShare($id) {
267
+        try {
268
+            $share = $this->getShareById($id);
269
+        } catch (ShareNotFound $e) {
270
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
271
+        }
272
+
273
+        try {
274
+            $this->lock($share->getNode());
275
+        } catch (LockedException $e) {
276
+            throw new OCSNotFoundException($this->l->t('could not delete share'));
277
+        }
278
+
279
+        if (!$this->canAccessShare($share)) {
280
+            throw new OCSNotFoundException($this->l->t('Could not delete share'));
281
+        }
282
+
283
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP &&
284
+            $share->getShareOwner() !== $this->currentUser &&
285
+            $share->getSharedBy() !== $this->currentUser) {
286
+            $this->shareManager->deleteFromSelf($share, $this->currentUser);
287
+        } else {
288
+            $this->shareManager->deleteShare($share);
289
+        }
290
+
291
+        return new DataResponse();
292
+    }
293
+
294
+    /**
295
+     * @NoAdminRequired
296
+     *
297
+     * @param string $path
298
+     * @param int $permissions
299
+     * @param int $shareType
300
+     * @param string $shareWith
301
+     * @param string $publicUpload
302
+     * @param string $password
303
+     * @param string $expireDate
304
+     *
305
+     * @return DataResponse
306
+     * @throws OCSNotFoundException
307
+     * @throws OCSForbiddenException
308
+     * @throws OCSBadRequestException
309
+     * @throws OCSException
310
+     */
311
+    public function createShare(
312
+        $path = null,
313
+        $permissions = \OCP\Constants::PERMISSION_ALL,
314
+        $shareType = -1,
315
+        $shareWith = null,
316
+        $publicUpload = 'false',
317
+        $password = '',
318
+        $expireDate = ''
319
+    ) {
320
+        $share = $this->shareManager->newShare();
321
+
322
+        // Verify path
323
+        if ($path === null) {
324
+            throw new OCSNotFoundException($this->l->t('Please specify a file or folder path'));
325
+        }
326
+
327
+        $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
328
+        try {
329
+            $path = $userFolder->get($path);
330
+        } catch (NotFoundException $e) {
331
+            throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
332
+        }
333
+
334
+        $share->setNode($path);
335
+
336
+        try {
337
+            $this->lock($share->getNode());
338
+        } catch (LockedException $e) {
339
+            throw new OCSNotFoundException($this->l->t('Could not create share'));
340
+        }
341
+
342
+        if ($permissions < 0 || $permissions > \OCP\Constants::PERMISSION_ALL) {
343
+            throw new OCSNotFoundException($this->l->t('invalid permissions'));
344
+        }
345
+
346
+        // Shares always require read permissions
347
+        $permissions |= \OCP\Constants::PERMISSION_READ;
348
+
349
+        if ($path instanceof \OCP\Files\File) {
350
+            // Single file shares should never have delete or create permissions
351
+            $permissions &= ~\OCP\Constants::PERMISSION_DELETE;
352
+            $permissions &= ~\OCP\Constants::PERMISSION_CREATE;
353
+        }
354
+
355
+        /*
356 356
 		 * Hack for https://github.com/owncloud/core/issues/22587
357 357
 		 * We check the permissions via webdav. But the permissions of the mount point
358 358
 		 * do not equal the share permissions. Here we fix that for federated mounts.
359 359
 		 */
360
-		if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
361
-			$permissions &= ~($permissions & ~$path->getPermissions());
362
-		}
363
-
364
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
365
-			// Valid user is required to share
366
-			if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
367
-				throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
368
-			}
369
-			$share->setSharedWith($shareWith);
370
-			$share->setPermissions($permissions);
371
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
372
-			if (!$this->shareManager->allowGroupSharing()) {
373
-				throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
374
-			}
375
-
376
-			// Valid group is required to share
377
-			if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
378
-				throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
379
-			}
380
-			$share->setSharedWith($shareWith);
381
-			$share->setPermissions($permissions);
382
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
383
-			//Can we even share links?
384
-			if (!$this->shareManager->shareApiAllowLinks()) {
385
-				throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
386
-			}
387
-
388
-			/*
360
+        if ($path->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
361
+            $permissions &= ~($permissions & ~$path->getPermissions());
362
+        }
363
+
364
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
365
+            // Valid user is required to share
366
+            if ($shareWith === null || !$this->userManager->userExists($shareWith)) {
367
+                throw new OCSNotFoundException($this->l->t('Please specify a valid user'));
368
+            }
369
+            $share->setSharedWith($shareWith);
370
+            $share->setPermissions($permissions);
371
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
372
+            if (!$this->shareManager->allowGroupSharing()) {
373
+                throw new OCSNotFoundException($this->l->t('Group sharing is disabled by the administrator'));
374
+            }
375
+
376
+            // Valid group is required to share
377
+            if ($shareWith === null || !$this->groupManager->groupExists($shareWith)) {
378
+                throw new OCSNotFoundException($this->l->t('Please specify a valid group'));
379
+            }
380
+            $share->setSharedWith($shareWith);
381
+            $share->setPermissions($permissions);
382
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
383
+            //Can we even share links?
384
+            if (!$this->shareManager->shareApiAllowLinks()) {
385
+                throw new OCSNotFoundException($this->l->t('Public link sharing is disabled by the administrator'));
386
+            }
387
+
388
+            /*
389 389
 			 * For now we only allow 1 link share.
390 390
 			 * Return the existing link share if this is a duplicate
391 391
 			 */
392
-			$existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
393
-			if (!empty($existingShares)) {
394
-				return new DataResponse($this->formatShare($existingShares[0]));
395
-			}
396
-
397
-			if ($publicUpload === 'true') {
398
-				// Check if public upload is allowed
399
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
400
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
401
-				}
402
-
403
-				// Public upload can only be set for folders
404
-				if ($path instanceof \OCP\Files\File) {
405
-					throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
406
-				}
407
-
408
-				$share->setPermissions(
409
-					\OCP\Constants::PERMISSION_READ |
410
-					\OCP\Constants::PERMISSION_CREATE |
411
-					\OCP\Constants::PERMISSION_UPDATE |
412
-					\OCP\Constants::PERMISSION_DELETE
413
-				);
414
-			} else {
415
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
416
-			}
417
-
418
-			// Set password
419
-			if ($password !== '') {
420
-				$share->setPassword($password);
421
-			}
422
-
423
-			//Expire date
424
-			if ($expireDate !== '') {
425
-				try {
426
-					$expireDate = $this->parseDate($expireDate);
427
-					$share->setExpirationDate($expireDate);
428
-				} catch (\Exception $e) {
429
-					throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
430
-				}
431
-			}
432
-
433
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
434
-			if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
435
-				throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
436
-			}
437
-
438
-			$share->setSharedWith($shareWith);
439
-			$share->setPermissions($permissions);
440
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
441
-			if ($share->getNodeType() === 'file') {
442
-				$share->setPermissions(\OCP\Constants::PERMISSION_READ);
443
-			} else {
444
-				$share->setPermissions(
445
-					\OCP\Constants::PERMISSION_READ |
446
-					\OCP\Constants::PERMISSION_CREATE |
447
-					\OCP\Constants::PERMISSION_UPDATE |
448
-					\OCP\Constants::PERMISSION_DELETE);
449
-			}
450
-			$share->setSharedWith($shareWith);
451
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
452
-			if (!\OCP\App::isEnabled('circles')) {
453
-				throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
454
-			}
455
-
456
-			$circle = \OCA\Circles\Api\Circles::detailsCircle($shareWith);
457
-
458
-			// Valid circle is required to share
459
-			if ($circle === null) {
460
-				throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
461
-			}
462
-			$share->setSharedWith($shareWith);
463
-			$share->setPermissions($permissions);
464
-		} else {
465
-			throw new OCSBadRequestException($this->l->t('Unknown share type'));
466
-		}
467
-
468
-		$share->setShareType($shareType);
469
-		$share->setSharedBy($this->currentUser);
470
-
471
-		try {
472
-			$share = $this->shareManager->createShare($share);
473
-		} catch (GenericShareException $e) {
474
-			$code = $e->getCode() === 0 ? 403 : $e->getCode();
475
-			throw new OCSException($e->getHint(), $code);
476
-		} catch (\Exception $e) {
477
-			throw new OCSForbiddenException($e->getMessage());
478
-		}
479
-
480
-		$output = $this->formatShare($share);
481
-
482
-		return new DataResponse($output);
483
-	}
484
-
485
-	/**
486
-	 * @param \OCP\Files\File|\OCP\Files\Folder $node
487
-	 * @return DataResponse
488
-	 */
489
-	private function getSharedWithMe($node = null) {
490
-
491
-		$userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
492
-		$groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
493
-		$circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
494
-
495
-		$shares = array_merge($userShares, $groupShares, $circleShares);
496
-
497
-		$shares = array_filter($shares, function (IShare $share) {
498
-			return $share->getShareOwner() !== $this->currentUser;
499
-		});
500
-
501
-		$formatted = [];
502
-		foreach ($shares as $share) {
503
-			if ($this->canAccessShare($share)) {
504
-				try {
505
-					$formatted[] = $this->formatShare($share);
506
-				} catch (NotFoundException $e) {
507
-					// Ignore this share
508
-				}
509
-			}
510
-		}
511
-
512
-		return new DataResponse($formatted);
513
-	}
514
-
515
-	/**
516
-	 * @param \OCP\Files\Folder $folder
517
-	 * @return DataResponse
518
-	 * @throws OCSBadRequestException
519
-	 */
520
-	private function getSharesInDir($folder) {
521
-		if (!($folder instanceof \OCP\Files\Folder)) {
522
-			throw new OCSBadRequestException($this->l->t('Not a directory'));
523
-		}
524
-
525
-		$nodes = $folder->getDirectoryListing();
526
-		/** @var \OCP\Share\IShare[] $shares */
527
-		$shares = [];
528
-		foreach ($nodes as $node) {
529
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
530
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
531
-			$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
532
-			if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
533
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
534
-			}
535
-			if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
536
-				$shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
537
-			}
538
-		}
539
-
540
-		$formatted = [];
541
-		foreach ($shares as $share) {
542
-			try {
543
-				$formatted[] = $this->formatShare($share);
544
-			} catch (NotFoundException $e) {
545
-				//Ignore this share
546
-			}
547
-		}
548
-
549
-		return new DataResponse($formatted);
550
-	}
551
-
552
-	/**
553
-	 * The getShares function.
554
-	 *
555
-	 * @NoAdminRequired
556
-	 *
557
-	 * @param string $shared_with_me
558
-	 * @param string $reshares
559
-	 * @param string $subfiles
560
-	 * @param string $path
561
-	 *
562
-	 * - Get shares by the current user
563
-	 * - Get shares by the current user and reshares (?reshares=true)
564
-	 * - Get shares with the current user (?shared_with_me=true)
565
-	 * - Get shares for a specific path (?path=...)
566
-	 * - Get all shares in a folder (?subfiles=true&path=..)
567
-	 *
568
-	 * @return DataResponse
569
-	 * @throws OCSNotFoundException
570
-	 */
571
-	public function getShares(
572
-		$shared_with_me = 'false',
573
-		$reshares = 'false',
574
-		$subfiles = 'false',
575
-		$path = null
576
-	) {
577
-
578
-		if ($path !== null) {
579
-			$userFolder = $this->rootFolder->getUserFolder($this->currentUser);
580
-			try {
581
-				$path = $userFolder->get($path);
582
-				$this->lock($path);
583
-			} catch (\OCP\Files\NotFoundException $e) {
584
-				throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
585
-			} catch (LockedException $e) {
586
-				throw new OCSNotFoundException($this->l->t('Could not lock path'));
587
-			}
588
-		}
589
-
590
-		if ($shared_with_me === 'true') {
591
-			$result = $this->getSharedWithMe($path);
592
-			return $result;
593
-		}
594
-
595
-		if ($subfiles === 'true') {
596
-			$result = $this->getSharesInDir($path);
597
-			return $result;
598
-		}
599
-
600
-		if ($reshares === 'true') {
601
-			$reshares = true;
602
-		} else {
603
-			$reshares = false;
604
-		}
605
-
606
-		// Get all shares
607
-		$userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
608
-		$groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
609
-		$linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
610
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
611
-			$mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
612
-		} else {
613
-			$mailShares = [];
614
-		}
615
-		if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
616
-			$circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
617
-		} else {
618
-			$circleShares = [];
619
-		}
620
-
621
-		$shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
622
-
623
-		if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
624
-			$federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
625
-			$shares = array_merge($shares, $federatedShares);
626
-		}
627
-
628
-		$formatted = [];
629
-		foreach ($shares as $share) {
630
-			try {
631
-				$formatted[] = $this->formatShare($share, $path);
632
-			} catch (NotFoundException $e) {
633
-				//Ignore share
634
-			}
635
-		}
636
-
637
-		return new DataResponse($formatted);
638
-	}
639
-
640
-	/**
641
-	 * @NoAdminRequired
642
-	 *
643
-	 * @param int $id
644
-	 * @param int $permissions
645
-	 * @param string $password
646
-	 * @param string $publicUpload
647
-	 * @param string $expireDate
648
-	 * @return DataResponse
649
-	 * @throws OCSNotFoundException
650
-	 * @throws OCSBadRequestException
651
-	 * @throws OCSForbiddenException
652
-	 */
653
-	public function updateShare(
654
-		$id,
655
-		$permissions = null,
656
-		$password = null,
657
-		$publicUpload = null,
658
-		$expireDate = null
659
-	) {
660
-		try {
661
-			$share = $this->getShareById($id);
662
-		} catch (ShareNotFound $e) {
663
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
664
-		}
665
-
666
-		$this->lock($share->getNode());
667
-
668
-		if (!$this->canAccessShare($share, false)) {
669
-			throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
670
-		}
671
-
672
-		if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
673
-			throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
674
-		}
675
-
676
-		/*
392
+            $existingShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, false, 1, 0);
393
+            if (!empty($existingShares)) {
394
+                return new DataResponse($this->formatShare($existingShares[0]));
395
+            }
396
+
397
+            if ($publicUpload === 'true') {
398
+                // Check if public upload is allowed
399
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
400
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
401
+                }
402
+
403
+                // Public upload can only be set for folders
404
+                if ($path instanceof \OCP\Files\File) {
405
+                    throw new OCSNotFoundException($this->l->t('Public upload is only possible for publicly shared folders'));
406
+                }
407
+
408
+                $share->setPermissions(
409
+                    \OCP\Constants::PERMISSION_READ |
410
+                    \OCP\Constants::PERMISSION_CREATE |
411
+                    \OCP\Constants::PERMISSION_UPDATE |
412
+                    \OCP\Constants::PERMISSION_DELETE
413
+                );
414
+            } else {
415
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
416
+            }
417
+
418
+            // Set password
419
+            if ($password !== '') {
420
+                $share->setPassword($password);
421
+            }
422
+
423
+            //Expire date
424
+            if ($expireDate !== '') {
425
+                try {
426
+                    $expireDate = $this->parseDate($expireDate);
427
+                    $share->setExpirationDate($expireDate);
428
+                } catch (\Exception $e) {
429
+                    throw new OCSNotFoundException($this->l->t('Invalid date, date format must be YYYY-MM-DD'));
430
+                }
431
+            }
432
+
433
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
434
+            if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
435
+                throw new OCSForbiddenException($this->l->t('Sharing %s failed because the back end does not allow shares from type %s', [$path->getPath(), $shareType]));
436
+            }
437
+
438
+            $share->setSharedWith($shareWith);
439
+            $share->setPermissions($permissions);
440
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
441
+            if ($share->getNodeType() === 'file') {
442
+                $share->setPermissions(\OCP\Constants::PERMISSION_READ);
443
+            } else {
444
+                $share->setPermissions(
445
+                    \OCP\Constants::PERMISSION_READ |
446
+                    \OCP\Constants::PERMISSION_CREATE |
447
+                    \OCP\Constants::PERMISSION_UPDATE |
448
+                    \OCP\Constants::PERMISSION_DELETE);
449
+            }
450
+            $share->setSharedWith($shareWith);
451
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
452
+            if (!\OCP\App::isEnabled('circles')) {
453
+                throw new OCSNotFoundException($this->l->t('You cannot share to a Circle if the app is not enabled'));
454
+            }
455
+
456
+            $circle = \OCA\Circles\Api\Circles::detailsCircle($shareWith);
457
+
458
+            // Valid circle is required to share
459
+            if ($circle === null) {
460
+                throw new OCSNotFoundException($this->l->t('Please specify a valid circle'));
461
+            }
462
+            $share->setSharedWith($shareWith);
463
+            $share->setPermissions($permissions);
464
+        } else {
465
+            throw new OCSBadRequestException($this->l->t('Unknown share type'));
466
+        }
467
+
468
+        $share->setShareType($shareType);
469
+        $share->setSharedBy($this->currentUser);
470
+
471
+        try {
472
+            $share = $this->shareManager->createShare($share);
473
+        } catch (GenericShareException $e) {
474
+            $code = $e->getCode() === 0 ? 403 : $e->getCode();
475
+            throw new OCSException($e->getHint(), $code);
476
+        } catch (\Exception $e) {
477
+            throw new OCSForbiddenException($e->getMessage());
478
+        }
479
+
480
+        $output = $this->formatShare($share);
481
+
482
+        return new DataResponse($output);
483
+    }
484
+
485
+    /**
486
+     * @param \OCP\Files\File|\OCP\Files\Folder $node
487
+     * @return DataResponse
488
+     */
489
+    private function getSharedWithMe($node = null) {
490
+
491
+        $userShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, -1, 0);
492
+        $groupShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, -1, 0);
493
+        $circleShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $node, -1, 0);
494
+
495
+        $shares = array_merge($userShares, $groupShares, $circleShares);
496
+
497
+        $shares = array_filter($shares, function (IShare $share) {
498
+            return $share->getShareOwner() !== $this->currentUser;
499
+        });
500
+
501
+        $formatted = [];
502
+        foreach ($shares as $share) {
503
+            if ($this->canAccessShare($share)) {
504
+                try {
505
+                    $formatted[] = $this->formatShare($share);
506
+                } catch (NotFoundException $e) {
507
+                    // Ignore this share
508
+                }
509
+            }
510
+        }
511
+
512
+        return new DataResponse($formatted);
513
+    }
514
+
515
+    /**
516
+     * @param \OCP\Files\Folder $folder
517
+     * @return DataResponse
518
+     * @throws OCSBadRequestException
519
+     */
520
+    private function getSharesInDir($folder) {
521
+        if (!($folder instanceof \OCP\Files\Folder)) {
522
+            throw new OCSBadRequestException($this->l->t('Not a directory'));
523
+        }
524
+
525
+        $nodes = $folder->getDirectoryListing();
526
+        /** @var \OCP\Share\IShare[] $shares */
527
+        $shares = [];
528
+        foreach ($nodes as $node) {
529
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $node, false, -1, 0));
530
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $node, false, -1, 0));
531
+            $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $node, false, -1, 0));
532
+            if($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
533
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $node, false, -1, 0));
534
+            }
535
+            if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
536
+                $shares = array_merge($shares, $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $node, false, -1, 0));
537
+            }
538
+        }
539
+
540
+        $formatted = [];
541
+        foreach ($shares as $share) {
542
+            try {
543
+                $formatted[] = $this->formatShare($share);
544
+            } catch (NotFoundException $e) {
545
+                //Ignore this share
546
+            }
547
+        }
548
+
549
+        return new DataResponse($formatted);
550
+    }
551
+
552
+    /**
553
+     * The getShares function.
554
+     *
555
+     * @NoAdminRequired
556
+     *
557
+     * @param string $shared_with_me
558
+     * @param string $reshares
559
+     * @param string $subfiles
560
+     * @param string $path
561
+     *
562
+     * - Get shares by the current user
563
+     * - Get shares by the current user and reshares (?reshares=true)
564
+     * - Get shares with the current user (?shared_with_me=true)
565
+     * - Get shares for a specific path (?path=...)
566
+     * - Get all shares in a folder (?subfiles=true&path=..)
567
+     *
568
+     * @return DataResponse
569
+     * @throws OCSNotFoundException
570
+     */
571
+    public function getShares(
572
+        $shared_with_me = 'false',
573
+        $reshares = 'false',
574
+        $subfiles = 'false',
575
+        $path = null
576
+    ) {
577
+
578
+        if ($path !== null) {
579
+            $userFolder = $this->rootFolder->getUserFolder($this->currentUser);
580
+            try {
581
+                $path = $userFolder->get($path);
582
+                $this->lock($path);
583
+            } catch (\OCP\Files\NotFoundException $e) {
584
+                throw new OCSNotFoundException($this->l->t('Wrong path, file/folder doesn\'t exist'));
585
+            } catch (LockedException $e) {
586
+                throw new OCSNotFoundException($this->l->t('Could not lock path'));
587
+            }
588
+        }
589
+
590
+        if ($shared_with_me === 'true') {
591
+            $result = $this->getSharedWithMe($path);
592
+            return $result;
593
+        }
594
+
595
+        if ($subfiles === 'true') {
596
+            $result = $this->getSharesInDir($path);
597
+            return $result;
598
+        }
599
+
600
+        if ($reshares === 'true') {
601
+            $reshares = true;
602
+        } else {
603
+            $reshares = false;
604
+        }
605
+
606
+        // Get all shares
607
+        $userShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $path, $reshares, -1, 0);
608
+        $groupShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $path, $reshares, -1, 0);
609
+        $linkShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_LINK, $path, $reshares, -1, 0);
610
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
611
+            $mailShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_EMAIL, $path, $reshares, -1, 0);
612
+        } else {
613
+            $mailShares = [];
614
+        }
615
+        if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
616
+            $circleShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_CIRCLE, $path, $reshares, -1, 0);
617
+        } else {
618
+            $circleShares = [];
619
+        }
620
+
621
+        $shares = array_merge($userShares, $groupShares, $linkShares, $mailShares, $circleShares);
622
+
623
+        if ($this->shareManager->outgoingServer2ServerSharesAllowed()) {
624
+            $federatedShares = $this->shareManager->getSharesBy($this->currentUser, \OCP\Share::SHARE_TYPE_REMOTE, $path, $reshares, -1, 0);
625
+            $shares = array_merge($shares, $federatedShares);
626
+        }
627
+
628
+        $formatted = [];
629
+        foreach ($shares as $share) {
630
+            try {
631
+                $formatted[] = $this->formatShare($share, $path);
632
+            } catch (NotFoundException $e) {
633
+                //Ignore share
634
+            }
635
+        }
636
+
637
+        return new DataResponse($formatted);
638
+    }
639
+
640
+    /**
641
+     * @NoAdminRequired
642
+     *
643
+     * @param int $id
644
+     * @param int $permissions
645
+     * @param string $password
646
+     * @param string $publicUpload
647
+     * @param string $expireDate
648
+     * @return DataResponse
649
+     * @throws OCSNotFoundException
650
+     * @throws OCSBadRequestException
651
+     * @throws OCSForbiddenException
652
+     */
653
+    public function updateShare(
654
+        $id,
655
+        $permissions = null,
656
+        $password = null,
657
+        $publicUpload = null,
658
+        $expireDate = null
659
+    ) {
660
+        try {
661
+            $share = $this->getShareById($id);
662
+        } catch (ShareNotFound $e) {
663
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
664
+        }
665
+
666
+        $this->lock($share->getNode());
667
+
668
+        if (!$this->canAccessShare($share, false)) {
669
+            throw new OCSNotFoundException($this->l->t('Wrong share ID, share doesn\'t exist'));
670
+        }
671
+
672
+        if ($permissions === null && $password === null && $publicUpload === null && $expireDate === null) {
673
+            throw new OCSBadRequestException($this->l->t('Wrong or no update parameter given'));
674
+        }
675
+
676
+        /*
677 677
 		 * expirationdate, password and publicUpload only make sense for link shares
678 678
 		 */
679
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
680
-
681
-			$newPermissions = null;
682
-			if ($publicUpload === 'true') {
683
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
684
-			} else if ($publicUpload === 'false') {
685
-				$newPermissions = \OCP\Constants::PERMISSION_READ;
686
-			}
687
-
688
-			if ($permissions !== null) {
689
-				$newPermissions = (int)$permissions;
690
-			}
691
-
692
-			if ($newPermissions !== null &&
693
-				!in_array($newPermissions, [
694
-					\OCP\Constants::PERMISSION_READ,
695
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
696
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
697
-					\OCP\Constants::PERMISSION_CREATE, // hidden file list
698
-					\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
699
-				])
700
-			) {
701
-				throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
702
-			}
703
-
704
-			if (
705
-				// legacy
706
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
707
-				// correct
708
-				$newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
709
-			) {
710
-				if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
711
-					throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
712
-				}
713
-
714
-				if (!($share->getNode() instanceof \OCP\Files\Folder)) {
715
-					throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
716
-				}
717
-
718
-				// normalize to correct public upload permissions
719
-				$newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
720
-			}
721
-
722
-			if ($newPermissions !== null) {
723
-				$share->setPermissions($newPermissions);
724
-				$permissions = $newPermissions;
725
-			}
726
-
727
-			if ($expireDate === '') {
728
-				$share->setExpirationDate(null);
729
-			} else if ($expireDate !== null) {
730
-				try {
731
-					$expireDate = $this->parseDate($expireDate);
732
-				} catch (\Exception $e) {
733
-					throw new OCSBadRequestException($e->getMessage());
734
-				}
735
-				$share->setExpirationDate($expireDate);
736
-			}
737
-
738
-			if ($password === '') {
739
-				$share->setPassword(null);
740
-			} else if ($password !== null) {
741
-				$share->setPassword($password);
742
-			}
743
-
744
-		} else {
745
-			if ($permissions !== null) {
746
-				$permissions = (int)$permissions;
747
-				$share->setPermissions($permissions);
748
-			}
749
-
750
-			if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
751
-				if ($password === '') {
752
-					$share->setPassword(null);
753
-				} else if ($password !== null) {
754
-					$share->setPassword($password);
755
-				}
756
-			}
757
-
758
-			if ($expireDate === '') {
759
-				$share->setExpirationDate(null);
760
-			} else if ($expireDate !== null) {
761
-				try {
762
-					$expireDate = $this->parseDate($expireDate);
763
-				} catch (\Exception $e) {
764
-					throw new OCSBadRequestException($e->getMessage());
765
-				}
766
-				$share->setExpirationDate($expireDate);
767
-			}
768
-
769
-		}
770
-
771
-		if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
772
-			/* Check if this is an incomming share */
773
-			$incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
774
-			$incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
775
-
776
-			/** @var \OCP\Share\IShare[] $incomingShares */
777
-			if (!empty($incomingShares)) {
778
-				$maxPermissions = 0;
779
-				foreach ($incomingShares as $incomingShare) {
780
-					$maxPermissions |= $incomingShare->getPermissions();
781
-				}
782
-
783
-				if ($share->getPermissions() & ~$maxPermissions) {
784
-					throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
785
-				}
786
-			}
787
-		}
788
-
789
-
790
-		try {
791
-			$share = $this->shareManager->updateShare($share);
792
-		} catch (\Exception $e) {
793
-			throw new OCSBadRequestException($e->getMessage());
794
-		}
795
-
796
-		return new DataResponse($this->formatShare($share));
797
-	}
798
-
799
-	/**
800
-	 * @param \OCP\Share\IShare $share
801
-	 * @return bool
802
-	 */
803
-	protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
804
-		// A file with permissions 0 can't be accessed by us. So Don't show it
805
-		if ($share->getPermissions() === 0) {
806
-			return false;
807
-		}
808
-
809
-		// Owner of the file and the sharer of the file can always get share
810
-		if ($share->getShareOwner() === $this->currentUser ||
811
-			$share->getSharedBy() === $this->currentUser
812
-		) {
813
-			return true;
814
-		}
815
-
816
-		// If the share is shared with you (or a group you are a member of)
817
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
818
-			$share->getSharedWith() === $this->currentUser
819
-		) {
820
-			return true;
821
-		}
822
-
823
-		if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
824
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
825
-			$user = $this->userManager->get($this->currentUser);
826
-			if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
827
-				return true;
828
-			}
829
-		}
830
-
831
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
832
-			// TODO: have a sanity check like above?
833
-			return true;
834
-		}
835
-
836
-		return false;
837
-	}
838
-
839
-	/**
840
-	 * Make sure that the passed date is valid ISO 8601
841
-	 * So YYYY-MM-DD
842
-	 * If not throw an exception
843
-	 *
844
-	 * @param string $expireDate
845
-	 *
846
-	 * @throws \Exception
847
-	 * @return \DateTime
848
-	 */
849
-	private function parseDate($expireDate) {
850
-		try {
851
-			$date = new \DateTime($expireDate);
852
-		} catch (\Exception $e) {
853
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
854
-		}
855
-
856
-		if ($date === false) {
857
-			throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
858
-		}
859
-
860
-		$date->setTime(0, 0, 0);
861
-
862
-		return $date;
863
-	}
864
-
865
-	/**
866
-	 * Since we have multiple providers but the OCS Share API v1 does
867
-	 * not support this we need to check all backends.
868
-	 *
869
-	 * @param string $id
870
-	 * @return \OCP\Share\IShare
871
-	 * @throws ShareNotFound
872
-	 */
873
-	private function getShareById($id) {
874
-		$share = null;
875
-
876
-		// First check if it is an internal share.
877
-		try {
878
-			$share = $this->shareManager->getShareById('ocinternal:' . $id);
879
-			return $share;
880
-		} catch (ShareNotFound $e) {
881
-			// Do nothing, just try the other share type
882
-		}
883
-
884
-
885
-		try {
886
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
887
-				$share = $this->shareManager->getShareById('ocCircleShare:' . $id);
888
-				return $share;
889
-			}
890
-		} catch (ShareNotFound $e) {
891
-			// Do nothing, just try the other share type
892
-		}
893
-
894
-		try {
895
-			if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
896
-				$share = $this->shareManager->getShareById('ocMailShare:' . $id);
897
-				return $share;
898
-			}
899
-		} catch (ShareNotFound $e) {
900
-			// Do nothing, just try the other share type
901
-		}
902
-
903
-		if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
904
-			throw new ShareNotFound();
905
-		}
906
-		$share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
907
-
908
-		return $share;
909
-	}
910
-
911
-	/**
912
-	 * Lock a Node
913
-	 *
914
-	 * @param \OCP\Files\Node $node
915
-	 */
916
-	private function lock(\OCP\Files\Node $node) {
917
-		$node->lock(ILockingProvider::LOCK_SHARED);
918
-		$this->lockedNode = $node;
919
-	}
920
-
921
-	/**
922
-	 * Cleanup the remaining locks
923
-	 */
924
-	public function cleanup() {
925
-		if ($this->lockedNode !== null) {
926
-			$this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
927
-		}
928
-	}
679
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
680
+
681
+            $newPermissions = null;
682
+            if ($publicUpload === 'true') {
683
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
684
+            } else if ($publicUpload === 'false') {
685
+                $newPermissions = \OCP\Constants::PERMISSION_READ;
686
+            }
687
+
688
+            if ($permissions !== null) {
689
+                $newPermissions = (int)$permissions;
690
+            }
691
+
692
+            if ($newPermissions !== null &&
693
+                !in_array($newPermissions, [
694
+                    \OCP\Constants::PERMISSION_READ,
695
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE, // legacy
696
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE, // correct
697
+                    \OCP\Constants::PERMISSION_CREATE, // hidden file list
698
+                    \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_UPDATE, // allow to edit single files
699
+                ])
700
+            ) {
701
+                throw new OCSBadRequestException($this->l->t('Can\'t change permissions for public share links'));
702
+            }
703
+
704
+            if (
705
+                // legacy
706
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE) ||
707
+                // correct
708
+                $newPermissions === (\OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE)
709
+            ) {
710
+                if (!$this->shareManager->shareApiLinkAllowPublicUpload()) {
711
+                    throw new OCSForbiddenException($this->l->t('Public upload disabled by the administrator'));
712
+                }
713
+
714
+                if (!($share->getNode() instanceof \OCP\Files\Folder)) {
715
+                    throw new OCSBadRequestException($this->l->t('Public upload is only possible for publicly shared folders'));
716
+                }
717
+
718
+                // normalize to correct public upload permissions
719
+                $newPermissions = \OCP\Constants::PERMISSION_READ | \OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
720
+            }
721
+
722
+            if ($newPermissions !== null) {
723
+                $share->setPermissions($newPermissions);
724
+                $permissions = $newPermissions;
725
+            }
726
+
727
+            if ($expireDate === '') {
728
+                $share->setExpirationDate(null);
729
+            } else if ($expireDate !== null) {
730
+                try {
731
+                    $expireDate = $this->parseDate($expireDate);
732
+                } catch (\Exception $e) {
733
+                    throw new OCSBadRequestException($e->getMessage());
734
+                }
735
+                $share->setExpirationDate($expireDate);
736
+            }
737
+
738
+            if ($password === '') {
739
+                $share->setPassword(null);
740
+            } else if ($password !== null) {
741
+                $share->setPassword($password);
742
+            }
743
+
744
+        } else {
745
+            if ($permissions !== null) {
746
+                $permissions = (int)$permissions;
747
+                $share->setPermissions($permissions);
748
+            }
749
+
750
+            if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
751
+                if ($password === '') {
752
+                    $share->setPassword(null);
753
+                } else if ($password !== null) {
754
+                    $share->setPassword($password);
755
+                }
756
+            }
757
+
758
+            if ($expireDate === '') {
759
+                $share->setExpirationDate(null);
760
+            } else if ($expireDate !== null) {
761
+                try {
762
+                    $expireDate = $this->parseDate($expireDate);
763
+                } catch (\Exception $e) {
764
+                    throw new OCSBadRequestException($e->getMessage());
765
+                }
766
+                $share->setExpirationDate($expireDate);
767
+            }
768
+
769
+        }
770
+
771
+        if ($permissions !== null && $share->getShareOwner() !== $this->currentUser) {
772
+            /* Check if this is an incomming share */
773
+            $incomingShares = $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_USER, $share->getNode(), -1, 0);
774
+            $incomingShares = array_merge($incomingShares, $this->shareManager->getSharedWith($this->currentUser, \OCP\Share::SHARE_TYPE_GROUP, $share->getNode(), -1, 0));
775
+
776
+            /** @var \OCP\Share\IShare[] $incomingShares */
777
+            if (!empty($incomingShares)) {
778
+                $maxPermissions = 0;
779
+                foreach ($incomingShares as $incomingShare) {
780
+                    $maxPermissions |= $incomingShare->getPermissions();
781
+                }
782
+
783
+                if ($share->getPermissions() & ~$maxPermissions) {
784
+                    throw new OCSNotFoundException($this->l->t('Cannot increase permissions'));
785
+                }
786
+            }
787
+        }
788
+
789
+
790
+        try {
791
+            $share = $this->shareManager->updateShare($share);
792
+        } catch (\Exception $e) {
793
+            throw new OCSBadRequestException($e->getMessage());
794
+        }
795
+
796
+        return new DataResponse($this->formatShare($share));
797
+    }
798
+
799
+    /**
800
+     * @param \OCP\Share\IShare $share
801
+     * @return bool
802
+     */
803
+    protected function canAccessShare(\OCP\Share\IShare $share, $checkGroups = true) {
804
+        // A file with permissions 0 can't be accessed by us. So Don't show it
805
+        if ($share->getPermissions() === 0) {
806
+            return false;
807
+        }
808
+
809
+        // Owner of the file and the sharer of the file can always get share
810
+        if ($share->getShareOwner() === $this->currentUser ||
811
+            $share->getSharedBy() === $this->currentUser
812
+        ) {
813
+            return true;
814
+        }
815
+
816
+        // If the share is shared with you (or a group you are a member of)
817
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
818
+            $share->getSharedWith() === $this->currentUser
819
+        ) {
820
+            return true;
821
+        }
822
+
823
+        if ($checkGroups && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
824
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
825
+            $user = $this->userManager->get($this->currentUser);
826
+            if ($user !== null && $sharedWith !== null && $sharedWith->inGroup($user)) {
827
+                return true;
828
+            }
829
+        }
830
+
831
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
832
+            // TODO: have a sanity check like above?
833
+            return true;
834
+        }
835
+
836
+        return false;
837
+    }
838
+
839
+    /**
840
+     * Make sure that the passed date is valid ISO 8601
841
+     * So YYYY-MM-DD
842
+     * If not throw an exception
843
+     *
844
+     * @param string $expireDate
845
+     *
846
+     * @throws \Exception
847
+     * @return \DateTime
848
+     */
849
+    private function parseDate($expireDate) {
850
+        try {
851
+            $date = new \DateTime($expireDate);
852
+        } catch (\Exception $e) {
853
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
854
+        }
855
+
856
+        if ($date === false) {
857
+            throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
858
+        }
859
+
860
+        $date->setTime(0, 0, 0);
861
+
862
+        return $date;
863
+    }
864
+
865
+    /**
866
+     * Since we have multiple providers but the OCS Share API v1 does
867
+     * not support this we need to check all backends.
868
+     *
869
+     * @param string $id
870
+     * @return \OCP\Share\IShare
871
+     * @throws ShareNotFound
872
+     */
873
+    private function getShareById($id) {
874
+        $share = null;
875
+
876
+        // First check if it is an internal share.
877
+        try {
878
+            $share = $this->shareManager->getShareById('ocinternal:' . $id);
879
+            return $share;
880
+        } catch (ShareNotFound $e) {
881
+            // Do nothing, just try the other share type
882
+        }
883
+
884
+
885
+        try {
886
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
887
+                $share = $this->shareManager->getShareById('ocCircleShare:' . $id);
888
+                return $share;
889
+            }
890
+        } catch (ShareNotFound $e) {
891
+            // Do nothing, just try the other share type
892
+        }
893
+
894
+        try {
895
+            if ($this->shareManager->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
896
+                $share = $this->shareManager->getShareById('ocMailShare:' . $id);
897
+                return $share;
898
+            }
899
+        } catch (ShareNotFound $e) {
900
+            // Do nothing, just try the other share type
901
+        }
902
+
903
+        if (!$this->shareManager->outgoingServer2ServerSharesAllowed()) {
904
+            throw new ShareNotFound();
905
+        }
906
+        $share = $this->shareManager->getShareById('ocFederatedSharing:' . $id);
907
+
908
+        return $share;
909
+    }
910
+
911
+    /**
912
+     * Lock a Node
913
+     *
914
+     * @param \OCP\Files\Node $node
915
+     */
916
+    private function lock(\OCP\Files\Node $node) {
917
+        $node->lock(ILockingProvider::LOCK_SHARED);
918
+        $this->lockedNode = $node;
919
+    }
920
+
921
+    /**
922
+     * Cleanup the remaining locks
923
+     */
924
+    public function cleanup() {
925
+        if ($this->lockedNode !== null) {
926
+            $this->lockedNode->unlock(ILockingProvider::LOCK_SHARED);
927
+        }
928
+    }
929 929
 }
Please login to merge, or discard this patch.