Completed
Pull Request — master (#4283)
by Robin
27:54 queued 14:59
created
lib/private/Share20/DefaultShareProvider.php 2 patches
Indentation   +990 added lines, -990 removed lines patch added patch discarded remove patch
@@ -47,1027 +47,1027 @@
 block discarded – undo
47 47
  */
48 48
 class DefaultShareProvider implements IShareProvider {
49 49
 
50
-	// Special share type for user modified group shares
51
-	const SHARE_TYPE_USERGROUP = 2;
52
-
53
-	/** @var IDBConnection */
54
-	private $dbConn;
55
-
56
-	/** @var IUserManager */
57
-	private $userManager;
58
-
59
-	/** @var IGroupManager */
60
-	private $groupManager;
61
-
62
-	/** @var IRootFolder */
63
-	private $rootFolder;
64
-
65
-	/**
66
-	 * DefaultShareProvider constructor.
67
-	 *
68
-	 * @param IDBConnection $connection
69
-	 * @param IUserManager $userManager
70
-	 * @param IGroupManager $groupManager
71
-	 * @param IRootFolder $rootFolder
72
-	 */
73
-	public function __construct(
74
-			IDBConnection $connection,
75
-			IUserManager $userManager,
76
-			IGroupManager $groupManager,
77
-			IRootFolder $rootFolder) {
78
-		$this->dbConn = $connection;
79
-		$this->userManager = $userManager;
80
-		$this->groupManager = $groupManager;
81
-		$this->rootFolder = $rootFolder;
82
-	}
83
-
84
-	/**
85
-	 * Return the identifier of this provider.
86
-	 *
87
-	 * @return string Containing only [a-zA-Z0-9]
88
-	 */
89
-	public function identifier() {
90
-		return 'ocinternal';
91
-	}
92
-
93
-	/**
94
-	 * Share a path
95
-	 *
96
-	 * @param \OCP\Share\IShare $share
97
-	 * @return \OCP\Share\IShare The share object
98
-	 * @throws ShareNotFound
99
-	 * @throws \Exception
100
-	 */
101
-	public function create(\OCP\Share\IShare $share) {
102
-		$qb = $this->dbConn->getQueryBuilder();
103
-
104
-		$qb->insert('share');
105
-		$qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
-
107
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
-			//Set the UID of the user we share with
109
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
-			//Set the GID of the group we share with
112
-			$qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
-			//Set the token of the share
115
-			$qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
-
117
-			//If a password is set store it
118
-			if ($share->getPassword() !== null) {
119
-				$qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
-			}
121
-
122
-			//If an expiration date is set store it
123
-			if ($share->getExpirationDate() !== null) {
124
-				$qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
-			}
126
-
127
-			if (method_exists($share, 'getParent')) {
128
-				$qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
-			}
130
-		} else {
131
-			throw new \Exception('invalid share type!');
132
-		}
133
-
134
-		// Set what is shares
135
-		$qb->setValue('item_type', $qb->createParameter('itemType'));
136
-		if ($share->getNode() instanceof \OCP\Files\File) {
137
-			$qb->setParameter('itemType', 'file');
138
-		} else {
139
-			$qb->setParameter('itemType', 'folder');
140
-		}
141
-
142
-		// Set the file id
143
-		$qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
-		$qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
-
146
-		// set the permissions
147
-		$qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
-
149
-		// Set who created this share
150
-		$qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
-
152
-		// Set who is the owner of this file/folder (and this the owner of the share)
153
-		$qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
-
155
-		// Set the file target
156
-		$qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
-
158
-		// Set the time this share was created
159
-		$qb->setValue('stime', $qb->createNamedParameter(time()));
160
-
161
-		// insert the data and fetch the id of the share
162
-		$this->dbConn->beginTransaction();
163
-		$qb->execute();
164
-		$id = $this->dbConn->lastInsertId('*PREFIX*share');
165
-
166
-		// Now fetch the inserted share and create a complete share object
167
-		$qb = $this->dbConn->getQueryBuilder();
168
-		$qb->select('*')
169
-			->from('share')
170
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
-
172
-		$cursor = $qb->execute();
173
-		$data = $cursor->fetch();
174
-		$this->dbConn->commit();
175
-		$cursor->closeCursor();
176
-
177
-		if ($data === false) {
178
-			throw new ShareNotFound();
179
-		}
180
-
181
-		$share = $this->createShare($data);
182
-		return $share;
183
-	}
184
-
185
-	/**
186
-	 * Update a share
187
-	 *
188
-	 * @param \OCP\Share\IShare $share
189
-	 * @return \OCP\Share\IShare The share object
190
-	 */
191
-	public function update(\OCP\Share\IShare $share) {
192
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
-			/*
50
+    // Special share type for user modified group shares
51
+    const SHARE_TYPE_USERGROUP = 2;
52
+
53
+    /** @var IDBConnection */
54
+    private $dbConn;
55
+
56
+    /** @var IUserManager */
57
+    private $userManager;
58
+
59
+    /** @var IGroupManager */
60
+    private $groupManager;
61
+
62
+    /** @var IRootFolder */
63
+    private $rootFolder;
64
+
65
+    /**
66
+     * DefaultShareProvider constructor.
67
+     *
68
+     * @param IDBConnection $connection
69
+     * @param IUserManager $userManager
70
+     * @param IGroupManager $groupManager
71
+     * @param IRootFolder $rootFolder
72
+     */
73
+    public function __construct(
74
+            IDBConnection $connection,
75
+            IUserManager $userManager,
76
+            IGroupManager $groupManager,
77
+            IRootFolder $rootFolder) {
78
+        $this->dbConn = $connection;
79
+        $this->userManager = $userManager;
80
+        $this->groupManager = $groupManager;
81
+        $this->rootFolder = $rootFolder;
82
+    }
83
+
84
+    /**
85
+     * Return the identifier of this provider.
86
+     *
87
+     * @return string Containing only [a-zA-Z0-9]
88
+     */
89
+    public function identifier() {
90
+        return 'ocinternal';
91
+    }
92
+
93
+    /**
94
+     * Share a path
95
+     *
96
+     * @param \OCP\Share\IShare $share
97
+     * @return \OCP\Share\IShare The share object
98
+     * @throws ShareNotFound
99
+     * @throws \Exception
100
+     */
101
+    public function create(\OCP\Share\IShare $share) {
102
+        $qb = $this->dbConn->getQueryBuilder();
103
+
104
+        $qb->insert('share');
105
+        $qb->setValue('share_type', $qb->createNamedParameter($share->getShareType()));
106
+
107
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
108
+            //Set the UID of the user we share with
109
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
110
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
111
+            //Set the GID of the group we share with
112
+            $qb->setValue('share_with', $qb->createNamedParameter($share->getSharedWith()));
113
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
114
+            //Set the token of the share
115
+            $qb->setValue('token', $qb->createNamedParameter($share->getToken()));
116
+
117
+            //If a password is set store it
118
+            if ($share->getPassword() !== null) {
119
+                $qb->setValue('password', $qb->createNamedParameter($share->getPassword()));
120
+            }
121
+
122
+            //If an expiration date is set store it
123
+            if ($share->getExpirationDate() !== null) {
124
+                $qb->setValue('expiration', $qb->createNamedParameter($share->getExpirationDate(), 'datetime'));
125
+            }
126
+
127
+            if (method_exists($share, 'getParent')) {
128
+                $qb->setValue('parent', $qb->createNamedParameter($share->getParent()));
129
+            }
130
+        } else {
131
+            throw new \Exception('invalid share type!');
132
+        }
133
+
134
+        // Set what is shares
135
+        $qb->setValue('item_type', $qb->createParameter('itemType'));
136
+        if ($share->getNode() instanceof \OCP\Files\File) {
137
+            $qb->setParameter('itemType', 'file');
138
+        } else {
139
+            $qb->setParameter('itemType', 'folder');
140
+        }
141
+
142
+        // Set the file id
143
+        $qb->setValue('item_source', $qb->createNamedParameter($share->getNode()->getId()));
144
+        $qb->setValue('file_source', $qb->createNamedParameter($share->getNode()->getId()));
145
+
146
+        // set the permissions
147
+        $qb->setValue('permissions', $qb->createNamedParameter($share->getPermissions()));
148
+
149
+        // Set who created this share
150
+        $qb->setValue('uid_initiator', $qb->createNamedParameter($share->getSharedBy()));
151
+
152
+        // Set who is the owner of this file/folder (and this the owner of the share)
153
+        $qb->setValue('uid_owner', $qb->createNamedParameter($share->getShareOwner()));
154
+
155
+        // Set the file target
156
+        $qb->setValue('file_target', $qb->createNamedParameter($share->getTarget()));
157
+
158
+        // Set the time this share was created
159
+        $qb->setValue('stime', $qb->createNamedParameter(time()));
160
+
161
+        // insert the data and fetch the id of the share
162
+        $this->dbConn->beginTransaction();
163
+        $qb->execute();
164
+        $id = $this->dbConn->lastInsertId('*PREFIX*share');
165
+
166
+        // Now fetch the inserted share and create a complete share object
167
+        $qb = $this->dbConn->getQueryBuilder();
168
+        $qb->select('*')
169
+            ->from('share')
170
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
171
+
172
+        $cursor = $qb->execute();
173
+        $data = $cursor->fetch();
174
+        $this->dbConn->commit();
175
+        $cursor->closeCursor();
176
+
177
+        if ($data === false) {
178
+            throw new ShareNotFound();
179
+        }
180
+
181
+        $share = $this->createShare($data);
182
+        return $share;
183
+    }
184
+
185
+    /**
186
+     * Update a share
187
+     *
188
+     * @param \OCP\Share\IShare $share
189
+     * @return \OCP\Share\IShare The share object
190
+     */
191
+    public function update(\OCP\Share\IShare $share) {
192
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
193
+            /*
194 194
 			 * We allow updating the recipient on user shares.
195 195
 			 */
196
-			$qb = $this->dbConn->getQueryBuilder();
197
-			$qb->update('share')
198
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
-				->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
-				->execute();
207
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
-			$qb = $this->dbConn->getQueryBuilder();
209
-			$qb->update('share')
210
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
-				->execute();
218
-
219
-			/*
196
+            $qb = $this->dbConn->getQueryBuilder();
197
+            $qb->update('share')
198
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
199
+                ->set('share_with', $qb->createNamedParameter($share->getSharedWith()))
200
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
201
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
202
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
203
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
204
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
205
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
206
+                ->execute();
207
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
208
+            $qb = $this->dbConn->getQueryBuilder();
209
+            $qb->update('share')
210
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
211
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
212
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
213
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
214
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
215
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
216
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
217
+                ->execute();
218
+
219
+            /*
220 220
 			 * Update all user defined group shares
221 221
 			 */
222
-			$qb = $this->dbConn->getQueryBuilder();
223
-			$qb->update('share')
224
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
-				->execute();
231
-
232
-			/*
222
+            $qb = $this->dbConn->getQueryBuilder();
223
+            $qb->update('share')
224
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
225
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
226
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
227
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
228
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
229
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
230
+                ->execute();
231
+
232
+            /*
233 233
 			 * Now update the permissions for all children that have not set it to 0
234 234
 			 */
235
-			$qb = $this->dbConn->getQueryBuilder();
236
-			$qb->update('share')
237
-				->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
-				->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
-				->execute();
241
-
242
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
-			$qb = $this->dbConn->getQueryBuilder();
244
-			$qb->update('share')
245
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
-				->set('password', $qb->createNamedParameter($share->getPassword()))
247
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
-				->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
-				->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
-				->set('token', $qb->createNamedParameter($share->getToken()))
253
-				->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
-				->execute();
255
-		}
256
-
257
-		return $share;
258
-	}
259
-
260
-	/**
261
-	 * Get all children of this share
262
-	 * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
-	 *
264
-	 * @param \OCP\Share\IShare $parent
265
-	 * @return \OCP\Share\IShare[]
266
-	 */
267
-	public function getChildren(\OCP\Share\IShare $parent) {
268
-		$children = [];
269
-
270
-		$qb = $this->dbConn->getQueryBuilder();
271
-		$qb->select('*')
272
-			->from('share')
273
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
-			->andWhere(
275
-				$qb->expr()->in(
276
-					'share_type',
277
-					$qb->createNamedParameter([
278
-						\OCP\Share::SHARE_TYPE_USER,
279
-						\OCP\Share::SHARE_TYPE_GROUP,
280
-						\OCP\Share::SHARE_TYPE_LINK,
281
-					], IQueryBuilder::PARAM_INT_ARRAY)
282
-				)
283
-			)
284
-			->andWhere($qb->expr()->orX(
285
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
-			))
288
-			->orderBy('id');
289
-
290
-		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
292
-			$children[] = $this->createShare($data);
293
-		}
294
-		$cursor->closeCursor();
295
-
296
-		return $children;
297
-	}
298
-
299
-	/**
300
-	 * Delete a share
301
-	 *
302
-	 * @param \OCP\Share\IShare $share
303
-	 */
304
-	public function delete(\OCP\Share\IShare $share) {
305
-		$qb = $this->dbConn->getQueryBuilder();
306
-		$qb->delete('share')
307
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
-
309
-		/*
235
+            $qb = $this->dbConn->getQueryBuilder();
236
+            $qb->update('share')
237
+                ->where($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
238
+                ->andWhere($qb->expr()->neq('permissions', $qb->createNamedParameter(0)))
239
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
240
+                ->execute();
241
+
242
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
243
+            $qb = $this->dbConn->getQueryBuilder();
244
+            $qb->update('share')
245
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
246
+                ->set('password', $qb->createNamedParameter($share->getPassword()))
247
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
248
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
249
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
250
+                ->set('item_source', $qb->createNamedParameter($share->getNode()->getId()))
251
+                ->set('file_source', $qb->createNamedParameter($share->getNode()->getId()))
252
+                ->set('token', $qb->createNamedParameter($share->getToken()))
253
+                ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
254
+                ->execute();
255
+        }
256
+
257
+        return $share;
258
+    }
259
+
260
+    /**
261
+     * Get all children of this share
262
+     * FIXME: remove once https://github.com/owncloud/core/pull/21660 is in
263
+     *
264
+     * @param \OCP\Share\IShare $parent
265
+     * @return \OCP\Share\IShare[]
266
+     */
267
+    public function getChildren(\OCP\Share\IShare $parent) {
268
+        $children = [];
269
+
270
+        $qb = $this->dbConn->getQueryBuilder();
271
+        $qb->select('*')
272
+            ->from('share')
273
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
274
+            ->andWhere(
275
+                $qb->expr()->in(
276
+                    'share_type',
277
+                    $qb->createNamedParameter([
278
+                        \OCP\Share::SHARE_TYPE_USER,
279
+                        \OCP\Share::SHARE_TYPE_GROUP,
280
+                        \OCP\Share::SHARE_TYPE_LINK,
281
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
282
+                )
283
+            )
284
+            ->andWhere($qb->expr()->orX(
285
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
286
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
287
+            ))
288
+            ->orderBy('id');
289
+
290
+        $cursor = $qb->execute();
291
+        while($data = $cursor->fetch()) {
292
+            $children[] = $this->createShare($data);
293
+        }
294
+        $cursor->closeCursor();
295
+
296
+        return $children;
297
+    }
298
+
299
+    /**
300
+     * Delete a share
301
+     *
302
+     * @param \OCP\Share\IShare $share
303
+     */
304
+    public function delete(\OCP\Share\IShare $share) {
305
+        $qb = $this->dbConn->getQueryBuilder();
306
+        $qb->delete('share')
307
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())));
308
+
309
+        /*
310 310
 		 * If the share is a group share delete all possible
311 311
 		 * user defined groups shares.
312 312
 		 */
313
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
-			$qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
-		}
316
-
317
-		$qb->execute();
318
-	}
319
-
320
-	/**
321
-	 * Unshare a share from the recipient. If this is a group share
322
-	 * this means we need a special entry in the share db.
323
-	 *
324
-	 * @param \OCP\Share\IShare $share
325
-	 * @param string $recipient UserId of recipient
326
-	 * @throws BackendError
327
-	 * @throws ProviderException
328
-	 */
329
-	public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
-
332
-			$group = $this->groupManager->get($share->getSharedWith());
333
-			$user = $this->userManager->get($recipient);
334
-
335
-			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
-			}
338
-
339
-			if (!$group->inGroup($user)) {
340
-				throw new ProviderException('Recipient not in receiving group');
341
-			}
342
-
343
-			// Try to fetch user specific share
344
-			$qb = $this->dbConn->getQueryBuilder();
345
-			$stmt = $qb->select('*')
346
-				->from('share')
347
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
-				->andWhere($qb->expr()->orX(
351
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
-				))
354
-				->execute();
355
-
356
-			$data = $stmt->fetch();
357
-
358
-			/*
313
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
314
+            $qb->orWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())));
315
+        }
316
+
317
+        $qb->execute();
318
+    }
319
+
320
+    /**
321
+     * Unshare a share from the recipient. If this is a group share
322
+     * this means we need a special entry in the share db.
323
+     *
324
+     * @param \OCP\Share\IShare $share
325
+     * @param string $recipient UserId of recipient
326
+     * @throws BackendError
327
+     * @throws ProviderException
328
+     */
329
+    public function deleteFromSelf(\OCP\Share\IShare $share, $recipient) {
330
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
331
+
332
+            $group = $this->groupManager->get($share->getSharedWith());
333
+            $user = $this->userManager->get($recipient);
334
+
335
+            if (is_null($group)) {
336
+                throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
337
+            }
338
+
339
+            if (!$group->inGroup($user)) {
340
+                throw new ProviderException('Recipient not in receiving group');
341
+            }
342
+
343
+            // Try to fetch user specific share
344
+            $qb = $this->dbConn->getQueryBuilder();
345
+            $stmt = $qb->select('*')
346
+                ->from('share')
347
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
348
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
349
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
350
+                ->andWhere($qb->expr()->orX(
351
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
352
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
353
+                ))
354
+                ->execute();
355
+
356
+            $data = $stmt->fetch();
357
+
358
+            /*
359 359
 			 * Check if there already is a user specific group share.
360 360
 			 * If there is update it (if required).
361 361
 			 */
362
-			if ($data === false) {
363
-				$qb = $this->dbConn->getQueryBuilder();
364
-
365
-				$type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
-
367
-				//Insert new share
368
-				$qb->insert('share')
369
-					->values([
370
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
-						'share_with' => $qb->createNamedParameter($recipient),
372
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
-						'parent' => $qb->createNamedParameter($share->getId()),
375
-						'item_type' => $qb->createNamedParameter($type),
376
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
379
-						'permissions' => $qb->createNamedParameter(0),
380
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
-					])->execute();
382
-
383
-			} else if ($data['permissions'] !== 0) {
384
-
385
-				// Update existing usergroup share
386
-				$qb = $this->dbConn->getQueryBuilder();
387
-				$qb->update('share')
388
-					->set('permissions', $qb->createNamedParameter(0))
389
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
-					->execute();
391
-			}
392
-
393
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
-
395
-			if ($share->getSharedWith() !== $recipient) {
396
-				throw new ProviderException('Recipient does not match');
397
-			}
398
-
399
-			// We can just delete user and link shares
400
-			$this->delete($share);
401
-		} else {
402
-			throw new ProviderException('Invalid shareType');
403
-		}
404
-	}
405
-
406
-	/**
407
-	 * @inheritdoc
408
-	 */
409
-	public function move(\OCP\Share\IShare $share, $recipient) {
410
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
-			// Just update the target
412
-			$qb = $this->dbConn->getQueryBuilder();
413
-			$qb->update('share')
414
-				->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
-				->execute();
417
-
418
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
-
420
-			// Check if there is a usergroup share
421
-			$qb = $this->dbConn->getQueryBuilder();
422
-			$stmt = $qb->select('id')
423
-				->from('share')
424
-				->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
-				->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
-				->andWhere($qb->expr()->orX(
428
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
-				))
431
-				->setMaxResults(1)
432
-				->execute();
433
-
434
-			$data = $stmt->fetch();
435
-			$stmt->closeCursor();
436
-
437
-			if ($data === false) {
438
-				// No usergroup share yet. Create one.
439
-				$qb = $this->dbConn->getQueryBuilder();
440
-				$qb->insert('share')
441
-					->values([
442
-						'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
-						'share_with' => $qb->createNamedParameter($recipient),
444
-						'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
-						'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
-						'parent' => $qb->createNamedParameter($share->getId()),
447
-						'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
-						'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
-						'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
-						'file_target' => $qb->createNamedParameter($share->getTarget()),
451
-						'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
-						'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
-					])->execute();
454
-			} else {
455
-				// Already a usergroup share. Update it.
456
-				$qb = $this->dbConn->getQueryBuilder();
457
-				$qb->update('share')
458
-					->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
-					->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
-					->execute();
461
-			}
462
-		}
463
-
464
-		return $share;
465
-	}
466
-
467
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
468
-		$qb = $this->dbConn->getQueryBuilder();
469
-		$qb->select('*')
470
-			->from('share', 's')
471
-			->andWhere($qb->expr()->orX(
472
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
-			));
475
-
476
-		$qb->andWhere($qb->expr()->orX(
477
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
-			$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
-		));
481
-
482
-		/**
483
-		 * Reshares for this user are shares where they are the owner.
484
-		 */
485
-		if ($reshares === false) {
486
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
-		} else {
488
-			$qb->andWhere(
489
-				$qb->expr()->orX(
490
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
-				)
493
-			);
494
-		}
495
-
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
-
499
-		$qb->orderBy('id');
500
-
501
-		$cursor = $qb->execute();
502
-		$shares = [];
503
-		while ($data = $cursor->fetch()) {
504
-			$shares[$data['fileid']][] = $this->createShare($data);
505
-		}
506
-		$cursor->closeCursor();
507
-
508
-		return $shares;
509
-	}
510
-
511
-	/**
512
-	 * @inheritdoc
513
-	 */
514
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
-		$qb = $this->dbConn->getQueryBuilder();
516
-		$qb->select('*')
517
-			->from('share')
518
-			->andWhere($qb->expr()->orX(
519
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
-			));
522
-
523
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
-
525
-		/**
526
-		 * Reshares for this user are shares where they are the owner.
527
-		 */
528
-		if ($reshares === false) {
529
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
-		} else {
531
-			$qb->andWhere(
532
-				$qb->expr()->orX(
533
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
-				)
536
-			);
537
-		}
538
-
539
-		if ($node !== null) {
540
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
-		}
542
-
543
-		if ($limit !== -1) {
544
-			$qb->setMaxResults($limit);
545
-		}
546
-
547
-		$qb->setFirstResult($offset);
548
-		$qb->orderBy('id');
549
-
550
-		$cursor = $qb->execute();
551
-		$shares = [];
552
-		while($data = $cursor->fetch()) {
553
-			$shares[] = $this->createShare($data);
554
-		}
555
-		$cursor->closeCursor();
556
-
557
-		return $shares;
558
-	}
559
-
560
-	/**
561
-	 * @inheritdoc
562
-	 */
563
-	public function getShareById($id, $recipientId = null) {
564
-		$qb = $this->dbConn->getQueryBuilder();
565
-
566
-		$qb->select('*')
567
-			->from('share')
568
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
-			->andWhere(
570
-				$qb->expr()->in(
571
-					'share_type',
572
-					$qb->createNamedParameter([
573
-						\OCP\Share::SHARE_TYPE_USER,
574
-						\OCP\Share::SHARE_TYPE_GROUP,
575
-						\OCP\Share::SHARE_TYPE_LINK,
576
-					], IQueryBuilder::PARAM_INT_ARRAY)
577
-				)
578
-			)
579
-			->andWhere($qb->expr()->orX(
580
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
-			));
583
-
584
-		$cursor = $qb->execute();
585
-		$data = $cursor->fetch();
586
-		$cursor->closeCursor();
587
-
588
-		if ($data === false) {
589
-			throw new ShareNotFound();
590
-		}
591
-
592
-		try {
593
-			$share = $this->createShare($data);
594
-		} catch (InvalidShare $e) {
595
-			throw new ShareNotFound();
596
-		}
597
-
598
-		// If the recipient is set for a group share resolve to that user
599
-		if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
-			$share = $this->resolveGroupShares([$share], $recipientId)[0];
601
-		}
602
-
603
-		return $share;
604
-	}
605
-
606
-	/**
607
-	 * Get shares for a given path
608
-	 *
609
-	 * @param \OCP\Files\Node $path
610
-	 * @return \OCP\Share\IShare[]
611
-	 */
612
-	public function getSharesByPath(Node $path) {
613
-		$qb = $this->dbConn->getQueryBuilder();
614
-
615
-		$cursor = $qb->select('*')
616
-			->from('share')
617
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
-			->andWhere(
619
-				$qb->expr()->orX(
620
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
-				)
623
-			)
624
-			->andWhere($qb->expr()->orX(
625
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
-			))
628
-			->execute();
629
-
630
-		$shares = [];
631
-		while($data = $cursor->fetch()) {
632
-			$shares[] = $this->createShare($data);
633
-		}
634
-		$cursor->closeCursor();
635
-
636
-		return $shares;
637
-	}
638
-
639
-	/**
640
-	 * Returns whether the given database result can be interpreted as
641
-	 * a share with accessible file (not trashed, not deleted)
642
-	 */
643
-	private function isAccessibleResult($data) {
644
-		// exclude shares leading to deleted file entries
645
-		if ($data['fileid'] === null) {
646
-			return false;
647
-		}
648
-
649
-		// exclude shares leading to trashbin on home storages
650
-		$pathSections = explode('/', $data['path'], 2);
651
-		// FIXME: would not detect rare md5'd home storage case properly
652
-		if ($pathSections[0] !== 'files'
653
-		    	&& in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
-			return false;
655
-		}
656
-		return true;
657
-	}
658
-
659
-	/**
660
-	 * @inheritdoc
661
-	 */
662
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
-		/** @var Share[] $shares */
664
-		$shares = [];
665
-
666
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
-			//Get shares directly with this user
668
-			$qb = $this->dbConn->getQueryBuilder();
669
-			$qb->select('s.*',
670
-				'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
-				'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
-				'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
-			)
674
-				->selectAlias('st.id', 'storage_string_id')
675
-				->from('share', 's')
676
-				->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
-				->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
-
679
-			// Order by id
680
-			$qb->orderBy('s.id');
681
-
682
-			// Set limit and offset
683
-			if ($limit !== -1) {
684
-				$qb->setMaxResults($limit);
685
-			}
686
-			$qb->setFirstResult($offset);
687
-
688
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
-				->andWhere($qb->expr()->orX(
691
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
-				));
694
-
695
-			// Filter by node if provided
696
-			if ($node !== null) {
697
-				$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
-			}
699
-
700
-			$cursor = $qb->execute();
701
-
702
-			while($data = $cursor->fetch()) {
703
-				if ($this->isAccessibleResult($data)) {
704
-					$shares[] = $this->createShare($data);
705
-				}
706
-			}
707
-			$cursor->closeCursor();
708
-
709
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
-			$user = $this->userManager->get($userId);
711
-			$allGroups = $this->groupManager->getUserGroups($user);
712
-
713
-			/** @var Share[] $shares2 */
714
-			$shares2 = [];
715
-
716
-			$start = 0;
717
-			while(true) {
718
-				$groups = array_slice($allGroups, $start, 100);
719
-				$start += 100;
720
-
721
-				if ($groups === []) {
722
-					break;
723
-				}
724
-
725
-				$qb = $this->dbConn->getQueryBuilder();
726
-				$qb->select('s.*',
727
-					'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
-					'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
-					'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
-				)
731
-					->selectAlias('st.id', 'storage_string_id')
732
-					->from('share', 's')
733
-					->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
-					->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
-					->orderBy('s.id')
736
-					->setFirstResult(0);
737
-
738
-				if ($limit !== -1) {
739
-					$qb->setMaxResults($limit - count($shares));
740
-				}
741
-
742
-				// Filter by node if provided
743
-				if ($node !== null) {
744
-					$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
-				}
746
-
747
-				$groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
-
749
-				$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
-					->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
-						$groups,
752
-						IQueryBuilder::PARAM_STR_ARRAY
753
-					)))
754
-					->andWhere($qb->expr()->orX(
755
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
-						$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
-					));
758
-
759
-				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
761
-					if ($offset > 0) {
762
-						$offset--;
763
-						continue;
764
-					}
765
-
766
-					if ($this->isAccessibleResult($data)) {
767
-						$shares2[] = $this->createShare($data);
768
-					}
769
-				}
770
-				$cursor->closeCursor();
771
-			}
772
-
773
-			/*
362
+            if ($data === false) {
363
+                $qb = $this->dbConn->getQueryBuilder();
364
+
365
+                $type = $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder';
366
+
367
+                //Insert new share
368
+                $qb->insert('share')
369
+                    ->values([
370
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
371
+                        'share_with' => $qb->createNamedParameter($recipient),
372
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
373
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
374
+                        'parent' => $qb->createNamedParameter($share->getId()),
375
+                        'item_type' => $qb->createNamedParameter($type),
376
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
377
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
378
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
379
+                        'permissions' => $qb->createNamedParameter(0),
380
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
381
+                    ])->execute();
382
+
383
+            } else if ($data['permissions'] !== 0) {
384
+
385
+                // Update existing usergroup share
386
+                $qb = $this->dbConn->getQueryBuilder();
387
+                $qb->update('share')
388
+                    ->set('permissions', $qb->createNamedParameter(0))
389
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
390
+                    ->execute();
391
+            }
392
+
393
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
394
+
395
+            if ($share->getSharedWith() !== $recipient) {
396
+                throw new ProviderException('Recipient does not match');
397
+            }
398
+
399
+            // We can just delete user and link shares
400
+            $this->delete($share);
401
+        } else {
402
+            throw new ProviderException('Invalid shareType');
403
+        }
404
+    }
405
+
406
+    /**
407
+     * @inheritdoc
408
+     */
409
+    public function move(\OCP\Share\IShare $share, $recipient) {
410
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
411
+            // Just update the target
412
+            $qb = $this->dbConn->getQueryBuilder();
413
+            $qb->update('share')
414
+                ->set('file_target', $qb->createNamedParameter($share->getTarget()))
415
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
416
+                ->execute();
417
+
418
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
419
+
420
+            // Check if there is a usergroup share
421
+            $qb = $this->dbConn->getQueryBuilder();
422
+            $stmt = $qb->select('id')
423
+                ->from('share')
424
+                ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
425
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($recipient)))
426
+                ->andWhere($qb->expr()->eq('parent', $qb->createNamedParameter($share->getId())))
427
+                ->andWhere($qb->expr()->orX(
428
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
429
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
430
+                ))
431
+                ->setMaxResults(1)
432
+                ->execute();
433
+
434
+            $data = $stmt->fetch();
435
+            $stmt->closeCursor();
436
+
437
+            if ($data === false) {
438
+                // No usergroup share yet. Create one.
439
+                $qb = $this->dbConn->getQueryBuilder();
440
+                $qb->insert('share')
441
+                    ->values([
442
+                        'share_type' => $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP),
443
+                        'share_with' => $qb->createNamedParameter($recipient),
444
+                        'uid_owner' => $qb->createNamedParameter($share->getShareOwner()),
445
+                        'uid_initiator' => $qb->createNamedParameter($share->getSharedBy()),
446
+                        'parent' => $qb->createNamedParameter($share->getId()),
447
+                        'item_type' => $qb->createNamedParameter($share->getNode() instanceof File ? 'file' : 'folder'),
448
+                        'item_source' => $qb->createNamedParameter($share->getNode()->getId()),
449
+                        'file_source' => $qb->createNamedParameter($share->getNode()->getId()),
450
+                        'file_target' => $qb->createNamedParameter($share->getTarget()),
451
+                        'permissions' => $qb->createNamedParameter($share->getPermissions()),
452
+                        'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()),
453
+                    ])->execute();
454
+            } else {
455
+                // Already a usergroup share. Update it.
456
+                $qb = $this->dbConn->getQueryBuilder();
457
+                $qb->update('share')
458
+                    ->set('file_target', $qb->createNamedParameter($share->getTarget()))
459
+                    ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id'])))
460
+                    ->execute();
461
+            }
462
+        }
463
+
464
+        return $share;
465
+    }
466
+
467
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
468
+        $qb = $this->dbConn->getQueryBuilder();
469
+        $qb->select('*')
470
+            ->from('share', 's')
471
+            ->andWhere($qb->expr()->orX(
472
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
473
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
474
+            ));
475
+
476
+        $qb->andWhere($qb->expr()->orX(
477
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
478
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
479
+            $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK))
480
+        ));
481
+
482
+        /**
483
+         * Reshares for this user are shares where they are the owner.
484
+         */
485
+        if ($reshares === false) {
486
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
487
+        } else {
488
+            $qb->andWhere(
489
+                $qb->expr()->orX(
490
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
491
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
492
+                )
493
+            );
494
+        }
495
+
496
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498
+
499
+        $qb->orderBy('id');
500
+
501
+        $cursor = $qb->execute();
502
+        $shares = [];
503
+        while ($data = $cursor->fetch()) {
504
+            $shares[$data['fileid']][] = $this->createShare($data);
505
+        }
506
+        $cursor->closeCursor();
507
+
508
+        return $shares;
509
+    }
510
+
511
+    /**
512
+     * @inheritdoc
513
+     */
514
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
515
+        $qb = $this->dbConn->getQueryBuilder();
516
+        $qb->select('*')
517
+            ->from('share')
518
+            ->andWhere($qb->expr()->orX(
519
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
520
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
521
+            ));
522
+
523
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter($shareType)));
524
+
525
+        /**
526
+         * Reshares for this user are shares where they are the owner.
527
+         */
528
+        if ($reshares === false) {
529
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
530
+        } else {
531
+            $qb->andWhere(
532
+                $qb->expr()->orX(
533
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
534
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
535
+                )
536
+            );
537
+        }
538
+
539
+        if ($node !== null) {
540
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
541
+        }
542
+
543
+        if ($limit !== -1) {
544
+            $qb->setMaxResults($limit);
545
+        }
546
+
547
+        $qb->setFirstResult($offset);
548
+        $qb->orderBy('id');
549
+
550
+        $cursor = $qb->execute();
551
+        $shares = [];
552
+        while($data = $cursor->fetch()) {
553
+            $shares[] = $this->createShare($data);
554
+        }
555
+        $cursor->closeCursor();
556
+
557
+        return $shares;
558
+    }
559
+
560
+    /**
561
+     * @inheritdoc
562
+     */
563
+    public function getShareById($id, $recipientId = null) {
564
+        $qb = $this->dbConn->getQueryBuilder();
565
+
566
+        $qb->select('*')
567
+            ->from('share')
568
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
569
+            ->andWhere(
570
+                $qb->expr()->in(
571
+                    'share_type',
572
+                    $qb->createNamedParameter([
573
+                        \OCP\Share::SHARE_TYPE_USER,
574
+                        \OCP\Share::SHARE_TYPE_GROUP,
575
+                        \OCP\Share::SHARE_TYPE_LINK,
576
+                    ], IQueryBuilder::PARAM_INT_ARRAY)
577
+                )
578
+            )
579
+            ->andWhere($qb->expr()->orX(
580
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
581
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
582
+            ));
583
+
584
+        $cursor = $qb->execute();
585
+        $data = $cursor->fetch();
586
+        $cursor->closeCursor();
587
+
588
+        if ($data === false) {
589
+            throw new ShareNotFound();
590
+        }
591
+
592
+        try {
593
+            $share = $this->createShare($data);
594
+        } catch (InvalidShare $e) {
595
+            throw new ShareNotFound();
596
+        }
597
+
598
+        // If the recipient is set for a group share resolve to that user
599
+        if ($recipientId !== null && $share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
600
+            $share = $this->resolveGroupShares([$share], $recipientId)[0];
601
+        }
602
+
603
+        return $share;
604
+    }
605
+
606
+    /**
607
+     * Get shares for a given path
608
+     *
609
+     * @param \OCP\Files\Node $path
610
+     * @return \OCP\Share\IShare[]
611
+     */
612
+    public function getSharesByPath(Node $path) {
613
+        $qb = $this->dbConn->getQueryBuilder();
614
+
615
+        $cursor = $qb->select('*')
616
+            ->from('share')
617
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
618
+            ->andWhere(
619
+                $qb->expr()->orX(
620
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)),
621
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP))
622
+                )
623
+            )
624
+            ->andWhere($qb->expr()->orX(
625
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
626
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
627
+            ))
628
+            ->execute();
629
+
630
+        $shares = [];
631
+        while($data = $cursor->fetch()) {
632
+            $shares[] = $this->createShare($data);
633
+        }
634
+        $cursor->closeCursor();
635
+
636
+        return $shares;
637
+    }
638
+
639
+    /**
640
+     * Returns whether the given database result can be interpreted as
641
+     * a share with accessible file (not trashed, not deleted)
642
+     */
643
+    private function isAccessibleResult($data) {
644
+        // exclude shares leading to deleted file entries
645
+        if ($data['fileid'] === null) {
646
+            return false;
647
+        }
648
+
649
+        // exclude shares leading to trashbin on home storages
650
+        $pathSections = explode('/', $data['path'], 2);
651
+        // FIXME: would not detect rare md5'd home storage case properly
652
+        if ($pathSections[0] !== 'files'
653
+                && in_array(explode(':', $data['storage_string_id'], 2)[0], array('home', 'object'))) {
654
+            return false;
655
+        }
656
+        return true;
657
+    }
658
+
659
+    /**
660
+     * @inheritdoc
661
+     */
662
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
663
+        /** @var Share[] $shares */
664
+        $shares = [];
665
+
666
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
667
+            //Get shares directly with this user
668
+            $qb = $this->dbConn->getQueryBuilder();
669
+            $qb->select('s.*',
670
+                'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
671
+                'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
672
+                'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
673
+            )
674
+                ->selectAlias('st.id', 'storage_string_id')
675
+                ->from('share', 's')
676
+                ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
677
+                ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'));
678
+
679
+            // Order by id
680
+            $qb->orderBy('s.id');
681
+
682
+            // Set limit and offset
683
+            if ($limit !== -1) {
684
+                $qb->setMaxResults($limit);
685
+            }
686
+            $qb->setFirstResult($offset);
687
+
688
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)))
689
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
690
+                ->andWhere($qb->expr()->orX(
691
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
692
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
693
+                ));
694
+
695
+            // Filter by node if provided
696
+            if ($node !== null) {
697
+                $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
698
+            }
699
+
700
+            $cursor = $qb->execute();
701
+
702
+            while($data = $cursor->fetch()) {
703
+                if ($this->isAccessibleResult($data)) {
704
+                    $shares[] = $this->createShare($data);
705
+                }
706
+            }
707
+            $cursor->closeCursor();
708
+
709
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
710
+            $user = $this->userManager->get($userId);
711
+            $allGroups = $this->groupManager->getUserGroups($user);
712
+
713
+            /** @var Share[] $shares2 */
714
+            $shares2 = [];
715
+
716
+            $start = 0;
717
+            while(true) {
718
+                $groups = array_slice($allGroups, $start, 100);
719
+                $start += 100;
720
+
721
+                if ($groups === []) {
722
+                    break;
723
+                }
724
+
725
+                $qb = $this->dbConn->getQueryBuilder();
726
+                $qb->select('s.*',
727
+                    'f.fileid', 'f.path', 'f.permissions AS f_permissions', 'f.storage', 'f.path_hash',
728
+                    'f.parent AS f_parent', 'f.name', 'f.mimetype', 'f.mimepart', 'f.size', 'f.mtime', 'f.storage_mtime',
729
+                    'f.encrypted', 'f.unencrypted_size', 'f.etag', 'f.checksum'
730
+                )
731
+                    ->selectAlias('st.id', 'storage_string_id')
732
+                    ->from('share', 's')
733
+                    ->leftJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'))
734
+                    ->leftJoin('f', 'storages', 'st', $qb->expr()->eq('f.storage', 'st.numeric_id'))
735
+                    ->orderBy('s.id')
736
+                    ->setFirstResult(0);
737
+
738
+                if ($limit !== -1) {
739
+                    $qb->setMaxResults($limit - count($shares));
740
+                }
741
+
742
+                // Filter by node if provided
743
+                if ($node !== null) {
744
+                    $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
745
+                }
746
+
747
+                $groups = array_map(function(IGroup $group) { return $group->getGID(); }, $groups);
748
+
749
+                $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
750
+                    ->andWhere($qb->expr()->in('share_with', $qb->createNamedParameter(
751
+                        $groups,
752
+                        IQueryBuilder::PARAM_STR_ARRAY
753
+                    )))
754
+                    ->andWhere($qb->expr()->orX(
755
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
756
+                        $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
757
+                    ));
758
+
759
+                $cursor = $qb->execute();
760
+                while($data = $cursor->fetch()) {
761
+                    if ($offset > 0) {
762
+                        $offset--;
763
+                        continue;
764
+                    }
765
+
766
+                    if ($this->isAccessibleResult($data)) {
767
+                        $shares2[] = $this->createShare($data);
768
+                    }
769
+                }
770
+                $cursor->closeCursor();
771
+            }
772
+
773
+            /*
774 774
  			 * Resolve all group shares to user specific shares
775 775
  			 */
776
-			$shares = $this->resolveGroupShares($shares2, $userId);
777
-		} else {
778
-			throw new BackendError('Invalid backend');
779
-		}
780
-
781
-
782
-		return $shares;
783
-	}
784
-
785
-	/**
786
-	 * Get a share by token
787
-	 *
788
-	 * @param string $token
789
-	 * @return \OCP\Share\IShare
790
-	 * @throws ShareNotFound
791
-	 */
792
-	public function getShareByToken($token) {
793
-		$qb = $this->dbConn->getQueryBuilder();
794
-
795
-		$cursor = $qb->select('*')
796
-			->from('share')
797
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
-			->andWhere($qb->expr()->orX(
800
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
-			))
803
-			->execute();
804
-
805
-		$data = $cursor->fetch();
806
-
807
-		if ($data === false) {
808
-			throw new ShareNotFound();
809
-		}
810
-
811
-		try {
812
-			$share = $this->createShare($data);
813
-		} catch (InvalidShare $e) {
814
-			throw new ShareNotFound();
815
-		}
816
-
817
-		return $share;
818
-	}
819
-
820
-	/**
821
-	 * Create a share object from an database row
822
-	 *
823
-	 * @param mixed[] $data
824
-	 * @return \OCP\Share\IShare
825
-	 * @throws InvalidShare
826
-	 */
827
-	private function createShare($data) {
828
-		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
832
-			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
834
-
835
-		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
837
-		$share->setShareTime($shareTime);
838
-
839
-		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
-			$share->setSharedWith($data['share_with']);
841
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
-			$share->setSharedWith($data['share_with']);
843
-		} else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
-			$share->setPassword($data['password']);
845
-			$share->setToken($data['token']);
846
-		}
847
-
848
-		$share->setSharedBy($data['uid_initiator']);
849
-		$share->setShareOwner($data['uid_owner']);
850
-
851
-		$share->setNodeId((int)$data['file_source']);
852
-		$share->setNodeType($data['item_type']);
853
-
854
-		if ($data['expiration'] !== null) {
855
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
-			$share->setExpirationDate($expiration);
857
-		}
858
-
859
-		if (isset($data['f_permissions'])) {
860
-			$entryData = $data;
861
-			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
863
-			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
-				\OC::$server->getMimeTypeLoader()));
865
-		}
866
-
867
-		$share->setProviderId($this->identifier());
868
-
869
-		return $share;
870
-	}
871
-
872
-	/**
873
-	 * @param Share[] $shares
874
-	 * @param $userId
875
-	 * @return Share[] The updates shares if no update is found for a share return the original
876
-	 */
877
-	private function resolveGroupShares($shares, $userId) {
878
-		$result = [];
879
-
880
-		$start = 0;
881
-		while(true) {
882
-			/** @var Share[] $shareSlice */
883
-			$shareSlice = array_slice($shares, $start, 100);
884
-			$start += 100;
885
-
886
-			if ($shareSlice === []) {
887
-				break;
888
-			}
889
-
890
-			/** @var int[] $ids */
891
-			$ids = [];
892
-			/** @var Share[] $shareMap */
893
-			$shareMap = [];
894
-
895
-			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
897
-				$shareMap[$share->getId()] = $share;
898
-			}
899
-
900
-			$qb = $this->dbConn->getQueryBuilder();
901
-
902
-			$query = $qb->select('*')
903
-				->from('share')
904
-				->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
-				->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
-				->andWhere($qb->expr()->orX(
907
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
-					$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
-				));
910
-
911
-			$stmt = $query->execute();
912
-
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
-				$shareMap[$data['parent']]->setTarget($data['file_target']);
916
-			}
917
-
918
-			$stmt->closeCursor();
919
-
920
-			foreach ($shareMap as $share) {
921
-				$result[] = $share;
922
-			}
923
-		}
924
-
925
-		return $result;
926
-	}
927
-
928
-	/**
929
-	 * A user is deleted from the system
930
-	 * So clean up the relevant shares.
931
-	 *
932
-	 * @param string $uid
933
-	 * @param int $shareType
934
-	 */
935
-	public function userDeleted($uid, $shareType) {
936
-		$qb = $this->dbConn->getQueryBuilder();
937
-
938
-		$qb->delete('share');
939
-
940
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
-			/*
776
+            $shares = $this->resolveGroupShares($shares2, $userId);
777
+        } else {
778
+            throw new BackendError('Invalid backend');
779
+        }
780
+
781
+
782
+        return $shares;
783
+    }
784
+
785
+    /**
786
+     * Get a share by token
787
+     *
788
+     * @param string $token
789
+     * @return \OCP\Share\IShare
790
+     * @throws ShareNotFound
791
+     */
792
+    public function getShareByToken($token) {
793
+        $qb = $this->dbConn->getQueryBuilder();
794
+
795
+        $cursor = $qb->select('*')
796
+            ->from('share')
797
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)))
798
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
799
+            ->andWhere($qb->expr()->orX(
800
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
801
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
802
+            ))
803
+            ->execute();
804
+
805
+        $data = $cursor->fetch();
806
+
807
+        if ($data === false) {
808
+            throw new ShareNotFound();
809
+        }
810
+
811
+        try {
812
+            $share = $this->createShare($data);
813
+        } catch (InvalidShare $e) {
814
+            throw new ShareNotFound();
815
+        }
816
+
817
+        return $share;
818
+    }
819
+
820
+    /**
821
+     * Create a share object from an database row
822
+     *
823
+     * @param mixed[] $data
824
+     * @return \OCP\Share\IShare
825
+     * @throws InvalidShare
826
+     */
827
+    private function createShare($data) {
828
+        $share = new Share($this->rootFolder, $this->userManager);
829
+        $share->setId((int)$data['id'])
830
+            ->setShareType((int)$data['share_type'])
831
+            ->setPermissions((int)$data['permissions'])
832
+            ->setTarget($data['file_target'])
833
+            ->setMailSend((bool)$data['mail_send']);
834
+
835
+        $shareTime = new \DateTime();
836
+        $shareTime->setTimestamp((int)$data['stime']);
837
+        $share->setShareTime($shareTime);
838
+
839
+        if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
840
+            $share->setSharedWith($data['share_with']);
841
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
842
+            $share->setSharedWith($data['share_with']);
843
+        } else if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
844
+            $share->setPassword($data['password']);
845
+            $share->setToken($data['token']);
846
+        }
847
+
848
+        $share->setSharedBy($data['uid_initiator']);
849
+        $share->setShareOwner($data['uid_owner']);
850
+
851
+        $share->setNodeId((int)$data['file_source']);
852
+        $share->setNodeType($data['item_type']);
853
+
854
+        if ($data['expiration'] !== null) {
855
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
856
+            $share->setExpirationDate($expiration);
857
+        }
858
+
859
+        if (isset($data['f_permissions'])) {
860
+            $entryData = $data;
861
+            $entryData['permissions'] = $entryData['f_permissions'];
862
+            $entryData['parent'] = $entryData['f_parent'];;
863
+            $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864
+                \OC::$server->getMimeTypeLoader()));
865
+        }
866
+
867
+        $share->setProviderId($this->identifier());
868
+
869
+        return $share;
870
+    }
871
+
872
+    /**
873
+     * @param Share[] $shares
874
+     * @param $userId
875
+     * @return Share[] The updates shares if no update is found for a share return the original
876
+     */
877
+    private function resolveGroupShares($shares, $userId) {
878
+        $result = [];
879
+
880
+        $start = 0;
881
+        while(true) {
882
+            /** @var Share[] $shareSlice */
883
+            $shareSlice = array_slice($shares, $start, 100);
884
+            $start += 100;
885
+
886
+            if ($shareSlice === []) {
887
+                break;
888
+            }
889
+
890
+            /** @var int[] $ids */
891
+            $ids = [];
892
+            /** @var Share[] $shareMap */
893
+            $shareMap = [];
894
+
895
+            foreach ($shareSlice as $share) {
896
+                $ids[] = (int)$share->getId();
897
+                $shareMap[$share->getId()] = $share;
898
+            }
899
+
900
+            $qb = $this->dbConn->getQueryBuilder();
901
+
902
+            $query = $qb->select('*')
903
+                ->from('share')
904
+                ->where($qb->expr()->in('parent', $qb->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)))
905
+                ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)))
906
+                ->andWhere($qb->expr()->orX(
907
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
908
+                    $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
909
+                ));
910
+
911
+            $stmt = $query->execute();
912
+
913
+            while($data = $stmt->fetch()) {
914
+                $shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
915
+                $shareMap[$data['parent']]->setTarget($data['file_target']);
916
+            }
917
+
918
+            $stmt->closeCursor();
919
+
920
+            foreach ($shareMap as $share) {
921
+                $result[] = $share;
922
+            }
923
+        }
924
+
925
+        return $result;
926
+    }
927
+
928
+    /**
929
+     * A user is deleted from the system
930
+     * So clean up the relevant shares.
931
+     *
932
+     * @param string $uid
933
+     * @param int $shareType
934
+     */
935
+    public function userDeleted($uid, $shareType) {
936
+        $qb = $this->dbConn->getQueryBuilder();
937
+
938
+        $qb->delete('share');
939
+
940
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER) {
941
+            /*
942 942
 			 * Delete all user shares that are owned by this user
943 943
 			 * or that are received by this user
944 944
 			 */
945 945
 
946
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
946
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_USER)));
947 947
 
948
-			$qb->andWhere(
949
-				$qb->expr()->orX(
950
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
-				)
953
-			);
954
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
-			/*
948
+            $qb->andWhere(
949
+                $qb->expr()->orX(
950
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
951
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
952
+                )
953
+            );
954
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_GROUP) {
955
+            /*
956 956
 			 * Delete all group shares that are owned by this user
957 957
 			 * Or special user group shares that are received by this user
958 958
 			 */
959
-			$qb->where(
960
-				$qb->expr()->andX(
961
-					$qb->expr()->orX(
962
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
-						$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
-					),
965
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
-				)
967
-			);
968
-
969
-			$qb->orWhere(
970
-				$qb->expr()->andX(
971
-					$qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
-					$qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
-				)
974
-			);
975
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
-			/*
959
+            $qb->where(
960
+                $qb->expr()->andX(
961
+                    $qb->expr()->orX(
962
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)),
963
+                        $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP))
964
+                    ),
965
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid))
966
+                )
967
+            );
968
+
969
+            $qb->orWhere(
970
+                $qb->expr()->andX(
971
+                    $qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)),
972
+                    $qb->expr()->eq('share_with', $qb->createNamedParameter($uid))
973
+                )
974
+            );
975
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_LINK) {
976
+            /*
977 977
 			 * Delete all link shares owned by this user.
978 978
 			 * And all link shares initiated by this user (until #22327 is in)
979 979
 			 */
980
-			$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
-
982
-			$qb->andWhere(
983
-				$qb->expr()->orX(
984
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
-				)
987
-			);
988
-		}
989
-
990
-		$qb->execute();
991
-	}
992
-
993
-	/**
994
-	 * Delete all shares received by this group. As well as any custom group
995
-	 * shares for group members.
996
-	 *
997
-	 * @param string $gid
998
-	 */
999
-	public function groupDeleted($gid) {
1000
-		/*
980
+            $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_LINK)));
981
+
982
+            $qb->andWhere(
983
+                $qb->expr()->orX(
984
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)),
985
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($uid))
986
+                )
987
+            );
988
+        }
989
+
990
+        $qb->execute();
991
+    }
992
+
993
+    /**
994
+     * Delete all shares received by this group. As well as any custom group
995
+     * shares for group members.
996
+     *
997
+     * @param string $gid
998
+     */
999
+    public function groupDeleted($gid) {
1000
+        /*
1001 1001
 		 * First delete all custom group shares for group members
1002 1002
 		 */
1003
-		$qb = $this->dbConn->getQueryBuilder();
1004
-		$qb->select('id')
1005
-			->from('share')
1006
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
-
1009
-		$cursor = $qb->execute();
1010
-		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1013
-		}
1014
-		$cursor->closeCursor();
1015
-
1016
-		if (!empty($ids)) {
1017
-			$chunks = array_chunk($ids, 100);
1018
-			foreach ($chunks as $chunk) {
1019
-				$qb->delete('share')
1020
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
-				$qb->execute();
1023
-			}
1024
-		}
1025
-
1026
-		/*
1003
+        $qb = $this->dbConn->getQueryBuilder();
1004
+        $qb->select('id')
1005
+            ->from('share')
1006
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1007
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1008
+
1009
+        $cursor = $qb->execute();
1010
+        $ids = [];
1011
+        while($row = $cursor->fetch()) {
1012
+            $ids[] = (int)$row['id'];
1013
+        }
1014
+        $cursor->closeCursor();
1015
+
1016
+        if (!empty($ids)) {
1017
+            $chunks = array_chunk($ids, 100);
1018
+            foreach ($chunks as $chunk) {
1019
+                $qb->delete('share')
1020
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1021
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1022
+                $qb->execute();
1023
+            }
1024
+        }
1025
+
1026
+        /*
1027 1027
 		 * Now delete all the group shares
1028 1028
 		 */
1029
-		$qb = $this->dbConn->getQueryBuilder();
1030
-		$qb->delete('share')
1031
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
-		$qb->execute();
1034
-	}
1035
-
1036
-	/**
1037
-	 * Delete custom group shares to this group for this user
1038
-	 *
1039
-	 * @param string $uid
1040
-	 * @param string $gid
1041
-	 */
1042
-	public function userDeletedFromGroup($uid, $gid) {
1043
-		/*
1029
+        $qb = $this->dbConn->getQueryBuilder();
1030
+        $qb->delete('share')
1031
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1032
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1033
+        $qb->execute();
1034
+    }
1035
+
1036
+    /**
1037
+     * Delete custom group shares to this group for this user
1038
+     *
1039
+     * @param string $uid
1040
+     * @param string $gid
1041
+     */
1042
+    public function userDeletedFromGroup($uid, $gid) {
1043
+        /*
1044 1044
 		 * Get all group shares
1045 1045
 		 */
1046
-		$qb = $this->dbConn->getQueryBuilder();
1047
-		$qb->select('id')
1048
-			->from('share')
1049
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
-			->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
-
1052
-		$cursor = $qb->execute();
1053
-		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1056
-		}
1057
-		$cursor->closeCursor();
1058
-
1059
-		if (!empty($ids)) {
1060
-			$chunks = array_chunk($ids, 100);
1061
-			foreach ($chunks as $chunk) {
1062
-				/*
1046
+        $qb = $this->dbConn->getQueryBuilder();
1047
+        $qb->select('id')
1048
+            ->from('share')
1049
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_GROUP)))
1050
+            ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($gid)));
1051
+
1052
+        $cursor = $qb->execute();
1053
+        $ids = [];
1054
+        while($row = $cursor->fetch()) {
1055
+            $ids[] = (int)$row['id'];
1056
+        }
1057
+        $cursor->closeCursor();
1058
+
1059
+        if (!empty($ids)) {
1060
+            $chunks = array_chunk($ids, 100);
1061
+            foreach ($chunks as $chunk) {
1062
+                /*
1063 1063
 				 * Delete all special shares wit this users for the found group shares
1064 1064
 				 */
1065
-				$qb->delete('share')
1066
-					->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
-					->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
-					->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
-				$qb->execute();
1070
-			}
1071
-		}
1072
-	}
1065
+                $qb->delete('share')
1066
+                    ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_USERGROUP)))
1067
+                    ->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($uid)))
1068
+                    ->andWhere($qb->expr()->in('parent', $qb->createNamedParameter($chunk, IQueryBuilder::PARAM_INT_ARRAY)));
1069
+                $qb->execute();
1070
+            }
1071
+        }
1072
+    }
1073 1073
 }
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 			->orderBy('id');
289 289
 
290 290
 		$cursor = $qb->execute();
291
-		while($data = $cursor->fetch()) {
291
+		while ($data = $cursor->fetch()) {
292 292
 			$children[] = $this->createShare($data);
293 293
 		}
294 294
 		$cursor->closeCursor();
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 			$user = $this->userManager->get($recipient);
334 334
 
335 335
 			if (is_null($group)) {
336
-				throw new ProviderException('Group "' . $share->getSharedWith() . '" does not exist');
336
+				throw new ProviderException('Group "'.$share->getSharedWith().'" does not exist');
337 337
 			}
338 338
 
339 339
 			if (!$group->inGroup($user)) {
@@ -493,7 +493,7 @@  discard block
 block discarded – undo
493 493
 			);
494 494
 		}
495 495
 
496
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
496
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
497 497
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
498 498
 
499 499
 		$qb->orderBy('id');
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 
550 550
 		$cursor = $qb->execute();
551 551
 		$shares = [];
552
-		while($data = $cursor->fetch()) {
552
+		while ($data = $cursor->fetch()) {
553 553
 			$shares[] = $this->createShare($data);
554 554
 		}
555 555
 		$cursor->closeCursor();
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 			->execute();
629 629
 
630 630
 		$shares = [];
631
-		while($data = $cursor->fetch()) {
631
+		while ($data = $cursor->fetch()) {
632 632
 			$shares[] = $this->createShare($data);
633 633
 		}
634 634
 		$cursor->closeCursor();
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 
700 700
 			$cursor = $qb->execute();
701 701
 
702
-			while($data = $cursor->fetch()) {
702
+			while ($data = $cursor->fetch()) {
703 703
 				if ($this->isAccessibleResult($data)) {
704 704
 					$shares[] = $this->createShare($data);
705 705
 				}
@@ -714,7 +714,7 @@  discard block
 block discarded – undo
714 714
 			$shares2 = [];
715 715
 
716 716
 			$start = 0;
717
-			while(true) {
717
+			while (true) {
718 718
 				$groups = array_slice($allGroups, $start, 100);
719 719
 				$start += 100;
720 720
 
@@ -757,7 +757,7 @@  discard block
 block discarded – undo
757 757
 					));
758 758
 
759 759
 				$cursor = $qb->execute();
760
-				while($data = $cursor->fetch()) {
760
+				while ($data = $cursor->fetch()) {
761 761
 					if ($offset > 0) {
762 762
 						$offset--;
763 763
 						continue;
@@ -826,14 +826,14 @@  discard block
 block discarded – undo
826 826
 	 */
827 827
 	private function createShare($data) {
828 828
 		$share = new Share($this->rootFolder, $this->userManager);
829
-		$share->setId((int)$data['id'])
830
-			->setShareType((int)$data['share_type'])
831
-			->setPermissions((int)$data['permissions'])
829
+		$share->setId((int) $data['id'])
830
+			->setShareType((int) $data['share_type'])
831
+			->setPermissions((int) $data['permissions'])
832 832
 			->setTarget($data['file_target'])
833
-			->setMailSend((bool)$data['mail_send']);
833
+			->setMailSend((bool) $data['mail_send']);
834 834
 
835 835
 		$shareTime = new \DateTime();
836
-		$shareTime->setTimestamp((int)$data['stime']);
836
+		$shareTime->setTimestamp((int) $data['stime']);
837 837
 		$share->setShareTime($shareTime);
838 838
 
839 839
 		if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
@@ -848,7 +848,7 @@  discard block
 block discarded – undo
848 848
 		$share->setSharedBy($data['uid_initiator']);
849 849
 		$share->setShareOwner($data['uid_owner']);
850 850
 
851
-		$share->setNodeId((int)$data['file_source']);
851
+		$share->setNodeId((int) $data['file_source']);
852 852
 		$share->setNodeType($data['item_type']);
853 853
 
854 854
 		if ($data['expiration'] !== null) {
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		if (isset($data['f_permissions'])) {
860 860
 			$entryData = $data;
861 861
 			$entryData['permissions'] = $entryData['f_permissions'];
862
-			$entryData['parent'] = $entryData['f_parent'];;
862
+			$entryData['parent'] = $entryData['f_parent']; ;
863 863
 			$share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData,
864 864
 				\OC::$server->getMimeTypeLoader()));
865 865
 		}
@@ -878,7 +878,7 @@  discard block
 block discarded – undo
878 878
 		$result = [];
879 879
 
880 880
 		$start = 0;
881
-		while(true) {
881
+		while (true) {
882 882
 			/** @var Share[] $shareSlice */
883 883
 			$shareSlice = array_slice($shares, $start, 100);
884 884
 			$start += 100;
@@ -893,7 +893,7 @@  discard block
 block discarded – undo
893 893
 			$shareMap = [];
894 894
 
895 895
 			foreach ($shareSlice as $share) {
896
-				$ids[] = (int)$share->getId();
896
+				$ids[] = (int) $share->getId();
897 897
 				$shareMap[$share->getId()] = $share;
898 898
 			}
899 899
 
@@ -910,8 +910,8 @@  discard block
 block discarded – undo
910 910
 
911 911
 			$stmt = $query->execute();
912 912
 
913
-			while($data = $stmt->fetch()) {
914
-				$shareMap[$data['parent']]->setPermissions((int)$data['permissions']);
913
+			while ($data = $stmt->fetch()) {
914
+				$shareMap[$data['parent']]->setPermissions((int) $data['permissions']);
915 915
 				$shareMap[$data['parent']]->setTarget($data['file_target']);
916 916
 			}
917 917
 
@@ -1008,8 +1008,8 @@  discard block
 block discarded – undo
1008 1008
 
1009 1009
 		$cursor = $qb->execute();
1010 1010
 		$ids = [];
1011
-		while($row = $cursor->fetch()) {
1012
-			$ids[] = (int)$row['id'];
1011
+		while ($row = $cursor->fetch()) {
1012
+			$ids[] = (int) $row['id'];
1013 1013
 		}
1014 1014
 		$cursor->closeCursor();
1015 1015
 
@@ -1051,8 +1051,8 @@  discard block
 block discarded – undo
1051 1051
 
1052 1052
 		$cursor = $qb->execute();
1053 1053
 		$ids = [];
1054
-		while($row = $cursor->fetch()) {
1055
-			$ids[] = (int)$row['id'];
1054
+		while ($row = $cursor->fetch()) {
1055
+			$ids[] = (int) $row['id'];
1056 1056
 		}
1057 1057
 		$cursor->closeCursor();
1058 1058
 
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/FederatedShareProvider.php 2 patches
Indentation   +915 added lines, -915 removed lines patch added patch discarded remove patch
@@ -49,929 +49,929 @@
 block discarded – undo
49 49
  */
50 50
 class FederatedShareProvider implements IShareProvider {
51 51
 
52
-	const SHARE_TYPE_REMOTE = 6;
53
-
54
-	/** @var IDBConnection */
55
-	private $dbConnection;
56
-
57
-	/** @var AddressHandler */
58
-	private $addressHandler;
59
-
60
-	/** @var Notifications */
61
-	private $notifications;
62
-
63
-	/** @var TokenHandler */
64
-	private $tokenHandler;
65
-
66
-	/** @var IL10N */
67
-	private $l;
68
-
69
-	/** @var ILogger */
70
-	private $logger;
71
-
72
-	/** @var IRootFolder */
73
-	private $rootFolder;
74
-
75
-	/** @var IConfig */
76
-	private $config;
77
-
78
-	/** @var string */
79
-	private $externalShareTable = 'share_external';
80
-
81
-	/** @var IUserManager */
82
-	private $userManager;
83
-
84
-	/** @var ICloudIdManager */
85
-	private $cloudIdManager;
86
-
87
-	/**
88
-	 * DefaultShareProvider constructor.
89
-	 *
90
-	 * @param IDBConnection $connection
91
-	 * @param AddressHandler $addressHandler
92
-	 * @param Notifications $notifications
93
-	 * @param TokenHandler $tokenHandler
94
-	 * @param IL10N $l10n
95
-	 * @param ILogger $logger
96
-	 * @param IRootFolder $rootFolder
97
-	 * @param IConfig $config
98
-	 * @param IUserManager $userManager
99
-	 * @param ICloudIdManager $cloudIdManager
100
-	 */
101
-	public function __construct(
102
-			IDBConnection $connection,
103
-			AddressHandler $addressHandler,
104
-			Notifications $notifications,
105
-			TokenHandler $tokenHandler,
106
-			IL10N $l10n,
107
-			ILogger $logger,
108
-			IRootFolder $rootFolder,
109
-			IConfig $config,
110
-			IUserManager $userManager,
111
-			ICloudIdManager $cloudIdManager
112
-	) {
113
-		$this->dbConnection = $connection;
114
-		$this->addressHandler = $addressHandler;
115
-		$this->notifications = $notifications;
116
-		$this->tokenHandler = $tokenHandler;
117
-		$this->l = $l10n;
118
-		$this->logger = $logger;
119
-		$this->rootFolder = $rootFolder;
120
-		$this->config = $config;
121
-		$this->userManager = $userManager;
122
-		$this->cloudIdManager = $cloudIdManager;
123
-	}
124
-
125
-	/**
126
-	 * Return the identifier of this provider.
127
-	 *
128
-	 * @return string Containing only [a-zA-Z0-9]
129
-	 */
130
-	public function identifier() {
131
-		return 'ocFederatedSharing';
132
-	}
133
-
134
-	/**
135
-	 * Share a path
136
-	 *
137
-	 * @param IShare $share
138
-	 * @return IShare The share object
139
-	 * @throws ShareNotFound
140
-	 * @throws \Exception
141
-	 */
142
-	public function create(IShare $share) {
143
-
144
-		$shareWith = $share->getSharedWith();
145
-		$itemSource = $share->getNodeId();
146
-		$itemType = $share->getNodeType();
147
-		$permissions = $share->getPermissions();
148
-		$sharedBy = $share->getSharedBy();
149
-
150
-		/*
52
+    const SHARE_TYPE_REMOTE = 6;
53
+
54
+    /** @var IDBConnection */
55
+    private $dbConnection;
56
+
57
+    /** @var AddressHandler */
58
+    private $addressHandler;
59
+
60
+    /** @var Notifications */
61
+    private $notifications;
62
+
63
+    /** @var TokenHandler */
64
+    private $tokenHandler;
65
+
66
+    /** @var IL10N */
67
+    private $l;
68
+
69
+    /** @var ILogger */
70
+    private $logger;
71
+
72
+    /** @var IRootFolder */
73
+    private $rootFolder;
74
+
75
+    /** @var IConfig */
76
+    private $config;
77
+
78
+    /** @var string */
79
+    private $externalShareTable = 'share_external';
80
+
81
+    /** @var IUserManager */
82
+    private $userManager;
83
+
84
+    /** @var ICloudIdManager */
85
+    private $cloudIdManager;
86
+
87
+    /**
88
+     * DefaultShareProvider constructor.
89
+     *
90
+     * @param IDBConnection $connection
91
+     * @param AddressHandler $addressHandler
92
+     * @param Notifications $notifications
93
+     * @param TokenHandler $tokenHandler
94
+     * @param IL10N $l10n
95
+     * @param ILogger $logger
96
+     * @param IRootFolder $rootFolder
97
+     * @param IConfig $config
98
+     * @param IUserManager $userManager
99
+     * @param ICloudIdManager $cloudIdManager
100
+     */
101
+    public function __construct(
102
+            IDBConnection $connection,
103
+            AddressHandler $addressHandler,
104
+            Notifications $notifications,
105
+            TokenHandler $tokenHandler,
106
+            IL10N $l10n,
107
+            ILogger $logger,
108
+            IRootFolder $rootFolder,
109
+            IConfig $config,
110
+            IUserManager $userManager,
111
+            ICloudIdManager $cloudIdManager
112
+    ) {
113
+        $this->dbConnection = $connection;
114
+        $this->addressHandler = $addressHandler;
115
+        $this->notifications = $notifications;
116
+        $this->tokenHandler = $tokenHandler;
117
+        $this->l = $l10n;
118
+        $this->logger = $logger;
119
+        $this->rootFolder = $rootFolder;
120
+        $this->config = $config;
121
+        $this->userManager = $userManager;
122
+        $this->cloudIdManager = $cloudIdManager;
123
+    }
124
+
125
+    /**
126
+     * Return the identifier of this provider.
127
+     *
128
+     * @return string Containing only [a-zA-Z0-9]
129
+     */
130
+    public function identifier() {
131
+        return 'ocFederatedSharing';
132
+    }
133
+
134
+    /**
135
+     * Share a path
136
+     *
137
+     * @param IShare $share
138
+     * @return IShare The share object
139
+     * @throws ShareNotFound
140
+     * @throws \Exception
141
+     */
142
+    public function create(IShare $share) {
143
+
144
+        $shareWith = $share->getSharedWith();
145
+        $itemSource = $share->getNodeId();
146
+        $itemType = $share->getNodeType();
147
+        $permissions = $share->getPermissions();
148
+        $sharedBy = $share->getSharedBy();
149
+
150
+        /*
151 151
 		 * Check if file is not already shared with the remote user
152 152
 		 */
153
-		$alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
154
-		if (!empty($alreadyShared)) {
155
-			$message = 'Sharing %s failed, because this item is already shared with %s';
156
-			$message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
157
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
158
-			throw new \Exception($message_t);
159
-		}
160
-
161
-
162
-		// don't allow federated shares if source and target server are the same
163
-		$cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
164
-		$currentServer = $this->addressHandler->generateRemoteURL();
165
-		$currentUser = $sharedBy;
166
-		if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
167
-			$message = 'Not allowed to create a federated share with the same user.';
168
-			$message_t = $this->l->t('Not allowed to create a federated share with the same user');
169
-			$this->logger->debug($message, ['app' => 'Federated File Sharing']);
170
-			throw new \Exception($message_t);
171
-		}
172
-
173
-
174
-		$share->setSharedWith($cloudId->getId());
175
-
176
-		try {
177
-			$remoteShare = $this->getShareFromExternalShareTable($share);
178
-		} catch (ShareNotFound $e) {
179
-			$remoteShare = null;
180
-		}
181
-
182
-		if ($remoteShare) {
183
-			try {
184
-				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
185
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
186
-				$share->setId($shareId);
187
-				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
188
-				// remote share was create successfully if we get a valid token as return
189
-				$send = is_string($token) && $token !== '';
190
-			} catch (\Exception $e) {
191
-				// fall back to old re-share behavior if the remote server
192
-				// doesn't support flat re-shares (was introduced with Nextcloud 9.1)
193
-				$this->removeShareFromTable($share);
194
-				$shareId = $this->createFederatedShare($share);
195
-			}
196
-			if ($send) {
197
-				$this->updateSuccessfulReshare($shareId, $token);
198
-				$this->storeRemoteId($shareId, $remoteId);
199
-			} else {
200
-				$this->removeShareFromTable($share);
201
-				$message_t = $this->l->t('File is already shared with %s', [$shareWith]);
202
-				throw new \Exception($message_t);
203
-			}
204
-
205
-		} else {
206
-			$shareId = $this->createFederatedShare($share);
207
-		}
208
-
209
-		$data = $this->getRawShare($shareId);
210
-		return $this->createShareObject($data);
211
-	}
212
-
213
-	/**
214
-	 * create federated share and inform the recipient
215
-	 *
216
-	 * @param IShare $share
217
-	 * @return int
218
-	 * @throws ShareNotFound
219
-	 * @throws \Exception
220
-	 */
221
-	protected function createFederatedShare(IShare $share) {
222
-		$token = $this->tokenHandler->generateToken();
223
-		$shareId = $this->addShareToDB(
224
-			$share->getNodeId(),
225
-			$share->getNodeType(),
226
-			$share->getSharedWith(),
227
-			$share->getSharedBy(),
228
-			$share->getShareOwner(),
229
-			$share->getPermissions(),
230
-			$token
231
-		);
232
-
233
-		$failure = false;
234
-
235
-		try {
236
-			$sharedByFederatedId = $share->getSharedBy();
237
-			if ($this->userManager->userExists($sharedByFederatedId)) {
238
-				$cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
239
-				$sharedByFederatedId = $cloudId->getId();
240
-			}
241
-			$ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
242
-			$send = $this->notifications->sendRemoteShare(
243
-				$token,
244
-				$share->getSharedWith(),
245
-				$share->getNode()->getName(),
246
-				$shareId,
247
-				$share->getShareOwner(),
248
-				$ownerCloudId->getId(),
249
-				$share->getSharedBy(),
250
-				$sharedByFederatedId
251
-			);
252
-
253
-			if ($send === false) {
254
-				$failure = true;
255
-			}
256
-		} catch (\Exception $e) {
257
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
258
-			$failure = true;
259
-		}
260
-
261
-		if($failure) {
262
-			$this->removeShareFromTableById($shareId);
263
-			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
264
-				[$share->getNode()->getName(), $share->getSharedWith()]);
265
-			throw new \Exception($message_t);
266
-		}
267
-
268
-		return $shareId;
269
-
270
-	}
271
-
272
-	/**
273
-	 * @param string $shareWith
274
-	 * @param IShare $share
275
-	 * @param string $shareId internal share Id
276
-	 * @return array
277
-	 * @throws \Exception
278
-	 */
279
-	protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
280
-
281
-		$remoteShare = $this->getShareFromExternalShareTable($share);
282
-		$token = $remoteShare['share_token'];
283
-		$remoteId = $remoteShare['remote_id'];
284
-		$remote = $remoteShare['remote'];
285
-
286
-		list($token, $remoteId) = $this->notifications->requestReShare(
287
-			$token,
288
-			$remoteId,
289
-			$shareId,
290
-			$remote,
291
-			$shareWith,
292
-			$share->getPermissions()
293
-		);
294
-
295
-		return [$token, $remoteId];
296
-	}
297
-
298
-	/**
299
-	 * get federated share from the share_external table but exclude mounted link shares
300
-	 *
301
-	 * @param IShare $share
302
-	 * @return array
303
-	 * @throws ShareNotFound
304
-	 */
305
-	protected function getShareFromExternalShareTable(IShare $share) {
306
-		$query = $this->dbConnection->getQueryBuilder();
307
-		$query->select('*')->from($this->externalShareTable)
308
-			->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
309
-			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
310
-		$result = $query->execute()->fetchAll();
311
-
312
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
313
-			return $result[0];
314
-		}
315
-
316
-		throw new ShareNotFound('share not found in share_external table');
317
-	}
318
-
319
-	/**
320
-	 * add share to the database and return the ID
321
-	 *
322
-	 * @param int $itemSource
323
-	 * @param string $itemType
324
-	 * @param string $shareWith
325
-	 * @param string $sharedBy
326
-	 * @param string $uidOwner
327
-	 * @param int $permissions
328
-	 * @param string $token
329
-	 * @return int
330
-	 */
331
-	private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
332
-		$qb = $this->dbConnection->getQueryBuilder();
333
-		$qb->insert('share')
334
-			->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
335
-			->setValue('item_type', $qb->createNamedParameter($itemType))
336
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
337
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
338
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
339
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
340
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
341
-			->setValue('permissions', $qb->createNamedParameter($permissions))
342
-			->setValue('token', $qb->createNamedParameter($token))
343
-			->setValue('stime', $qb->createNamedParameter(time()));
344
-
345
-		/*
153
+        $alreadyShared = $this->getSharedWith($shareWith, self::SHARE_TYPE_REMOTE, $share->getNode(), 1, 0);
154
+        if (!empty($alreadyShared)) {
155
+            $message = 'Sharing %s failed, because this item is already shared with %s';
156
+            $message_t = $this->l->t('Sharing %s failed, because this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
157
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
158
+            throw new \Exception($message_t);
159
+        }
160
+
161
+
162
+        // don't allow federated shares if source and target server are the same
163
+        $cloudId = $this->cloudIdManager->resolveCloudId($shareWith);
164
+        $currentServer = $this->addressHandler->generateRemoteURL();
165
+        $currentUser = $sharedBy;
166
+        if ($this->addressHandler->compareAddresses($cloudId->getUser(), $cloudId->getRemote(), $currentUser, $currentServer)) {
167
+            $message = 'Not allowed to create a federated share with the same user.';
168
+            $message_t = $this->l->t('Not allowed to create a federated share with the same user');
169
+            $this->logger->debug($message, ['app' => 'Federated File Sharing']);
170
+            throw new \Exception($message_t);
171
+        }
172
+
173
+
174
+        $share->setSharedWith($cloudId->getId());
175
+
176
+        try {
177
+            $remoteShare = $this->getShareFromExternalShareTable($share);
178
+        } catch (ShareNotFound $e) {
179
+            $remoteShare = null;
180
+        }
181
+
182
+        if ($remoteShare) {
183
+            try {
184
+                $ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
185
+                $shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
186
+                $share->setId($shareId);
187
+                list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
188
+                // remote share was create successfully if we get a valid token as return
189
+                $send = is_string($token) && $token !== '';
190
+            } catch (\Exception $e) {
191
+                // fall back to old re-share behavior if the remote server
192
+                // doesn't support flat re-shares (was introduced with Nextcloud 9.1)
193
+                $this->removeShareFromTable($share);
194
+                $shareId = $this->createFederatedShare($share);
195
+            }
196
+            if ($send) {
197
+                $this->updateSuccessfulReshare($shareId, $token);
198
+                $this->storeRemoteId($shareId, $remoteId);
199
+            } else {
200
+                $this->removeShareFromTable($share);
201
+                $message_t = $this->l->t('File is already shared with %s', [$shareWith]);
202
+                throw new \Exception($message_t);
203
+            }
204
+
205
+        } else {
206
+            $shareId = $this->createFederatedShare($share);
207
+        }
208
+
209
+        $data = $this->getRawShare($shareId);
210
+        return $this->createShareObject($data);
211
+    }
212
+
213
+    /**
214
+     * create federated share and inform the recipient
215
+     *
216
+     * @param IShare $share
217
+     * @return int
218
+     * @throws ShareNotFound
219
+     * @throws \Exception
220
+     */
221
+    protected function createFederatedShare(IShare $share) {
222
+        $token = $this->tokenHandler->generateToken();
223
+        $shareId = $this->addShareToDB(
224
+            $share->getNodeId(),
225
+            $share->getNodeType(),
226
+            $share->getSharedWith(),
227
+            $share->getSharedBy(),
228
+            $share->getShareOwner(),
229
+            $share->getPermissions(),
230
+            $token
231
+        );
232
+
233
+        $failure = false;
234
+
235
+        try {
236
+            $sharedByFederatedId = $share->getSharedBy();
237
+            if ($this->userManager->userExists($sharedByFederatedId)) {
238
+                $cloudId = $this->cloudIdManager->getCloudId($sharedByFederatedId, $this->addressHandler->generateRemoteURL());
239
+                $sharedByFederatedId = $cloudId->getId();
240
+            }
241
+            $ownerCloudId = $this->cloudIdManager->getCloudId($share->getShareOwner(), $this->addressHandler->generateRemoteURL());
242
+            $send = $this->notifications->sendRemoteShare(
243
+                $token,
244
+                $share->getSharedWith(),
245
+                $share->getNode()->getName(),
246
+                $shareId,
247
+                $share->getShareOwner(),
248
+                $ownerCloudId->getId(),
249
+                $share->getSharedBy(),
250
+                $sharedByFederatedId
251
+            );
252
+
253
+            if ($send === false) {
254
+                $failure = true;
255
+            }
256
+        } catch (\Exception $e) {
257
+            $this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
258
+            $failure = true;
259
+        }
260
+
261
+        if($failure) {
262
+            $this->removeShareFromTableById($shareId);
263
+            $message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
264
+                [$share->getNode()->getName(), $share->getSharedWith()]);
265
+            throw new \Exception($message_t);
266
+        }
267
+
268
+        return $shareId;
269
+
270
+    }
271
+
272
+    /**
273
+     * @param string $shareWith
274
+     * @param IShare $share
275
+     * @param string $shareId internal share Id
276
+     * @return array
277
+     * @throws \Exception
278
+     */
279
+    protected function askOwnerToReShare($shareWith, IShare $share, $shareId) {
280
+
281
+        $remoteShare = $this->getShareFromExternalShareTable($share);
282
+        $token = $remoteShare['share_token'];
283
+        $remoteId = $remoteShare['remote_id'];
284
+        $remote = $remoteShare['remote'];
285
+
286
+        list($token, $remoteId) = $this->notifications->requestReShare(
287
+            $token,
288
+            $remoteId,
289
+            $shareId,
290
+            $remote,
291
+            $shareWith,
292
+            $share->getPermissions()
293
+        );
294
+
295
+        return [$token, $remoteId];
296
+    }
297
+
298
+    /**
299
+     * get federated share from the share_external table but exclude mounted link shares
300
+     *
301
+     * @param IShare $share
302
+     * @return array
303
+     * @throws ShareNotFound
304
+     */
305
+    protected function getShareFromExternalShareTable(IShare $share) {
306
+        $query = $this->dbConnection->getQueryBuilder();
307
+        $query->select('*')->from($this->externalShareTable)
308
+            ->where($query->expr()->eq('user', $query->createNamedParameter($share->getShareOwner())))
309
+            ->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
310
+        $result = $query->execute()->fetchAll();
311
+
312
+        if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
313
+            return $result[0];
314
+        }
315
+
316
+        throw new ShareNotFound('share not found in share_external table');
317
+    }
318
+
319
+    /**
320
+     * add share to the database and return the ID
321
+     *
322
+     * @param int $itemSource
323
+     * @param string $itemType
324
+     * @param string $shareWith
325
+     * @param string $sharedBy
326
+     * @param string $uidOwner
327
+     * @param int $permissions
328
+     * @param string $token
329
+     * @return int
330
+     */
331
+    private function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
332
+        $qb = $this->dbConnection->getQueryBuilder();
333
+        $qb->insert('share')
334
+            ->setValue('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE))
335
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
336
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
337
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
338
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
339
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
340
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
341
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
342
+            ->setValue('token', $qb->createNamedParameter($token))
343
+            ->setValue('stime', $qb->createNamedParameter(time()));
344
+
345
+        /*
346 346
 		 * Added to fix https://github.com/owncloud/core/issues/22215
347 347
 		 * Can be removed once we get rid of ajax/share.php
348 348
 		 */
349
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
350
-
351
-		$qb->execute();
352
-		$id = $qb->getLastInsertId();
353
-
354
-		return (int)$id;
355
-	}
356
-
357
-	/**
358
-	 * Update a share
359
-	 *
360
-	 * @param IShare $share
361
-	 * @return IShare The share object
362
-	 */
363
-	public function update(IShare $share) {
364
-		/*
349
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
350
+
351
+        $qb->execute();
352
+        $id = $qb->getLastInsertId();
353
+
354
+        return (int)$id;
355
+    }
356
+
357
+    /**
358
+     * Update a share
359
+     *
360
+     * @param IShare $share
361
+     * @return IShare The share object
362
+     */
363
+    public function update(IShare $share) {
364
+        /*
365 365
 		 * We allow updating the permissions of federated shares
366 366
 		 */
367
-		$qb = $this->dbConnection->getQueryBuilder();
368
-			$qb->update('share')
369
-				->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
370
-				->set('permissions', $qb->createNamedParameter($share->getPermissions()))
371
-				->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
372
-				->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
373
-				->execute();
374
-
375
-		// send the updated permission to the owner/initiator, if they are not the same
376
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
377
-			$this->sendPermissionUpdate($share);
378
-		}
379
-
380
-		return $share;
381
-	}
382
-
383
-	/**
384
-	 * send the updated permission to the owner/initiator, if they are not the same
385
-	 *
386
-	 * @param IShare $share
387
-	 * @throws ShareNotFound
388
-	 * @throws \OC\HintException
389
-	 */
390
-	protected function sendPermissionUpdate(IShare $share) {
391
-		$remoteId = $this->getRemoteId($share);
392
-		// if the local user is the owner we send the permission change to the initiator
393
-		if ($this->userManager->userExists($share->getShareOwner())) {
394
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
395
-		} else { // ... if not we send the permission change to the owner
396
-			list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
397
-		}
398
-		$this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
399
-	}
400
-
401
-
402
-	/**
403
-	 * update successful reShare with the correct token
404
-	 *
405
-	 * @param int $shareId
406
-	 * @param string $token
407
-	 */
408
-	protected function updateSuccessfulReShare($shareId, $token) {
409
-		$query = $this->dbConnection->getQueryBuilder();
410
-		$query->update('share')
411
-			->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
412
-			->set('token', $query->createNamedParameter($token))
413
-			->execute();
414
-	}
415
-
416
-	/**
417
-	 * store remote ID in federated reShare table
418
-	 *
419
-	 * @param $shareId
420
-	 * @param $remoteId
421
-	 */
422
-	public function storeRemoteId($shareId, $remoteId) {
423
-		$query = $this->dbConnection->getQueryBuilder();
424
-		$query->insert('federated_reshares')
425
-			->values(
426
-				[
427
-					'share_id' =>  $query->createNamedParameter($shareId),
428
-					'remote_id' => $query->createNamedParameter($remoteId),
429
-				]
430
-			);
431
-		$query->execute();
432
-	}
433
-
434
-	/**
435
-	 * get share ID on remote server for federated re-shares
436
-	 *
437
-	 * @param IShare $share
438
-	 * @return int
439
-	 * @throws ShareNotFound
440
-	 */
441
-	public function getRemoteId(IShare $share) {
442
-		$query = $this->dbConnection->getQueryBuilder();
443
-		$query->select('remote_id')->from('federated_reshares')
444
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
445
-		$data = $query->execute()->fetch();
446
-
447
-		if (!is_array($data) || !isset($data['remote_id'])) {
448
-			throw new ShareNotFound();
449
-		}
450
-
451
-		return (int)$data['remote_id'];
452
-	}
453
-
454
-	/**
455
-	 * @inheritdoc
456
-	 */
457
-	public function move(IShare $share, $recipient) {
458
-		/*
367
+        $qb = $this->dbConnection->getQueryBuilder();
368
+            $qb->update('share')
369
+                ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
370
+                ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
371
+                ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
372
+                ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
373
+                ->execute();
374
+
375
+        // send the updated permission to the owner/initiator, if they are not the same
376
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
377
+            $this->sendPermissionUpdate($share);
378
+        }
379
+
380
+        return $share;
381
+    }
382
+
383
+    /**
384
+     * send the updated permission to the owner/initiator, if they are not the same
385
+     *
386
+     * @param IShare $share
387
+     * @throws ShareNotFound
388
+     * @throws \OC\HintException
389
+     */
390
+    protected function sendPermissionUpdate(IShare $share) {
391
+        $remoteId = $this->getRemoteId($share);
392
+        // if the local user is the owner we send the permission change to the initiator
393
+        if ($this->userManager->userExists($share->getShareOwner())) {
394
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
395
+        } else { // ... if not we send the permission change to the owner
396
+            list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
397
+        }
398
+        $this->notifications->sendPermissionChange($remote, $remoteId, $share->getToken(), $share->getPermissions());
399
+    }
400
+
401
+
402
+    /**
403
+     * update successful reShare with the correct token
404
+     *
405
+     * @param int $shareId
406
+     * @param string $token
407
+     */
408
+    protected function updateSuccessfulReShare($shareId, $token) {
409
+        $query = $this->dbConnection->getQueryBuilder();
410
+        $query->update('share')
411
+            ->where($query->expr()->eq('id', $query->createNamedParameter($shareId)))
412
+            ->set('token', $query->createNamedParameter($token))
413
+            ->execute();
414
+    }
415
+
416
+    /**
417
+     * store remote ID in federated reShare table
418
+     *
419
+     * @param $shareId
420
+     * @param $remoteId
421
+     */
422
+    public function storeRemoteId($shareId, $remoteId) {
423
+        $query = $this->dbConnection->getQueryBuilder();
424
+        $query->insert('federated_reshares')
425
+            ->values(
426
+                [
427
+                    'share_id' =>  $query->createNamedParameter($shareId),
428
+                    'remote_id' => $query->createNamedParameter($remoteId),
429
+                ]
430
+            );
431
+        $query->execute();
432
+    }
433
+
434
+    /**
435
+     * get share ID on remote server for federated re-shares
436
+     *
437
+     * @param IShare $share
438
+     * @return int
439
+     * @throws ShareNotFound
440
+     */
441
+    public function getRemoteId(IShare $share) {
442
+        $query = $this->dbConnection->getQueryBuilder();
443
+        $query->select('remote_id')->from('federated_reshares')
444
+            ->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
445
+        $data = $query->execute()->fetch();
446
+
447
+        if (!is_array($data) || !isset($data['remote_id'])) {
448
+            throw new ShareNotFound();
449
+        }
450
+
451
+        return (int)$data['remote_id'];
452
+    }
453
+
454
+    /**
455
+     * @inheritdoc
456
+     */
457
+    public function move(IShare $share, $recipient) {
458
+        /*
459 459
 		 * This function does nothing yet as it is just for outgoing
460 460
 		 * federated shares.
461 461
 		 */
462
-		return $share;
463
-	}
464
-
465
-	/**
466
-	 * Get all children of this share
467
-	 *
468
-	 * @param IShare $parent
469
-	 * @return IShare[]
470
-	 */
471
-	public function getChildren(IShare $parent) {
472
-		$children = [];
473
-
474
-		$qb = $this->dbConnection->getQueryBuilder();
475
-		$qb->select('*')
476
-			->from('share')
477
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
478
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
479
-			->orderBy('id');
480
-
481
-		$cursor = $qb->execute();
482
-		while($data = $cursor->fetch()) {
483
-			$children[] = $this->createShareObject($data);
484
-		}
485
-		$cursor->closeCursor();
486
-
487
-		return $children;
488
-	}
489
-
490
-	/**
491
-	 * Delete a share (owner unShares the file)
492
-	 *
493
-	 * @param IShare $share
494
-	 */
495
-	public function delete(IShare $share) {
496
-
497
-		list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
498
-
499
-		$isOwner = false;
500
-
501
-		$this->removeShareFromTable($share);
502
-
503
-		// if the local user is the owner we can send the unShare request directly...
504
-		if ($this->userManager->userExists($share->getShareOwner())) {
505
-			$this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
506
-			$this->revokeShare($share, true);
507
-			$isOwner = true;
508
-		} else { // ... if not we need to correct ID for the unShare request
509
-			$remoteId = $this->getRemoteId($share);
510
-			$this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
511
-			$this->revokeShare($share, false);
512
-		}
513
-
514
-		// send revoke notification to the other user, if initiator and owner are not the same user
515
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
516
-			$remoteId = $this->getRemoteId($share);
517
-			if ($isOwner) {
518
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
519
-			} else {
520
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
521
-			}
522
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
523
-		}
524
-	}
525
-
526
-	/**
527
-	 * in case of a re-share we need to send the other use (initiator or owner)
528
-	 * a message that the file was unshared
529
-	 *
530
-	 * @param IShare $share
531
-	 * @param bool $isOwner the user can either be the owner or the user who re-sahred it
532
-	 * @throws ShareNotFound
533
-	 * @throws \OC\HintException
534
-	 */
535
-	protected function revokeShare($share, $isOwner) {
536
-		// also send a unShare request to the initiator, if this is a different user than the owner
537
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
538
-			if ($isOwner) {
539
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
540
-			} else {
541
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
542
-			}
543
-			$remoteId = $this->getRemoteId($share);
544
-			$this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
545
-		}
546
-	}
547
-
548
-	/**
549
-	 * remove share from table
550
-	 *
551
-	 * @param IShare $share
552
-	 */
553
-	public function removeShareFromTable(IShare $share) {
554
-		$this->removeShareFromTableById($share->getId());
555
-	}
556
-
557
-	/**
558
-	 * remove share from table
559
-	 *
560
-	 * @param string $shareId
561
-	 */
562
-	private function removeShareFromTableById($shareId) {
563
-		$qb = $this->dbConnection->getQueryBuilder();
564
-		$qb->delete('share')
565
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
566
-		$qb->execute();
567
-
568
-		$qb->delete('federated_reshares')
569
-			->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
570
-		$qb->execute();
571
-	}
572
-
573
-	/**
574
-	 * @inheritdoc
575
-	 */
576
-	public function deleteFromSelf(IShare $share, $recipient) {
577
-		// nothing to do here. Technically deleteFromSelf in the context of federated
578
-		// shares is a umount of a external storage. This is handled here
579
-		// apps/files_sharing/lib/external/manager.php
580
-		// TODO move this code over to this app
581
-		return;
582
-	}
583
-
584
-
585
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
586
-		$qb = $this->dbConnection->getQueryBuilder();
587
-		$qb->select('*')
588
-			->from('share', 's')
589
-			->andWhere($qb->expr()->orX(
590
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
591
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
592
-			))
593
-			->andWhere(
594
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
595
-			);
596
-
597
-		/**
598
-		 * Reshares for this user are shares where they are the owner.
599
-		 */
600
-		if ($reshares === false) {
601
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
602
-		} else {
603
-			$qb->andWhere(
604
-				$qb->expr()->orX(
605
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
606
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
607
-				)
608
-			);
609
-		}
610
-
611
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
612
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
613
-
614
-		$qb->orderBy('id');
615
-
616
-		$cursor = $qb->execute();
617
-		$shares = [];
618
-		while ($data = $cursor->fetch()) {
619
-			$shares[$data['fileid']][] = $this->createShareObject($data);
620
-		}
621
-		$cursor->closeCursor();
622
-
623
-		return $shares;
624
-	}
625
-
626
-	/**
627
-	 * @inheritdoc
628
-	 */
629
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
630
-		$qb = $this->dbConnection->getQueryBuilder();
631
-		$qb->select('*')
632
-			->from('share');
633
-
634
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
635
-
636
-		/**
637
-		 * Reshares for this user are shares where they are the owner.
638
-		 */
639
-		if ($reshares === false) {
640
-			//Special case for old shares created via the web UI
641
-			$or1 = $qb->expr()->andX(
642
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
643
-				$qb->expr()->isNull('uid_initiator')
644
-			);
645
-
646
-			$qb->andWhere(
647
-				$qb->expr()->orX(
648
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
649
-					$or1
650
-				)
651
-			);
652
-		} else {
653
-			$qb->andWhere(
654
-				$qb->expr()->orX(
655
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
656
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
657
-				)
658
-			);
659
-		}
660
-
661
-		if ($node !== null) {
662
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
663
-		}
664
-
665
-		if ($limit !== -1) {
666
-			$qb->setMaxResults($limit);
667
-		}
668
-
669
-		$qb->setFirstResult($offset);
670
-		$qb->orderBy('id');
671
-
672
-		$cursor = $qb->execute();
673
-		$shares = [];
674
-		while($data = $cursor->fetch()) {
675
-			$shares[] = $this->createShareObject($data);
676
-		}
677
-		$cursor->closeCursor();
678
-
679
-		return $shares;
680
-	}
681
-
682
-	/**
683
-	 * @inheritdoc
684
-	 */
685
-	public function getShareById($id, $recipientId = null) {
686
-		$qb = $this->dbConnection->getQueryBuilder();
687
-
688
-		$qb->select('*')
689
-			->from('share')
690
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
691
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
692
-
693
-		$cursor = $qb->execute();
694
-		$data = $cursor->fetch();
695
-		$cursor->closeCursor();
696
-
697
-		if ($data === false) {
698
-			throw new ShareNotFound();
699
-		}
700
-
701
-		try {
702
-			$share = $this->createShareObject($data);
703
-		} catch (InvalidShare $e) {
704
-			throw new ShareNotFound();
705
-		}
706
-
707
-		return $share;
708
-	}
709
-
710
-	/**
711
-	 * Get shares for a given path
712
-	 *
713
-	 * @param \OCP\Files\Node $path
714
-	 * @return IShare[]
715
-	 */
716
-	public function getSharesByPath(Node $path) {
717
-		$qb = $this->dbConnection->getQueryBuilder();
718
-
719
-		$cursor = $qb->select('*')
720
-			->from('share')
721
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
722
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
723
-			->execute();
724
-
725
-		$shares = [];
726
-		while($data = $cursor->fetch()) {
727
-			$shares[] = $this->createShareObject($data);
728
-		}
729
-		$cursor->closeCursor();
730
-
731
-		return $shares;
732
-	}
733
-
734
-	/**
735
-	 * @inheritdoc
736
-	 */
737
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
738
-		/** @var IShare[] $shares */
739
-		$shares = [];
740
-
741
-		//Get shares directly with this user
742
-		$qb = $this->dbConnection->getQueryBuilder();
743
-		$qb->select('*')
744
-			->from('share');
745
-
746
-		// Order by id
747
-		$qb->orderBy('id');
748
-
749
-		// Set limit and offset
750
-		if ($limit !== -1) {
751
-			$qb->setMaxResults($limit);
752
-		}
753
-		$qb->setFirstResult($offset);
754
-
755
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
756
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
757
-
758
-		// Filter by node if provided
759
-		if ($node !== null) {
760
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
761
-		}
762
-
763
-		$cursor = $qb->execute();
764
-
765
-		while($data = $cursor->fetch()) {
766
-			$shares[] = $this->createShareObject($data);
767
-		}
768
-		$cursor->closeCursor();
769
-
770
-
771
-		return $shares;
772
-	}
773
-
774
-	/**
775
-	 * Get a share by token
776
-	 *
777
-	 * @param string $token
778
-	 * @return IShare
779
-	 * @throws ShareNotFound
780
-	 */
781
-	public function getShareByToken($token) {
782
-		$qb = $this->dbConnection->getQueryBuilder();
783
-
784
-		$cursor = $qb->select('*')
785
-			->from('share')
786
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
787
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
788
-			->execute();
789
-
790
-		$data = $cursor->fetch();
791
-
792
-		if ($data === false) {
793
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
794
-		}
795
-
796
-		try {
797
-			$share = $this->createShareObject($data);
798
-		} catch (InvalidShare $e) {
799
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
800
-		}
801
-
802
-		return $share;
803
-	}
804
-
805
-	/**
806
-	 * get database row of a give share
807
-	 *
808
-	 * @param $id
809
-	 * @return array
810
-	 * @throws ShareNotFound
811
-	 */
812
-	private function getRawShare($id) {
813
-
814
-		// Now fetch the inserted share and create a complete share object
815
-		$qb = $this->dbConnection->getQueryBuilder();
816
-		$qb->select('*')
817
-			->from('share')
818
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
819
-
820
-		$cursor = $qb->execute();
821
-		$data = $cursor->fetch();
822
-		$cursor->closeCursor();
823
-
824
-		if ($data === false) {
825
-			throw new ShareNotFound;
826
-		}
827
-
828
-		return $data;
829
-	}
830
-
831
-	/**
832
-	 * Create a share object from an database row
833
-	 *
834
-	 * @param array $data
835
-	 * @return IShare
836
-	 * @throws InvalidShare
837
-	 * @throws ShareNotFound
838
-	 */
839
-	private function createShareObject($data) {
840
-
841
-		$share = new Share($this->rootFolder, $this->userManager);
842
-		$share->setId((int)$data['id'])
843
-			->setShareType((int)$data['share_type'])
844
-			->setPermissions((int)$data['permissions'])
845
-			->setTarget($data['file_target'])
846
-			->setMailSend((bool)$data['mail_send'])
847
-			->setToken($data['token']);
848
-
849
-		$shareTime = new \DateTime();
850
-		$shareTime->setTimestamp((int)$data['stime']);
851
-		$share->setShareTime($shareTime);
852
-		$share->setSharedWith($data['share_with']);
853
-
854
-		if ($data['uid_initiator'] !== null) {
855
-			$share->setShareOwner($data['uid_owner']);
856
-			$share->setSharedBy($data['uid_initiator']);
857
-		} else {
858
-			//OLD SHARE
859
-			$share->setSharedBy($data['uid_owner']);
860
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
861
-
862
-			$owner = $path->getOwner();
863
-			$share->setShareOwner($owner->getUID());
864
-		}
865
-
866
-		$share->setNodeId((int)$data['file_source']);
867
-		$share->setNodeType($data['item_type']);
868
-
869
-		$share->setProviderId($this->identifier());
870
-
871
-		return $share;
872
-	}
873
-
874
-	/**
875
-	 * Get the node with file $id for $user
876
-	 *
877
-	 * @param string $userId
878
-	 * @param int $id
879
-	 * @return \OCP\Files\File|\OCP\Files\Folder
880
-	 * @throws InvalidShare
881
-	 */
882
-	private function getNode($userId, $id) {
883
-		try {
884
-			$userFolder = $this->rootFolder->getUserFolder($userId);
885
-		} catch (NotFoundException $e) {
886
-			throw new InvalidShare();
887
-		}
888
-
889
-		$nodes = $userFolder->getById($id);
890
-
891
-		if (empty($nodes)) {
892
-			throw new InvalidShare();
893
-		}
894
-
895
-		return $nodes[0];
896
-	}
897
-
898
-	/**
899
-	 * A user is deleted from the system
900
-	 * So clean up the relevant shares.
901
-	 *
902
-	 * @param string $uid
903
-	 * @param int $shareType
904
-	 */
905
-	public function userDeleted($uid, $shareType) {
906
-		//TODO: probabaly a good idea to send unshare info to remote servers
907
-
908
-		$qb = $this->dbConnection->getQueryBuilder();
909
-
910
-		$qb->delete('share')
911
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
912
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
913
-			->execute();
914
-	}
915
-
916
-	/**
917
-	 * This provider does not handle groups
918
-	 *
919
-	 * @param string $gid
920
-	 */
921
-	public function groupDeleted($gid) {
922
-		// We don't handle groups here
923
-		return;
924
-	}
925
-
926
-	/**
927
-	 * This provider does not handle groups
928
-	 *
929
-	 * @param string $uid
930
-	 * @param string $gid
931
-	 */
932
-	public function userDeletedFromGroup($uid, $gid) {
933
-		// We don't handle groups here
934
-		return;
935
-	}
936
-
937
-	/**
938
-	 * check if users from other Nextcloud instances are allowed to mount public links share by this instance
939
-	 *
940
-	 * @return bool
941
-	 */
942
-	public function isOutgoingServer2serverShareEnabled() {
943
-		$result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
944
-		return ($result === 'yes');
945
-	}
946
-
947
-	/**
948
-	 * check if users are allowed to mount public links from other ownClouds
949
-	 *
950
-	 * @return bool
951
-	 */
952
-	public function isIncomingServer2serverShareEnabled() {
953
-		$result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
954
-		return ($result === 'yes');
955
-	}
956
-
957
-	/**
958
-	 * Check if querying sharees on the lookup server is enabled
959
-	 *
960
-	 * @return bool
961
-	 */
962
-	public function isLookupServerQueriesEnabled() {
963
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
964
-		return ($result === 'yes');
965
-	}
966
-
967
-
968
-	/**
969
-	 * Check if it is allowed to publish user specific data to the lookup server
970
-	 *
971
-	 * @return bool
972
-	 */
973
-	public function isLookupServerUploadEnabled() {
974
-		$result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
975
-		return ($result === 'yes');
976
-	}
462
+        return $share;
463
+    }
464
+
465
+    /**
466
+     * Get all children of this share
467
+     *
468
+     * @param IShare $parent
469
+     * @return IShare[]
470
+     */
471
+    public function getChildren(IShare $parent) {
472
+        $children = [];
473
+
474
+        $qb = $this->dbConnection->getQueryBuilder();
475
+        $qb->select('*')
476
+            ->from('share')
477
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
478
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
479
+            ->orderBy('id');
480
+
481
+        $cursor = $qb->execute();
482
+        while($data = $cursor->fetch()) {
483
+            $children[] = $this->createShareObject($data);
484
+        }
485
+        $cursor->closeCursor();
486
+
487
+        return $children;
488
+    }
489
+
490
+    /**
491
+     * Delete a share (owner unShares the file)
492
+     *
493
+     * @param IShare $share
494
+     */
495
+    public function delete(IShare $share) {
496
+
497
+        list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedWith());
498
+
499
+        $isOwner = false;
500
+
501
+        $this->removeShareFromTable($share);
502
+
503
+        // if the local user is the owner we can send the unShare request directly...
504
+        if ($this->userManager->userExists($share->getShareOwner())) {
505
+            $this->notifications->sendRemoteUnShare($remote, $share->getId(), $share->getToken());
506
+            $this->revokeShare($share, true);
507
+            $isOwner = true;
508
+        } else { // ... if not we need to correct ID for the unShare request
509
+            $remoteId = $this->getRemoteId($share);
510
+            $this->notifications->sendRemoteUnShare($remote, $remoteId, $share->getToken());
511
+            $this->revokeShare($share, false);
512
+        }
513
+
514
+        // send revoke notification to the other user, if initiator and owner are not the same user
515
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
516
+            $remoteId = $this->getRemoteId($share);
517
+            if ($isOwner) {
518
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
519
+            } else {
520
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
521
+            }
522
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
523
+        }
524
+    }
525
+
526
+    /**
527
+     * in case of a re-share we need to send the other use (initiator or owner)
528
+     * a message that the file was unshared
529
+     *
530
+     * @param IShare $share
531
+     * @param bool $isOwner the user can either be the owner or the user who re-sahred it
532
+     * @throws ShareNotFound
533
+     * @throws \OC\HintException
534
+     */
535
+    protected function revokeShare($share, $isOwner) {
536
+        // also send a unShare request to the initiator, if this is a different user than the owner
537
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
538
+            if ($isOwner) {
539
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
540
+            } else {
541
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getShareOwner());
542
+            }
543
+            $remoteId = $this->getRemoteId($share);
544
+            $this->notifications->sendRevokeShare($remote, $remoteId, $share->getToken());
545
+        }
546
+    }
547
+
548
+    /**
549
+     * remove share from table
550
+     *
551
+     * @param IShare $share
552
+     */
553
+    public function removeShareFromTable(IShare $share) {
554
+        $this->removeShareFromTableById($share->getId());
555
+    }
556
+
557
+    /**
558
+     * remove share from table
559
+     *
560
+     * @param string $shareId
561
+     */
562
+    private function removeShareFromTableById($shareId) {
563
+        $qb = $this->dbConnection->getQueryBuilder();
564
+        $qb->delete('share')
565
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
566
+        $qb->execute();
567
+
568
+        $qb->delete('federated_reshares')
569
+            ->where($qb->expr()->eq('share_id', $qb->createNamedParameter($shareId)));
570
+        $qb->execute();
571
+    }
572
+
573
+    /**
574
+     * @inheritdoc
575
+     */
576
+    public function deleteFromSelf(IShare $share, $recipient) {
577
+        // nothing to do here. Technically deleteFromSelf in the context of federated
578
+        // shares is a umount of a external storage. This is handled here
579
+        // apps/files_sharing/lib/external/manager.php
580
+        // TODO move this code over to this app
581
+        return;
582
+    }
583
+
584
+
585
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
586
+        $qb = $this->dbConnection->getQueryBuilder();
587
+        $qb->select('*')
588
+            ->from('share', 's')
589
+            ->andWhere($qb->expr()->orX(
590
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
591
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
592
+            ))
593
+            ->andWhere(
594
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE))
595
+            );
596
+
597
+        /**
598
+         * Reshares for this user are shares where they are the owner.
599
+         */
600
+        if ($reshares === false) {
601
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
602
+        } else {
603
+            $qb->andWhere(
604
+                $qb->expr()->orX(
605
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
606
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
607
+                )
608
+            );
609
+        }
610
+
611
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
612
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
613
+
614
+        $qb->orderBy('id');
615
+
616
+        $cursor = $qb->execute();
617
+        $shares = [];
618
+        while ($data = $cursor->fetch()) {
619
+            $shares[$data['fileid']][] = $this->createShareObject($data);
620
+        }
621
+        $cursor->closeCursor();
622
+
623
+        return $shares;
624
+    }
625
+
626
+    /**
627
+     * @inheritdoc
628
+     */
629
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
630
+        $qb = $this->dbConnection->getQueryBuilder();
631
+        $qb->select('*')
632
+            ->from('share');
633
+
634
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
635
+
636
+        /**
637
+         * Reshares for this user are shares where they are the owner.
638
+         */
639
+        if ($reshares === false) {
640
+            //Special case for old shares created via the web UI
641
+            $or1 = $qb->expr()->andX(
642
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
643
+                $qb->expr()->isNull('uid_initiator')
644
+            );
645
+
646
+            $qb->andWhere(
647
+                $qb->expr()->orX(
648
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
649
+                    $or1
650
+                )
651
+            );
652
+        } else {
653
+            $qb->andWhere(
654
+                $qb->expr()->orX(
655
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
656
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
657
+                )
658
+            );
659
+        }
660
+
661
+        if ($node !== null) {
662
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
663
+        }
664
+
665
+        if ($limit !== -1) {
666
+            $qb->setMaxResults($limit);
667
+        }
668
+
669
+        $qb->setFirstResult($offset);
670
+        $qb->orderBy('id');
671
+
672
+        $cursor = $qb->execute();
673
+        $shares = [];
674
+        while($data = $cursor->fetch()) {
675
+            $shares[] = $this->createShareObject($data);
676
+        }
677
+        $cursor->closeCursor();
678
+
679
+        return $shares;
680
+    }
681
+
682
+    /**
683
+     * @inheritdoc
684
+     */
685
+    public function getShareById($id, $recipientId = null) {
686
+        $qb = $this->dbConnection->getQueryBuilder();
687
+
688
+        $qb->select('*')
689
+            ->from('share')
690
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
691
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
692
+
693
+        $cursor = $qb->execute();
694
+        $data = $cursor->fetch();
695
+        $cursor->closeCursor();
696
+
697
+        if ($data === false) {
698
+            throw new ShareNotFound();
699
+        }
700
+
701
+        try {
702
+            $share = $this->createShareObject($data);
703
+        } catch (InvalidShare $e) {
704
+            throw new ShareNotFound();
705
+        }
706
+
707
+        return $share;
708
+    }
709
+
710
+    /**
711
+     * Get shares for a given path
712
+     *
713
+     * @param \OCP\Files\Node $path
714
+     * @return IShare[]
715
+     */
716
+    public function getSharesByPath(Node $path) {
717
+        $qb = $this->dbConnection->getQueryBuilder();
718
+
719
+        $cursor = $qb->select('*')
720
+            ->from('share')
721
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
722
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
723
+            ->execute();
724
+
725
+        $shares = [];
726
+        while($data = $cursor->fetch()) {
727
+            $shares[] = $this->createShareObject($data);
728
+        }
729
+        $cursor->closeCursor();
730
+
731
+        return $shares;
732
+    }
733
+
734
+    /**
735
+     * @inheritdoc
736
+     */
737
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
738
+        /** @var IShare[] $shares */
739
+        $shares = [];
740
+
741
+        //Get shares directly with this user
742
+        $qb = $this->dbConnection->getQueryBuilder();
743
+        $qb->select('*')
744
+            ->from('share');
745
+
746
+        // Order by id
747
+        $qb->orderBy('id');
748
+
749
+        // Set limit and offset
750
+        if ($limit !== -1) {
751
+            $qb->setMaxResults($limit);
752
+        }
753
+        $qb->setFirstResult($offset);
754
+
755
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)));
756
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
757
+
758
+        // Filter by node if provided
759
+        if ($node !== null) {
760
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
761
+        }
762
+
763
+        $cursor = $qb->execute();
764
+
765
+        while($data = $cursor->fetch()) {
766
+            $shares[] = $this->createShareObject($data);
767
+        }
768
+        $cursor->closeCursor();
769
+
770
+
771
+        return $shares;
772
+    }
773
+
774
+    /**
775
+     * Get a share by token
776
+     *
777
+     * @param string $token
778
+     * @return IShare
779
+     * @throws ShareNotFound
780
+     */
781
+    public function getShareByToken($token) {
782
+        $qb = $this->dbConnection->getQueryBuilder();
783
+
784
+        $cursor = $qb->select('*')
785
+            ->from('share')
786
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(self::SHARE_TYPE_REMOTE)))
787
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
788
+            ->execute();
789
+
790
+        $data = $cursor->fetch();
791
+
792
+        if ($data === false) {
793
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
794
+        }
795
+
796
+        try {
797
+            $share = $this->createShareObject($data);
798
+        } catch (InvalidShare $e) {
799
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
800
+        }
801
+
802
+        return $share;
803
+    }
804
+
805
+    /**
806
+     * get database row of a give share
807
+     *
808
+     * @param $id
809
+     * @return array
810
+     * @throws ShareNotFound
811
+     */
812
+    private function getRawShare($id) {
813
+
814
+        // Now fetch the inserted share and create a complete share object
815
+        $qb = $this->dbConnection->getQueryBuilder();
816
+        $qb->select('*')
817
+            ->from('share')
818
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
819
+
820
+        $cursor = $qb->execute();
821
+        $data = $cursor->fetch();
822
+        $cursor->closeCursor();
823
+
824
+        if ($data === false) {
825
+            throw new ShareNotFound;
826
+        }
827
+
828
+        return $data;
829
+    }
830
+
831
+    /**
832
+     * Create a share object from an database row
833
+     *
834
+     * @param array $data
835
+     * @return IShare
836
+     * @throws InvalidShare
837
+     * @throws ShareNotFound
838
+     */
839
+    private function createShareObject($data) {
840
+
841
+        $share = new Share($this->rootFolder, $this->userManager);
842
+        $share->setId((int)$data['id'])
843
+            ->setShareType((int)$data['share_type'])
844
+            ->setPermissions((int)$data['permissions'])
845
+            ->setTarget($data['file_target'])
846
+            ->setMailSend((bool)$data['mail_send'])
847
+            ->setToken($data['token']);
848
+
849
+        $shareTime = new \DateTime();
850
+        $shareTime->setTimestamp((int)$data['stime']);
851
+        $share->setShareTime($shareTime);
852
+        $share->setSharedWith($data['share_with']);
853
+
854
+        if ($data['uid_initiator'] !== null) {
855
+            $share->setShareOwner($data['uid_owner']);
856
+            $share->setSharedBy($data['uid_initiator']);
857
+        } else {
858
+            //OLD SHARE
859
+            $share->setSharedBy($data['uid_owner']);
860
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
861
+
862
+            $owner = $path->getOwner();
863
+            $share->setShareOwner($owner->getUID());
864
+        }
865
+
866
+        $share->setNodeId((int)$data['file_source']);
867
+        $share->setNodeType($data['item_type']);
868
+
869
+        $share->setProviderId($this->identifier());
870
+
871
+        return $share;
872
+    }
873
+
874
+    /**
875
+     * Get the node with file $id for $user
876
+     *
877
+     * @param string $userId
878
+     * @param int $id
879
+     * @return \OCP\Files\File|\OCP\Files\Folder
880
+     * @throws InvalidShare
881
+     */
882
+    private function getNode($userId, $id) {
883
+        try {
884
+            $userFolder = $this->rootFolder->getUserFolder($userId);
885
+        } catch (NotFoundException $e) {
886
+            throw new InvalidShare();
887
+        }
888
+
889
+        $nodes = $userFolder->getById($id);
890
+
891
+        if (empty($nodes)) {
892
+            throw new InvalidShare();
893
+        }
894
+
895
+        return $nodes[0];
896
+    }
897
+
898
+    /**
899
+     * A user is deleted from the system
900
+     * So clean up the relevant shares.
901
+     *
902
+     * @param string $uid
903
+     * @param int $shareType
904
+     */
905
+    public function userDeleted($uid, $shareType) {
906
+        //TODO: probabaly a good idea to send unshare info to remote servers
907
+
908
+        $qb = $this->dbConnection->getQueryBuilder();
909
+
910
+        $qb->delete('share')
911
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_REMOTE)))
912
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
913
+            ->execute();
914
+    }
915
+
916
+    /**
917
+     * This provider does not handle groups
918
+     *
919
+     * @param string $gid
920
+     */
921
+    public function groupDeleted($gid) {
922
+        // We don't handle groups here
923
+        return;
924
+    }
925
+
926
+    /**
927
+     * This provider does not handle groups
928
+     *
929
+     * @param string $uid
930
+     * @param string $gid
931
+     */
932
+    public function userDeletedFromGroup($uid, $gid) {
933
+        // We don't handle groups here
934
+        return;
935
+    }
936
+
937
+    /**
938
+     * check if users from other Nextcloud instances are allowed to mount public links share by this instance
939
+     *
940
+     * @return bool
941
+     */
942
+    public function isOutgoingServer2serverShareEnabled() {
943
+        $result = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes');
944
+        return ($result === 'yes');
945
+    }
946
+
947
+    /**
948
+     * check if users are allowed to mount public links from other ownClouds
949
+     *
950
+     * @return bool
951
+     */
952
+    public function isIncomingServer2serverShareEnabled() {
953
+        $result = $this->config->getAppValue('files_sharing', 'incoming_server2server_share_enabled', 'yes');
954
+        return ($result === 'yes');
955
+    }
956
+
957
+    /**
958
+     * Check if querying sharees on the lookup server is enabled
959
+     *
960
+     * @return bool
961
+     */
962
+    public function isLookupServerQueriesEnabled() {
963
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerEnabled', 'no');
964
+        return ($result === 'yes');
965
+    }
966
+
967
+
968
+    /**
969
+     * Check if it is allowed to publish user specific data to the lookup server
970
+     *
971
+     * @return bool
972
+     */
973
+    public function isLookupServerUploadEnabled() {
974
+        $result = $this->config->getAppValue('files_sharing', 'lookupServerUploadEnabled', 'yes');
975
+        return ($result === 'yes');
976
+    }
977 977
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 		if ($remoteShare) {
183 183
 			try {
184 184
 				$ownerCloudId = $this->cloudIdManager->getCloudId($remoteShare['owner'], $remoteShare['remote']);
185
-				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_' . time());
185
+				$shareId = $this->addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $ownerCloudId->getId(), $permissions, 'tmp_token_'.time());
186 186
 				$share->setId($shareId);
187 187
 				list($token, $remoteId) = $this->askOwnerToReShare($shareWith, $share, $shareId);
188 188
 				// remote share was create successfully if we get a valid token as return
@@ -254,11 +254,11 @@  discard block
 block discarded – undo
254 254
 				$failure = true;
255 255
 			}
256 256
 		} catch (\Exception $e) {
257
-			$this->logger->error('Failed to notify remote server of federated share, removing share (' . $e->getMessage() . ')');
257
+			$this->logger->error('Failed to notify remote server of federated share, removing share ('.$e->getMessage().')');
258 258
 			$failure = true;
259 259
 		}
260 260
 
261
-		if($failure) {
261
+		if ($failure) {
262 262
 			$this->removeShareFromTableById($shareId);
263 263
 			$message_t = $this->l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable or uses a self-signed certificate.',
264 264
 				[$share->getNode()->getName(), $share->getSharedWith()]);
@@ -309,7 +309,7 @@  discard block
 block discarded – undo
309 309
 			->andWhere($query->expr()->eq('mountpoint', $query->createNamedParameter($share->getTarget())));
310 310
 		$result = $query->execute()->fetchAll();
311 311
 
312
-		if (isset($result[0]) && (int)$result[0]['remote_id'] > 0) {
312
+		if (isset($result[0]) && (int) $result[0]['remote_id'] > 0) {
313 313
 			return $result[0];
314 314
 		}
315 315
 
@@ -351,7 +351,7 @@  discard block
 block discarded – undo
351 351
 		$qb->execute();
352 352
 		$id = $qb->getLastInsertId();
353 353
 
354
-		return (int)$id;
354
+		return (int) $id;
355 355
 	}
356 356
 
357 357
 	/**
@@ -441,14 +441,14 @@  discard block
 block discarded – undo
441 441
 	public function getRemoteId(IShare $share) {
442 442
 		$query = $this->dbConnection->getQueryBuilder();
443 443
 		$query->select('remote_id')->from('federated_reshares')
444
-			->where($query->expr()->eq('share_id', $query->createNamedParameter((int)$share->getId())));
444
+			->where($query->expr()->eq('share_id', $query->createNamedParameter((int) $share->getId())));
445 445
 		$data = $query->execute()->fetch();
446 446
 
447 447
 		if (!is_array($data) || !isset($data['remote_id'])) {
448 448
 			throw new ShareNotFound();
449 449
 		}
450 450
 
451
-		return (int)$data['remote_id'];
451
+		return (int) $data['remote_id'];
452 452
 	}
453 453
 
454 454
 	/**
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 			->orderBy('id');
480 480
 
481 481
 		$cursor = $qb->execute();
482
-		while($data = $cursor->fetch()) {
482
+		while ($data = $cursor->fetch()) {
483 483
 			$children[] = $this->createShareObject($data);
484 484
 		}
485 485
 		$cursor->closeCursor();
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 			);
609 609
 		}
610 610
 
611
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
611
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
612 612
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
613 613
 
614 614
 		$qb->orderBy('id');
@@ -671,7 +671,7 @@  discard block
 block discarded – undo
671 671
 
672 672
 		$cursor = $qb->execute();
673 673
 		$shares = [];
674
-		while($data = $cursor->fetch()) {
674
+		while ($data = $cursor->fetch()) {
675 675
 			$shares[] = $this->createShareObject($data);
676 676
 		}
677 677
 		$cursor->closeCursor();
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
 			->execute();
724 724
 
725 725
 		$shares = [];
726
-		while($data = $cursor->fetch()) {
726
+		while ($data = $cursor->fetch()) {
727 727
 			$shares[] = $this->createShareObject($data);
728 728
 		}
729 729
 		$cursor->closeCursor();
@@ -762,7 +762,7 @@  discard block
 block discarded – undo
762 762
 
763 763
 		$cursor = $qb->execute();
764 764
 
765
-		while($data = $cursor->fetch()) {
765
+		while ($data = $cursor->fetch()) {
766 766
 			$shares[] = $this->createShareObject($data);
767 767
 		}
768 768
 		$cursor->closeCursor();
@@ -839,15 +839,15 @@  discard block
 block discarded – undo
839 839
 	private function createShareObject($data) {
840 840
 
841 841
 		$share = new Share($this->rootFolder, $this->userManager);
842
-		$share->setId((int)$data['id'])
843
-			->setShareType((int)$data['share_type'])
844
-			->setPermissions((int)$data['permissions'])
842
+		$share->setId((int) $data['id'])
843
+			->setShareType((int) $data['share_type'])
844
+			->setPermissions((int) $data['permissions'])
845 845
 			->setTarget($data['file_target'])
846
-			->setMailSend((bool)$data['mail_send'])
846
+			->setMailSend((bool) $data['mail_send'])
847 847
 			->setToken($data['token']);
848 848
 
849 849
 		$shareTime = new \DateTime();
850
-		$shareTime->setTimestamp((int)$data['stime']);
850
+		$shareTime->setTimestamp((int) $data['stime']);
851 851
 		$share->setShareTime($shareTime);
852 852
 		$share->setSharedWith($data['share_with']);
853 853
 
@@ -857,13 +857,13 @@  discard block
 block discarded – undo
857 857
 		} else {
858 858
 			//OLD SHARE
859 859
 			$share->setSharedBy($data['uid_owner']);
860
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
860
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
861 861
 
862 862
 			$owner = $path->getOwner();
863 863
 			$share->setShareOwner($owner->getUID());
864 864
 		}
865 865
 
866
-		$share->setNodeId((int)$data['file_source']);
866
+		$share->setNodeId((int) $data['file_source']);
867 867
 		$share->setNodeType($data['item_type']);
868 868
 
869 869
 		$share->setProviderId($this->identifier());
Please login to merge, or discard this patch.
apps/sharebymail/lib/ShareByMailProvider.php 2 patches
Indentation   +790 added lines, -790 removed lines patch added patch discarded remove patch
@@ -50,808 +50,808 @@
 block discarded – undo
50 50
  */
51 51
 class ShareByMailProvider implements IShareProvider {
52 52
 
53
-	/** @var  IDBConnection */
54
-	private $dbConnection;
55
-
56
-	/** @var ILogger */
57
-	private $logger;
58
-
59
-	/** @var ISecureRandom */
60
-	private $secureRandom;
61
-
62
-	/** @var IUserManager */
63
-	private $userManager;
64
-
65
-	/** @var IRootFolder */
66
-	private $rootFolder;
67
-
68
-	/** @var IL10N */
69
-	private $l;
70
-
71
-	/** @var IMailer */
72
-	private $mailer;
73
-
74
-	/** @var IURLGenerator */
75
-	private $urlGenerator;
76
-
77
-	/** @var IManager  */
78
-	private $activityManager;
79
-
80
-	/** @var SettingsManager */
81
-	private $settingsManager;
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 'ocMailShare';
90
-	}
91
-
92
-	/**
93
-	 * DefaultShareProvider constructor.
94
-	 *
95
-	 * @param IDBConnection $connection
96
-	 * @param ISecureRandom $secureRandom
97
-	 * @param IUserManager $userManager
98
-	 * @param IRootFolder $rootFolder
99
-	 * @param IL10N $l
100
-	 * @param ILogger $logger
101
-	 * @param IMailer $mailer
102
-	 * @param IURLGenerator $urlGenerator
103
-	 * @param IManager $activityManager
104
-	 * @param SettingsManager $settingsManager
105
-	 */
106
-	public function __construct(
107
-		IDBConnection $connection,
108
-		ISecureRandom $secureRandom,
109
-		IUserManager $userManager,
110
-		IRootFolder $rootFolder,
111
-		IL10N $l,
112
-		ILogger $logger,
113
-		IMailer $mailer,
114
-		IURLGenerator $urlGenerator,
115
-		IManager $activityManager,
116
-		SettingsManager $settingsManager
117
-	) {
118
-		$this->dbConnection = $connection;
119
-		$this->secureRandom = $secureRandom;
120
-		$this->userManager = $userManager;
121
-		$this->rootFolder = $rootFolder;
122
-		$this->l = $l;
123
-		$this->logger = $logger;
124
-		$this->mailer = $mailer;
125
-		$this->urlGenerator = $urlGenerator;
126
-		$this->activityManager = $activityManager;
127
-		$this->settingsManager = $settingsManager;
128
-	}
129
-
130
-	/**
131
-	 * Share a path
132
-	 *
133
-	 * @param IShare $share
134
-	 * @return IShare The share object
135
-	 * @throws ShareNotFound
136
-	 * @throws \Exception
137
-	 */
138
-	public function create(IShare $share) {
139
-
140
-		$shareWith = $share->getSharedWith();
141
-		/*
53
+    /** @var  IDBConnection */
54
+    private $dbConnection;
55
+
56
+    /** @var ILogger */
57
+    private $logger;
58
+
59
+    /** @var ISecureRandom */
60
+    private $secureRandom;
61
+
62
+    /** @var IUserManager */
63
+    private $userManager;
64
+
65
+    /** @var IRootFolder */
66
+    private $rootFolder;
67
+
68
+    /** @var IL10N */
69
+    private $l;
70
+
71
+    /** @var IMailer */
72
+    private $mailer;
73
+
74
+    /** @var IURLGenerator */
75
+    private $urlGenerator;
76
+
77
+    /** @var IManager  */
78
+    private $activityManager;
79
+
80
+    /** @var SettingsManager */
81
+    private $settingsManager;
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 'ocMailShare';
90
+    }
91
+
92
+    /**
93
+     * DefaultShareProvider constructor.
94
+     *
95
+     * @param IDBConnection $connection
96
+     * @param ISecureRandom $secureRandom
97
+     * @param IUserManager $userManager
98
+     * @param IRootFolder $rootFolder
99
+     * @param IL10N $l
100
+     * @param ILogger $logger
101
+     * @param IMailer $mailer
102
+     * @param IURLGenerator $urlGenerator
103
+     * @param IManager $activityManager
104
+     * @param SettingsManager $settingsManager
105
+     */
106
+    public function __construct(
107
+        IDBConnection $connection,
108
+        ISecureRandom $secureRandom,
109
+        IUserManager $userManager,
110
+        IRootFolder $rootFolder,
111
+        IL10N $l,
112
+        ILogger $logger,
113
+        IMailer $mailer,
114
+        IURLGenerator $urlGenerator,
115
+        IManager $activityManager,
116
+        SettingsManager $settingsManager
117
+    ) {
118
+        $this->dbConnection = $connection;
119
+        $this->secureRandom = $secureRandom;
120
+        $this->userManager = $userManager;
121
+        $this->rootFolder = $rootFolder;
122
+        $this->l = $l;
123
+        $this->logger = $logger;
124
+        $this->mailer = $mailer;
125
+        $this->urlGenerator = $urlGenerator;
126
+        $this->activityManager = $activityManager;
127
+        $this->settingsManager = $settingsManager;
128
+    }
129
+
130
+    /**
131
+     * Share a path
132
+     *
133
+     * @param IShare $share
134
+     * @return IShare The share object
135
+     * @throws ShareNotFound
136
+     * @throws \Exception
137
+     */
138
+    public function create(IShare $share) {
139
+
140
+        $shareWith = $share->getSharedWith();
141
+        /*
142 142
 		 * Check if file is not already shared with the remote user
143 143
 		 */
144
-		$alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
145
-		if (!empty($alreadyShared)) {
146
-			$message = 'Sharing %s failed, this item is already shared with %s';
147
-			$message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
148
-			$this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
149
-			throw new \Exception($message_t);
150
-		}
151
-
152
-		$shareId = $this->createMailShare($share);
153
-		$this->createActivity($share);
154
-		$data = $this->getRawShare($shareId);
155
-		return $this->createShareObject($data);
156
-
157
-	}
158
-
159
-	/**
160
-	 * create activity if a file/folder was shared by mail
161
-	 *
162
-	 * @param IShare $share
163
-	 */
164
-	protected function createActivity(IShare $share) {
165
-
166
-		$userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
167
-
168
-		$this->publishActivity(
169
-			Activity::SUBJECT_SHARED_EMAIL_SELF,
170
-			[$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
171
-			$share->getSharedBy(),
172
-			$share->getNode()->getId(),
173
-			$userFolder->getRelativePath($share->getNode()->getPath())
174
-		);
175
-
176
-		if ($share->getShareOwner() !== $share->getSharedBy()) {
177
-			$ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
178
-			$fileId = $share->getNode()->getId();
179
-			$nodes = $ownerFolder->getById($fileId);
180
-			$ownerPath = $nodes[0]->getPath();
181
-			$this->publishActivity(
182
-				Activity::SUBJECT_SHARED_EMAIL_BY,
183
-				[$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
184
-				$share->getShareOwner(),
185
-				$fileId,
186
-				$ownerFolder->getRelativePath($ownerPath)
187
-			);
188
-		}
189
-
190
-	}
191
-
192
-	/**
193
-	 * publish activity if a file/folder was shared by mail
194
-	 *
195
-	 * @param $subject
196
-	 * @param $parameters
197
-	 * @param $affectedUser
198
-	 * @param $fileId
199
-	 * @param $filePath
200
-	 */
201
-	protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
202
-		$event = $this->activityManager->generateEvent();
203
-		$event->setApp('sharebymail')
204
-			->setType('shared')
205
-			->setSubject($subject, $parameters)
206
-			->setAffectedUser($affectedUser)
207
-			->setObject('files', $fileId, $filePath);
208
-		$this->activityManager->publish($event);
209
-
210
-	}
211
-
212
-	/**
213
-	 * @param IShare $share
214
-	 * @return int
215
-	 * @throws \Exception
216
-	 */
217
-	protected function createMailShare(IShare $share) {
218
-		$share->setToken($this->generateToken());
219
-		$shareId = $this->addShareToDB(
220
-			$share->getNodeId(),
221
-			$share->getNodeType(),
222
-			$share->getSharedWith(),
223
-			$share->getSharedBy(),
224
-			$share->getShareOwner(),
225
-			$share->getPermissions(),
226
-			$share->getToken()
227
-		);
228
-
229
-		try {
230
-			$link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
231
-				['token' => $share->getToken()]);
232
-			$this->sendMailNotification($share->getNode()->getName(),
233
-				$link,
234
-				$share->getShareOwner(),
235
-				$share->getSharedBy(), $share->getSharedWith());
236
-		} catch (HintException $hintException) {
237
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
238
-			$this->removeShareFromTable($shareId);
239
-			throw $hintException;
240
-		} catch (\Exception $e) {
241
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
242
-			$this->removeShareFromTable($shareId);
243
-			throw new HintException('Failed to send share by mail',
244
-				$this->l->t('Failed to send share by E-mail'));
245
-		}
246
-
247
-		return $shareId;
248
-
249
-	}
250
-
251
-	protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
252
-		$ownerUser = $this->userManager->get($owner);
253
-		$initiatorUser = $this->userManager->get($initiator);
254
-		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256
-		if ($owner === $initiator) {
257
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258
-		} else {
259
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260
-		}
261
-
262
-		$message = $this->mailer->createMessage();
263
-		$htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
264
-		$textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
265
-		$message->setTo([$shareWith]);
266
-		$message->setSubject($subject);
267
-		$message->setBody($textBody, 'text/plain');
268
-		$message->setHtmlBody($htmlBody);
269
-		$this->mailer->send($message);
270
-
271
-	}
272
-
273
-	/**
274
-	 * create mail body
275
-	 *
276
-	 * @param $filename
277
-	 * @param $link
278
-	 * @param $owner
279
-	 * @param $initiator
280
-	 * @return string plain text mail
281
-	 * @throws HintException
282
-	 */
283
-	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
284
-
285
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
286
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
287
-		$mailBodyTemplate->assign ('link', $link);
288
-		$mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
289
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
290
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
291
-		$mailBody = $mailBodyTemplate->fetchPage();
292
-
293
-		if (is_string($mailBody)) {
294
-			return $mailBody;
295
-		}
296
-
297
-		throw new HintException('Failed to create the E-mail',
298
-			$this->l->t('Failed to create the E-mail'));
299
-	}
300
-
301
-	/**
302
-	 * send password to recipient of a mail share
303
-	 *
304
-	 * @param string $filename
305
-	 * @param string $initiator
306
-	 * @param string $shareWith
307
-	 */
308
-	protected function sendPassword($filename, $initiator, $shareWith, $password) {
309
-
310
-		if ($this->settingsManager->sendPasswordByMail() === false) {
311
-			return;
312
-		}
313
-
314
-		$initiatorUser = $this->userManager->get($initiator);
315
-		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
316
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
317
-
318
-		$message = $this->mailer->createMessage();
319
-		$htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
320
-		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
321
-		$message->setTo([$shareWith]);
322
-		$message->setSubject($subject);
323
-		$message->setBody($textBody, 'text/plain');
324
-		$message->setHtmlBody($htmlBody);
325
-		$this->mailer->send($message);
326
-
327
-	}
328
-
329
-	/**
330
-	 * create mail body to send password to recipient
331
-	 *
332
-	 * @param string $filename
333
-	 * @param string $initiator
334
-	 * @param string $password
335
-	 * @return string plain text mail
336
-	 * @throws HintException
337
-	 */
338
-	protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
339
-
340
-		$mailBodyTemplate = new Template('sharebymail', $template, '');
341
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
342
-		$mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
343
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
344
-		$mailBody = $mailBodyTemplate->fetchPage();
345
-
346
-		if (is_string($mailBody)) {
347
-			return $mailBody;
348
-		}
349
-
350
-		throw new HintException('Failed to create the E-mail',
351
-			$this->l->t('Failed to create the E-mail'));
352
-	}
353
-
354
-
355
-	/**
356
-	 * generate share token
357
-	 *
358
-	 * @return string
359
-	 */
360
-	protected function generateToken() {
361
-		$token = $this->secureRandom->generate(
362
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
363
-		return $token;
364
-	}
365
-
366
-	/**
367
-	 * Get all children of this share
368
-	 *
369
-	 * @param IShare $parent
370
-	 * @return IShare[]
371
-	 */
372
-	public function getChildren(IShare $parent) {
373
-		$children = [];
374
-
375
-		$qb = $this->dbConnection->getQueryBuilder();
376
-		$qb->select('*')
377
-			->from('share')
378
-			->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
379
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
380
-			->orderBy('id');
381
-
382
-		$cursor = $qb->execute();
383
-		while($data = $cursor->fetch()) {
384
-			$children[] = $this->createShareObject($data);
385
-		}
386
-		$cursor->closeCursor();
387
-
388
-		return $children;
389
-	}
390
-
391
-	/**
392
-	 * add share to the database and return the ID
393
-	 *
394
-	 * @param int $itemSource
395
-	 * @param string $itemType
396
-	 * @param string $shareWith
397
-	 * @param string $sharedBy
398
-	 * @param string $uidOwner
399
-	 * @param int $permissions
400
-	 * @param string $token
401
-	 * @return int
402
-	 */
403
-	protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
404
-		$qb = $this->dbConnection->getQueryBuilder();
405
-		$qb->insert('share')
406
-			->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
407
-			->setValue('item_type', $qb->createNamedParameter($itemType))
408
-			->setValue('item_source', $qb->createNamedParameter($itemSource))
409
-			->setValue('file_source', $qb->createNamedParameter($itemSource))
410
-			->setValue('share_with', $qb->createNamedParameter($shareWith))
411
-			->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
412
-			->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
413
-			->setValue('permissions', $qb->createNamedParameter($permissions))
414
-			->setValue('token', $qb->createNamedParameter($token))
415
-			->setValue('stime', $qb->createNamedParameter(time()));
416
-
417
-		/*
144
+        $alreadyShared = $this->getSharedWith($shareWith, \OCP\Share::SHARE_TYPE_EMAIL, $share->getNode(), 1, 0);
145
+        if (!empty($alreadyShared)) {
146
+            $message = 'Sharing %s failed, this item is already shared with %s';
147
+            $message_t = $this->l->t('Sharing %s failed, this item is already shared with %s', array($share->getNode()->getName(), $shareWith));
148
+            $this->logger->debug(sprintf($message, $share->getNode()->getName(), $shareWith), ['app' => 'Federated File Sharing']);
149
+            throw new \Exception($message_t);
150
+        }
151
+
152
+        $shareId = $this->createMailShare($share);
153
+        $this->createActivity($share);
154
+        $data = $this->getRawShare($shareId);
155
+        return $this->createShareObject($data);
156
+
157
+    }
158
+
159
+    /**
160
+     * create activity if a file/folder was shared by mail
161
+     *
162
+     * @param IShare $share
163
+     */
164
+    protected function createActivity(IShare $share) {
165
+
166
+        $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
167
+
168
+        $this->publishActivity(
169
+            Activity::SUBJECT_SHARED_EMAIL_SELF,
170
+            [$userFolder->getRelativePath($share->getNode()->getPath()), $share->getSharedWith()],
171
+            $share->getSharedBy(),
172
+            $share->getNode()->getId(),
173
+            $userFolder->getRelativePath($share->getNode()->getPath())
174
+        );
175
+
176
+        if ($share->getShareOwner() !== $share->getSharedBy()) {
177
+            $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
178
+            $fileId = $share->getNode()->getId();
179
+            $nodes = $ownerFolder->getById($fileId);
180
+            $ownerPath = $nodes[0]->getPath();
181
+            $this->publishActivity(
182
+                Activity::SUBJECT_SHARED_EMAIL_BY,
183
+                [$ownerFolder->getRelativePath($ownerPath), $share->getSharedWith(), $share->getSharedBy()],
184
+                $share->getShareOwner(),
185
+                $fileId,
186
+                $ownerFolder->getRelativePath($ownerPath)
187
+            );
188
+        }
189
+
190
+    }
191
+
192
+    /**
193
+     * publish activity if a file/folder was shared by mail
194
+     *
195
+     * @param $subject
196
+     * @param $parameters
197
+     * @param $affectedUser
198
+     * @param $fileId
199
+     * @param $filePath
200
+     */
201
+    protected function publishActivity($subject, $parameters, $affectedUser, $fileId, $filePath) {
202
+        $event = $this->activityManager->generateEvent();
203
+        $event->setApp('sharebymail')
204
+            ->setType('shared')
205
+            ->setSubject($subject, $parameters)
206
+            ->setAffectedUser($affectedUser)
207
+            ->setObject('files', $fileId, $filePath);
208
+        $this->activityManager->publish($event);
209
+
210
+    }
211
+
212
+    /**
213
+     * @param IShare $share
214
+     * @return int
215
+     * @throws \Exception
216
+     */
217
+    protected function createMailShare(IShare $share) {
218
+        $share->setToken($this->generateToken());
219
+        $shareId = $this->addShareToDB(
220
+            $share->getNodeId(),
221
+            $share->getNodeType(),
222
+            $share->getSharedWith(),
223
+            $share->getSharedBy(),
224
+            $share->getShareOwner(),
225
+            $share->getPermissions(),
226
+            $share->getToken()
227
+        );
228
+
229
+        try {
230
+            $link = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.showShare',
231
+                ['token' => $share->getToken()]);
232
+            $this->sendMailNotification($share->getNode()->getName(),
233
+                $link,
234
+                $share->getShareOwner(),
235
+                $share->getSharedBy(), $share->getSharedWith());
236
+        } catch (HintException $hintException) {
237
+            $this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
238
+            $this->removeShareFromTable($shareId);
239
+            throw $hintException;
240
+        } catch (\Exception $e) {
241
+            $this->logger->error('Failed to send share by mail: ' . $e->getMessage());
242
+            $this->removeShareFromTable($shareId);
243
+            throw new HintException('Failed to send share by mail',
244
+                $this->l->t('Failed to send share by E-mail'));
245
+        }
246
+
247
+        return $shareId;
248
+
249
+    }
250
+
251
+    protected function sendMailNotification($filename, $link, $owner, $initiator, $shareWith) {
252
+        $ownerUser = $this->userManager->get($owner);
253
+        $initiatorUser = $this->userManager->get($initiator);
254
+        $ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256
+        if ($owner === $initiator) {
257
+            $subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258
+        } else {
259
+            $subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260
+        }
261
+
262
+        $message = $this->mailer->createMessage();
263
+        $htmlBody = $this->createMailBody('mail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
264
+        $textBody = $this->createMailBody('altmail', $filename, $link, $ownerDisplayName, $initiatorDisplayName);
265
+        $message->setTo([$shareWith]);
266
+        $message->setSubject($subject);
267
+        $message->setBody($textBody, 'text/plain');
268
+        $message->setHtmlBody($htmlBody);
269
+        $this->mailer->send($message);
270
+
271
+    }
272
+
273
+    /**
274
+     * create mail body
275
+     *
276
+     * @param $filename
277
+     * @param $link
278
+     * @param $owner
279
+     * @param $initiator
280
+     * @return string plain text mail
281
+     * @throws HintException
282
+     */
283
+    protected function createMailBody($template, $filename, $link, $owner, $initiator) {
284
+
285
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
286
+        $mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
287
+        $mailBodyTemplate->assign ('link', $link);
288
+        $mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
289
+        $mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
290
+        $mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
291
+        $mailBody = $mailBodyTemplate->fetchPage();
292
+
293
+        if (is_string($mailBody)) {
294
+            return $mailBody;
295
+        }
296
+
297
+        throw new HintException('Failed to create the E-mail',
298
+            $this->l->t('Failed to create the E-mail'));
299
+    }
300
+
301
+    /**
302
+     * send password to recipient of a mail share
303
+     *
304
+     * @param string $filename
305
+     * @param string $initiator
306
+     * @param string $shareWith
307
+     */
308
+    protected function sendPassword($filename, $initiator, $shareWith, $password) {
309
+
310
+        if ($this->settingsManager->sendPasswordByMail() === false) {
311
+            return;
312
+        }
313
+
314
+        $initiatorUser = $this->userManager->get($initiator);
315
+        $initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
316
+        $subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
317
+
318
+        $message = $this->mailer->createMessage();
319
+        $htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
320
+        $textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
321
+        $message->setTo([$shareWith]);
322
+        $message->setSubject($subject);
323
+        $message->setBody($textBody, 'text/plain');
324
+        $message->setHtmlBody($htmlBody);
325
+        $this->mailer->send($message);
326
+
327
+    }
328
+
329
+    /**
330
+     * create mail body to send password to recipient
331
+     *
332
+     * @param string $filename
333
+     * @param string $initiator
334
+     * @param string $password
335
+     * @return string plain text mail
336
+     * @throws HintException
337
+     */
338
+    protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
339
+
340
+        $mailBodyTemplate = new Template('sharebymail', $template, '');
341
+        $mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
342
+        $mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
343
+        $mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
344
+        $mailBody = $mailBodyTemplate->fetchPage();
345
+
346
+        if (is_string($mailBody)) {
347
+            return $mailBody;
348
+        }
349
+
350
+        throw new HintException('Failed to create the E-mail',
351
+            $this->l->t('Failed to create the E-mail'));
352
+    }
353
+
354
+
355
+    /**
356
+     * generate share token
357
+     *
358
+     * @return string
359
+     */
360
+    protected function generateToken() {
361
+        $token = $this->secureRandom->generate(
362
+            15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
363
+        return $token;
364
+    }
365
+
366
+    /**
367
+     * Get all children of this share
368
+     *
369
+     * @param IShare $parent
370
+     * @return IShare[]
371
+     */
372
+    public function getChildren(IShare $parent) {
373
+        $children = [];
374
+
375
+        $qb = $this->dbConnection->getQueryBuilder();
376
+        $qb->select('*')
377
+            ->from('share')
378
+            ->where($qb->expr()->eq('parent', $qb->createNamedParameter($parent->getId())))
379
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
380
+            ->orderBy('id');
381
+
382
+        $cursor = $qb->execute();
383
+        while($data = $cursor->fetch()) {
384
+            $children[] = $this->createShareObject($data);
385
+        }
386
+        $cursor->closeCursor();
387
+
388
+        return $children;
389
+    }
390
+
391
+    /**
392
+     * add share to the database and return the ID
393
+     *
394
+     * @param int $itemSource
395
+     * @param string $itemType
396
+     * @param string $shareWith
397
+     * @param string $sharedBy
398
+     * @param string $uidOwner
399
+     * @param int $permissions
400
+     * @param string $token
401
+     * @return int
402
+     */
403
+    protected function addShareToDB($itemSource, $itemType, $shareWith, $sharedBy, $uidOwner, $permissions, $token) {
404
+        $qb = $this->dbConnection->getQueryBuilder();
405
+        $qb->insert('share')
406
+            ->setValue('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
407
+            ->setValue('item_type', $qb->createNamedParameter($itemType))
408
+            ->setValue('item_source', $qb->createNamedParameter($itemSource))
409
+            ->setValue('file_source', $qb->createNamedParameter($itemSource))
410
+            ->setValue('share_with', $qb->createNamedParameter($shareWith))
411
+            ->setValue('uid_owner', $qb->createNamedParameter($uidOwner))
412
+            ->setValue('uid_initiator', $qb->createNamedParameter($sharedBy))
413
+            ->setValue('permissions', $qb->createNamedParameter($permissions))
414
+            ->setValue('token', $qb->createNamedParameter($token))
415
+            ->setValue('stime', $qb->createNamedParameter(time()));
416
+
417
+        /*
418 418
 		 * Added to fix https://github.com/owncloud/core/issues/22215
419 419
 		 * Can be removed once we get rid of ajax/share.php
420 420
 		 */
421
-		$qb->setValue('file_target', $qb->createNamedParameter(''));
421
+        $qb->setValue('file_target', $qb->createNamedParameter(''));
422 422
 
423
-		$qb->execute();
424
-		$id = $qb->getLastInsertId();
423
+        $qb->execute();
424
+        $id = $qb->getLastInsertId();
425 425
 
426
-		return (int)$id;
427
-	}
426
+        return (int)$id;
427
+    }
428 428
 
429
-	/**
430
-	 * Update a share
431
-	 *
432
-	 * @param IShare $share
433
-	 * @param string|null $plainTextPassword
434
-	 * @return IShare The share object
435
-	 */
436
-	public function update(IShare $share, $plainTextPassword = null) {
429
+    /**
430
+     * Update a share
431
+     *
432
+     * @param IShare $share
433
+     * @param string|null $plainTextPassword
434
+     * @return IShare The share object
435
+     */
436
+    public function update(IShare $share, $plainTextPassword = null) {
437 437
 
438
-		$originalShare = $this->getShareById($share->getId());
438
+        $originalShare = $this->getShareById($share->getId());
439 439
 
440
-		// a real password was given
441
-		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
440
+        // a real password was given
441
+        $validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
442 442
 
443
-		if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
444
-			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
445
-		}
446
-		/*
443
+        if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
444
+            $this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
445
+        }
446
+        /*
447 447
 		 * We allow updating the permissions and password of mail shares
448 448
 		 */
449
-		$qb = $this->dbConnection->getQueryBuilder();
450
-		$qb->update('share')
451
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
452
-			->set('permissions', $qb->createNamedParameter($share->getPermissions()))
453
-			->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
454
-			->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
455
-			->set('password', $qb->createNamedParameter($share->getPassword()))
456
-			->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
457
-			->execute();
458
-
459
-		return $share;
460
-	}
461
-
462
-	/**
463
-	 * @inheritdoc
464
-	 */
465
-	public function move(IShare $share, $recipient) {
466
-		/**
467
-		 * nothing to do here, mail shares are only outgoing shares
468
-		 */
469
-		return $share;
470
-	}
471
-
472
-	/**
473
-	 * Delete a share (owner unShares the file)
474
-	 *
475
-	 * @param IShare $share
476
-	 */
477
-	public function delete(IShare $share) {
478
-		$this->removeShareFromTable($share->getId());
479
-	}
480
-
481
-	/**
482
-	 * @inheritdoc
483
-	 */
484
-	public function deleteFromSelf(IShare $share, $recipient) {
485
-		// nothing to do here, mail shares are only outgoing shares
486
-		return;
487
-	}
488
-
489
-	/**
490
-	 * @inheritdoc
491
-	 */
492
-	public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
493
-		$qb = $this->dbConnection->getQueryBuilder();
494
-		$qb->select('*')
495
-			->from('share');
496
-
497
-		$qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
498
-
499
-		/**
500
-		 * Reshares for this user are shares where they are the owner.
501
-		 */
502
-		if ($reshares === false) {
503
-			//Special case for old shares created via the web UI
504
-			$or1 = $qb->expr()->andX(
505
-				$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
506
-				$qb->expr()->isNull('uid_initiator')
507
-			);
508
-
509
-			$qb->andWhere(
510
-				$qb->expr()->orX(
511
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
512
-					$or1
513
-				)
514
-			);
515
-		} else {
516
-			$qb->andWhere(
517
-				$qb->expr()->orX(
518
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
519
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
520
-				)
521
-			);
522
-		}
523
-
524
-		if ($node !== null) {
525
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
526
-		}
527
-
528
-		if ($limit !== -1) {
529
-			$qb->setMaxResults($limit);
530
-		}
531
-
532
-		$qb->setFirstResult($offset);
533
-		$qb->orderBy('id');
534
-
535
-		$cursor = $qb->execute();
536
-		$shares = [];
537
-		while($data = $cursor->fetch()) {
538
-			$shares[] = $this->createShareObject($data);
539
-		}
540
-		$cursor->closeCursor();
541
-
542
-		return $shares;
543
-	}
544
-
545
-	/**
546
-	 * @inheritdoc
547
-	 */
548
-	public function getShareById($id, $recipientId = null) {
549
-		$qb = $this->dbConnection->getQueryBuilder();
550
-
551
-		$qb->select('*')
552
-			->from('share')
553
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
554
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
555
-
556
-		$cursor = $qb->execute();
557
-		$data = $cursor->fetch();
558
-		$cursor->closeCursor();
559
-
560
-		if ($data === false) {
561
-			throw new ShareNotFound();
562
-		}
563
-
564
-		try {
565
-			$share = $this->createShareObject($data);
566
-		} catch (InvalidShare $e) {
567
-			throw new ShareNotFound();
568
-		}
569
-
570
-		return $share;
571
-	}
572
-
573
-	/**
574
-	 * Get shares for a given path
575
-	 *
576
-	 * @param \OCP\Files\Node $path
577
-	 * @return IShare[]
578
-	 */
579
-	public function getSharesByPath(Node $path) {
580
-		$qb = $this->dbConnection->getQueryBuilder();
581
-
582
-		$cursor = $qb->select('*')
583
-			->from('share')
584
-			->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
585
-			->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
586
-			->execute();
587
-
588
-		$shares = [];
589
-		while($data = $cursor->fetch()) {
590
-			$shares[] = $this->createShareObject($data);
591
-		}
592
-		$cursor->closeCursor();
593
-
594
-		return $shares;
595
-	}
596
-
597
-	/**
598
-	 * @inheritdoc
599
-	 */
600
-	public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
601
-		/** @var IShare[] $shares */
602
-		$shares = [];
603
-
604
-		//Get shares directly with this user
605
-		$qb = $this->dbConnection->getQueryBuilder();
606
-		$qb->select('*')
607
-			->from('share');
608
-
609
-		// Order by id
610
-		$qb->orderBy('id');
611
-
612
-		// Set limit and offset
613
-		if ($limit !== -1) {
614
-			$qb->setMaxResults($limit);
615
-		}
616
-		$qb->setFirstResult($offset);
617
-
618
-		$qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
619
-		$qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
620
-
621
-		// Filter by node if provided
622
-		if ($node !== null) {
623
-			$qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
624
-		}
625
-
626
-		$cursor = $qb->execute();
627
-
628
-		while($data = $cursor->fetch()) {
629
-			$shares[] = $this->createShareObject($data);
630
-		}
631
-		$cursor->closeCursor();
632
-
633
-
634
-		return $shares;
635
-	}
636
-
637
-	/**
638
-	 * Get a share by token
639
-	 *
640
-	 * @param string $token
641
-	 * @return IShare
642
-	 * @throws ShareNotFound
643
-	 */
644
-	public function getShareByToken($token) {
645
-		$qb = $this->dbConnection->getQueryBuilder();
646
-
647
-		$cursor = $qb->select('*')
648
-			->from('share')
649
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
650
-			->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
651
-			->execute();
652
-
653
-		$data = $cursor->fetch();
654
-
655
-		if ($data === false) {
656
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
657
-		}
658
-
659
-		try {
660
-			$share = $this->createShareObject($data);
661
-		} catch (InvalidShare $e) {
662
-			throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
663
-		}
664
-
665
-		return $share;
666
-	}
667
-
668
-	/**
669
-	 * remove share from table
670
-	 *
671
-	 * @param string $shareId
672
-	 */
673
-	protected function removeShareFromTable($shareId) {
674
-		$qb = $this->dbConnection->getQueryBuilder();
675
-		$qb->delete('share')
676
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
677
-		$qb->execute();
678
-	}
679
-
680
-	/**
681
-	 * Create a share object from an database row
682
-	 *
683
-	 * @param array $data
684
-	 * @return IShare
685
-	 * @throws InvalidShare
686
-	 * @throws ShareNotFound
687
-	 */
688
-	protected function createShareObject($data) {
689
-
690
-		$share = new Share($this->rootFolder, $this->userManager);
691
-		$share->setId((int)$data['id'])
692
-			->setShareType((int)$data['share_type'])
693
-			->setPermissions((int)$data['permissions'])
694
-			->setTarget($data['file_target'])
695
-			->setMailSend((bool)$data['mail_send'])
696
-			->setToken($data['token']);
697
-
698
-		$shareTime = new \DateTime();
699
-		$shareTime->setTimestamp((int)$data['stime']);
700
-		$share->setShareTime($shareTime);
701
-		$share->setSharedWith($data['share_with']);
702
-		$share->setPassword($data['password']);
703
-
704
-		if ($data['uid_initiator'] !== null) {
705
-			$share->setShareOwner($data['uid_owner']);
706
-			$share->setSharedBy($data['uid_initiator']);
707
-		} else {
708
-			//OLD SHARE
709
-			$share->setSharedBy($data['uid_owner']);
710
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
711
-
712
-			$owner = $path->getOwner();
713
-			$share->setShareOwner($owner->getUID());
714
-		}
715
-
716
-		if ($data['expiration'] !== null) {
717
-			$expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
718
-			if ($expiration !== false) {
719
-				$share->setExpirationDate($expiration);
720
-			}
721
-		}
722
-
723
-		$share->setNodeId((int)$data['file_source']);
724
-		$share->setNodeType($data['item_type']);
725
-
726
-		$share->setProviderId($this->identifier());
727
-
728
-		return $share;
729
-	}
730
-
731
-	/**
732
-	 * Get the node with file $id for $user
733
-	 *
734
-	 * @param string $userId
735
-	 * @param int $id
736
-	 * @return \OCP\Files\File|\OCP\Files\Folder
737
-	 * @throws InvalidShare
738
-	 */
739
-	private function getNode($userId, $id) {
740
-		try {
741
-			$userFolder = $this->rootFolder->getUserFolder($userId);
742
-		} catch (NotFoundException $e) {
743
-			throw new InvalidShare();
744
-		}
745
-
746
-		$nodes = $userFolder->getById($id);
747
-
748
-		if (empty($nodes)) {
749
-			throw new InvalidShare();
750
-		}
751
-
752
-		return $nodes[0];
753
-	}
754
-
755
-	/**
756
-	 * A user is deleted from the system
757
-	 * So clean up the relevant shares.
758
-	 *
759
-	 * @param string $uid
760
-	 * @param int $shareType
761
-	 */
762
-	public function userDeleted($uid, $shareType) {
763
-		$qb = $this->dbConnection->getQueryBuilder();
764
-
765
-		$qb->delete('share')
766
-			->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
767
-			->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
768
-			->execute();
769
-	}
770
-
771
-	/**
772
-	 * This provider does not support group shares
773
-	 *
774
-	 * @param string $gid
775
-	 */
776
-	public function groupDeleted($gid) {
777
-		return;
778
-	}
779
-
780
-	/**
781
-	 * This provider does not support group shares
782
-	 *
783
-	 * @param string $uid
784
-	 * @param string $gid
785
-	 */
786
-	public function userDeletedFromGroup($uid, $gid) {
787
-		return;
788
-	}
789
-
790
-	/**
791
-	 * get database row of a give share
792
-	 *
793
-	 * @param $id
794
-	 * @return array
795
-	 * @throws ShareNotFound
796
-	 */
797
-	protected function getRawShare($id) {
798
-
799
-		// Now fetch the inserted share and create a complete share object
800
-		$qb = $this->dbConnection->getQueryBuilder();
801
-		$qb->select('*')
802
-			->from('share')
803
-			->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
804
-
805
-		$cursor = $qb->execute();
806
-		$data = $cursor->fetch();
807
-		$cursor->closeCursor();
808
-
809
-		if ($data === false) {
810
-			throw new ShareNotFound;
811
-		}
812
-
813
-		return $data;
814
-	}
815
-
816
-	public function getSharesInFolder($userId, Folder $node, $reshares) {
817
-		$qb = $this->dbConnection->getQueryBuilder();
818
-		$qb->select('*')
819
-			->from('share', 's')
820
-			->andWhere($qb->expr()->orX(
821
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
822
-				$qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
823
-			))
824
-			->andWhere(
825
-				$qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
826
-			);
827
-
828
-		/**
829
-		 * Reshares for this user are shares where they are the owner.
830
-		 */
831
-		if ($reshares === false) {
832
-			$qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
833
-		} else {
834
-			$qb->andWhere(
835
-				$qb->expr()->orX(
836
-					$qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
837
-					$qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
838
-				)
839
-			);
840
-		}
841
-
842
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
843
-		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
844
-
845
-		$qb->orderBy('id');
846
-
847
-		$cursor = $qb->execute();
848
-		$shares = [];
849
-		while ($data = $cursor->fetch()) {
850
-			$shares[$data['fileid']][] = $this->createShareObject($data);
851
-		}
852
-		$cursor->closeCursor();
853
-
854
-		return $shares;
855
-	}
449
+        $qb = $this->dbConnection->getQueryBuilder();
450
+        $qb->update('share')
451
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($share->getId())))
452
+            ->set('permissions', $qb->createNamedParameter($share->getPermissions()))
453
+            ->set('uid_owner', $qb->createNamedParameter($share->getShareOwner()))
454
+            ->set('uid_initiator', $qb->createNamedParameter($share->getSharedBy()))
455
+            ->set('password', $qb->createNamedParameter($share->getPassword()))
456
+            ->set('expiration', $qb->createNamedParameter($share->getExpirationDate(), IQueryBuilder::PARAM_DATE))
457
+            ->execute();
458
+
459
+        return $share;
460
+    }
461
+
462
+    /**
463
+     * @inheritdoc
464
+     */
465
+    public function move(IShare $share, $recipient) {
466
+        /**
467
+         * nothing to do here, mail shares are only outgoing shares
468
+         */
469
+        return $share;
470
+    }
471
+
472
+    /**
473
+     * Delete a share (owner unShares the file)
474
+     *
475
+     * @param IShare $share
476
+     */
477
+    public function delete(IShare $share) {
478
+        $this->removeShareFromTable($share->getId());
479
+    }
480
+
481
+    /**
482
+     * @inheritdoc
483
+     */
484
+    public function deleteFromSelf(IShare $share, $recipient) {
485
+        // nothing to do here, mail shares are only outgoing shares
486
+        return;
487
+    }
488
+
489
+    /**
490
+     * @inheritdoc
491
+     */
492
+    public function getSharesBy($userId, $shareType, $node, $reshares, $limit, $offset) {
493
+        $qb = $this->dbConnection->getQueryBuilder();
494
+        $qb->select('*')
495
+            ->from('share');
496
+
497
+        $qb->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
498
+
499
+        /**
500
+         * Reshares for this user are shares where they are the owner.
501
+         */
502
+        if ($reshares === false) {
503
+            //Special case for old shares created via the web UI
504
+            $or1 = $qb->expr()->andX(
505
+                $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
506
+                $qb->expr()->isNull('uid_initiator')
507
+            );
508
+
509
+            $qb->andWhere(
510
+                $qb->expr()->orX(
511
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)),
512
+                    $or1
513
+                )
514
+            );
515
+        } else {
516
+            $qb->andWhere(
517
+                $qb->expr()->orX(
518
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
519
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
520
+                )
521
+            );
522
+        }
523
+
524
+        if ($node !== null) {
525
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
526
+        }
527
+
528
+        if ($limit !== -1) {
529
+            $qb->setMaxResults($limit);
530
+        }
531
+
532
+        $qb->setFirstResult($offset);
533
+        $qb->orderBy('id');
534
+
535
+        $cursor = $qb->execute();
536
+        $shares = [];
537
+        while($data = $cursor->fetch()) {
538
+            $shares[] = $this->createShareObject($data);
539
+        }
540
+        $cursor->closeCursor();
541
+
542
+        return $shares;
543
+    }
544
+
545
+    /**
546
+     * @inheritdoc
547
+     */
548
+    public function getShareById($id, $recipientId = null) {
549
+        $qb = $this->dbConnection->getQueryBuilder();
550
+
551
+        $qb->select('*')
552
+            ->from('share')
553
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)))
554
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
555
+
556
+        $cursor = $qb->execute();
557
+        $data = $cursor->fetch();
558
+        $cursor->closeCursor();
559
+
560
+        if ($data === false) {
561
+            throw new ShareNotFound();
562
+        }
563
+
564
+        try {
565
+            $share = $this->createShareObject($data);
566
+        } catch (InvalidShare $e) {
567
+            throw new ShareNotFound();
568
+        }
569
+
570
+        return $share;
571
+    }
572
+
573
+    /**
574
+     * Get shares for a given path
575
+     *
576
+     * @param \OCP\Files\Node $path
577
+     * @return IShare[]
578
+     */
579
+    public function getSharesByPath(Node $path) {
580
+        $qb = $this->dbConnection->getQueryBuilder();
581
+
582
+        $cursor = $qb->select('*')
583
+            ->from('share')
584
+            ->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($path->getId())))
585
+            ->andWhere($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
586
+            ->execute();
587
+
588
+        $shares = [];
589
+        while($data = $cursor->fetch()) {
590
+            $shares[] = $this->createShareObject($data);
591
+        }
592
+        $cursor->closeCursor();
593
+
594
+        return $shares;
595
+    }
596
+
597
+    /**
598
+     * @inheritdoc
599
+     */
600
+    public function getSharedWith($userId, $shareType, $node, $limit, $offset) {
601
+        /** @var IShare[] $shares */
602
+        $shares = [];
603
+
604
+        //Get shares directly with this user
605
+        $qb = $this->dbConnection->getQueryBuilder();
606
+        $qb->select('*')
607
+            ->from('share');
608
+
609
+        // Order by id
610
+        $qb->orderBy('id');
611
+
612
+        // Set limit and offset
613
+        if ($limit !== -1) {
614
+            $qb->setMaxResults($limit);
615
+        }
616
+        $qb->setFirstResult($offset);
617
+
618
+        $qb->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)));
619
+        $qb->andWhere($qb->expr()->eq('share_with', $qb->createNamedParameter($userId)));
620
+
621
+        // Filter by node if provided
622
+        if ($node !== null) {
623
+            $qb->andWhere($qb->expr()->eq('file_source', $qb->createNamedParameter($node->getId())));
624
+        }
625
+
626
+        $cursor = $qb->execute();
627
+
628
+        while($data = $cursor->fetch()) {
629
+            $shares[] = $this->createShareObject($data);
630
+        }
631
+        $cursor->closeCursor();
632
+
633
+
634
+        return $shares;
635
+    }
636
+
637
+    /**
638
+     * Get a share by token
639
+     *
640
+     * @param string $token
641
+     * @return IShare
642
+     * @throws ShareNotFound
643
+     */
644
+    public function getShareByToken($token) {
645
+        $qb = $this->dbConnection->getQueryBuilder();
646
+
647
+        $cursor = $qb->select('*')
648
+            ->from('share')
649
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
650
+            ->andWhere($qb->expr()->eq('token', $qb->createNamedParameter($token)))
651
+            ->execute();
652
+
653
+        $data = $cursor->fetch();
654
+
655
+        if ($data === false) {
656
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
657
+        }
658
+
659
+        try {
660
+            $share = $this->createShareObject($data);
661
+        } catch (InvalidShare $e) {
662
+            throw new ShareNotFound('Share not found', $this->l->t('Could not find share'));
663
+        }
664
+
665
+        return $share;
666
+    }
667
+
668
+    /**
669
+     * remove share from table
670
+     *
671
+     * @param string $shareId
672
+     */
673
+    protected function removeShareFromTable($shareId) {
674
+        $qb = $this->dbConnection->getQueryBuilder();
675
+        $qb->delete('share')
676
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($shareId)));
677
+        $qb->execute();
678
+    }
679
+
680
+    /**
681
+     * Create a share object from an database row
682
+     *
683
+     * @param array $data
684
+     * @return IShare
685
+     * @throws InvalidShare
686
+     * @throws ShareNotFound
687
+     */
688
+    protected function createShareObject($data) {
689
+
690
+        $share = new Share($this->rootFolder, $this->userManager);
691
+        $share->setId((int)$data['id'])
692
+            ->setShareType((int)$data['share_type'])
693
+            ->setPermissions((int)$data['permissions'])
694
+            ->setTarget($data['file_target'])
695
+            ->setMailSend((bool)$data['mail_send'])
696
+            ->setToken($data['token']);
697
+
698
+        $shareTime = new \DateTime();
699
+        $shareTime->setTimestamp((int)$data['stime']);
700
+        $share->setShareTime($shareTime);
701
+        $share->setSharedWith($data['share_with']);
702
+        $share->setPassword($data['password']);
703
+
704
+        if ($data['uid_initiator'] !== null) {
705
+            $share->setShareOwner($data['uid_owner']);
706
+            $share->setSharedBy($data['uid_initiator']);
707
+        } else {
708
+            //OLD SHARE
709
+            $share->setSharedBy($data['uid_owner']);
710
+            $path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
711
+
712
+            $owner = $path->getOwner();
713
+            $share->setShareOwner($owner->getUID());
714
+        }
715
+
716
+        if ($data['expiration'] !== null) {
717
+            $expiration = \DateTime::createFromFormat('Y-m-d H:i:s', $data['expiration']);
718
+            if ($expiration !== false) {
719
+                $share->setExpirationDate($expiration);
720
+            }
721
+        }
722
+
723
+        $share->setNodeId((int)$data['file_source']);
724
+        $share->setNodeType($data['item_type']);
725
+
726
+        $share->setProviderId($this->identifier());
727
+
728
+        return $share;
729
+    }
730
+
731
+    /**
732
+     * Get the node with file $id for $user
733
+     *
734
+     * @param string $userId
735
+     * @param int $id
736
+     * @return \OCP\Files\File|\OCP\Files\Folder
737
+     * @throws InvalidShare
738
+     */
739
+    private function getNode($userId, $id) {
740
+        try {
741
+            $userFolder = $this->rootFolder->getUserFolder($userId);
742
+        } catch (NotFoundException $e) {
743
+            throw new InvalidShare();
744
+        }
745
+
746
+        $nodes = $userFolder->getById($id);
747
+
748
+        if (empty($nodes)) {
749
+            throw new InvalidShare();
750
+        }
751
+
752
+        return $nodes[0];
753
+    }
754
+
755
+    /**
756
+     * A user is deleted from the system
757
+     * So clean up the relevant shares.
758
+     *
759
+     * @param string $uid
760
+     * @param int $shareType
761
+     */
762
+    public function userDeleted($uid, $shareType) {
763
+        $qb = $this->dbConnection->getQueryBuilder();
764
+
765
+        $qb->delete('share')
766
+            ->where($qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL)))
767
+            ->andWhere($qb->expr()->eq('uid_owner', $qb->createNamedParameter($uid)))
768
+            ->execute();
769
+    }
770
+
771
+    /**
772
+     * This provider does not support group shares
773
+     *
774
+     * @param string $gid
775
+     */
776
+    public function groupDeleted($gid) {
777
+        return;
778
+    }
779
+
780
+    /**
781
+     * This provider does not support group shares
782
+     *
783
+     * @param string $uid
784
+     * @param string $gid
785
+     */
786
+    public function userDeletedFromGroup($uid, $gid) {
787
+        return;
788
+    }
789
+
790
+    /**
791
+     * get database row of a give share
792
+     *
793
+     * @param $id
794
+     * @return array
795
+     * @throws ShareNotFound
796
+     */
797
+    protected function getRawShare($id) {
798
+
799
+        // Now fetch the inserted share and create a complete share object
800
+        $qb = $this->dbConnection->getQueryBuilder();
801
+        $qb->select('*')
802
+            ->from('share')
803
+            ->where($qb->expr()->eq('id', $qb->createNamedParameter($id)));
804
+
805
+        $cursor = $qb->execute();
806
+        $data = $cursor->fetch();
807
+        $cursor->closeCursor();
808
+
809
+        if ($data === false) {
810
+            throw new ShareNotFound;
811
+        }
812
+
813
+        return $data;
814
+    }
815
+
816
+    public function getSharesInFolder($userId, Folder $node, $reshares) {
817
+        $qb = $this->dbConnection->getQueryBuilder();
818
+        $qb->select('*')
819
+            ->from('share', 's')
820
+            ->andWhere($qb->expr()->orX(
821
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('file')),
822
+                $qb->expr()->eq('item_type', $qb->createNamedParameter('folder'))
823
+            ))
824
+            ->andWhere(
825
+                $qb->expr()->eq('share_type', $qb->createNamedParameter(\OCP\Share::SHARE_TYPE_EMAIL))
826
+            );
827
+
828
+        /**
829
+         * Reshares for this user are shares where they are the owner.
830
+         */
831
+        if ($reshares === false) {
832
+            $qb->andWhere($qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId)));
833
+        } else {
834
+            $qb->andWhere(
835
+                $qb->expr()->orX(
836
+                    $qb->expr()->eq('uid_owner', $qb->createNamedParameter($userId)),
837
+                    $qb->expr()->eq('uid_initiator', $qb->createNamedParameter($userId))
838
+                )
839
+            );
840
+        }
841
+
842
+        $qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
843
+        $qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
844
+
845
+        $qb->orderBy('id');
846
+
847
+        $cursor = $qb->execute();
848
+        $shares = [];
849
+        while ($data = $cursor->fetch()) {
850
+            $shares[$data['fileid']][] = $this->createShareObject($data);
851
+        }
852
+        $cursor->closeCursor();
853
+
854
+        return $shares;
855
+    }
856 856
 
857 857
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -234,11 +234,11 @@  discard block
 block discarded – undo
234 234
 				$share->getShareOwner(),
235 235
 				$share->getSharedBy(), $share->getSharedWith());
236 236
 		} catch (HintException $hintException) {
237
-			$this->logger->error('Failed to send share by mail: ' . $hintException->getMessage());
237
+			$this->logger->error('Failed to send share by mail: '.$hintException->getMessage());
238 238
 			$this->removeShareFromTable($shareId);
239 239
 			throw $hintException;
240 240
 		} catch (\Exception $e) {
241
-			$this->logger->error('Failed to send share by mail: ' . $e->getMessage());
241
+			$this->logger->error('Failed to send share by mail: '.$e->getMessage());
242 242
 			$this->removeShareFromTable($shareId);
243 243
 			throw new HintException('Failed to send share by mail',
244 244
 				$this->l->t('Failed to send share by E-mail'));
@@ -254,9 +254,9 @@  discard block
 block discarded – undo
254 254
 		$ownerDisplayName = ($ownerUser instanceof IUser) ? $ownerUser->getDisplayName() : $owner;
255 255
 		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
256 256
 		if ($owner === $initiator) {
257
-			$subject = (string)$this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
257
+			$subject = (string) $this->l->t('%s shared »%s« with you', array($ownerDisplayName, $filename));
258 258
 		} else {
259
-			$subject = (string)$this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
259
+			$subject = (string) $this->l->t('%s shared »%s« with you on behalf of %s', array($ownerDisplayName, $filename, $initiatorDisplayName));
260 260
 		}
261 261
 
262 262
 		$message = $this->mailer->createMessage();
@@ -283,11 +283,11 @@  discard block
 block discarded – undo
283 283
 	protected function createMailBody($template, $filename, $link, $owner, $initiator) {
284 284
 
285 285
 		$mailBodyTemplate = new Template('sharebymail', $template, '');
286
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
287
-		$mailBodyTemplate->assign ('link', $link);
288
-		$mailBodyTemplate->assign ('owner', \OCP\Util::sanitizeHTML($owner));
289
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
290
-		$mailBodyTemplate->assign ('onBehalfOf', $initiator !== $owner);
286
+		$mailBodyTemplate->assign('filename', \OCP\Util::sanitizeHTML($filename));
287
+		$mailBodyTemplate->assign('link', $link);
288
+		$mailBodyTemplate->assign('owner', \OCP\Util::sanitizeHTML($owner));
289
+		$mailBodyTemplate->assign('initiator', \OCP\Util::sanitizeHTML($initiator));
290
+		$mailBodyTemplate->assign('onBehalfOf', $initiator !== $owner);
291 291
 		$mailBody = $mailBodyTemplate->fetchPage();
292 292
 
293 293
 		if (is_string($mailBody)) {
@@ -313,11 +313,11 @@  discard block
 block discarded – undo
313 313
 
314 314
 		$initiatorUser = $this->userManager->get($initiator);
315 315
 		$initiatorDisplayName = ($initiatorUser instanceof IUser) ? $initiatorUser->getDisplayName() : $initiator;
316
-		$subject = (string)$this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
316
+		$subject = (string) $this->l->t('Password to access »%s« shared to you by %s', [$filename, $initiatorDisplayName]);
317 317
 
318 318
 		$message = $this->mailer->createMessage();
319 319
 		$htmlBody = $this->createMailBodyToSendPassword('mailpassword', $filename, $initiatorDisplayName, $password);
320
-		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename,$initiatorDisplayName, $password);
320
+		$textBody = $this->createMailBodyToSendPassword('altmailpassword', $filename, $initiatorDisplayName, $password);
321 321
 		$message->setTo([$shareWith]);
322 322
 		$message->setSubject($subject);
323 323
 		$message->setBody($textBody, 'text/plain');
@@ -338,9 +338,9 @@  discard block
 block discarded – undo
338 338
 	protected function createMailBodyToSendPassword($template, $filename, $initiator, $password) {
339 339
 
340 340
 		$mailBodyTemplate = new Template('sharebymail', $template, '');
341
-		$mailBodyTemplate->assign ('filename', \OCP\Util::sanitizeHTML($filename));
342
-		$mailBodyTemplate->assign ('password', \OCP\Util::sanitizeHTML($password));
343
-		$mailBodyTemplate->assign ('initiator', \OCP\Util::sanitizeHTML($initiator));
341
+		$mailBodyTemplate->assign('filename', \OCP\Util::sanitizeHTML($filename));
342
+		$mailBodyTemplate->assign('password', \OCP\Util::sanitizeHTML($password));
343
+		$mailBodyTemplate->assign('initiator', \OCP\Util::sanitizeHTML($initiator));
344 344
 		$mailBody = $mailBodyTemplate->fetchPage();
345 345
 
346 346
 		if (is_string($mailBody)) {
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
 	 */
360 360
 	protected function generateToken() {
361 361
 		$token = $this->secureRandom->generate(
362
-			15, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
362
+			15, ISecureRandom::CHAR_LOWER.ISecureRandom::CHAR_UPPER.ISecureRandom::CHAR_DIGITS);
363 363
 		return $token;
364 364
 	}
365 365
 
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 			->orderBy('id');
381 381
 
382 382
 		$cursor = $qb->execute();
383
-		while($data = $cursor->fetch()) {
383
+		while ($data = $cursor->fetch()) {
384 384
 			$children[] = $this->createShareObject($data);
385 385
 		}
386 386
 		$cursor->closeCursor();
@@ -423,7 +423,7 @@  discard block
 block discarded – undo
423 423
 		$qb->execute();
424 424
 		$id = $qb->getLastInsertId();
425 425
 
426
-		return (int)$id;
426
+		return (int) $id;
427 427
 	}
428 428
 
429 429
 	/**
@@ -440,7 +440,7 @@  discard block
 block discarded – undo
440 440
 		// a real password was given
441 441
 		$validPassword = $plainTextPassword !== null && $plainTextPassword !== '';
442 442
 
443
-		if($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
443
+		if ($validPassword && $originalShare->getPassword() !== $share->getPassword()) {
444 444
 			$this->sendPassword($share->getNode()->getName(), $share->getSharedBy(), $share->getSharedWith(), $plainTextPassword);
445 445
 		}
446 446
 		/*
@@ -534,7 +534,7 @@  discard block
 block discarded – undo
534 534
 
535 535
 		$cursor = $qb->execute();
536 536
 		$shares = [];
537
-		while($data = $cursor->fetch()) {
537
+		while ($data = $cursor->fetch()) {
538 538
 			$shares[] = $this->createShareObject($data);
539 539
 		}
540 540
 		$cursor->closeCursor();
@@ -586,7 +586,7 @@  discard block
 block discarded – undo
586 586
 			->execute();
587 587
 
588 588
 		$shares = [];
589
-		while($data = $cursor->fetch()) {
589
+		while ($data = $cursor->fetch()) {
590 590
 			$shares[] = $this->createShareObject($data);
591 591
 		}
592 592
 		$cursor->closeCursor();
@@ -625,7 +625,7 @@  discard block
 block discarded – undo
625 625
 
626 626
 		$cursor = $qb->execute();
627 627
 
628
-		while($data = $cursor->fetch()) {
628
+		while ($data = $cursor->fetch()) {
629 629
 			$shares[] = $this->createShareObject($data);
630 630
 		}
631 631
 		$cursor->closeCursor();
@@ -688,15 +688,15 @@  discard block
 block discarded – undo
688 688
 	protected function createShareObject($data) {
689 689
 
690 690
 		$share = new Share($this->rootFolder, $this->userManager);
691
-		$share->setId((int)$data['id'])
692
-			->setShareType((int)$data['share_type'])
693
-			->setPermissions((int)$data['permissions'])
691
+		$share->setId((int) $data['id'])
692
+			->setShareType((int) $data['share_type'])
693
+			->setPermissions((int) $data['permissions'])
694 694
 			->setTarget($data['file_target'])
695
-			->setMailSend((bool)$data['mail_send'])
695
+			->setMailSend((bool) $data['mail_send'])
696 696
 			->setToken($data['token']);
697 697
 
698 698
 		$shareTime = new \DateTime();
699
-		$shareTime->setTimestamp((int)$data['stime']);
699
+		$shareTime->setTimestamp((int) $data['stime']);
700 700
 		$share->setShareTime($shareTime);
701 701
 		$share->setSharedWith($data['share_with']);
702 702
 		$share->setPassword($data['password']);
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 		} else {
708 708
 			//OLD SHARE
709 709
 			$share->setSharedBy($data['uid_owner']);
710
-			$path = $this->getNode($share->getSharedBy(), (int)$data['file_source']);
710
+			$path = $this->getNode($share->getSharedBy(), (int) $data['file_source']);
711 711
 
712 712
 			$owner = $path->getOwner();
713 713
 			$share->setShareOwner($owner->getUID());
@@ -720,7 +720,7 @@  discard block
 block discarded – undo
720 720
 			}
721 721
 		}
722 722
 
723
-		$share->setNodeId((int)$data['file_source']);
723
+		$share->setNodeId((int) $data['file_source']);
724 724
 		$share->setNodeType($data['item_type']);
725 725
 
726 726
 		$share->setProviderId($this->identifier());
@@ -839,7 +839,7 @@  discard block
 block discarded – undo
839 839
 			);
840 840
 		}
841 841
 
842
-		$qb->innerJoin('s', 'filecache' ,'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
842
+		$qb->innerJoin('s', 'filecache', 'f', $qb->expr()->eq('s.file_source', 'f.fileid'));
843 843
 		$qb->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($node->getId())));
844 844
 
845 845
 		$qb->orderBy('id');
Please login to merge, or discard this patch.