Completed
Pull Request — master (#6437)
by Morris
31:48 queued 16:28
created
lib/private/Share20/DefaultShareProvider.php 1 patch
Indentation   +1106 added lines, -1106 removed lines patch added patch discarded remove patch
@@ -46,1143 +46,1143 @@
 block discarded – undo
46 46
  */
47 47
 class DefaultShareProvider implements IShareProvider {
48 48
 
49
-	// Special share type for user modified group shares
50
-	const SHARE_TYPE_USERGROUP = 2;
51
-
52
-	/** @var IDBConnection */
53
-	private $dbConn;
54
-
55
-	/** @var IUserManager */
56
-	private $userManager;
57
-
58
-	/** @var IGroupManager */
59
-	private $groupManager;
60
-
61
-	/** @var IRootFolder */
62
-	private $rootFolder;
63
-
64
-	/**
65
-	 * DefaultShareProvider constructor.
66
-	 *
67
-	 * @param IDBConnection $connection
68
-	 * @param IUserManager $userManager
69
-	 * @param IGroupManager $groupManager
70
-	 * @param IRootFolder $rootFolder
71
-	 */
72
-	public function __construct(
73
-			IDBConnection $connection,
74
-			IUserManager $userManager,
75
-			IGroupManager $groupManager,
76
-			IRootFolder $rootFolder) {
77
-		$this->dbConn = $connection;
78
-		$this->userManager = $userManager;
79
-		$this->groupManager = $groupManager;
80
-		$this->rootFolder = $rootFolder;
81
-	}
82
-
83
-	/**
84
-	 * Return the identifier of this provider.
85
-	 *
86
-	 * @return string Containing only [a-zA-Z0-9]
87
-	 */
88
-	public function identifier() {
89
-		return 'ocinternal';
90
-	}
91
-
92
-	/**
93
-	 * Share a path
94
-	 *
95
-	 * @param \OCP\Share\IShare $share
96
-	 * @return \OCP\Share\IShare The share object
97
-	 * @throws ShareNotFound
98
-	 * @throws \Exception
99
-	 */
100
-	public function create(\OCP\Share\IShare $share) {
101
-		$qb = $this->dbConn->getQueryBuilder();
102
-
103
-		$qb->insert('share');
104
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
105
-
106
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
107
-			//Set the UID of the user we share with
108
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
109
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
110
-			//Set the GID of the group we share with
111
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
112
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
113
-			//Set the token of the share
114
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
115
-
116
-			//If a password is set store it
117
-			if ($share->getPassword() !== null) {
118
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
119
-			}
120
-
121
-			//If an expiration date is set store it
122
-			if ($share->getExpirationDate() !== null) {
123
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
124
-			}
125
-
126
-			if (method_exists($share, 'getParent')) {
127
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
128
-			}
129
-		} else {
130
-			throw new \Exception('invalid share type!');
131
-		}
132
-
133
-		// Set what is shares
134
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
135
-		if ($share->getNode() instanceof \OCP\Files\File) {
136
-			$qb->setParameter('itemType', 'file');
137
-		} else {
138
-			$qb->setParameter('itemType', 'folder');
139
-		}
140
-
141
-		// Set the file id
142
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
143
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-
145
-		// set the permissions
146
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
147
-
148
-		// Set who created this share
149
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
150
-
151
-		// Set who is the owner of this file/folder (and this the owner of the share)
152
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
153
-
154
-		// Set the file target
155
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
156
-
157
-		// Set the time this share was created
158
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
159
-
160
-		// insert the data and fetch the id of the share
161
-		$this->dbConn->beginTransaction();
162
-		$qb->execute();
163
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
164
-
165
-		// Now fetch the inserted share and create a complete share object
166
-		$qb = $this->dbConn->getQueryBuilder();
167
-		$qb->select('*')
168
-			->from('share')
169
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
170
-
171
-		$cursor = $qb->execute();
172
-		$data = $cursor->fetch();
173
-		$this->dbConn->commit();
174
-		$cursor->closeCursor();
175
-
176
-		if ($data === false) {
177
-			throw new ShareNotFound();
178
-		}
179
-
180
-		$mailSendValue = $share->getMailSend();
181
-		$data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
182
-
183
-		$share = $this->createShare($data);
184
-		return $share;
185
-	}
186
-
187
-	/**
188
-	 * Update a share
189
-	 *
190
-	 * @param \OCP\Share\IShare $share
191
-	 * @return \OCP\Share\IShare The share object
192
-	 */
193
-	public function update(\OCP\Share\IShare $share) {
194
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
195
-			/*
49
+    // Special share type for user modified group shares
50
+    const SHARE_TYPE_USERGROUP = 2;
51
+
52
+    /** @var IDBConnection */
53
+    private $dbConn;
54
+
55
+    /** @var IUserManager */
56
+    private $userManager;
57
+
58
+    /** @var IGroupManager */
59
+    private $groupManager;
60
+
61
+    /** @var IRootFolder */
62
+    private $rootFolder;
63
+
64
+    /**
65
+     * DefaultShareProvider constructor.
66
+     *
67
+     * @param IDBConnection $connection
68
+     * @param IUserManager $userManager
69
+     * @param IGroupManager $groupManager
70
+     * @param IRootFolder $rootFolder
71
+     */
72
+    public function __construct(
73
+            IDBConnection $connection,
74
+            IUserManager $userManager,
75
+            IGroupManager $groupManager,
76
+            IRootFolder $rootFolder) {
77
+        $this->dbConn = $connection;
78
+        $this->userManager = $userManager;
79
+        $this->groupManager = $groupManager;
80
+        $this->rootFolder = $rootFolder;
81
+    }
82
+
83
+    /**
84
+     * Return the identifier of this provider.
85
+     *
86
+     * @return string Containing only [a-zA-Z0-9]
87
+     */
88
+    public function identifier() {
89
+        return 'ocinternal';
90
+    }
91
+
92
+    /**
93
+     * Share a path
94
+     *
95
+     * @param \OCP\Share\IShare $share
96
+     * @return \OCP\Share\IShare The share object
97
+     * @throws ShareNotFound
98
+     * @throws \Exception
99
+     */
100
+    public function create(\OCP\Share\IShare $share) {
101
+        $qb = $this->dbConn->getQueryBuilder();
102
+
103
+        $qb->insert('share');
104
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
105
+
106
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
107
+            //Set the UID of the user we share with
108
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
109
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
110
+            //Set the GID of the group we share with
111
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
112
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
113
+            //Set the token of the share
114
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
115
+
116
+            //If a password is set store it
117
+            if ($share->getPassword() !== null) {
118
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
119
+            }
120
+
121
+            //If an expiration date is set store it
122
+            if ($share->getExpirationDate() !== null) {
123
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
124
+            }
125
+
126
+            if (method_exists($share, 'getParent')) {
127
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
128
+            }
129
+        } else {
130
+            throw new \Exception('invalid share type!');
131
+        }
132
+
133
+        // Set what is shares
134
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
135
+        if ($share->getNode() instanceof \OCP\Files\File) {
136
+            $qb->setParameter('itemType', 'file');
137
+        } else {
138
+            $qb->setParameter('itemType', 'folder');
139
+        }
140
+
141
+        // Set the file id
142
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
143
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+
145
+        // set the permissions
146
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
147
+
148
+        // Set who created this share
149
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
150
+
151
+        // Set who is the owner of this file/folder (and this the owner of the share)
152
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
153
+
154
+        // Set the file target
155
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
156
+
157
+        // Set the time this share was created
158
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
159
+
160
+        // insert the data and fetch the id of the share
161
+        $this->dbConn->beginTransaction();
162
+        $qb->execute();
163
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
164
+
165
+        // Now fetch the inserted share and create a complete share object
166
+        $qb = $this->dbConn->getQueryBuilder();
167
+        $qb->select('*')
168
+            ->from('share')
169
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
170
+
171
+        $cursor = $qb->execute();
172
+        $data = $cursor->fetch();
173
+        $this->dbConn->commit();
174
+        $cursor->closeCursor();
175
+
176
+        if ($data === false) {
177
+            throw new ShareNotFound();
178
+        }
179
+
180
+        $mailSendValue = $share->getMailSend();
181
+        $data['mail_send'] = ($mailSendValue === null) ? true : $mailSendValue;
182
+
183
+        $share = $this->createShare($data);
184
+        return $share;
185
+    }
186
+
187
+    /**
188
+     * Update a share
189
+     *
190
+     * @param \OCP\Share\IShare $share
191
+     * @return \OCP\Share\IShare The share object
192
+     */
193
+    public function update(\OCP\Share\IShare $share) {
194
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
195
+            /*
196 196
 			 * We allow updating the recipient on user shares.
197 197
 			 */
198
-			$qb = $this->dbConn->getQueryBuilder();
199
-			$qb->update('share')
200
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
201
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
202
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
203
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
204
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
205
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
206
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
207
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
208
-				->execute();
209
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
210
-			$qb = $this->dbConn->getQueryBuilder();
211
-			$qb->update('share')
212
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
213
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
214
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
215
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
216
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
217
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
218
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
219
-				->execute();
220
-
221
-			/*
198
+            $qb = $this->dbConn->getQueryBuilder();
199
+            $qb->update('share')
200
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
201
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
202
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
203
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
204
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
205
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
206
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
207
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
208
+                ->execute();
209
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
210
+            $qb = $this->dbConn->getQueryBuilder();
211
+            $qb->update('share')
212
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
213
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
214
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
215
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
216
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
217
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
218
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
219
+                ->execute();
220
+
221
+            /*
222 222
 			 * Update all user defined group shares
223 223
 			 */
224
-			$qb = $this->dbConn->getQueryBuilder();
225
-			$qb->update('share')
226
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
227
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
228
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
229
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
230
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
231
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
232
-				->execute();
233
-
234
-			/*
224
+            $qb = $this->dbConn->getQueryBuilder();
225
+            $qb->update('share')
226
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
227
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
228
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
229
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
230
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
231
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
232
+                ->execute();
233
+
234
+            /*
235 235
 			 * Now update the permissions for all children that have not set it to 0
236 236
 			 */
237
-			$qb = $this->dbConn->getQueryBuilder();
238
-			$qb->update('share')
239
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
240
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
241
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
242
-				->execute();
243
-
244
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
245
-			$qb = $this->dbConn->getQueryBuilder();
246
-			$qb->update('share')
247
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
248
-				->set('password', $qb->createNamedParameter($share->getPassword()))
249
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
250
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
251
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
252
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
253
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
254
-				->set('token', $qb->createNamedParameter($share->getToken()))
255
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
256
-				->execute();
257
-		}
258
-
259
-		return $share;
260
-	}
261
-
262
-	/**
263
-	 * Get all children of this share
264
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
265
-	 *
266
-	 * @param \OCP\Share\IShare $parent
267
-	 * @return \OCP\Share\IShare[]
268
-	 */
269
-	public function getChildren(\OCP\Share\IShare $parent) {
270
-		$children = [];
271
-
272
-		$qb = $this->dbConn->getQueryBuilder();
273
-		$qb->select('*')
274
-			->from('share')
275
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
276
-			->andWhere(
277
-				$qb->expr()->in(
278
-					'share_type',
279
-					$qb->createNamedParameter([
280
-						\OCP\Share::SHARE_TYPE_USER,
281
-						\OCP\Share::SHARE_TYPE_GROUP,
282
-						\OCP\Share::SHARE_TYPE_LINK,
283
-					], IQueryBuilder::PARAM_INT_ARRAY)
284
-				)
285
-			)
286
-			->andWhere($qb->expr()->orX(
287
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
288
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
289
-			))
290
-			->orderBy('id');
291
-
292
-		$cursor = $qb->execute();
293
-		while($data = $cursor->fetch()) {
294
-			$children[] = $this->createShare($data);
295
-		}
296
-		$cursor->closeCursor();
297
-
298
-		return $children;
299
-	}
300
-
301
-	/**
302
-	 * Delete a share
303
-	 *
304
-	 * @param \OCP\Share\IShare $share
305
-	 */
306
-	public function delete(\OCP\Share\IShare $share) {
307
-		$qb = $this->dbConn->getQueryBuilder();
308
-		$qb->delete('share')
309
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
310
-
311
-		/*
237
+            $qb = $this->dbConn->getQueryBuilder();
238
+            $qb->update('share')
239
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
240
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
241
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
242
+                ->execute();
243
+
244
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
245
+            $qb = $this->dbConn->getQueryBuilder();
246
+            $qb->update('share')
247
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
248
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
249
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
250
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
251
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
252
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
253
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
254
+                ->set('token', $qb->createNamedParameter($share->getToken()))
255
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
256
+                ->execute();
257
+        }
258
+
259
+        return $share;
260
+    }
261
+
262
+    /**
263
+     * Get all children of this share
264
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
265
+     *
266
+     * @param \OCP\Share\IShare $parent
267
+     * @return \OCP\Share\IShare[]
268
+     */
269
+    public function getChildren(\OCP\Share\IShare $parent) {
270
+        $children = [];
271
+
272
+        $qb = $this->dbConn->getQueryBuilder();
273
+        $qb->select('*')
274
+            ->from('share')
275
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
276
+            ->andWhere(
277
+                $qb->expr()->in(
278
+                    'share_type',
279
+                    $qb->createNamedParameter([
280
+                        \OCP\Share::SHARE_TYPE_USER,
281
+                        \OCP\Share::SHARE_TYPE_GROUP,
282
+                        \OCP\Share::SHARE_TYPE_LINK,
283
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
284
+                )
285
+            )
286
+            ->andWhere($qb->expr()->orX(
287
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
288
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
289
+            ))
290
+            ->orderBy('id');
291
+
292
+        $cursor = $qb->execute();
293
+        while($data = $cursor->fetch()) {
294
+            $children[] = $this->createShare($data);
295
+        }
296
+        $cursor->closeCursor();
297
+
298
+        return $children;
299
+    }
300
+
301
+    /**
302
+     * Delete a share
303
+     *
304
+     * @param \OCP\Share\IShare $share
305
+     */
306
+    public function delete(\OCP\Share\IShare $share) {
307
+        $qb = $this->dbConn->getQueryBuilder();
308
+        $qb->delete('share')
309
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
310
+
311
+        /*
312 312
 		 * If the share is a group share delete all possible
313 313
 		 * user defined groups shares.
314 314
 		 */
315
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
316
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
317
-		}
318
-
319
-		$qb->execute();
320
-	}
321
-
322
-	/**
323
-	 * Unshare a share from the recipient. If this is a group share
324
-	 * this means we need a special entry in the share db.
325
-	 *
326
-	 * @param \OCP\Share\IShare $share
327
-	 * @param string $recipient UserId of recipient
328
-	 * @throws BackendError
329
-	 * @throws ProviderException
330
-	 */
331
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
332
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
333
-
334
-			$group = $this->groupManager->get($share->getSharedWith());
335
-			$user = $this->userManager->get($recipient);
336
-
337
-			if (is_null($group)) {
338
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
339
-			}
340
-
341
-			if (!$group->inGroup($user)) {
342
-				throw new ProviderException('Recipient not in receiving group');
343
-			}
344
-
345
-			// Try to fetch user specific share
346
-			$qb = $this->dbConn->getQueryBuilder();
347
-			$stmt = $qb->select('*')
348
-				->from('share')
349
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
350
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
351
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
352
-				->andWhere($qb->expr()->orX(
353
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
354
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
355
-				))
356
-				->execute();
357
-
358
-			$data = $stmt->fetch();
359
-
360
-			/*
315
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
316
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
317
+        }
318
+
319
+        $qb->execute();
320
+    }
321
+
322
+    /**
323
+     * Unshare a share from the recipient. If this is a group share
324
+     * this means we need a special entry in the share db.
325
+     *
326
+     * @param \OCP\Share\IShare $share
327
+     * @param string $recipient UserId of recipient
328
+     * @throws BackendError
329
+     * @throws ProviderException
330
+     */
331
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
332
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
333
+
334
+            $group = $this->groupManager->get($share->getSharedWith());
335
+            $user = $this->userManager->get($recipient);
336
+
337
+            if (is_null($group)) {
338
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
339
+            }
340
+
341
+            if (!$group->inGroup($user)) {
342
+                throw new ProviderException('Recipient not in receiving group');
343
+            }
344
+
345
+            // Try to fetch user specific share
346
+            $qb = $this->dbConn->getQueryBuilder();
347
+            $stmt = $qb->select('*')
348
+                ->from('share')
349
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
350
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
351
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
352
+                ->andWhere($qb->expr()->orX(
353
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
354
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
355
+                ))
356
+                ->execute();
357
+
358
+            $data = $stmt->fetch();
359
+
360
+            /*
361 361
 			 * Check if there already is a user specific group share.
362 362
 			 * If there is update it (if required).
363 363
 			 */
364
-			if ($data === false) {
365
-				$qb = $this->dbConn->getQueryBuilder();
366
-
367
-				$type = $share->getNodeType();
368
-
369
-				//Insert new share
370
-				$qb->insert('share')
371
-					->values([
372
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
373
-						'share_with' => $qb->createNamedParameter($recipient),
374
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
375
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
376
-						'parent' => $qb->createNamedParameter($share->getId()),
377
-						'item_type' => $qb->createNamedParameter($type),
378
-						'item_source' => $qb->createNamedParameter($share->getNodeId()),
379
-						'file_source' => $qb->createNamedParameter($share->getNodeId()),
380
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
381
-						'permissions' => $qb->createNamedParameter(0),
382
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
383
-					])->execute();
384
-
385
-			} else if ($data['permissions'] !== 0) {
386
-
387
-				// Update existing usergroup share
388
-				$qb = $this->dbConn->getQueryBuilder();
389
-				$qb->update('share')
390
-					->set('permissions', $qb->createNamedParameter(0))
391
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
392
-					->execute();
393
-			}
394
-
395
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
396
-
397
-			if ($share->getSharedWith() !== $recipient) {
398
-				throw new ProviderException('Recipient does not match');
399
-			}
400
-
401
-			// We can just delete user and link shares
402
-			$this->delete($share);
403
-		} else {
404
-			throw new ProviderException('Invalid shareType');
405
-		}
406
-	}
407
-
408
-	/**
409
-	 * @inheritdoc
410
-	 */
411
-	public function move(\OCP\Share\IShare $share, $recipient) {
412
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
413
-			// Just update the target
414
-			$qb = $this->dbConn->getQueryBuilder();
415
-			$qb->update('share')
416
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
417
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
418
-				->execute();
419
-
420
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
421
-
422
-			// Check if there is a usergroup share
423
-			$qb = $this->dbConn->getQueryBuilder();
424
-			$stmt = $qb->select('id')
425
-				->from('share')
426
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
427
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
428
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
429
-				->andWhere($qb->expr()->orX(
430
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
431
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
432
-				))
433
-				->setMaxResults(1)
434
-				->execute();
435
-
436
-			$data = $stmt->fetch();
437
-			$stmt->closeCursor();
438
-
439
-			if ($data === false) {
440
-				// No usergroup share yet. Create one.
441
-				$qb = $this->dbConn->getQueryBuilder();
442
-				$qb->insert('share')
443
-					->values([
444
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
445
-						'share_with' => $qb->createNamedParameter($recipient),
446
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
447
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
448
-						'parent' => $qb->createNamedParameter($share->getId()),
449
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
450
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
451
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
452
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
453
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
454
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
455
-					])->execute();
456
-			} else {
457
-				// Already a usergroup share. Update it.
458
-				$qb = $this->dbConn->getQueryBuilder();
459
-				$qb->update('share')
460
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
461
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
462
-					->execute();
463
-			}
464
-		}
465
-
466
-		return $share;
467
-	}
468
-
469
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
470
-		$qb = $this->dbConn->getQueryBuilder();
471
-		$qb->select('*')
472
-			->from('share', 's')
473
-			->andWhere($qb->expr()->orX(
474
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
475
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
476
-			));
477
-
478
-		$qb->andWhere($qb->expr()->orX(
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
480
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
481
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
482
-		));
483
-
484
-		/**
485
-		 * Reshares for this user are shares where they are the owner.
486
-		 */
487
-		if ($reshares === false) {
488
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
489
-		} else {
490
-			$qb->andWhere(
491
-				$qb->expr()->orX(
492
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
493
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
494
-				)
495
-			);
496
-		}
497
-
498
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
499
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
500
-
501
-		$qb->orderBy('id');
502
-
503
-		$cursor = $qb->execute();
504
-		$shares = [];
505
-		while ($data = $cursor->fetch()) {
506
-			$shares[$data['fileid']][] = $this->createShare($data);
507
-		}
508
-		$cursor->closeCursor();
509
-
510
-		return $shares;
511
-	}
512
-
513
-	/**
514
-	 * @inheritdoc
515
-	 */
516
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
517
-		$qb = $this->dbConn->getQueryBuilder();
518
-		$qb->select('*')
519
-			->from('share')
520
-			->andWhere($qb->expr()->orX(
521
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
522
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
523
-			));
524
-
525
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
526
-
527
-		/**
528
-		 * Reshares for this user are shares where they are the owner.
529
-		 */
530
-		if ($reshares === false) {
531
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
532
-		} else {
533
-			$qb->andWhere(
534
-				$qb->expr()->orX(
535
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
536
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
537
-				)
538
-			);
539
-		}
540
-
541
-		if ($node !== null) {
542
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
543
-		}
544
-
545
-		if ($limit !== -1) {
546
-			$qb->setMaxResults($limit);
547
-		}
548
-
549
-		$qb->setFirstResult($offset);
550
-		$qb->orderBy('id');
551
-
552
-		$cursor = $qb->execute();
553
-		$shares = [];
554
-		while($data = $cursor->fetch()) {
555
-			$shares[] = $this->createShare($data);
556
-		}
557
-		$cursor->closeCursor();
558
-
559
-		return $shares;
560
-	}
561
-
562
-	/**
563
-	 * @inheritdoc
564
-	 */
565
-	public function getShareById($id, $recipientId = null) {
566
-		$qb = $this->dbConn->getQueryBuilder();
567
-
568
-		$qb->select('*')
569
-			->from('share')
570
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
571
-			->andWhere(
572
-				$qb->expr()->in(
573
-					'share_type',
574
-					$qb->createNamedParameter([
575
-						\OCP\Share::SHARE_TYPE_USER,
576
-						\OCP\Share::SHARE_TYPE_GROUP,
577
-						\OCP\Share::SHARE_TYPE_LINK,
578
-					], IQueryBuilder::PARAM_INT_ARRAY)
579
-				)
580
-			)
581
-			->andWhere($qb->expr()->orX(
582
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
583
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
584
-			));
585
-
586
-		$cursor = $qb->execute();
587
-		$data = $cursor->fetch();
588
-		$cursor->closeCursor();
589
-
590
-		if ($data === false) {
591
-			throw new ShareNotFound();
592
-		}
593
-
594
-		try {
595
-			$share = $this->createShare($data);
596
-		} catch (InvalidShare $e) {
597
-			throw new ShareNotFound();
598
-		}
599
-
600
-		// If the recipient is set for a group share resolve to that user
601
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
602
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
603
-		}
604
-
605
-		return $share;
606
-	}
607
-
608
-	/**
609
-	 * Get shares for a given path
610
-	 *
611
-	 * @param \OCP\Files\Node $path
612
-	 * @return \OCP\Share\IShare[]
613
-	 */
614
-	public function getSharesByPath(Node $path) {
615
-		$qb = $this->dbConn->getQueryBuilder();
616
-
617
-		$cursor = $qb->select('*')
618
-			->from('share')
619
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
620
-			->andWhere(
621
-				$qb->expr()->orX(
622
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
623
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
624
-				)
625
-			)
626
-			->andWhere($qb->expr()->orX(
627
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
628
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
629
-			))
630
-			->execute();
631
-
632
-		$shares = [];
633
-		while($data = $cursor->fetch()) {
634
-			$shares[] = $this->createShare($data);
635
-		}
636
-		$cursor->closeCursor();
637
-
638
-		return $shares;
639
-	}
640
-
641
-	/**
642
-	 * Returns whether the given database result can be interpreted as
643
-	 * a share with accessible file (not trashed, not deleted)
644
-	 */
645
-	private function isAccessibleResult($data) {
646
-		// exclude shares leading to deleted file entries
647
-		if ($data['fileid'] === null) {
648
-			return false;
649
-		}
650
-
651
-		// exclude shares leading to trashbin on home storages
652
-		$pathSections = explode('/', $data['path'], 2);
653
-		// FIXME: would not detect rare md5'd home storage case properly
654
-		if ($pathSections[0] !== 'files'
655
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
656
-			return false;
657
-		}
658
-		return true;
659
-	}
660
-
661
-	/**
662
-	 * @inheritdoc
663
-	 */
664
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
665
-		/** @var Share[] $shares */
666
-		$shares = [];
667
-
668
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
669
-			//Get shares directly with this user
670
-			$qb = $this->dbConn->getQueryBuilder();
671
-			$qb->select('s.*',
672
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
673
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
674
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
675
-			)
676
-				->selectAlias('st.id', 'storage_string_id')
677
-				->from('share', 's')
678
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
679
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
680
-
681
-			// Order by id
682
-			$qb->orderBy('s.id');
683
-
684
-			// Set limit and offset
685
-			if ($limit !== -1) {
686
-				$qb->setMaxResults($limit);
687
-			}
688
-			$qb->setFirstResult($offset);
689
-
690
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
691
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
692
-				->andWhere($qb->expr()->orX(
693
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
694
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
695
-				));
696
-
697
-			// Filter by node if provided
698
-			if ($node !== null) {
699
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
700
-			}
701
-
702
-			$cursor = $qb->execute();
703
-
704
-			while($data = $cursor->fetch()) {
705
-				if ($this->isAccessibleResult($data)) {
706
-					$shares[] = $this->createShare($data);
707
-				}
708
-			}
709
-			$cursor->closeCursor();
710
-
711
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
712
-			$user = $this->userManager->get($userId);
713
-			$allGroups = $this->groupManager->getUserGroups($user);
714
-
715
-			/** @var Share[] $shares2 */
716
-			$shares2 = [];
717
-
718
-			$start = 0;
719
-			while(true) {
720
-				$groups = array_slice($allGroups, $start, 100);
721
-				$start += 100;
722
-
723
-				if ($groups === []) {
724
-					break;
725
-				}
726
-
727
-				$qb = $this->dbConn->getQueryBuilder();
728
-				$qb->select('s.*',
729
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
730
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
731
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
732
-				)
733
-					->selectAlias('st.id', 'storage_string_id')
734
-					->from('share', 's')
735
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
736
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
737
-					->orderBy('s.id')
738
-					->setFirstResult(0);
739
-
740
-				if ($limit !== -1) {
741
-					$qb->setMaxResults($limit - count($shares));
742
-				}
743
-
744
-				// Filter by node if provided
745
-				if ($node !== null) {
746
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
747
-				}
748
-
749
-
750
-				$groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
751
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
752
-
753
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
754
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
755
-						$groups,
756
-						IQueryBuilder::PARAM_STR_ARRAY
757
-					)))
758
-					->andWhere($qb->expr()->orX(
759
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
760
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
761
-					));
762
-
763
-				$cursor = $qb->execute();
764
-				while($data = $cursor->fetch()) {
765
-					if ($offset > 0) {
766
-						$offset--;
767
-						continue;
768
-					}
769
-
770
-					if ($this->isAccessibleResult($data)) {
771
-						$shares2[] = $this->createShare($data);
772
-					}
773
-				}
774
-				$cursor->closeCursor();
775
-			}
776
-
777
-			/*
364
+            if ($data === false) {
365
+                $qb = $this->dbConn->getQueryBuilder();
366
+
367
+                $type = $share->getNodeType();
368
+
369
+                //Insert new share
370
+                $qb->insert('share')
371
+                    ->values([
372
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
373
+                        'share_with' => $qb->createNamedParameter($recipient),
374
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
375
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
376
+                        'parent' => $qb->createNamedParameter($share->getId()),
377
+                        'item_type' => $qb->createNamedParameter($type),
378
+                        'item_source' => $qb->createNamedParameter($share->getNodeId()),
379
+                        'file_source' => $qb->createNamedParameter($share->getNodeId()),
380
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
381
+                        'permissions' => $qb->createNamedParameter(0),
382
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
383
+                    ])->execute();
384
+
385
+            } else if ($data['permissions'] !== 0) {
386
+
387
+                // Update existing usergroup share
388
+                $qb = $this->dbConn->getQueryBuilder();
389
+                $qb->update('share')
390
+                    ->set('permissions', $qb->createNamedParameter(0))
391
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
392
+                    ->execute();
393
+            }
394
+
395
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
396
+
397
+            if ($share->getSharedWith() !== $recipient) {
398
+                throw new ProviderException('Recipient does not match');
399
+            }
400
+
401
+            // We can just delete user and link shares
402
+            $this->delete($share);
403
+        } else {
404
+            throw new ProviderException('Invalid shareType');
405
+        }
406
+    }
407
+
408
+    /**
409
+     * @inheritdoc
410
+     */
411
+    public function move(\OCP\Share\IShare $share, $recipient) {
412
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
413
+            // Just update the target
414
+            $qb = $this->dbConn->getQueryBuilder();
415
+            $qb->update('share')
416
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
417
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
418
+                ->execute();
419
+
420
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
421
+
422
+            // Check if there is a usergroup share
423
+            $qb = $this->dbConn->getQueryBuilder();
424
+            $stmt = $qb->select('id')
425
+                ->from('share')
426
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
427
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
428
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
429
+                ->andWhere($qb->expr()->orX(
430
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
431
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
432
+                ))
433
+                ->setMaxResults(1)
434
+                ->execute();
435
+
436
+            $data = $stmt->fetch();
437
+            $stmt->closeCursor();
438
+
439
+            if ($data === false) {
440
+                // No usergroup share yet. Create one.
441
+                $qb = $this->dbConn->getQueryBuilder();
442
+                $qb->insert('share')
443
+                    ->values([
444
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
445
+                        'share_with' => $qb->createNamedParameter($recipient),
446
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
447
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
448
+                        'parent' => $qb->createNamedParameter($share->getId()),
449
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
450
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
451
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
452
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
453
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
454
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
455
+                    ])->execute();
456
+            } else {
457
+                // Already a usergroup share. Update it.
458
+                $qb = $this->dbConn->getQueryBuilder();
459
+                $qb->update('share')
460
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
461
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
462
+                    ->execute();
463
+            }
464
+        }
465
+
466
+        return $share;
467
+    }
468
+
469
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
470
+        $qb = $this->dbConn->getQueryBuilder();
471
+        $qb->select('*')
472
+            ->from('share', 's')
473
+            ->andWhere($qb->expr()->orX(
474
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
475
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
476
+            ));
477
+
478
+        $qb->andWhere($qb->expr()->orX(
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
480
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
481
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
482
+        ));
483
+
484
+        /**
485
+         * Reshares for this user are shares where they are the owner.
486
+         */
487
+        if ($reshares === false) {
488
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
489
+        } else {
490
+            $qb->andWhere(
491
+                $qb->expr()->orX(
492
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
493
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
494
+                )
495
+            );
496
+        }
497
+
498
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
499
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
500
+
501
+        $qb->orderBy('id');
502
+
503
+        $cursor = $qb->execute();
504
+        $shares = [];
505
+        while ($data = $cursor->fetch()) {
506
+            $shares[$data['fileid']][] = $this->createShare($data);
507
+        }
508
+        $cursor->closeCursor();
509
+
510
+        return $shares;
511
+    }
512
+
513
+    /**
514
+     * @inheritdoc
515
+     */
516
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
517
+        $qb = $this->dbConn->getQueryBuilder();
518
+        $qb->select('*')
519
+            ->from('share')
520
+            ->andWhere($qb->expr()->orX(
521
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
522
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
523
+            ));
524
+
525
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
526
+
527
+        /**
528
+         * Reshares for this user are shares where they are the owner.
529
+         */
530
+        if ($reshares === false) {
531
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
532
+        } else {
533
+            $qb->andWhere(
534
+                $qb->expr()->orX(
535
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
536
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
537
+                )
538
+            );
539
+        }
540
+
541
+        if ($node !== null) {
542
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
543
+        }
544
+
545
+        if ($limit !== -1) {
546
+            $qb->setMaxResults($limit);
547
+        }
548
+
549
+        $qb->setFirstResult($offset);
550
+        $qb->orderBy('id');
551
+
552
+        $cursor = $qb->execute();
553
+        $shares = [];
554
+        while($data = $cursor->fetch()) {
555
+            $shares[] = $this->createShare($data);
556
+        }
557
+        $cursor->closeCursor();
558
+
559
+        return $shares;
560
+    }
561
+
562
+    /**
563
+     * @inheritdoc
564
+     */
565
+    public function getShareById($id, $recipientId = null) {
566
+        $qb = $this->dbConn->getQueryBuilder();
567
+
568
+        $qb->select('*')
569
+            ->from('share')
570
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
571
+            ->andWhere(
572
+                $qb->expr()->in(
573
+                    'share_type',
574
+                    $qb->createNamedParameter([
575
+                        \OCP\Share::SHARE_TYPE_USER,
576
+                        \OCP\Share::SHARE_TYPE_GROUP,
577
+                        \OCP\Share::SHARE_TYPE_LINK,
578
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
579
+                )
580
+            )
581
+            ->andWhere($qb->expr()->orX(
582
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
583
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
584
+            ));
585
+
586
+        $cursor = $qb->execute();
587
+        $data = $cursor->fetch();
588
+        $cursor->closeCursor();
589
+
590
+        if ($data === false) {
591
+            throw new ShareNotFound();
592
+        }
593
+
594
+        try {
595
+            $share = $this->createShare($data);
596
+        } catch (InvalidShare $e) {
597
+            throw new ShareNotFound();
598
+        }
599
+
600
+        // If the recipient is set for a group share resolve to that user
601
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
602
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
603
+        }
604
+
605
+        return $share;
606
+    }
607
+
608
+    /**
609
+     * Get shares for a given path
610
+     *
611
+     * @param \OCP\Files\Node $path
612
+     * @return \OCP\Share\IShare[]
613
+     */
614
+    public function getSharesByPath(Node $path) {
615
+        $qb = $this->dbConn->getQueryBuilder();
616
+
617
+        $cursor = $qb->select('*')
618
+            ->from('share')
619
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
620
+            ->andWhere(
621
+                $qb->expr()->orX(
622
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
623
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
624
+                )
625
+            )
626
+            ->andWhere($qb->expr()->orX(
627
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
628
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
629
+            ))
630
+            ->execute();
631
+
632
+        $shares = [];
633
+        while($data = $cursor->fetch()) {
634
+            $shares[] = $this->createShare($data);
635
+        }
636
+        $cursor->closeCursor();
637
+
638
+        return $shares;
639
+    }
640
+
641
+    /**
642
+     * Returns whether the given database result can be interpreted as
643
+     * a share with accessible file (not trashed, not deleted)
644
+     */
645
+    private function isAccessibleResult($data) {
646
+        // exclude shares leading to deleted file entries
647
+        if ($data['fileid'] === null) {
648
+            return false;
649
+        }
650
+
651
+        // exclude shares leading to trashbin on home storages
652
+        $pathSections = explode('/', $data['path'], 2);
653
+        // FIXME: would not detect rare md5'd home storage case properly
654
+        if ($pathSections[0] !== 'files'
655
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
656
+            return false;
657
+        }
658
+        return true;
659
+    }
660
+
661
+    /**
662
+     * @inheritdoc
663
+     */
664
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
665
+        /** @var Share[] $shares */
666
+        $shares = [];
667
+
668
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
669
+            //Get shares directly with this user
670
+            $qb = $this->dbConn->getQueryBuilder();
671
+            $qb->select('s.*',
672
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
673
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
674
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
675
+            )
676
+                ->selectAlias('st.id', 'storage_string_id')
677
+                ->from('share', 's')
678
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
679
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
680
+
681
+            // Order by id
682
+            $qb->orderBy('s.id');
683
+
684
+            // Set limit and offset
685
+            if ($limit !== -1) {
686
+                $qb->setMaxResults($limit);
687
+            }
688
+            $qb->setFirstResult($offset);
689
+
690
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
691
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
692
+                ->andWhere($qb->expr()->orX(
693
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
694
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
695
+                ));
696
+
697
+            // Filter by node if provided
698
+            if ($node !== null) {
699
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
700
+            }
701
+
702
+            $cursor = $qb->execute();
703
+
704
+            while($data = $cursor->fetch()) {
705
+                if ($this->isAccessibleResult($data)) {
706
+                    $shares[] = $this->createShare($data);
707
+                }
708
+            }
709
+            $cursor->closeCursor();
710
+
711
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
712
+            $user = $this->userManager->get($userId);
713
+            $allGroups = $this->groupManager->getUserGroups($user);
714
+
715
+            /** @var Share[] $shares2 */
716
+            $shares2 = [];
717
+
718
+            $start = 0;
719
+            while(true) {
720
+                $groups = array_slice($allGroups, $start, 100);
721
+                $start += 100;
722
+
723
+                if ($groups === []) {
724
+                    break;
725
+                }
726
+
727
+                $qb = $this->dbConn->getQueryBuilder();
728
+                $qb->select('s.*',
729
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
730
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
731
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
732
+                )
733
+                    ->selectAlias('st.id', 'storage_string_id')
734
+                    ->from('share', 's')
735
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
736
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
737
+                    ->orderBy('s.id')
738
+                    ->setFirstResult(0);
739
+
740
+                if ($limit !== -1) {
741
+                    $qb->setMaxResults($limit - count($shares));
742
+                }
743
+
744
+                // Filter by node if provided
745
+                if ($node !== null) {
746
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
747
+                }
748
+
749
+
750
+                $groups = array_filter($groups, function($group) { return $group instanceof IGroup; });
751
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
752
+
753
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
754
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
755
+                        $groups,
756
+                        IQueryBuilder::PARAM_STR_ARRAY
757
+                    )))
758
+                    ->andWhere($qb->expr()->orX(
759
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
760
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
761
+                    ));
762
+
763
+                $cursor = $qb->execute();
764
+                while($data = $cursor->fetch()) {
765
+                    if ($offset > 0) {
766
+                        $offset--;
767
+                        continue;
768
+                    }
769
+
770
+                    if ($this->isAccessibleResult($data)) {
771
+                        $shares2[] = $this->createShare($data);
772
+                    }
773
+                }
774
+                $cursor->closeCursor();
775
+            }
776
+
777
+            /*
778 778
  			 * Resolve all group shares to user specific shares
779 779
  			 */
780
-			$shares = $this->resolveGroupShares($shares2, $userId);
781
-		} else {
782
-			throw new BackendError('Invalid backend');
783
-		}
784
-
785
-
786
-		return $shares;
787
-	}
788
-
789
-	/**
790
-	 * Get a share by token
791
-	 *
792
-	 * @param string $token
793
-	 * @return \OCP\Share\IShare
794
-	 * @throws ShareNotFound
795
-	 */
796
-	public function getShareByToken($token) {
797
-		$qb = $this->dbConn->getQueryBuilder();
798
-
799
-		$cursor = $qb->select('*')
800
-			->from('share')
801
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
802
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
803
-			->andWhere($qb->expr()->orX(
804
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
805
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
806
-			))
807
-			->execute();
808
-
809
-		$data = $cursor->fetch();
810
-
811
-		if ($data === false) {
812
-			throw new ShareNotFound();
813
-		}
814
-
815
-		try {
816
-			$share = $this->createShare($data);
817
-		} catch (InvalidShare $e) {
818
-			throw new ShareNotFound();
819
-		}
820
-
821
-		return $share;
822
-	}
823
-
824
-	/**
825
-	 * Create a share object from an database row
826
-	 *
827
-	 * @param mixed[] $data
828
-	 * @return \OCP\Share\IShare
829
-	 * @throws InvalidShare
830
-	 */
831
-	private function createShare($data) {
832
-		$share = new Share($this->rootFolder, $this->userManager);
833
-		$share->setId((int)$data['id'])
834
-			->setShareType((int)$data['share_type'])
835
-			->setPermissions((int)$data['permissions'])
836
-			->setTarget($data['file_target'])
837
-			->setMailSend((bool)$data['mail_send']);
838
-
839
-		$shareTime = new \DateTime();
840
-		$shareTime->setTimestamp((int)$data['stime']);
841
-		$share->setShareTime($shareTime);
842
-
843
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
844
-			$share->setSharedWith($data['share_with']);
845
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
846
-			$share->setSharedWith($data['share_with']);
847
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
848
-			$share->setPassword($data['password']);
849
-			$share->setToken($data['token']);
850
-		}
851
-
852
-		$share->setSharedBy($data['uid_initiator']);
853
-		$share->setShareOwner($data['uid_owner']);
854
-
855
-		$share->setNodeId((int)$data['file_source']);
856
-		$share->setNodeType($data['item_type']);
857
-
858
-		if ($data['expiration'] !== null) {
859
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
860
-			$share->setExpirationDate($expiration);
861
-		}
862
-
863
-		if (isset($data['f_permissions'])) {
864
-			$entryData = $data;
865
-			$entryData['permissions'] = $entryData['f_permissions'];
866
-			$entryData['parent'] = $entryData['f_parent'];
867
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
868
-				\OC::$server->getMimeTypeLoader()));
869
-		}
870
-
871
-		$share->setProviderId($this->identifier());
872
-
873
-		return $share;
874
-	}
875
-
876
-	/**
877
-	 * @param Share[] $shares
878
-	 * @param $userId
879
-	 * @return Share[] The updates shares if no update is found for a share return the original
880
-	 */
881
-	private function resolveGroupShares($shares, $userId) {
882
-		$result = [];
883
-
884
-		$start = 0;
885
-		while(true) {
886
-			/** @var Share[] $shareSlice */
887
-			$shareSlice = array_slice($shares, $start, 100);
888
-			$start += 100;
889
-
890
-			if ($shareSlice === []) {
891
-				break;
892
-			}
893
-
894
-			/** @var int[] $ids */
895
-			$ids = [];
896
-			/** @var Share[] $shareMap */
897
-			$shareMap = [];
898
-
899
-			foreach ($shareSlice as $share) {
900
-				$ids[] = (int)$share->getId();
901
-				$shareMap[$share->getId()] = $share;
902
-			}
903
-
904
-			$qb = $this->dbConn->getQueryBuilder();
905
-
906
-			$query = $qb->select('*')
907
-				->from('share')
908
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
909
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
910
-				->andWhere($qb->expr()->orX(
911
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
912
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
913
-				));
914
-
915
-			$stmt = $query->execute();
916
-
917
-			while($data = $stmt->fetch()) {
918
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
919
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
920
-			}
921
-
922
-			$stmt->closeCursor();
923
-
924
-			foreach ($shareMap as $share) {
925
-				$result[] = $share;
926
-			}
927
-		}
928
-
929
-		return $result;
930
-	}
931
-
932
-	/**
933
-	 * A user is deleted from the system
934
-	 * So clean up the relevant shares.
935
-	 *
936
-	 * @param string $uid
937
-	 * @param int $shareType
938
-	 */
939
-	public function userDeleted($uid, $shareType) {
940
-		$qb = $this->dbConn->getQueryBuilder();
941
-
942
-		$qb->delete('share');
943
-
944
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
945
-			/*
780
+            $shares = $this->resolveGroupShares($shares2, $userId);
781
+        } else {
782
+            throw new BackendError('Invalid backend');
783
+        }
784
+
785
+
786
+        return $shares;
787
+    }
788
+
789
+    /**
790
+     * Get a share by token
791
+     *
792
+     * @param string $token
793
+     * @return \OCP\Share\IShare
794
+     * @throws ShareNotFound
795
+     */
796
+    public function getShareByToken($token) {
797
+        $qb = $this->dbConn->getQueryBuilder();
798
+
799
+        $cursor = $qb->select('*')
800
+            ->from('share')
801
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
802
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
803
+            ->andWhere($qb->expr()->orX(
804
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
805
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
806
+            ))
807
+            ->execute();
808
+
809
+        $data = $cursor->fetch();
810
+
811
+        if ($data === false) {
812
+            throw new ShareNotFound();
813
+        }
814
+
815
+        try {
816
+            $share = $this->createShare($data);
817
+        } catch (InvalidShare $e) {
818
+            throw new ShareNotFound();
819
+        }
820
+
821
+        return $share;
822
+    }
823
+
824
+    /**
825
+     * Create a share object from an database row
826
+     *
827
+     * @param mixed[] $data
828
+     * @return \OCP\Share\IShare
829
+     * @throws InvalidShare
830
+     */
831
+    private function createShare($data) {
832
+        $share = new Share($this->rootFolder, $this->userManager);
833
+        $share->setId((int)$data['id'])
834
+            ->setShareType((int)$data['share_type'])
835
+            ->setPermissions((int)$data['permissions'])
836
+            ->setTarget($data['file_target'])
837
+            ->setMailSend((bool)$data['mail_send']);
838
+
839
+        $shareTime = new \DateTime();
840
+        $shareTime->setTimestamp((int)$data['stime']);
841
+        $share->setShareTime($shareTime);
842
+
843
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
844
+            $share->setSharedWith($data['share_with']);
845
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
846
+            $share->setSharedWith($data['share_with']);
847
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
848
+            $share->setPassword($data['password']);
849
+            $share->setToken($data['token']);
850
+        }
851
+
852
+        $share->setSharedBy($data['uid_initiator']);
853
+        $share->setShareOwner($data['uid_owner']);
854
+
855
+        $share->setNodeId((int)$data['file_source']);
856
+        $share->setNodeType($data['item_type']);
857
+
858
+        if ($data['expiration'] !== null) {
859
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
860
+            $share->setExpirationDate($expiration);
861
+        }
862
+
863
+        if (isset($data['f_permissions'])) {
864
+            $entryData = $data;
865
+            $entryData['permissions'] = $entryData['f_permissions'];
866
+            $entryData['parent'] = $entryData['f_parent'];
867
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
868
+                \OC::$server->getMimeTypeLoader()));
869
+        }
870
+
871
+        $share->setProviderId($this->identifier());
872
+
873
+        return $share;
874
+    }
875
+
876
+    /**
877
+     * @param Share[] $shares
878
+     * @param $userId
879
+     * @return Share[] The updates shares if no update is found for a share return the original
880
+     */
881
+    private function resolveGroupShares($shares, $userId) {
882
+        $result = [];
883
+
884
+        $start = 0;
885
+        while(true) {
886
+            /** @var Share[] $shareSlice */
887
+            $shareSlice = array_slice($shares, $start, 100);
888
+            $start += 100;
889
+
890
+            if ($shareSlice === []) {
891
+                break;
892
+            }
893
+
894
+            /** @var int[] $ids */
895
+            $ids = [];
896
+            /** @var Share[] $shareMap */
897
+            $shareMap = [];
898
+
899
+            foreach ($shareSlice as $share) {
900
+                $ids[] = (int)$share->getId();
901
+                $shareMap[$share->getId()] = $share;
902
+            }
903
+
904
+            $qb = $this->dbConn->getQueryBuilder();
905
+
906
+            $query = $qb->select('*')
907
+                ->from('share')
908
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
909
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
910
+                ->andWhere($qb->expr()->orX(
911
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
912
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
913
+                ));
914
+
915
+            $stmt = $query->execute();
916
+
917
+            while($data = $stmt->fetch()) {
918
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
919
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
920
+            }
921
+
922
+            $stmt->closeCursor();
923
+
924
+            foreach ($shareMap as $share) {
925
+                $result[] = $share;
926
+            }
927
+        }
928
+
929
+        return $result;
930
+    }
931
+
932
+    /**
933
+     * A user is deleted from the system
934
+     * So clean up the relevant shares.
935
+     *
936
+     * @param string $uid
937
+     * @param int $shareType
938
+     */
939
+    public function userDeleted($uid, $shareType) {
940
+        $qb = $this->dbConn->getQueryBuilder();
941
+
942
+        $qb->delete('share');
943
+
944
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
945
+            /*
946 946
 			 * Delete all user shares that are owned by this user
947 947
 			 * or that are received by this user
948 948
 			 */
949 949
 
950
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
950
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
951 951
 
952
-			$qb->andWhere(
953
-				$qb->expr()->orX(
954
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
955
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
956
-				)
957
-			);
958
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
959
-			/*
952
+            $qb->andWhere(
953
+                $qb->expr()->orX(
954
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
955
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
956
+                )
957
+            );
958
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
959
+            /*
960 960
 			 * Delete all group shares that are owned by this user
961 961
 			 * Or special user group shares that are received by this user
962 962
 			 */
963
-			$qb->where(
964
-				$qb->expr()->andX(
965
-					$qb->expr()->orX(
966
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
967
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
968
-					),
969
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
970
-				)
971
-			);
972
-
973
-			$qb->orWhere(
974
-				$qb->expr()->andX(
975
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
976
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
977
-				)
978
-			);
979
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
980
-			/*
963
+            $qb->where(
964
+                $qb->expr()->andX(
965
+                    $qb->expr()->orX(
966
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
967
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
968
+                    ),
969
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
970
+                )
971
+            );
972
+
973
+            $qb->orWhere(
974
+                $qb->expr()->andX(
975
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
976
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
977
+                )
978
+            );
979
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
980
+            /*
981 981
 			 * Delete all link shares owned by this user.
982 982
 			 * And all link shares initiated by this user (until #22327 is in)
983 983
 			 */
984
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
985
-
986
-			$qb->andWhere(
987
-				$qb->expr()->orX(
988
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
989
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
990
-				)
991
-			);
992
-		}
993
-
994
-		$qb->execute();
995
-	}
996
-
997
-	/**
998
-	 * Delete all shares received by this group. As well as any custom group
999
-	 * shares for group members.
1000
-	 *
1001
-	 * @param string $gid
1002
-	 */
1003
-	public function groupDeleted($gid) {
1004
-		/*
984
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
985
+
986
+            $qb->andWhere(
987
+                $qb->expr()->orX(
988
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
989
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
990
+                )
991
+            );
992
+        }
993
+
994
+        $qb->execute();
995
+    }
996
+
997
+    /**
998
+     * Delete all shares received by this group. As well as any custom group
999
+     * shares for group members.
1000
+     *
1001
+     * @param string $gid
1002
+     */
1003
+    public function groupDeleted($gid) {
1004
+        /*
1005 1005
 		 * First delete all custom group shares for group members
1006 1006
 		 */
1007
-		$qb = $this->dbConn->getQueryBuilder();
1008
-		$qb->select('id')
1009
-			->from('share')
1010
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1011
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1012
-
1013
-		$cursor = $qb->execute();
1014
-		$ids = [];
1015
-		while($row = $cursor->fetch()) {
1016
-			$ids[] = (int)$row['id'];
1017
-		}
1018
-		$cursor->closeCursor();
1019
-
1020
-		if (!empty($ids)) {
1021
-			$chunks = array_chunk($ids, 100);
1022
-			foreach ($chunks as $chunk) {
1023
-				$qb->delete('share')
1024
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1025
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1026
-				$qb->execute();
1027
-			}
1028
-		}
1029
-
1030
-		/*
1007
+        $qb = $this->dbConn->getQueryBuilder();
1008
+        $qb->select('id')
1009
+            ->from('share')
1010
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1011
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1012
+
1013
+        $cursor = $qb->execute();
1014
+        $ids = [];
1015
+        while($row = $cursor->fetch()) {
1016
+            $ids[] = (int)$row['id'];
1017
+        }
1018
+        $cursor->closeCursor();
1019
+
1020
+        if (!empty($ids)) {
1021
+            $chunks = array_chunk($ids, 100);
1022
+            foreach ($chunks as $chunk) {
1023
+                $qb->delete('share')
1024
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1025
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1026
+                $qb->execute();
1027
+            }
1028
+        }
1029
+
1030
+        /*
1031 1031
 		 * Now delete all the group shares
1032 1032
 		 */
1033
-		$qb = $this->dbConn->getQueryBuilder();
1034
-		$qb->delete('share')
1035
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1036
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1037
-		$qb->execute();
1038
-	}
1039
-
1040
-	/**
1041
-	 * Delete custom group shares to this group for this user
1042
-	 *
1043
-	 * @param string $uid
1044
-	 * @param string $gid
1045
-	 */
1046
-	public function userDeletedFromGroup($uid, $gid) {
1047
-		/*
1033
+        $qb = $this->dbConn->getQueryBuilder();
1034
+        $qb->delete('share')
1035
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1036
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1037
+        $qb->execute();
1038
+    }
1039
+
1040
+    /**
1041
+     * Delete custom group shares to this group for this user
1042
+     *
1043
+     * @param string $uid
1044
+     * @param string $gid
1045
+     */
1046
+    public function userDeletedFromGroup($uid, $gid) {
1047
+        /*
1048 1048
 		 * Get all group shares
1049 1049
 		 */
1050
-		$qb = $this->dbConn->getQueryBuilder();
1051
-		$qb->select('id')
1052
-			->from('share')
1053
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1054
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1055
-
1056
-		$cursor = $qb->execute();
1057
-		$ids = [];
1058
-		while($row = $cursor->fetch()) {
1059
-			$ids[] = (int)$row['id'];
1060
-		}
1061
-		$cursor->closeCursor();
1062
-
1063
-		if (!empty($ids)) {
1064
-			$chunks = array_chunk($ids, 100);
1065
-			foreach ($chunks as $chunk) {
1066
-				/*
1050
+        $qb = $this->dbConn->getQueryBuilder();
1051
+        $qb->select('id')
1052
+            ->from('share')
1053
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1054
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1055
+
1056
+        $cursor = $qb->execute();
1057
+        $ids = [];
1058
+        while($row = $cursor->fetch()) {
1059
+            $ids[] = (int)$row['id'];
1060
+        }
1061
+        $cursor->closeCursor();
1062
+
1063
+        if (!empty($ids)) {
1064
+            $chunks = array_chunk($ids, 100);
1065
+            foreach ($chunks as $chunk) {
1066
+                /*
1067 1067
 				 * Delete all special shares wit this users for the found group shares
1068 1068
 				 */
1069
-				$qb->delete('share')
1070
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1071
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1072
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1073
-				$qb->execute();
1074
-			}
1075
-		}
1076
-	}
1077
-
1078
-	/**
1079
-	 * @inheritdoc
1080
-	 */
1081
-	public function getAccessList($nodes, $currentAccess) {
1082
-		$ids = [];
1083
-		foreach ($nodes as $node) {
1084
-			$ids[] = $node->getId();
1085
-		}
1086
-
1087
-		$qb = $this->dbConn->getQueryBuilder();
1088
-
1089
-		$or = $qb->expr()->orX(
1090
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1091
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1092
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1093
-		);
1094
-
1095
-		if ($currentAccess) {
1096
-			$or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1097
-		}
1098
-
1099
-		$qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1100
-			->from('share')
1101
-			->where(
1102
-				$or
1103
-			)
1104
-			->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1105
-			->andWhere($qb->expr()->orX(
1106
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
-			));
1109
-		$cursor = $qb->execute();
1110
-
1111
-		$users = [];
1112
-		$link = false;
1113
-		while($row = $cursor->fetch()) {
1114
-			$type = (int)$row['share_type'];
1115
-			if ($type === \OCP\Share::SHARE_TYPE_USER) {
1116
-				$uid = $row['share_with'];
1117
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1118
-				$users[$uid][$row['id']] = $row;
1119
-			} else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1120
-				$gid = $row['share_with'];
1121
-				$group = $this->groupManager->get($gid);
1122
-
1123
-				if ($group === null) {
1124
-					continue;
1125
-				}
1126
-
1127
-				$userList = $group->getUsers();
1128
-				foreach ($userList as $user) {
1129
-					$uid = $user->getUID();
1130
-					$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1131
-					$users[$uid][$row['id']] = $row;
1132
-				}
1133
-			} else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1134
-				$link = true;
1135
-			} else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1136
-				$uid = $row['share_with'];
1137
-				$users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1138
-				$users[$uid][$row['id']] = $row;
1139
-			}
1140
-		}
1141
-		$cursor->closeCursor();
1142
-
1143
-		if ($currentAccess === true) {
1144
-			$users = array_map([$this, 'filterSharesOfUser'], $users);
1145
-			$users = array_filter($users);
1146
-		} else {
1147
-			$users = array_keys($users);
1148
-		}
1149
-
1150
-		return ['users' => $users, 'public' => $link];
1151
-	}
1152
-
1153
-	/**
1154
-	 * For each user the path with the fewest slashes is returned
1155
-	 * @param array $shares
1156
-	 * @return array
1157
-	 */
1158
-	protected function filterSharesOfUser(array $shares) {
1159
-		// Group shares when the user has a share exception
1160
-		foreach ($shares as $id => $share) {
1161
-			$type = (int) $share['share_type'];
1162
-			$permissions = (int) $share['permissions'];
1163
-
1164
-			if ($type === self::SHARE_TYPE_USERGROUP) {
1165
-				unset($shares[$share['parent']]);
1166
-
1167
-				if ($permissions === 0) {
1168
-					unset($shares[$id]);
1169
-				}
1170
-			}
1171
-		}
1172
-
1173
-		$best = [];
1174
-		$bestDepth = 0;
1175
-		foreach ($shares as $id => $share) {
1176
-			$depth = substr_count($share['file_target'], '/');
1177
-			if (empty($best) || $depth < $bestDepth) {
1178
-				$bestDepth = $depth;
1179
-				$best = [
1180
-					'node_id' => $share['file_source'],
1181
-					'node_path' => $share['file_target'],
1182
-				];
1183
-			}
1184
-		}
1185
-
1186
-		return $best;
1187
-	}
1069
+                $qb->delete('share')
1070
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1071
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1072
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1073
+                $qb->execute();
1074
+            }
1075
+        }
1076
+    }
1077
+
1078
+    /**
1079
+     * @inheritdoc
1080
+     */
1081
+    public function getAccessList($nodes, $currentAccess) {
1082
+        $ids = [];
1083
+        foreach ($nodes as $node) {
1084
+            $ids[] = $node->getId();
1085
+        }
1086
+
1087
+        $qb = $this->dbConn->getQueryBuilder();
1088
+
1089
+        $or = $qb->expr()->orX(
1090
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
1091
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
1092
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
1093
+        );
1094
+
1095
+        if ($currentAccess) {
1096
+            $or->add($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)));
1097
+        }
1098
+
1099
+        $qb->select('id', 'parent', 'share_type', 'share_with', 'file_source', 'file_target', 'permissions')
1100
+            ->from('share')
1101
+            ->where(
1102
+                $or
1103
+            )
1104
+            ->andWhere($qb->expr()->in('file_source', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
1105
+            ->andWhere($qb->expr()->orX(
1106
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
1107
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
1108
+            ));
1109
+        $cursor = $qb->execute();
1110
+
1111
+        $users = [];
1112
+        $link = false;
1113
+        while($row = $cursor->fetch()) {
1114
+            $type = (int)$row['share_type'];
1115
+            if ($type === \OCP\Share::SHARE_TYPE_USER) {
1116
+                $uid = $row['share_with'];
1117
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1118
+                $users[$uid][$row['id']] = $row;
1119
+            } else if ($type === \OCP\Share::SHARE_TYPE_GROUP) {
1120
+                $gid = $row['share_with'];
1121
+                $group = $this->groupManager->get($gid);
1122
+
1123
+                if ($group === null) {
1124
+                    continue;
1125
+                }
1126
+
1127
+                $userList = $group->getUsers();
1128
+                foreach ($userList as $user) {
1129
+                    $uid = $user->getUID();
1130
+                    $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1131
+                    $users[$uid][$row['id']] = $row;
1132
+                }
1133
+            } else if ($type === \OCP\Share::SHARE_TYPE_LINK) {
1134
+                $link = true;
1135
+            } else if ($type === self::SHARE_TYPE_USERGROUP && $currentAccess === true) {
1136
+                $uid = $row['share_with'];
1137
+                $users[$uid] = isset($users[$uid]) ? $users[$uid] : [];
1138
+                $users[$uid][$row['id']] = $row;
1139
+            }
1140
+        }
1141
+        $cursor->closeCursor();
1142
+
1143
+        if ($currentAccess === true) {
1144
+            $users = array_map([$this, 'filterSharesOfUser'], $users);
1145
+            $users = array_filter($users);
1146
+        } else {
1147
+            $users = array_keys($users);
1148
+        }
1149
+
1150
+        return ['users' => $users, 'public' => $link];
1151
+    }
1152
+
1153
+    /**
1154
+     * For each user the path with the fewest slashes is returned
1155
+     * @param array $shares
1156
+     * @return array
1157
+     */
1158
+    protected function filterSharesOfUser(array $shares) {
1159
+        // Group shares when the user has a share exception
1160
+        foreach ($shares as $id => $share) {
1161
+            $type = (int) $share['share_type'];
1162
+            $permissions = (int) $share['permissions'];
1163
+
1164
+            if ($type === self::SHARE_TYPE_USERGROUP) {
1165
+                unset($shares[$share['parent']]);
1166
+
1167
+                if ($permissions === 0) {
1168
+                    unset($shares[$id]);
1169
+                }
1170
+            }
1171
+        }
1172
+
1173
+        $best = [];
1174
+        $bestDepth = 0;
1175
+        foreach ($shares as $id => $share) {
1176
+            $depth = substr_count($share['file_target'], '/');
1177
+            if (empty($best) || $depth < $bestDepth) {
1178
+                $bestDepth = $depth;
1179
+                $best = [
1180
+                    'node_id' => $share['file_source'],
1181
+                    'node_path' => $share['file_target'],
1182
+                ];
1183
+            }
1184
+        }
1185
+
1186
+        return $best;
1187
+    }
1188 1188
 }
Please login to merge, or discard this patch.
lib/private/Share20/Manager.php 2 patches
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
 
346 346
 		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
347 347
 			$expirationDate = new \DateTime();
348
-			$expirationDate->setTime(0,0,0);
348
+			$expirationDate->setTime(0, 0, 0);
349 349
 			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
350 350
 		}
351 351
 
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 
358 358
 			$date = new \DateTime();
359 359
 			$date->setTime(0, 0, 0);
360
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
360
+			$date->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
361 361
 			if ($date < $expirationDate) {
362 362
 				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
363 363
 				throw new GenericShareException($message, $message, 404);
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		 */
411 411
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
412 412
 		$existingShares = $provider->getSharesByPath($share->getNode());
413
-		foreach($existingShares as $existingShare) {
413
+		foreach ($existingShares as $existingShare) {
414 414
 			// Ignore if it is the same share
415 415
 			try {
416 416
 				if ($existingShare->getFullId() === $share->getFullId()) {
@@ -467,7 +467,7 @@  discard block
 block discarded – undo
467 467
 		 */
468 468
 		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
469 469
 		$existingShares = $provider->getSharesByPath($share->getNode());
470
-		foreach($existingShares as $existingShare) {
470
+		foreach ($existingShares as $existingShare) {
471 471
 			try {
472 472
 				if ($existingShare->getFullId() === $share->getFullId()) {
473 473
 					continue;
@@ -536,7 +536,7 @@  discard block
 block discarded – undo
536 536
 		// Make sure that we do not share a path that contains a shared mountpoint
537 537
 		if ($path instanceof \OCP\Files\Folder) {
538 538
 			$mounts = $this->mountManager->findIn($path->getPath());
539
-			foreach($mounts as $mount) {
539
+			foreach ($mounts as $mount) {
540 540
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
541 541
 					throw new \InvalidArgumentException('Path contains files shared with you');
542 542
 				}
@@ -584,7 +584,7 @@  discard block
 block discarded – undo
584 584
 		$storage = $share->getNode()->getStorage();
585 585
 		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
586 586
 			$parent = $share->getNode()->getParent();
587
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
587
+			while ($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
588 588
 				$parent = $parent->getParent();
589 589
 			}
590 590
 			$share->setShareOwner($parent->getOwner()->getUID());
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 		}
638 638
 
639 639
 		// Generate the target
640
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
640
+		$target = $this->config->getSystemValue('share_folder', '/').'/'.$share->getNode()->getName();
641 641
 		$target = \OC\Files\Filesystem::normalizePath($target);
642 642
 		$share->setTarget($target);
643 643
 
@@ -660,7 +660,7 @@  discard block
 block discarded – undo
660 660
 
661 661
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
662 662
 			$mailSend = $share->getMailSend();
663
-			if($mailSend === true) {
663
+			if ($mailSend === true) {
664 664
 				$user = $this->userManager->get($share->getSharedWith());
665 665
 				if ($user !== null) {
666 666
 					$emailAddress = $user->getEMailAddress();
@@ -675,12 +675,12 @@  discard block
 block discarded – undo
675 675
 							$emailAddress,
676 676
 							$share->getExpirationDate()
677 677
 						);
678
-						$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
678
+						$this->logger->debug('Send share notification to '.$emailAddress.' for share with ID '.$share->getId(), ['app' => 'share']);
679 679
 					} else {
680
-						$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
680
+						$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because email address is not set.', ['app' => 'share']);
681 681
 					}
682 682
 				} else {
683
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
683
+					$this->logger->debug('Share notification not send to '.$share->getSharedWith().' because user could not be found.', ['app' => 'share']);
684 684
 				}
685 685
 			} else {
686 686
 				$this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
 		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
725 725
 
726 726
 		$emailTemplate->addBodyText(
727
-			$text . ' ' . $l->t('Click the button below to open it.'),
727
+			$text.' '.$l->t('Click the button below to open it.'),
728 728
 			$text
729 729
 		);
730 730
 		$emailTemplate->addBodyButton(
@@ -748,9 +748,9 @@  discard block
 block discarded – undo
748 748
 		// The "Reply-To" is set to the sharer if an mail address is configured
749 749
 		// also the default footer contains a "Do not reply" which needs to be adjusted.
750 750
 		$initiatorEmail = $initiatorUser->getEMailAddress();
751
-		if($initiatorEmail !== null) {
751
+		if ($initiatorEmail !== null) {
752 752
 			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
753
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
753
+			$emailTemplate->addFooter($instanceName.($this->defaults->getSlogan() !== '' ? ' - '.$this->defaults->getSlogan() : ''));
754 754
 		} else {
755 755
 			$emailTemplate->addFooter();
756 756
 		}
@@ -959,7 +959,7 @@  discard block
 block discarded – undo
959 959
 	 * @param string $recipientId
960 960
 	 */
961 961
 	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
962
-		list($providerId, ) = $this->splitFullId($share->getFullId());
962
+		list($providerId,) = $this->splitFullId($share->getFullId());
963 963
 		$provider = $this->factory->getProvider($providerId);
964 964
 
965 965
 		$provider->deleteFromSelf($share, $recipientId);
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
983 983
 			$sharedWith = $this->groupManager->get($share->getSharedWith());
984 984
 			if (is_null($sharedWith)) {
985
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
985
+				throw new \InvalidArgumentException('Group "'.$share->getSharedWith().'" does not exist');
986 986
 			}
987 987
 			$recipient = $this->userManager->get($recipientId);
988 988
 			if (!$sharedWith->inGroup($recipient)) {
@@ -990,7 +990,7 @@  discard block
 block discarded – undo
990 990
 			}
991 991
 		}
992 992
 
993
-		list($providerId, ) = $this->splitFullId($share->getFullId());
993
+		list($providerId,) = $this->splitFullId($share->getFullId());
994 994
 		$provider = $this->factory->getProvider($providerId);
995 995
 
996 996
 		$provider->move($share, $recipientId);
@@ -1037,7 +1037,7 @@  discard block
 block discarded – undo
1037 1037
 
1038 1038
 		$shares2 = [];
1039 1039
 
1040
-		while(true) {
1040
+		while (true) {
1041 1041
 			$added = 0;
1042 1042
 			foreach ($shares as $share) {
1043 1043
 
@@ -1142,7 +1142,7 @@  discard block
 block discarded – undo
1142 1142
 	 *
1143 1143
 	 * @return Share[]
1144 1144
 	 */
1145
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1145
+	public function getSharesByPath(\OCP\Files\Node $path, $page = 0, $perPage = 50) {
1146 1146
 		return [];
1147 1147
 	}
1148 1148
 
@@ -1157,7 +1157,7 @@  discard block
 block discarded – undo
1157 1157
 	public function getShareByToken($token) {
1158 1158
 		$share = null;
1159 1159
 		try {
1160
-			if($this->shareApiAllowLinks()) {
1160
+			if ($this->shareApiAllowLinks()) {
1161 1161
 				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1162 1162
 				$share = $provider->getShareByToken($token);
1163 1163
 			}
@@ -1364,7 +1364,7 @@  discard block
 block discarded – undo
1364 1364
 			}
1365 1365
 			$al['users'][$owner] = [
1366 1366
 				'node_id' => $path->getId(),
1367
-				'node_path' => '/' . $ownerPath,
1367
+				'node_path' => '/'.$ownerPath,
1368 1368
 			];
1369 1369
 		} else {
1370 1370
 			$al['users'][] = $owner;
@@ -1458,7 +1458,7 @@  discard block
 block discarded – undo
1458 1458
 	 * @return int
1459 1459
 	 */
1460 1460
 	public function shareApiLinkDefaultExpireDays() {
1461
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1461
+		return (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1462 1462
 	}
1463 1463
 
1464 1464
 	/**
Please login to merge, or discard this patch.
Indentation   +1464 added lines, -1464 removed lines patch added patch discarded remove patch
@@ -70,1492 +70,1492 @@
 block discarded – undo
70 70
  */
71 71
 class Manager implements IManager {
72 72
 
73
-	/** @var IProviderFactory */
74
-	private $factory;
75
-	/** @var ILogger */
76
-	private $logger;
77
-	/** @var IConfig */
78
-	private $config;
79
-	/** @var ISecureRandom */
80
-	private $secureRandom;
81
-	/** @var IHasher */
82
-	private $hasher;
83
-	/** @var IMountManager */
84
-	private $mountManager;
85
-	/** @var IGroupManager */
86
-	private $groupManager;
87
-	/** @var IL10N */
88
-	private $l;
89
-	/** @var IFactory */
90
-	private $l10nFactory;
91
-	/** @var IUserManager */
92
-	private $userManager;
93
-	/** @var IRootFolder */
94
-	private $rootFolder;
95
-	/** @var CappedMemoryCache */
96
-	private $sharingDisabledForUsersCache;
97
-	/** @var EventDispatcher */
98
-	private $eventDispatcher;
99
-	/** @var LegacyHooks */
100
-	private $legacyHooks;
101
-	/** @var IMailer */
102
-	private $mailer;
103
-	/** @var IURLGenerator */
104
-	private $urlGenerator;
105
-	/** @var \OC_Defaults */
106
-	private $defaults;
107
-
108
-
109
-	/**
110
-	 * Manager constructor.
111
-	 *
112
-	 * @param ILogger $logger
113
-	 * @param IConfig $config
114
-	 * @param ISecureRandom $secureRandom
115
-	 * @param IHasher $hasher
116
-	 * @param IMountManager $mountManager
117
-	 * @param IGroupManager $groupManager
118
-	 * @param IL10N $l
119
-	 * @param IFactory $l10nFactory
120
-	 * @param IProviderFactory $factory
121
-	 * @param IUserManager $userManager
122
-	 * @param IRootFolder $rootFolder
123
-	 * @param EventDispatcher $eventDispatcher
124
-	 * @param IMailer $mailer
125
-	 * @param IURLGenerator $urlGenerator
126
-	 * @param \OC_Defaults $defaults
127
-	 */
128
-	public function __construct(
129
-			ILogger $logger,
130
-			IConfig $config,
131
-			ISecureRandom $secureRandom,
132
-			IHasher $hasher,
133
-			IMountManager $mountManager,
134
-			IGroupManager $groupManager,
135
-			IL10N $l,
136
-			IFactory $l10nFactory,
137
-			IProviderFactory $factory,
138
-			IUserManager $userManager,
139
-			IRootFolder $rootFolder,
140
-			EventDispatcher $eventDispatcher,
141
-			IMailer $mailer,
142
-			IURLGenerator $urlGenerator,
143
-			\OC_Defaults $defaults
144
-	) {
145
-		$this->logger = $logger;
146
-		$this->config = $config;
147
-		$this->secureRandom = $secureRandom;
148
-		$this->hasher = $hasher;
149
-		$this->mountManager = $mountManager;
150
-		$this->groupManager = $groupManager;
151
-		$this->l = $l;
152
-		$this->l10nFactory = $l10nFactory;
153
-		$this->factory = $factory;
154
-		$this->userManager = $userManager;
155
-		$this->rootFolder = $rootFolder;
156
-		$this->eventDispatcher = $eventDispatcher;
157
-		$this->sharingDisabledForUsersCache = new CappedMemoryCache();
158
-		$this->legacyHooks = new LegacyHooks($this->eventDispatcher);
159
-		$this->mailer = $mailer;
160
-		$this->urlGenerator = $urlGenerator;
161
-		$this->defaults = $defaults;
162
-	}
163
-
164
-	/**
165
-	 * Convert from a full share id to a tuple (providerId, shareId)
166
-	 *
167
-	 * @param string $id
168
-	 * @return string[]
169
-	 */
170
-	private function splitFullId($id) {
171
-		return explode(':', $id, 2);
172
-	}
173
-
174
-	/**
175
-	 * Verify if a password meets all requirements
176
-	 *
177
-	 * @param string $password
178
-	 * @throws \Exception
179
-	 */
180
-	protected function verifyPassword($password) {
181
-		if ($password === null) {
182
-			// No password is set, check if this is allowed.
183
-			if ($this->shareApiLinkEnforcePassword()) {
184
-				throw new \InvalidArgumentException('Passwords are enforced for link shares');
185
-			}
186
-
187
-			return;
188
-		}
189
-
190
-		// Let others verify the password
191
-		try {
192
-			$event = new GenericEvent($password);
193
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
194
-		} catch (HintException $e) {
195
-			throw new \Exception($e->getHint());
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * Check for generic requirements before creating a share
201
-	 *
202
-	 * @param \OCP\Share\IShare $share
203
-	 * @throws \InvalidArgumentException
204
-	 * @throws GenericShareException
205
-	 *
206
-	 * @suppress PhanUndeclaredClassMethod
207
-	 */
208
-	protected function generalCreateChecks(\OCP\Share\IShare $share) {
209
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
210
-			// We expect a valid user as sharedWith for user shares
211
-			if (!$this->userManager->userExists($share->getSharedWith())) {
212
-				throw new \InvalidArgumentException('SharedWith is not a valid user');
213
-			}
214
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
215
-			// We expect a valid group as sharedWith for group shares
216
-			if (!$this->groupManager->groupExists($share->getSharedWith())) {
217
-				throw new \InvalidArgumentException('SharedWith is not a valid group');
218
-			}
219
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
220
-			if ($share->getSharedWith() !== null) {
221
-				throw new \InvalidArgumentException('SharedWith should be empty');
222
-			}
223
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
224
-			if ($share->getSharedWith() === null) {
225
-				throw new \InvalidArgumentException('SharedWith should not be empty');
226
-			}
227
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
228
-			if ($share->getSharedWith() === null) {
229
-				throw new \InvalidArgumentException('SharedWith should not be empty');
230
-			}
231
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
232
-			$circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
233
-			if ($circle === null) {
234
-				throw new \InvalidArgumentException('SharedWith is not a valid circle');
235
-			}
236
-		} else {
237
-			// We can't handle other types yet
238
-			throw new \InvalidArgumentException('unknown share type');
239
-		}
240
-
241
-		// Verify the initiator of the share is set
242
-		if ($share->getSharedBy() === null) {
243
-			throw new \InvalidArgumentException('SharedBy should be set');
244
-		}
245
-
246
-		// Cannot share with yourself
247
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
248
-			$share->getSharedWith() === $share->getSharedBy()) {
249
-			throw new \InvalidArgumentException('Can’t share with yourself');
250
-		}
251
-
252
-		// The path should be set
253
-		if ($share->getNode() === null) {
254
-			throw new \InvalidArgumentException('Path should be set');
255
-		}
256
-
257
-		// And it should be a file or a folder
258
-		if (!($share->getNode() instanceof \OCP\Files\File) &&
259
-				!($share->getNode() instanceof \OCP\Files\Folder)) {
260
-			throw new \InvalidArgumentException('Path should be either a file or a folder');
261
-		}
262
-
263
-		// And you can't share your rootfolder
264
-		if ($this->userManager->userExists($share->getSharedBy())) {
265
-			$sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
266
-		} else {
267
-			$sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
268
-		}
269
-		if ($sharedPath === $share->getNode()->getPath()) {
270
-			throw new \InvalidArgumentException('You can’t share your root folder');
271
-		}
272
-
273
-		// Check if we actually have share permissions
274
-		if (!$share->getNode()->isShareable()) {
275
-			$message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
276
-			throw new GenericShareException($message_t, $message_t, 404);
277
-		}
278
-
279
-		// Permissions should be set
280
-		if ($share->getPermissions() === null) {
281
-			throw new \InvalidArgumentException('A share requires permissions');
282
-		}
283
-
284
-		/*
73
+    /** @var IProviderFactory */
74
+    private $factory;
75
+    /** @var ILogger */
76
+    private $logger;
77
+    /** @var IConfig */
78
+    private $config;
79
+    /** @var ISecureRandom */
80
+    private $secureRandom;
81
+    /** @var IHasher */
82
+    private $hasher;
83
+    /** @var IMountManager */
84
+    private $mountManager;
85
+    /** @var IGroupManager */
86
+    private $groupManager;
87
+    /** @var IL10N */
88
+    private $l;
89
+    /** @var IFactory */
90
+    private $l10nFactory;
91
+    /** @var IUserManager */
92
+    private $userManager;
93
+    /** @var IRootFolder */
94
+    private $rootFolder;
95
+    /** @var CappedMemoryCache */
96
+    private $sharingDisabledForUsersCache;
97
+    /** @var EventDispatcher */
98
+    private $eventDispatcher;
99
+    /** @var LegacyHooks */
100
+    private $legacyHooks;
101
+    /** @var IMailer */
102
+    private $mailer;
103
+    /** @var IURLGenerator */
104
+    private $urlGenerator;
105
+    /** @var \OC_Defaults */
106
+    private $defaults;
107
+
108
+
109
+    /**
110
+     * Manager constructor.
111
+     *
112
+     * @param ILogger $logger
113
+     * @param IConfig $config
114
+     * @param ISecureRandom $secureRandom
115
+     * @param IHasher $hasher
116
+     * @param IMountManager $mountManager
117
+     * @param IGroupManager $groupManager
118
+     * @param IL10N $l
119
+     * @param IFactory $l10nFactory
120
+     * @param IProviderFactory $factory
121
+     * @param IUserManager $userManager
122
+     * @param IRootFolder $rootFolder
123
+     * @param EventDispatcher $eventDispatcher
124
+     * @param IMailer $mailer
125
+     * @param IURLGenerator $urlGenerator
126
+     * @param \OC_Defaults $defaults
127
+     */
128
+    public function __construct(
129
+            ILogger $logger,
130
+            IConfig $config,
131
+            ISecureRandom $secureRandom,
132
+            IHasher $hasher,
133
+            IMountManager $mountManager,
134
+            IGroupManager $groupManager,
135
+            IL10N $l,
136
+            IFactory $l10nFactory,
137
+            IProviderFactory $factory,
138
+            IUserManager $userManager,
139
+            IRootFolder $rootFolder,
140
+            EventDispatcher $eventDispatcher,
141
+            IMailer $mailer,
142
+            IURLGenerator $urlGenerator,
143
+            \OC_Defaults $defaults
144
+    ) {
145
+        $this->logger = $logger;
146
+        $this->config = $config;
147
+        $this->secureRandom = $secureRandom;
148
+        $this->hasher = $hasher;
149
+        $this->mountManager = $mountManager;
150
+        $this->groupManager = $groupManager;
151
+        $this->l = $l;
152
+        $this->l10nFactory = $l10nFactory;
153
+        $this->factory = $factory;
154
+        $this->userManager = $userManager;
155
+        $this->rootFolder = $rootFolder;
156
+        $this->eventDispatcher = $eventDispatcher;
157
+        $this->sharingDisabledForUsersCache = new CappedMemoryCache();
158
+        $this->legacyHooks = new LegacyHooks($this->eventDispatcher);
159
+        $this->mailer = $mailer;
160
+        $this->urlGenerator = $urlGenerator;
161
+        $this->defaults = $defaults;
162
+    }
163
+
164
+    /**
165
+     * Convert from a full share id to a tuple (providerId, shareId)
166
+     *
167
+     * @param string $id
168
+     * @return string[]
169
+     */
170
+    private function splitFullId($id) {
171
+        return explode(':', $id, 2);
172
+    }
173
+
174
+    /**
175
+     * Verify if a password meets all requirements
176
+     *
177
+     * @param string $password
178
+     * @throws \Exception
179
+     */
180
+    protected function verifyPassword($password) {
181
+        if ($password === null) {
182
+            // No password is set, check if this is allowed.
183
+            if ($this->shareApiLinkEnforcePassword()) {
184
+                throw new \InvalidArgumentException('Passwords are enforced for link shares');
185
+            }
186
+
187
+            return;
188
+        }
189
+
190
+        // Let others verify the password
191
+        try {
192
+            $event = new GenericEvent($password);
193
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
194
+        } catch (HintException $e) {
195
+            throw new \Exception($e->getHint());
196
+        }
197
+    }
198
+
199
+    /**
200
+     * Check for generic requirements before creating a share
201
+     *
202
+     * @param \OCP\Share\IShare $share
203
+     * @throws \InvalidArgumentException
204
+     * @throws GenericShareException
205
+     *
206
+     * @suppress PhanUndeclaredClassMethod
207
+     */
208
+    protected function generalCreateChecks(\OCP\Share\IShare $share) {
209
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
210
+            // We expect a valid user as sharedWith for user shares
211
+            if (!$this->userManager->userExists($share->getSharedWith())) {
212
+                throw new \InvalidArgumentException('SharedWith is not a valid user');
213
+            }
214
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
215
+            // We expect a valid group as sharedWith for group shares
216
+            if (!$this->groupManager->groupExists($share->getSharedWith())) {
217
+                throw new \InvalidArgumentException('SharedWith is not a valid group');
218
+            }
219
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
220
+            if ($share->getSharedWith() !== null) {
221
+                throw new \InvalidArgumentException('SharedWith should be empty');
222
+            }
223
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) {
224
+            if ($share->getSharedWith() === null) {
225
+                throw new \InvalidArgumentException('SharedWith should not be empty');
226
+            }
227
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
228
+            if ($share->getSharedWith() === null) {
229
+                throw new \InvalidArgumentException('SharedWith should not be empty');
230
+            }
231
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_CIRCLE) {
232
+            $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($share->getSharedWith());
233
+            if ($circle === null) {
234
+                throw new \InvalidArgumentException('SharedWith is not a valid circle');
235
+            }
236
+        } else {
237
+            // We can't handle other types yet
238
+            throw new \InvalidArgumentException('unknown share type');
239
+        }
240
+
241
+        // Verify the initiator of the share is set
242
+        if ($share->getSharedBy() === null) {
243
+            throw new \InvalidArgumentException('SharedBy should be set');
244
+        }
245
+
246
+        // Cannot share with yourself
247
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
248
+            $share->getSharedWith() === $share->getSharedBy()) {
249
+            throw new \InvalidArgumentException('Can’t share with yourself');
250
+        }
251
+
252
+        // The path should be set
253
+        if ($share->getNode() === null) {
254
+            throw new \InvalidArgumentException('Path should be set');
255
+        }
256
+
257
+        // And it should be a file or a folder
258
+        if (!($share->getNode() instanceof \OCP\Files\File) &&
259
+                !($share->getNode() instanceof \OCP\Files\Folder)) {
260
+            throw new \InvalidArgumentException('Path should be either a file or a folder');
261
+        }
262
+
263
+        // And you can't share your rootfolder
264
+        if ($this->userManager->userExists($share->getSharedBy())) {
265
+            $sharedPath = $this->rootFolder->getUserFolder($share->getSharedBy())->getPath();
266
+        } else {
267
+            $sharedPath = $this->rootFolder->getUserFolder($share->getShareOwner())->getPath();
268
+        }
269
+        if ($sharedPath === $share->getNode()->getPath()) {
270
+            throw new \InvalidArgumentException('You can’t share your root folder');
271
+        }
272
+
273
+        // Check if we actually have share permissions
274
+        if (!$share->getNode()->isShareable()) {
275
+            $message_t = $this->l->t('You are not allowed to share %s', [$share->getNode()->getPath()]);
276
+            throw new GenericShareException($message_t, $message_t, 404);
277
+        }
278
+
279
+        // Permissions should be set
280
+        if ($share->getPermissions() === null) {
281
+            throw new \InvalidArgumentException('A share requires permissions');
282
+        }
283
+
284
+        /*
285 285
 		 * Quick fix for #23536
286 286
 		 * Non moveable mount points do not have update and delete permissions
287 287
 		 * while we 'most likely' do have that on the storage.
288 288
 		 */
289
-		$permissions = $share->getNode()->getPermissions();
290
-		$mount = $share->getNode()->getMountPoint();
291
-		if (!($mount instanceof MoveableMount)) {
292
-			$permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
293
-		}
294
-
295
-		// Check that we do not share with more permissions than we have
296
-		if ($share->getPermissions() & ~$permissions) {
297
-			$message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
298
-			throw new GenericShareException($message_t, $message_t, 404);
299
-		}
300
-
301
-
302
-		// Check that read permissions are always set
303
-		// Link shares are allowed to have no read permissions to allow upload to hidden folders
304
-		$noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
305
-			|| $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
306
-		if (!$noReadPermissionRequired &&
307
-			($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
308
-			throw new \InvalidArgumentException('Shares need at least read permissions');
309
-		}
310
-
311
-		if ($share->getNode() instanceof \OCP\Files\File) {
312
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
313
-				$message_t = $this->l->t('Files can’t be shared with delete permissions');
314
-				throw new GenericShareException($message_t);
315
-			}
316
-			if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
317
-				$message_t = $this->l->t('Files can’t be shared with create permissions');
318
-				throw new GenericShareException($message_t);
319
-			}
320
-		}
321
-	}
322
-
323
-	/**
324
-	 * Validate if the expiration date fits the system settings
325
-	 *
326
-	 * @param \OCP\Share\IShare $share The share to validate the expiration date of
327
-	 * @return \OCP\Share\IShare The modified share object
328
-	 * @throws GenericShareException
329
-	 * @throws \InvalidArgumentException
330
-	 * @throws \Exception
331
-	 */
332
-	protected function validateExpirationDate(\OCP\Share\IShare $share) {
333
-
334
-		$expirationDate = $share->getExpirationDate();
335
-
336
-		if ($expirationDate !== null) {
337
-			//Make sure the expiration date is a date
338
-			$expirationDate->setTime(0, 0, 0);
339
-
340
-			$date = new \DateTime();
341
-			$date->setTime(0, 0, 0);
342
-			if ($date >= $expirationDate) {
343
-				$message = $this->l->t('Expiration date is in the past');
344
-				throw new GenericShareException($message, $message, 404);
345
-			}
346
-		}
347
-
348
-		// If expiredate is empty set a default one if there is a default
349
-		$fullId = null;
350
-		try {
351
-			$fullId = $share->getFullId();
352
-		} catch (\UnexpectedValueException $e) {
353
-			// This is a new share
354
-		}
355
-
356
-		if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
357
-			$expirationDate = new \DateTime();
358
-			$expirationDate->setTime(0,0,0);
359
-			$expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
360
-		}
361
-
362
-		// If we enforce the expiration date check that is does not exceed
363
-		if ($this->shareApiLinkDefaultExpireDateEnforced()) {
364
-			if ($expirationDate === null) {
365
-				throw new \InvalidArgumentException('Expiration date is enforced');
366
-			}
367
-
368
-			$date = new \DateTime();
369
-			$date->setTime(0, 0, 0);
370
-			$date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
371
-			if ($date < $expirationDate) {
372
-				$message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
373
-				throw new GenericShareException($message, $message, 404);
374
-			}
375
-		}
376
-
377
-		$accepted = true;
378
-		$message = '';
379
-		\OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
380
-			'expirationDate' => &$expirationDate,
381
-			'accepted' => &$accepted,
382
-			'message' => &$message,
383
-			'passwordSet' => $share->getPassword() !== null,
384
-		]);
385
-
386
-		if (!$accepted) {
387
-			throw new \Exception($message);
388
-		}
389
-
390
-		$share->setExpirationDate($expirationDate);
391
-
392
-		return $share;
393
-	}
394
-
395
-	/**
396
-	 * Check for pre share requirements for user shares
397
-	 *
398
-	 * @param \OCP\Share\IShare $share
399
-	 * @throws \Exception
400
-	 */
401
-	protected function userCreateChecks(\OCP\Share\IShare $share) {
402
-		// Check if we can share with group members only
403
-		if ($this->shareWithGroupMembersOnly()) {
404
-			$sharedBy = $this->userManager->get($share->getSharedBy());
405
-			$sharedWith = $this->userManager->get($share->getSharedWith());
406
-			// Verify we can share with this user
407
-			$groups = array_intersect(
408
-					$this->groupManager->getUserGroupIds($sharedBy),
409
-					$this->groupManager->getUserGroupIds($sharedWith)
410
-			);
411
-			if (empty($groups)) {
412
-				throw new \Exception('Sharing is only allowed with group members');
413
-			}
414
-		}
415
-
416
-		/*
289
+        $permissions = $share->getNode()->getPermissions();
290
+        $mount = $share->getNode()->getMountPoint();
291
+        if (!($mount instanceof MoveableMount)) {
292
+            $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE;
293
+        }
294
+
295
+        // Check that we do not share with more permissions than we have
296
+        if ($share->getPermissions() & ~$permissions) {
297
+            $message_t = $this->l->t('Can’t increase permissions of %s', [$share->getNode()->getPath()]);
298
+            throw new GenericShareException($message_t, $message_t, 404);
299
+        }
300
+
301
+
302
+        // Check that read permissions are always set
303
+        // Link shares are allowed to have no read permissions to allow upload to hidden folders
304
+        $noReadPermissionRequired = $share->getShareType() === \OCP\Share::SHARE_TYPE_LINK
305
+            || $share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL;
306
+        if (!$noReadPermissionRequired &&
307
+            ($share->getPermissions() & \OCP\Constants::PERMISSION_READ) === 0) {
308
+            throw new \InvalidArgumentException('Shares need at least read permissions');
309
+        }
310
+
311
+        if ($share->getNode() instanceof \OCP\Files\File) {
312
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_DELETE) {
313
+                $message_t = $this->l->t('Files can’t be shared with delete permissions');
314
+                throw new GenericShareException($message_t);
315
+            }
316
+            if ($share->getPermissions() & \OCP\Constants::PERMISSION_CREATE) {
317
+                $message_t = $this->l->t('Files can’t be shared with create permissions');
318
+                throw new GenericShareException($message_t);
319
+            }
320
+        }
321
+    }
322
+
323
+    /**
324
+     * Validate if the expiration date fits the system settings
325
+     *
326
+     * @param \OCP\Share\IShare $share The share to validate the expiration date of
327
+     * @return \OCP\Share\IShare The modified share object
328
+     * @throws GenericShareException
329
+     * @throws \InvalidArgumentException
330
+     * @throws \Exception
331
+     */
332
+    protected function validateExpirationDate(\OCP\Share\IShare $share) {
333
+
334
+        $expirationDate = $share->getExpirationDate();
335
+
336
+        if ($expirationDate !== null) {
337
+            //Make sure the expiration date is a date
338
+            $expirationDate->setTime(0, 0, 0);
339
+
340
+            $date = new \DateTime();
341
+            $date->setTime(0, 0, 0);
342
+            if ($date >= $expirationDate) {
343
+                $message = $this->l->t('Expiration date is in the past');
344
+                throw new GenericShareException($message, $message, 404);
345
+            }
346
+        }
347
+
348
+        // If expiredate is empty set a default one if there is a default
349
+        $fullId = null;
350
+        try {
351
+            $fullId = $share->getFullId();
352
+        } catch (\UnexpectedValueException $e) {
353
+            // This is a new share
354
+        }
355
+
356
+        if ($fullId === null && $expirationDate === null && $this->shareApiLinkDefaultExpireDate()) {
357
+            $expirationDate = new \DateTime();
358
+            $expirationDate->setTime(0,0,0);
359
+            $expirationDate->add(new \DateInterval('P'.$this->shareApiLinkDefaultExpireDays().'D'));
360
+        }
361
+
362
+        // If we enforce the expiration date check that is does not exceed
363
+        if ($this->shareApiLinkDefaultExpireDateEnforced()) {
364
+            if ($expirationDate === null) {
365
+                throw new \InvalidArgumentException('Expiration date is enforced');
366
+            }
367
+
368
+            $date = new \DateTime();
369
+            $date->setTime(0, 0, 0);
370
+            $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D'));
371
+            if ($date < $expirationDate) {
372
+                $message = $this->l->t('Can’t set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]);
373
+                throw new GenericShareException($message, $message, 404);
374
+            }
375
+        }
376
+
377
+        $accepted = true;
378
+        $message = '';
379
+        \OCP\Util::emitHook('\OC\Share', 'verifyExpirationDate', [
380
+            'expirationDate' => &$expirationDate,
381
+            'accepted' => &$accepted,
382
+            'message' => &$message,
383
+            'passwordSet' => $share->getPassword() !== null,
384
+        ]);
385
+
386
+        if (!$accepted) {
387
+            throw new \Exception($message);
388
+        }
389
+
390
+        $share->setExpirationDate($expirationDate);
391
+
392
+        return $share;
393
+    }
394
+
395
+    /**
396
+     * Check for pre share requirements for user shares
397
+     *
398
+     * @param \OCP\Share\IShare $share
399
+     * @throws \Exception
400
+     */
401
+    protected function userCreateChecks(\OCP\Share\IShare $share) {
402
+        // Check if we can share with group members only
403
+        if ($this->shareWithGroupMembersOnly()) {
404
+            $sharedBy = $this->userManager->get($share->getSharedBy());
405
+            $sharedWith = $this->userManager->get($share->getSharedWith());
406
+            // Verify we can share with this user
407
+            $groups = array_intersect(
408
+                    $this->groupManager->getUserGroupIds($sharedBy),
409
+                    $this->groupManager->getUserGroupIds($sharedWith)
410
+            );
411
+            if (empty($groups)) {
412
+                throw new \Exception('Sharing is only allowed with group members');
413
+            }
414
+        }
415
+
416
+        /*
417 417
 		 * TODO: Could be costly, fix
418 418
 		 *
419 419
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
420 420
 		 */
421
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
422
-		$existingShares = $provider->getSharesByPath($share->getNode());
423
-		foreach($existingShares as $existingShare) {
424
-			// Ignore if it is the same share
425
-			try {
426
-				if ($existingShare->getFullId() === $share->getFullId()) {
427
-					continue;
428
-				}
429
-			} catch (\UnexpectedValueException $e) {
430
-				//Shares are not identical
431
-			}
432
-
433
-			// Identical share already existst
434
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
435
-				throw new \Exception('Path is already shared with this user');
436
-			}
437
-
438
-			// The share is already shared with this user via a group share
439
-			if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
440
-				$group = $this->groupManager->get($existingShare->getSharedWith());
441
-				if (!is_null($group)) {
442
-					$user = $this->userManager->get($share->getSharedWith());
443
-
444
-					if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
445
-						throw new \Exception('Path is already shared with this user');
446
-					}
447
-				}
448
-			}
449
-		}
450
-	}
451
-
452
-	/**
453
-	 * Check for pre share requirements for group shares
454
-	 *
455
-	 * @param \OCP\Share\IShare $share
456
-	 * @throws \Exception
457
-	 */
458
-	protected function groupCreateChecks(\OCP\Share\IShare $share) {
459
-		// Verify group shares are allowed
460
-		if (!$this->allowGroupSharing()) {
461
-			throw new \Exception('Group sharing is now allowed');
462
-		}
463
-
464
-		// Verify if the user can share with this group
465
-		if ($this->shareWithGroupMembersOnly()) {
466
-			$sharedBy = $this->userManager->get($share->getSharedBy());
467
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
468
-			if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
469
-				throw new \Exception('Sharing is only allowed within your own groups');
470
-			}
471
-		}
472
-
473
-		/*
421
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_USER);
422
+        $existingShares = $provider->getSharesByPath($share->getNode());
423
+        foreach($existingShares as $existingShare) {
424
+            // Ignore if it is the same share
425
+            try {
426
+                if ($existingShare->getFullId() === $share->getFullId()) {
427
+                    continue;
428
+                }
429
+            } catch (\UnexpectedValueException $e) {
430
+                //Shares are not identical
431
+            }
432
+
433
+            // Identical share already existst
434
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
435
+                throw new \Exception('Path is already shared with this user');
436
+            }
437
+
438
+            // The share is already shared with this user via a group share
439
+            if ($existingShare->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
440
+                $group = $this->groupManager->get($existingShare->getSharedWith());
441
+                if (!is_null($group)) {
442
+                    $user = $this->userManager->get($share->getSharedWith());
443
+
444
+                    if ($group->inGroup($user) && $existingShare->getShareOwner() !== $share->getShareOwner()) {
445
+                        throw new \Exception('Path is already shared with this user');
446
+                    }
447
+                }
448
+            }
449
+        }
450
+    }
451
+
452
+    /**
453
+     * Check for pre share requirements for group shares
454
+     *
455
+     * @param \OCP\Share\IShare $share
456
+     * @throws \Exception
457
+     */
458
+    protected function groupCreateChecks(\OCP\Share\IShare $share) {
459
+        // Verify group shares are allowed
460
+        if (!$this->allowGroupSharing()) {
461
+            throw new \Exception('Group sharing is now allowed');
462
+        }
463
+
464
+        // Verify if the user can share with this group
465
+        if ($this->shareWithGroupMembersOnly()) {
466
+            $sharedBy = $this->userManager->get($share->getSharedBy());
467
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
468
+            if (is_null($sharedWith) || !$sharedWith->inGroup($sharedBy)) {
469
+                throw new \Exception('Sharing is only allowed within your own groups');
470
+            }
471
+        }
472
+
473
+        /*
474 474
 		 * TODO: Could be costly, fix
475 475
 		 *
476 476
 		 * Also this is not what we want in the future.. then we want to squash identical shares.
477 477
 		 */
478
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
479
-		$existingShares = $provider->getSharesByPath($share->getNode());
480
-		foreach($existingShares as $existingShare) {
481
-			try {
482
-				if ($existingShare->getFullId() === $share->getFullId()) {
483
-					continue;
484
-				}
485
-			} catch (\UnexpectedValueException $e) {
486
-				//It is a new share so just continue
487
-			}
488
-
489
-			if ($existingShare->getSharedWith() === $share->getSharedWith()) {
490
-				throw new \Exception('Path is already shared with this group');
491
-			}
492
-		}
493
-	}
494
-
495
-	/**
496
-	 * Check for pre share requirements for link shares
497
-	 *
498
-	 * @param \OCP\Share\IShare $share
499
-	 * @throws \Exception
500
-	 */
501
-	protected function linkCreateChecks(\OCP\Share\IShare $share) {
502
-		// Are link shares allowed?
503
-		if (!$this->shareApiAllowLinks()) {
504
-			throw new \Exception('Link sharing is not allowed');
505
-		}
506
-
507
-		// Link shares by definition can't have share permissions
508
-		if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
509
-			throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
510
-		}
511
-
512
-		// Check if public upload is allowed
513
-		if (!$this->shareApiLinkAllowPublicUpload() &&
514
-			($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
515
-			throw new \InvalidArgumentException('Public upload is not allowed');
516
-		}
517
-	}
518
-
519
-	/**
520
-	 * To make sure we don't get invisible link shares we set the parent
521
-	 * of a link if it is a reshare. This is a quick word around
522
-	 * until we can properly display multiple link shares in the UI
523
-	 *
524
-	 * See: https://github.com/owncloud/core/issues/22295
525
-	 *
526
-	 * FIXME: Remove once multiple link shares can be properly displayed
527
-	 *
528
-	 * @param \OCP\Share\IShare $share
529
-	 */
530
-	protected function setLinkParent(\OCP\Share\IShare $share) {
531
-
532
-		// No sense in checking if the method is not there.
533
-		if (method_exists($share, 'setParent')) {
534
-			$storage = $share->getNode()->getStorage();
535
-			if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536
-				/** @var \OCA\Files_Sharing\SharedStorage $storage */
537
-				$share->setParent($storage->getShareId());
538
-			}
539
-		};
540
-	}
541
-
542
-	/**
543
-	 * @param File|Folder $path
544
-	 */
545
-	protected function pathCreateChecks($path) {
546
-		// Make sure that we do not share a path that contains a shared mountpoint
547
-		if ($path instanceof \OCP\Files\Folder) {
548
-			$mounts = $this->mountManager->findIn($path->getPath());
549
-			foreach($mounts as $mount) {
550
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
551
-					throw new \InvalidArgumentException('Path contains files shared with you');
552
-				}
553
-			}
554
-		}
555
-	}
556
-
557
-	/**
558
-	 * Check if the user that is sharing can actually share
559
-	 *
560
-	 * @param \OCP\Share\IShare $share
561
-	 * @throws \Exception
562
-	 */
563
-	protected function canShare(\OCP\Share\IShare $share) {
564
-		if (!$this->shareApiEnabled()) {
565
-			throw new \Exception('Sharing is disabled');
566
-		}
567
-
568
-		if ($this->sharingDisabledForUser($share->getSharedBy())) {
569
-			throw new \Exception('Sharing is disabled for you');
570
-		}
571
-	}
572
-
573
-	/**
574
-	 * Share a path
575
-	 *
576
-	 * @param \OCP\Share\IShare $share
577
-	 * @return Share The share object
578
-	 * @throws \Exception
579
-	 *
580
-	 * TODO: handle link share permissions or check them
581
-	 */
582
-	public function createShare(\OCP\Share\IShare $share) {
583
-		$this->canShare($share);
584
-
585
-		$this->generalCreateChecks($share);
586
-
587
-		// Verify if there are any issues with the path
588
-		$this->pathCreateChecks($share->getNode());
589
-
590
-		/*
478
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
479
+        $existingShares = $provider->getSharesByPath($share->getNode());
480
+        foreach($existingShares as $existingShare) {
481
+            try {
482
+                if ($existingShare->getFullId() === $share->getFullId()) {
483
+                    continue;
484
+                }
485
+            } catch (\UnexpectedValueException $e) {
486
+                //It is a new share so just continue
487
+            }
488
+
489
+            if ($existingShare->getSharedWith() === $share->getSharedWith()) {
490
+                throw new \Exception('Path is already shared with this group');
491
+            }
492
+        }
493
+    }
494
+
495
+    /**
496
+     * Check for pre share requirements for link shares
497
+     *
498
+     * @param \OCP\Share\IShare $share
499
+     * @throws \Exception
500
+     */
501
+    protected function linkCreateChecks(\OCP\Share\IShare $share) {
502
+        // Are link shares allowed?
503
+        if (!$this->shareApiAllowLinks()) {
504
+            throw new \Exception('Link sharing is not allowed');
505
+        }
506
+
507
+        // Link shares by definition can't have share permissions
508
+        if ($share->getPermissions() & \OCP\Constants::PERMISSION_SHARE) {
509
+            throw new \InvalidArgumentException('Link shares can’t have reshare permissions');
510
+        }
511
+
512
+        // Check if public upload is allowed
513
+        if (!$this->shareApiLinkAllowPublicUpload() &&
514
+            ($share->getPermissions() & (\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE))) {
515
+            throw new \InvalidArgumentException('Public upload is not allowed');
516
+        }
517
+    }
518
+
519
+    /**
520
+     * To make sure we don't get invisible link shares we set the parent
521
+     * of a link if it is a reshare. This is a quick word around
522
+     * until we can properly display multiple link shares in the UI
523
+     *
524
+     * See: https://github.com/owncloud/core/issues/22295
525
+     *
526
+     * FIXME: Remove once multiple link shares can be properly displayed
527
+     *
528
+     * @param \OCP\Share\IShare $share
529
+     */
530
+    protected function setLinkParent(\OCP\Share\IShare $share) {
531
+
532
+        // No sense in checking if the method is not there.
533
+        if (method_exists($share, 'setParent')) {
534
+            $storage = $share->getNode()->getStorage();
535
+            if ($storage->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
536
+                /** @var \OCA\Files_Sharing\SharedStorage $storage */
537
+                $share->setParent($storage->getShareId());
538
+            }
539
+        };
540
+    }
541
+
542
+    /**
543
+     * @param File|Folder $path
544
+     */
545
+    protected function pathCreateChecks($path) {
546
+        // Make sure that we do not share a path that contains a shared mountpoint
547
+        if ($path instanceof \OCP\Files\Folder) {
548
+            $mounts = $this->mountManager->findIn($path->getPath());
549
+            foreach($mounts as $mount) {
550
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
551
+                    throw new \InvalidArgumentException('Path contains files shared with you');
552
+                }
553
+            }
554
+        }
555
+    }
556
+
557
+    /**
558
+     * Check if the user that is sharing can actually share
559
+     *
560
+     * @param \OCP\Share\IShare $share
561
+     * @throws \Exception
562
+     */
563
+    protected function canShare(\OCP\Share\IShare $share) {
564
+        if (!$this->shareApiEnabled()) {
565
+            throw new \Exception('Sharing is disabled');
566
+        }
567
+
568
+        if ($this->sharingDisabledForUser($share->getSharedBy())) {
569
+            throw new \Exception('Sharing is disabled for you');
570
+        }
571
+    }
572
+
573
+    /**
574
+     * Share a path
575
+     *
576
+     * @param \OCP\Share\IShare $share
577
+     * @return Share The share object
578
+     * @throws \Exception
579
+     *
580
+     * TODO: handle link share permissions or check them
581
+     */
582
+    public function createShare(\OCP\Share\IShare $share) {
583
+        $this->canShare($share);
584
+
585
+        $this->generalCreateChecks($share);
586
+
587
+        // Verify if there are any issues with the path
588
+        $this->pathCreateChecks($share->getNode());
589
+
590
+        /*
591 591
 		 * On creation of a share the owner is always the owner of the path
592 592
 		 * Except for mounted federated shares.
593 593
 		 */
594
-		$storage = $share->getNode()->getStorage();
595
-		if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
596
-			$parent = $share->getNode()->getParent();
597
-			while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
598
-				$parent = $parent->getParent();
599
-			}
600
-			$share->setShareOwner($parent->getOwner()->getUID());
601
-		} else {
602
-			$share->setShareOwner($share->getNode()->getOwner()->getUID());
603
-		}
604
-
605
-		//Verify share type
606
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
607
-			$this->userCreateChecks($share);
608
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
609
-			$this->groupCreateChecks($share);
610
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
611
-			$this->linkCreateChecks($share);
612
-			$this->setLinkParent($share);
613
-
614
-			/*
594
+        $storage = $share->getNode()->getStorage();
595
+        if ($storage->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
596
+            $parent = $share->getNode()->getParent();
597
+            while($parent->getStorage()->instanceOfStorage('OCA\Files_Sharing\External\Storage')) {
598
+                $parent = $parent->getParent();
599
+            }
600
+            $share->setShareOwner($parent->getOwner()->getUID());
601
+        } else {
602
+            $share->setShareOwner($share->getNode()->getOwner()->getUID());
603
+        }
604
+
605
+        //Verify share type
606
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
607
+            $this->userCreateChecks($share);
608
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
609
+            $this->groupCreateChecks($share);
610
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
611
+            $this->linkCreateChecks($share);
612
+            $this->setLinkParent($share);
613
+
614
+            /*
615 615
 			 * For now ignore a set token.
616 616
 			 */
617
-			$share->setToken(
618
-				$this->secureRandom->generate(
619
-					\OC\Share\Constants::TOKEN_LENGTH,
620
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
621
-				)
622
-			);
623
-
624
-			//Verify the expiration date
625
-			$this->validateExpirationDate($share);
626
-
627
-			//Verify the password
628
-			$this->verifyPassword($share->getPassword());
629
-
630
-			// If a password is set. Hash it!
631
-			if ($share->getPassword() !== null) {
632
-				$share->setPassword($this->hasher->hash($share->getPassword()));
633
-			}
634
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
635
-			$share->setToken(
636
-				$this->secureRandom->generate(
637
-					\OC\Share\Constants::TOKEN_LENGTH,
638
-					\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
639
-				)
640
-			);
641
-		}
642
-
643
-		// Cannot share with the owner
644
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
645
-			$share->getSharedWith() === $share->getShareOwner()) {
646
-			throw new \InvalidArgumentException('Can’t share with the share owner');
647
-		}
648
-
649
-		// Generate the target
650
-		$target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
651
-		$target = \OC\Files\Filesystem::normalizePath($target);
652
-		$share->setTarget($target);
653
-
654
-		// Pre share event
655
-		$event = new GenericEvent($share);
656
-		$a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
657
-		if ($event->isPropagationStopped() && $event->hasArgument('error')) {
658
-			throw new \Exception($event->getArgument('error'));
659
-		}
660
-
661
-		$oldShare = $share;
662
-		$provider = $this->factory->getProviderForType($share->getShareType());
663
-		$share = $provider->create($share);
664
-		//reuse the node we already have
665
-		$share->setNode($oldShare->getNode());
666
-
667
-		// Post share event
668
-		$event = new GenericEvent($share);
669
-		$this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
670
-
671
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
672
-			$mailSend = $share->getMailSend();
673
-			if($mailSend === true) {
674
-				$user = $this->userManager->get($share->getSharedWith());
675
-				if ($user !== null) {
676
-					$emailAddress = $user->getEMailAddress();
677
-					if ($emailAddress !== null && $emailAddress !== '') {
678
-						$userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
679
-						$l = $this->l10nFactory->get('lib', $userLang);
680
-						$this->sendMailNotification(
681
-							$l,
682
-							$share->getNode()->getName(),
683
-							$this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
684
-							$share->getSharedBy(),
685
-							$emailAddress,
686
-							$share->getExpirationDate()
687
-						);
688
-						$this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
689
-					} else {
690
-						$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
691
-					}
692
-				} else {
693
-					$this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
694
-				}
695
-			} else {
696
-				$this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
697
-			}
698
-		}
699
-
700
-		return $share;
701
-	}
702
-
703
-	/**
704
-	 * @param IL10N $l Language of the recipient
705
-	 * @param string $filename file/folder name
706
-	 * @param string $link link to the file/folder
707
-	 * @param string $initiator user ID of share sender
708
-	 * @param string $shareWith email address of share receiver
709
-	 * @param \DateTime|null $expiration
710
-	 * @throws \Exception If mail couldn't be sent
711
-	 */
712
-	protected function sendMailNotification(IL10N $l,
713
-											$filename,
714
-											$link,
715
-											$initiator,
716
-											$shareWith,
717
-											\DateTime $expiration = null) {
718
-		$initiatorUser = $this->userManager->get($initiator);
719
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
720
-
721
-		$message = $this->mailer->createMessage();
722
-
723
-		$emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
724
-			'filename' => $filename,
725
-			'link' => $link,
726
-			'initiator' => $initiatorDisplayName,
727
-			'expiration' => $expiration,
728
-			'shareWith' => $shareWith,
729
-		]);
730
-
731
-		$emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
732
-		$emailTemplate->addHeader();
733
-		$emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
734
-		$text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
735
-
736
-		$emailTemplate->addBodyText(
737
-			$text . ' ' . $l->t('Click the button below to open it.'),
738
-			$text
739
-		);
740
-		$emailTemplate->addBodyButton(
741
-			$l->t('Open »%s«', [$filename]),
742
-			$link
743
-		);
744
-
745
-		$message->setTo([$shareWith]);
746
-
747
-		// The "From" contains the sharers name
748
-		$instanceName = $this->defaults->getName();
749
-		$senderName = $l->t(
750
-			'%s via %s',
751
-			[
752
-				$initiatorDisplayName,
753
-				$instanceName
754
-			]
755
-		);
756
-		$message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
757
-
758
-		// The "Reply-To" is set to the sharer if an mail address is configured
759
-		// also the default footer contains a "Do not reply" which needs to be adjusted.
760
-		$initiatorEmail = $initiatorUser->getEMailAddress();
761
-		if($initiatorEmail !== null) {
762
-			$message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
763
-			$emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
764
-		} else {
765
-			$emailTemplate->addFooter();
766
-		}
767
-
768
-		$message->useTemplate($emailTemplate);
769
-		$this->mailer->send($message);
770
-	}
771
-
772
-	/**
773
-	 * Update a share
774
-	 *
775
-	 * @param \OCP\Share\IShare $share
776
-	 * @return \OCP\Share\IShare The share object
777
-	 * @throws \InvalidArgumentException
778
-	 */
779
-	public function updateShare(\OCP\Share\IShare $share) {
780
-		$expirationDateUpdated = false;
781
-
782
-		$this->canShare($share);
783
-
784
-		try {
785
-			$originalShare = $this->getShareById($share->getFullId());
786
-		} catch (\UnexpectedValueException $e) {
787
-			throw new \InvalidArgumentException('Share does not have a full id');
788
-		}
789
-
790
-		// We can't change the share type!
791
-		if ($share->getShareType() !== $originalShare->getShareType()) {
792
-			throw new \InvalidArgumentException('Can’t change share type');
793
-		}
794
-
795
-		// We can only change the recipient on user shares
796
-		if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
797
-		    $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
798
-			throw new \InvalidArgumentException('Can only update recipient on user shares');
799
-		}
800
-
801
-		// Cannot share with the owner
802
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
803
-			$share->getSharedWith() === $share->getShareOwner()) {
804
-			throw new \InvalidArgumentException('Can’t share with the share owner');
805
-		}
806
-
807
-		$this->generalCreateChecks($share);
808
-
809
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
810
-			$this->userCreateChecks($share);
811
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
812
-			$this->groupCreateChecks($share);
813
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
814
-			$this->linkCreateChecks($share);
815
-
816
-			$this->updateSharePasswordIfNeeded($share, $originalShare);
817
-
818
-			if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
819
-				//Verify the expiration date
820
-				$this->validateExpirationDate($share);
821
-				$expirationDateUpdated = true;
822
-			}
823
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
824
-			$plainTextPassword = $share->getPassword();
825
-			if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
826
-				$plainTextPassword = null;
827
-			}
828
-		}
829
-
830
-		$this->pathCreateChecks($share->getNode());
831
-
832
-		// Now update the share!
833
-		$provider = $this->factory->getProviderForType($share->getShareType());
834
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
835
-			$share = $provider->update($share, $plainTextPassword);
836
-		} else {
837
-			$share = $provider->update($share);
838
-		}
839
-
840
-		if ($expirationDateUpdated === true) {
841
-			\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
842
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
843
-				'itemSource' => $share->getNode()->getId(),
844
-				'date' => $share->getExpirationDate(),
845
-				'uidOwner' => $share->getSharedBy(),
846
-			]);
847
-		}
848
-
849
-		if ($share->getPassword() !== $originalShare->getPassword()) {
850
-			\OC_Hook::emit('OCP\Share', 'post_update_password', [
851
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
-				'itemSource' => $share->getNode()->getId(),
853
-				'uidOwner' => $share->getSharedBy(),
854
-				'token' => $share->getToken(),
855
-				'disabled' => is_null($share->getPassword()),
856
-			]);
857
-		}
858
-
859
-		if ($share->getPermissions() !== $originalShare->getPermissions()) {
860
-			if ($this->userManager->userExists($share->getShareOwner())) {
861
-				$userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
862
-			} else {
863
-				$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
864
-			}
865
-			\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
866
-				'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
867
-				'itemSource' => $share->getNode()->getId(),
868
-				'shareType' => $share->getShareType(),
869
-				'shareWith' => $share->getSharedWith(),
870
-				'uidOwner' => $share->getSharedBy(),
871
-				'permissions' => $share->getPermissions(),
872
-				'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
873
-			));
874
-		}
875
-
876
-		return $share;
877
-	}
878
-
879
-	/**
880
-	 * Updates the password of the given share if it is not the same as the
881
-	 * password of the original share.
882
-	 *
883
-	 * @param \OCP\Share\IShare $share the share to update its password.
884
-	 * @param \OCP\Share\IShare $originalShare the original share to compare its
885
-	 *        password with.
886
-	 * @return boolean whether the password was updated or not.
887
-	 */
888
-	private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
889
-		// Password updated.
890
-		if ($share->getPassword() !== $originalShare->getPassword()) {
891
-			//Verify the password
892
-			$this->verifyPassword($share->getPassword());
893
-
894
-			// If a password is set. Hash it!
895
-			if ($share->getPassword() !== null) {
896
-				$share->setPassword($this->hasher->hash($share->getPassword()));
897
-
898
-				return true;
899
-			}
900
-		}
901
-
902
-		return false;
903
-	}
904
-
905
-	/**
906
-	 * Delete all the children of this share
907
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
908
-	 *
909
-	 * @param \OCP\Share\IShare $share
910
-	 * @return \OCP\Share\IShare[] List of deleted shares
911
-	 */
912
-	protected function deleteChildren(\OCP\Share\IShare $share) {
913
-		$deletedShares = [];
914
-
915
-		$provider = $this->factory->getProviderForType($share->getShareType());
916
-
917
-		foreach ($provider->getChildren($share) as $child) {
918
-			$deletedChildren = $this->deleteChildren($child);
919
-			$deletedShares = array_merge($deletedShares, $deletedChildren);
920
-
921
-			$provider->delete($child);
922
-			$deletedShares[] = $child;
923
-		}
924
-
925
-		return $deletedShares;
926
-	}
927
-
928
-	/**
929
-	 * Delete a share
930
-	 *
931
-	 * @param \OCP\Share\IShare $share
932
-	 * @throws ShareNotFound
933
-	 * @throws \InvalidArgumentException
934
-	 */
935
-	public function deleteShare(\OCP\Share\IShare $share) {
936
-
937
-		try {
938
-			$share->getFullId();
939
-		} catch (\UnexpectedValueException $e) {
940
-			throw new \InvalidArgumentException('Share does not have a full id');
941
-		}
942
-
943
-		$event = new GenericEvent($share);
944
-		$this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
945
-
946
-		// Get all children and delete them as well
947
-		$deletedShares = $this->deleteChildren($share);
948
-
949
-		// Do the actual delete
950
-		$provider = $this->factory->getProviderForType($share->getShareType());
951
-		$provider->delete($share);
952
-
953
-		// All the deleted shares caused by this delete
954
-		$deletedShares[] = $share;
955
-
956
-		// Emit post hook
957
-		$event->setArgument('deletedShares', $deletedShares);
958
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
959
-	}
960
-
961
-
962
-	/**
963
-	 * Unshare a file as the recipient.
964
-	 * This can be different from a regular delete for example when one of
965
-	 * the users in a groups deletes that share. But the provider should
966
-	 * handle this.
967
-	 *
968
-	 * @param \OCP\Share\IShare $share
969
-	 * @param string $recipientId
970
-	 */
971
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
972
-		list($providerId, ) = $this->splitFullId($share->getFullId());
973
-		$provider = $this->factory->getProvider($providerId);
974
-
975
-		$provider->deleteFromSelf($share, $recipientId);
976
-		$event = new GenericEvent($share);
977
-		$this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
978
-	}
979
-
980
-	/**
981
-	 * @inheritdoc
982
-	 */
983
-	public function moveShare(\OCP\Share\IShare $share, $recipientId) {
984
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
985
-			throw new \InvalidArgumentException('Can’t change target of link share');
986
-		}
987
-
988
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
989
-			throw new \InvalidArgumentException('Invalid recipient');
990
-		}
991
-
992
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
993
-			$sharedWith = $this->groupManager->get($share->getSharedWith());
994
-			if (is_null($sharedWith)) {
995
-				throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
996
-			}
997
-			$recipient = $this->userManager->get($recipientId);
998
-			if (!$sharedWith->inGroup($recipient)) {
999
-				throw new \InvalidArgumentException('Invalid recipient');
1000
-			}
1001
-		}
1002
-
1003
-		list($providerId, ) = $this->splitFullId($share->getFullId());
1004
-		$provider = $this->factory->getProvider($providerId);
1005
-
1006
-		$provider->move($share, $recipientId);
1007
-	}
1008
-
1009
-	public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1010
-		$providers = $this->factory->getAllProviders();
1011
-
1012
-		return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1013
-			$newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1014
-			foreach ($newShares as $fid => $data) {
1015
-				if (!isset($shares[$fid])) {
1016
-					$shares[$fid] = [];
1017
-				}
1018
-
1019
-				$shares[$fid] = array_merge($shares[$fid], $data);
1020
-			}
1021
-			return $shares;
1022
-		}, []);
1023
-	}
1024
-
1025
-	/**
1026
-	 * @inheritdoc
1027
-	 */
1028
-	public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1029
-		if ($path !== null &&
1030
-				!($path instanceof \OCP\Files\File) &&
1031
-				!($path instanceof \OCP\Files\Folder)) {
1032
-			throw new \InvalidArgumentException('invalid path');
1033
-		}
1034
-
1035
-		try {
1036
-			$provider = $this->factory->getProviderForType($shareType);
1037
-		} catch (ProviderException $e) {
1038
-			return [];
1039
-		}
1040
-
1041
-		$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1042
-
1043
-		/*
617
+            $share->setToken(
618
+                $this->secureRandom->generate(
619
+                    \OC\Share\Constants::TOKEN_LENGTH,
620
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
621
+                )
622
+            );
623
+
624
+            //Verify the expiration date
625
+            $this->validateExpirationDate($share);
626
+
627
+            //Verify the password
628
+            $this->verifyPassword($share->getPassword());
629
+
630
+            // If a password is set. Hash it!
631
+            if ($share->getPassword() !== null) {
632
+                $share->setPassword($this->hasher->hash($share->getPassword()));
633
+            }
634
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
635
+            $share->setToken(
636
+                $this->secureRandom->generate(
637
+                    \OC\Share\Constants::TOKEN_LENGTH,
638
+                    \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
639
+                )
640
+            );
641
+        }
642
+
643
+        // Cannot share with the owner
644
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
645
+            $share->getSharedWith() === $share->getShareOwner()) {
646
+            throw new \InvalidArgumentException('Can’t share with the share owner');
647
+        }
648
+
649
+        // Generate the target
650
+        $target = $this->config->getSystemValue('share_folder', '/') .'/'. $share->getNode()->getName();
651
+        $target = \OC\Files\Filesystem::normalizePath($target);
652
+        $share->setTarget($target);
653
+
654
+        // Pre share event
655
+        $event = new GenericEvent($share);
656
+        $a = $this->eventDispatcher->dispatch('OCP\Share::preShare', $event);
657
+        if ($event->isPropagationStopped() && $event->hasArgument('error')) {
658
+            throw new \Exception($event->getArgument('error'));
659
+        }
660
+
661
+        $oldShare = $share;
662
+        $provider = $this->factory->getProviderForType($share->getShareType());
663
+        $share = $provider->create($share);
664
+        //reuse the node we already have
665
+        $share->setNode($oldShare->getNode());
666
+
667
+        // Post share event
668
+        $event = new GenericEvent($share);
669
+        $this->eventDispatcher->dispatch('OCP\Share::postShare', $event);
670
+
671
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
672
+            $mailSend = $share->getMailSend();
673
+            if($mailSend === true) {
674
+                $user = $this->userManager->get($share->getSharedWith());
675
+                if ($user !== null) {
676
+                    $emailAddress = $user->getEMailAddress();
677
+                    if ($emailAddress !== null && $emailAddress !== '') {
678
+                        $userLang = $this->config->getUserValue($share->getSharedWith(), 'core', 'lang', null);
679
+                        $l = $this->l10nFactory->get('lib', $userLang);
680
+                        $this->sendMailNotification(
681
+                            $l,
682
+                            $share->getNode()->getName(),
683
+                            $this->urlGenerator->linkToRouteAbsolute('files.viewcontroller.showFile', ['fileid' => $share->getNode()->getId()]),
684
+                            $share->getSharedBy(),
685
+                            $emailAddress,
686
+                            $share->getExpirationDate()
687
+                        );
688
+                        $this->logger->debug('Send share notification to ' . $emailAddress . ' for share with ID ' . $share->getId(), ['app' => 'share']);
689
+                    } else {
690
+                        $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because email address is not set.', ['app' => 'share']);
691
+                    }
692
+                } else {
693
+                    $this->logger->debug('Share notification not send to ' . $share->getSharedWith() . ' because user could not be found.', ['app' => 'share']);
694
+                }
695
+            } else {
696
+                $this->logger->debug('Share notification not send because mailsend is false.', ['app' => 'share']);
697
+            }
698
+        }
699
+
700
+        return $share;
701
+    }
702
+
703
+    /**
704
+     * @param IL10N $l Language of the recipient
705
+     * @param string $filename file/folder name
706
+     * @param string $link link to the file/folder
707
+     * @param string $initiator user ID of share sender
708
+     * @param string $shareWith email address of share receiver
709
+     * @param \DateTime|null $expiration
710
+     * @throws \Exception If mail couldn't be sent
711
+     */
712
+    protected function sendMailNotification(IL10N $l,
713
+                                            $filename,
714
+                                            $link,
715
+                                            $initiator,
716
+                                            $shareWith,
717
+                                            \DateTime $expiration = null) {
718
+        $initiatorUser = $this->userManager->get($initiator);
719
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
720
+
721
+        $message = $this->mailer->createMessage();
722
+
723
+        $emailTemplate = $this->mailer->createEMailTemplate('files_sharing.RecipientNotification', [
724
+            'filename' => $filename,
725
+            'link' => $link,
726
+            'initiator' => $initiatorDisplayName,
727
+            'expiration' => $expiration,
728
+            'shareWith' => $shareWith,
729
+        ]);
730
+
731
+        $emailTemplate->setSubject($l->t('%s shared »%s« with you', array($initiatorDisplayName, $filename)));
732
+        $emailTemplate->addHeader();
733
+        $emailTemplate->addHeading($l->t('%s shared »%s« with you', [$initiatorDisplayName, $filename]), false);
734
+        $text = $l->t('%s shared »%s« with you.', [$initiatorDisplayName, $filename]);
735
+
736
+        $emailTemplate->addBodyText(
737
+            $text . ' ' . $l->t('Click the button below to open it.'),
738
+            $text
739
+        );
740
+        $emailTemplate->addBodyButton(
741
+            $l->t('Open »%s«', [$filename]),
742
+            $link
743
+        );
744
+
745
+        $message->setTo([$shareWith]);
746
+
747
+        // The "From" contains the sharers name
748
+        $instanceName = $this->defaults->getName();
749
+        $senderName = $l->t(
750
+            '%s via %s',
751
+            [
752
+                $initiatorDisplayName,
753
+                $instanceName
754
+            ]
755
+        );
756
+        $message->setFrom([\OCP\Util::getDefaultEmailAddress($instanceName) => $senderName]);
757
+
758
+        // The "Reply-To" is set to the sharer if an mail address is configured
759
+        // also the default footer contains a "Do not reply" which needs to be adjusted.
760
+        $initiatorEmail = $initiatorUser->getEMailAddress();
761
+        if($initiatorEmail !== null) {
762
+            $message->setReplyTo([$initiatorEmail => $initiatorDisplayName]);
763
+            $emailTemplate->addFooter($instanceName . ($this->defaults->getSlogan() !== '' ? ' - ' . $this->defaults->getSlogan() : ''));
764
+        } else {
765
+            $emailTemplate->addFooter();
766
+        }
767
+
768
+        $message->useTemplate($emailTemplate);
769
+        $this->mailer->send($message);
770
+    }
771
+
772
+    /**
773
+     * Update a share
774
+     *
775
+     * @param \OCP\Share\IShare $share
776
+     * @return \OCP\Share\IShare The share object
777
+     * @throws \InvalidArgumentException
778
+     */
779
+    public function updateShare(\OCP\Share\IShare $share) {
780
+        $expirationDateUpdated = false;
781
+
782
+        $this->canShare($share);
783
+
784
+        try {
785
+            $originalShare = $this->getShareById($share->getFullId());
786
+        } catch (\UnexpectedValueException $e) {
787
+            throw new \InvalidArgumentException('Share does not have a full id');
788
+        }
789
+
790
+        // We can't change the share type!
791
+        if ($share->getShareType() !== $originalShare->getShareType()) {
792
+            throw new \InvalidArgumentException('Can’t change share type');
793
+        }
794
+
795
+        // We can only change the recipient on user shares
796
+        if ($share->getSharedWith() !== $originalShare->getSharedWith() &&
797
+            $share->getShareType() !== \OCP\Share::SHARE_TYPE_USER) {
798
+            throw new \InvalidArgumentException('Can only update recipient on user shares');
799
+        }
800
+
801
+        // Cannot share with the owner
802
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER &&
803
+            $share->getSharedWith() === $share->getShareOwner()) {
804
+            throw new \InvalidArgumentException('Can’t share with the share owner');
805
+        }
806
+
807
+        $this->generalCreateChecks($share);
808
+
809
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
810
+            $this->userCreateChecks($share);
811
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
812
+            $this->groupCreateChecks($share);
813
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
814
+            $this->linkCreateChecks($share);
815
+
816
+            $this->updateSharePasswordIfNeeded($share, $originalShare);
817
+
818
+            if ($share->getExpirationDate() != $originalShare->getExpirationDate()) {
819
+                //Verify the expiration date
820
+                $this->validateExpirationDate($share);
821
+                $expirationDateUpdated = true;
822
+            }
823
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
824
+            $plainTextPassword = $share->getPassword();
825
+            if (!$this->updateSharePasswordIfNeeded($share, $originalShare)) {
826
+                $plainTextPassword = null;
827
+            }
828
+        }
829
+
830
+        $this->pathCreateChecks($share->getNode());
831
+
832
+        // Now update the share!
833
+        $provider = $this->factory->getProviderForType($share->getShareType());
834
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_EMAIL) {
835
+            $share = $provider->update($share, $plainTextPassword);
836
+        } else {
837
+            $share = $provider->update($share);
838
+        }
839
+
840
+        if ($expirationDateUpdated === true) {
841
+            \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', [
842
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
843
+                'itemSource' => $share->getNode()->getId(),
844
+                'date' => $share->getExpirationDate(),
845
+                'uidOwner' => $share->getSharedBy(),
846
+            ]);
847
+        }
848
+
849
+        if ($share->getPassword() !== $originalShare->getPassword()) {
850
+            \OC_Hook::emit('OCP\Share', 'post_update_password', [
851
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
852
+                'itemSource' => $share->getNode()->getId(),
853
+                'uidOwner' => $share->getSharedBy(),
854
+                'token' => $share->getToken(),
855
+                'disabled' => is_null($share->getPassword()),
856
+            ]);
857
+        }
858
+
859
+        if ($share->getPermissions() !== $originalShare->getPermissions()) {
860
+            if ($this->userManager->userExists($share->getShareOwner())) {
861
+                $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
862
+            } else {
863
+                $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
864
+            }
865
+            \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
866
+                'itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder',
867
+                'itemSource' => $share->getNode()->getId(),
868
+                'shareType' => $share->getShareType(),
869
+                'shareWith' => $share->getSharedWith(),
870
+                'uidOwner' => $share->getSharedBy(),
871
+                'permissions' => $share->getPermissions(),
872
+                'path' => $userFolder->getRelativePath($share->getNode()->getPath()),
873
+            ));
874
+        }
875
+
876
+        return $share;
877
+    }
878
+
879
+    /**
880
+     * Updates the password of the given share if it is not the same as the
881
+     * password of the original share.
882
+     *
883
+     * @param \OCP\Share\IShare $share the share to update its password.
884
+     * @param \OCP\Share\IShare $originalShare the original share to compare its
885
+     *        password with.
886
+     * @return boolean whether the password was updated or not.
887
+     */
888
+    private function updateSharePasswordIfNeeded(\OCP\Share\IShare $share, \OCP\Share\IShare $originalShare) {
889
+        // Password updated.
890
+        if ($share->getPassword() !== $originalShare->getPassword()) {
891
+            //Verify the password
892
+            $this->verifyPassword($share->getPassword());
893
+
894
+            // If a password is set. Hash it!
895
+            if ($share->getPassword() !== null) {
896
+                $share->setPassword($this->hasher->hash($share->getPassword()));
897
+
898
+                return true;
899
+            }
900
+        }
901
+
902
+        return false;
903
+    }
904
+
905
+    /**
906
+     * Delete all the children of this share
907
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
908
+     *
909
+     * @param \OCP\Share\IShare $share
910
+     * @return \OCP\Share\IShare[] List of deleted shares
911
+     */
912
+    protected function deleteChildren(\OCP\Share\IShare $share) {
913
+        $deletedShares = [];
914
+
915
+        $provider = $this->factory->getProviderForType($share->getShareType());
916
+
917
+        foreach ($provider->getChildren($share) as $child) {
918
+            $deletedChildren = $this->deleteChildren($child);
919
+            $deletedShares = array_merge($deletedShares, $deletedChildren);
920
+
921
+            $provider->delete($child);
922
+            $deletedShares[] = $child;
923
+        }
924
+
925
+        return $deletedShares;
926
+    }
927
+
928
+    /**
929
+     * Delete a share
930
+     *
931
+     * @param \OCP\Share\IShare $share
932
+     * @throws ShareNotFound
933
+     * @throws \InvalidArgumentException
934
+     */
935
+    public function deleteShare(\OCP\Share\IShare $share) {
936
+
937
+        try {
938
+            $share->getFullId();
939
+        } catch (\UnexpectedValueException $e) {
940
+            throw new \InvalidArgumentException('Share does not have a full id');
941
+        }
942
+
943
+        $event = new GenericEvent($share);
944
+        $this->eventDispatcher->dispatch('OCP\Share::preUnshare', $event);
945
+
946
+        // Get all children and delete them as well
947
+        $deletedShares = $this->deleteChildren($share);
948
+
949
+        // Do the actual delete
950
+        $provider = $this->factory->getProviderForType($share->getShareType());
951
+        $provider->delete($share);
952
+
953
+        // All the deleted shares caused by this delete
954
+        $deletedShares[] = $share;
955
+
956
+        // Emit post hook
957
+        $event->setArgument('deletedShares', $deletedShares);
958
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshare', $event);
959
+    }
960
+
961
+
962
+    /**
963
+     * Unshare a file as the recipient.
964
+     * This can be different from a regular delete for example when one of
965
+     * the users in a groups deletes that share. But the provider should
966
+     * handle this.
967
+     *
968
+     * @param \OCP\Share\IShare $share
969
+     * @param string $recipientId
970
+     */
971
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipientId) {
972
+        list($providerId, ) = $this->splitFullId($share->getFullId());
973
+        $provider = $this->factory->getProvider($providerId);
974
+
975
+        $provider->deleteFromSelf($share, $recipientId);
976
+        $event = new GenericEvent($share);
977
+        $this->eventDispatcher->dispatch('OCP\Share::postUnshareFromSelf', $event);
978
+    }
979
+
980
+    /**
981
+     * @inheritdoc
982
+     */
983
+    public function moveShare(\OCP\Share\IShare $share, $recipientId) {
984
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
985
+            throw new \InvalidArgumentException('Can’t change target of link share');
986
+        }
987
+
988
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() !== $recipientId) {
989
+            throw new \InvalidArgumentException('Invalid recipient');
990
+        }
991
+
992
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
993
+            $sharedWith = $this->groupManager->get($share->getSharedWith());
994
+            if (is_null($sharedWith)) {
995
+                throw new \InvalidArgumentException('Group "' . $share->getSharedWith() . '" does not exist');
996
+            }
997
+            $recipient = $this->userManager->get($recipientId);
998
+            if (!$sharedWith->inGroup($recipient)) {
999
+                throw new \InvalidArgumentException('Invalid recipient');
1000
+            }
1001
+        }
1002
+
1003
+        list($providerId, ) = $this->splitFullId($share->getFullId());
1004
+        $provider = $this->factory->getProvider($providerId);
1005
+
1006
+        $provider->move($share, $recipientId);
1007
+    }
1008
+
1009
+    public function getSharesInFolder($userId, Folder $node, $reshares = false) {
1010
+        $providers = $this->factory->getAllProviders();
1011
+
1012
+        return array_reduce($providers, function($shares, IShareProvider $provider) use ($userId, $node, $reshares) {
1013
+            $newShares = $provider->getSharesInFolder($userId, $node, $reshares);
1014
+            foreach ($newShares as $fid => $data) {
1015
+                if (!isset($shares[$fid])) {
1016
+                    $shares[$fid] = [];
1017
+                }
1018
+
1019
+                $shares[$fid] = array_merge($shares[$fid], $data);
1020
+            }
1021
+            return $shares;
1022
+        }, []);
1023
+    }
1024
+
1025
+    /**
1026
+     * @inheritdoc
1027
+     */
1028
+    public function getSharesBy($userId, $shareType, $path = null, $reshares = false, $limit = 50, $offset = 0) {
1029
+        if ($path !== null &&
1030
+                !($path instanceof \OCP\Files\File) &&
1031
+                !($path instanceof \OCP\Files\Folder)) {
1032
+            throw new \InvalidArgumentException('invalid path');
1033
+        }
1034
+
1035
+        try {
1036
+            $provider = $this->factory->getProviderForType($shareType);
1037
+        } catch (ProviderException $e) {
1038
+            return [];
1039
+        }
1040
+
1041
+        $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1042
+
1043
+        /*
1044 1044
 		 * Work around so we don't return expired shares but still follow
1045 1045
 		 * proper pagination.
1046 1046
 		 */
1047 1047
 
1048
-		$shares2 = [];
1049
-
1050
-		while(true) {
1051
-			$added = 0;
1052
-			foreach ($shares as $share) {
1053
-
1054
-				try {
1055
-					$this->checkExpireDate($share);
1056
-				} catch (ShareNotFound $e) {
1057
-					//Ignore since this basically means the share is deleted
1058
-					continue;
1059
-				}
1060
-
1061
-				$added++;
1062
-				$shares2[] = $share;
1063
-
1064
-				if (count($shares2) === $limit) {
1065
-					break;
1066
-				}
1067
-			}
1068
-
1069
-			// If we did not fetch more shares than the limit then there are no more shares
1070
-			if (count($shares) < $limit) {
1071
-				break;
1072
-			}
1073
-
1074
-			if (count($shares2) === $limit) {
1075
-				break;
1076
-			}
1077
-
1078
-			// If there was no limit on the select we are done
1079
-			if ($limit === -1) {
1080
-				break;
1081
-			}
1082
-
1083
-			$offset += $added;
1084
-
1085
-			// Fetch again $limit shares
1086
-			$shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1087
-
1088
-			// No more shares means we are done
1089
-			if (empty($shares)) {
1090
-				break;
1091
-			}
1092
-		}
1093
-
1094
-		$shares = $shares2;
1095
-
1096
-		return $shares;
1097
-	}
1098
-
1099
-	/**
1100
-	 * @inheritdoc
1101
-	 */
1102
-	public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1103
-		try {
1104
-			$provider = $this->factory->getProviderForType($shareType);
1105
-		} catch (ProviderException $e) {
1106
-			return [];
1107
-		}
1108
-
1109
-		$shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1110
-
1111
-		// remove all shares which are already expired
1112
-		foreach ($shares as $key => $share) {
1113
-			try {
1114
-				$this->checkExpireDate($share);
1115
-			} catch (ShareNotFound $e) {
1116
-				unset($shares[$key]);
1117
-			}
1118
-		}
1119
-
1120
-		return $shares;
1121
-	}
1122
-
1123
-	/**
1124
-	 * @inheritdoc
1125
-	 */
1126
-	public function getShareById($id, $recipient = null) {
1127
-		if ($id === null) {
1128
-			throw new ShareNotFound();
1129
-		}
1130
-
1131
-		list($providerId, $id) = $this->splitFullId($id);
1132
-
1133
-		try {
1134
-			$provider = $this->factory->getProvider($providerId);
1135
-		} catch (ProviderException $e) {
1136
-			throw new ShareNotFound();
1137
-		}
1138
-
1139
-		$share = $provider->getShareById($id, $recipient);
1140
-
1141
-		$this->checkExpireDate($share);
1142
-
1143
-		return $share;
1144
-	}
1145
-
1146
-	/**
1147
-	 * Get all the shares for a given path
1148
-	 *
1149
-	 * @param \OCP\Files\Node $path
1150
-	 * @param int $page
1151
-	 * @param int $perPage
1152
-	 *
1153
-	 * @return Share[]
1154
-	 */
1155
-	public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1156
-		return [];
1157
-	}
1158
-
1159
-	/**
1160
-	 * Get the share by token possible with password
1161
-	 *
1162
-	 * @param string $token
1163
-	 * @return Share
1164
-	 *
1165
-	 * @throws ShareNotFound
1166
-	 */
1167
-	public function getShareByToken($token) {
1168
-		$share = null;
1169
-		try {
1170
-			if($this->shareApiAllowLinks()) {
1171
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1172
-				$share = $provider->getShareByToken($token);
1173
-			}
1174
-		} catch (ProviderException $e) {
1175
-		} catch (ShareNotFound $e) {
1176
-		}
1177
-
1178
-
1179
-		// If it is not a link share try to fetch a federated share by token
1180
-		if ($share === null) {
1181
-			try {
1182
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1183
-				$share = $provider->getShareByToken($token);
1184
-			} catch (ProviderException $e) {
1185
-			} catch (ShareNotFound $e) {
1186
-			}
1187
-		}
1188
-
1189
-		// If it is not a link share try to fetch a mail share by token
1190
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1191
-			try {
1192
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1193
-				$share = $provider->getShareByToken($token);
1194
-			} catch (ProviderException $e) {
1195
-			} catch (ShareNotFound $e) {
1196
-			}
1197
-		}
1198
-
1199
-		if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1200
-			try {
1201
-				$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1202
-				$share = $provider->getShareByToken($token);
1203
-			} catch (ProviderException $e) {
1204
-			} catch (ShareNotFound $e) {
1205
-			}
1206
-		}
1207
-
1208
-		if ($share === null) {
1209
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1210
-		}
1211
-
1212
-		$this->checkExpireDate($share);
1213
-
1214
-		/*
1048
+        $shares2 = [];
1049
+
1050
+        while(true) {
1051
+            $added = 0;
1052
+            foreach ($shares as $share) {
1053
+
1054
+                try {
1055
+                    $this->checkExpireDate($share);
1056
+                } catch (ShareNotFound $e) {
1057
+                    //Ignore since this basically means the share is deleted
1058
+                    continue;
1059
+                }
1060
+
1061
+                $added++;
1062
+                $shares2[] = $share;
1063
+
1064
+                if (count($shares2) === $limit) {
1065
+                    break;
1066
+                }
1067
+            }
1068
+
1069
+            // If we did not fetch more shares than the limit then there are no more shares
1070
+            if (count($shares) < $limit) {
1071
+                break;
1072
+            }
1073
+
1074
+            if (count($shares2) === $limit) {
1075
+                break;
1076
+            }
1077
+
1078
+            // If there was no limit on the select we are done
1079
+            if ($limit === -1) {
1080
+                break;
1081
+            }
1082
+
1083
+            $offset += $added;
1084
+
1085
+            // Fetch again $limit shares
1086
+            $shares = $provider->getSharesBy($userId, $shareType, $path, $reshares, $limit, $offset);
1087
+
1088
+            // No more shares means we are done
1089
+            if (empty($shares)) {
1090
+                break;
1091
+            }
1092
+        }
1093
+
1094
+        $shares = $shares2;
1095
+
1096
+        return $shares;
1097
+    }
1098
+
1099
+    /**
1100
+     * @inheritdoc
1101
+     */
1102
+    public function getSharedWith($userId, $shareType, $node = null, $limit = 50, $offset = 0) {
1103
+        try {
1104
+            $provider = $this->factory->getProviderForType($shareType);
1105
+        } catch (ProviderException $e) {
1106
+            return [];
1107
+        }
1108
+
1109
+        $shares = $provider->getSharedWith($userId, $shareType, $node, $limit, $offset);
1110
+
1111
+        // remove all shares which are already expired
1112
+        foreach ($shares as $key => $share) {
1113
+            try {
1114
+                $this->checkExpireDate($share);
1115
+            } catch (ShareNotFound $e) {
1116
+                unset($shares[$key]);
1117
+            }
1118
+        }
1119
+
1120
+        return $shares;
1121
+    }
1122
+
1123
+    /**
1124
+     * @inheritdoc
1125
+     */
1126
+    public function getShareById($id, $recipient = null) {
1127
+        if ($id === null) {
1128
+            throw new ShareNotFound();
1129
+        }
1130
+
1131
+        list($providerId, $id) = $this->splitFullId($id);
1132
+
1133
+        try {
1134
+            $provider = $this->factory->getProvider($providerId);
1135
+        } catch (ProviderException $e) {
1136
+            throw new ShareNotFound();
1137
+        }
1138
+
1139
+        $share = $provider->getShareById($id, $recipient);
1140
+
1141
+        $this->checkExpireDate($share);
1142
+
1143
+        return $share;
1144
+    }
1145
+
1146
+    /**
1147
+     * Get all the shares for a given path
1148
+     *
1149
+     * @param \OCP\Files\Node $path
1150
+     * @param int $page
1151
+     * @param int $perPage
1152
+     *
1153
+     * @return Share[]
1154
+     */
1155
+    public function getSharesByPath(\OCP\Files\Node $path, $page=0, $perPage=50) {
1156
+        return [];
1157
+    }
1158
+
1159
+    /**
1160
+     * Get the share by token possible with password
1161
+     *
1162
+     * @param string $token
1163
+     * @return Share
1164
+     *
1165
+     * @throws ShareNotFound
1166
+     */
1167
+    public function getShareByToken($token) {
1168
+        $share = null;
1169
+        try {
1170
+            if($this->shareApiAllowLinks()) {
1171
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_LINK);
1172
+                $share = $provider->getShareByToken($token);
1173
+            }
1174
+        } catch (ProviderException $e) {
1175
+        } catch (ShareNotFound $e) {
1176
+        }
1177
+
1178
+
1179
+        // If it is not a link share try to fetch a federated share by token
1180
+        if ($share === null) {
1181
+            try {
1182
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_REMOTE);
1183
+                $share = $provider->getShareByToken($token);
1184
+            } catch (ProviderException $e) {
1185
+            } catch (ShareNotFound $e) {
1186
+            }
1187
+        }
1188
+
1189
+        // If it is not a link share try to fetch a mail share by token
1190
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_EMAIL)) {
1191
+            try {
1192
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_EMAIL);
1193
+                $share = $provider->getShareByToken($token);
1194
+            } catch (ProviderException $e) {
1195
+            } catch (ShareNotFound $e) {
1196
+            }
1197
+        }
1198
+
1199
+        if ($share === null && $this->shareProviderExists(\OCP\Share::SHARE_TYPE_CIRCLE)) {
1200
+            try {
1201
+                $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_CIRCLE);
1202
+                $share = $provider->getShareByToken($token);
1203
+            } catch (ProviderException $e) {
1204
+            } catch (ShareNotFound $e) {
1205
+            }
1206
+        }
1207
+
1208
+        if ($share === null) {
1209
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1210
+        }
1211
+
1212
+        $this->checkExpireDate($share);
1213
+
1214
+        /*
1215 1215
 		 * Reduce the permissions for link shares if public upload is not enabled
1216 1216
 		 */
1217
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1218
-			!$this->shareApiLinkAllowPublicUpload()) {
1219
-			$share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1220
-		}
1221
-
1222
-		return $share;
1223
-	}
1224
-
1225
-	protected function checkExpireDate($share) {
1226
-		if ($share->getExpirationDate() !== null &&
1227
-			$share->getExpirationDate() <= new \DateTime()) {
1228
-			$this->deleteShare($share);
1229
-			throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1230
-		}
1231
-
1232
-	}
1233
-
1234
-	/**
1235
-	 * Verify the password of a public share
1236
-	 *
1237
-	 * @param \OCP\Share\IShare $share
1238
-	 * @param string $password
1239
-	 * @return bool
1240
-	 */
1241
-	public function checkPassword(\OCP\Share\IShare $share, $password) {
1242
-		$passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1243
-			|| $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1244
-		if (!$passwordProtected) {
1245
-			//TODO maybe exception?
1246
-			return false;
1247
-		}
1248
-
1249
-		if ($password === null || $share->getPassword() === null) {
1250
-			return false;
1251
-		}
1252
-
1253
-		$newHash = '';
1254
-		if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1255
-			return false;
1256
-		}
1257
-
1258
-		if (!empty($newHash)) {
1259
-			$share->setPassword($newHash);
1260
-			$provider = $this->factory->getProviderForType($share->getShareType());
1261
-			$provider->update($share);
1262
-		}
1263
-
1264
-		return true;
1265
-	}
1266
-
1267
-	/**
1268
-	 * @inheritdoc
1269
-	 */
1270
-	public function userDeleted($uid) {
1271
-		$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];
1272
-
1273
-		foreach ($types as $type) {
1274
-			try {
1275
-				$provider = $this->factory->getProviderForType($type);
1276
-			} catch (ProviderException $e) {
1277
-				continue;
1278
-			}
1279
-			$provider->userDeleted($uid, $type);
1280
-		}
1281
-	}
1282
-
1283
-	/**
1284
-	 * @inheritdoc
1285
-	 */
1286
-	public function groupDeleted($gid) {
1287
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1288
-		$provider->groupDeleted($gid);
1289
-	}
1290
-
1291
-	/**
1292
-	 * @inheritdoc
1293
-	 */
1294
-	public function userDeletedFromGroup($uid, $gid) {
1295
-		$provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1296
-		$provider->userDeletedFromGroup($uid, $gid);
1297
-	}
1298
-
1299
-	/**
1300
-	 * Get access list to a path. This means
1301
-	 * all the users that can access a given path.
1302
-	 *
1303
-	 * Consider:
1304
-	 * -root
1305
-	 * |-folder1 (23)
1306
-	 *  |-folder2 (32)
1307
-	 *   |-fileA (42)
1308
-	 *
1309
-	 * fileA is shared with user1 and user1@server1
1310
-	 * folder2 is shared with group2 (user4 is a member of group2)
1311
-	 * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1312
-	 *
1313
-	 * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1314
-	 * [
1315
-	 *  users  => [
1316
-	 *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1317
-	 *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1318
-	 *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1319
-	 *  ],
1320
-	 *  remote => [
1321
-	 *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1322
-	 *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1323
-	 *  ],
1324
-	 *  public => bool
1325
-	 *  mail => bool
1326
-	 * ]
1327
-	 *
1328
-	 * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1329
-	 * [
1330
-	 *  users  => ['user1', 'user2', 'user4'],
1331
-	 *  remote => bool,
1332
-	 *  public => bool
1333
-	 *  mail => bool
1334
-	 * ]
1335
-	 *
1336
-	 * This is required for encryption/activity
1337
-	 *
1338
-	 * @param \OCP\Files\Node $path
1339
-	 * @param bool $recursive Should we check all parent folders as well
1340
-	 * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1341
-	 * @return array
1342
-	 */
1343
-	public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1344
-		$owner = $path->getOwner()->getUID();
1345
-
1346
-		if ($currentAccess) {
1347
-			$al = ['users' => [], 'remote' => [], 'public' => false];
1348
-		} else {
1349
-			$al = ['users' => [], 'remote' => false, 'public' => false];
1350
-		}
1351
-		if (!$this->userManager->userExists($owner)) {
1352
-			return $al;
1353
-		}
1354
-
1355
-		//Get node for the owner
1356
-		$userFolder = $this->rootFolder->getUserFolder($owner);
1357
-		if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1358
-			$path = $userFolder->getById($path->getId())[0];
1359
-		}
1360
-
1361
-		$providers = $this->factory->getAllProviders();
1362
-
1363
-		/** @var Node[] $nodes */
1364
-		$nodes = [];
1365
-
1366
-
1367
-		if ($currentAccess) {
1368
-			$ownerPath = $path->getPath();
1369
-			$ownerPath = explode('/', $ownerPath, 4);
1370
-			if (count($ownerPath) < 4) {
1371
-				$ownerPath = '';
1372
-			} else {
1373
-				$ownerPath = $ownerPath[3];
1374
-			}
1375
-			$al['users'][$owner] = [
1376
-				'node_id' => $path->getId(),
1377
-				'node_path' => '/' . $ownerPath,
1378
-			];
1379
-		} else {
1380
-			$al['users'][] = $owner;
1381
-		}
1382
-
1383
-		// Collect all the shares
1384
-		while ($path->getPath() !== $userFolder->getPath()) {
1385
-			$nodes[] = $path;
1386
-			if (!$recursive) {
1387
-				break;
1388
-			}
1389
-			$path = $path->getParent();
1390
-		}
1391
-
1392
-		foreach ($providers as $provider) {
1393
-			$tmp = $provider->getAccessList($nodes, $currentAccess);
1394
-
1395
-			foreach ($tmp as $k => $v) {
1396
-				if (isset($al[$k])) {
1397
-					if (is_array($al[$k])) {
1398
-						$al[$k] += $v;
1399
-					} else {
1400
-						$al[$k] = $al[$k] || $v;
1401
-					}
1402
-				} else {
1403
-					$al[$k] = $v;
1404
-				}
1405
-			}
1406
-		}
1407
-
1408
-		return $al;
1409
-	}
1410
-
1411
-	/**
1412
-	 * Create a new share
1413
-	 * @return \OCP\Share\IShare
1414
-	 */
1415
-	public function newShare() {
1416
-		return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1417
-	}
1418
-
1419
-	/**
1420
-	 * Is the share API enabled
1421
-	 *
1422
-	 * @return bool
1423
-	 */
1424
-	public function shareApiEnabled() {
1425
-		return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1426
-	}
1427
-
1428
-	/**
1429
-	 * Is public link sharing enabled
1430
-	 *
1431
-	 * @return bool
1432
-	 */
1433
-	public function shareApiAllowLinks() {
1434
-		return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1435
-	}
1436
-
1437
-	/**
1438
-	 * Is password on public link requires
1439
-	 *
1440
-	 * @return bool
1441
-	 */
1442
-	public function shareApiLinkEnforcePassword() {
1443
-		return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1444
-	}
1445
-
1446
-	/**
1447
-	 * Is default expire date enabled
1448
-	 *
1449
-	 * @return bool
1450
-	 */
1451
-	public function shareApiLinkDefaultExpireDate() {
1452
-		return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1453
-	}
1454
-
1455
-	/**
1456
-	 * Is default expire date enforced
1457
-	 *`
1458
-	 * @return bool
1459
-	 */
1460
-	public function shareApiLinkDefaultExpireDateEnforced() {
1461
-		return $this->shareApiLinkDefaultExpireDate() &&
1462
-			$this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1463
-	}
1464
-
1465
-	/**
1466
-	 * Number of default expire days
1467
-	 *shareApiLinkAllowPublicUpload
1468
-	 * @return int
1469
-	 */
1470
-	public function shareApiLinkDefaultExpireDays() {
1471
-		return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1472
-	}
1473
-
1474
-	/**
1475
-	 * Allow public upload on link shares
1476
-	 *
1477
-	 * @return bool
1478
-	 */
1479
-	public function shareApiLinkAllowPublicUpload() {
1480
-		return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1481
-	}
1482
-
1483
-	/**
1484
-	 * check if user can only share with group members
1485
-	 * @return bool
1486
-	 */
1487
-	public function shareWithGroupMembersOnly() {
1488
-		return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1489
-	}
1490
-
1491
-	/**
1492
-	 * Check if users can share with groups
1493
-	 * @return bool
1494
-	 */
1495
-	public function allowGroupSharing() {
1496
-		return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1497
-	}
1498
-
1499
-	/**
1500
-	 * Copied from \OC_Util::isSharingDisabledForUser
1501
-	 *
1502
-	 * TODO: Deprecate fuction from OC_Util
1503
-	 *
1504
-	 * @param string $userId
1505
-	 * @return bool
1506
-	 */
1507
-	public function sharingDisabledForUser($userId) {
1508
-		if ($userId === null) {
1509
-			return false;
1510
-		}
1511
-
1512
-		if (isset($this->sharingDisabledForUsersCache[$userId])) {
1513
-			return $this->sharingDisabledForUsersCache[$userId];
1514
-		}
1515
-
1516
-		if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1517
-			$groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1518
-			$excludedGroups = json_decode($groupsList);
1519
-			if (is_null($excludedGroups)) {
1520
-				$excludedGroups = explode(',', $groupsList);
1521
-				$newValue = json_encode($excludedGroups);
1522
-				$this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1523
-			}
1524
-			$user = $this->userManager->get($userId);
1525
-			$usersGroups = $this->groupManager->getUserGroupIds($user);
1526
-			if (!empty($usersGroups)) {
1527
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
1528
-				// if the user is only in groups which are disabled for sharing then
1529
-				// sharing is also disabled for the user
1530
-				if (empty($remainingGroups)) {
1531
-					$this->sharingDisabledForUsersCache[$userId] = true;
1532
-					return true;
1533
-				}
1534
-			}
1535
-		}
1536
-
1537
-		$this->sharingDisabledForUsersCache[$userId] = false;
1538
-		return false;
1539
-	}
1540
-
1541
-	/**
1542
-	 * @inheritdoc
1543
-	 */
1544
-	public function outgoingServer2ServerSharesAllowed() {
1545
-		return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1546
-	}
1547
-
1548
-	/**
1549
-	 * @inheritdoc
1550
-	 */
1551
-	public function shareProviderExists($shareType) {
1552
-		try {
1553
-			$this->factory->getProviderForType($shareType);
1554
-		} catch (ProviderException $e) {
1555
-			return false;
1556
-		}
1557
-
1558
-		return true;
1559
-	}
1217
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK &&
1218
+            !$this->shareApiLinkAllowPublicUpload()) {
1219
+            $share->setPermissions($share->getPermissions() & ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_UPDATE));
1220
+        }
1221
+
1222
+        return $share;
1223
+    }
1224
+
1225
+    protected function checkExpireDate($share) {
1226
+        if ($share->getExpirationDate() !== null &&
1227
+            $share->getExpirationDate() <= new \DateTime()) {
1228
+            $this->deleteShare($share);
1229
+            throw new ShareNotFound($this->l->t('The requested share does not exist anymore'));
1230
+        }
1231
+
1232
+    }
1233
+
1234
+    /**
1235
+     * Verify the password of a public share
1236
+     *
1237
+     * @param \OCP\Share\IShare $share
1238
+     * @param string $password
1239
+     * @return bool
1240
+     */
1241
+    public function checkPassword(\OCP\Share\IShare $share, $password) {
1242
+        $passwordProtected = $share->getShareType() !== \OCP\Share::SHARE_TYPE_LINK
1243
+            || $share->getShareType() !== \OCP\Share::SHARE_TYPE_EMAIL;
1244
+        if (!$passwordProtected) {
1245
+            //TODO maybe exception?
1246
+            return false;
1247
+        }
1248
+
1249
+        if ($password === null || $share->getPassword() === null) {
1250
+            return false;
1251
+        }
1252
+
1253
+        $newHash = '';
1254
+        if (!$this->hasher->verify($password, $share->getPassword(), $newHash)) {
1255
+            return false;
1256
+        }
1257
+
1258
+        if (!empty($newHash)) {
1259
+            $share->setPassword($newHash);
1260
+            $provider = $this->factory->getProviderForType($share->getShareType());
1261
+            $provider->update($share);
1262
+        }
1263
+
1264
+        return true;
1265
+    }
1266
+
1267
+    /**
1268
+     * @inheritdoc
1269
+     */
1270
+    public function userDeleted($uid) {
1271
+        $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];
1272
+
1273
+        foreach ($types as $type) {
1274
+            try {
1275
+                $provider = $this->factory->getProviderForType($type);
1276
+            } catch (ProviderException $e) {
1277
+                continue;
1278
+            }
1279
+            $provider->userDeleted($uid, $type);
1280
+        }
1281
+    }
1282
+
1283
+    /**
1284
+     * @inheritdoc
1285
+     */
1286
+    public function groupDeleted($gid) {
1287
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1288
+        $provider->groupDeleted($gid);
1289
+    }
1290
+
1291
+    /**
1292
+     * @inheritdoc
1293
+     */
1294
+    public function userDeletedFromGroup($uid, $gid) {
1295
+        $provider = $this->factory->getProviderForType(\OCP\Share::SHARE_TYPE_GROUP);
1296
+        $provider->userDeletedFromGroup($uid, $gid);
1297
+    }
1298
+
1299
+    /**
1300
+     * Get access list to a path. This means
1301
+     * all the users that can access a given path.
1302
+     *
1303
+     * Consider:
1304
+     * -root
1305
+     * |-folder1 (23)
1306
+     *  |-folder2 (32)
1307
+     *   |-fileA (42)
1308
+     *
1309
+     * fileA is shared with user1 and user1@server1
1310
+     * folder2 is shared with group2 (user4 is a member of group2)
1311
+     * folder1 is shared with user2 (renamed to "folder (1)") and user2@server2
1312
+     *
1313
+     * Then the access list to '/folder1/folder2/fileA' with $currentAccess is:
1314
+     * [
1315
+     *  users  => [
1316
+     *      'user1' => ['node_id' => 42, 'node_path' => '/fileA'],
1317
+     *      'user4' => ['node_id' => 32, 'node_path' => '/folder2'],
1318
+     *      'user2' => ['node_id' => 23, 'node_path' => '/folder (1)'],
1319
+     *  ],
1320
+     *  remote => [
1321
+     *      'user1@server1' => ['node_id' => 42, 'token' => 'SeCr3t'],
1322
+     *      'user2@server2' => ['node_id' => 23, 'token' => 'FooBaR'],
1323
+     *  ],
1324
+     *  public => bool
1325
+     *  mail => bool
1326
+     * ]
1327
+     *
1328
+     * The access list to '/folder1/folder2/fileA' **without** $currentAccess is:
1329
+     * [
1330
+     *  users  => ['user1', 'user2', 'user4'],
1331
+     *  remote => bool,
1332
+     *  public => bool
1333
+     *  mail => bool
1334
+     * ]
1335
+     *
1336
+     * This is required for encryption/activity
1337
+     *
1338
+     * @param \OCP\Files\Node $path
1339
+     * @param bool $recursive Should we check all parent folders as well
1340
+     * @param bool $currentAccess Ensure the recipient has access to the file (e.g. did not unshare it)
1341
+     * @return array
1342
+     */
1343
+    public function getAccessList(\OCP\Files\Node $path, $recursive = true, $currentAccess = false) {
1344
+        $owner = $path->getOwner()->getUID();
1345
+
1346
+        if ($currentAccess) {
1347
+            $al = ['users' => [], 'remote' => [], 'public' => false];
1348
+        } else {
1349
+            $al = ['users' => [], 'remote' => false, 'public' => false];
1350
+        }
1351
+        if (!$this->userManager->userExists($owner)) {
1352
+            return $al;
1353
+        }
1354
+
1355
+        //Get node for the owner
1356
+        $userFolder = $this->rootFolder->getUserFolder($owner);
1357
+        if ($path->getId() !== $userFolder->getId() && !$userFolder->isSubNode($path)) {
1358
+            $path = $userFolder->getById($path->getId())[0];
1359
+        }
1360
+
1361
+        $providers = $this->factory->getAllProviders();
1362
+
1363
+        /** @var Node[] $nodes */
1364
+        $nodes = [];
1365
+
1366
+
1367
+        if ($currentAccess) {
1368
+            $ownerPath = $path->getPath();
1369
+            $ownerPath = explode('/', $ownerPath, 4);
1370
+            if (count($ownerPath) < 4) {
1371
+                $ownerPath = '';
1372
+            } else {
1373
+                $ownerPath = $ownerPath[3];
1374
+            }
1375
+            $al['users'][$owner] = [
1376
+                'node_id' => $path->getId(),
1377
+                'node_path' => '/' . $ownerPath,
1378
+            ];
1379
+        } else {
1380
+            $al['users'][] = $owner;
1381
+        }
1382
+
1383
+        // Collect all the shares
1384
+        while ($path->getPath() !== $userFolder->getPath()) {
1385
+            $nodes[] = $path;
1386
+            if (!$recursive) {
1387
+                break;
1388
+            }
1389
+            $path = $path->getParent();
1390
+        }
1391
+
1392
+        foreach ($providers as $provider) {
1393
+            $tmp = $provider->getAccessList($nodes, $currentAccess);
1394
+
1395
+            foreach ($tmp as $k => $v) {
1396
+                if (isset($al[$k])) {
1397
+                    if (is_array($al[$k])) {
1398
+                        $al[$k] += $v;
1399
+                    } else {
1400
+                        $al[$k] = $al[$k] || $v;
1401
+                    }
1402
+                } else {
1403
+                    $al[$k] = $v;
1404
+                }
1405
+            }
1406
+        }
1407
+
1408
+        return $al;
1409
+    }
1410
+
1411
+    /**
1412
+     * Create a new share
1413
+     * @return \OCP\Share\IShare
1414
+     */
1415
+    public function newShare() {
1416
+        return new \OC\Share20\Share($this->rootFolder, $this->userManager);
1417
+    }
1418
+
1419
+    /**
1420
+     * Is the share API enabled
1421
+     *
1422
+     * @return bool
1423
+     */
1424
+    public function shareApiEnabled() {
1425
+        return $this->config->getAppValue('core', 'shareapi_enabled', 'yes') === 'yes';
1426
+    }
1427
+
1428
+    /**
1429
+     * Is public link sharing enabled
1430
+     *
1431
+     * @return bool
1432
+     */
1433
+    public function shareApiAllowLinks() {
1434
+        return $this->config->getAppValue('core', 'shareapi_allow_links', 'yes') === 'yes';
1435
+    }
1436
+
1437
+    /**
1438
+     * Is password on public link requires
1439
+     *
1440
+     * @return bool
1441
+     */
1442
+    public function shareApiLinkEnforcePassword() {
1443
+        return $this->config->getAppValue('core', 'shareapi_enforce_links_password', 'no') === 'yes';
1444
+    }
1445
+
1446
+    /**
1447
+     * Is default expire date enabled
1448
+     *
1449
+     * @return bool
1450
+     */
1451
+    public function shareApiLinkDefaultExpireDate() {
1452
+        return $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
1453
+    }
1454
+
1455
+    /**
1456
+     * Is default expire date enforced
1457
+     *`
1458
+     * @return bool
1459
+     */
1460
+    public function shareApiLinkDefaultExpireDateEnforced() {
1461
+        return $this->shareApiLinkDefaultExpireDate() &&
1462
+            $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
1463
+    }
1464
+
1465
+    /**
1466
+     * Number of default expire days
1467
+     *shareApiLinkAllowPublicUpload
1468
+     * @return int
1469
+     */
1470
+    public function shareApiLinkDefaultExpireDays() {
1471
+        return (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1472
+    }
1473
+
1474
+    /**
1475
+     * Allow public upload on link shares
1476
+     *
1477
+     * @return bool
1478
+     */
1479
+    public function shareApiLinkAllowPublicUpload() {
1480
+        return $this->config->getAppValue('core', 'shareapi_allow_public_upload', 'yes') === 'yes';
1481
+    }
1482
+
1483
+    /**
1484
+     * check if user can only share with group members
1485
+     * @return bool
1486
+     */
1487
+    public function shareWithGroupMembersOnly() {
1488
+        return $this->config->getAppValue('core', 'shareapi_only_share_with_group_members', 'no') === 'yes';
1489
+    }
1490
+
1491
+    /**
1492
+     * Check if users can share with groups
1493
+     * @return bool
1494
+     */
1495
+    public function allowGroupSharing() {
1496
+        return $this->config->getAppValue('core', 'shareapi_allow_group_sharing', 'yes') === 'yes';
1497
+    }
1498
+
1499
+    /**
1500
+     * Copied from \OC_Util::isSharingDisabledForUser
1501
+     *
1502
+     * TODO: Deprecate fuction from OC_Util
1503
+     *
1504
+     * @param string $userId
1505
+     * @return bool
1506
+     */
1507
+    public function sharingDisabledForUser($userId) {
1508
+        if ($userId === null) {
1509
+            return false;
1510
+        }
1511
+
1512
+        if (isset($this->sharingDisabledForUsersCache[$userId])) {
1513
+            return $this->sharingDisabledForUsersCache[$userId];
1514
+        }
1515
+
1516
+        if ($this->config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
1517
+            $groupsList = $this->config->getAppValue('core', 'shareapi_exclude_groups_list', '');
1518
+            $excludedGroups = json_decode($groupsList);
1519
+            if (is_null($excludedGroups)) {
1520
+                $excludedGroups = explode(',', $groupsList);
1521
+                $newValue = json_encode($excludedGroups);
1522
+                $this->config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
1523
+            }
1524
+            $user = $this->userManager->get($userId);
1525
+            $usersGroups = $this->groupManager->getUserGroupIds($user);
1526
+            if (!empty($usersGroups)) {
1527
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
1528
+                // if the user is only in groups which are disabled for sharing then
1529
+                // sharing is also disabled for the user
1530
+                if (empty($remainingGroups)) {
1531
+                    $this->sharingDisabledForUsersCache[$userId] = true;
1532
+                    return true;
1533
+                }
1534
+            }
1535
+        }
1536
+
1537
+        $this->sharingDisabledForUsersCache[$userId] = false;
1538
+        return false;
1539
+    }
1540
+
1541
+    /**
1542
+     * @inheritdoc
1543
+     */
1544
+    public function outgoingServer2ServerSharesAllowed() {
1545
+        return $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
1546
+    }
1547
+
1548
+    /**
1549
+     * @inheritdoc
1550
+     */
1551
+    public function shareProviderExists($shareType) {
1552
+        try {
1553
+            $this->factory->getProviderForType($shareType);
1554
+        } catch (ProviderException $e) {
1555
+            return false;
1556
+        }
1557
+
1558
+        return true;
1559
+    }
1560 1560
 
1561 1561
 }
Please login to merge, or discard this patch.