Completed
Pull Request — master (#8854)
by Morris
33:42 queued 16:39
created
lib/private/Share/Share.php 1 patch
Indentation   +2089 added lines, -2089 removed lines patch added patch discarded remove patch
@@ -52,2103 +52,2103 @@
 block discarded – undo
52 52
  */
53 53
 class Share extends Constants {
54 54
 
55
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
56
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
57
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
58
-	 *
59
-	 * Check if permission is granted with And (&) e.g. Check if delete is
60
-	 * granted: if ($permissions & PERMISSION_DELETE)
61
-	 *
62
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
63
-	 * permission: $permissions &= ~PERMISSION_UPDATE
64
-	 *
65
-	 * Apps are required to handle permissions on their own, this class only
66
-	 * stores and manages the permissions of shares
67
-	 * @see lib/public/constants.php
68
-	 */
69
-
70
-	/**
71
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
72
-	 * @param string $itemType Item type
73
-	 * @param string $class Backend class
74
-	 * @param string $collectionOf (optional) Depends on item type
75
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
76
-	 * @return boolean true if backend is registered or false if error
77
-	 */
78
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
79
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
80
-			if (!isset(self::$backendTypes[$itemType])) {
81
-				self::$backendTypes[$itemType] = array(
82
-					'class' => $class,
83
-					'collectionOf' => $collectionOf,
84
-					'supportedFileExtensions' => $supportedFileExtensions
85
-				);
86
-				if(count(self::$backendTypes) === 1) {
87
-					Util::addScript('core', 'merged-share-backend');
88
-					\OC_Util::addStyle('core', 'share');
89
-				}
90
-				return true;
91
-			}
92
-			\OCP\Util::writeLog('OCP\Share',
93
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
94
-				.' is already registered for '.$itemType,
95
-				\OCP\Util::WARN);
96
-		}
97
-		return false;
98
-	}
99
-
100
-	/**
101
-	 * Get the items of item type shared with the current user
102
-	 * @param string $itemType
103
-	 * @param int $format (optional) Format type must be defined by the backend
104
-	 * @param mixed $parameters (optional)
105
-	 * @param int $limit Number of items to return (optional) Returns all by default
106
-	 * @param boolean $includeCollections (optional)
107
-	 * @return mixed Return depends on format
108
-	 */
109
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
110
-											  $parameters = null, $limit = -1, $includeCollections = false) {
111
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
112
-			$parameters, $limit, $includeCollections);
113
-	}
114
-
115
-	/**
116
-	 * Get the items of item type shared with a user
117
-	 * @param string $itemType
118
-	 * @param string $user id for which user we want the shares
119
-	 * @param int $format (optional) Format type must be defined by the backend
120
-	 * @param mixed $parameters (optional)
121
-	 * @param int $limit Number of items to return (optional) Returns all by default
122
-	 * @param boolean $includeCollections (optional)
123
-	 * @return mixed Return depends on format
124
-	 */
125
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
126
-												  $parameters = null, $limit = -1, $includeCollections = false) {
127
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
128
-			$parameters, $limit, $includeCollections);
129
-	}
130
-
131
-	/**
132
-	 * Get the item of item type shared with a given user by source
133
-	 * @param string $itemType
134
-	 * @param string $itemSource
135
-	 * @param string $user User to whom the item was shared
136
-	 * @param string $owner Owner of the share
137
-	 * @param int $shareType only look for a specific share type
138
-	 * @return array Return list of items with file_target, permissions and expiration
139
-	 */
140
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
141
-		$shares = array();
142
-		$fileDependent = false;
143
-
144
-		$where = 'WHERE';
145
-		$fileDependentWhere = '';
146
-		if ($itemType === 'file' || $itemType === 'folder') {
147
-			$fileDependent = true;
148
-			$column = 'file_source';
149
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
150
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
151
-		} else {
152
-			$column = 'item_source';
153
-		}
154
-
155
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
156
-
157
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
158
-		$arguments = array($itemSource, $itemType);
159
-		// for link shares $user === null
160
-		if ($user !== null) {
161
-			$where .= ' AND `share_with` = ? ';
162
-			$arguments[] = $user;
163
-		}
164
-
165
-		if ($shareType !== null) {
166
-			$where .= ' AND `share_type` = ? ';
167
-			$arguments[] = $shareType;
168
-		}
169
-
170
-		if ($owner !== null) {
171
-			$where .= ' AND `uid_owner` = ? ';
172
-			$arguments[] = $owner;
173
-		}
174
-
175
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
176
-
177
-		$result = \OC_DB::executeAudited($query, $arguments);
178
-
179
-		while ($row = $result->fetchRow()) {
180
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
181
-				continue;
182
-			}
183
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
184
-				// if it is a mount point we need to get the path from the mount manager
185
-				$mountManager = \OC\Files\Filesystem::getMountManager();
186
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
187
-				if (!empty($mountPoint)) {
188
-					$path = $mountPoint[0]->getMountPoint();
189
-					$path = trim($path, '/');
190
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
191
-					$row['path'] = $path;
192
-				} else {
193
-					\OC::$server->getLogger()->warning(
194
-						'Could not resolve mount point for ' . $row['storage_id'],
195
-						['app' => 'OCP\Share']
196
-					);
197
-				}
198
-			}
199
-			$shares[] = $row;
200
-		}
201
-
202
-		//if didn't found a result than let's look for a group share.
203
-		if(empty($shares) && $user !== null) {
204
-			$userObject = \OC::$server->getUserManager()->get($user);
205
-			$groups = [];
206
-			if ($userObject) {
207
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
208
-			}
209
-
210
-			if (!empty($groups)) {
211
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
212
-				$arguments = array($itemSource, $itemType, $groups);
213
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
214
-
215
-				if ($owner !== null) {
216
-					$where .= ' AND `uid_owner` = ?';
217
-					$arguments[] = $owner;
218
-					$types[] = null;
219
-				}
220
-
221
-				// TODO: inject connection, hopefully one day in the future when this
222
-				// class isn't static anymore...
223
-				$conn = \OC::$server->getDatabaseConnection();
224
-				$result = $conn->executeQuery(
225
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
226
-					$arguments,
227
-					$types
228
-				);
229
-
230
-				while ($row = $result->fetch()) {
231
-					$shares[] = $row;
232
-				}
233
-			}
234
-		}
235
-
236
-		return $shares;
237
-
238
-	}
239
-
240
-	/**
241
-	 * Get the item of item type shared with the current user by source
242
-	 * @param string $itemType
243
-	 * @param string $itemSource
244
-	 * @param int $format (optional) Format type must be defined by the backend
245
-	 * @param mixed $parameters
246
-	 * @param boolean $includeCollections
247
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
248
-	 * @return array
249
-	 */
250
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
251
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
252
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
253
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
254
-			$parameters, 1, $includeCollections, true);
255
-	}
256
-
257
-	/**
258
-	 * Based on the given token the share information will be returned - password protected shares will be verified
259
-	 * @param string $token
260
-	 * @param bool $checkPasswordProtection
261
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
262
-	 */
263
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
264
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
265
-		$result = $query->execute(array($token));
266
-		if ($result === false) {
267
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
268
-		}
269
-		$row = $result->fetchRow();
270
-		if ($row === false) {
271
-			return false;
272
-		}
273
-		if (is_array($row) and self::expireItem($row)) {
274
-			return false;
275
-		}
276
-
277
-		// password protected shares need to be authenticated
278
-		if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
279
-			return false;
280
-		}
281
-
282
-		return $row;
283
-	}
284
-
285
-	/**
286
-	 * resolves reshares down to the last real share
287
-	 * @param array $linkItem
288
-	 * @return array file owner
289
-	 */
290
-	public static function resolveReShare($linkItem)
291
-	{
292
-		if (isset($linkItem['parent'])) {
293
-			$parent = $linkItem['parent'];
294
-			while (isset($parent)) {
295
-				$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
296
-				$item = $query->execute(array($parent))->fetchRow();
297
-				if (isset($item['parent'])) {
298
-					$parent = $item['parent'];
299
-				} else {
300
-					return $item;
301
-				}
302
-			}
303
-		}
304
-		return $linkItem;
305
-	}
306
-
307
-
308
-	/**
309
-	 * Get the shared items of item type owned by the current user
310
-	 * @param string $itemType
311
-	 * @param int $format (optional) Format type must be defined by the backend
312
-	 * @param mixed $parameters
313
-	 * @param int $limit Number of items to return (optional) Returns all by default
314
-	 * @param boolean $includeCollections
315
-	 * @return mixed Return depends on format
316
-	 */
317
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
318
-										  $limit = -1, $includeCollections = false) {
319
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
320
-			$parameters, $limit, $includeCollections);
321
-	}
322
-
323
-	/**
324
-	 * Get the shared item of item type owned by the current user
325
-	 * @param string $itemType
326
-	 * @param string $itemSource
327
-	 * @param int $format (optional) Format type must be defined by the backend
328
-	 * @param mixed $parameters
329
-	 * @param boolean $includeCollections
330
-	 * @return mixed Return depends on format
331
-	 */
332
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
333
-										 $parameters = null, $includeCollections = false) {
334
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
335
-			$parameters, -1, $includeCollections);
336
-	}
337
-
338
-	/**
339
-	 * Share an item with a user, group, or via private link
340
-	 * @param string $itemType
341
-	 * @param string $itemSource
342
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
343
-	 * @param string $shareWith User or group the item is being shared with
344
-	 * @param int $permissions CRUDS
345
-	 * @param string $itemSourceName
346
-	 * @param \DateTime|null $expirationDate
347
-	 * @param bool|null $passwordChanged
348
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
349
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
350
-	 * @throws \Exception
351
-	 * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
352
-	 * TESTS ONLY
353
-	 */
354
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
355
-
356
-		$backend = self::getBackend($itemType);
357
-		$l = \OC::$server->getL10N('lib');
358
-
359
-		if ($backend->isShareTypeAllowed($shareType) === false) {
360
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
361
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
362
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
363
-			throw new \Exception($message_t);
364
-		}
365
-
366
-		$uidOwner = \OC_User::getUser();
367
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
368
-
369
-		if (is_null($itemSourceName)) {
370
-			$itemSourceName = $itemSource;
371
-		}
372
-		$itemName = $itemSourceName;
373
-
374
-		// check if file can be shared
375
-		if ($itemType === 'file' or $itemType === 'folder') {
376
-			$path = \OC\Files\Filesystem::getPath($itemSource);
377
-			$itemName = $path;
378
-
379
-			// verify that the file exists before we try to share it
380
-			if (!$path) {
381
-				$message = 'Sharing %s failed, because the file does not exist';
382
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
383
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
384
-				throw new \Exception($message_t);
385
-			}
386
-			// verify that the user has share permission
387
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
388
-				$message = 'You are not allowed to share %s';
389
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
390
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
391
-				throw new \Exception($message_t);
392
-			}
393
-		}
394
-
395
-		//verify that we don't share a folder which already contains a share mount point
396
-		if ($itemType === 'folder') {
397
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
398
-			$mountManager = \OC\Files\Filesystem::getMountManager();
399
-			$mounts = $mountManager->findIn($path);
400
-			foreach ($mounts as $mount) {
401
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
402
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
403
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
404
-					throw new \Exception($message);
405
-				}
406
-
407
-			}
408
-		}
409
-
410
-		// single file shares should never have delete permissions
411
-		if ($itemType === 'file') {
412
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
413
-		}
414
-
415
-		//Validate expirationDate
416
-		if ($expirationDate !== null) {
417
-			try {
418
-				/*
55
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
56
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
57
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
58
+     *
59
+     * Check if permission is granted with And (&) e.g. Check if delete is
60
+     * granted: if ($permissions & PERMISSION_DELETE)
61
+     *
62
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
63
+     * permission: $permissions &= ~PERMISSION_UPDATE
64
+     *
65
+     * Apps are required to handle permissions on their own, this class only
66
+     * stores and manages the permissions of shares
67
+     * @see lib/public/constants.php
68
+     */
69
+
70
+    /**
71
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
72
+     * @param string $itemType Item type
73
+     * @param string $class Backend class
74
+     * @param string $collectionOf (optional) Depends on item type
75
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
76
+     * @return boolean true if backend is registered or false if error
77
+     */
78
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
79
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
80
+            if (!isset(self::$backendTypes[$itemType])) {
81
+                self::$backendTypes[$itemType] = array(
82
+                    'class' => $class,
83
+                    'collectionOf' => $collectionOf,
84
+                    'supportedFileExtensions' => $supportedFileExtensions
85
+                );
86
+                if(count(self::$backendTypes) === 1) {
87
+                    Util::addScript('core', 'merged-share-backend');
88
+                    \OC_Util::addStyle('core', 'share');
89
+                }
90
+                return true;
91
+            }
92
+            \OCP\Util::writeLog('OCP\Share',
93
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
94
+                .' is already registered for '.$itemType,
95
+                \OCP\Util::WARN);
96
+        }
97
+        return false;
98
+    }
99
+
100
+    /**
101
+     * Get the items of item type shared with the current user
102
+     * @param string $itemType
103
+     * @param int $format (optional) Format type must be defined by the backend
104
+     * @param mixed $parameters (optional)
105
+     * @param int $limit Number of items to return (optional) Returns all by default
106
+     * @param boolean $includeCollections (optional)
107
+     * @return mixed Return depends on format
108
+     */
109
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
110
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
111
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
112
+            $parameters, $limit, $includeCollections);
113
+    }
114
+
115
+    /**
116
+     * Get the items of item type shared with a user
117
+     * @param string $itemType
118
+     * @param string $user id for which user we want the shares
119
+     * @param int $format (optional) Format type must be defined by the backend
120
+     * @param mixed $parameters (optional)
121
+     * @param int $limit Number of items to return (optional) Returns all by default
122
+     * @param boolean $includeCollections (optional)
123
+     * @return mixed Return depends on format
124
+     */
125
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
126
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
127
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
128
+            $parameters, $limit, $includeCollections);
129
+    }
130
+
131
+    /**
132
+     * Get the item of item type shared with a given user by source
133
+     * @param string $itemType
134
+     * @param string $itemSource
135
+     * @param string $user User to whom the item was shared
136
+     * @param string $owner Owner of the share
137
+     * @param int $shareType only look for a specific share type
138
+     * @return array Return list of items with file_target, permissions and expiration
139
+     */
140
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
141
+        $shares = array();
142
+        $fileDependent = false;
143
+
144
+        $where = 'WHERE';
145
+        $fileDependentWhere = '';
146
+        if ($itemType === 'file' || $itemType === 'folder') {
147
+            $fileDependent = true;
148
+            $column = 'file_source';
149
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
150
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
151
+        } else {
152
+            $column = 'item_source';
153
+        }
154
+
155
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
156
+
157
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
158
+        $arguments = array($itemSource, $itemType);
159
+        // for link shares $user === null
160
+        if ($user !== null) {
161
+            $where .= ' AND `share_with` = ? ';
162
+            $arguments[] = $user;
163
+        }
164
+
165
+        if ($shareType !== null) {
166
+            $where .= ' AND `share_type` = ? ';
167
+            $arguments[] = $shareType;
168
+        }
169
+
170
+        if ($owner !== null) {
171
+            $where .= ' AND `uid_owner` = ? ';
172
+            $arguments[] = $owner;
173
+        }
174
+
175
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
176
+
177
+        $result = \OC_DB::executeAudited($query, $arguments);
178
+
179
+        while ($row = $result->fetchRow()) {
180
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
181
+                continue;
182
+            }
183
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
184
+                // if it is a mount point we need to get the path from the mount manager
185
+                $mountManager = \OC\Files\Filesystem::getMountManager();
186
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
187
+                if (!empty($mountPoint)) {
188
+                    $path = $mountPoint[0]->getMountPoint();
189
+                    $path = trim($path, '/');
190
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
191
+                    $row['path'] = $path;
192
+                } else {
193
+                    \OC::$server->getLogger()->warning(
194
+                        'Could not resolve mount point for ' . $row['storage_id'],
195
+                        ['app' => 'OCP\Share']
196
+                    );
197
+                }
198
+            }
199
+            $shares[] = $row;
200
+        }
201
+
202
+        //if didn't found a result than let's look for a group share.
203
+        if(empty($shares) && $user !== null) {
204
+            $userObject = \OC::$server->getUserManager()->get($user);
205
+            $groups = [];
206
+            if ($userObject) {
207
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
208
+            }
209
+
210
+            if (!empty($groups)) {
211
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
212
+                $arguments = array($itemSource, $itemType, $groups);
213
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
214
+
215
+                if ($owner !== null) {
216
+                    $where .= ' AND `uid_owner` = ?';
217
+                    $arguments[] = $owner;
218
+                    $types[] = null;
219
+                }
220
+
221
+                // TODO: inject connection, hopefully one day in the future when this
222
+                // class isn't static anymore...
223
+                $conn = \OC::$server->getDatabaseConnection();
224
+                $result = $conn->executeQuery(
225
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
226
+                    $arguments,
227
+                    $types
228
+                );
229
+
230
+                while ($row = $result->fetch()) {
231
+                    $shares[] = $row;
232
+                }
233
+            }
234
+        }
235
+
236
+        return $shares;
237
+
238
+    }
239
+
240
+    /**
241
+     * Get the item of item type shared with the current user by source
242
+     * @param string $itemType
243
+     * @param string $itemSource
244
+     * @param int $format (optional) Format type must be defined by the backend
245
+     * @param mixed $parameters
246
+     * @param boolean $includeCollections
247
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
248
+     * @return array
249
+     */
250
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
251
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
252
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
253
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
254
+            $parameters, 1, $includeCollections, true);
255
+    }
256
+
257
+    /**
258
+     * Based on the given token the share information will be returned - password protected shares will be verified
259
+     * @param string $token
260
+     * @param bool $checkPasswordProtection
261
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
262
+     */
263
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
264
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
265
+        $result = $query->execute(array($token));
266
+        if ($result === false) {
267
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
268
+        }
269
+        $row = $result->fetchRow();
270
+        if ($row === false) {
271
+            return false;
272
+        }
273
+        if (is_array($row) and self::expireItem($row)) {
274
+            return false;
275
+        }
276
+
277
+        // password protected shares need to be authenticated
278
+        if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
279
+            return false;
280
+        }
281
+
282
+        return $row;
283
+    }
284
+
285
+    /**
286
+     * resolves reshares down to the last real share
287
+     * @param array $linkItem
288
+     * @return array file owner
289
+     */
290
+    public static function resolveReShare($linkItem)
291
+    {
292
+        if (isset($linkItem['parent'])) {
293
+            $parent = $linkItem['parent'];
294
+            while (isset($parent)) {
295
+                $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
296
+                $item = $query->execute(array($parent))->fetchRow();
297
+                if (isset($item['parent'])) {
298
+                    $parent = $item['parent'];
299
+                } else {
300
+                    return $item;
301
+                }
302
+            }
303
+        }
304
+        return $linkItem;
305
+    }
306
+
307
+
308
+    /**
309
+     * Get the shared items of item type owned by the current user
310
+     * @param string $itemType
311
+     * @param int $format (optional) Format type must be defined by the backend
312
+     * @param mixed $parameters
313
+     * @param int $limit Number of items to return (optional) Returns all by default
314
+     * @param boolean $includeCollections
315
+     * @return mixed Return depends on format
316
+     */
317
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
318
+                                            $limit = -1, $includeCollections = false) {
319
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
320
+            $parameters, $limit, $includeCollections);
321
+    }
322
+
323
+    /**
324
+     * Get the shared item of item type owned by the current user
325
+     * @param string $itemType
326
+     * @param string $itemSource
327
+     * @param int $format (optional) Format type must be defined by the backend
328
+     * @param mixed $parameters
329
+     * @param boolean $includeCollections
330
+     * @return mixed Return depends on format
331
+     */
332
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
333
+                                            $parameters = null, $includeCollections = false) {
334
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
335
+            $parameters, -1, $includeCollections);
336
+    }
337
+
338
+    /**
339
+     * Share an item with a user, group, or via private link
340
+     * @param string $itemType
341
+     * @param string $itemSource
342
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
343
+     * @param string $shareWith User or group the item is being shared with
344
+     * @param int $permissions CRUDS
345
+     * @param string $itemSourceName
346
+     * @param \DateTime|null $expirationDate
347
+     * @param bool|null $passwordChanged
348
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
349
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
350
+     * @throws \Exception
351
+     * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
352
+     * TESTS ONLY
353
+     */
354
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
355
+
356
+        $backend = self::getBackend($itemType);
357
+        $l = \OC::$server->getL10N('lib');
358
+
359
+        if ($backend->isShareTypeAllowed($shareType) === false) {
360
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
361
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
362
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
363
+            throw new \Exception($message_t);
364
+        }
365
+
366
+        $uidOwner = \OC_User::getUser();
367
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
368
+
369
+        if (is_null($itemSourceName)) {
370
+            $itemSourceName = $itemSource;
371
+        }
372
+        $itemName = $itemSourceName;
373
+
374
+        // check if file can be shared
375
+        if ($itemType === 'file' or $itemType === 'folder') {
376
+            $path = \OC\Files\Filesystem::getPath($itemSource);
377
+            $itemName = $path;
378
+
379
+            // verify that the file exists before we try to share it
380
+            if (!$path) {
381
+                $message = 'Sharing %s failed, because the file does not exist';
382
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
383
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
384
+                throw new \Exception($message_t);
385
+            }
386
+            // verify that the user has share permission
387
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
388
+                $message = 'You are not allowed to share %s';
389
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
390
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
391
+                throw new \Exception($message_t);
392
+            }
393
+        }
394
+
395
+        //verify that we don't share a folder which already contains a share mount point
396
+        if ($itemType === 'folder') {
397
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
398
+            $mountManager = \OC\Files\Filesystem::getMountManager();
399
+            $mounts = $mountManager->findIn($path);
400
+            foreach ($mounts as $mount) {
401
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
402
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
403
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
404
+                    throw new \Exception($message);
405
+                }
406
+
407
+            }
408
+        }
409
+
410
+        // single file shares should never have delete permissions
411
+        if ($itemType === 'file') {
412
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
413
+        }
414
+
415
+        //Validate expirationDate
416
+        if ($expirationDate !== null) {
417
+            try {
418
+                /*
419 419
 				 * Reuse the validateExpireDate.
420 420
 				 * We have to pass time() since the second arg is the time
421 421
 				 * the file was shared, since it is not shared yet we just use
422 422
 				 * the current time.
423 423
 				 */
424
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
425
-			} catch (\Exception $e) {
426
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
427
-			}
428
-		}
429
-
430
-		// Verify share type and sharing conditions are met
431
-		if ($shareType === self::SHARE_TYPE_USER) {
432
-			if ($shareWith == $uidOwner) {
433
-				$message = 'Sharing %s failed, because you can not share with yourself';
434
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
435
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
436
-				throw new \Exception($message_t);
437
-			}
438
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
439
-				$message = 'Sharing %s failed, because the user %s does not exist';
440
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
441
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
442
-				throw new \Exception($message_t);
443
-			}
444
-			if ($shareWithinGroupOnly) {
445
-				$userManager = \OC::$server->getUserManager();
446
-				$groupManager = \OC::$server->getGroupManager();
447
-				$userOwner = $userManager->get($uidOwner);
448
-				$userShareWith = $userManager->get($shareWith);
449
-				$groupsOwner = [];
450
-				$groupsShareWith = [];
451
-				if ($userOwner) {
452
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
453
-				}
454
-				if ($userShareWith) {
455
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
456
-				}
457
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
458
-				if (empty($inGroup)) {
459
-					$message = 'Sharing %s failed, because the user '
460
-						.'%s is not a member of any groups that %s is a member of';
461
-					$message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
462
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
463
-					throw new \Exception($message_t);
464
-				}
465
-			}
466
-			// Check if the item source is already shared with the user, either from the same owner or a different user
467
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
468
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
469
-				// Only allow the same share to occur again if it is the same
470
-				// owner and is not a user share, this use case is for increasing
471
-				// permissions for a specific user
472
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
473
-					$message = 'Sharing %s failed, because this item is already shared with %s';
474
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
475
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
476
-					throw new \Exception($message_t);
477
-				}
478
-			}
479
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
480
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
481
-				// Only allow the same share to occur again if it is the same
482
-				// owner and is not a user share, this use case is for increasing
483
-				// permissions for a specific user
484
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
485
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
486
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
487
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
488
-					throw new \Exception($message_t);
489
-				}
490
-			}
491
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
492
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
493
-				$message = 'Sharing %s failed, because the group %s does not exist';
494
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
495
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
496
-				throw new \Exception($message_t);
497
-			}
498
-			if ($shareWithinGroupOnly) {
499
-				$group = \OC::$server->getGroupManager()->get($shareWith);
500
-				$user = \OC::$server->getUserManager()->get($uidOwner);
501
-				if (!$group || !$user || !$group->inGroup($user)) {
502
-					$message = 'Sharing %s failed, because '
503
-						. '%s is not a member of the group %s';
504
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
505
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
506
-					throw new \Exception($message_t);
507
-				}
508
-			}
509
-			// Check if the item source is already shared with the group, either from the same owner or a different user
510
-			// The check for each user in the group is done inside the put() function
511
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
512
-				null, self::FORMAT_NONE, null, 1, true, true)) {
513
-
514
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
515
-					$message = 'Sharing %s failed, because this item is already shared with %s';
516
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
517
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
518
-					throw new \Exception($message_t);
519
-				}
520
-			}
521
-			// Convert share with into an array with the keys group and users
522
-			$group = $shareWith;
523
-			$shareWith = array();
524
-			$shareWith['group'] = $group;
525
-
526
-
527
-			$groupObject = \OC::$server->getGroupManager()->get($group);
528
-			$userIds = [];
529
-			if ($groupObject) {
530
-				$users = $groupObject->searchUsers('', -1, 0);
531
-				foreach ($users as $user) {
532
-					$userIds[] = $user->getUID();
533
-				}
534
-			}
535
-
536
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
537
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
538
-			$updateExistingShare = false;
539
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
540
-
541
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
542
-				if ($passwordChanged === true) {
543
-					self::verifyPassword($shareWith);
544
-				}
545
-
546
-				// when updating a link share
547
-				// FIXME Don't delete link if we update it
548
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
549
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
550
-					// remember old token
551
-					$oldToken = $checkExists['token'];
552
-					$oldPermissions = $checkExists['permissions'];
553
-					//delete the old share
554
-					Helper::delete($checkExists['id']);
555
-					$updateExistingShare = true;
556
-				}
557
-
558
-				if ($passwordChanged === null) {
559
-					// Generate hash of password - same method as user passwords
560
-					if (is_string($shareWith) && $shareWith !== '') {
561
-						self::verifyPassword($shareWith);
562
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
563
-					} else {
564
-						// reuse the already set password, but only if we change permissions
565
-						// otherwise the user disabled the password protection
566
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
567
-							$shareWith = $checkExists['share_with'];
568
-						}
569
-					}
570
-				} else {
571
-					if ($passwordChanged === true) {
572
-						if (is_string($shareWith) && $shareWith !== '') {
573
-							self::verifyPassword($shareWith);
574
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
575
-						}
576
-					} else if ($updateExistingShare) {
577
-						$shareWith = $checkExists['share_with'];
578
-					}
579
-				}
580
-
581
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
582
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
583
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
584
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
585
-					throw new \Exception($message_t);
586
-				}
587
-
588
-				if ($updateExistingShare === false &&
589
-					self::isDefaultExpireDateEnabled() &&
590
-					empty($expirationDate)) {
591
-					$expirationDate = Helper::calcExpireDate();
592
-				}
593
-
594
-				// Generate token
595
-				if (isset($oldToken)) {
596
-					$token = $oldToken;
597
-				} else {
598
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
599
-						\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
600
-					);
601
-				}
602
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
603
-					null, $token, $itemSourceName, $expirationDate);
604
-				if ($result) {
605
-					return $token;
606
-				} else {
607
-					return false;
608
-				}
609
-			}
610
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
611
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
612
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
613
-			throw new \Exception($message_t);
614
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
615
-
616
-			/*
424
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
425
+            } catch (\Exception $e) {
426
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
427
+            }
428
+        }
429
+
430
+        // Verify share type and sharing conditions are met
431
+        if ($shareType === self::SHARE_TYPE_USER) {
432
+            if ($shareWith == $uidOwner) {
433
+                $message = 'Sharing %s failed, because you can not share with yourself';
434
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
435
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
436
+                throw new \Exception($message_t);
437
+            }
438
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
439
+                $message = 'Sharing %s failed, because the user %s does not exist';
440
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
441
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
442
+                throw new \Exception($message_t);
443
+            }
444
+            if ($shareWithinGroupOnly) {
445
+                $userManager = \OC::$server->getUserManager();
446
+                $groupManager = \OC::$server->getGroupManager();
447
+                $userOwner = $userManager->get($uidOwner);
448
+                $userShareWith = $userManager->get($shareWith);
449
+                $groupsOwner = [];
450
+                $groupsShareWith = [];
451
+                if ($userOwner) {
452
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
453
+                }
454
+                if ($userShareWith) {
455
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
456
+                }
457
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
458
+                if (empty($inGroup)) {
459
+                    $message = 'Sharing %s failed, because the user '
460
+                        .'%s is not a member of any groups that %s is a member of';
461
+                    $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
462
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
463
+                    throw new \Exception($message_t);
464
+                }
465
+            }
466
+            // Check if the item source is already shared with the user, either from the same owner or a different user
467
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
468
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
469
+                // Only allow the same share to occur again if it is the same
470
+                // owner and is not a user share, this use case is for increasing
471
+                // permissions for a specific user
472
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
473
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
474
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
475
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
476
+                    throw new \Exception($message_t);
477
+                }
478
+            }
479
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
480
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
481
+                // Only allow the same share to occur again if it is the same
482
+                // owner and is not a user share, this use case is for increasing
483
+                // permissions for a specific user
484
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
485
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
486
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
487
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
488
+                    throw new \Exception($message_t);
489
+                }
490
+            }
491
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
492
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
493
+                $message = 'Sharing %s failed, because the group %s does not exist';
494
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
495
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
496
+                throw new \Exception($message_t);
497
+            }
498
+            if ($shareWithinGroupOnly) {
499
+                $group = \OC::$server->getGroupManager()->get($shareWith);
500
+                $user = \OC::$server->getUserManager()->get($uidOwner);
501
+                if (!$group || !$user || !$group->inGroup($user)) {
502
+                    $message = 'Sharing %s failed, because '
503
+                        . '%s is not a member of the group %s';
504
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
505
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
506
+                    throw new \Exception($message_t);
507
+                }
508
+            }
509
+            // Check if the item source is already shared with the group, either from the same owner or a different user
510
+            // The check for each user in the group is done inside the put() function
511
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
512
+                null, self::FORMAT_NONE, null, 1, true, true)) {
513
+
514
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
515
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
516
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
517
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
518
+                    throw new \Exception($message_t);
519
+                }
520
+            }
521
+            // Convert share with into an array with the keys group and users
522
+            $group = $shareWith;
523
+            $shareWith = array();
524
+            $shareWith['group'] = $group;
525
+
526
+
527
+            $groupObject = \OC::$server->getGroupManager()->get($group);
528
+            $userIds = [];
529
+            if ($groupObject) {
530
+                $users = $groupObject->searchUsers('', -1, 0);
531
+                foreach ($users as $user) {
532
+                    $userIds[] = $user->getUID();
533
+                }
534
+            }
535
+
536
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
537
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
538
+            $updateExistingShare = false;
539
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
540
+
541
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
542
+                if ($passwordChanged === true) {
543
+                    self::verifyPassword($shareWith);
544
+                }
545
+
546
+                // when updating a link share
547
+                // FIXME Don't delete link if we update it
548
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
549
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
550
+                    // remember old token
551
+                    $oldToken = $checkExists['token'];
552
+                    $oldPermissions = $checkExists['permissions'];
553
+                    //delete the old share
554
+                    Helper::delete($checkExists['id']);
555
+                    $updateExistingShare = true;
556
+                }
557
+
558
+                if ($passwordChanged === null) {
559
+                    // Generate hash of password - same method as user passwords
560
+                    if (is_string($shareWith) && $shareWith !== '') {
561
+                        self::verifyPassword($shareWith);
562
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
563
+                    } else {
564
+                        // reuse the already set password, but only if we change permissions
565
+                        // otherwise the user disabled the password protection
566
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
567
+                            $shareWith = $checkExists['share_with'];
568
+                        }
569
+                    }
570
+                } else {
571
+                    if ($passwordChanged === true) {
572
+                        if (is_string($shareWith) && $shareWith !== '') {
573
+                            self::verifyPassword($shareWith);
574
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
575
+                        }
576
+                    } else if ($updateExistingShare) {
577
+                        $shareWith = $checkExists['share_with'];
578
+                    }
579
+                }
580
+
581
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
582
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
583
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
584
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
585
+                    throw new \Exception($message_t);
586
+                }
587
+
588
+                if ($updateExistingShare === false &&
589
+                    self::isDefaultExpireDateEnabled() &&
590
+                    empty($expirationDate)) {
591
+                    $expirationDate = Helper::calcExpireDate();
592
+                }
593
+
594
+                // Generate token
595
+                if (isset($oldToken)) {
596
+                    $token = $oldToken;
597
+                } else {
598
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
599
+                        \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
600
+                    );
601
+                }
602
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
603
+                    null, $token, $itemSourceName, $expirationDate);
604
+                if ($result) {
605
+                    return $token;
606
+                } else {
607
+                    return false;
608
+                }
609
+            }
610
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
611
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
612
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
613
+            throw new \Exception($message_t);
614
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
615
+
616
+            /*
617 617
 			 * Check if file is not already shared with the remote user
618 618
 			 */
619
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
620
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
621
-					$message = 'Sharing %s failed, because this item is already shared with %s';
622
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
623
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
624
-					throw new \Exception($message_t);
625
-			}
626
-
627
-			// don't allow federated shares if source and target server are the same
628
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
629
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
630
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
631
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
632
-				$message = 'Not allowed to create a federated share with the same user.';
633
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
634
-				\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
635
-				throw new \Exception($message_t);
636
-			}
637
-
638
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
639
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
640
-
641
-			$shareWith = $user . '@' . $remote;
642
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
643
-
644
-			$send = false;
645
-			if ($shareId) {
646
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
647
-			}
648
-
649
-			if ($send === false) {
650
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
651
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
652
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
653
-				throw new \Exception($message_t);
654
-			}
655
-
656
-			return $send;
657
-		} else {
658
-			// Future share types need to include their own conditions
659
-			$message = 'Share type %s is not valid for %s';
660
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
661
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
662
-			throw new \Exception($message_t);
663
-		}
664
-
665
-		// Put the item into the database
666
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
667
-
668
-		return $result ? true : false;
669
-	}
670
-
671
-	/**
672
-	 * Unshare an item from a user, group, or delete a private link
673
-	 * @param string $itemType
674
-	 * @param string $itemSource
675
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
676
-	 * @param string $shareWith User or group the item is being shared with
677
-	 * @param string $owner owner of the share, if null the current user is used
678
-	 * @return boolean true on success or false on failure
679
-	 */
680
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
681
-
682
-		// check if it is a valid itemType
683
-		self::getBackend($itemType);
684
-
685
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
686
-
687
-		$toDelete = array();
688
-		$newParent = null;
689
-		$currentUser = $owner ? $owner : \OC_User::getUser();
690
-		foreach ($items as $item) {
691
-			// delete the item with the expected share_type and owner
692
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
693
-				$toDelete = $item;
694
-				// if there is more then one result we don't have to delete the children
695
-				// but update their parent. For group shares the new parent should always be
696
-				// the original group share and not the db entry with the unique name
697
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
698
-				$newParent = $item['parent'];
699
-			} else {
700
-				$newParent = $item['id'];
701
-			}
702
-		}
703
-
704
-		if (!empty($toDelete)) {
705
-			self::unshareItem($toDelete, $newParent);
706
-			return true;
707
-		}
708
-		return false;
709
-	}
710
-
711
-	/**
712
-	 * sent status if users got informed by mail about share
713
-	 * @param string $itemType
714
-	 * @param string $itemSource
715
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
716
-	 * @param string $recipient with whom was the file shared
717
-	 * @param boolean $status
718
-	 */
719
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
720
-		$status = $status ? 1 : 0;
721
-
722
-		$query = \OC_DB::prepare(
723
-			'UPDATE `*PREFIX*share`
619
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
620
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
621
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
622
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
623
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
624
+                    throw new \Exception($message_t);
625
+            }
626
+
627
+            // don't allow federated shares if source and target server are the same
628
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
629
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
630
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
631
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
632
+                $message = 'Not allowed to create a federated share with the same user.';
633
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
634
+                \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
635
+                throw new \Exception($message_t);
636
+            }
637
+
638
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
639
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
640
+
641
+            $shareWith = $user . '@' . $remote;
642
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
643
+
644
+            $send = false;
645
+            if ($shareId) {
646
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
647
+            }
648
+
649
+            if ($send === false) {
650
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
651
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
652
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
653
+                throw new \Exception($message_t);
654
+            }
655
+
656
+            return $send;
657
+        } else {
658
+            // Future share types need to include their own conditions
659
+            $message = 'Share type %s is not valid for %s';
660
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
661
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
662
+            throw new \Exception($message_t);
663
+        }
664
+
665
+        // Put the item into the database
666
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
667
+
668
+        return $result ? true : false;
669
+    }
670
+
671
+    /**
672
+     * Unshare an item from a user, group, or delete a private link
673
+     * @param string $itemType
674
+     * @param string $itemSource
675
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
676
+     * @param string $shareWith User or group the item is being shared with
677
+     * @param string $owner owner of the share, if null the current user is used
678
+     * @return boolean true on success or false on failure
679
+     */
680
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
681
+
682
+        // check if it is a valid itemType
683
+        self::getBackend($itemType);
684
+
685
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
686
+
687
+        $toDelete = array();
688
+        $newParent = null;
689
+        $currentUser = $owner ? $owner : \OC_User::getUser();
690
+        foreach ($items as $item) {
691
+            // delete the item with the expected share_type and owner
692
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
693
+                $toDelete = $item;
694
+                // if there is more then one result we don't have to delete the children
695
+                // but update their parent. For group shares the new parent should always be
696
+                // the original group share and not the db entry with the unique name
697
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
698
+                $newParent = $item['parent'];
699
+            } else {
700
+                $newParent = $item['id'];
701
+            }
702
+        }
703
+
704
+        if (!empty($toDelete)) {
705
+            self::unshareItem($toDelete, $newParent);
706
+            return true;
707
+        }
708
+        return false;
709
+    }
710
+
711
+    /**
712
+     * sent status if users got informed by mail about share
713
+     * @param string $itemType
714
+     * @param string $itemSource
715
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
716
+     * @param string $recipient with whom was the file shared
717
+     * @param boolean $status
718
+     */
719
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
720
+        $status = $status ? 1 : 0;
721
+
722
+        $query = \OC_DB::prepare(
723
+            'UPDATE `*PREFIX*share`
724 724
 					SET `mail_send` = ?
725 725
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
726 726
 
727
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
728
-
729
-		if($result === false) {
730
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
731
-		}
732
-	}
733
-
734
-	/**
735
-	 * validate expiration date if it meets all constraints
736
-	 *
737
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
738
-	 * @param string $shareTime timestamp when the file was shared
739
-	 * @param string $itemType
740
-	 * @param string $itemSource
741
-	 * @return \DateTime validated date
742
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
743
-	 */
744
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
745
-		$l = \OC::$server->getL10N('lib');
746
-		$date = new \DateTime($expireDate);
747
-		$today = new \DateTime('now');
748
-
749
-		// if the user doesn't provide a share time we need to get it from the database
750
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
751
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
752
-		if ($defaultExpireDateEnforced && $shareTime === null) {
753
-			$items = self::getItemShared($itemType, $itemSource);
754
-			$firstItem = reset($items);
755
-			$shareTime = (int)$firstItem['stime'];
756
-		}
757
-
758
-		if ($defaultExpireDateEnforced) {
759
-			// initialize max date with share time
760
-			$maxDate = new \DateTime();
761
-			$maxDate->setTimestamp($shareTime);
762
-			$maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
763
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
764
-			if ($date > $maxDate) {
765
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
766
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
767
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
768
-				throw new \Exception($warning_t);
769
-			}
770
-		}
771
-
772
-		if ($date < $today) {
773
-			$message = 'Cannot set expiration date. Expiration date is in the past';
774
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
775
-			\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
776
-			throw new \Exception($message_t);
777
-		}
778
-
779
-		return $date;
780
-	}
781
-
782
-	/**
783
-	 * Checks whether a share has expired, calls unshareItem() if yes.
784
-	 * @param array $item Share data (usually database row)
785
-	 * @return boolean True if item was expired, false otherwise.
786
-	 */
787
-	protected static function expireItem(array $item) {
788
-
789
-		$result = false;
790
-
791
-		// only use default expiration date for link shares
792
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
793
-
794
-			// calculate expiration date
795
-			if (!empty($item['expiration'])) {
796
-				$userDefinedExpire = new \DateTime($item['expiration']);
797
-				$expires = $userDefinedExpire->getTimestamp();
798
-			} else {
799
-				$expires = null;
800
-			}
801
-
802
-
803
-			// get default expiration settings
804
-			$defaultSettings = Helper::getDefaultExpireSetting();
805
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
806
-
807
-
808
-			if (is_int($expires)) {
809
-				$now = time();
810
-				if ($now > $expires) {
811
-					self::unshareItem($item);
812
-					$result = true;
813
-				}
814
-			}
815
-		}
816
-		return $result;
817
-	}
818
-
819
-	/**
820
-	 * Unshares a share given a share data array
821
-	 * @param array $item Share data (usually database row)
822
-	 * @param int $newParent parent ID
823
-	 * @return null
824
-	 */
825
-	protected static function unshareItem(array $item, $newParent = null) {
826
-
827
-		$shareType = (int)$item['share_type'];
828
-		$shareWith = null;
829
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
830
-			$shareWith = $item['share_with'];
831
-		}
832
-
833
-		// Pass all the vars we have for now, they may be useful
834
-		$hookParams = array(
835
-			'id'            => $item['id'],
836
-			'itemType'      => $item['item_type'],
837
-			'itemSource'    => $item['item_source'],
838
-			'shareType'     => $shareType,
839
-			'shareWith'     => $shareWith,
840
-			'itemParent'    => $item['parent'],
841
-			'uidOwner'      => $item['uid_owner'],
842
-		);
843
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
844
-			$hookParams['fileSource'] = $item['file_source'];
845
-			$hookParams['fileTarget'] = $item['file_target'];
846
-		}
847
-
848
-		\OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
849
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
850
-		$deletedShares[] = $hookParams;
851
-		$hookParams['deletedShares'] = $deletedShares;
852
-		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
853
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
854
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
855
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
856
-		}
857
-	}
858
-
859
-	/**
860
-	 * Get the backend class for the specified item type
861
-	 * @param string $itemType
862
-	 * @throws \Exception
863
-	 * @return \OCP\Share_Backend
864
-	 */
865
-	public static function getBackend($itemType) {
866
-		$l = \OC::$server->getL10N('lib');
867
-		if (isset(self::$backends[$itemType])) {
868
-			return self::$backends[$itemType];
869
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
870
-			$class = self::$backendTypes[$itemType]['class'];
871
-			if (class_exists($class)) {
872
-				self::$backends[$itemType] = new $class;
873
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
874
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
875
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
876
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
877
-					throw new \Exception($message_t);
878
-				}
879
-				return self::$backends[$itemType];
880
-			} else {
881
-				$message = 'Sharing backend %s not found';
882
-				$message_t = $l->t('Sharing backend %s not found', array($class));
883
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
884
-				throw new \Exception($message_t);
885
-			}
886
-		}
887
-		$message = 'Sharing backend for %s not found';
888
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
889
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
890
-		throw new \Exception($message_t);
891
-	}
892
-
893
-	/**
894
-	 * Check if resharing is allowed
895
-	 * @return boolean true if allowed or false
896
-	 *
897
-	 * Resharing is allowed by default if not configured
898
-	 */
899
-	public static function isResharingAllowed() {
900
-		if (!isset(self::$isResharingAllowed)) {
901
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
902
-				self::$isResharingAllowed = true;
903
-			} else {
904
-				self::$isResharingAllowed = false;
905
-			}
906
-		}
907
-		return self::$isResharingAllowed;
908
-	}
909
-
910
-	/**
911
-	 * Get a list of collection item types for the specified item type
912
-	 * @param string $itemType
913
-	 * @return array
914
-	 */
915
-	private static function getCollectionItemTypes($itemType) {
916
-		$collectionTypes = array($itemType);
917
-		foreach (self::$backendTypes as $type => $backend) {
918
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
919
-				$collectionTypes[] = $type;
920
-			}
921
-		}
922
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
923
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
924
-			unset($collectionTypes[0]);
925
-		}
926
-		// Return array if collections were found or the item type is a
927
-		// collection itself - collections can be inside collections
928
-		if (count($collectionTypes) > 0) {
929
-			return $collectionTypes;
930
-		}
931
-		return false;
932
-	}
933
-
934
-	/**
935
-	 * Get the owners of items shared with a user.
936
-	 *
937
-	 * @param string $user The user the items are shared with.
938
-	 * @param string $type The type of the items shared with the user.
939
-	 * @param boolean $includeCollections Include collection item types (optional)
940
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
941
-	 * @return array
942
-	 */
943
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
944
-		// First, we find out if $type is part of a collection (and if that collection is part of
945
-		// another one and so on).
946
-		$collectionTypes = array();
947
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
948
-			$collectionTypes[] = $type;
949
-		}
950
-
951
-		// Of these collection types, along with our original $type, we make a
952
-		// list of the ones for which a sharing backend has been registered.
953
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
954
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
955
-		$allMaybeSharedItems = array();
956
-		foreach ($collectionTypes as $collectionType) {
957
-			if (isset(self::$backends[$collectionType])) {
958
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
959
-					$collectionType,
960
-					$user,
961
-					self::FORMAT_NONE
962
-				);
963
-			}
964
-		}
965
-
966
-		$owners = array();
967
-		if ($includeOwner) {
968
-			$owners[] = $user;
969
-		}
970
-
971
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
972
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
973
-		// and return them as elements of a list that look like "Tag (owner)".
974
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
975
-			foreach ($maybeSharedItems as $sharedItem) {
976
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
977
-					$owners[] = $sharedItem['uid_owner'];
978
-				}
979
-			}
980
-		}
981
-
982
-		return $owners;
983
-	}
984
-
985
-	/**
986
-	 * Get shared items from the database
987
-	 * @param string $itemType
988
-	 * @param string $item Item source or target (optional)
989
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
990
-	 * @param string $shareWith User or group the item is being shared with
991
-	 * @param string $uidOwner User that is the owner of shared items (optional)
992
-	 * @param int $format Format to convert items to with formatItems() (optional)
993
-	 * @param mixed $parameters to pass to formatItems() (optional)
994
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
995
-	 * @param boolean $includeCollections Include collection item types (optional)
996
-	 * @param boolean $itemShareWithBySource (optional)
997
-	 * @param boolean $checkExpireDate
998
-	 * @return array
999
-	 *
1000
-	 * See public functions getItem(s)... for parameter usage
1001
-	 *
1002
-	 */
1003
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1004
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1005
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1006
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
1007
-			return array();
1008
-		}
1009
-		$backend = self::getBackend($itemType);
1010
-		$collectionTypes = false;
1011
-		// Get filesystem root to add it to the file target and remove from the
1012
-		// file source, match file_source with the file cache
1013
-		if ($itemType == 'file' || $itemType == 'folder') {
1014
-			if(!is_null($uidOwner)) {
1015
-				$root = \OC\Files\Filesystem::getRoot();
1016
-			} else {
1017
-				$root = '';
1018
-			}
1019
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1020
-			if (!isset($item)) {
1021
-				$where .= ' AND `file_target` IS NOT NULL ';
1022
-			}
1023
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1024
-			$fileDependent = true;
1025
-			$queryArgs = array();
1026
-		} else {
1027
-			$fileDependent = false;
1028
-			$root = '';
1029
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1030
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1031
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1032
-				if (!in_array($itemType, $collectionTypes)) {
1033
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1034
-				} else {
1035
-					$itemTypes = $collectionTypes;
1036
-				}
1037
-				$placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
1038
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1039
-				$queryArgs = $itemTypes;
1040
-			} else {
1041
-				$where = ' WHERE `item_type` = ?';
1042
-				$queryArgs = array($itemType);
1043
-			}
1044
-		}
1045
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1046
-			$where .= ' AND `share_type` != ?';
1047
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1048
-		}
1049
-		if (isset($shareType)) {
1050
-			// Include all user and group items
1051
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1052
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1053
-				$queryArgs[] = self::SHARE_TYPE_USER;
1054
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1055
-				$queryArgs[] = $shareWith;
1056
-
1057
-				$user = \OC::$server->getUserManager()->get($shareWith);
1058
-				$groups = [];
1059
-				if ($user) {
1060
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1061
-				}
1062
-				if (!empty($groups)) {
1063
-					$placeholders = implode(',', array_fill(0, count($groups), '?'));
1064
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1065
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1066
-					$queryArgs = array_merge($queryArgs, $groups);
1067
-				}
1068
-				$where .= ')';
1069
-				// Don't include own group shares
1070
-				$where .= ' AND `uid_owner` != ?';
1071
-				$queryArgs[] = $shareWith;
1072
-			} else {
1073
-				$where .= ' AND `share_type` = ?';
1074
-				$queryArgs[] = $shareType;
1075
-				if (isset($shareWith)) {
1076
-					$where .= ' AND `share_with` = ?';
1077
-					$queryArgs[] = $shareWith;
1078
-				}
1079
-			}
1080
-		}
1081
-		if (isset($uidOwner)) {
1082
-			$where .= ' AND `uid_owner` = ?';
1083
-			$queryArgs[] = $uidOwner;
1084
-			if (!isset($shareType)) {
1085
-				// Prevent unique user targets for group shares from being selected
1086
-				$where .= ' AND `share_type` != ?';
1087
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1088
-			}
1089
-			if ($fileDependent) {
1090
-				$column = 'file_source';
1091
-			} else {
1092
-				$column = 'item_source';
1093
-			}
1094
-		} else {
1095
-			if ($fileDependent) {
1096
-				$column = 'file_target';
1097
-			} else {
1098
-				$column = 'item_target';
1099
-			}
1100
-		}
1101
-		if (isset($item)) {
1102
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1103
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1104
-				$where .= ' AND (';
1105
-			} else {
1106
-				$where .= ' AND';
1107
-			}
1108
-			// If looking for own shared items, check item_source else check item_target
1109
-			if (isset($uidOwner) || $itemShareWithBySource) {
1110
-				// If item type is a file, file source needs to be checked in case the item was converted
1111
-				if ($fileDependent) {
1112
-					$where .= ' `file_source` = ?';
1113
-					$column = 'file_source';
1114
-				} else {
1115
-					$where .= ' `item_source` = ?';
1116
-					$column = 'item_source';
1117
-				}
1118
-			} else {
1119
-				if ($fileDependent) {
1120
-					$where .= ' `file_target` = ?';
1121
-					$item = \OC\Files\Filesystem::normalizePath($item);
1122
-				} else {
1123
-					$where .= ' `item_target` = ?';
1124
-				}
1125
-			}
1126
-			$queryArgs[] = $item;
1127
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1128
-				$placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
1129
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1130
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1131
-			}
1132
-		}
1133
-
1134
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1135
-			// Make sure the unique user target is returned if it exists,
1136
-			// unique targets should follow the group share in the database
1137
-			// If the limit is not 1, the filtering can be done later
1138
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1139
-		} else {
1140
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1141
-		}
1142
-
1143
-		if ($limit != -1 && !$includeCollections) {
1144
-			// The limit must be at least 3, because filtering needs to be done
1145
-			if ($limit < 3) {
1146
-				$queryLimit = 3;
1147
-			} else {
1148
-				$queryLimit = $limit;
1149
-			}
1150
-		} else {
1151
-			$queryLimit = null;
1152
-		}
1153
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1154
-		$root = strlen($root);
1155
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1156
-		$result = $query->execute($queryArgs);
1157
-		if ($result === false) {
1158
-			\OCP\Util::writeLog('OCP\Share',
1159
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1160
-				\OCP\Util::ERROR);
1161
-		}
1162
-		$items = array();
1163
-		$targets = array();
1164
-		$switchedItems = array();
1165
-		$mounts = array();
1166
-		while ($row = $result->fetchRow()) {
1167
-			self::transformDBResults($row);
1168
-			// Filter out duplicate group shares for users with unique targets
1169
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1170
-				continue;
1171
-			}
1172
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1173
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1174
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1175
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1176
-				// if the group share was unshared from the user we keep the permission, otherwise
1177
-				// we take the permission from the parent because this is always the up-to-date
1178
-				// permission for the group share
1179
-				if ($row['permissions'] > 0) {
1180
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1181
-				}
1182
-				// Remove the parent group share
1183
-				unset($items[$row['parent']]);
1184
-				if ($row['permissions'] == 0) {
1185
-					continue;
1186
-				}
1187
-			} else if (!isset($uidOwner)) {
1188
-				// Check if the same target already exists
1189
-				if (isset($targets[$row['id']])) {
1190
-					// Check if the same owner shared with the user twice
1191
-					// through a group and user share - this is allowed
1192
-					$id = $targets[$row['id']];
1193
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1194
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1195
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1196
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1197
-							$items[$id]['share_with'] = $row['share_with'];
1198
-						}
1199
-						// Switch ids if sharing permission is granted on only
1200
-						// one share to ensure correct parent is used if resharing
1201
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1202
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1203
-							$items[$row['id']] = $items[$id];
1204
-							$switchedItems[$id] = $row['id'];
1205
-							unset($items[$id]);
1206
-							$id = $row['id'];
1207
-						}
1208
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1209
-
1210
-					}
1211
-					continue;
1212
-				} elseif (!empty($row['parent'])) {
1213
-					$targets[$row['parent']] = $row['id'];
1214
-				}
1215
-			}
1216
-			// Remove root from file source paths if retrieving own shared items
1217
-			if (isset($uidOwner) && isset($row['path'])) {
1218
-				if (isset($row['parent'])) {
1219
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1220
-					$parentResult = $query->execute(array($row['parent']));
1221
-					if ($result === false) {
1222
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1223
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1224
-							\OCP\Util::ERROR);
1225
-					} else {
1226
-						$parentRow = $parentResult->fetchRow();
1227
-						$tmpPath = $parentRow['file_target'];
1228
-						// find the right position where the row path continues from the target path
1229
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1230
-						$subPath = substr($row['path'], $pos);
1231
-						$splitPath = explode('/', $subPath);
1232
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1233
-							$tmpPath = $tmpPath . '/' . $pathPart;
1234
-						}
1235
-						$row['path'] = $tmpPath;
1236
-					}
1237
-				} else {
1238
-					if (!isset($mounts[$row['storage']])) {
1239
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1240
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1241
-							$mounts[$row['storage']] = current($mountPoints);
1242
-						}
1243
-					}
1244
-					if (!empty($mounts[$row['storage']])) {
1245
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1246
-						$relPath = substr($path, $root); // path relative to data/user
1247
-						$row['path'] = rtrim($relPath, '/');
1248
-					}
1249
-				}
1250
-			}
1251
-
1252
-			if($checkExpireDate) {
1253
-				if (self::expireItem($row)) {
1254
-					continue;
1255
-				}
1256
-			}
1257
-			// Check if resharing is allowed, if not remove share permission
1258
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1259
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1260
-			}
1261
-			// Add display names to result
1262
-			$row['share_with_displayname'] = $row['share_with'];
1263
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
1264
-				$row['share_type'] === self::SHARE_TYPE_USER) {
1265
-				$row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
1266
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
1267
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
1268
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1269
-				foreach ($addressBookEntries as $entry) {
1270
-					foreach ($entry['CLOUD'] as $cloudID) {
1271
-						if ($cloudID === $row['share_with']) {
1272
-							$row['share_with_displayname'] = $entry['FN'];
1273
-						}
1274
-					}
1275
-				}
1276
-			}
1277
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1278
-				$row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
1279
-			}
1280
-
1281
-			if ($row['permissions'] > 0) {
1282
-				$items[$row['id']] = $row;
1283
-			}
1284
-
1285
-		}
1286
-
1287
-		// group items if we are looking for items shared with the current user
1288
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1289
-			$items = self::groupItems($items, $itemType);
1290
-		}
1291
-
1292
-		if (!empty($items)) {
1293
-			$collectionItems = array();
1294
-			foreach ($items as &$row) {
1295
-				// Return only the item instead of a 2-dimensional array
1296
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1297
-					if ($format == self::FORMAT_NONE) {
1298
-						return $row;
1299
-					} else {
1300
-						break;
1301
-					}
1302
-				}
1303
-				// Check if this is a collection of the requested item type
1304
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1305
-					if (($collectionBackend = self::getBackend($row['item_type']))
1306
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1307
-						// Collections can be inside collections, check if the item is a collection
1308
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1309
-							$collectionItems[] = $row;
1310
-						} else {
1311
-							$collection = array();
1312
-							$collection['item_type'] = $row['item_type'];
1313
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1314
-								$collection['path'] = basename($row['path']);
1315
-							}
1316
-							$row['collection'] = $collection;
1317
-							// Fetch all of the children sources
1318
-							$children = $collectionBackend->getChildren($row[$column]);
1319
-							foreach ($children as $child) {
1320
-								$childItem = $row;
1321
-								$childItem['item_type'] = $itemType;
1322
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1323
-									$childItem['item_source'] = $child['source'];
1324
-									$childItem['item_target'] = $child['target'];
1325
-								}
1326
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1327
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1328
-										$childItem['file_source'] = $child['source'];
1329
-									} else { // TODO is this really needed if we already know that we use the file backend?
1330
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1331
-										$childItem['file_source'] = $meta['fileid'];
1332
-									}
1333
-									$childItem['file_target'] =
1334
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
1335
-								}
1336
-								if (isset($item)) {
1337
-									if ($childItem[$column] == $item) {
1338
-										// Return only the item instead of a 2-dimensional array
1339
-										if ($limit == 1) {
1340
-											if ($format == self::FORMAT_NONE) {
1341
-												return $childItem;
1342
-											} else {
1343
-												// Unset the items array and break out of both loops
1344
-												$items = array();
1345
-												$items[] = $childItem;
1346
-												break 2;
1347
-											}
1348
-										} else {
1349
-											$collectionItems[] = $childItem;
1350
-										}
1351
-									}
1352
-								} else {
1353
-									$collectionItems[] = $childItem;
1354
-								}
1355
-							}
1356
-						}
1357
-					}
1358
-					// Remove collection item
1359
-					$toRemove = $row['id'];
1360
-					if (array_key_exists($toRemove, $switchedItems)) {
1361
-						$toRemove = $switchedItems[$toRemove];
1362
-					}
1363
-					unset($items[$toRemove]);
1364
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1365
-					// FIXME: Thats a dirty hack to improve file sharing performance,
1366
-					// see github issue #10588 for more details
1367
-					// Need to find a solution which works for all back-ends
1368
-					$collectionBackend = self::getBackend($row['item_type']);
1369
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
1370
-					foreach ($sharedParents as $parent) {
1371
-						$collectionItems[] = $parent;
1372
-					}
1373
-				}
1374
-			}
1375
-			if (!empty($collectionItems)) {
1376
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
1377
-				$items = array_merge($items, $collectionItems);
1378
-			}
1379
-
1380
-			// filter out invalid items, these can appear when subshare entries exist
1381
-			// for a group in which the requested user isn't a member any more
1382
-			$items = array_filter($items, function($item) {
1383
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1384
-			});
1385
-
1386
-			return self::formatResult($items, $column, $backend, $format, $parameters);
1387
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1388
-			// FIXME: Thats a dirty hack to improve file sharing performance,
1389
-			// see github issue #10588 for more details
1390
-			// Need to find a solution which works for all back-ends
1391
-			$collectionItems = array();
1392
-			$collectionBackend = self::getBackend('folder');
1393
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1394
-			foreach ($sharedParents as $parent) {
1395
-				$collectionItems[] = $parent;
1396
-			}
1397
-			if ($limit === 1) {
1398
-				return reset($collectionItems);
1399
-			}
1400
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1401
-		}
1402
-
1403
-		return array();
1404
-	}
1405
-
1406
-	/**
1407
-	 * group items with link to the same source
1408
-	 *
1409
-	 * @param array $items
1410
-	 * @param string $itemType
1411
-	 * @return array of grouped items
1412
-	 */
1413
-	protected static function groupItems($items, $itemType) {
1414
-
1415
-		$fileSharing = $itemType === 'file' || $itemType === 'folder';
1416
-
1417
-		$result = array();
1418
-
1419
-		foreach ($items as $item) {
1420
-			$grouped = false;
1421
-			foreach ($result as $key => $r) {
1422
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1423
-				// only group shares if they already point to the same target, otherwise the file where shared
1424
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1425
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1426
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1427
-					// add the first item to the list of grouped shares
1428
-					if (!isset($result[$key]['grouped'])) {
1429
-						$result[$key]['grouped'][] = $result[$key];
1430
-					}
1431
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1432
-					$result[$key]['grouped'][] = $item;
1433
-					$grouped = true;
1434
-					break;
1435
-				}
1436
-			}
1437
-
1438
-			if (!$grouped) {
1439
-				$result[] = $item;
1440
-			}
1441
-
1442
-		}
1443
-
1444
-		return $result;
1445
-	}
1446
-
1447
-	/**
1448
-	 * Put shared item into the database
1449
-	 * @param string $itemType Item type
1450
-	 * @param string $itemSource Item source
1451
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1452
-	 * @param string $shareWith User or group the item is being shared with
1453
-	 * @param string $uidOwner User that is the owner of shared item
1454
-	 * @param int $permissions CRUDS permissions
1455
-	 * @param boolean|array $parentFolder Parent folder target (optional)
1456
-	 * @param string $token (optional)
1457
-	 * @param string $itemSourceName name of the source item (optional)
1458
-	 * @param \DateTime $expirationDate (optional)
1459
-	 * @throws \Exception
1460
-	 * @return mixed id of the new share or false
1461
-	 */
1462
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1463
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1464
-
1465
-		$queriesToExecute = array();
1466
-		$suggestedItemTarget = null;
1467
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1468
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1469
-
1470
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1471
-		if(!empty($result)) {
1472
-			$parent = $result['parent'];
1473
-			$itemSource = $result['itemSource'];
1474
-			$fileSource = $result['fileSource'];
1475
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1476
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1477
-			$filePath = $result['filePath'];
1478
-		}
1479
-
1480
-		$isGroupShare = false;
1481
-		if ($shareType == self::SHARE_TYPE_GROUP) {
1482
-			$isGroupShare = true;
1483
-			if (isset($shareWith['users'])) {
1484
-				$users = $shareWith['users'];
1485
-			} else {
1486
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
1487
-				if ($group) {
1488
-					$users = $group->searchUsers('', -1, 0);
1489
-					$userIds = [];
1490
-					foreach ($users as $user) {
1491
-						$userIds[] = $user->getUID();
1492
-					}
1493
-					$users = $userIds;
1494
-				} else {
1495
-					$users = [];
1496
-				}
1497
-			}
1498
-			// remove current user from list
1499
-			if (in_array(\OCP\User::getUser(), $users)) {
1500
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
1501
-			}
1502
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1503
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1504
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1505
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
1506
-
1507
-			// add group share to table and remember the id as parent
1508
-			$queriesToExecute['groupShare'] = array(
1509
-				'itemType'			=> $itemType,
1510
-				'itemSource'		=> $itemSource,
1511
-				'itemTarget'		=> $groupItemTarget,
1512
-				'shareType'			=> $shareType,
1513
-				'shareWith'			=> $shareWith['group'],
1514
-				'uidOwner'			=> $uidOwner,
1515
-				'permissions'		=> $permissions,
1516
-				'shareTime'			=> time(),
1517
-				'fileSource'		=> $fileSource,
1518
-				'fileTarget'		=> $groupFileTarget,
1519
-				'token'				=> $token,
1520
-				'parent'			=> $parent,
1521
-				'expiration'		=> $expirationDate,
1522
-			);
1523
-
1524
-		} else {
1525
-			$users = array($shareWith);
1526
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1527
-				$suggestedItemTarget);
1528
-		}
1529
-
1530
-		$run = true;
1531
-		$error = '';
1532
-		$preHookData = array(
1533
-			'itemType' => $itemType,
1534
-			'itemSource' => $itemSource,
1535
-			'shareType' => $shareType,
1536
-			'uidOwner' => $uidOwner,
1537
-			'permissions' => $permissions,
1538
-			'fileSource' => $fileSource,
1539
-			'expiration' => $expirationDate,
1540
-			'token' => $token,
1541
-			'run' => &$run,
1542
-			'error' => &$error
1543
-		);
1544
-
1545
-		$preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1546
-		$preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1547
-
1548
-		\OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1549
-
1550
-		if ($run === false) {
1551
-			throw new \Exception($error);
1552
-		}
1553
-
1554
-		foreach ($users as $user) {
1555
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1556
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1557
-
1558
-			$userShareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType;
1559
-
1560
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1561
-				$fileTarget = $sourceExists['file_target'];
1562
-				$itemTarget = $sourceExists['item_target'];
1563
-
1564
-				// for group shares we don't need a additional entry if the target is the same
1565
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
1566
-					continue;
1567
-				}
1568
-
1569
-			} elseif(!$sourceExists && !$isGroupShare)  {
1570
-
1571
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1572
-					$uidOwner, $suggestedItemTarget, $parent);
1573
-				if (isset($fileSource)) {
1574
-					if ($parentFolder) {
1575
-						if ($parentFolder === true) {
1576
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1577
-								$uidOwner, $suggestedFileTarget, $parent);
1578
-							if ($fileTarget != $groupFileTarget) {
1579
-								$parentFolders[$user]['folder'] = $fileTarget;
1580
-							}
1581
-						} else if (isset($parentFolder[$user])) {
1582
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
1583
-							$parent = $parentFolder[$user]['id'];
1584
-						}
1585
-					} else {
1586
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1587
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1588
-					}
1589
-				} else {
1590
-					$fileTarget = null;
1591
-				}
1592
-
1593
-			} else {
1594
-
1595
-				// group share which doesn't exists until now, check if we need a unique target for this user
1596
-
1597
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1598
-					$uidOwner, $suggestedItemTarget, $parent);
1599
-
1600
-				// do we also need a file target
1601
-				if (isset($fileSource)) {
1602
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1603
-						$uidOwner, $suggestedFileTarget, $parent);
1604
-				} else {
1605
-					$fileTarget = null;
1606
-				}
1607
-
1608
-				if (($itemTarget === $groupItemTarget) &&
1609
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1610
-					continue;
1611
-				}
1612
-			}
1613
-
1614
-			$queriesToExecute[] = array(
1615
-				'itemType'			=> $itemType,
1616
-				'itemSource'		=> $itemSource,
1617
-				'itemTarget'		=> $itemTarget,
1618
-				'shareType'			=> $userShareType,
1619
-				'shareWith'			=> $user,
1620
-				'uidOwner'			=> $uidOwner,
1621
-				'permissions'		=> $permissions,
1622
-				'shareTime'			=> time(),
1623
-				'fileSource'		=> $fileSource,
1624
-				'fileTarget'		=> $fileTarget,
1625
-				'token'				=> $token,
1626
-				'parent'			=> $parent,
1627
-				'expiration'		=> $expirationDate,
1628
-			);
1629
-
1630
-		}
1631
-
1632
-		$id = false;
1633
-		if ($isGroupShare) {
1634
-			$id = self::insertShare($queriesToExecute['groupShare']);
1635
-			// Save this id, any extra rows for this group share will need to reference it
1636
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1637
-			unset($queriesToExecute['groupShare']);
1638
-		}
1639
-
1640
-		foreach ($queriesToExecute as $shareQuery) {
1641
-			$shareQuery['parent'] = $parent;
1642
-			$id = self::insertShare($shareQuery);
1643
-		}
1644
-
1645
-		$postHookData = array(
1646
-			'itemType' => $itemType,
1647
-			'itemSource' => $itemSource,
1648
-			'parent' => $parent,
1649
-			'shareType' => $shareType,
1650
-			'uidOwner' => $uidOwner,
1651
-			'permissions' => $permissions,
1652
-			'fileSource' => $fileSource,
1653
-			'id' => $parent,
1654
-			'token' => $token,
1655
-			'expirationDate' => $expirationDate,
1656
-		);
1657
-
1658
-		$postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1659
-		$postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1660
-		$postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1661
-
1662
-		\OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1663
-
1664
-
1665
-		return $id ? $id : false;
1666
-	}
1667
-
1668
-	/**
1669
-	 * @param string $itemType
1670
-	 * @param string $itemSource
1671
-	 * @param int $shareType
1672
-	 * @param string $shareWith
1673
-	 * @param string $uidOwner
1674
-	 * @param int $permissions
1675
-	 * @param string|null $itemSourceName
1676
-	 * @param null|\DateTime $expirationDate
1677
-	 */
1678
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1679
-		$backend = self::getBackend($itemType);
1680
-
1681
-		$l = \OC::$server->getL10N('lib');
1682
-		$result = array();
1683
-
1684
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1685
-
1686
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1687
-		if ($checkReshare) {
1688
-			// Check if attempting to share back to owner
1689
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1690
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
1691
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1692
-
1693
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
1694
-				throw new \Exception($message_t);
1695
-			}
1696
-		}
1697
-
1698
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1699
-			// Check if share permissions is granted
1700
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1701
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1702
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1703
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1704
-
1705
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
1706
-					throw new \Exception($message_t);
1707
-				} else {
1708
-					// TODO Don't check if inside folder
1709
-					$result['parent'] = $checkReshare['id'];
1710
-
1711
-					$result['expirationDate'] = $expirationDate;
1712
-					// $checkReshare['expiration'] could be null and then is always less than any value
1713
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1714
-						$result['expirationDate'] = $checkReshare['expiration'];
1715
-					}
1716
-
1717
-					// only suggest the same name as new target if it is a reshare of the
1718
-					// same file/folder and not the reshare of a child
1719
-					if ($checkReshare[$column] === $itemSource) {
1720
-						$result['filePath'] = $checkReshare['file_target'];
1721
-						$result['itemSource'] = $checkReshare['item_source'];
1722
-						$result['fileSource'] = $checkReshare['file_source'];
1723
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1724
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1725
-					} else {
1726
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1727
-						$result['suggestedItemTarget'] = null;
1728
-						$result['suggestedFileTarget'] = null;
1729
-						$result['itemSource'] = $itemSource;
1730
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1731
-					}
1732
-				}
1733
-			} else {
1734
-				$message = 'Sharing %s failed, because resharing is not allowed';
1735
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1736
-
1737
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
1738
-				throw new \Exception($message_t);
1739
-			}
1740
-		} else {
1741
-			$result['parent'] = null;
1742
-			$result['suggestedItemTarget'] = null;
1743
-			$result['suggestedFileTarget'] = null;
1744
-			$result['itemSource'] = $itemSource;
1745
-			$result['expirationDate'] = $expirationDate;
1746
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1747
-				$message = 'Sharing %s failed, because the sharing backend for '
1748
-					.'%s could not find its source';
1749
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1750
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
1751
-				throw new \Exception($message_t);
1752
-			}
1753
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1754
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1755
-				if ($itemType == 'file' || $itemType == 'folder') {
1756
-					$result['fileSource'] = $itemSource;
1757
-				} else {
1758
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1759
-					$result['fileSource'] = $meta['fileid'];
1760
-				}
1761
-				if ($result['fileSource'] == -1) {
1762
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1763
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1764
-
1765
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1766
-					throw new \Exception($message_t);
1767
-				}
1768
-			} else {
1769
-				$result['filePath'] = null;
1770
-				$result['fileSource'] = null;
1771
-			}
1772
-		}
1773
-
1774
-		return $result;
1775
-	}
1776
-
1777
-	/**
1778
-	 *
1779
-	 * @param array $shareData
1780
-	 * @return mixed false in case of a failure or the id of the new share
1781
-	 */
1782
-	private static function insertShare(array $shareData) {
1783
-
1784
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1785
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1786
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1787
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1788
-		$query->bindValue(1, $shareData['itemType']);
1789
-		$query->bindValue(2, $shareData['itemSource']);
1790
-		$query->bindValue(3, $shareData['itemTarget']);
1791
-		$query->bindValue(4, $shareData['shareType']);
1792
-		$query->bindValue(5, $shareData['shareWith']);
1793
-		$query->bindValue(6, $shareData['uidOwner']);
1794
-		$query->bindValue(7, $shareData['permissions']);
1795
-		$query->bindValue(8, $shareData['shareTime']);
1796
-		$query->bindValue(9, $shareData['fileSource']);
1797
-		$query->bindValue(10, $shareData['fileTarget']);
1798
-		$query->bindValue(11, $shareData['token']);
1799
-		$query->bindValue(12, $shareData['parent']);
1800
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1801
-		$result = $query->execute();
1802
-
1803
-		$id = false;
1804
-		if ($result) {
1805
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1806
-		}
1807
-
1808
-		return $id;
1809
-
1810
-	}
1811
-
1812
-	/**
1813
-	 * In case a password protected link is not yet authenticated this function will return false
1814
-	 *
1815
-	 * @param array $linkItem
1816
-	 * @return boolean
1817
-	 */
1818
-	public static function checkPasswordProtectedShare(array $linkItem) {
1819
-		if (!isset($linkItem['share_with'])) {
1820
-			return true;
1821
-		}
1822
-		if (!isset($linkItem['share_type'])) {
1823
-			return true;
1824
-		}
1825
-		if (!isset($linkItem['id'])) {
1826
-			return true;
1827
-		}
1828
-
1829
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1830
-			return true;
1831
-		}
1832
-
1833
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
1834
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1835
-			return true;
1836
-		}
1837
-
1838
-		return false;
1839
-	}
1840
-
1841
-	/**
1842
-	 * construct select statement
1843
-	 * @param int $format
1844
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1845
-	 * @param string $uidOwner
1846
-	 * @return string select statement
1847
-	 */
1848
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1849
-		$select = '*';
1850
-		if ($format == self::FORMAT_STATUSES) {
1851
-			if ($fileDependent) {
1852
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1853
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1854
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1855
-					. '`uid_initiator`';
1856
-			} else {
1857
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1858
-			}
1859
-		} else {
1860
-			if (isset($uidOwner)) {
1861
-				if ($fileDependent) {
1862
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1863
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1864
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1865
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1866
-				} else {
1867
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1868
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1869
-				}
1870
-			} else {
1871
-				if ($fileDependent) {
1872
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1873
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1874
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1875
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1876
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1877
-					} else {
1878
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1879
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1880
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1881
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1882
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1883
-					}
1884
-				}
1885
-			}
1886
-		}
1887
-		return $select;
1888
-	}
1889
-
1890
-
1891
-	/**
1892
-	 * transform db results
1893
-	 * @param array $row result
1894
-	 */
1895
-	private static function transformDBResults(&$row) {
1896
-		if (isset($row['id'])) {
1897
-			$row['id'] = (int) $row['id'];
1898
-		}
1899
-		if (isset($row['share_type'])) {
1900
-			$row['share_type'] = (int) $row['share_type'];
1901
-		}
1902
-		if (isset($row['parent'])) {
1903
-			$row['parent'] = (int) $row['parent'];
1904
-		}
1905
-		if (isset($row['file_parent'])) {
1906
-			$row['file_parent'] = (int) $row['file_parent'];
1907
-		}
1908
-		if (isset($row['file_source'])) {
1909
-			$row['file_source'] = (int) $row['file_source'];
1910
-		}
1911
-		if (isset($row['permissions'])) {
1912
-			$row['permissions'] = (int) $row['permissions'];
1913
-		}
1914
-		if (isset($row['storage'])) {
1915
-			$row['storage'] = (int) $row['storage'];
1916
-		}
1917
-		if (isset($row['stime'])) {
1918
-			$row['stime'] = (int) $row['stime'];
1919
-		}
1920
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1921
-			// discard expiration date for non-link shares, which might have been
1922
-			// set by ancient bugs
1923
-			$row['expiration'] = null;
1924
-		}
1925
-	}
1926
-
1927
-	/**
1928
-	 * format result
1929
-	 * @param array $items result
1930
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1931
-	 * @param \OCP\Share_Backend $backend sharing backend
1932
-	 * @param int $format
1933
-	 * @param array $parameters additional format parameters
1934
-	 * @return array format result
1935
-	 */
1936
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1937
-		if ($format === self::FORMAT_NONE) {
1938
-			return $items;
1939
-		} else if ($format === self::FORMAT_STATUSES) {
1940
-			$statuses = array();
1941
-			foreach ($items as $item) {
1942
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1943
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1944
-						continue;
1945
-					}
1946
-					$statuses[$item[$column]]['link'] = true;
1947
-				} else if (!isset($statuses[$item[$column]])) {
1948
-					$statuses[$item[$column]]['link'] = false;
1949
-				}
1950
-				if (!empty($item['file_target'])) {
1951
-					$statuses[$item[$column]]['path'] = $item['path'];
1952
-				}
1953
-			}
1954
-			return $statuses;
1955
-		} else {
1956
-			return $backend->formatItems($items, $format, $parameters);
1957
-		}
1958
-	}
1959
-
1960
-	/**
1961
-	 * remove protocol from URL
1962
-	 *
1963
-	 * @param string $url
1964
-	 * @return string
1965
-	 */
1966
-	public static function removeProtocolFromUrl($url) {
1967
-		if (strpos($url, 'https://') === 0) {
1968
-			return substr($url, strlen('https://'));
1969
-		} else if (strpos($url, 'http://') === 0) {
1970
-			return substr($url, strlen('http://'));
1971
-		}
1972
-
1973
-		return $url;
1974
-	}
1975
-
1976
-	/**
1977
-	 * try http post first with https and then with http as a fallback
1978
-	 *
1979
-	 * @param string $remoteDomain
1980
-	 * @param string $urlSuffix
1981
-	 * @param array $fields post parameters
1982
-	 * @return array
1983
-	 */
1984
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1985
-		$protocol = 'https://';
1986
-		$result = [
1987
-			'success' => false,
1988
-			'result' => '',
1989
-		];
1990
-		$try = 0;
1991
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1992
-		while ($result['success'] === false && $try < 2) {
1993
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1994
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1995
-			$client = \OC::$server->getHTTPClientService()->newClient();
1996
-
1997
-			try {
1998
-				$response = $client->post(
1999
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
2000
-					[
2001
-						'body' => $fields,
2002
-						'connect_timeout' => 10,
2003
-					]
2004
-				);
2005
-
2006
-				$result = ['success' => true, 'result' => $response->getBody()];
2007
-			} catch (\Exception $e) {
2008
-				$result = ['success' => false, 'result' => $e->getMessage()];
2009
-			}
2010
-
2011
-			$try++;
2012
-			$protocol = 'http://';
2013
-		}
2014
-
2015
-		return $result;
2016
-	}
2017
-
2018
-	/**
2019
-	 * send server-to-server share to remote server
2020
-	 *
2021
-	 * @param string $token
2022
-	 * @param string $shareWith
2023
-	 * @param string $name
2024
-	 * @param int $remote_id
2025
-	 * @param string $owner
2026
-	 * @return bool
2027
-	 */
2028
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2029
-
2030
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2031
-
2032
-		if ($user && $remote) {
2033
-			$url = $remote;
2034
-
2035
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2036
-
2037
-			$fields = array(
2038
-				'shareWith' => $user,
2039
-				'token' => $token,
2040
-				'name' => $name,
2041
-				'remoteId' => $remote_id,
2042
-				'owner' => $owner,
2043
-				'remote' => $local,
2044
-			);
2045
-
2046
-			$url = self::removeProtocolFromUrl($url);
2047
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2048
-			$status = json_decode($result['result'], true);
2049
-
2050
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2051
-				\OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]);
2052
-				return true;
2053
-			}
2054
-
2055
-		}
2056
-
2057
-		return false;
2058
-	}
2059
-
2060
-	/**
2061
-	 * send server-to-server unshare to remote server
2062
-	 *
2063
-	 * @param string $remote url
2064
-	 * @param int $id share id
2065
-	 * @param string $token
2066
-	 * @return bool
2067
-	 */
2068
-	private static function sendRemoteUnshare($remote, $id, $token) {
2069
-		$url = rtrim($remote, '/');
2070
-		$fields = array('token' => $token, 'format' => 'json');
2071
-		$url = self::removeProtocolFromUrl($url);
2072
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2073
-		$status = json_decode($result['result'], true);
2074
-
2075
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2076
-	}
2077
-
2078
-	/**
2079
-	 * check if user can only share with group members
2080
-	 * @return bool
2081
-	 */
2082
-	public static function shareWithGroupMembersOnly() {
2083
-		$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2084
-		return $value === 'yes';
2085
-	}
2086
-
2087
-	/**
2088
-	 * @return bool
2089
-	 */
2090
-	public static function isDefaultExpireDateEnabled() {
2091
-		$defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2092
-		return $defaultExpireDateEnabled === 'yes';
2093
-	}
2094
-
2095
-	/**
2096
-	 * @return int
2097
-	 */
2098
-	public static function getExpireInterval() {
2099
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2100
-	}
2101
-
2102
-	/**
2103
-	 * Checks whether the given path is reachable for the given owner
2104
-	 *
2105
-	 * @param string $path path relative to files
2106
-	 * @param string $ownerStorageId storage id of the owner
2107
-	 *
2108
-	 * @return boolean true if file is reachable, false otherwise
2109
-	 */
2110
-	private static function isFileReachable($path, $ownerStorageId) {
2111
-		// if outside the home storage, file is always considered reachable
2112
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2113
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2114
-		)) {
2115
-			return true;
2116
-		}
2117
-
2118
-		// if inside the home storage, the file has to be under "/files/"
2119
-		$path = ltrim($path, '/');
2120
-		if (substr($path, 0, 6) === 'files/') {
2121
-			return true;
2122
-		}
2123
-
2124
-		return false;
2125
-	}
2126
-
2127
-	/**
2128
-	 * @param IConfig $config
2129
-	 * @return bool
2130
-	 */
2131
-	public static function enforcePassword(IConfig $config) {
2132
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2133
-		return $enforcePassword === 'yes';
2134
-	}
2135
-
2136
-	/**
2137
-	 * @param string $password
2138
-	 * @throws \Exception
2139
-	 */
2140
-	private static function verifyPassword($password) {
2141
-
2142
-		$accepted = true;
2143
-		$message = '';
2144
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2145
-			'password' => $password,
2146
-			'accepted' => &$accepted,
2147
-			'message' => &$message
2148
-		]);
2149
-
2150
-		if (!$accepted) {
2151
-			throw new \Exception($message);
2152
-		}
2153
-	}
727
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
728
+
729
+        if($result === false) {
730
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
731
+        }
732
+    }
733
+
734
+    /**
735
+     * validate expiration date if it meets all constraints
736
+     *
737
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
738
+     * @param string $shareTime timestamp when the file was shared
739
+     * @param string $itemType
740
+     * @param string $itemSource
741
+     * @return \DateTime validated date
742
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
743
+     */
744
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
745
+        $l = \OC::$server->getL10N('lib');
746
+        $date = new \DateTime($expireDate);
747
+        $today = new \DateTime('now');
748
+
749
+        // if the user doesn't provide a share time we need to get it from the database
750
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
751
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
752
+        if ($defaultExpireDateEnforced && $shareTime === null) {
753
+            $items = self::getItemShared($itemType, $itemSource);
754
+            $firstItem = reset($items);
755
+            $shareTime = (int)$firstItem['stime'];
756
+        }
757
+
758
+        if ($defaultExpireDateEnforced) {
759
+            // initialize max date with share time
760
+            $maxDate = new \DateTime();
761
+            $maxDate->setTimestamp($shareTime);
762
+            $maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
763
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
764
+            if ($date > $maxDate) {
765
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
766
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
767
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
768
+                throw new \Exception($warning_t);
769
+            }
770
+        }
771
+
772
+        if ($date < $today) {
773
+            $message = 'Cannot set expiration date. Expiration date is in the past';
774
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
775
+            \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
776
+            throw new \Exception($message_t);
777
+        }
778
+
779
+        return $date;
780
+    }
781
+
782
+    /**
783
+     * Checks whether a share has expired, calls unshareItem() if yes.
784
+     * @param array $item Share data (usually database row)
785
+     * @return boolean True if item was expired, false otherwise.
786
+     */
787
+    protected static function expireItem(array $item) {
788
+
789
+        $result = false;
790
+
791
+        // only use default expiration date for link shares
792
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
793
+
794
+            // calculate expiration date
795
+            if (!empty($item['expiration'])) {
796
+                $userDefinedExpire = new \DateTime($item['expiration']);
797
+                $expires = $userDefinedExpire->getTimestamp();
798
+            } else {
799
+                $expires = null;
800
+            }
801
+
802
+
803
+            // get default expiration settings
804
+            $defaultSettings = Helper::getDefaultExpireSetting();
805
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
806
+
807
+
808
+            if (is_int($expires)) {
809
+                $now = time();
810
+                if ($now > $expires) {
811
+                    self::unshareItem($item);
812
+                    $result = true;
813
+                }
814
+            }
815
+        }
816
+        return $result;
817
+    }
818
+
819
+    /**
820
+     * Unshares a share given a share data array
821
+     * @param array $item Share data (usually database row)
822
+     * @param int $newParent parent ID
823
+     * @return null
824
+     */
825
+    protected static function unshareItem(array $item, $newParent = null) {
826
+
827
+        $shareType = (int)$item['share_type'];
828
+        $shareWith = null;
829
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
830
+            $shareWith = $item['share_with'];
831
+        }
832
+
833
+        // Pass all the vars we have for now, they may be useful
834
+        $hookParams = array(
835
+            'id'            => $item['id'],
836
+            'itemType'      => $item['item_type'],
837
+            'itemSource'    => $item['item_source'],
838
+            'shareType'     => $shareType,
839
+            'shareWith'     => $shareWith,
840
+            'itemParent'    => $item['parent'],
841
+            'uidOwner'      => $item['uid_owner'],
842
+        );
843
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
844
+            $hookParams['fileSource'] = $item['file_source'];
845
+            $hookParams['fileTarget'] = $item['file_target'];
846
+        }
847
+
848
+        \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
849
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
850
+        $deletedShares[] = $hookParams;
851
+        $hookParams['deletedShares'] = $deletedShares;
852
+        \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
853
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
854
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
855
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
856
+        }
857
+    }
858
+
859
+    /**
860
+     * Get the backend class for the specified item type
861
+     * @param string $itemType
862
+     * @throws \Exception
863
+     * @return \OCP\Share_Backend
864
+     */
865
+    public static function getBackend($itemType) {
866
+        $l = \OC::$server->getL10N('lib');
867
+        if (isset(self::$backends[$itemType])) {
868
+            return self::$backends[$itemType];
869
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
870
+            $class = self::$backendTypes[$itemType]['class'];
871
+            if (class_exists($class)) {
872
+                self::$backends[$itemType] = new $class;
873
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
874
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
875
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
876
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
877
+                    throw new \Exception($message_t);
878
+                }
879
+                return self::$backends[$itemType];
880
+            } else {
881
+                $message = 'Sharing backend %s not found';
882
+                $message_t = $l->t('Sharing backend %s not found', array($class));
883
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
884
+                throw new \Exception($message_t);
885
+            }
886
+        }
887
+        $message = 'Sharing backend for %s not found';
888
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
889
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
890
+        throw new \Exception($message_t);
891
+    }
892
+
893
+    /**
894
+     * Check if resharing is allowed
895
+     * @return boolean true if allowed or false
896
+     *
897
+     * Resharing is allowed by default if not configured
898
+     */
899
+    public static function isResharingAllowed() {
900
+        if (!isset(self::$isResharingAllowed)) {
901
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
902
+                self::$isResharingAllowed = true;
903
+            } else {
904
+                self::$isResharingAllowed = false;
905
+            }
906
+        }
907
+        return self::$isResharingAllowed;
908
+    }
909
+
910
+    /**
911
+     * Get a list of collection item types for the specified item type
912
+     * @param string $itemType
913
+     * @return array
914
+     */
915
+    private static function getCollectionItemTypes($itemType) {
916
+        $collectionTypes = array($itemType);
917
+        foreach (self::$backendTypes as $type => $backend) {
918
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
919
+                $collectionTypes[] = $type;
920
+            }
921
+        }
922
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
923
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
924
+            unset($collectionTypes[0]);
925
+        }
926
+        // Return array if collections were found or the item type is a
927
+        // collection itself - collections can be inside collections
928
+        if (count($collectionTypes) > 0) {
929
+            return $collectionTypes;
930
+        }
931
+        return false;
932
+    }
933
+
934
+    /**
935
+     * Get the owners of items shared with a user.
936
+     *
937
+     * @param string $user The user the items are shared with.
938
+     * @param string $type The type of the items shared with the user.
939
+     * @param boolean $includeCollections Include collection item types (optional)
940
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
941
+     * @return array
942
+     */
943
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
944
+        // First, we find out if $type is part of a collection (and if that collection is part of
945
+        // another one and so on).
946
+        $collectionTypes = array();
947
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
948
+            $collectionTypes[] = $type;
949
+        }
950
+
951
+        // Of these collection types, along with our original $type, we make a
952
+        // list of the ones for which a sharing backend has been registered.
953
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
954
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
955
+        $allMaybeSharedItems = array();
956
+        foreach ($collectionTypes as $collectionType) {
957
+            if (isset(self::$backends[$collectionType])) {
958
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
959
+                    $collectionType,
960
+                    $user,
961
+                    self::FORMAT_NONE
962
+                );
963
+            }
964
+        }
965
+
966
+        $owners = array();
967
+        if ($includeOwner) {
968
+            $owners[] = $user;
969
+        }
970
+
971
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
972
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
973
+        // and return them as elements of a list that look like "Tag (owner)".
974
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
975
+            foreach ($maybeSharedItems as $sharedItem) {
976
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
977
+                    $owners[] = $sharedItem['uid_owner'];
978
+                }
979
+            }
980
+        }
981
+
982
+        return $owners;
983
+    }
984
+
985
+    /**
986
+     * Get shared items from the database
987
+     * @param string $itemType
988
+     * @param string $item Item source or target (optional)
989
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
990
+     * @param string $shareWith User or group the item is being shared with
991
+     * @param string $uidOwner User that is the owner of shared items (optional)
992
+     * @param int $format Format to convert items to with formatItems() (optional)
993
+     * @param mixed $parameters to pass to formatItems() (optional)
994
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
995
+     * @param boolean $includeCollections Include collection item types (optional)
996
+     * @param boolean $itemShareWithBySource (optional)
997
+     * @param boolean $checkExpireDate
998
+     * @return array
999
+     *
1000
+     * See public functions getItem(s)... for parameter usage
1001
+     *
1002
+     */
1003
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1004
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1005
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1006
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
1007
+            return array();
1008
+        }
1009
+        $backend = self::getBackend($itemType);
1010
+        $collectionTypes = false;
1011
+        // Get filesystem root to add it to the file target and remove from the
1012
+        // file source, match file_source with the file cache
1013
+        if ($itemType == 'file' || $itemType == 'folder') {
1014
+            if(!is_null($uidOwner)) {
1015
+                $root = \OC\Files\Filesystem::getRoot();
1016
+            } else {
1017
+                $root = '';
1018
+            }
1019
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1020
+            if (!isset($item)) {
1021
+                $where .= ' AND `file_target` IS NOT NULL ';
1022
+            }
1023
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1024
+            $fileDependent = true;
1025
+            $queryArgs = array();
1026
+        } else {
1027
+            $fileDependent = false;
1028
+            $root = '';
1029
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1030
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1031
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1032
+                if (!in_array($itemType, $collectionTypes)) {
1033
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1034
+                } else {
1035
+                    $itemTypes = $collectionTypes;
1036
+                }
1037
+                $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
1038
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1039
+                $queryArgs = $itemTypes;
1040
+            } else {
1041
+                $where = ' WHERE `item_type` = ?';
1042
+                $queryArgs = array($itemType);
1043
+            }
1044
+        }
1045
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1046
+            $where .= ' AND `share_type` != ?';
1047
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1048
+        }
1049
+        if (isset($shareType)) {
1050
+            // Include all user and group items
1051
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1052
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1053
+                $queryArgs[] = self::SHARE_TYPE_USER;
1054
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1055
+                $queryArgs[] = $shareWith;
1056
+
1057
+                $user = \OC::$server->getUserManager()->get($shareWith);
1058
+                $groups = [];
1059
+                if ($user) {
1060
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1061
+                }
1062
+                if (!empty($groups)) {
1063
+                    $placeholders = implode(',', array_fill(0, count($groups), '?'));
1064
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1065
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1066
+                    $queryArgs = array_merge($queryArgs, $groups);
1067
+                }
1068
+                $where .= ')';
1069
+                // Don't include own group shares
1070
+                $where .= ' AND `uid_owner` != ?';
1071
+                $queryArgs[] = $shareWith;
1072
+            } else {
1073
+                $where .= ' AND `share_type` = ?';
1074
+                $queryArgs[] = $shareType;
1075
+                if (isset($shareWith)) {
1076
+                    $where .= ' AND `share_with` = ?';
1077
+                    $queryArgs[] = $shareWith;
1078
+                }
1079
+            }
1080
+        }
1081
+        if (isset($uidOwner)) {
1082
+            $where .= ' AND `uid_owner` = ?';
1083
+            $queryArgs[] = $uidOwner;
1084
+            if (!isset($shareType)) {
1085
+                // Prevent unique user targets for group shares from being selected
1086
+                $where .= ' AND `share_type` != ?';
1087
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1088
+            }
1089
+            if ($fileDependent) {
1090
+                $column = 'file_source';
1091
+            } else {
1092
+                $column = 'item_source';
1093
+            }
1094
+        } else {
1095
+            if ($fileDependent) {
1096
+                $column = 'file_target';
1097
+            } else {
1098
+                $column = 'item_target';
1099
+            }
1100
+        }
1101
+        if (isset($item)) {
1102
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1103
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1104
+                $where .= ' AND (';
1105
+            } else {
1106
+                $where .= ' AND';
1107
+            }
1108
+            // If looking for own shared items, check item_source else check item_target
1109
+            if (isset($uidOwner) || $itemShareWithBySource) {
1110
+                // If item type is a file, file source needs to be checked in case the item was converted
1111
+                if ($fileDependent) {
1112
+                    $where .= ' `file_source` = ?';
1113
+                    $column = 'file_source';
1114
+                } else {
1115
+                    $where .= ' `item_source` = ?';
1116
+                    $column = 'item_source';
1117
+                }
1118
+            } else {
1119
+                if ($fileDependent) {
1120
+                    $where .= ' `file_target` = ?';
1121
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1122
+                } else {
1123
+                    $where .= ' `item_target` = ?';
1124
+                }
1125
+            }
1126
+            $queryArgs[] = $item;
1127
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1128
+                $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
1129
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1130
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1131
+            }
1132
+        }
1133
+
1134
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1135
+            // Make sure the unique user target is returned if it exists,
1136
+            // unique targets should follow the group share in the database
1137
+            // If the limit is not 1, the filtering can be done later
1138
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1139
+        } else {
1140
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1141
+        }
1142
+
1143
+        if ($limit != -1 && !$includeCollections) {
1144
+            // The limit must be at least 3, because filtering needs to be done
1145
+            if ($limit < 3) {
1146
+                $queryLimit = 3;
1147
+            } else {
1148
+                $queryLimit = $limit;
1149
+            }
1150
+        } else {
1151
+            $queryLimit = null;
1152
+        }
1153
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1154
+        $root = strlen($root);
1155
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1156
+        $result = $query->execute($queryArgs);
1157
+        if ($result === false) {
1158
+            \OCP\Util::writeLog('OCP\Share',
1159
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1160
+                \OCP\Util::ERROR);
1161
+        }
1162
+        $items = array();
1163
+        $targets = array();
1164
+        $switchedItems = array();
1165
+        $mounts = array();
1166
+        while ($row = $result->fetchRow()) {
1167
+            self::transformDBResults($row);
1168
+            // Filter out duplicate group shares for users with unique targets
1169
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1170
+                continue;
1171
+            }
1172
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1173
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1174
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1175
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1176
+                // if the group share was unshared from the user we keep the permission, otherwise
1177
+                // we take the permission from the parent because this is always the up-to-date
1178
+                // permission for the group share
1179
+                if ($row['permissions'] > 0) {
1180
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1181
+                }
1182
+                // Remove the parent group share
1183
+                unset($items[$row['parent']]);
1184
+                if ($row['permissions'] == 0) {
1185
+                    continue;
1186
+                }
1187
+            } else if (!isset($uidOwner)) {
1188
+                // Check if the same target already exists
1189
+                if (isset($targets[$row['id']])) {
1190
+                    // Check if the same owner shared with the user twice
1191
+                    // through a group and user share - this is allowed
1192
+                    $id = $targets[$row['id']];
1193
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1194
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1195
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1196
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1197
+                            $items[$id]['share_with'] = $row['share_with'];
1198
+                        }
1199
+                        // Switch ids if sharing permission is granted on only
1200
+                        // one share to ensure correct parent is used if resharing
1201
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1202
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1203
+                            $items[$row['id']] = $items[$id];
1204
+                            $switchedItems[$id] = $row['id'];
1205
+                            unset($items[$id]);
1206
+                            $id = $row['id'];
1207
+                        }
1208
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1209
+
1210
+                    }
1211
+                    continue;
1212
+                } elseif (!empty($row['parent'])) {
1213
+                    $targets[$row['parent']] = $row['id'];
1214
+                }
1215
+            }
1216
+            // Remove root from file source paths if retrieving own shared items
1217
+            if (isset($uidOwner) && isset($row['path'])) {
1218
+                if (isset($row['parent'])) {
1219
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1220
+                    $parentResult = $query->execute(array($row['parent']));
1221
+                    if ($result === false) {
1222
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1223
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1224
+                            \OCP\Util::ERROR);
1225
+                    } else {
1226
+                        $parentRow = $parentResult->fetchRow();
1227
+                        $tmpPath = $parentRow['file_target'];
1228
+                        // find the right position where the row path continues from the target path
1229
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1230
+                        $subPath = substr($row['path'], $pos);
1231
+                        $splitPath = explode('/', $subPath);
1232
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1233
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1234
+                        }
1235
+                        $row['path'] = $tmpPath;
1236
+                    }
1237
+                } else {
1238
+                    if (!isset($mounts[$row['storage']])) {
1239
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1240
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1241
+                            $mounts[$row['storage']] = current($mountPoints);
1242
+                        }
1243
+                    }
1244
+                    if (!empty($mounts[$row['storage']])) {
1245
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1246
+                        $relPath = substr($path, $root); // path relative to data/user
1247
+                        $row['path'] = rtrim($relPath, '/');
1248
+                    }
1249
+                }
1250
+            }
1251
+
1252
+            if($checkExpireDate) {
1253
+                if (self::expireItem($row)) {
1254
+                    continue;
1255
+                }
1256
+            }
1257
+            // Check if resharing is allowed, if not remove share permission
1258
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1259
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1260
+            }
1261
+            // Add display names to result
1262
+            $row['share_with_displayname'] = $row['share_with'];
1263
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
1264
+                $row['share_type'] === self::SHARE_TYPE_USER) {
1265
+                $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
1266
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
1267
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
1268
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1269
+                foreach ($addressBookEntries as $entry) {
1270
+                    foreach ($entry['CLOUD'] as $cloudID) {
1271
+                        if ($cloudID === $row['share_with']) {
1272
+                            $row['share_with_displayname'] = $entry['FN'];
1273
+                        }
1274
+                    }
1275
+                }
1276
+            }
1277
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1278
+                $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
1279
+            }
1280
+
1281
+            if ($row['permissions'] > 0) {
1282
+                $items[$row['id']] = $row;
1283
+            }
1284
+
1285
+        }
1286
+
1287
+        // group items if we are looking for items shared with the current user
1288
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1289
+            $items = self::groupItems($items, $itemType);
1290
+        }
1291
+
1292
+        if (!empty($items)) {
1293
+            $collectionItems = array();
1294
+            foreach ($items as &$row) {
1295
+                // Return only the item instead of a 2-dimensional array
1296
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1297
+                    if ($format == self::FORMAT_NONE) {
1298
+                        return $row;
1299
+                    } else {
1300
+                        break;
1301
+                    }
1302
+                }
1303
+                // Check if this is a collection of the requested item type
1304
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1305
+                    if (($collectionBackend = self::getBackend($row['item_type']))
1306
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1307
+                        // Collections can be inside collections, check if the item is a collection
1308
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1309
+                            $collectionItems[] = $row;
1310
+                        } else {
1311
+                            $collection = array();
1312
+                            $collection['item_type'] = $row['item_type'];
1313
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1314
+                                $collection['path'] = basename($row['path']);
1315
+                            }
1316
+                            $row['collection'] = $collection;
1317
+                            // Fetch all of the children sources
1318
+                            $children = $collectionBackend->getChildren($row[$column]);
1319
+                            foreach ($children as $child) {
1320
+                                $childItem = $row;
1321
+                                $childItem['item_type'] = $itemType;
1322
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1323
+                                    $childItem['item_source'] = $child['source'];
1324
+                                    $childItem['item_target'] = $child['target'];
1325
+                                }
1326
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1327
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1328
+                                        $childItem['file_source'] = $child['source'];
1329
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
1330
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1331
+                                        $childItem['file_source'] = $meta['fileid'];
1332
+                                    }
1333
+                                    $childItem['file_target'] =
1334
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
1335
+                                }
1336
+                                if (isset($item)) {
1337
+                                    if ($childItem[$column] == $item) {
1338
+                                        // Return only the item instead of a 2-dimensional array
1339
+                                        if ($limit == 1) {
1340
+                                            if ($format == self::FORMAT_NONE) {
1341
+                                                return $childItem;
1342
+                                            } else {
1343
+                                                // Unset the items array and break out of both loops
1344
+                                                $items = array();
1345
+                                                $items[] = $childItem;
1346
+                                                break 2;
1347
+                                            }
1348
+                                        } else {
1349
+                                            $collectionItems[] = $childItem;
1350
+                                        }
1351
+                                    }
1352
+                                } else {
1353
+                                    $collectionItems[] = $childItem;
1354
+                                }
1355
+                            }
1356
+                        }
1357
+                    }
1358
+                    // Remove collection item
1359
+                    $toRemove = $row['id'];
1360
+                    if (array_key_exists($toRemove, $switchedItems)) {
1361
+                        $toRemove = $switchedItems[$toRemove];
1362
+                    }
1363
+                    unset($items[$toRemove]);
1364
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1365
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
1366
+                    // see github issue #10588 for more details
1367
+                    // Need to find a solution which works for all back-ends
1368
+                    $collectionBackend = self::getBackend($row['item_type']);
1369
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
1370
+                    foreach ($sharedParents as $parent) {
1371
+                        $collectionItems[] = $parent;
1372
+                    }
1373
+                }
1374
+            }
1375
+            if (!empty($collectionItems)) {
1376
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
1377
+                $items = array_merge($items, $collectionItems);
1378
+            }
1379
+
1380
+            // filter out invalid items, these can appear when subshare entries exist
1381
+            // for a group in which the requested user isn't a member any more
1382
+            $items = array_filter($items, function($item) {
1383
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1384
+            });
1385
+
1386
+            return self::formatResult($items, $column, $backend, $format, $parameters);
1387
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1388
+            // FIXME: Thats a dirty hack to improve file sharing performance,
1389
+            // see github issue #10588 for more details
1390
+            // Need to find a solution which works for all back-ends
1391
+            $collectionItems = array();
1392
+            $collectionBackend = self::getBackend('folder');
1393
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1394
+            foreach ($sharedParents as $parent) {
1395
+                $collectionItems[] = $parent;
1396
+            }
1397
+            if ($limit === 1) {
1398
+                return reset($collectionItems);
1399
+            }
1400
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1401
+        }
1402
+
1403
+        return array();
1404
+    }
1405
+
1406
+    /**
1407
+     * group items with link to the same source
1408
+     *
1409
+     * @param array $items
1410
+     * @param string $itemType
1411
+     * @return array of grouped items
1412
+     */
1413
+    protected static function groupItems($items, $itemType) {
1414
+
1415
+        $fileSharing = $itemType === 'file' || $itemType === 'folder';
1416
+
1417
+        $result = array();
1418
+
1419
+        foreach ($items as $item) {
1420
+            $grouped = false;
1421
+            foreach ($result as $key => $r) {
1422
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1423
+                // only group shares if they already point to the same target, otherwise the file where shared
1424
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1425
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1426
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1427
+                    // add the first item to the list of grouped shares
1428
+                    if (!isset($result[$key]['grouped'])) {
1429
+                        $result[$key]['grouped'][] = $result[$key];
1430
+                    }
1431
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1432
+                    $result[$key]['grouped'][] = $item;
1433
+                    $grouped = true;
1434
+                    break;
1435
+                }
1436
+            }
1437
+
1438
+            if (!$grouped) {
1439
+                $result[] = $item;
1440
+            }
1441
+
1442
+        }
1443
+
1444
+        return $result;
1445
+    }
1446
+
1447
+    /**
1448
+     * Put shared item into the database
1449
+     * @param string $itemType Item type
1450
+     * @param string $itemSource Item source
1451
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1452
+     * @param string $shareWith User or group the item is being shared with
1453
+     * @param string $uidOwner User that is the owner of shared item
1454
+     * @param int $permissions CRUDS permissions
1455
+     * @param boolean|array $parentFolder Parent folder target (optional)
1456
+     * @param string $token (optional)
1457
+     * @param string $itemSourceName name of the source item (optional)
1458
+     * @param \DateTime $expirationDate (optional)
1459
+     * @throws \Exception
1460
+     * @return mixed id of the new share or false
1461
+     */
1462
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1463
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1464
+
1465
+        $queriesToExecute = array();
1466
+        $suggestedItemTarget = null;
1467
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1468
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1469
+
1470
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1471
+        if(!empty($result)) {
1472
+            $parent = $result['parent'];
1473
+            $itemSource = $result['itemSource'];
1474
+            $fileSource = $result['fileSource'];
1475
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1476
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1477
+            $filePath = $result['filePath'];
1478
+        }
1479
+
1480
+        $isGroupShare = false;
1481
+        if ($shareType == self::SHARE_TYPE_GROUP) {
1482
+            $isGroupShare = true;
1483
+            if (isset($shareWith['users'])) {
1484
+                $users = $shareWith['users'];
1485
+            } else {
1486
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
1487
+                if ($group) {
1488
+                    $users = $group->searchUsers('', -1, 0);
1489
+                    $userIds = [];
1490
+                    foreach ($users as $user) {
1491
+                        $userIds[] = $user->getUID();
1492
+                    }
1493
+                    $users = $userIds;
1494
+                } else {
1495
+                    $users = [];
1496
+                }
1497
+            }
1498
+            // remove current user from list
1499
+            if (in_array(\OCP\User::getUser(), $users)) {
1500
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
1501
+            }
1502
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1503
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1504
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1505
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
1506
+
1507
+            // add group share to table and remember the id as parent
1508
+            $queriesToExecute['groupShare'] = array(
1509
+                'itemType'			=> $itemType,
1510
+                'itemSource'		=> $itemSource,
1511
+                'itemTarget'		=> $groupItemTarget,
1512
+                'shareType'			=> $shareType,
1513
+                'shareWith'			=> $shareWith['group'],
1514
+                'uidOwner'			=> $uidOwner,
1515
+                'permissions'		=> $permissions,
1516
+                'shareTime'			=> time(),
1517
+                'fileSource'		=> $fileSource,
1518
+                'fileTarget'		=> $groupFileTarget,
1519
+                'token'				=> $token,
1520
+                'parent'			=> $parent,
1521
+                'expiration'		=> $expirationDate,
1522
+            );
1523
+
1524
+        } else {
1525
+            $users = array($shareWith);
1526
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1527
+                $suggestedItemTarget);
1528
+        }
1529
+
1530
+        $run = true;
1531
+        $error = '';
1532
+        $preHookData = array(
1533
+            'itemType' => $itemType,
1534
+            'itemSource' => $itemSource,
1535
+            'shareType' => $shareType,
1536
+            'uidOwner' => $uidOwner,
1537
+            'permissions' => $permissions,
1538
+            'fileSource' => $fileSource,
1539
+            'expiration' => $expirationDate,
1540
+            'token' => $token,
1541
+            'run' => &$run,
1542
+            'error' => &$error
1543
+        );
1544
+
1545
+        $preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1546
+        $preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1547
+
1548
+        \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1549
+
1550
+        if ($run === false) {
1551
+            throw new \Exception($error);
1552
+        }
1553
+
1554
+        foreach ($users as $user) {
1555
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1556
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1557
+
1558
+            $userShareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType;
1559
+
1560
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1561
+                $fileTarget = $sourceExists['file_target'];
1562
+                $itemTarget = $sourceExists['item_target'];
1563
+
1564
+                // for group shares we don't need a additional entry if the target is the same
1565
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
1566
+                    continue;
1567
+                }
1568
+
1569
+            } elseif(!$sourceExists && !$isGroupShare)  {
1570
+
1571
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1572
+                    $uidOwner, $suggestedItemTarget, $parent);
1573
+                if (isset($fileSource)) {
1574
+                    if ($parentFolder) {
1575
+                        if ($parentFolder === true) {
1576
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1577
+                                $uidOwner, $suggestedFileTarget, $parent);
1578
+                            if ($fileTarget != $groupFileTarget) {
1579
+                                $parentFolders[$user]['folder'] = $fileTarget;
1580
+                            }
1581
+                        } else if (isset($parentFolder[$user])) {
1582
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
1583
+                            $parent = $parentFolder[$user]['id'];
1584
+                        }
1585
+                    } else {
1586
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1587
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1588
+                    }
1589
+                } else {
1590
+                    $fileTarget = null;
1591
+                }
1592
+
1593
+            } else {
1594
+
1595
+                // group share which doesn't exists until now, check if we need a unique target for this user
1596
+
1597
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1598
+                    $uidOwner, $suggestedItemTarget, $parent);
1599
+
1600
+                // do we also need a file target
1601
+                if (isset($fileSource)) {
1602
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1603
+                        $uidOwner, $suggestedFileTarget, $parent);
1604
+                } else {
1605
+                    $fileTarget = null;
1606
+                }
1607
+
1608
+                if (($itemTarget === $groupItemTarget) &&
1609
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1610
+                    continue;
1611
+                }
1612
+            }
1613
+
1614
+            $queriesToExecute[] = array(
1615
+                'itemType'			=> $itemType,
1616
+                'itemSource'		=> $itemSource,
1617
+                'itemTarget'		=> $itemTarget,
1618
+                'shareType'			=> $userShareType,
1619
+                'shareWith'			=> $user,
1620
+                'uidOwner'			=> $uidOwner,
1621
+                'permissions'		=> $permissions,
1622
+                'shareTime'			=> time(),
1623
+                'fileSource'		=> $fileSource,
1624
+                'fileTarget'		=> $fileTarget,
1625
+                'token'				=> $token,
1626
+                'parent'			=> $parent,
1627
+                'expiration'		=> $expirationDate,
1628
+            );
1629
+
1630
+        }
1631
+
1632
+        $id = false;
1633
+        if ($isGroupShare) {
1634
+            $id = self::insertShare($queriesToExecute['groupShare']);
1635
+            // Save this id, any extra rows for this group share will need to reference it
1636
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1637
+            unset($queriesToExecute['groupShare']);
1638
+        }
1639
+
1640
+        foreach ($queriesToExecute as $shareQuery) {
1641
+            $shareQuery['parent'] = $parent;
1642
+            $id = self::insertShare($shareQuery);
1643
+        }
1644
+
1645
+        $postHookData = array(
1646
+            'itemType' => $itemType,
1647
+            'itemSource' => $itemSource,
1648
+            'parent' => $parent,
1649
+            'shareType' => $shareType,
1650
+            'uidOwner' => $uidOwner,
1651
+            'permissions' => $permissions,
1652
+            'fileSource' => $fileSource,
1653
+            'id' => $parent,
1654
+            'token' => $token,
1655
+            'expirationDate' => $expirationDate,
1656
+        );
1657
+
1658
+        $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1659
+        $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1660
+        $postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1661
+
1662
+        \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1663
+
1664
+
1665
+        return $id ? $id : false;
1666
+    }
1667
+
1668
+    /**
1669
+     * @param string $itemType
1670
+     * @param string $itemSource
1671
+     * @param int $shareType
1672
+     * @param string $shareWith
1673
+     * @param string $uidOwner
1674
+     * @param int $permissions
1675
+     * @param string|null $itemSourceName
1676
+     * @param null|\DateTime $expirationDate
1677
+     */
1678
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1679
+        $backend = self::getBackend($itemType);
1680
+
1681
+        $l = \OC::$server->getL10N('lib');
1682
+        $result = array();
1683
+
1684
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1685
+
1686
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1687
+        if ($checkReshare) {
1688
+            // Check if attempting to share back to owner
1689
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1690
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
1691
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1692
+
1693
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
1694
+                throw new \Exception($message_t);
1695
+            }
1696
+        }
1697
+
1698
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1699
+            // Check if share permissions is granted
1700
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1701
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1702
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1703
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1704
+
1705
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
1706
+                    throw new \Exception($message_t);
1707
+                } else {
1708
+                    // TODO Don't check if inside folder
1709
+                    $result['parent'] = $checkReshare['id'];
1710
+
1711
+                    $result['expirationDate'] = $expirationDate;
1712
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1713
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1714
+                        $result['expirationDate'] = $checkReshare['expiration'];
1715
+                    }
1716
+
1717
+                    // only suggest the same name as new target if it is a reshare of the
1718
+                    // same file/folder and not the reshare of a child
1719
+                    if ($checkReshare[$column] === $itemSource) {
1720
+                        $result['filePath'] = $checkReshare['file_target'];
1721
+                        $result['itemSource'] = $checkReshare['item_source'];
1722
+                        $result['fileSource'] = $checkReshare['file_source'];
1723
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1724
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1725
+                    } else {
1726
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1727
+                        $result['suggestedItemTarget'] = null;
1728
+                        $result['suggestedFileTarget'] = null;
1729
+                        $result['itemSource'] = $itemSource;
1730
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1731
+                    }
1732
+                }
1733
+            } else {
1734
+                $message = 'Sharing %s failed, because resharing is not allowed';
1735
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1736
+
1737
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
1738
+                throw new \Exception($message_t);
1739
+            }
1740
+        } else {
1741
+            $result['parent'] = null;
1742
+            $result['suggestedItemTarget'] = null;
1743
+            $result['suggestedFileTarget'] = null;
1744
+            $result['itemSource'] = $itemSource;
1745
+            $result['expirationDate'] = $expirationDate;
1746
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1747
+                $message = 'Sharing %s failed, because the sharing backend for '
1748
+                    .'%s could not find its source';
1749
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1750
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
1751
+                throw new \Exception($message_t);
1752
+            }
1753
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1754
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1755
+                if ($itemType == 'file' || $itemType == 'folder') {
1756
+                    $result['fileSource'] = $itemSource;
1757
+                } else {
1758
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1759
+                    $result['fileSource'] = $meta['fileid'];
1760
+                }
1761
+                if ($result['fileSource'] == -1) {
1762
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1763
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1764
+
1765
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1766
+                    throw new \Exception($message_t);
1767
+                }
1768
+            } else {
1769
+                $result['filePath'] = null;
1770
+                $result['fileSource'] = null;
1771
+            }
1772
+        }
1773
+
1774
+        return $result;
1775
+    }
1776
+
1777
+    /**
1778
+     *
1779
+     * @param array $shareData
1780
+     * @return mixed false in case of a failure or the id of the new share
1781
+     */
1782
+    private static function insertShare(array $shareData) {
1783
+
1784
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1785
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1786
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1787
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1788
+        $query->bindValue(1, $shareData['itemType']);
1789
+        $query->bindValue(2, $shareData['itemSource']);
1790
+        $query->bindValue(3, $shareData['itemTarget']);
1791
+        $query->bindValue(4, $shareData['shareType']);
1792
+        $query->bindValue(5, $shareData['shareWith']);
1793
+        $query->bindValue(6, $shareData['uidOwner']);
1794
+        $query->bindValue(7, $shareData['permissions']);
1795
+        $query->bindValue(8, $shareData['shareTime']);
1796
+        $query->bindValue(9, $shareData['fileSource']);
1797
+        $query->bindValue(10, $shareData['fileTarget']);
1798
+        $query->bindValue(11, $shareData['token']);
1799
+        $query->bindValue(12, $shareData['parent']);
1800
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1801
+        $result = $query->execute();
1802
+
1803
+        $id = false;
1804
+        if ($result) {
1805
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1806
+        }
1807
+
1808
+        return $id;
1809
+
1810
+    }
1811
+
1812
+    /**
1813
+     * In case a password protected link is not yet authenticated this function will return false
1814
+     *
1815
+     * @param array $linkItem
1816
+     * @return boolean
1817
+     */
1818
+    public static function checkPasswordProtectedShare(array $linkItem) {
1819
+        if (!isset($linkItem['share_with'])) {
1820
+            return true;
1821
+        }
1822
+        if (!isset($linkItem['share_type'])) {
1823
+            return true;
1824
+        }
1825
+        if (!isset($linkItem['id'])) {
1826
+            return true;
1827
+        }
1828
+
1829
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1830
+            return true;
1831
+        }
1832
+
1833
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
1834
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1835
+            return true;
1836
+        }
1837
+
1838
+        return false;
1839
+    }
1840
+
1841
+    /**
1842
+     * construct select statement
1843
+     * @param int $format
1844
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1845
+     * @param string $uidOwner
1846
+     * @return string select statement
1847
+     */
1848
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1849
+        $select = '*';
1850
+        if ($format == self::FORMAT_STATUSES) {
1851
+            if ($fileDependent) {
1852
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1853
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1854
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1855
+                    . '`uid_initiator`';
1856
+            } else {
1857
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1858
+            }
1859
+        } else {
1860
+            if (isset($uidOwner)) {
1861
+                if ($fileDependent) {
1862
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1863
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1864
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1865
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1866
+                } else {
1867
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1868
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1869
+                }
1870
+            } else {
1871
+                if ($fileDependent) {
1872
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1873
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1874
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1875
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1876
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1877
+                    } else {
1878
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1879
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1880
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1881
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1882
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1883
+                    }
1884
+                }
1885
+            }
1886
+        }
1887
+        return $select;
1888
+    }
1889
+
1890
+
1891
+    /**
1892
+     * transform db results
1893
+     * @param array $row result
1894
+     */
1895
+    private static function transformDBResults(&$row) {
1896
+        if (isset($row['id'])) {
1897
+            $row['id'] = (int) $row['id'];
1898
+        }
1899
+        if (isset($row['share_type'])) {
1900
+            $row['share_type'] = (int) $row['share_type'];
1901
+        }
1902
+        if (isset($row['parent'])) {
1903
+            $row['parent'] = (int) $row['parent'];
1904
+        }
1905
+        if (isset($row['file_parent'])) {
1906
+            $row['file_parent'] = (int) $row['file_parent'];
1907
+        }
1908
+        if (isset($row['file_source'])) {
1909
+            $row['file_source'] = (int) $row['file_source'];
1910
+        }
1911
+        if (isset($row['permissions'])) {
1912
+            $row['permissions'] = (int) $row['permissions'];
1913
+        }
1914
+        if (isset($row['storage'])) {
1915
+            $row['storage'] = (int) $row['storage'];
1916
+        }
1917
+        if (isset($row['stime'])) {
1918
+            $row['stime'] = (int) $row['stime'];
1919
+        }
1920
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1921
+            // discard expiration date for non-link shares, which might have been
1922
+            // set by ancient bugs
1923
+            $row['expiration'] = null;
1924
+        }
1925
+    }
1926
+
1927
+    /**
1928
+     * format result
1929
+     * @param array $items result
1930
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1931
+     * @param \OCP\Share_Backend $backend sharing backend
1932
+     * @param int $format
1933
+     * @param array $parameters additional format parameters
1934
+     * @return array format result
1935
+     */
1936
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1937
+        if ($format === self::FORMAT_NONE) {
1938
+            return $items;
1939
+        } else if ($format === self::FORMAT_STATUSES) {
1940
+            $statuses = array();
1941
+            foreach ($items as $item) {
1942
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1943
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1944
+                        continue;
1945
+                    }
1946
+                    $statuses[$item[$column]]['link'] = true;
1947
+                } else if (!isset($statuses[$item[$column]])) {
1948
+                    $statuses[$item[$column]]['link'] = false;
1949
+                }
1950
+                if (!empty($item['file_target'])) {
1951
+                    $statuses[$item[$column]]['path'] = $item['path'];
1952
+                }
1953
+            }
1954
+            return $statuses;
1955
+        } else {
1956
+            return $backend->formatItems($items, $format, $parameters);
1957
+        }
1958
+    }
1959
+
1960
+    /**
1961
+     * remove protocol from URL
1962
+     *
1963
+     * @param string $url
1964
+     * @return string
1965
+     */
1966
+    public static function removeProtocolFromUrl($url) {
1967
+        if (strpos($url, 'https://') === 0) {
1968
+            return substr($url, strlen('https://'));
1969
+        } else if (strpos($url, 'http://') === 0) {
1970
+            return substr($url, strlen('http://'));
1971
+        }
1972
+
1973
+        return $url;
1974
+    }
1975
+
1976
+    /**
1977
+     * try http post first with https and then with http as a fallback
1978
+     *
1979
+     * @param string $remoteDomain
1980
+     * @param string $urlSuffix
1981
+     * @param array $fields post parameters
1982
+     * @return array
1983
+     */
1984
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1985
+        $protocol = 'https://';
1986
+        $result = [
1987
+            'success' => false,
1988
+            'result' => '',
1989
+        ];
1990
+        $try = 0;
1991
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1992
+        while ($result['success'] === false && $try < 2) {
1993
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1994
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1995
+            $client = \OC::$server->getHTTPClientService()->newClient();
1996
+
1997
+            try {
1998
+                $response = $client->post(
1999
+                    $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
2000
+                    [
2001
+                        'body' => $fields,
2002
+                        'connect_timeout' => 10,
2003
+                    ]
2004
+                );
2005
+
2006
+                $result = ['success' => true, 'result' => $response->getBody()];
2007
+            } catch (\Exception $e) {
2008
+                $result = ['success' => false, 'result' => $e->getMessage()];
2009
+            }
2010
+
2011
+            $try++;
2012
+            $protocol = 'http://';
2013
+        }
2014
+
2015
+        return $result;
2016
+    }
2017
+
2018
+    /**
2019
+     * send server-to-server share to remote server
2020
+     *
2021
+     * @param string $token
2022
+     * @param string $shareWith
2023
+     * @param string $name
2024
+     * @param int $remote_id
2025
+     * @param string $owner
2026
+     * @return bool
2027
+     */
2028
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2029
+
2030
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2031
+
2032
+        if ($user && $remote) {
2033
+            $url = $remote;
2034
+
2035
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2036
+
2037
+            $fields = array(
2038
+                'shareWith' => $user,
2039
+                'token' => $token,
2040
+                'name' => $name,
2041
+                'remoteId' => $remote_id,
2042
+                'owner' => $owner,
2043
+                'remote' => $local,
2044
+            );
2045
+
2046
+            $url = self::removeProtocolFromUrl($url);
2047
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2048
+            $status = json_decode($result['result'], true);
2049
+
2050
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2051
+                \OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]);
2052
+                return true;
2053
+            }
2054
+
2055
+        }
2056
+
2057
+        return false;
2058
+    }
2059
+
2060
+    /**
2061
+     * send server-to-server unshare to remote server
2062
+     *
2063
+     * @param string $remote url
2064
+     * @param int $id share id
2065
+     * @param string $token
2066
+     * @return bool
2067
+     */
2068
+    private static function sendRemoteUnshare($remote, $id, $token) {
2069
+        $url = rtrim($remote, '/');
2070
+        $fields = array('token' => $token, 'format' => 'json');
2071
+        $url = self::removeProtocolFromUrl($url);
2072
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2073
+        $status = json_decode($result['result'], true);
2074
+
2075
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2076
+    }
2077
+
2078
+    /**
2079
+     * check if user can only share with group members
2080
+     * @return bool
2081
+     */
2082
+    public static function shareWithGroupMembersOnly() {
2083
+        $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2084
+        return $value === 'yes';
2085
+    }
2086
+
2087
+    /**
2088
+     * @return bool
2089
+     */
2090
+    public static function isDefaultExpireDateEnabled() {
2091
+        $defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2092
+        return $defaultExpireDateEnabled === 'yes';
2093
+    }
2094
+
2095
+    /**
2096
+     * @return int
2097
+     */
2098
+    public static function getExpireInterval() {
2099
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2100
+    }
2101
+
2102
+    /**
2103
+     * Checks whether the given path is reachable for the given owner
2104
+     *
2105
+     * @param string $path path relative to files
2106
+     * @param string $ownerStorageId storage id of the owner
2107
+     *
2108
+     * @return boolean true if file is reachable, false otherwise
2109
+     */
2110
+    private static function isFileReachable($path, $ownerStorageId) {
2111
+        // if outside the home storage, file is always considered reachable
2112
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2113
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2114
+        )) {
2115
+            return true;
2116
+        }
2117
+
2118
+        // if inside the home storage, the file has to be under "/files/"
2119
+        $path = ltrim($path, '/');
2120
+        if (substr($path, 0, 6) === 'files/') {
2121
+            return true;
2122
+        }
2123
+
2124
+        return false;
2125
+    }
2126
+
2127
+    /**
2128
+     * @param IConfig $config
2129
+     * @return bool
2130
+     */
2131
+    public static function enforcePassword(IConfig $config) {
2132
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2133
+        return $enforcePassword === 'yes';
2134
+    }
2135
+
2136
+    /**
2137
+     * @param string $password
2138
+     * @throws \Exception
2139
+     */
2140
+    private static function verifyPassword($password) {
2141
+
2142
+        $accepted = true;
2143
+        $message = '';
2144
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2145
+            'password' => $password,
2146
+            'accepted' => &$accepted,
2147
+            'message' => &$message
2148
+        ]);
2149
+
2150
+        if (!$accepted) {
2151
+            throw new \Exception($message);
2152
+        }
2153
+    }
2154 2154
 }
Please login to merge, or discard this patch.