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