Completed
Pull Request — master (#4042)
by Lukas
56:50 queued 45:38
created
lib/private/Share/Share.php 1 patch
Indentation   +2830 added lines, -2830 removed lines patch added patch discarded remove patch
@@ -61,2867 +61,2867 @@
 block discarded – undo
61 61
  */
62 62
 class Share extends Constants {
63 63
 
64
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
65
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
66
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
67
-	 *
68
-	 * Check if permission is granted with And (&) e.g. Check if delete is
69
-	 * granted: if ($permissions & PERMISSION_DELETE)
70
-	 *
71
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
72
-	 * permission: $permissions &= ~PERMISSION_UPDATE
73
-	 *
74
-	 * Apps are required to handle permissions on their own, this class only
75
-	 * stores and manages the permissions of shares
76
-	 * @see lib/public/constants.php
77
-	 */
78
-
79
-	/**
80
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
81
-	 * @param string $itemType Item type
82
-	 * @param string $class Backend class
83
-	 * @param string $collectionOf (optional) Depends on item type
84
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
85
-	 * @return boolean true if backend is registered or false if error
86
-	 */
87
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
88
-		if (self::isEnabled()) {
89
-			if (!isset(self::$backendTypes[$itemType])) {
90
-				self::$backendTypes[$itemType] = array(
91
-					'class' => $class,
92
-					'collectionOf' => $collectionOf,
93
-					'supportedFileExtensions' => $supportedFileExtensions
94
-				);
95
-				if(count(self::$backendTypes) === 1) {
96
-					Util::addScript('core', 'merged-share-backend');
97
-					\OC_Util::addStyle('core', 'share');
98
-				}
99
-				return true;
100
-			}
101
-			\OCP\Util::writeLog('OCP\Share',
102
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
103
-				.' is already registered for '.$itemType,
104
-				\OCP\Util::WARN);
105
-		}
106
-		return false;
107
-	}
108
-
109
-	/**
110
-	 * Check if the Share API is enabled
111
-	 * @return boolean true if enabled or false
112
-	 *
113
-	 * The Share API is enabled by default if not configured
114
-	 */
115
-	public static function isEnabled() {
116
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
117
-			return true;
118
-		}
119
-		return false;
120
-	}
121
-
122
-	/**
123
-	 * Find which users can access a shared item
124
-	 * @param string $path to the file
125
-	 * @param string $ownerUser owner of the file
126
-	 * @param IUserManager $userManager
127
-	 * @param ILogger $logger
128
-	 * @param boolean $includeOwner include owner to the list of users with access to the file
129
-	 * @param boolean $returnUserPaths Return an array with the user => path map
130
-	 * @param boolean $recursive take all parent folders into account (default true)
131
-	 * @return array
132
-	 * @note $path needs to be relative to user data dir, e.g. 'file.txt'
133
-	 *       not '/admin/data/file.txt'
134
-	 * @throws \OC\User\NoUserException
135
-	 */
136
-	public static function getUsersSharingFile($path,
137
-											   $ownerUser,
138
-											   IUserManager $userManager,
139
-											   ILogger $logger,
140
-											   $includeOwner = false,
141
-											   $returnUserPaths = false,
142
-											   $recursive = true) {
143
-		$userObject = $userManager->get($ownerUser);
144
-
145
-		if (is_null($userObject)) {
146
-			$logger->error(
147
-				sprintf(
148
-					'Backends provided no user object for %s',
149
-					$ownerUser
150
-				),
151
-				[
152
-					'app' => 'files',
153
-				]
154
-			);
155
-			throw new \OC\User\NoUserException('Backends provided no user object');
156
-		}
157
-
158
-		$ownerUser = $userObject->getUID();
159
-
160
-		Filesystem::initMountPoints($ownerUser);
161
-		$shares = $sharePaths = $fileTargets = array();
162
-		$publicShare = false;
163
-		$remoteShare = false;
164
-		$source = -1;
165
-		$cache = $mountPath = false;
166
-
167
-		$view = new \OC\Files\View('/' . $ownerUser . '/files');
168
-		$meta = $view->getFileInfo($path);
169
-		if ($meta) {
170
-			$path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
171
-		} else {
172
-			// if the file doesn't exists yet we start with the parent folder
173
-			$meta = $view->getFileInfo(dirname($path));
174
-		}
175
-
176
-		if($meta !== false) {
177
-			$source = $meta['fileid'];
178
-			$cache = new \OC\Files\Cache\Cache($meta['storage']);
179
-
180
-			$mountPath = $meta->getMountPoint()->getMountPoint();
181
-			if ($mountPath !== false) {
182
-				$mountPath = substr($mountPath, strlen('/' . $ownerUser . '/files'));
183
-			}
184
-		}
185
-
186
-		$paths = [];
187
-		while ($source !== -1) {
188
-			// Fetch all shares with another user
189
-			if (!$returnUserPaths) {
190
-				$query = \OC_DB::prepare(
191
-					'SELECT `share_with`, `file_source`, `file_target`
64
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
65
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
66
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
67
+     *
68
+     * Check if permission is granted with And (&) e.g. Check if delete is
69
+     * granted: if ($permissions & PERMISSION_DELETE)
70
+     *
71
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
72
+     * permission: $permissions &= ~PERMISSION_UPDATE
73
+     *
74
+     * Apps are required to handle permissions on their own, this class only
75
+     * stores and manages the permissions of shares
76
+     * @see lib/public/constants.php
77
+     */
78
+
79
+    /**
80
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
81
+     * @param string $itemType Item type
82
+     * @param string $class Backend class
83
+     * @param string $collectionOf (optional) Depends on item type
84
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
85
+     * @return boolean true if backend is registered or false if error
86
+     */
87
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
88
+        if (self::isEnabled()) {
89
+            if (!isset(self::$backendTypes[$itemType])) {
90
+                self::$backendTypes[$itemType] = array(
91
+                    'class' => $class,
92
+                    'collectionOf' => $collectionOf,
93
+                    'supportedFileExtensions' => $supportedFileExtensions
94
+                );
95
+                if(count(self::$backendTypes) === 1) {
96
+                    Util::addScript('core', 'merged-share-backend');
97
+                    \OC_Util::addStyle('core', 'share');
98
+                }
99
+                return true;
100
+            }
101
+            \OCP\Util::writeLog('OCP\Share',
102
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
103
+                .' is already registered for '.$itemType,
104
+                \OCP\Util::WARN);
105
+        }
106
+        return false;
107
+    }
108
+
109
+    /**
110
+     * Check if the Share API is enabled
111
+     * @return boolean true if enabled or false
112
+     *
113
+     * The Share API is enabled by default if not configured
114
+     */
115
+    public static function isEnabled() {
116
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
117
+            return true;
118
+        }
119
+        return false;
120
+    }
121
+
122
+    /**
123
+     * Find which users can access a shared item
124
+     * @param string $path to the file
125
+     * @param string $ownerUser owner of the file
126
+     * @param IUserManager $userManager
127
+     * @param ILogger $logger
128
+     * @param boolean $includeOwner include owner to the list of users with access to the file
129
+     * @param boolean $returnUserPaths Return an array with the user => path map
130
+     * @param boolean $recursive take all parent folders into account (default true)
131
+     * @return array
132
+     * @note $path needs to be relative to user data dir, e.g. 'file.txt'
133
+     *       not '/admin/data/file.txt'
134
+     * @throws \OC\User\NoUserException
135
+     */
136
+    public static function getUsersSharingFile($path,
137
+                                                $ownerUser,
138
+                                                IUserManager $userManager,
139
+                                                ILogger $logger,
140
+                                                $includeOwner = false,
141
+                                                $returnUserPaths = false,
142
+                                                $recursive = true) {
143
+        $userObject = $userManager->get($ownerUser);
144
+
145
+        if (is_null($userObject)) {
146
+            $logger->error(
147
+                sprintf(
148
+                    'Backends provided no user object for %s',
149
+                    $ownerUser
150
+                ),
151
+                [
152
+                    'app' => 'files',
153
+                ]
154
+            );
155
+            throw new \OC\User\NoUserException('Backends provided no user object');
156
+        }
157
+
158
+        $ownerUser = $userObject->getUID();
159
+
160
+        Filesystem::initMountPoints($ownerUser);
161
+        $shares = $sharePaths = $fileTargets = array();
162
+        $publicShare = false;
163
+        $remoteShare = false;
164
+        $source = -1;
165
+        $cache = $mountPath = false;
166
+
167
+        $view = new \OC\Files\View('/' . $ownerUser . '/files');
168
+        $meta = $view->getFileInfo($path);
169
+        if ($meta) {
170
+            $path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
171
+        } else {
172
+            // if the file doesn't exists yet we start with the parent folder
173
+            $meta = $view->getFileInfo(dirname($path));
174
+        }
175
+
176
+        if($meta !== false) {
177
+            $source = $meta['fileid'];
178
+            $cache = new \OC\Files\Cache\Cache($meta['storage']);
179
+
180
+            $mountPath = $meta->getMountPoint()->getMountPoint();
181
+            if ($mountPath !== false) {
182
+                $mountPath = substr($mountPath, strlen('/' . $ownerUser . '/files'));
183
+            }
184
+        }
185
+
186
+        $paths = [];
187
+        while ($source !== -1) {
188
+            // Fetch all shares with another user
189
+            if (!$returnUserPaths) {
190
+                $query = \OC_DB::prepare(
191
+                    'SELECT `share_with`, `file_source`, `file_target`
192 192
 					FROM
193 193
 					`*PREFIX*share`
194 194
 					WHERE
195 195
 					`item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
196
-				);
197
-				$result = $query->execute(array($source, self::SHARE_TYPE_USER));
198
-			} else {
199
-				$query = \OC_DB::prepare(
200
-					'SELECT `share_with`, `file_source`, `file_target`
196
+                );
197
+                $result = $query->execute(array($source, self::SHARE_TYPE_USER));
198
+            } else {
199
+                $query = \OC_DB::prepare(
200
+                    'SELECT `share_with`, `file_source`, `file_target`
201 201
 				FROM
202 202
 				`*PREFIX*share`
203 203
 				WHERE
204 204
 				`item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')'
205
-				);
206
-				$result = $query->execute(array($source, self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique));
207
-			}
208
-
209
-			if (\OCP\DB::isError($result)) {
210
-				\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
211
-			} else {
212
-				while ($row = $result->fetchRow()) {
213
-					$shares[] = $row['share_with'];
214
-					if ($returnUserPaths) {
215
-						$fileTargets[(int) $row['file_source']][$row['share_with']] = $row;
216
-					}
217
-				}
218
-			}
219
-
220
-			// We also need to take group shares into account
221
-			$query = \OC_DB::prepare(
222
-				'SELECT `share_with`, `file_source`, `file_target`
205
+                );
206
+                $result = $query->execute(array($source, self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique));
207
+            }
208
+
209
+            if (\OCP\DB::isError($result)) {
210
+                \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
211
+            } else {
212
+                while ($row = $result->fetchRow()) {
213
+                    $shares[] = $row['share_with'];
214
+                    if ($returnUserPaths) {
215
+                        $fileTargets[(int) $row['file_source']][$row['share_with']] = $row;
216
+                    }
217
+                }
218
+            }
219
+
220
+            // We also need to take group shares into account
221
+            $query = \OC_DB::prepare(
222
+                'SELECT `share_with`, `file_source`, `file_target`
223 223
 				FROM
224 224
 				`*PREFIX*share`
225 225
 				WHERE
226 226
 				`item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
227
-			);
228
-
229
-			$result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
230
-
231
-			if (\OCP\DB::isError($result)) {
232
-				\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
233
-			} else {
234
-				$groupManager = \OC::$server->getGroupManager();
235
-				while ($row = $result->fetchRow()) {
236
-
237
-					$usersInGroup = [];
238
-					$group = $groupManager->get($row['share_with']);
239
-					if ($group) {
240
-						$users = $group->searchUsers('', -1, 0);
241
-						$userIds = array();
242
-						foreach ($users as $user) {
243
-							$userIds[] = $user->getUID();
244
-						}
245
-						$usersInGroup = $userIds;
246
-					}
247
-					$shares = array_merge($shares, $usersInGroup);
248
-					if ($returnUserPaths) {
249
-						foreach ($usersInGroup as $user) {
250
-							if (!isset($fileTargets[(int) $row['file_source']][$user])) {
251
-								// When the user already has an entry for this file source
252
-								// the file is either shared directly with him as well, or
253
-								// he has an exception entry (because of naming conflict).
254
-								$fileTargets[(int) $row['file_source']][$user] = $row;
255
-							}
256
-						}
257
-					}
258
-				}
259
-			}
260
-
261
-			//check for public link shares
262
-			if (!$publicShare) {
263
-				$query = \OC_DB::prepare('
227
+            );
228
+
229
+            $result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
230
+
231
+            if (\OCP\DB::isError($result)) {
232
+                \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
233
+            } else {
234
+                $groupManager = \OC::$server->getGroupManager();
235
+                while ($row = $result->fetchRow()) {
236
+
237
+                    $usersInGroup = [];
238
+                    $group = $groupManager->get($row['share_with']);
239
+                    if ($group) {
240
+                        $users = $group->searchUsers('', -1, 0);
241
+                        $userIds = array();
242
+                        foreach ($users as $user) {
243
+                            $userIds[] = $user->getUID();
244
+                        }
245
+                        $usersInGroup = $userIds;
246
+                    }
247
+                    $shares = array_merge($shares, $usersInGroup);
248
+                    if ($returnUserPaths) {
249
+                        foreach ($usersInGroup as $user) {
250
+                            if (!isset($fileTargets[(int) $row['file_source']][$user])) {
251
+                                // When the user already has an entry for this file source
252
+                                // the file is either shared directly with him as well, or
253
+                                // he has an exception entry (because of naming conflict).
254
+                                $fileTargets[(int) $row['file_source']][$user] = $row;
255
+                            }
256
+                        }
257
+                    }
258
+                }
259
+            }
260
+
261
+            //check for public link shares
262
+            if (!$publicShare) {
263
+                $query = \OC_DB::prepare('
264 264
 					SELECT `share_with`
265 265
 					FROM `*PREFIX*share`
266 266
 					WHERE `item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')', 1
267
-				);
268
-
269
-				$result = $query->execute(array($source, self::SHARE_TYPE_LINK, self::SHARE_TYPE_EMAIL));
270
-
271
-				if (\OCP\DB::isError($result)) {
272
-					\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
273
-				} else {
274
-					if ($result->fetchRow()) {
275
-						$publicShare = true;
276
-					}
277
-				}
278
-			}
279
-
280
-			//check for remote share
281
-			if (!$remoteShare) {
282
-				$query = \OC_DB::prepare('
267
+                );
268
+
269
+                $result = $query->execute(array($source, self::SHARE_TYPE_LINK, self::SHARE_TYPE_EMAIL));
270
+
271
+                if (\OCP\DB::isError($result)) {
272
+                    \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
273
+                } else {
274
+                    if ($result->fetchRow()) {
275
+                        $publicShare = true;
276
+                    }
277
+                }
278
+            }
279
+
280
+            //check for remote share
281
+            if (!$remoteShare) {
282
+                $query = \OC_DB::prepare('
283 283
 					SELECT `share_with`
284 284
 					FROM `*PREFIX*share`
285 285
 					WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1
286
-				);
287
-
288
-				$result = $query->execute(array($source, self::SHARE_TYPE_REMOTE));
289
-
290
-				if (\OCP\DB::isError($result)) {
291
-					\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
292
-				} else {
293
-					if ($result->fetchRow()) {
294
-						$remoteShare = true;
295
-					}
296
-				}
297
-			}
298
-
299
-			// let's get the parent for the next round
300
-			$meta = $cache->get((int)$source);
301
-			if ($recursive === true && $meta !== false) {
302
-				$paths[$source] = $meta['path'];
303
-				$source = (int)$meta['parent'];
304
-			} else {
305
-				$source = -1;
306
-			}
307
-		}
308
-
309
-		// Include owner in list of users, if requested
310
-		if ($includeOwner) {
311
-			$shares[] = $ownerUser;
312
-		}
313
-
314
-		if ($returnUserPaths) {
315
-			$fileTargetIDs = array_keys($fileTargets);
316
-			$fileTargetIDs = array_unique($fileTargetIDs);
317
-
318
-			if (!empty($fileTargetIDs)) {
319
-				$query = \OC_DB::prepare(
320
-					'SELECT `fileid`, `path`
286
+                );
287
+
288
+                $result = $query->execute(array($source, self::SHARE_TYPE_REMOTE));
289
+
290
+                if (\OCP\DB::isError($result)) {
291
+                    \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
292
+                } else {
293
+                    if ($result->fetchRow()) {
294
+                        $remoteShare = true;
295
+                    }
296
+                }
297
+            }
298
+
299
+            // let's get the parent for the next round
300
+            $meta = $cache->get((int)$source);
301
+            if ($recursive === true && $meta !== false) {
302
+                $paths[$source] = $meta['path'];
303
+                $source = (int)$meta['parent'];
304
+            } else {
305
+                $source = -1;
306
+            }
307
+        }
308
+
309
+        // Include owner in list of users, if requested
310
+        if ($includeOwner) {
311
+            $shares[] = $ownerUser;
312
+        }
313
+
314
+        if ($returnUserPaths) {
315
+            $fileTargetIDs = array_keys($fileTargets);
316
+            $fileTargetIDs = array_unique($fileTargetIDs);
317
+
318
+            if (!empty($fileTargetIDs)) {
319
+                $query = \OC_DB::prepare(
320
+                    'SELECT `fileid`, `path`
321 321
 					FROM `*PREFIX*filecache`
322 322
 					WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'
323
-				);
324
-				$result = $query->execute();
325
-
326
-				if (\OCP\DB::isError($result)) {
327
-					\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
328
-				} else {
329
-					while ($row = $result->fetchRow()) {
330
-						foreach ($fileTargets[$row['fileid']] as $uid => $shareData) {
331
-							if ($mountPath !== false) {
332
-								$sharedPath = $shareData['file_target'];
333
-								$sharedPath .= substr($path, strlen($mountPath) + strlen($paths[$row['fileid']]));
334
-								$sharePaths[$uid] = $sharedPath;
335
-							} else {
336
-								$sharedPath = $shareData['file_target'];
337
-								$sharedPath .= substr($path, strlen($row['path']) -5);
338
-								$sharePaths[$uid] = $sharedPath;
339
-							}
340
-						}
341
-					}
342
-				}
343
-			}
344
-
345
-			if ($includeOwner) {
346
-				$sharePaths[$ownerUser] = $path;
347
-			} else {
348
-				unset($sharePaths[$ownerUser]);
349
-			}
350
-
351
-			return $sharePaths;
352
-		}
353
-
354
-		return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare);
355
-	}
356
-
357
-	/**
358
-	 * Get the items of item type shared with the current user
359
-	 * @param string $itemType
360
-	 * @param int $format (optional) Format type must be defined by the backend
361
-	 * @param mixed $parameters (optional)
362
-	 * @param int $limit Number of items to return (optional) Returns all by default
363
-	 * @param boolean $includeCollections (optional)
364
-	 * @return mixed Return depends on format
365
-	 */
366
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
367
-											  $parameters = null, $limit = -1, $includeCollections = false) {
368
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
369
-			$parameters, $limit, $includeCollections);
370
-	}
371
-
372
-	/**
373
-	 * Get the items of item type shared with a user
374
-	 * @param string $itemType
375
-	 * @param string $user id for which user we want the shares
376
-	 * @param int $format (optional) Format type must be defined by the backend
377
-	 * @param mixed $parameters (optional)
378
-	 * @param int $limit Number of items to return (optional) Returns all by default
379
-	 * @param boolean $includeCollections (optional)
380
-	 * @return mixed Return depends on format
381
-	 */
382
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
383
-												  $parameters = null, $limit = -1, $includeCollections = false) {
384
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
385
-			$parameters, $limit, $includeCollections);
386
-	}
387
-
388
-	/**
389
-	 * Get the item of item type shared with the current user
390
-	 * @param string $itemType
391
-	 * @param string $itemTarget
392
-	 * @param int $format (optional) Format type must be defined by the backend
393
-	 * @param mixed $parameters (optional)
394
-	 * @param boolean $includeCollections (optional)
395
-	 * @return mixed Return depends on format
396
-	 */
397
-	public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
398
-											 $parameters = null, $includeCollections = false) {
399
-		return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
400
-			$parameters, 1, $includeCollections);
401
-	}
402
-
403
-	/**
404
-	 * Get the item of item type shared with a given user by source
405
-	 * @param string $itemType
406
-	 * @param string $itemSource
407
-	 * @param string $user User to whom the item was shared
408
-	 * @param string $owner Owner of the share
409
-	 * @param int $shareType only look for a specific share type
410
-	 * @return array Return list of items with file_target, permissions and expiration
411
-	 */
412
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
413
-		$shares = array();
414
-		$fileDependent = false;
415
-
416
-		$where = 'WHERE';
417
-		$fileDependentWhere = '';
418
-		if ($itemType === 'file' || $itemType === 'folder') {
419
-			$fileDependent = true;
420
-			$column = 'file_source';
421
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
422
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
423
-		} else {
424
-			$column = 'item_source';
425
-		}
426
-
427
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
428
-
429
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
430
-		$arguments = array($itemSource, $itemType);
431
-		// for link shares $user === null
432
-		if ($user !== null) {
433
-			$where .= ' AND `share_with` = ? ';
434
-			$arguments[] = $user;
435
-		}
436
-
437
-		if ($shareType !== null) {
438
-			$where .= ' AND `share_type` = ? ';
439
-			$arguments[] = $shareType;
440
-		}
441
-
442
-		if ($owner !== null) {
443
-			$where .= ' AND `uid_owner` = ? ';
444
-			$arguments[] = $owner;
445
-		}
446
-
447
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
448
-
449
-		$result = \OC_DB::executeAudited($query, $arguments);
450
-
451
-		while ($row = $result->fetchRow()) {
452
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
453
-				continue;
454
-			}
455
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
456
-				// if it is a mount point we need to get the path from the mount manager
457
-				$mountManager = \OC\Files\Filesystem::getMountManager();
458
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
459
-				if (!empty($mountPoint)) {
460
-					$path = $mountPoint[0]->getMountPoint();
461
-					$path = trim($path, '/');
462
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
463
-					$row['path'] = $path;
464
-				} else {
465
-					\OC::$server->getLogger()->warning(
466
-						'Could not resolve mount point for ' . $row['storage_id'],
467
-						['app' => 'OCP\Share']
468
-					);
469
-				}
470
-			}
471
-			$shares[] = $row;
472
-		}
473
-
474
-		//if didn't found a result than let's look for a group share.
475
-		if(empty($shares) && $user !== null) {
476
-			$userObject = \OC::$server->getUserManager()->get($user);
477
-			$groups = [];
478
-			if ($userObject) {
479
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
480
-			}
481
-
482
-			if (!empty($groups)) {
483
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
484
-				$arguments = array($itemSource, $itemType, $groups);
485
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
486
-
487
-				if ($owner !== null) {
488
-					$where .= ' AND `uid_owner` = ?';
489
-					$arguments[] = $owner;
490
-					$types[] = null;
491
-				}
492
-
493
-				// TODO: inject connection, hopefully one day in the future when this
494
-				// class isn't static anymore...
495
-				$conn = \OC::$server->getDatabaseConnection();
496
-				$result = $conn->executeQuery(
497
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
498
-					$arguments,
499
-					$types
500
-				);
501
-
502
-				while ($row = $result->fetch()) {
503
-					$shares[] = $row;
504
-				}
505
-			}
506
-		}
507
-
508
-		return $shares;
509
-
510
-	}
511
-
512
-	/**
513
-	 * Get the item of item type shared with the current user by source
514
-	 * @param string $itemType
515
-	 * @param string $itemSource
516
-	 * @param int $format (optional) Format type must be defined by the backend
517
-	 * @param mixed $parameters
518
-	 * @param boolean $includeCollections
519
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
520
-	 * @return array
521
-	 */
522
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
523
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
524
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
525
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
526
-			$parameters, 1, $includeCollections, true);
527
-	}
528
-
529
-	/**
530
-	 * Get the item of item type shared by a link
531
-	 * @param string $itemType
532
-	 * @param string $itemSource
533
-	 * @param string $uidOwner Owner of link
534
-	 * @return array
535
-	 */
536
-	public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
537
-		return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
538
-			null, 1);
539
-	}
540
-
541
-	/**
542
-	 * Based on the given token the share information will be returned - password protected shares will be verified
543
-	 * @param string $token
544
-	 * @param bool $checkPasswordProtection
545
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
546
-	 */
547
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
548
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
549
-		$result = $query->execute(array($token));
550
-		if ($result === false) {
551
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
552
-		}
553
-		$row = $result->fetchRow();
554
-		if ($row === false) {
555
-			return false;
556
-		}
557
-		if (is_array($row) and self::expireItem($row)) {
558
-			return false;
559
-		}
560
-
561
-		// password protected shares need to be authenticated
562
-		if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
563
-			return false;
564
-		}
565
-
566
-		return $row;
567
-	}
568
-
569
-	/**
570
-	 * resolves reshares down to the last real share
571
-	 * @param array $linkItem
572
-	 * @return array file owner
573
-	 */
574
-	public static function resolveReShare($linkItem)
575
-	{
576
-		if (isset($linkItem['parent'])) {
577
-			$parent = $linkItem['parent'];
578
-			while (isset($parent)) {
579
-				$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
580
-				$item = $query->execute(array($parent))->fetchRow();
581
-				if (isset($item['parent'])) {
582
-					$parent = $item['parent'];
583
-				} else {
584
-					return $item;
585
-				}
586
-			}
587
-		}
588
-		return $linkItem;
589
-	}
590
-
591
-
592
-	/**
593
-	 * Get the shared items of item type owned by the current user
594
-	 * @param string $itemType
595
-	 * @param int $format (optional) Format type must be defined by the backend
596
-	 * @param mixed $parameters
597
-	 * @param int $limit Number of items to return (optional) Returns all by default
598
-	 * @param boolean $includeCollections
599
-	 * @return mixed Return depends on format
600
-	 */
601
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
602
-										  $limit = -1, $includeCollections = false) {
603
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
604
-			$parameters, $limit, $includeCollections);
605
-	}
606
-
607
-	/**
608
-	 * Get the shared item of item type owned by the current user
609
-	 * @param string $itemType
610
-	 * @param string $itemSource
611
-	 * @param int $format (optional) Format type must be defined by the backend
612
-	 * @param mixed $parameters
613
-	 * @param boolean $includeCollections
614
-	 * @return mixed Return depends on format
615
-	 */
616
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
617
-										 $parameters = null, $includeCollections = false) {
618
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
619
-			$parameters, -1, $includeCollections);
620
-	}
621
-
622
-	/**
623
-	 * Get all users an item is shared with
624
-	 * @param string $itemType
625
-	 * @param string $itemSource
626
-	 * @param string $uidOwner
627
-	 * @param boolean $includeCollections
628
-	 * @param boolean $checkExpireDate
629
-	 * @return array Return array of users
630
-	 */
631
-	public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
632
-
633
-		$users = array();
634
-		$items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
635
-		if ($items) {
636
-			foreach ($items as $item) {
637
-				if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
638
-					$users[] = $item['share_with'];
639
-				} else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
640
-
641
-					$group = \OC::$server->getGroupManager()->get($item['share_with']);
642
-					$userIds = [];
643
-					if ($group) {
644
-						$users = $group->searchUsers('', -1, 0);
645
-						foreach ($users as $user) {
646
-							$userIds[] = $user->getUID();
647
-						}
648
-						return $userIds;
649
-					}
650
-
651
-					$users = array_merge($users, $userIds);
652
-				}
653
-			}
654
-		}
655
-		return $users;
656
-	}
657
-
658
-	/**
659
-	 * Share an item with a user, group, or via private link
660
-	 * @param string $itemType
661
-	 * @param string $itemSource
662
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
663
-	 * @param string $shareWith User or group the item is being shared with
664
-	 * @param int $permissions CRUDS
665
-	 * @param string $itemSourceName
666
-	 * @param \DateTime $expirationDate
667
-	 * @param bool $passwordChanged
668
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
669
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
670
-	 * @throws \Exception
671
-	 */
672
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
673
-
674
-		$backend = self::getBackend($itemType);
675
-		$l = \OC::$server->getL10N('lib');
676
-
677
-		if ($backend->isShareTypeAllowed($shareType) === false) {
678
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
679
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
680
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
681
-			throw new \Exception($message_t);
682
-		}
683
-
684
-		$uidOwner = \OC_User::getUser();
685
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
686
-
687
-		if (is_null($itemSourceName)) {
688
-			$itemSourceName = $itemSource;
689
-		}
690
-		$itemName = $itemSourceName;
691
-
692
-		// check if file can be shared
693
-		if ($itemType === 'file' or $itemType === 'folder') {
694
-			$path = \OC\Files\Filesystem::getPath($itemSource);
695
-			$itemName = $path;
696
-
697
-			// verify that the file exists before we try to share it
698
-			if (!$path) {
699
-				$message = 'Sharing %s failed, because the file does not exist';
700
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
701
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
702
-				throw new \Exception($message_t);
703
-			}
704
-			// verify that the user has share permission
705
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
706
-				$message = 'You are not allowed to share %s';
707
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
708
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
709
-				throw new \Exception($message_t);
710
-			}
711
-		}
712
-
713
-		//verify that we don't share a folder which already contains a share mount point
714
-		if ($itemType === 'folder') {
715
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
716
-			$mountManager = \OC\Files\Filesystem::getMountManager();
717
-			$mounts = $mountManager->findIn($path);
718
-			foreach ($mounts as $mount) {
719
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
720
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
721
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
722
-					throw new \Exception($message);
723
-				}
724
-
725
-			}
726
-		}
727
-
728
-		// single file shares should never have delete permissions
729
-		if ($itemType === 'file') {
730
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
731
-		}
732
-
733
-		//Validate expirationDate
734
-		if ($expirationDate !== null) {
735
-			try {
736
-				/*
323
+                );
324
+                $result = $query->execute();
325
+
326
+                if (\OCP\DB::isError($result)) {
327
+                    \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
328
+                } else {
329
+                    while ($row = $result->fetchRow()) {
330
+                        foreach ($fileTargets[$row['fileid']] as $uid => $shareData) {
331
+                            if ($mountPath !== false) {
332
+                                $sharedPath = $shareData['file_target'];
333
+                                $sharedPath .= substr($path, strlen($mountPath) + strlen($paths[$row['fileid']]));
334
+                                $sharePaths[$uid] = $sharedPath;
335
+                            } else {
336
+                                $sharedPath = $shareData['file_target'];
337
+                                $sharedPath .= substr($path, strlen($row['path']) -5);
338
+                                $sharePaths[$uid] = $sharedPath;
339
+                            }
340
+                        }
341
+                    }
342
+                }
343
+            }
344
+
345
+            if ($includeOwner) {
346
+                $sharePaths[$ownerUser] = $path;
347
+            } else {
348
+                unset($sharePaths[$ownerUser]);
349
+            }
350
+
351
+            return $sharePaths;
352
+        }
353
+
354
+        return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare);
355
+    }
356
+
357
+    /**
358
+     * Get the items of item type shared with the current user
359
+     * @param string $itemType
360
+     * @param int $format (optional) Format type must be defined by the backend
361
+     * @param mixed $parameters (optional)
362
+     * @param int $limit Number of items to return (optional) Returns all by default
363
+     * @param boolean $includeCollections (optional)
364
+     * @return mixed Return depends on format
365
+     */
366
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
367
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
368
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
369
+            $parameters, $limit, $includeCollections);
370
+    }
371
+
372
+    /**
373
+     * Get the items of item type shared with a user
374
+     * @param string $itemType
375
+     * @param string $user id for which user we want the shares
376
+     * @param int $format (optional) Format type must be defined by the backend
377
+     * @param mixed $parameters (optional)
378
+     * @param int $limit Number of items to return (optional) Returns all by default
379
+     * @param boolean $includeCollections (optional)
380
+     * @return mixed Return depends on format
381
+     */
382
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
383
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
384
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
385
+            $parameters, $limit, $includeCollections);
386
+    }
387
+
388
+    /**
389
+     * Get the item of item type shared with the current user
390
+     * @param string $itemType
391
+     * @param string $itemTarget
392
+     * @param int $format (optional) Format type must be defined by the backend
393
+     * @param mixed $parameters (optional)
394
+     * @param boolean $includeCollections (optional)
395
+     * @return mixed Return depends on format
396
+     */
397
+    public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
398
+                                                $parameters = null, $includeCollections = false) {
399
+        return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
400
+            $parameters, 1, $includeCollections);
401
+    }
402
+
403
+    /**
404
+     * Get the item of item type shared with a given user by source
405
+     * @param string $itemType
406
+     * @param string $itemSource
407
+     * @param string $user User to whom the item was shared
408
+     * @param string $owner Owner of the share
409
+     * @param int $shareType only look for a specific share type
410
+     * @return array Return list of items with file_target, permissions and expiration
411
+     */
412
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
413
+        $shares = array();
414
+        $fileDependent = false;
415
+
416
+        $where = 'WHERE';
417
+        $fileDependentWhere = '';
418
+        if ($itemType === 'file' || $itemType === 'folder') {
419
+            $fileDependent = true;
420
+            $column = 'file_source';
421
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
422
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
423
+        } else {
424
+            $column = 'item_source';
425
+        }
426
+
427
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
428
+
429
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
430
+        $arguments = array($itemSource, $itemType);
431
+        // for link shares $user === null
432
+        if ($user !== null) {
433
+            $where .= ' AND `share_with` = ? ';
434
+            $arguments[] = $user;
435
+        }
436
+
437
+        if ($shareType !== null) {
438
+            $where .= ' AND `share_type` = ? ';
439
+            $arguments[] = $shareType;
440
+        }
441
+
442
+        if ($owner !== null) {
443
+            $where .= ' AND `uid_owner` = ? ';
444
+            $arguments[] = $owner;
445
+        }
446
+
447
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
448
+
449
+        $result = \OC_DB::executeAudited($query, $arguments);
450
+
451
+        while ($row = $result->fetchRow()) {
452
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
453
+                continue;
454
+            }
455
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
456
+                // if it is a mount point we need to get the path from the mount manager
457
+                $mountManager = \OC\Files\Filesystem::getMountManager();
458
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
459
+                if (!empty($mountPoint)) {
460
+                    $path = $mountPoint[0]->getMountPoint();
461
+                    $path = trim($path, '/');
462
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
463
+                    $row['path'] = $path;
464
+                } else {
465
+                    \OC::$server->getLogger()->warning(
466
+                        'Could not resolve mount point for ' . $row['storage_id'],
467
+                        ['app' => 'OCP\Share']
468
+                    );
469
+                }
470
+            }
471
+            $shares[] = $row;
472
+        }
473
+
474
+        //if didn't found a result than let's look for a group share.
475
+        if(empty($shares) && $user !== null) {
476
+            $userObject = \OC::$server->getUserManager()->get($user);
477
+            $groups = [];
478
+            if ($userObject) {
479
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
480
+            }
481
+
482
+            if (!empty($groups)) {
483
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
484
+                $arguments = array($itemSource, $itemType, $groups);
485
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
486
+
487
+                if ($owner !== null) {
488
+                    $where .= ' AND `uid_owner` = ?';
489
+                    $arguments[] = $owner;
490
+                    $types[] = null;
491
+                }
492
+
493
+                // TODO: inject connection, hopefully one day in the future when this
494
+                // class isn't static anymore...
495
+                $conn = \OC::$server->getDatabaseConnection();
496
+                $result = $conn->executeQuery(
497
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
498
+                    $arguments,
499
+                    $types
500
+                );
501
+
502
+                while ($row = $result->fetch()) {
503
+                    $shares[] = $row;
504
+                }
505
+            }
506
+        }
507
+
508
+        return $shares;
509
+
510
+    }
511
+
512
+    /**
513
+     * Get the item of item type shared with the current user by source
514
+     * @param string $itemType
515
+     * @param string $itemSource
516
+     * @param int $format (optional) Format type must be defined by the backend
517
+     * @param mixed $parameters
518
+     * @param boolean $includeCollections
519
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
520
+     * @return array
521
+     */
522
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
523
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
524
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
525
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
526
+            $parameters, 1, $includeCollections, true);
527
+    }
528
+
529
+    /**
530
+     * Get the item of item type shared by a link
531
+     * @param string $itemType
532
+     * @param string $itemSource
533
+     * @param string $uidOwner Owner of link
534
+     * @return array
535
+     */
536
+    public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
537
+        return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
538
+            null, 1);
539
+    }
540
+
541
+    /**
542
+     * Based on the given token the share information will be returned - password protected shares will be verified
543
+     * @param string $token
544
+     * @param bool $checkPasswordProtection
545
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
546
+     */
547
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
548
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
549
+        $result = $query->execute(array($token));
550
+        if ($result === false) {
551
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
552
+        }
553
+        $row = $result->fetchRow();
554
+        if ($row === false) {
555
+            return false;
556
+        }
557
+        if (is_array($row) and self::expireItem($row)) {
558
+            return false;
559
+        }
560
+
561
+        // password protected shares need to be authenticated
562
+        if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
563
+            return false;
564
+        }
565
+
566
+        return $row;
567
+    }
568
+
569
+    /**
570
+     * resolves reshares down to the last real share
571
+     * @param array $linkItem
572
+     * @return array file owner
573
+     */
574
+    public static function resolveReShare($linkItem)
575
+    {
576
+        if (isset($linkItem['parent'])) {
577
+            $parent = $linkItem['parent'];
578
+            while (isset($parent)) {
579
+                $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
580
+                $item = $query->execute(array($parent))->fetchRow();
581
+                if (isset($item['parent'])) {
582
+                    $parent = $item['parent'];
583
+                } else {
584
+                    return $item;
585
+                }
586
+            }
587
+        }
588
+        return $linkItem;
589
+    }
590
+
591
+
592
+    /**
593
+     * Get the shared items of item type owned by the current user
594
+     * @param string $itemType
595
+     * @param int $format (optional) Format type must be defined by the backend
596
+     * @param mixed $parameters
597
+     * @param int $limit Number of items to return (optional) Returns all by default
598
+     * @param boolean $includeCollections
599
+     * @return mixed Return depends on format
600
+     */
601
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
602
+                                            $limit = -1, $includeCollections = false) {
603
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
604
+            $parameters, $limit, $includeCollections);
605
+    }
606
+
607
+    /**
608
+     * Get the shared item of item type owned by the current user
609
+     * @param string $itemType
610
+     * @param string $itemSource
611
+     * @param int $format (optional) Format type must be defined by the backend
612
+     * @param mixed $parameters
613
+     * @param boolean $includeCollections
614
+     * @return mixed Return depends on format
615
+     */
616
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
617
+                                            $parameters = null, $includeCollections = false) {
618
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
619
+            $parameters, -1, $includeCollections);
620
+    }
621
+
622
+    /**
623
+     * Get all users an item is shared with
624
+     * @param string $itemType
625
+     * @param string $itemSource
626
+     * @param string $uidOwner
627
+     * @param boolean $includeCollections
628
+     * @param boolean $checkExpireDate
629
+     * @return array Return array of users
630
+     */
631
+    public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
632
+
633
+        $users = array();
634
+        $items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
635
+        if ($items) {
636
+            foreach ($items as $item) {
637
+                if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
638
+                    $users[] = $item['share_with'];
639
+                } else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
640
+
641
+                    $group = \OC::$server->getGroupManager()->get($item['share_with']);
642
+                    $userIds = [];
643
+                    if ($group) {
644
+                        $users = $group->searchUsers('', -1, 0);
645
+                        foreach ($users as $user) {
646
+                            $userIds[] = $user->getUID();
647
+                        }
648
+                        return $userIds;
649
+                    }
650
+
651
+                    $users = array_merge($users, $userIds);
652
+                }
653
+            }
654
+        }
655
+        return $users;
656
+    }
657
+
658
+    /**
659
+     * Share an item with a user, group, or via private link
660
+     * @param string $itemType
661
+     * @param string $itemSource
662
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
663
+     * @param string $shareWith User or group the item is being shared with
664
+     * @param int $permissions CRUDS
665
+     * @param string $itemSourceName
666
+     * @param \DateTime $expirationDate
667
+     * @param bool $passwordChanged
668
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
669
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
670
+     * @throws \Exception
671
+     */
672
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
673
+
674
+        $backend = self::getBackend($itemType);
675
+        $l = \OC::$server->getL10N('lib');
676
+
677
+        if ($backend->isShareTypeAllowed($shareType) === false) {
678
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
679
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
680
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
681
+            throw new \Exception($message_t);
682
+        }
683
+
684
+        $uidOwner = \OC_User::getUser();
685
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
686
+
687
+        if (is_null($itemSourceName)) {
688
+            $itemSourceName = $itemSource;
689
+        }
690
+        $itemName = $itemSourceName;
691
+
692
+        // check if file can be shared
693
+        if ($itemType === 'file' or $itemType === 'folder') {
694
+            $path = \OC\Files\Filesystem::getPath($itemSource);
695
+            $itemName = $path;
696
+
697
+            // verify that the file exists before we try to share it
698
+            if (!$path) {
699
+                $message = 'Sharing %s failed, because the file does not exist';
700
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
701
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
702
+                throw new \Exception($message_t);
703
+            }
704
+            // verify that the user has share permission
705
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
706
+                $message = 'You are not allowed to share %s';
707
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
708
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
709
+                throw new \Exception($message_t);
710
+            }
711
+        }
712
+
713
+        //verify that we don't share a folder which already contains a share mount point
714
+        if ($itemType === 'folder') {
715
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
716
+            $mountManager = \OC\Files\Filesystem::getMountManager();
717
+            $mounts = $mountManager->findIn($path);
718
+            foreach ($mounts as $mount) {
719
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
720
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
721
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
722
+                    throw new \Exception($message);
723
+                }
724
+
725
+            }
726
+        }
727
+
728
+        // single file shares should never have delete permissions
729
+        if ($itemType === 'file') {
730
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
731
+        }
732
+
733
+        //Validate expirationDate
734
+        if ($expirationDate !== null) {
735
+            try {
736
+                /*
737 737
 				 * Reuse the validateExpireDate.
738 738
 				 * We have to pass time() since the second arg is the time
739 739
 				 * the file was shared, since it is not shared yet we just use
740 740
 				 * the current time.
741 741
 				 */
742
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
743
-			} catch (\Exception $e) {
744
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
745
-			}
746
-		}
747
-
748
-		// Verify share type and sharing conditions are met
749
-		if ($shareType === self::SHARE_TYPE_USER) {
750
-			if ($shareWith == $uidOwner) {
751
-				$message = 'Sharing %s failed, because you can not share with yourself';
752
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
753
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
754
-				throw new \Exception($message_t);
755
-			}
756
-			if (!\OC_User::userExists($shareWith)) {
757
-				$message = 'Sharing %s failed, because the user %s does not exist';
758
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
759
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
760
-				throw new \Exception($message_t);
761
-			}
762
-			if ($shareWithinGroupOnly) {
763
-				$userManager = \OC::$server->getUserManager();
764
-				$groupManager = \OC::$server->getGroupManager();
765
-				$userOwner = $userManager->get($uidOwner);
766
-				$userShareWith = $userManager->get($shareWith);
767
-				$groupsOwner = [];
768
-				$groupsShareWith = [];
769
-				if ($userOwner) {
770
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
771
-				}
772
-				if ($userShareWith) {
773
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
774
-				}
775
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
776
-				if (empty($inGroup)) {
777
-					$message = 'Sharing %s failed, because the user '
778
-						.'%s is not a member of any groups that %s is a member of';
779
-					$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));
780
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
781
-					throw new \Exception($message_t);
782
-				}
783
-			}
784
-			// Check if the item source is already shared with the user, either from the same owner or a different user
785
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
786
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
787
-				// Only allow the same share to occur again if it is the same
788
-				// owner and is not a user share, this use case is for increasing
789
-				// permissions for a specific user
790
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
791
-					$message = 'Sharing %s failed, because this item is already shared with %s';
792
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
793
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
794
-					throw new \Exception($message_t);
795
-				}
796
-			}
797
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
798
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
799
-				// Only allow the same share to occur again if it is the same
800
-				// owner and is not a user share, this use case is for increasing
801
-				// permissions for a specific user
802
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
803
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
804
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
805
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
806
-					throw new \Exception($message_t);
807
-				}
808
-			}
809
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
810
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
811
-				$message = 'Sharing %s failed, because the group %s does not exist';
812
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
813
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
814
-				throw new \Exception($message_t);
815
-			}
816
-			if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
817
-				$group = \OC::$server->getGroupManager()->get($shareWith);
818
-				$user = \OC::$server->getUserManager()->get($uidOwner);
819
-				if (!$group || !$user || !$group->inGroup($user)) {
820
-					$message = 'Sharing %s failed, because '
821
-						. '%s is not a member of the group %s';
822
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
823
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
824
-					throw new \Exception($message_t);
825
-				}
826
-			}
827
-			// Check if the item source is already shared with the group, either from the same owner or a different user
828
-			// The check for each user in the group is done inside the put() function
829
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
830
-				null, self::FORMAT_NONE, null, 1, true, true)) {
831
-
832
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
833
-					$message = 'Sharing %s failed, because this item is already shared with %s';
834
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
835
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
836
-					throw new \Exception($message_t);
837
-				}
838
-			}
839
-			// Convert share with into an array with the keys group and users
840
-			$group = $shareWith;
841
-			$shareWith = array();
842
-			$shareWith['group'] = $group;
843
-
844
-
845
-			$groupObject = \OC::$server->getGroupManager()->get($group);
846
-			$userIds = [];
847
-			if ($groupObject) {
848
-				$users = $groupObject->searchUsers('', -1, 0);
849
-				foreach ($users as $user) {
850
-					$userIds[] = $user->getUID();
851
-				}
852
-			}
853
-
854
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
855
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
856
-			$updateExistingShare = false;
857
-			if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
858
-
859
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
860
-				if ($passwordChanged === true) {
861
-					self::verifyPassword($shareWith);
862
-				}
863
-
864
-				// when updating a link share
865
-				// FIXME Don't delete link if we update it
866
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
867
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
868
-					// remember old token
869
-					$oldToken = $checkExists['token'];
870
-					$oldPermissions = $checkExists['permissions'];
871
-					//delete the old share
872
-					Helper::delete($checkExists['id']);
873
-					$updateExistingShare = true;
874
-				}
875
-
876
-				if ($passwordChanged === null) {
877
-					// Generate hash of password - same method as user passwords
878
-					if (is_string($shareWith) && $shareWith !== '') {
879
-						self::verifyPassword($shareWith);
880
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
881
-					} else {
882
-						// reuse the already set password, but only if we change permissions
883
-						// otherwise the user disabled the password protection
884
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
885
-							$shareWith = $checkExists['share_with'];
886
-						}
887
-					}
888
-				} else {
889
-					if ($passwordChanged === true) {
890
-						if (is_string($shareWith) && $shareWith !== '') {
891
-							self::verifyPassword($shareWith);
892
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
893
-						}
894
-					} else if ($updateExistingShare) {
895
-						$shareWith = $checkExists['share_with'];
896
-					}
897
-				}
898
-
899
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
900
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
901
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
902
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
903
-					throw new \Exception($message_t);
904
-				}
905
-
906
-				if ($updateExistingShare === false &&
907
-					self::isDefaultExpireDateEnabled() &&
908
-					empty($expirationDate)) {
909
-					$expirationDate = Helper::calcExpireDate();
910
-				}
911
-
912
-				// Generate token
913
-				if (isset($oldToken)) {
914
-					$token = $oldToken;
915
-				} else {
916
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
917
-						\OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
918
-						\OCP\Security\ISecureRandom::CHAR_DIGITS
919
-					);
920
-				}
921
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
922
-					null, $token, $itemSourceName, $expirationDate);
923
-				if ($result) {
924
-					return $token;
925
-				} else {
926
-					return false;
927
-				}
928
-			}
929
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
930
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
931
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
932
-			throw new \Exception($message_t);
933
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
934
-
935
-			/*
742
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
743
+            } catch (\Exception $e) {
744
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
745
+            }
746
+        }
747
+
748
+        // Verify share type and sharing conditions are met
749
+        if ($shareType === self::SHARE_TYPE_USER) {
750
+            if ($shareWith == $uidOwner) {
751
+                $message = 'Sharing %s failed, because you can not share with yourself';
752
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
753
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
754
+                throw new \Exception($message_t);
755
+            }
756
+            if (!\OC_User::userExists($shareWith)) {
757
+                $message = 'Sharing %s failed, because the user %s does not exist';
758
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
759
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
760
+                throw new \Exception($message_t);
761
+            }
762
+            if ($shareWithinGroupOnly) {
763
+                $userManager = \OC::$server->getUserManager();
764
+                $groupManager = \OC::$server->getGroupManager();
765
+                $userOwner = $userManager->get($uidOwner);
766
+                $userShareWith = $userManager->get($shareWith);
767
+                $groupsOwner = [];
768
+                $groupsShareWith = [];
769
+                if ($userOwner) {
770
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
771
+                }
772
+                if ($userShareWith) {
773
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
774
+                }
775
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
776
+                if (empty($inGroup)) {
777
+                    $message = 'Sharing %s failed, because the user '
778
+                        .'%s is not a member of any groups that %s is a member of';
779
+                    $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));
780
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
781
+                    throw new \Exception($message_t);
782
+                }
783
+            }
784
+            // Check if the item source is already shared with the user, either from the same owner or a different user
785
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
786
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
787
+                // Only allow the same share to occur again if it is the same
788
+                // owner and is not a user share, this use case is for increasing
789
+                // permissions for a specific user
790
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
791
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
792
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
793
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
794
+                    throw new \Exception($message_t);
795
+                }
796
+            }
797
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
798
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
799
+                // Only allow the same share to occur again if it is the same
800
+                // owner and is not a user share, this use case is for increasing
801
+                // permissions for a specific user
802
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
803
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
804
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
805
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
806
+                    throw new \Exception($message_t);
807
+                }
808
+            }
809
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
810
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
811
+                $message = 'Sharing %s failed, because the group %s does not exist';
812
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
813
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
814
+                throw new \Exception($message_t);
815
+            }
816
+            if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
817
+                $group = \OC::$server->getGroupManager()->get($shareWith);
818
+                $user = \OC::$server->getUserManager()->get($uidOwner);
819
+                if (!$group || !$user || !$group->inGroup($user)) {
820
+                    $message = 'Sharing %s failed, because '
821
+                        . '%s is not a member of the group %s';
822
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
823
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
824
+                    throw new \Exception($message_t);
825
+                }
826
+            }
827
+            // Check if the item source is already shared with the group, either from the same owner or a different user
828
+            // The check for each user in the group is done inside the put() function
829
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
830
+                null, self::FORMAT_NONE, null, 1, true, true)) {
831
+
832
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
833
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
834
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
835
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
836
+                    throw new \Exception($message_t);
837
+                }
838
+            }
839
+            // Convert share with into an array with the keys group and users
840
+            $group = $shareWith;
841
+            $shareWith = array();
842
+            $shareWith['group'] = $group;
843
+
844
+
845
+            $groupObject = \OC::$server->getGroupManager()->get($group);
846
+            $userIds = [];
847
+            if ($groupObject) {
848
+                $users = $groupObject->searchUsers('', -1, 0);
849
+                foreach ($users as $user) {
850
+                    $userIds[] = $user->getUID();
851
+                }
852
+            }
853
+
854
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
855
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
856
+            $updateExistingShare = false;
857
+            if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
858
+
859
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
860
+                if ($passwordChanged === true) {
861
+                    self::verifyPassword($shareWith);
862
+                }
863
+
864
+                // when updating a link share
865
+                // FIXME Don't delete link if we update it
866
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
867
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
868
+                    // remember old token
869
+                    $oldToken = $checkExists['token'];
870
+                    $oldPermissions = $checkExists['permissions'];
871
+                    //delete the old share
872
+                    Helper::delete($checkExists['id']);
873
+                    $updateExistingShare = true;
874
+                }
875
+
876
+                if ($passwordChanged === null) {
877
+                    // Generate hash of password - same method as user passwords
878
+                    if (is_string($shareWith) && $shareWith !== '') {
879
+                        self::verifyPassword($shareWith);
880
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
881
+                    } else {
882
+                        // reuse the already set password, but only if we change permissions
883
+                        // otherwise the user disabled the password protection
884
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
885
+                            $shareWith = $checkExists['share_with'];
886
+                        }
887
+                    }
888
+                } else {
889
+                    if ($passwordChanged === true) {
890
+                        if (is_string($shareWith) && $shareWith !== '') {
891
+                            self::verifyPassword($shareWith);
892
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
893
+                        }
894
+                    } else if ($updateExistingShare) {
895
+                        $shareWith = $checkExists['share_with'];
896
+                    }
897
+                }
898
+
899
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
900
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
901
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
902
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
903
+                    throw new \Exception($message_t);
904
+                }
905
+
906
+                if ($updateExistingShare === false &&
907
+                    self::isDefaultExpireDateEnabled() &&
908
+                    empty($expirationDate)) {
909
+                    $expirationDate = Helper::calcExpireDate();
910
+                }
911
+
912
+                // Generate token
913
+                if (isset($oldToken)) {
914
+                    $token = $oldToken;
915
+                } else {
916
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
917
+                        \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
918
+                        \OCP\Security\ISecureRandom::CHAR_DIGITS
919
+                    );
920
+                }
921
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
922
+                    null, $token, $itemSourceName, $expirationDate);
923
+                if ($result) {
924
+                    return $token;
925
+                } else {
926
+                    return false;
927
+                }
928
+            }
929
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
930
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
931
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
932
+            throw new \Exception($message_t);
933
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
934
+
935
+            /*
936 936
 			 * Check if file is not already shared with the remote user
937 937
 			 */
938
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
939
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
940
-					$message = 'Sharing %s failed, because this item is already shared with %s';
941
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
942
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
943
-					throw new \Exception($message_t);
944
-			}
945
-
946
-			// don't allow federated shares if source and target server are the same
947
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
948
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
949
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
950
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
951
-				$message = 'Not allowed to create a federated share with the same user.';
952
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
953
-				\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
954
-				throw new \Exception($message_t);
955
-			}
956
-
957
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
958
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
959
-
960
-			$shareWith = $user . '@' . $remote;
961
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
962
-
963
-			$send = false;
964
-			if ($shareId) {
965
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
966
-			}
967
-
968
-			if ($send === false) {
969
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
970
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
971
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
972
-				throw new \Exception($message_t);
973
-			}
974
-
975
-			return $send;
976
-		} else {
977
-			// Future share types need to include their own conditions
978
-			$message = 'Share type %s is not valid for %s';
979
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
980
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
981
-			throw new \Exception($message_t);
982
-		}
983
-
984
-		// Put the item into the database
985
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
986
-
987
-		return $result ? true : false;
988
-	}
989
-
990
-	/**
991
-	 * Unshare an item from a user, group, or delete a private link
992
-	 * @param string $itemType
993
-	 * @param string $itemSource
994
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
995
-	 * @param string $shareWith User or group the item is being shared with
996
-	 * @param string $owner owner of the share, if null the current user is used
997
-	 * @return boolean true on success or false on failure
998
-	 */
999
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
1000
-
1001
-		// check if it is a valid itemType
1002
-		self::getBackend($itemType);
1003
-
1004
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
1005
-
1006
-		$toDelete = array();
1007
-		$newParent = null;
1008
-		$currentUser = $owner ? $owner : \OC_User::getUser();
1009
-		foreach ($items as $item) {
1010
-			// delete the item with the expected share_type and owner
1011
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
1012
-				$toDelete = $item;
1013
-				// if there is more then one result we don't have to delete the children
1014
-				// but update their parent. For group shares the new parent should always be
1015
-				// the original group share and not the db entry with the unique name
1016
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
1017
-				$newParent = $item['parent'];
1018
-			} else {
1019
-				$newParent = $item['id'];
1020
-			}
1021
-		}
1022
-
1023
-		if (!empty($toDelete)) {
1024
-			self::unshareItem($toDelete, $newParent);
1025
-			return true;
1026
-		}
1027
-		return false;
1028
-	}
1029
-
1030
-	/**
1031
-	 * Unshare an item from all users, groups, and remove all links
1032
-	 * @param string $itemType
1033
-	 * @param string $itemSource
1034
-	 * @return boolean true on success or false on failure
1035
-	 */
1036
-	public static function unshareAll($itemType, $itemSource) {
1037
-		// Get all of the owners of shares of this item.
1038
-		$query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
1039
-		$result = $query->execute(array($itemType, $itemSource));
1040
-		$shares = array();
1041
-		// Add each owner's shares to the array of all shares for this item.
1042
-		while ($row = $result->fetchRow()) {
1043
-			$shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
1044
-		}
1045
-		if (!empty($shares)) {
1046
-			// Pass all the vars we have for now, they may be useful
1047
-			$hookParams = array(
1048
-				'itemType' => $itemType,
1049
-				'itemSource' => $itemSource,
1050
-				'shares' => $shares,
1051
-			);
1052
-			\OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
1053
-			foreach ($shares as $share) {
1054
-				self::unshareItem($share);
1055
-			}
1056
-			\OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
1057
-			return true;
1058
-		}
1059
-		return false;
1060
-	}
1061
-
1062
-	/**
1063
-	 * Unshare an item shared with the current user
1064
-	 * @param string $itemType
1065
-	 * @param string $itemOrigin Item target or source
1066
-	 * @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
1067
-	 * @return boolean true on success or false on failure
1068
-	 *
1069
-	 * Unsharing from self is not allowed for items inside collections
1070
-	 */
1071
-	public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
1072
-		$originType = ($originIsSource) ? 'source' : 'target';
1073
-		$uid = \OCP\User::getUser();
1074
-
1075
-		if ($itemType === 'file' || $itemType === 'folder') {
1076
-			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
1077
-		} else {
1078
-			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
1079
-		}
1080
-
1081
-		$query = \OCP\DB::prepare($statement);
1082
-		$result = $query->execute(array($itemType, $itemOrigin));
1083
-
1084
-		$shares = $result->fetchAll();
1085
-
1086
-		$listOfUnsharedItems = array();
1087
-
1088
-		$itemUnshared = false;
1089
-		foreach ($shares as $share) {
1090
-			if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
1091
-				$share['share_with'] === $uid) {
1092
-				$deletedShares = Helper::delete($share['id']);
1093
-				$shareTmp = array(
1094
-					'id' => $share['id'],
1095
-					'shareWith' => $share['share_with'],
1096
-					'itemTarget' => $share['item_target'],
1097
-					'itemType' => $share['item_type'],
1098
-					'shareType' => (int)$share['share_type'],
1099
-				);
1100
-				if (isset($share['file_target'])) {
1101
-					$shareTmp['fileTarget'] = $share['file_target'];
1102
-				}
1103
-				$listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
1104
-				$itemUnshared = true;
1105
-				break;
1106
-			} elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
1107
-				$group = \OC::$server->getGroupManager()->get($share['share_with']);
1108
-				$user = \OC::$server->getUserManager()->get($uid);
1109
-				if ($group && $user && $group->inGroup($user)) {
1110
-					$groupShare = $share;
1111
-				}
1112
-			} elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
1113
-				$share['share_with'] === $uid) {
1114
-				$uniqueGroupShare = $share;
1115
-			}
1116
-		}
1117
-
1118
-		if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
1119
-			$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
1120
-				.' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
1121
-				.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
1122
-				.' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
1123
-			$query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
1124
-				$groupShare['id'], self::$shareTypeGroupUserUnique,
1125
-				\OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
1126
-				$groupShare['file_target']));
1127
-			$shareTmp = array(
1128
-				'id' => $groupShare['id'],
1129
-				'shareWith' => $groupShare['share_with'],
1130
-				'itemTarget' => $groupShare['item_target'],
1131
-				'itemType' => $groupShare['item_type'],
1132
-				'shareType' => (int)$groupShare['share_type'],
1133
-			);
1134
-			if (isset($groupShare['file_target'])) {
1135
-				$shareTmp['fileTarget'] = $groupShare['file_target'];
1136
-			}
1137
-			$listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1138
-			$itemUnshared = true;
1139
-		} elseif (!$itemUnshared && isset($uniqueGroupShare)) {
1140
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
1141
-			$query->execute(array(0, $uniqueGroupShare['id']));
1142
-			$shareTmp = array(
1143
-				'id' => $uniqueGroupShare['id'],
1144
-				'shareWith' => $uniqueGroupShare['share_with'],
1145
-				'itemTarget' => $uniqueGroupShare['item_target'],
1146
-				'itemType' => $uniqueGroupShare['item_type'],
1147
-				'shareType' => (int)$uniqueGroupShare['share_type'],
1148
-			);
1149
-			if (isset($uniqueGroupShare['file_target'])) {
1150
-				$shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
1151
-			}
1152
-			$listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1153
-			$itemUnshared = true;
1154
-		}
1155
-
1156
-		if ($itemUnshared) {
1157
-			\OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
1158
-				array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
1159
-		}
1160
-
1161
-		return $itemUnshared;
1162
-	}
1163
-
1164
-	/**
1165
-	 * sent status if users got informed by mail about share
1166
-	 * @param string $itemType
1167
-	 * @param string $itemSource
1168
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1169
-	 * @param string $recipient with whom was the file shared
1170
-	 * @param boolean $status
1171
-	 */
1172
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
1173
-		$status = $status ? 1 : 0;
1174
-
1175
-		$query = \OC_DB::prepare(
1176
-			'UPDATE `*PREFIX*share`
938
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
939
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
940
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
941
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
942
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
943
+                    throw new \Exception($message_t);
944
+            }
945
+
946
+            // don't allow federated shares if source and target server are the same
947
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
948
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
949
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
950
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
951
+                $message = 'Not allowed to create a federated share with the same user.';
952
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
953
+                \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
954
+                throw new \Exception($message_t);
955
+            }
956
+
957
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
958
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
959
+
960
+            $shareWith = $user . '@' . $remote;
961
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
962
+
963
+            $send = false;
964
+            if ($shareId) {
965
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
966
+            }
967
+
968
+            if ($send === false) {
969
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
970
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
971
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
972
+                throw new \Exception($message_t);
973
+            }
974
+
975
+            return $send;
976
+        } else {
977
+            // Future share types need to include their own conditions
978
+            $message = 'Share type %s is not valid for %s';
979
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
980
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
981
+            throw new \Exception($message_t);
982
+        }
983
+
984
+        // Put the item into the database
985
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
986
+
987
+        return $result ? true : false;
988
+    }
989
+
990
+    /**
991
+     * Unshare an item from a user, group, or delete a private link
992
+     * @param string $itemType
993
+     * @param string $itemSource
994
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
995
+     * @param string $shareWith User or group the item is being shared with
996
+     * @param string $owner owner of the share, if null the current user is used
997
+     * @return boolean true on success or false on failure
998
+     */
999
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
1000
+
1001
+        // check if it is a valid itemType
1002
+        self::getBackend($itemType);
1003
+
1004
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
1005
+
1006
+        $toDelete = array();
1007
+        $newParent = null;
1008
+        $currentUser = $owner ? $owner : \OC_User::getUser();
1009
+        foreach ($items as $item) {
1010
+            // delete the item with the expected share_type and owner
1011
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
1012
+                $toDelete = $item;
1013
+                // if there is more then one result we don't have to delete the children
1014
+                // but update their parent. For group shares the new parent should always be
1015
+                // the original group share and not the db entry with the unique name
1016
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
1017
+                $newParent = $item['parent'];
1018
+            } else {
1019
+                $newParent = $item['id'];
1020
+            }
1021
+        }
1022
+
1023
+        if (!empty($toDelete)) {
1024
+            self::unshareItem($toDelete, $newParent);
1025
+            return true;
1026
+        }
1027
+        return false;
1028
+    }
1029
+
1030
+    /**
1031
+     * Unshare an item from all users, groups, and remove all links
1032
+     * @param string $itemType
1033
+     * @param string $itemSource
1034
+     * @return boolean true on success or false on failure
1035
+     */
1036
+    public static function unshareAll($itemType, $itemSource) {
1037
+        // Get all of the owners of shares of this item.
1038
+        $query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
1039
+        $result = $query->execute(array($itemType, $itemSource));
1040
+        $shares = array();
1041
+        // Add each owner's shares to the array of all shares for this item.
1042
+        while ($row = $result->fetchRow()) {
1043
+            $shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
1044
+        }
1045
+        if (!empty($shares)) {
1046
+            // Pass all the vars we have for now, they may be useful
1047
+            $hookParams = array(
1048
+                'itemType' => $itemType,
1049
+                'itemSource' => $itemSource,
1050
+                'shares' => $shares,
1051
+            );
1052
+            \OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
1053
+            foreach ($shares as $share) {
1054
+                self::unshareItem($share);
1055
+            }
1056
+            \OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
1057
+            return true;
1058
+        }
1059
+        return false;
1060
+    }
1061
+
1062
+    /**
1063
+     * Unshare an item shared with the current user
1064
+     * @param string $itemType
1065
+     * @param string $itemOrigin Item target or source
1066
+     * @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
1067
+     * @return boolean true on success or false on failure
1068
+     *
1069
+     * Unsharing from self is not allowed for items inside collections
1070
+     */
1071
+    public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
1072
+        $originType = ($originIsSource) ? 'source' : 'target';
1073
+        $uid = \OCP\User::getUser();
1074
+
1075
+        if ($itemType === 'file' || $itemType === 'folder') {
1076
+            $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
1077
+        } else {
1078
+            $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
1079
+        }
1080
+
1081
+        $query = \OCP\DB::prepare($statement);
1082
+        $result = $query->execute(array($itemType, $itemOrigin));
1083
+
1084
+        $shares = $result->fetchAll();
1085
+
1086
+        $listOfUnsharedItems = array();
1087
+
1088
+        $itemUnshared = false;
1089
+        foreach ($shares as $share) {
1090
+            if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
1091
+                $share['share_with'] === $uid) {
1092
+                $deletedShares = Helper::delete($share['id']);
1093
+                $shareTmp = array(
1094
+                    'id' => $share['id'],
1095
+                    'shareWith' => $share['share_with'],
1096
+                    'itemTarget' => $share['item_target'],
1097
+                    'itemType' => $share['item_type'],
1098
+                    'shareType' => (int)$share['share_type'],
1099
+                );
1100
+                if (isset($share['file_target'])) {
1101
+                    $shareTmp['fileTarget'] = $share['file_target'];
1102
+                }
1103
+                $listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
1104
+                $itemUnshared = true;
1105
+                break;
1106
+            } elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
1107
+                $group = \OC::$server->getGroupManager()->get($share['share_with']);
1108
+                $user = \OC::$server->getUserManager()->get($uid);
1109
+                if ($group && $user && $group->inGroup($user)) {
1110
+                    $groupShare = $share;
1111
+                }
1112
+            } elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
1113
+                $share['share_with'] === $uid) {
1114
+                $uniqueGroupShare = $share;
1115
+            }
1116
+        }
1117
+
1118
+        if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
1119
+            $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
1120
+                .' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
1121
+                .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
1122
+                .' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
1123
+            $query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
1124
+                $groupShare['id'], self::$shareTypeGroupUserUnique,
1125
+                \OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
1126
+                $groupShare['file_target']));
1127
+            $shareTmp = array(
1128
+                'id' => $groupShare['id'],
1129
+                'shareWith' => $groupShare['share_with'],
1130
+                'itemTarget' => $groupShare['item_target'],
1131
+                'itemType' => $groupShare['item_type'],
1132
+                'shareType' => (int)$groupShare['share_type'],
1133
+            );
1134
+            if (isset($groupShare['file_target'])) {
1135
+                $shareTmp['fileTarget'] = $groupShare['file_target'];
1136
+            }
1137
+            $listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1138
+            $itemUnshared = true;
1139
+        } elseif (!$itemUnshared && isset($uniqueGroupShare)) {
1140
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
1141
+            $query->execute(array(0, $uniqueGroupShare['id']));
1142
+            $shareTmp = array(
1143
+                'id' => $uniqueGroupShare['id'],
1144
+                'shareWith' => $uniqueGroupShare['share_with'],
1145
+                'itemTarget' => $uniqueGroupShare['item_target'],
1146
+                'itemType' => $uniqueGroupShare['item_type'],
1147
+                'shareType' => (int)$uniqueGroupShare['share_type'],
1148
+            );
1149
+            if (isset($uniqueGroupShare['file_target'])) {
1150
+                $shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
1151
+            }
1152
+            $listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1153
+            $itemUnshared = true;
1154
+        }
1155
+
1156
+        if ($itemUnshared) {
1157
+            \OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
1158
+                array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
1159
+        }
1160
+
1161
+        return $itemUnshared;
1162
+    }
1163
+
1164
+    /**
1165
+     * sent status if users got informed by mail about share
1166
+     * @param string $itemType
1167
+     * @param string $itemSource
1168
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1169
+     * @param string $recipient with whom was the file shared
1170
+     * @param boolean $status
1171
+     */
1172
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
1173
+        $status = $status ? 1 : 0;
1174
+
1175
+        $query = \OC_DB::prepare(
1176
+            'UPDATE `*PREFIX*share`
1177 1177
 					SET `mail_send` = ?
1178 1178
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
1179 1179
 
1180
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
1181
-
1182
-		if($result === false) {
1183
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
1184
-		}
1185
-	}
1186
-
1187
-	/**
1188
-	 * Set the permissions of an item for a specific user or group
1189
-	 * @param string $itemType
1190
-	 * @param string $itemSource
1191
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1192
-	 * @param string $shareWith User or group the item is being shared with
1193
-	 * @param int $permissions CRUDS permissions
1194
-	 * @return boolean true on success or false on failure
1195
-	 * @throws \Exception when trying to grant more permissions then the user has himself
1196
-	 */
1197
-	public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
1198
-		$l = \OC::$server->getL10N('lib');
1199
-		$connection = \OC::$server->getDatabaseConnection();
1200
-
1201
-		$intArrayToLiteralArray = function($intArray, $eb) {
1202
-			return array_map(function($int) use ($eb) {
1203
-				return $eb->literal((int)$int, 'integer');
1204
-			}, $intArray);
1205
-		};
1206
-		$sanitizeItem = function($item) {
1207
-			$item['id'] = (int)$item['id'];
1208
-			$item['premissions'] = (int)$item['permissions'];
1209
-			return $item;
1210
-		};
1211
-
1212
-		if ($rootItem = self::getItems($itemType, $itemSource, $shareType, $shareWith,
1213
-			\OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
1214
-			// Check if this item is a reshare and verify that the permissions
1215
-			// granted don't exceed the parent shared item
1216
-			if (isset($rootItem['parent'])) {
1217
-				$qb = $connection->getQueryBuilder();
1218
-				$qb->select('permissions')
1219
-					->from('share')
1220
-					->where($qb->expr()->eq('id', $qb->createParameter('id')))
1221
-					->setParameter(':id', $rootItem['parent']);
1222
-				$dbresult = $qb->execute();
1223
-
1224
-				$result = $dbresult->fetch();
1225
-				$dbresult->closeCursor();
1226
-				if (~(int)$result['permissions'] & $permissions) {
1227
-					$message = 'Setting permissions for %s failed,'
1228
-						.' because the permissions exceed permissions granted to %s';
1229
-					$message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
1230
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG);
1231
-					throw new \Exception($message_t);
1232
-				}
1233
-			}
1234
-			$qb = $connection->getQueryBuilder();
1235
-			$qb->update('share')
1236
-				->set('permissions', $qb->createParameter('permissions'))
1237
-				->where($qb->expr()->eq('id', $qb->createParameter('id')))
1238
-				->setParameter(':id', $rootItem['id'])
1239
-				->setParameter(':permissions', $permissions);
1240
-			$qb->execute();
1241
-			if ($itemType === 'file' || $itemType === 'folder') {
1242
-				\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
1243
-					'itemType' => $itemType,
1244
-					'itemSource' => $itemSource,
1245
-					'shareType' => $shareType,
1246
-					'shareWith' => $shareWith,
1247
-					'uidOwner' => \OC_User::getUser(),
1248
-					'permissions' => $permissions,
1249
-					'path' => $rootItem['path'],
1250
-					'share' => $rootItem
1251
-				));
1252
-			}
1253
-
1254
-			// Share id's to update with the new permissions
1255
-			$ids = [];
1256
-			$items = [];
1257
-
1258
-			// Check if permissions were removed
1259
-			if ((int)$rootItem['permissions'] & ~$permissions) {
1260
-				// If share permission is removed all reshares must be deleted
1261
-				if (($rootItem['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
1262
-					// delete all shares, keep parent and group children
1263
-					Helper::delete($rootItem['id'], true, null, null, true);
1264
-				}
1265
-
1266
-				// Remove permission from all children
1267
-				$parents = [$rootItem['id']];
1268
-				while (!empty($parents)) {
1269
-					$parents = $intArrayToLiteralArray($parents, $qb->expr());
1270
-					$qb = $connection->getQueryBuilder();
1271
-					$qb->select('id', 'permissions', 'item_type')
1272
-						->from('share')
1273
-						->where($qb->expr()->in('parent', $parents));
1274
-					$result = $qb->execute();
1275
-					// Reset parents array, only go through loop again if
1276
-					// items are found that need permissions removed
1277
-					$parents = [];
1278
-					while ($item = $result->fetch()) {
1279
-						$item = $sanitizeItem($item);
1280
-
1281
-						$items[] = $item;
1282
-						// Check if permissions need to be removed
1283
-						if ($item['permissions'] & ~$permissions) {
1284
-							// Add to list of items that need permissions removed
1285
-							$ids[] = $item['id'];
1286
-							$parents[] = $item['id'];
1287
-						}
1288
-					}
1289
-					$result->closeCursor();
1290
-				}
1291
-
1292
-				// Remove the permissions for all reshares of this item
1293
-				if (!empty($ids)) {
1294
-					$ids = "'".implode("','", $ids)."'";
1295
-					// TODO this should be done with Doctrine platform objects
1296
-					if (\OC::$server->getConfig()->getSystemValue("dbtype") === 'oci') {
1297
-						$andOp = 'BITAND(`permissions`, ?)';
1298
-					} else {
1299
-						$andOp = '`permissions` & ?';
1300
-					}
1301
-					$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
1302
-						.' WHERE `id` IN ('.$ids.')');
1303
-					$query->execute(array($permissions));
1304
-				}
1305
-
1306
-			}
1307
-
1308
-			/*
1180
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
1181
+
1182
+        if($result === false) {
1183
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
1184
+        }
1185
+    }
1186
+
1187
+    /**
1188
+     * Set the permissions of an item for a specific user or group
1189
+     * @param string $itemType
1190
+     * @param string $itemSource
1191
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1192
+     * @param string $shareWith User or group the item is being shared with
1193
+     * @param int $permissions CRUDS permissions
1194
+     * @return boolean true on success or false on failure
1195
+     * @throws \Exception when trying to grant more permissions then the user has himself
1196
+     */
1197
+    public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
1198
+        $l = \OC::$server->getL10N('lib');
1199
+        $connection = \OC::$server->getDatabaseConnection();
1200
+
1201
+        $intArrayToLiteralArray = function($intArray, $eb) {
1202
+            return array_map(function($int) use ($eb) {
1203
+                return $eb->literal((int)$int, 'integer');
1204
+            }, $intArray);
1205
+        };
1206
+        $sanitizeItem = function($item) {
1207
+            $item['id'] = (int)$item['id'];
1208
+            $item['premissions'] = (int)$item['permissions'];
1209
+            return $item;
1210
+        };
1211
+
1212
+        if ($rootItem = self::getItems($itemType, $itemSource, $shareType, $shareWith,
1213
+            \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
1214
+            // Check if this item is a reshare and verify that the permissions
1215
+            // granted don't exceed the parent shared item
1216
+            if (isset($rootItem['parent'])) {
1217
+                $qb = $connection->getQueryBuilder();
1218
+                $qb->select('permissions')
1219
+                    ->from('share')
1220
+                    ->where($qb->expr()->eq('id', $qb->createParameter('id')))
1221
+                    ->setParameter(':id', $rootItem['parent']);
1222
+                $dbresult = $qb->execute();
1223
+
1224
+                $result = $dbresult->fetch();
1225
+                $dbresult->closeCursor();
1226
+                if (~(int)$result['permissions'] & $permissions) {
1227
+                    $message = 'Setting permissions for %s failed,'
1228
+                        .' because the permissions exceed permissions granted to %s';
1229
+                    $message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
1230
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG);
1231
+                    throw new \Exception($message_t);
1232
+                }
1233
+            }
1234
+            $qb = $connection->getQueryBuilder();
1235
+            $qb->update('share')
1236
+                ->set('permissions', $qb->createParameter('permissions'))
1237
+                ->where($qb->expr()->eq('id', $qb->createParameter('id')))
1238
+                ->setParameter(':id', $rootItem['id'])
1239
+                ->setParameter(':permissions', $permissions);
1240
+            $qb->execute();
1241
+            if ($itemType === 'file' || $itemType === 'folder') {
1242
+                \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
1243
+                    'itemType' => $itemType,
1244
+                    'itemSource' => $itemSource,
1245
+                    'shareType' => $shareType,
1246
+                    'shareWith' => $shareWith,
1247
+                    'uidOwner' => \OC_User::getUser(),
1248
+                    'permissions' => $permissions,
1249
+                    'path' => $rootItem['path'],
1250
+                    'share' => $rootItem
1251
+                ));
1252
+            }
1253
+
1254
+            // Share id's to update with the new permissions
1255
+            $ids = [];
1256
+            $items = [];
1257
+
1258
+            // Check if permissions were removed
1259
+            if ((int)$rootItem['permissions'] & ~$permissions) {
1260
+                // If share permission is removed all reshares must be deleted
1261
+                if (($rootItem['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
1262
+                    // delete all shares, keep parent and group children
1263
+                    Helper::delete($rootItem['id'], true, null, null, true);
1264
+                }
1265
+
1266
+                // Remove permission from all children
1267
+                $parents = [$rootItem['id']];
1268
+                while (!empty($parents)) {
1269
+                    $parents = $intArrayToLiteralArray($parents, $qb->expr());
1270
+                    $qb = $connection->getQueryBuilder();
1271
+                    $qb->select('id', 'permissions', 'item_type')
1272
+                        ->from('share')
1273
+                        ->where($qb->expr()->in('parent', $parents));
1274
+                    $result = $qb->execute();
1275
+                    // Reset parents array, only go through loop again if
1276
+                    // items are found that need permissions removed
1277
+                    $parents = [];
1278
+                    while ($item = $result->fetch()) {
1279
+                        $item = $sanitizeItem($item);
1280
+
1281
+                        $items[] = $item;
1282
+                        // Check if permissions need to be removed
1283
+                        if ($item['permissions'] & ~$permissions) {
1284
+                            // Add to list of items that need permissions removed
1285
+                            $ids[] = $item['id'];
1286
+                            $parents[] = $item['id'];
1287
+                        }
1288
+                    }
1289
+                    $result->closeCursor();
1290
+                }
1291
+
1292
+                // Remove the permissions for all reshares of this item
1293
+                if (!empty($ids)) {
1294
+                    $ids = "'".implode("','", $ids)."'";
1295
+                    // TODO this should be done with Doctrine platform objects
1296
+                    if (\OC::$server->getConfig()->getSystemValue("dbtype") === 'oci') {
1297
+                        $andOp = 'BITAND(`permissions`, ?)';
1298
+                    } else {
1299
+                        $andOp = '`permissions` & ?';
1300
+                    }
1301
+                    $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
1302
+                        .' WHERE `id` IN ('.$ids.')');
1303
+                    $query->execute(array($permissions));
1304
+                }
1305
+
1306
+            }
1307
+
1308
+            /*
1309 1309
 			 * Permissions were added
1310 1310
 			 * Update all USERGROUP shares. (So group shares where the user moved their mountpoint).
1311 1311
 			 */
1312
-			if ($permissions & ~(int)$rootItem['permissions']) {
1313
-				$qb = $connection->getQueryBuilder();
1314
-				$qb->select('id', 'permissions', 'item_type')
1315
-					->from('share')
1316
-					->where($qb->expr()->eq('parent', $qb->createParameter('parent')))
1317
-					->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
1318
-					->andWhere($qb->expr()->neq('permissions', $qb->createParameter('shareDeleted')))
1319
-					->setParameter(':parent', (int)$rootItem['id'])
1320
-					->setParameter(':share_type', 2)
1321
-					->setParameter(':shareDeleted', 0);
1322
-				$result = $qb->execute();
1323
-
1324
-				$ids = [];
1325
-				while ($item = $result->fetch()) {
1326
-					$item = $sanitizeItem($item);
1327
-					$items[] = $item;
1328
-					$ids[] = $item['id'];
1329
-				}
1330
-				$result->closeCursor();
1331
-
1332
-				// Add permssions for all USERGROUP shares of this item
1333
-				if (!empty($ids)) {
1334
-					$ids = $intArrayToLiteralArray($ids, $qb->expr());
1335
-
1336
-					$qb = $connection->getQueryBuilder();
1337
-					$qb->update('share')
1338
-						->set('permissions', $qb->createParameter('permissions'))
1339
-						->where($qb->expr()->in('id', $ids))
1340
-						->setParameter(':permissions', $permissions);
1341
-					$qb->execute();
1342
-				}
1343
-			}
1344
-
1345
-			foreach ($items as $item) {
1346
-				\OC_Hook::emit('OCP\Share', 'post_update_permissions', ['share' => $item]);
1347
-			}
1348
-
1349
-			return true;
1350
-		}
1351
-		$message = 'Setting permissions for %s failed, because the item was not found';
1352
-		$message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
1353
-
1354
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1355
-		throw new \Exception($message_t);
1356
-	}
1357
-
1358
-	/**
1359
-	 * validate expiration date if it meets all constraints
1360
-	 *
1361
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
1362
-	 * @param string $shareTime timestamp when the file was shared
1363
-	 * @param string $itemType
1364
-	 * @param string $itemSource
1365
-	 * @return \DateTime validated date
1366
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
1367
-	 */
1368
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
1369
-		$l = \OC::$server->getL10N('lib');
1370
-		$date = new \DateTime($expireDate);
1371
-		$today = new \DateTime('now');
1372
-
1373
-		// if the user doesn't provide a share time we need to get it from the database
1374
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
1375
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
1376
-		if ($defaultExpireDateEnforced && $shareTime === null) {
1377
-			$items = self::getItemShared($itemType, $itemSource);
1378
-			$firstItem = reset($items);
1379
-			$shareTime = (int)$firstItem['stime'];
1380
-		}
1381
-
1382
-		if ($defaultExpireDateEnforced) {
1383
-			// initialize max date with share time
1384
-			$maxDate = new \DateTime();
1385
-			$maxDate->setTimestamp($shareTime);
1386
-			$maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
1387
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
1388
-			if ($date > $maxDate) {
1389
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
1390
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
1391
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1392
-				throw new \Exception($warning_t);
1393
-			}
1394
-		}
1395
-
1396
-		if ($date < $today) {
1397
-			$message = 'Cannot set expiration date. Expiration date is in the past';
1398
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
1399
-			\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
1400
-			throw new \Exception($message_t);
1401
-		}
1402
-
1403
-		return $date;
1404
-	}
1405
-
1406
-	/**
1407
-	 * Set expiration date for a share
1408
-	 * @param string $itemType
1409
-	 * @param string $itemSource
1410
-	 * @param string $date expiration date
1411
-	 * @param int $shareTime timestamp from when the file was shared
1412
-	 * @return boolean
1413
-	 * @throws \Exception when the expire date is not set, in the past or further in the future then the enforced date
1414
-	 */
1415
-	public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
1416
-		$user = \OC_User::getUser();
1417
-		$l = \OC::$server->getL10N('lib');
1418
-
1419
-		if ($date == '') {
1420
-			if (\OCP\Util::isDefaultExpireDateEnforced()) {
1421
-				$warning = 'Cannot clear expiration date. Shares are required to have an expiration date.';
1422
-				$warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.');
1423
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1424
-				throw new \Exception($warning_t);
1425
-			} else {
1426
-				$date = null;
1427
-			}
1428
-		} else {
1429
-			$date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
1430
-		}
1431
-		$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ?  AND `uid_owner` = ? AND `share_type` = ?');
1432
-		$query->bindValue(1, $date, 'datetime');
1433
-		$query->bindValue(2, $itemType);
1434
-		$query->bindValue(3, $itemSource);
1435
-		$query->bindValue(4, $user);
1436
-		$query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
1437
-
1438
-		$query->execute();
1439
-
1440
-		\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
1441
-			'itemType' => $itemType,
1442
-			'itemSource' => $itemSource,
1443
-			'date' => $date,
1444
-			'uidOwner' => $user
1445
-		));
1446
-
1447
-		return true;
1448
-	}
1449
-
1450
-	/**
1451
-	 * Retrieve the owner of a connection
1452
-	 *
1453
-	 * @param IDBConnection $connection
1454
-	 * @param int $shareId
1455
-	 * @throws \Exception
1456
-	 * @return string uid of share owner
1457
-	 */
1458
-	private static function getShareOwner(IDBConnection $connection, $shareId) {
1459
-		$qb = $connection->getQueryBuilder();
1460
-
1461
-		$qb->select('uid_owner')
1462
-			->from('share')
1463
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1464
-			->setParameter(':shareId', $shareId);
1465
-		$result = $qb->execute();
1466
-		$result = $result->fetch();
1467
-
1468
-		if (empty($result)) {
1469
-			throw new \Exception('Share not found');
1470
-		}
1471
-
1472
-		return $result['uid_owner'];
1473
-	}
1474
-
1475
-	/**
1476
-	 * Set password for a public link share
1477
-	 *
1478
-	 * @param IUserSession $userSession
1479
-	 * @param IDBConnection $connection
1480
-	 * @param IConfig $config
1481
-	 * @param int $shareId
1482
-	 * @param string $password
1483
-	 * @throws \Exception
1484
-	 * @return boolean
1485
-	 */
1486
-	public static function setPassword(IUserSession $userSession,
1487
-	                                   IDBConnection $connection,
1488
-	                                   IConfig $config,
1489
-	                                   $shareId, $password) {
1490
-		$user = $userSession->getUser();
1491
-		if (is_null($user)) {
1492
-			throw new \Exception("User not logged in");
1493
-		}
1494
-
1495
-		$uid = self::getShareOwner($connection, $shareId);
1496
-
1497
-		if ($uid !== $user->getUID()) {
1498
-			throw new \Exception('Cannot update share of a different user');
1499
-		}
1500
-
1501
-		if ($password === '') {
1502
-			$password = null;
1503
-		}
1504
-
1505
-		//If passwords are enforced the password can't be null
1506
-		if (self::enforcePassword($config) && is_null($password)) {
1507
-			throw new \Exception('Cannot remove password');
1508
-		}
1509
-
1510
-		self::verifyPassword($password);
1511
-
1512
-		$qb = $connection->getQueryBuilder();
1513
-		$qb->update('share')
1514
-			->set('share_with', $qb->createParameter('pass'))
1515
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1516
-			->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
1517
-			->setParameter(':shareId', $shareId);
1518
-
1519
-		$qb->execute();
1520
-
1521
-		return true;
1522
-	}
1523
-
1524
-	/**
1525
-	 * Checks whether a share has expired, calls unshareItem() if yes.
1526
-	 * @param array $item Share data (usually database row)
1527
-	 * @return boolean True if item was expired, false otherwise.
1528
-	 */
1529
-	protected static function expireItem(array $item) {
1530
-
1531
-		$result = false;
1532
-
1533
-		// only use default expiration date for link shares
1534
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
1535
-
1536
-			// calculate expiration date
1537
-			if (!empty($item['expiration'])) {
1538
-				$userDefinedExpire = new \DateTime($item['expiration']);
1539
-				$expires = $userDefinedExpire->getTimestamp();
1540
-			} else {
1541
-				$expires = null;
1542
-			}
1543
-
1544
-
1545
-			// get default expiration settings
1546
-			$defaultSettings = Helper::getDefaultExpireSetting();
1547
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
1548
-
1549
-
1550
-			if (is_int($expires)) {
1551
-				$now = time();
1552
-				if ($now > $expires) {
1553
-					self::unshareItem($item);
1554
-					$result = true;
1555
-				}
1556
-			}
1557
-		}
1558
-		return $result;
1559
-	}
1560
-
1561
-	/**
1562
-	 * Unshares a share given a share data array
1563
-	 * @param array $item Share data (usually database row)
1564
-	 * @param int $newParent parent ID
1565
-	 * @return null
1566
-	 */
1567
-	protected static function unshareItem(array $item, $newParent = null) {
1568
-
1569
-		$shareType = (int)$item['share_type'];
1570
-		$shareWith = null;
1571
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
1572
-			$shareWith = $item['share_with'];
1573
-		}
1574
-
1575
-		// Pass all the vars we have for now, they may be useful
1576
-		$hookParams = array(
1577
-			'id'            => $item['id'],
1578
-			'itemType'      => $item['item_type'],
1579
-			'itemSource'    => $item['item_source'],
1580
-			'shareType'     => $shareType,
1581
-			'shareWith'     => $shareWith,
1582
-			'itemParent'    => $item['parent'],
1583
-			'uidOwner'      => $item['uid_owner'],
1584
-		);
1585
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
1586
-			$hookParams['fileSource'] = $item['file_source'];
1587
-			$hookParams['fileTarget'] = $item['file_target'];
1588
-		}
1589
-
1590
-		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
1591
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
1592
-		$deletedShares[] = $hookParams;
1593
-		$hookParams['deletedShares'] = $deletedShares;
1594
-		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
1595
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
1596
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
1597
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
1598
-		}
1599
-	}
1600
-
1601
-	/**
1602
-	 * Get the backend class for the specified item type
1603
-	 * @param string $itemType
1604
-	 * @throws \Exception
1605
-	 * @return \OCP\Share_Backend
1606
-	 */
1607
-	public static function getBackend($itemType) {
1608
-		$l = \OC::$server->getL10N('lib');
1609
-		if (isset(self::$backends[$itemType])) {
1610
-			return self::$backends[$itemType];
1611
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
1612
-			$class = self::$backendTypes[$itemType]['class'];
1613
-			if (class_exists($class)) {
1614
-				self::$backends[$itemType] = new $class;
1615
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
1616
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
1617
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
1618
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1619
-					throw new \Exception($message_t);
1620
-				}
1621
-				return self::$backends[$itemType];
1622
-			} else {
1623
-				$message = 'Sharing backend %s not found';
1624
-				$message_t = $l->t('Sharing backend %s not found', array($class));
1625
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1626
-				throw new \Exception($message_t);
1627
-			}
1628
-		}
1629
-		$message = 'Sharing backend for %s not found';
1630
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
1631
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
1632
-		throw new \Exception($message_t);
1633
-	}
1634
-
1635
-	/**
1636
-	 * Check if resharing is allowed
1637
-	 * @return boolean true if allowed or false
1638
-	 *
1639
-	 * Resharing is allowed by default if not configured
1640
-	 */
1641
-	public static function isResharingAllowed() {
1642
-		if (!isset(self::$isResharingAllowed)) {
1643
-			if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
1644
-				self::$isResharingAllowed = true;
1645
-			} else {
1646
-				self::$isResharingAllowed = false;
1647
-			}
1648
-		}
1649
-		return self::$isResharingAllowed;
1650
-	}
1651
-
1652
-	/**
1653
-	 * Get a list of collection item types for the specified item type
1654
-	 * @param string $itemType
1655
-	 * @return array
1656
-	 */
1657
-	private static function getCollectionItemTypes($itemType) {
1658
-		$collectionTypes = array($itemType);
1659
-		foreach (self::$backendTypes as $type => $backend) {
1660
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
1661
-				$collectionTypes[] = $type;
1662
-			}
1663
-		}
1664
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1665
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1666
-			unset($collectionTypes[0]);
1667
-		}
1668
-		// Return array if collections were found or the item type is a
1669
-		// collection itself - collections can be inside collections
1670
-		if (count($collectionTypes) > 0) {
1671
-			return $collectionTypes;
1672
-		}
1673
-		return false;
1674
-	}
1675
-
1676
-	/**
1677
-	 * Get the owners of items shared with a user.
1678
-	 *
1679
-	 * @param string $user The user the items are shared with.
1680
-	 * @param string $type The type of the items shared with the user.
1681
-	 * @param boolean $includeCollections Include collection item types (optional)
1682
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1683
-	 * @return array
1684
-	 */
1685
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1686
-		// First, we find out if $type is part of a collection (and if that collection is part of
1687
-		// another one and so on).
1688
-		$collectionTypes = array();
1689
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1690
-			$collectionTypes[] = $type;
1691
-		}
1692
-
1693
-		// Of these collection types, along with our original $type, we make a
1694
-		// list of the ones for which a sharing backend has been registered.
1695
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1696
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1697
-		$allMaybeSharedItems = array();
1698
-		foreach ($collectionTypes as $collectionType) {
1699
-			if (isset(self::$backends[$collectionType])) {
1700
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1701
-					$collectionType,
1702
-					$user,
1703
-					self::FORMAT_NONE
1704
-				);
1705
-			}
1706
-		}
1707
-
1708
-		$owners = array();
1709
-		if ($includeOwner) {
1710
-			$owners[] = $user;
1711
-		}
1712
-
1713
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
1714
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
1715
-		// and return them as elements of a list that look like "Tag (owner)".
1716
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1717
-			foreach ($maybeSharedItems as $sharedItem) {
1718
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1719
-					$owners[] = $sharedItem['uid_owner'];
1720
-				}
1721
-			}
1722
-		}
1723
-
1724
-		return $owners;
1725
-	}
1726
-
1727
-	/**
1728
-	 * Get shared items from the database
1729
-	 * @param string $itemType
1730
-	 * @param string $item Item source or target (optional)
1731
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1732
-	 * @param string $shareWith User or group the item is being shared with
1733
-	 * @param string $uidOwner User that is the owner of shared items (optional)
1734
-	 * @param int $format Format to convert items to with formatItems() (optional)
1735
-	 * @param mixed $parameters to pass to formatItems() (optional)
1736
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
1737
-	 * @param boolean $includeCollections Include collection item types (optional)
1738
-	 * @param boolean $itemShareWithBySource (optional)
1739
-	 * @param boolean $checkExpireDate
1740
-	 * @return array
1741
-	 *
1742
-	 * See public functions getItem(s)... for parameter usage
1743
-	 *
1744
-	 */
1745
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1746
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1747
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1748
-		if (!self::isEnabled()) {
1749
-			return array();
1750
-		}
1751
-		$backend = self::getBackend($itemType);
1752
-		$collectionTypes = false;
1753
-		// Get filesystem root to add it to the file target and remove from the
1754
-		// file source, match file_source with the file cache
1755
-		if ($itemType == 'file' || $itemType == 'folder') {
1756
-			if(!is_null($uidOwner)) {
1757
-				$root = \OC\Files\Filesystem::getRoot();
1758
-			} else {
1759
-				$root = '';
1760
-			}
1761
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1762
-			if (!isset($item)) {
1763
-				$where .= ' AND `file_target` IS NOT NULL ';
1764
-			}
1765
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1766
-			$fileDependent = true;
1767
-			$queryArgs = array();
1768
-		} else {
1769
-			$fileDependent = false;
1770
-			$root = '';
1771
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1772
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1773
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1774
-				if (!in_array($itemType, $collectionTypes)) {
1775
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1776
-				} else {
1777
-					$itemTypes = $collectionTypes;
1778
-				}
1779
-				$placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1780
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1781
-				$queryArgs = $itemTypes;
1782
-			} else {
1783
-				$where = ' WHERE `item_type` = ?';
1784
-				$queryArgs = array($itemType);
1785
-			}
1786
-		}
1787
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1788
-			$where .= ' AND `share_type` != ?';
1789
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1790
-		}
1791
-		if (isset($shareType)) {
1792
-			// Include all user and group items
1793
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1794
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1795
-				$queryArgs[] = self::SHARE_TYPE_USER;
1796
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1797
-				$queryArgs[] = $shareWith;
1798
-
1799
-				$user = \OC::$server->getUserManager()->get($shareWith);
1800
-				$groups = [];
1801
-				if ($user) {
1802
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1803
-				}
1804
-				if (!empty($groups)) {
1805
-					$placeholders = join(',', array_fill(0, count($groups), '?'));
1806
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1807
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1808
-					$queryArgs = array_merge($queryArgs, $groups);
1809
-				}
1810
-				$where .= ')';
1811
-				// Don't include own group shares
1812
-				$where .= ' AND `uid_owner` != ?';
1813
-				$queryArgs[] = $shareWith;
1814
-			} else {
1815
-				$where .= ' AND `share_type` = ?';
1816
-				$queryArgs[] = $shareType;
1817
-				if (isset($shareWith)) {
1818
-					$where .= ' AND `share_with` = ?';
1819
-					$queryArgs[] = $shareWith;
1820
-				}
1821
-			}
1822
-		}
1823
-		if (isset($uidOwner)) {
1824
-			$where .= ' AND `uid_owner` = ?';
1825
-			$queryArgs[] = $uidOwner;
1826
-			if (!isset($shareType)) {
1827
-				// Prevent unique user targets for group shares from being selected
1828
-				$where .= ' AND `share_type` != ?';
1829
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1830
-			}
1831
-			if ($fileDependent) {
1832
-				$column = 'file_source';
1833
-			} else {
1834
-				$column = 'item_source';
1835
-			}
1836
-		} else {
1837
-			if ($fileDependent) {
1838
-				$column = 'file_target';
1839
-			} else {
1840
-				$column = 'item_target';
1841
-			}
1842
-		}
1843
-		if (isset($item)) {
1844
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1845
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1846
-				$where .= ' AND (';
1847
-			} else {
1848
-				$where .= ' AND';
1849
-			}
1850
-			// If looking for own shared items, check item_source else check item_target
1851
-			if (isset($uidOwner) || $itemShareWithBySource) {
1852
-				// If item type is a file, file source needs to be checked in case the item was converted
1853
-				if ($fileDependent) {
1854
-					$where .= ' `file_source` = ?';
1855
-					$column = 'file_source';
1856
-				} else {
1857
-					$where .= ' `item_source` = ?';
1858
-					$column = 'item_source';
1859
-				}
1860
-			} else {
1861
-				if ($fileDependent) {
1862
-					$where .= ' `file_target` = ?';
1863
-					$item = \OC\Files\Filesystem::normalizePath($item);
1864
-				} else {
1865
-					$where .= ' `item_target` = ?';
1866
-				}
1867
-			}
1868
-			$queryArgs[] = $item;
1869
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1870
-				$placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1871
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1872
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1873
-			}
1874
-		}
1875
-
1876
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1877
-			// Make sure the unique user target is returned if it exists,
1878
-			// unique targets should follow the group share in the database
1879
-			// If the limit is not 1, the filtering can be done later
1880
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1881
-		} else {
1882
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1883
-		}
1884
-
1885
-		if ($limit != -1 && !$includeCollections) {
1886
-			// The limit must be at least 3, because filtering needs to be done
1887
-			if ($limit < 3) {
1888
-				$queryLimit = 3;
1889
-			} else {
1890
-				$queryLimit = $limit;
1891
-			}
1892
-		} else {
1893
-			$queryLimit = null;
1894
-		}
1895
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1896
-		$root = strlen($root);
1897
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1898
-		$result = $query->execute($queryArgs);
1899
-		if ($result === false) {
1900
-			\OCP\Util::writeLog('OCP\Share',
1901
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1902
-				\OCP\Util::ERROR);
1903
-		}
1904
-		$items = array();
1905
-		$targets = array();
1906
-		$switchedItems = array();
1907
-		$mounts = array();
1908
-		while ($row = $result->fetchRow()) {
1909
-			self::transformDBResults($row);
1910
-			// Filter out duplicate group shares for users with unique targets
1911
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1912
-				continue;
1913
-			}
1914
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1915
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1916
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1917
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1918
-				// if the group share was unshared from the user we keep the permission, otherwise
1919
-				// we take the permission from the parent because this is always the up-to-date
1920
-				// permission for the group share
1921
-				if ($row['permissions'] > 0) {
1922
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1923
-				}
1924
-				// Remove the parent group share
1925
-				unset($items[$row['parent']]);
1926
-				if ($row['permissions'] == 0) {
1927
-					continue;
1928
-				}
1929
-			} else if (!isset($uidOwner)) {
1930
-				// Check if the same target already exists
1931
-				if (isset($targets[$row['id']])) {
1932
-					// Check if the same owner shared with the user twice
1933
-					// through a group and user share - this is allowed
1934
-					$id = $targets[$row['id']];
1935
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1936
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1937
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1938
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1939
-							$items[$id]['share_with'] = $row['share_with'];
1940
-						}
1941
-						// Switch ids if sharing permission is granted on only
1942
-						// one share to ensure correct parent is used if resharing
1943
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1944
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1945
-							$items[$row['id']] = $items[$id];
1946
-							$switchedItems[$id] = $row['id'];
1947
-							unset($items[$id]);
1948
-							$id = $row['id'];
1949
-						}
1950
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1951
-
1952
-					}
1953
-					continue;
1954
-				} elseif (!empty($row['parent'])) {
1955
-					$targets[$row['parent']] = $row['id'];
1956
-				}
1957
-			}
1958
-			// Remove root from file source paths if retrieving own shared items
1959
-			if (isset($uidOwner) && isset($row['path'])) {
1960
-				if (isset($row['parent'])) {
1961
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1962
-					$parentResult = $query->execute(array($row['parent']));
1963
-					if ($result === false) {
1964
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1965
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1966
-							\OCP\Util::ERROR);
1967
-					} else {
1968
-						$parentRow = $parentResult->fetchRow();
1969
-						$tmpPath = $parentRow['file_target'];
1970
-						// find the right position where the row path continues from the target path
1971
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1972
-						$subPath = substr($row['path'], $pos);
1973
-						$splitPath = explode('/', $subPath);
1974
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1975
-							$tmpPath = $tmpPath . '/' . $pathPart;
1976
-						}
1977
-						$row['path'] = $tmpPath;
1978
-					}
1979
-				} else {
1980
-					if (!isset($mounts[$row['storage']])) {
1981
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1982
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1983
-							$mounts[$row['storage']] = current($mountPoints);
1984
-						}
1985
-					}
1986
-					if (!empty($mounts[$row['storage']])) {
1987
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1988
-						$relPath = substr($path, $root); // path relative to data/user
1989
-						$row['path'] = rtrim($relPath, '/');
1990
-					}
1991
-				}
1992
-			}
1993
-
1994
-			if($checkExpireDate) {
1995
-				if (self::expireItem($row)) {
1996
-					continue;
1997
-				}
1998
-			}
1999
-			// Check if resharing is allowed, if not remove share permission
2000
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
2001
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
2002
-			}
2003
-			// Add display names to result
2004
-			$row['share_with_displayname'] = $row['share_with'];
2005
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
2006
-				$row['share_type'] === self::SHARE_TYPE_USER) {
2007
-				$row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
2008
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
2009
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
2010
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
2011
-				foreach ($addressBookEntries as $entry) {
2012
-					foreach ($entry['CLOUD'] as $cloudID) {
2013
-						if ($cloudID === $row['share_with']) {
2014
-							$row['share_with_displayname'] = $entry['FN'];
2015
-						}
2016
-					}
2017
-				}
2018
-			}
2019
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
2020
-				$row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
2021
-			}
2022
-
2023
-			if ($row['permissions'] > 0) {
2024
-				$items[$row['id']] = $row;
2025
-			}
2026
-
2027
-		}
2028
-
2029
-		// group items if we are looking for items shared with the current user
2030
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
2031
-			$items = self::groupItems($items, $itemType);
2032
-		}
2033
-
2034
-		if (!empty($items)) {
2035
-			$collectionItems = array();
2036
-			foreach ($items as &$row) {
2037
-				// Return only the item instead of a 2-dimensional array
2038
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
2039
-					if ($format == self::FORMAT_NONE) {
2040
-						return $row;
2041
-					} else {
2042
-						break;
2043
-					}
2044
-				}
2045
-				// Check if this is a collection of the requested item type
2046
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
2047
-					if (($collectionBackend = self::getBackend($row['item_type']))
2048
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
2049
-						// Collections can be inside collections, check if the item is a collection
2050
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
2051
-							$collectionItems[] = $row;
2052
-						} else {
2053
-							$collection = array();
2054
-							$collection['item_type'] = $row['item_type'];
2055
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2056
-								$collection['path'] = basename($row['path']);
2057
-							}
2058
-							$row['collection'] = $collection;
2059
-							// Fetch all of the children sources
2060
-							$children = $collectionBackend->getChildren($row[$column]);
2061
-							foreach ($children as $child) {
2062
-								$childItem = $row;
2063
-								$childItem['item_type'] = $itemType;
2064
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
2065
-									$childItem['item_source'] = $child['source'];
2066
-									$childItem['item_target'] = $child['target'];
2067
-								}
2068
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2069
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2070
-										$childItem['file_source'] = $child['source'];
2071
-									} else { // TODO is this really needed if we already know that we use the file backend?
2072
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
2073
-										$childItem['file_source'] = $meta['fileid'];
2074
-									}
2075
-									$childItem['file_target'] =
2076
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
2077
-								}
2078
-								if (isset($item)) {
2079
-									if ($childItem[$column] == $item) {
2080
-										// Return only the item instead of a 2-dimensional array
2081
-										if ($limit == 1) {
2082
-											if ($format == self::FORMAT_NONE) {
2083
-												return $childItem;
2084
-											} else {
2085
-												// Unset the items array and break out of both loops
2086
-												$items = array();
2087
-												$items[] = $childItem;
2088
-												break 2;
2089
-											}
2090
-										} else {
2091
-											$collectionItems[] = $childItem;
2092
-										}
2093
-									}
2094
-								} else {
2095
-									$collectionItems[] = $childItem;
2096
-								}
2097
-							}
2098
-						}
2099
-					}
2100
-					// Remove collection item
2101
-					$toRemove = $row['id'];
2102
-					if (array_key_exists($toRemove, $switchedItems)) {
2103
-						$toRemove = $switchedItems[$toRemove];
2104
-					}
2105
-					unset($items[$toRemove]);
2106
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
2107
-					// FIXME: Thats a dirty hack to improve file sharing performance,
2108
-					// see github issue #10588 for more details
2109
-					// Need to find a solution which works for all back-ends
2110
-					$collectionBackend = self::getBackend($row['item_type']);
2111
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
2112
-					foreach ($sharedParents as $parent) {
2113
-						$collectionItems[] = $parent;
2114
-					}
2115
-				}
2116
-			}
2117
-			if (!empty($collectionItems)) {
2118
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
2119
-				$items = array_merge($items, $collectionItems);
2120
-			}
2121
-
2122
-			// filter out invalid items, these can appear when subshare entries exist
2123
-			// for a group in which the requested user isn't a member any more
2124
-			$items = array_filter($items, function($item) {
2125
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
2126
-			});
2127
-
2128
-			return self::formatResult($items, $column, $backend, $format, $parameters);
2129
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
2130
-			// FIXME: Thats a dirty hack to improve file sharing performance,
2131
-			// see github issue #10588 for more details
2132
-			// Need to find a solution which works for all back-ends
2133
-			$collectionItems = array();
2134
-			$collectionBackend = self::getBackend('folder');
2135
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
2136
-			foreach ($sharedParents as $parent) {
2137
-				$collectionItems[] = $parent;
2138
-			}
2139
-			if ($limit === 1) {
2140
-				return reset($collectionItems);
2141
-			}
2142
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
2143
-		}
2144
-
2145
-		return array();
2146
-	}
2147
-
2148
-	/**
2149
-	 * group items with link to the same source
2150
-	 *
2151
-	 * @param array $items
2152
-	 * @param string $itemType
2153
-	 * @return array of grouped items
2154
-	 */
2155
-	protected static function groupItems($items, $itemType) {
2156
-
2157
-		$fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
2158
-
2159
-		$result = array();
2160
-
2161
-		foreach ($items as $item) {
2162
-			$grouped = false;
2163
-			foreach ($result as $key => $r) {
2164
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
2165
-				// only group shares if they already point to the same target, otherwise the file where shared
2166
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
2167
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
2168
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
2169
-					// add the first item to the list of grouped shares
2170
-					if (!isset($result[$key]['grouped'])) {
2171
-						$result[$key]['grouped'][] = $result[$key];
2172
-					}
2173
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
2174
-					$result[$key]['grouped'][] = $item;
2175
-					$grouped = true;
2176
-					break;
2177
-				}
2178
-			}
2179
-
2180
-			if (!$grouped) {
2181
-				$result[] = $item;
2182
-			}
2183
-
2184
-		}
2185
-
2186
-		return $result;
2187
-	}
2188
-
2189
-	/**
2190
-	 * Put shared item into the database
2191
-	 * @param string $itemType Item type
2192
-	 * @param string $itemSource Item source
2193
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
2194
-	 * @param string $shareWith User or group the item is being shared with
2195
-	 * @param string $uidOwner User that is the owner of shared item
2196
-	 * @param int $permissions CRUDS permissions
2197
-	 * @param boolean|array $parentFolder Parent folder target (optional)
2198
-	 * @param string $token (optional)
2199
-	 * @param string $itemSourceName name of the source item (optional)
2200
-	 * @param \DateTime $expirationDate (optional)
2201
-	 * @throws \Exception
2202
-	 * @return mixed id of the new share or false
2203
-	 */
2204
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2205
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
2206
-
2207
-		$queriesToExecute = array();
2208
-		$suggestedItemTarget = null;
2209
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
2210
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
2211
-
2212
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
2213
-		if(!empty($result)) {
2214
-			$parent = $result['parent'];
2215
-			$itemSource = $result['itemSource'];
2216
-			$fileSource = $result['fileSource'];
2217
-			$suggestedItemTarget = $result['suggestedItemTarget'];
2218
-			$suggestedFileTarget = $result['suggestedFileTarget'];
2219
-			$filePath = $result['filePath'];
2220
-		}
2221
-
2222
-		$isGroupShare = false;
2223
-		if ($shareType == self::SHARE_TYPE_GROUP) {
2224
-			$isGroupShare = true;
2225
-			if (isset($shareWith['users'])) {
2226
-				$users = $shareWith['users'];
2227
-			} else {
2228
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
2229
-				if ($group) {
2230
-					$users = $group->searchUsers('', -1, 0);
2231
-					$userIds = [];
2232
-					foreach ($users as $user) {
2233
-						$userIds[] = $user->getUID();
2234
-					}
2235
-					$users = $userIds;
2236
-				} else {
2237
-					$users = [];
2238
-				}
2239
-			}
2240
-			// remove current user from list
2241
-			if (in_array(\OCP\User::getUser(), $users)) {
2242
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
2243
-			}
2244
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
2245
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
2246
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
2247
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
2248
-
2249
-			// add group share to table and remember the id as parent
2250
-			$queriesToExecute['groupShare'] = array(
2251
-				'itemType'			=> $itemType,
2252
-				'itemSource'		=> $itemSource,
2253
-				'itemTarget'		=> $groupItemTarget,
2254
-				'shareType'			=> $shareType,
2255
-				'shareWith'			=> $shareWith['group'],
2256
-				'uidOwner'			=> $uidOwner,
2257
-				'permissions'		=> $permissions,
2258
-				'shareTime'			=> time(),
2259
-				'fileSource'		=> $fileSource,
2260
-				'fileTarget'		=> $groupFileTarget,
2261
-				'token'				=> $token,
2262
-				'parent'			=> $parent,
2263
-				'expiration'		=> $expirationDate,
2264
-			);
2265
-
2266
-		} else {
2267
-			$users = array($shareWith);
2268
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2269
-				$suggestedItemTarget);
2270
-		}
2271
-
2272
-		$run = true;
2273
-		$error = '';
2274
-		$preHookData = array(
2275
-			'itemType' => $itemType,
2276
-			'itemSource' => $itemSource,
2277
-			'shareType' => $shareType,
2278
-			'uidOwner' => $uidOwner,
2279
-			'permissions' => $permissions,
2280
-			'fileSource' => $fileSource,
2281
-			'expiration' => $expirationDate,
2282
-			'token' => $token,
2283
-			'run' => &$run,
2284
-			'error' => &$error
2285
-		);
2286
-
2287
-		$preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2288
-		$preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2289
-
2290
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
2291
-
2292
-		if ($run === false) {
2293
-			throw new \Exception($error);
2294
-		}
2295
-
2296
-		foreach ($users as $user) {
2297
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
2298
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
2299
-
2300
-			$userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
2301
-
2302
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
2303
-				$fileTarget = $sourceExists['file_target'];
2304
-				$itemTarget = $sourceExists['item_target'];
2305
-
2306
-				// for group shares we don't need a additional entry if the target is the same
2307
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
2308
-					continue;
2309
-				}
2310
-
2311
-			} elseif(!$sourceExists && !$isGroupShare)  {
2312
-
2313
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
2314
-					$uidOwner, $suggestedItemTarget, $parent);
2315
-				if (isset($fileSource)) {
2316
-					if ($parentFolder) {
2317
-						if ($parentFolder === true) {
2318
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
2319
-								$uidOwner, $suggestedFileTarget, $parent);
2320
-							if ($fileTarget != $groupFileTarget) {
2321
-								$parentFolders[$user]['folder'] = $fileTarget;
2322
-							}
2323
-						} else if (isset($parentFolder[$user])) {
2324
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
2325
-							$parent = $parentFolder[$user]['id'];
2326
-						}
2327
-					} else {
2328
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
2329
-							$user, $uidOwner, $suggestedFileTarget, $parent);
2330
-					}
2331
-				} else {
2332
-					$fileTarget = null;
2333
-				}
2334
-
2335
-			} else {
2336
-
2337
-				// group share which doesn't exists until now, check if we need a unique target for this user
2338
-
2339
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
2340
-					$uidOwner, $suggestedItemTarget, $parent);
2341
-
2342
-				// do we also need a file target
2343
-				if (isset($fileSource)) {
2344
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
2345
-						$uidOwner, $suggestedFileTarget, $parent);
2346
-				} else {
2347
-					$fileTarget = null;
2348
-				}
2349
-
2350
-				if (($itemTarget === $groupItemTarget) &&
2351
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
2352
-					continue;
2353
-				}
2354
-			}
2355
-
2356
-			$queriesToExecute[] = array(
2357
-				'itemType'			=> $itemType,
2358
-				'itemSource'		=> $itemSource,
2359
-				'itemTarget'		=> $itemTarget,
2360
-				'shareType'			=> $userShareType,
2361
-				'shareWith'			=> $user,
2362
-				'uidOwner'			=> $uidOwner,
2363
-				'permissions'		=> $permissions,
2364
-				'shareTime'			=> time(),
2365
-				'fileSource'		=> $fileSource,
2366
-				'fileTarget'		=> $fileTarget,
2367
-				'token'				=> $token,
2368
-				'parent'			=> $parent,
2369
-				'expiration'		=> $expirationDate,
2370
-			);
2371
-
2372
-		}
2373
-
2374
-		$id = false;
2375
-		if ($isGroupShare) {
2376
-			$id = self::insertShare($queriesToExecute['groupShare']);
2377
-			// Save this id, any extra rows for this group share will need to reference it
2378
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2379
-			unset($queriesToExecute['groupShare']);
2380
-		}
2381
-
2382
-		foreach ($queriesToExecute as $shareQuery) {
2383
-			$shareQuery['parent'] = $parent;
2384
-			$id = self::insertShare($shareQuery);
2385
-		}
2386
-
2387
-		$postHookData = array(
2388
-			'itemType' => $itemType,
2389
-			'itemSource' => $itemSource,
2390
-			'parent' => $parent,
2391
-			'shareType' => $shareType,
2392
-			'uidOwner' => $uidOwner,
2393
-			'permissions' => $permissions,
2394
-			'fileSource' => $fileSource,
2395
-			'id' => $parent,
2396
-			'token' => $token,
2397
-			'expirationDate' => $expirationDate,
2398
-		);
2399
-
2400
-		$postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2401
-		$postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2402
-		$postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
2403
-
2404
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
2405
-
2406
-
2407
-		return $id ? $id : false;
2408
-	}
2409
-
2410
-	/**
2411
-	 * @param string $itemType
2412
-	 * @param string $itemSource
2413
-	 * @param int $shareType
2414
-	 * @param string $shareWith
2415
-	 * @param string $uidOwner
2416
-	 * @param int $permissions
2417
-	 * @param string|null $itemSourceName
2418
-	 * @param null|\DateTime $expirationDate
2419
-	 */
2420
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
2421
-		$backend = self::getBackend($itemType);
2422
-
2423
-		$l = \OC::$server->getL10N('lib');
2424
-		$result = array();
2425
-
2426
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
2427
-
2428
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
2429
-		if ($checkReshare) {
2430
-			// Check if attempting to share back to owner
2431
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
2432
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
2433
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
2434
-
2435
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
2436
-				throw new \Exception($message_t);
2437
-			}
2438
-		}
2439
-
2440
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
2441
-			// Check if share permissions is granted
2442
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
2443
-				if (~(int)$checkReshare['permissions'] & $permissions) {
2444
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
2445
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
2446
-
2447
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
2448
-					throw new \Exception($message_t);
2449
-				} else {
2450
-					// TODO Don't check if inside folder
2451
-					$result['parent'] = $checkReshare['id'];
2452
-
2453
-					$result['expirationDate'] = $expirationDate;
2454
-					// $checkReshare['expiration'] could be null and then is always less than any value
2455
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
2456
-						$result['expirationDate'] = $checkReshare['expiration'];
2457
-					}
2458
-
2459
-					// only suggest the same name as new target if it is a reshare of the
2460
-					// same file/folder and not the reshare of a child
2461
-					if ($checkReshare[$column] === $itemSource) {
2462
-						$result['filePath'] = $checkReshare['file_target'];
2463
-						$result['itemSource'] = $checkReshare['item_source'];
2464
-						$result['fileSource'] = $checkReshare['file_source'];
2465
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
2466
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
2467
-					} else {
2468
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
2469
-						$result['suggestedItemTarget'] = null;
2470
-						$result['suggestedFileTarget'] = null;
2471
-						$result['itemSource'] = $itemSource;
2472
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
2473
-					}
2474
-				}
2475
-			} else {
2476
-				$message = 'Sharing %s failed, because resharing is not allowed';
2477
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
2478
-
2479
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
2480
-				throw new \Exception($message_t);
2481
-			}
2482
-		} else {
2483
-			$result['parent'] = null;
2484
-			$result['suggestedItemTarget'] = null;
2485
-			$result['suggestedFileTarget'] = null;
2486
-			$result['itemSource'] = $itemSource;
2487
-			$result['expirationDate'] = $expirationDate;
2488
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
2489
-				$message = 'Sharing %s failed, because the sharing backend for '
2490
-					.'%s could not find its source';
2491
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
2492
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
2493
-				throw new \Exception($message_t);
2494
-			}
2495
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2496
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
2497
-				if ($itemType == 'file' || $itemType == 'folder') {
2498
-					$result['fileSource'] = $itemSource;
2499
-				} else {
2500
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
2501
-					$result['fileSource'] = $meta['fileid'];
2502
-				}
2503
-				if ($result['fileSource'] == -1) {
2504
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
2505
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
2506
-
2507
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
2508
-					throw new \Exception($message_t);
2509
-				}
2510
-			} else {
2511
-				$result['filePath'] = null;
2512
-				$result['fileSource'] = null;
2513
-			}
2514
-		}
2515
-
2516
-		return $result;
2517
-	}
2518
-
2519
-	/**
2520
-	 *
2521
-	 * @param array $shareData
2522
-	 * @return mixed false in case of a failure or the id of the new share
2523
-	 */
2524
-	private static function insertShare(array $shareData) {
2525
-
2526
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
2527
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
2528
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
2529
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
2530
-		$query->bindValue(1, $shareData['itemType']);
2531
-		$query->bindValue(2, $shareData['itemSource']);
2532
-		$query->bindValue(3, $shareData['itemTarget']);
2533
-		$query->bindValue(4, $shareData['shareType']);
2534
-		$query->bindValue(5, $shareData['shareWith']);
2535
-		$query->bindValue(6, $shareData['uidOwner']);
2536
-		$query->bindValue(7, $shareData['permissions']);
2537
-		$query->bindValue(8, $shareData['shareTime']);
2538
-		$query->bindValue(9, $shareData['fileSource']);
2539
-		$query->bindValue(10, $shareData['fileTarget']);
2540
-		$query->bindValue(11, $shareData['token']);
2541
-		$query->bindValue(12, $shareData['parent']);
2542
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
2543
-		$result = $query->execute();
2544
-
2545
-		$id = false;
2546
-		if ($result) {
2547
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2548
-		}
2549
-
2550
-		return $id;
2551
-
2552
-	}
2553
-
2554
-	/**
2555
-	 * Delete all shares with type SHARE_TYPE_LINK
2556
-	 */
2557
-	public static function removeAllLinkShares() {
2558
-		// Delete any link shares
2559
-		$query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
2560
-		$result = $query->execute(array(self::SHARE_TYPE_LINK));
2561
-		while ($item = $result->fetchRow()) {
2562
-			Helper::delete($item['id']);
2563
-		}
2564
-	}
2565
-
2566
-	/**
2567
-	 * In case a password protected link is not yet authenticated this function will return false
2568
-	 *
2569
-	 * @param array $linkItem
2570
-	 * @return boolean
2571
-	 */
2572
-	public static function checkPasswordProtectedShare(array $linkItem) {
2573
-		if (!isset($linkItem['share_with'])) {
2574
-			return true;
2575
-		}
2576
-		if (!isset($linkItem['share_type'])) {
2577
-			return true;
2578
-		}
2579
-		if (!isset($linkItem['id'])) {
2580
-			return true;
2581
-		}
2582
-
2583
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
2584
-			return true;
2585
-		}
2586
-
2587
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
2588
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
2589
-			return true;
2590
-		}
2591
-
2592
-		return false;
2593
-	}
2594
-
2595
-	/**
2596
-	 * construct select statement
2597
-	 * @param int $format
2598
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
2599
-	 * @param string $uidOwner
2600
-	 * @return string select statement
2601
-	 */
2602
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
2603
-		$select = '*';
2604
-		if ($format == self::FORMAT_STATUSES) {
2605
-			if ($fileDependent) {
2606
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
2607
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
2608
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2609
-					. '`uid_initiator`';
2610
-			} else {
2611
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
2612
-			}
2613
-		} else {
2614
-			if (isset($uidOwner)) {
2615
-				if ($fileDependent) {
2616
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
2617
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
2618
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
2619
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2620
-				} else {
2621
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
2622
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
2623
-				}
2624
-			} else {
2625
-				if ($fileDependent) {
2626
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
2627
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
2628
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
2629
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2630
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
2631
-					} else {
2632
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
2633
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
2634
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
2635
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
2636
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2637
-					}
2638
-				}
2639
-			}
2640
-		}
2641
-		return $select;
2642
-	}
2643
-
2644
-
2645
-	/**
2646
-	 * transform db results
2647
-	 * @param array $row result
2648
-	 */
2649
-	private static function transformDBResults(&$row) {
2650
-		if (isset($row['id'])) {
2651
-			$row['id'] = (int) $row['id'];
2652
-		}
2653
-		if (isset($row['share_type'])) {
2654
-			$row['share_type'] = (int) $row['share_type'];
2655
-		}
2656
-		if (isset($row['parent'])) {
2657
-			$row['parent'] = (int) $row['parent'];
2658
-		}
2659
-		if (isset($row['file_parent'])) {
2660
-			$row['file_parent'] = (int) $row['file_parent'];
2661
-		}
2662
-		if (isset($row['file_source'])) {
2663
-			$row['file_source'] = (int) $row['file_source'];
2664
-		}
2665
-		if (isset($row['permissions'])) {
2666
-			$row['permissions'] = (int) $row['permissions'];
2667
-		}
2668
-		if (isset($row['storage'])) {
2669
-			$row['storage'] = (int) $row['storage'];
2670
-		}
2671
-		if (isset($row['stime'])) {
2672
-			$row['stime'] = (int) $row['stime'];
2673
-		}
2674
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2675
-			// discard expiration date for non-link shares, which might have been
2676
-			// set by ancient bugs
2677
-			$row['expiration'] = null;
2678
-		}
2679
-	}
2680
-
2681
-	/**
2682
-	 * format result
2683
-	 * @param array $items result
2684
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2685
-	 * @param \OCP\Share_Backend $backend sharing backend
2686
-	 * @param int $format
2687
-	 * @param array $parameters additional format parameters
2688
-	 * @return array format result
2689
-	 */
2690
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2691
-		if ($format === self::FORMAT_NONE) {
2692
-			return $items;
2693
-		} else if ($format === self::FORMAT_STATUSES) {
2694
-			$statuses = array();
2695
-			foreach ($items as $item) {
2696
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2697
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2698
-						continue;
2699
-					}
2700
-					$statuses[$item[$column]]['link'] = true;
2701
-				} else if (!isset($statuses[$item[$column]])) {
2702
-					$statuses[$item[$column]]['link'] = false;
2703
-				}
2704
-				if (!empty($item['file_target'])) {
2705
-					$statuses[$item[$column]]['path'] = $item['path'];
2706
-				}
2707
-			}
2708
-			return $statuses;
2709
-		} else {
2710
-			return $backend->formatItems($items, $format, $parameters);
2711
-		}
2712
-	}
2713
-
2714
-	/**
2715
-	 * remove protocol from URL
2716
-	 *
2717
-	 * @param string $url
2718
-	 * @return string
2719
-	 */
2720
-	public static function removeProtocolFromUrl($url) {
2721
-		if (strpos($url, 'https://') === 0) {
2722
-			return substr($url, strlen('https://'));
2723
-		} else if (strpos($url, 'http://') === 0) {
2724
-			return substr($url, strlen('http://'));
2725
-		}
2726
-
2727
-		return $url;
2728
-	}
2729
-
2730
-	/**
2731
-	 * try http post first with https and then with http as a fallback
2732
-	 *
2733
-	 * @param string $remoteDomain
2734
-	 * @param string $urlSuffix
2735
-	 * @param array $fields post parameters
2736
-	 * @return array
2737
-	 */
2738
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2739
-		$protocol = 'https://';
2740
-		$result = [
2741
-			'success' => false,
2742
-			'result' => '',
2743
-		];
2744
-		$try = 0;
2745
-		$discoveryManager = new DiscoveryManager(
2746
-			\OC::$server->getMemCacheFactory(),
2747
-			\OC::$server->getHTTPClientService()
2748
-		);
2749
-		while ($result['success'] === false && $try < 2) {
2750
-			$endpoint = $discoveryManager->getShareEndpoint($protocol . $remoteDomain);
2751
-			$result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2752
-			$try++;
2753
-			$protocol = 'http://';
2754
-		}
2755
-
2756
-		return $result;
2757
-	}
2758
-
2759
-	/**
2760
-	 * send server-to-server share to remote server
2761
-	 *
2762
-	 * @param string $token
2763
-	 * @param string $shareWith
2764
-	 * @param string $name
2765
-	 * @param int $remote_id
2766
-	 * @param string $owner
2767
-	 * @return bool
2768
-	 */
2769
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2770
-
2771
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2772
-
2773
-		if ($user && $remote) {
2774
-			$url = $remote;
2775
-
2776
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2777
-
2778
-			$fields = array(
2779
-				'shareWith' => $user,
2780
-				'token' => $token,
2781
-				'name' => $name,
2782
-				'remoteId' => $remote_id,
2783
-				'owner' => $owner,
2784
-				'remote' => $local,
2785
-			);
2786
-
2787
-			$url = self::removeProtocolFromUrl($url);
2788
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2789
-			$status = json_decode($result['result'], true);
2790
-
2791
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2792
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2793
-				return true;
2794
-			}
2795
-
2796
-		}
2797
-
2798
-		return false;
2799
-	}
2800
-
2801
-	/**
2802
-	 * send server-to-server unshare to remote server
2803
-	 *
2804
-	 * @param string $remote url
2805
-	 * @param int $id share id
2806
-	 * @param string $token
2807
-	 * @return bool
2808
-	 */
2809
-	private static function sendRemoteUnshare($remote, $id, $token) {
2810
-		$url = rtrim($remote, '/');
2811
-		$fields = array('token' => $token, 'format' => 'json');
2812
-		$url = self::removeProtocolFromUrl($url);
2813
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2814
-		$status = json_decode($result['result'], true);
2815
-
2816
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2817
-	}
2818
-
2819
-	/**
2820
-	 * check if user can only share with group members
2821
-	 * @return bool
2822
-	 */
2823
-	public static function shareWithGroupMembersOnly() {
2824
-		$value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no');
2825
-		return ($value === 'yes') ? true : false;
2826
-	}
2827
-
2828
-	/**
2829
-	 * @return bool
2830
-	 */
2831
-	public static function isDefaultExpireDateEnabled() {
2832
-		$defaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
2833
-		return ($defaultExpireDateEnabled === "yes") ? true : false;
2834
-	}
2835
-
2836
-	/**
2837
-	 * @return bool
2838
-	 */
2839
-	public static function enforceDefaultExpireDate() {
2840
-		$enforceDefaultExpireDate = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2841
-		return ($enforceDefaultExpireDate === "yes") ? true : false;
2842
-	}
2843
-
2844
-	/**
2845
-	 * @return int
2846
-	 */
2847
-	public static function getExpireInterval() {
2848
-		return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
2849
-	}
2850
-
2851
-	/**
2852
-	 * Checks whether the given path is reachable for the given owner
2853
-	 *
2854
-	 * @param string $path path relative to files
2855
-	 * @param string $ownerStorageId storage id of the owner
2856
-	 *
2857
-	 * @return boolean true if file is reachable, false otherwise
2858
-	 */
2859
-	private static function isFileReachable($path, $ownerStorageId) {
2860
-		// if outside the home storage, file is always considered reachable
2861
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2862
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2863
-		)) {
2864
-			return true;
2865
-		}
2866
-
2867
-		// if inside the home storage, the file has to be under "/files/"
2868
-		$path = ltrim($path, '/');
2869
-		if (substr($path, 0, 6) === 'files/') {
2870
-			return true;
2871
-		}
2872
-
2873
-		return false;
2874
-	}
2875
-
2876
-	/**
2877
-	 * @param IConfig $config
2878
-	 * @return bool
2879
-	 */
2880
-	public static function enforcePassword(IConfig $config) {
2881
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2882
-		return ($enforcePassword === "yes") ? true : false;
2883
-	}
2884
-
2885
-	/**
2886
-	 * Get all share entries, including non-unique group items
2887
-	 *
2888
-	 * @param string $owner
2889
-	 * @return array
2890
-	 */
2891
-	public static function getAllSharesForOwner($owner) {
2892
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2893
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2894
-		return $result->fetchAll();
2895
-	}
2896
-
2897
-	/**
2898
-	 * Get all share entries, including non-unique group items for a file
2899
-	 *
2900
-	 * @param int $id
2901
-	 * @return array
2902
-	 */
2903
-	public static function getAllSharesForFileId($id) {
2904
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2905
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2906
-		return $result->fetchAll();
2907
-	}
2908
-
2909
-	/**
2910
-	 * @param string $password
2911
-	 * @throws \Exception
2912
-	 */
2913
-	private static function verifyPassword($password) {
2914
-
2915
-		$accepted = true;
2916
-		$message = '';
2917
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2918
-			'password' => $password,
2919
-			'accepted' => &$accepted,
2920
-			'message' => &$message
2921
-		]);
2922
-
2923
-		if (!$accepted) {
2924
-			throw new \Exception($message);
2925
-		}
2926
-	}
1312
+            if ($permissions & ~(int)$rootItem['permissions']) {
1313
+                $qb = $connection->getQueryBuilder();
1314
+                $qb->select('id', 'permissions', 'item_type')
1315
+                    ->from('share')
1316
+                    ->where($qb->expr()->eq('parent', $qb->createParameter('parent')))
1317
+                    ->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
1318
+                    ->andWhere($qb->expr()->neq('permissions', $qb->createParameter('shareDeleted')))
1319
+                    ->setParameter(':parent', (int)$rootItem['id'])
1320
+                    ->setParameter(':share_type', 2)
1321
+                    ->setParameter(':shareDeleted', 0);
1322
+                $result = $qb->execute();
1323
+
1324
+                $ids = [];
1325
+                while ($item = $result->fetch()) {
1326
+                    $item = $sanitizeItem($item);
1327
+                    $items[] = $item;
1328
+                    $ids[] = $item['id'];
1329
+                }
1330
+                $result->closeCursor();
1331
+
1332
+                // Add permssions for all USERGROUP shares of this item
1333
+                if (!empty($ids)) {
1334
+                    $ids = $intArrayToLiteralArray($ids, $qb->expr());
1335
+
1336
+                    $qb = $connection->getQueryBuilder();
1337
+                    $qb->update('share')
1338
+                        ->set('permissions', $qb->createParameter('permissions'))
1339
+                        ->where($qb->expr()->in('id', $ids))
1340
+                        ->setParameter(':permissions', $permissions);
1341
+                    $qb->execute();
1342
+                }
1343
+            }
1344
+
1345
+            foreach ($items as $item) {
1346
+                \OC_Hook::emit('OCP\Share', 'post_update_permissions', ['share' => $item]);
1347
+            }
1348
+
1349
+            return true;
1350
+        }
1351
+        $message = 'Setting permissions for %s failed, because the item was not found';
1352
+        $message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
1353
+
1354
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1355
+        throw new \Exception($message_t);
1356
+    }
1357
+
1358
+    /**
1359
+     * validate expiration date if it meets all constraints
1360
+     *
1361
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
1362
+     * @param string $shareTime timestamp when the file was shared
1363
+     * @param string $itemType
1364
+     * @param string $itemSource
1365
+     * @return \DateTime validated date
1366
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
1367
+     */
1368
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
1369
+        $l = \OC::$server->getL10N('lib');
1370
+        $date = new \DateTime($expireDate);
1371
+        $today = new \DateTime('now');
1372
+
1373
+        // if the user doesn't provide a share time we need to get it from the database
1374
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
1375
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
1376
+        if ($defaultExpireDateEnforced && $shareTime === null) {
1377
+            $items = self::getItemShared($itemType, $itemSource);
1378
+            $firstItem = reset($items);
1379
+            $shareTime = (int)$firstItem['stime'];
1380
+        }
1381
+
1382
+        if ($defaultExpireDateEnforced) {
1383
+            // initialize max date with share time
1384
+            $maxDate = new \DateTime();
1385
+            $maxDate->setTimestamp($shareTime);
1386
+            $maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
1387
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
1388
+            if ($date > $maxDate) {
1389
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
1390
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
1391
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1392
+                throw new \Exception($warning_t);
1393
+            }
1394
+        }
1395
+
1396
+        if ($date < $today) {
1397
+            $message = 'Cannot set expiration date. Expiration date is in the past';
1398
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
1399
+            \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
1400
+            throw new \Exception($message_t);
1401
+        }
1402
+
1403
+        return $date;
1404
+    }
1405
+
1406
+    /**
1407
+     * Set expiration date for a share
1408
+     * @param string $itemType
1409
+     * @param string $itemSource
1410
+     * @param string $date expiration date
1411
+     * @param int $shareTime timestamp from when the file was shared
1412
+     * @return boolean
1413
+     * @throws \Exception when the expire date is not set, in the past or further in the future then the enforced date
1414
+     */
1415
+    public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
1416
+        $user = \OC_User::getUser();
1417
+        $l = \OC::$server->getL10N('lib');
1418
+
1419
+        if ($date == '') {
1420
+            if (\OCP\Util::isDefaultExpireDateEnforced()) {
1421
+                $warning = 'Cannot clear expiration date. Shares are required to have an expiration date.';
1422
+                $warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.');
1423
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1424
+                throw new \Exception($warning_t);
1425
+            } else {
1426
+                $date = null;
1427
+            }
1428
+        } else {
1429
+            $date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
1430
+        }
1431
+        $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ?  AND `uid_owner` = ? AND `share_type` = ?');
1432
+        $query->bindValue(1, $date, 'datetime');
1433
+        $query->bindValue(2, $itemType);
1434
+        $query->bindValue(3, $itemSource);
1435
+        $query->bindValue(4, $user);
1436
+        $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
1437
+
1438
+        $query->execute();
1439
+
1440
+        \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
1441
+            'itemType' => $itemType,
1442
+            'itemSource' => $itemSource,
1443
+            'date' => $date,
1444
+            'uidOwner' => $user
1445
+        ));
1446
+
1447
+        return true;
1448
+    }
1449
+
1450
+    /**
1451
+     * Retrieve the owner of a connection
1452
+     *
1453
+     * @param IDBConnection $connection
1454
+     * @param int $shareId
1455
+     * @throws \Exception
1456
+     * @return string uid of share owner
1457
+     */
1458
+    private static function getShareOwner(IDBConnection $connection, $shareId) {
1459
+        $qb = $connection->getQueryBuilder();
1460
+
1461
+        $qb->select('uid_owner')
1462
+            ->from('share')
1463
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1464
+            ->setParameter(':shareId', $shareId);
1465
+        $result = $qb->execute();
1466
+        $result = $result->fetch();
1467
+
1468
+        if (empty($result)) {
1469
+            throw new \Exception('Share not found');
1470
+        }
1471
+
1472
+        return $result['uid_owner'];
1473
+    }
1474
+
1475
+    /**
1476
+     * Set password for a public link share
1477
+     *
1478
+     * @param IUserSession $userSession
1479
+     * @param IDBConnection $connection
1480
+     * @param IConfig $config
1481
+     * @param int $shareId
1482
+     * @param string $password
1483
+     * @throws \Exception
1484
+     * @return boolean
1485
+     */
1486
+    public static function setPassword(IUserSession $userSession,
1487
+                                        IDBConnection $connection,
1488
+                                        IConfig $config,
1489
+                                        $shareId, $password) {
1490
+        $user = $userSession->getUser();
1491
+        if (is_null($user)) {
1492
+            throw new \Exception("User not logged in");
1493
+        }
1494
+
1495
+        $uid = self::getShareOwner($connection, $shareId);
1496
+
1497
+        if ($uid !== $user->getUID()) {
1498
+            throw new \Exception('Cannot update share of a different user');
1499
+        }
1500
+
1501
+        if ($password === '') {
1502
+            $password = null;
1503
+        }
1504
+
1505
+        //If passwords are enforced the password can't be null
1506
+        if (self::enforcePassword($config) && is_null($password)) {
1507
+            throw new \Exception('Cannot remove password');
1508
+        }
1509
+
1510
+        self::verifyPassword($password);
1511
+
1512
+        $qb = $connection->getQueryBuilder();
1513
+        $qb->update('share')
1514
+            ->set('share_with', $qb->createParameter('pass'))
1515
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1516
+            ->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
1517
+            ->setParameter(':shareId', $shareId);
1518
+
1519
+        $qb->execute();
1520
+
1521
+        return true;
1522
+    }
1523
+
1524
+    /**
1525
+     * Checks whether a share has expired, calls unshareItem() if yes.
1526
+     * @param array $item Share data (usually database row)
1527
+     * @return boolean True if item was expired, false otherwise.
1528
+     */
1529
+    protected static function expireItem(array $item) {
1530
+
1531
+        $result = false;
1532
+
1533
+        // only use default expiration date for link shares
1534
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
1535
+
1536
+            // calculate expiration date
1537
+            if (!empty($item['expiration'])) {
1538
+                $userDefinedExpire = new \DateTime($item['expiration']);
1539
+                $expires = $userDefinedExpire->getTimestamp();
1540
+            } else {
1541
+                $expires = null;
1542
+            }
1543
+
1544
+
1545
+            // get default expiration settings
1546
+            $defaultSettings = Helper::getDefaultExpireSetting();
1547
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
1548
+
1549
+
1550
+            if (is_int($expires)) {
1551
+                $now = time();
1552
+                if ($now > $expires) {
1553
+                    self::unshareItem($item);
1554
+                    $result = true;
1555
+                }
1556
+            }
1557
+        }
1558
+        return $result;
1559
+    }
1560
+
1561
+    /**
1562
+     * Unshares a share given a share data array
1563
+     * @param array $item Share data (usually database row)
1564
+     * @param int $newParent parent ID
1565
+     * @return null
1566
+     */
1567
+    protected static function unshareItem(array $item, $newParent = null) {
1568
+
1569
+        $shareType = (int)$item['share_type'];
1570
+        $shareWith = null;
1571
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
1572
+            $shareWith = $item['share_with'];
1573
+        }
1574
+
1575
+        // Pass all the vars we have for now, they may be useful
1576
+        $hookParams = array(
1577
+            'id'            => $item['id'],
1578
+            'itemType'      => $item['item_type'],
1579
+            'itemSource'    => $item['item_source'],
1580
+            'shareType'     => $shareType,
1581
+            'shareWith'     => $shareWith,
1582
+            'itemParent'    => $item['parent'],
1583
+            'uidOwner'      => $item['uid_owner'],
1584
+        );
1585
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
1586
+            $hookParams['fileSource'] = $item['file_source'];
1587
+            $hookParams['fileTarget'] = $item['file_target'];
1588
+        }
1589
+
1590
+        \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
1591
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
1592
+        $deletedShares[] = $hookParams;
1593
+        $hookParams['deletedShares'] = $deletedShares;
1594
+        \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
1595
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
1596
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
1597
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
1598
+        }
1599
+    }
1600
+
1601
+    /**
1602
+     * Get the backend class for the specified item type
1603
+     * @param string $itemType
1604
+     * @throws \Exception
1605
+     * @return \OCP\Share_Backend
1606
+     */
1607
+    public static function getBackend($itemType) {
1608
+        $l = \OC::$server->getL10N('lib');
1609
+        if (isset(self::$backends[$itemType])) {
1610
+            return self::$backends[$itemType];
1611
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
1612
+            $class = self::$backendTypes[$itemType]['class'];
1613
+            if (class_exists($class)) {
1614
+                self::$backends[$itemType] = new $class;
1615
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
1616
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
1617
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
1618
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1619
+                    throw new \Exception($message_t);
1620
+                }
1621
+                return self::$backends[$itemType];
1622
+            } else {
1623
+                $message = 'Sharing backend %s not found';
1624
+                $message_t = $l->t('Sharing backend %s not found', array($class));
1625
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1626
+                throw new \Exception($message_t);
1627
+            }
1628
+        }
1629
+        $message = 'Sharing backend for %s not found';
1630
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
1631
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
1632
+        throw new \Exception($message_t);
1633
+    }
1634
+
1635
+    /**
1636
+     * Check if resharing is allowed
1637
+     * @return boolean true if allowed or false
1638
+     *
1639
+     * Resharing is allowed by default if not configured
1640
+     */
1641
+    public static function isResharingAllowed() {
1642
+        if (!isset(self::$isResharingAllowed)) {
1643
+            if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
1644
+                self::$isResharingAllowed = true;
1645
+            } else {
1646
+                self::$isResharingAllowed = false;
1647
+            }
1648
+        }
1649
+        return self::$isResharingAllowed;
1650
+    }
1651
+
1652
+    /**
1653
+     * Get a list of collection item types for the specified item type
1654
+     * @param string $itemType
1655
+     * @return array
1656
+     */
1657
+    private static function getCollectionItemTypes($itemType) {
1658
+        $collectionTypes = array($itemType);
1659
+        foreach (self::$backendTypes as $type => $backend) {
1660
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
1661
+                $collectionTypes[] = $type;
1662
+            }
1663
+        }
1664
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1665
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1666
+            unset($collectionTypes[0]);
1667
+        }
1668
+        // Return array if collections were found or the item type is a
1669
+        // collection itself - collections can be inside collections
1670
+        if (count($collectionTypes) > 0) {
1671
+            return $collectionTypes;
1672
+        }
1673
+        return false;
1674
+    }
1675
+
1676
+    /**
1677
+     * Get the owners of items shared with a user.
1678
+     *
1679
+     * @param string $user The user the items are shared with.
1680
+     * @param string $type The type of the items shared with the user.
1681
+     * @param boolean $includeCollections Include collection item types (optional)
1682
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1683
+     * @return array
1684
+     */
1685
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1686
+        // First, we find out if $type is part of a collection (and if that collection is part of
1687
+        // another one and so on).
1688
+        $collectionTypes = array();
1689
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1690
+            $collectionTypes[] = $type;
1691
+        }
1692
+
1693
+        // Of these collection types, along with our original $type, we make a
1694
+        // list of the ones for which a sharing backend has been registered.
1695
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1696
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1697
+        $allMaybeSharedItems = array();
1698
+        foreach ($collectionTypes as $collectionType) {
1699
+            if (isset(self::$backends[$collectionType])) {
1700
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1701
+                    $collectionType,
1702
+                    $user,
1703
+                    self::FORMAT_NONE
1704
+                );
1705
+            }
1706
+        }
1707
+
1708
+        $owners = array();
1709
+        if ($includeOwner) {
1710
+            $owners[] = $user;
1711
+        }
1712
+
1713
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
1714
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
1715
+        // and return them as elements of a list that look like "Tag (owner)".
1716
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1717
+            foreach ($maybeSharedItems as $sharedItem) {
1718
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1719
+                    $owners[] = $sharedItem['uid_owner'];
1720
+                }
1721
+            }
1722
+        }
1723
+
1724
+        return $owners;
1725
+    }
1726
+
1727
+    /**
1728
+     * Get shared items from the database
1729
+     * @param string $itemType
1730
+     * @param string $item Item source or target (optional)
1731
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1732
+     * @param string $shareWith User or group the item is being shared with
1733
+     * @param string $uidOwner User that is the owner of shared items (optional)
1734
+     * @param int $format Format to convert items to with formatItems() (optional)
1735
+     * @param mixed $parameters to pass to formatItems() (optional)
1736
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
1737
+     * @param boolean $includeCollections Include collection item types (optional)
1738
+     * @param boolean $itemShareWithBySource (optional)
1739
+     * @param boolean $checkExpireDate
1740
+     * @return array
1741
+     *
1742
+     * See public functions getItem(s)... for parameter usage
1743
+     *
1744
+     */
1745
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1746
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1747
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1748
+        if (!self::isEnabled()) {
1749
+            return array();
1750
+        }
1751
+        $backend = self::getBackend($itemType);
1752
+        $collectionTypes = false;
1753
+        // Get filesystem root to add it to the file target and remove from the
1754
+        // file source, match file_source with the file cache
1755
+        if ($itemType == 'file' || $itemType == 'folder') {
1756
+            if(!is_null($uidOwner)) {
1757
+                $root = \OC\Files\Filesystem::getRoot();
1758
+            } else {
1759
+                $root = '';
1760
+            }
1761
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1762
+            if (!isset($item)) {
1763
+                $where .= ' AND `file_target` IS NOT NULL ';
1764
+            }
1765
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1766
+            $fileDependent = true;
1767
+            $queryArgs = array();
1768
+        } else {
1769
+            $fileDependent = false;
1770
+            $root = '';
1771
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1772
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1773
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1774
+                if (!in_array($itemType, $collectionTypes)) {
1775
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1776
+                } else {
1777
+                    $itemTypes = $collectionTypes;
1778
+                }
1779
+                $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1780
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1781
+                $queryArgs = $itemTypes;
1782
+            } else {
1783
+                $where = ' WHERE `item_type` = ?';
1784
+                $queryArgs = array($itemType);
1785
+            }
1786
+        }
1787
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1788
+            $where .= ' AND `share_type` != ?';
1789
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1790
+        }
1791
+        if (isset($shareType)) {
1792
+            // Include all user and group items
1793
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1794
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1795
+                $queryArgs[] = self::SHARE_TYPE_USER;
1796
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1797
+                $queryArgs[] = $shareWith;
1798
+
1799
+                $user = \OC::$server->getUserManager()->get($shareWith);
1800
+                $groups = [];
1801
+                if ($user) {
1802
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1803
+                }
1804
+                if (!empty($groups)) {
1805
+                    $placeholders = join(',', array_fill(0, count($groups), '?'));
1806
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1807
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1808
+                    $queryArgs = array_merge($queryArgs, $groups);
1809
+                }
1810
+                $where .= ')';
1811
+                // Don't include own group shares
1812
+                $where .= ' AND `uid_owner` != ?';
1813
+                $queryArgs[] = $shareWith;
1814
+            } else {
1815
+                $where .= ' AND `share_type` = ?';
1816
+                $queryArgs[] = $shareType;
1817
+                if (isset($shareWith)) {
1818
+                    $where .= ' AND `share_with` = ?';
1819
+                    $queryArgs[] = $shareWith;
1820
+                }
1821
+            }
1822
+        }
1823
+        if (isset($uidOwner)) {
1824
+            $where .= ' AND `uid_owner` = ?';
1825
+            $queryArgs[] = $uidOwner;
1826
+            if (!isset($shareType)) {
1827
+                // Prevent unique user targets for group shares from being selected
1828
+                $where .= ' AND `share_type` != ?';
1829
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1830
+            }
1831
+            if ($fileDependent) {
1832
+                $column = 'file_source';
1833
+            } else {
1834
+                $column = 'item_source';
1835
+            }
1836
+        } else {
1837
+            if ($fileDependent) {
1838
+                $column = 'file_target';
1839
+            } else {
1840
+                $column = 'item_target';
1841
+            }
1842
+        }
1843
+        if (isset($item)) {
1844
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1845
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1846
+                $where .= ' AND (';
1847
+            } else {
1848
+                $where .= ' AND';
1849
+            }
1850
+            // If looking for own shared items, check item_source else check item_target
1851
+            if (isset($uidOwner) || $itemShareWithBySource) {
1852
+                // If item type is a file, file source needs to be checked in case the item was converted
1853
+                if ($fileDependent) {
1854
+                    $where .= ' `file_source` = ?';
1855
+                    $column = 'file_source';
1856
+                } else {
1857
+                    $where .= ' `item_source` = ?';
1858
+                    $column = 'item_source';
1859
+                }
1860
+            } else {
1861
+                if ($fileDependent) {
1862
+                    $where .= ' `file_target` = ?';
1863
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1864
+                } else {
1865
+                    $where .= ' `item_target` = ?';
1866
+                }
1867
+            }
1868
+            $queryArgs[] = $item;
1869
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1870
+                $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1871
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1872
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1873
+            }
1874
+        }
1875
+
1876
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1877
+            // Make sure the unique user target is returned if it exists,
1878
+            // unique targets should follow the group share in the database
1879
+            // If the limit is not 1, the filtering can be done later
1880
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1881
+        } else {
1882
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1883
+        }
1884
+
1885
+        if ($limit != -1 && !$includeCollections) {
1886
+            // The limit must be at least 3, because filtering needs to be done
1887
+            if ($limit < 3) {
1888
+                $queryLimit = 3;
1889
+            } else {
1890
+                $queryLimit = $limit;
1891
+            }
1892
+        } else {
1893
+            $queryLimit = null;
1894
+        }
1895
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1896
+        $root = strlen($root);
1897
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1898
+        $result = $query->execute($queryArgs);
1899
+        if ($result === false) {
1900
+            \OCP\Util::writeLog('OCP\Share',
1901
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1902
+                \OCP\Util::ERROR);
1903
+        }
1904
+        $items = array();
1905
+        $targets = array();
1906
+        $switchedItems = array();
1907
+        $mounts = array();
1908
+        while ($row = $result->fetchRow()) {
1909
+            self::transformDBResults($row);
1910
+            // Filter out duplicate group shares for users with unique targets
1911
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1912
+                continue;
1913
+            }
1914
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1915
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1916
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1917
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1918
+                // if the group share was unshared from the user we keep the permission, otherwise
1919
+                // we take the permission from the parent because this is always the up-to-date
1920
+                // permission for the group share
1921
+                if ($row['permissions'] > 0) {
1922
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1923
+                }
1924
+                // Remove the parent group share
1925
+                unset($items[$row['parent']]);
1926
+                if ($row['permissions'] == 0) {
1927
+                    continue;
1928
+                }
1929
+            } else if (!isset($uidOwner)) {
1930
+                // Check if the same target already exists
1931
+                if (isset($targets[$row['id']])) {
1932
+                    // Check if the same owner shared with the user twice
1933
+                    // through a group and user share - this is allowed
1934
+                    $id = $targets[$row['id']];
1935
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1936
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1937
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1938
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1939
+                            $items[$id]['share_with'] = $row['share_with'];
1940
+                        }
1941
+                        // Switch ids if sharing permission is granted on only
1942
+                        // one share to ensure correct parent is used if resharing
1943
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1944
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1945
+                            $items[$row['id']] = $items[$id];
1946
+                            $switchedItems[$id] = $row['id'];
1947
+                            unset($items[$id]);
1948
+                            $id = $row['id'];
1949
+                        }
1950
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1951
+
1952
+                    }
1953
+                    continue;
1954
+                } elseif (!empty($row['parent'])) {
1955
+                    $targets[$row['parent']] = $row['id'];
1956
+                }
1957
+            }
1958
+            // Remove root from file source paths if retrieving own shared items
1959
+            if (isset($uidOwner) && isset($row['path'])) {
1960
+                if (isset($row['parent'])) {
1961
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1962
+                    $parentResult = $query->execute(array($row['parent']));
1963
+                    if ($result === false) {
1964
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1965
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1966
+                            \OCP\Util::ERROR);
1967
+                    } else {
1968
+                        $parentRow = $parentResult->fetchRow();
1969
+                        $tmpPath = $parentRow['file_target'];
1970
+                        // find the right position where the row path continues from the target path
1971
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1972
+                        $subPath = substr($row['path'], $pos);
1973
+                        $splitPath = explode('/', $subPath);
1974
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1975
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1976
+                        }
1977
+                        $row['path'] = $tmpPath;
1978
+                    }
1979
+                } else {
1980
+                    if (!isset($mounts[$row['storage']])) {
1981
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1982
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1983
+                            $mounts[$row['storage']] = current($mountPoints);
1984
+                        }
1985
+                    }
1986
+                    if (!empty($mounts[$row['storage']])) {
1987
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1988
+                        $relPath = substr($path, $root); // path relative to data/user
1989
+                        $row['path'] = rtrim($relPath, '/');
1990
+                    }
1991
+                }
1992
+            }
1993
+
1994
+            if($checkExpireDate) {
1995
+                if (self::expireItem($row)) {
1996
+                    continue;
1997
+                }
1998
+            }
1999
+            // Check if resharing is allowed, if not remove share permission
2000
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
2001
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
2002
+            }
2003
+            // Add display names to result
2004
+            $row['share_with_displayname'] = $row['share_with'];
2005
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
2006
+                $row['share_type'] === self::SHARE_TYPE_USER) {
2007
+                $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
2008
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
2009
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
2010
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
2011
+                foreach ($addressBookEntries as $entry) {
2012
+                    foreach ($entry['CLOUD'] as $cloudID) {
2013
+                        if ($cloudID === $row['share_with']) {
2014
+                            $row['share_with_displayname'] = $entry['FN'];
2015
+                        }
2016
+                    }
2017
+                }
2018
+            }
2019
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
2020
+                $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
2021
+            }
2022
+
2023
+            if ($row['permissions'] > 0) {
2024
+                $items[$row['id']] = $row;
2025
+            }
2026
+
2027
+        }
2028
+
2029
+        // group items if we are looking for items shared with the current user
2030
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
2031
+            $items = self::groupItems($items, $itemType);
2032
+        }
2033
+
2034
+        if (!empty($items)) {
2035
+            $collectionItems = array();
2036
+            foreach ($items as &$row) {
2037
+                // Return only the item instead of a 2-dimensional array
2038
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
2039
+                    if ($format == self::FORMAT_NONE) {
2040
+                        return $row;
2041
+                    } else {
2042
+                        break;
2043
+                    }
2044
+                }
2045
+                // Check if this is a collection of the requested item type
2046
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
2047
+                    if (($collectionBackend = self::getBackend($row['item_type']))
2048
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
2049
+                        // Collections can be inside collections, check if the item is a collection
2050
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
2051
+                            $collectionItems[] = $row;
2052
+                        } else {
2053
+                            $collection = array();
2054
+                            $collection['item_type'] = $row['item_type'];
2055
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2056
+                                $collection['path'] = basename($row['path']);
2057
+                            }
2058
+                            $row['collection'] = $collection;
2059
+                            // Fetch all of the children sources
2060
+                            $children = $collectionBackend->getChildren($row[$column]);
2061
+                            foreach ($children as $child) {
2062
+                                $childItem = $row;
2063
+                                $childItem['item_type'] = $itemType;
2064
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
2065
+                                    $childItem['item_source'] = $child['source'];
2066
+                                    $childItem['item_target'] = $child['target'];
2067
+                                }
2068
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2069
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2070
+                                        $childItem['file_source'] = $child['source'];
2071
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
2072
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
2073
+                                        $childItem['file_source'] = $meta['fileid'];
2074
+                                    }
2075
+                                    $childItem['file_target'] =
2076
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
2077
+                                }
2078
+                                if (isset($item)) {
2079
+                                    if ($childItem[$column] == $item) {
2080
+                                        // Return only the item instead of a 2-dimensional array
2081
+                                        if ($limit == 1) {
2082
+                                            if ($format == self::FORMAT_NONE) {
2083
+                                                return $childItem;
2084
+                                            } else {
2085
+                                                // Unset the items array and break out of both loops
2086
+                                                $items = array();
2087
+                                                $items[] = $childItem;
2088
+                                                break 2;
2089
+                                            }
2090
+                                        } else {
2091
+                                            $collectionItems[] = $childItem;
2092
+                                        }
2093
+                                    }
2094
+                                } else {
2095
+                                    $collectionItems[] = $childItem;
2096
+                                }
2097
+                            }
2098
+                        }
2099
+                    }
2100
+                    // Remove collection item
2101
+                    $toRemove = $row['id'];
2102
+                    if (array_key_exists($toRemove, $switchedItems)) {
2103
+                        $toRemove = $switchedItems[$toRemove];
2104
+                    }
2105
+                    unset($items[$toRemove]);
2106
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
2107
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
2108
+                    // see github issue #10588 for more details
2109
+                    // Need to find a solution which works for all back-ends
2110
+                    $collectionBackend = self::getBackend($row['item_type']);
2111
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
2112
+                    foreach ($sharedParents as $parent) {
2113
+                        $collectionItems[] = $parent;
2114
+                    }
2115
+                }
2116
+            }
2117
+            if (!empty($collectionItems)) {
2118
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
2119
+                $items = array_merge($items, $collectionItems);
2120
+            }
2121
+
2122
+            // filter out invalid items, these can appear when subshare entries exist
2123
+            // for a group in which the requested user isn't a member any more
2124
+            $items = array_filter($items, function($item) {
2125
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
2126
+            });
2127
+
2128
+            return self::formatResult($items, $column, $backend, $format, $parameters);
2129
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
2130
+            // FIXME: Thats a dirty hack to improve file sharing performance,
2131
+            // see github issue #10588 for more details
2132
+            // Need to find a solution which works for all back-ends
2133
+            $collectionItems = array();
2134
+            $collectionBackend = self::getBackend('folder');
2135
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
2136
+            foreach ($sharedParents as $parent) {
2137
+                $collectionItems[] = $parent;
2138
+            }
2139
+            if ($limit === 1) {
2140
+                return reset($collectionItems);
2141
+            }
2142
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
2143
+        }
2144
+
2145
+        return array();
2146
+    }
2147
+
2148
+    /**
2149
+     * group items with link to the same source
2150
+     *
2151
+     * @param array $items
2152
+     * @param string $itemType
2153
+     * @return array of grouped items
2154
+     */
2155
+    protected static function groupItems($items, $itemType) {
2156
+
2157
+        $fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
2158
+
2159
+        $result = array();
2160
+
2161
+        foreach ($items as $item) {
2162
+            $grouped = false;
2163
+            foreach ($result as $key => $r) {
2164
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
2165
+                // only group shares if they already point to the same target, otherwise the file where shared
2166
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
2167
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
2168
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
2169
+                    // add the first item to the list of grouped shares
2170
+                    if (!isset($result[$key]['grouped'])) {
2171
+                        $result[$key]['grouped'][] = $result[$key];
2172
+                    }
2173
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
2174
+                    $result[$key]['grouped'][] = $item;
2175
+                    $grouped = true;
2176
+                    break;
2177
+                }
2178
+            }
2179
+
2180
+            if (!$grouped) {
2181
+                $result[] = $item;
2182
+            }
2183
+
2184
+        }
2185
+
2186
+        return $result;
2187
+    }
2188
+
2189
+    /**
2190
+     * Put shared item into the database
2191
+     * @param string $itemType Item type
2192
+     * @param string $itemSource Item source
2193
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
2194
+     * @param string $shareWith User or group the item is being shared with
2195
+     * @param string $uidOwner User that is the owner of shared item
2196
+     * @param int $permissions CRUDS permissions
2197
+     * @param boolean|array $parentFolder Parent folder target (optional)
2198
+     * @param string $token (optional)
2199
+     * @param string $itemSourceName name of the source item (optional)
2200
+     * @param \DateTime $expirationDate (optional)
2201
+     * @throws \Exception
2202
+     * @return mixed id of the new share or false
2203
+     */
2204
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2205
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
2206
+
2207
+        $queriesToExecute = array();
2208
+        $suggestedItemTarget = null;
2209
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
2210
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
2211
+
2212
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
2213
+        if(!empty($result)) {
2214
+            $parent = $result['parent'];
2215
+            $itemSource = $result['itemSource'];
2216
+            $fileSource = $result['fileSource'];
2217
+            $suggestedItemTarget = $result['suggestedItemTarget'];
2218
+            $suggestedFileTarget = $result['suggestedFileTarget'];
2219
+            $filePath = $result['filePath'];
2220
+        }
2221
+
2222
+        $isGroupShare = false;
2223
+        if ($shareType == self::SHARE_TYPE_GROUP) {
2224
+            $isGroupShare = true;
2225
+            if (isset($shareWith['users'])) {
2226
+                $users = $shareWith['users'];
2227
+            } else {
2228
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
2229
+                if ($group) {
2230
+                    $users = $group->searchUsers('', -1, 0);
2231
+                    $userIds = [];
2232
+                    foreach ($users as $user) {
2233
+                        $userIds[] = $user->getUID();
2234
+                    }
2235
+                    $users = $userIds;
2236
+                } else {
2237
+                    $users = [];
2238
+                }
2239
+            }
2240
+            // remove current user from list
2241
+            if (in_array(\OCP\User::getUser(), $users)) {
2242
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
2243
+            }
2244
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
2245
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
2246
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
2247
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
2248
+
2249
+            // add group share to table and remember the id as parent
2250
+            $queriesToExecute['groupShare'] = array(
2251
+                'itemType'			=> $itemType,
2252
+                'itemSource'		=> $itemSource,
2253
+                'itemTarget'		=> $groupItemTarget,
2254
+                'shareType'			=> $shareType,
2255
+                'shareWith'			=> $shareWith['group'],
2256
+                'uidOwner'			=> $uidOwner,
2257
+                'permissions'		=> $permissions,
2258
+                'shareTime'			=> time(),
2259
+                'fileSource'		=> $fileSource,
2260
+                'fileTarget'		=> $groupFileTarget,
2261
+                'token'				=> $token,
2262
+                'parent'			=> $parent,
2263
+                'expiration'		=> $expirationDate,
2264
+            );
2265
+
2266
+        } else {
2267
+            $users = array($shareWith);
2268
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2269
+                $suggestedItemTarget);
2270
+        }
2271
+
2272
+        $run = true;
2273
+        $error = '';
2274
+        $preHookData = array(
2275
+            'itemType' => $itemType,
2276
+            'itemSource' => $itemSource,
2277
+            'shareType' => $shareType,
2278
+            'uidOwner' => $uidOwner,
2279
+            'permissions' => $permissions,
2280
+            'fileSource' => $fileSource,
2281
+            'expiration' => $expirationDate,
2282
+            'token' => $token,
2283
+            'run' => &$run,
2284
+            'error' => &$error
2285
+        );
2286
+
2287
+        $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2288
+        $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2289
+
2290
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
2291
+
2292
+        if ($run === false) {
2293
+            throw new \Exception($error);
2294
+        }
2295
+
2296
+        foreach ($users as $user) {
2297
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
2298
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
2299
+
2300
+            $userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
2301
+
2302
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
2303
+                $fileTarget = $sourceExists['file_target'];
2304
+                $itemTarget = $sourceExists['item_target'];
2305
+
2306
+                // for group shares we don't need a additional entry if the target is the same
2307
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
2308
+                    continue;
2309
+                }
2310
+
2311
+            } elseif(!$sourceExists && !$isGroupShare)  {
2312
+
2313
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
2314
+                    $uidOwner, $suggestedItemTarget, $parent);
2315
+                if (isset($fileSource)) {
2316
+                    if ($parentFolder) {
2317
+                        if ($parentFolder === true) {
2318
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
2319
+                                $uidOwner, $suggestedFileTarget, $parent);
2320
+                            if ($fileTarget != $groupFileTarget) {
2321
+                                $parentFolders[$user]['folder'] = $fileTarget;
2322
+                            }
2323
+                        } else if (isset($parentFolder[$user])) {
2324
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
2325
+                            $parent = $parentFolder[$user]['id'];
2326
+                        }
2327
+                    } else {
2328
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
2329
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
2330
+                    }
2331
+                } else {
2332
+                    $fileTarget = null;
2333
+                }
2334
+
2335
+            } else {
2336
+
2337
+                // group share which doesn't exists until now, check if we need a unique target for this user
2338
+
2339
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
2340
+                    $uidOwner, $suggestedItemTarget, $parent);
2341
+
2342
+                // do we also need a file target
2343
+                if (isset($fileSource)) {
2344
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
2345
+                        $uidOwner, $suggestedFileTarget, $parent);
2346
+                } else {
2347
+                    $fileTarget = null;
2348
+                }
2349
+
2350
+                if (($itemTarget === $groupItemTarget) &&
2351
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
2352
+                    continue;
2353
+                }
2354
+            }
2355
+
2356
+            $queriesToExecute[] = array(
2357
+                'itemType'			=> $itemType,
2358
+                'itemSource'		=> $itemSource,
2359
+                'itemTarget'		=> $itemTarget,
2360
+                'shareType'			=> $userShareType,
2361
+                'shareWith'			=> $user,
2362
+                'uidOwner'			=> $uidOwner,
2363
+                'permissions'		=> $permissions,
2364
+                'shareTime'			=> time(),
2365
+                'fileSource'		=> $fileSource,
2366
+                'fileTarget'		=> $fileTarget,
2367
+                'token'				=> $token,
2368
+                'parent'			=> $parent,
2369
+                'expiration'		=> $expirationDate,
2370
+            );
2371
+
2372
+        }
2373
+
2374
+        $id = false;
2375
+        if ($isGroupShare) {
2376
+            $id = self::insertShare($queriesToExecute['groupShare']);
2377
+            // Save this id, any extra rows for this group share will need to reference it
2378
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2379
+            unset($queriesToExecute['groupShare']);
2380
+        }
2381
+
2382
+        foreach ($queriesToExecute as $shareQuery) {
2383
+            $shareQuery['parent'] = $parent;
2384
+            $id = self::insertShare($shareQuery);
2385
+        }
2386
+
2387
+        $postHookData = array(
2388
+            'itemType' => $itemType,
2389
+            'itemSource' => $itemSource,
2390
+            'parent' => $parent,
2391
+            'shareType' => $shareType,
2392
+            'uidOwner' => $uidOwner,
2393
+            'permissions' => $permissions,
2394
+            'fileSource' => $fileSource,
2395
+            'id' => $parent,
2396
+            'token' => $token,
2397
+            'expirationDate' => $expirationDate,
2398
+        );
2399
+
2400
+        $postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2401
+        $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2402
+        $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
2403
+
2404
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
2405
+
2406
+
2407
+        return $id ? $id : false;
2408
+    }
2409
+
2410
+    /**
2411
+     * @param string $itemType
2412
+     * @param string $itemSource
2413
+     * @param int $shareType
2414
+     * @param string $shareWith
2415
+     * @param string $uidOwner
2416
+     * @param int $permissions
2417
+     * @param string|null $itemSourceName
2418
+     * @param null|\DateTime $expirationDate
2419
+     */
2420
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
2421
+        $backend = self::getBackend($itemType);
2422
+
2423
+        $l = \OC::$server->getL10N('lib');
2424
+        $result = array();
2425
+
2426
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
2427
+
2428
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
2429
+        if ($checkReshare) {
2430
+            // Check if attempting to share back to owner
2431
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
2432
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
2433
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
2434
+
2435
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
2436
+                throw new \Exception($message_t);
2437
+            }
2438
+        }
2439
+
2440
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
2441
+            // Check if share permissions is granted
2442
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
2443
+                if (~(int)$checkReshare['permissions'] & $permissions) {
2444
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
2445
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
2446
+
2447
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
2448
+                    throw new \Exception($message_t);
2449
+                } else {
2450
+                    // TODO Don't check if inside folder
2451
+                    $result['parent'] = $checkReshare['id'];
2452
+
2453
+                    $result['expirationDate'] = $expirationDate;
2454
+                    // $checkReshare['expiration'] could be null and then is always less than any value
2455
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
2456
+                        $result['expirationDate'] = $checkReshare['expiration'];
2457
+                    }
2458
+
2459
+                    // only suggest the same name as new target if it is a reshare of the
2460
+                    // same file/folder and not the reshare of a child
2461
+                    if ($checkReshare[$column] === $itemSource) {
2462
+                        $result['filePath'] = $checkReshare['file_target'];
2463
+                        $result['itemSource'] = $checkReshare['item_source'];
2464
+                        $result['fileSource'] = $checkReshare['file_source'];
2465
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
2466
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
2467
+                    } else {
2468
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
2469
+                        $result['suggestedItemTarget'] = null;
2470
+                        $result['suggestedFileTarget'] = null;
2471
+                        $result['itemSource'] = $itemSource;
2472
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
2473
+                    }
2474
+                }
2475
+            } else {
2476
+                $message = 'Sharing %s failed, because resharing is not allowed';
2477
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
2478
+
2479
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
2480
+                throw new \Exception($message_t);
2481
+            }
2482
+        } else {
2483
+            $result['parent'] = null;
2484
+            $result['suggestedItemTarget'] = null;
2485
+            $result['suggestedFileTarget'] = null;
2486
+            $result['itemSource'] = $itemSource;
2487
+            $result['expirationDate'] = $expirationDate;
2488
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
2489
+                $message = 'Sharing %s failed, because the sharing backend for '
2490
+                    .'%s could not find its source';
2491
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
2492
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
2493
+                throw new \Exception($message_t);
2494
+            }
2495
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2496
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
2497
+                if ($itemType == 'file' || $itemType == 'folder') {
2498
+                    $result['fileSource'] = $itemSource;
2499
+                } else {
2500
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
2501
+                    $result['fileSource'] = $meta['fileid'];
2502
+                }
2503
+                if ($result['fileSource'] == -1) {
2504
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
2505
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
2506
+
2507
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
2508
+                    throw new \Exception($message_t);
2509
+                }
2510
+            } else {
2511
+                $result['filePath'] = null;
2512
+                $result['fileSource'] = null;
2513
+            }
2514
+        }
2515
+
2516
+        return $result;
2517
+    }
2518
+
2519
+    /**
2520
+     *
2521
+     * @param array $shareData
2522
+     * @return mixed false in case of a failure or the id of the new share
2523
+     */
2524
+    private static function insertShare(array $shareData) {
2525
+
2526
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
2527
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
2528
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
2529
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
2530
+        $query->bindValue(1, $shareData['itemType']);
2531
+        $query->bindValue(2, $shareData['itemSource']);
2532
+        $query->bindValue(3, $shareData['itemTarget']);
2533
+        $query->bindValue(4, $shareData['shareType']);
2534
+        $query->bindValue(5, $shareData['shareWith']);
2535
+        $query->bindValue(6, $shareData['uidOwner']);
2536
+        $query->bindValue(7, $shareData['permissions']);
2537
+        $query->bindValue(8, $shareData['shareTime']);
2538
+        $query->bindValue(9, $shareData['fileSource']);
2539
+        $query->bindValue(10, $shareData['fileTarget']);
2540
+        $query->bindValue(11, $shareData['token']);
2541
+        $query->bindValue(12, $shareData['parent']);
2542
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
2543
+        $result = $query->execute();
2544
+
2545
+        $id = false;
2546
+        if ($result) {
2547
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2548
+        }
2549
+
2550
+        return $id;
2551
+
2552
+    }
2553
+
2554
+    /**
2555
+     * Delete all shares with type SHARE_TYPE_LINK
2556
+     */
2557
+    public static function removeAllLinkShares() {
2558
+        // Delete any link shares
2559
+        $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
2560
+        $result = $query->execute(array(self::SHARE_TYPE_LINK));
2561
+        while ($item = $result->fetchRow()) {
2562
+            Helper::delete($item['id']);
2563
+        }
2564
+    }
2565
+
2566
+    /**
2567
+     * In case a password protected link is not yet authenticated this function will return false
2568
+     *
2569
+     * @param array $linkItem
2570
+     * @return boolean
2571
+     */
2572
+    public static function checkPasswordProtectedShare(array $linkItem) {
2573
+        if (!isset($linkItem['share_with'])) {
2574
+            return true;
2575
+        }
2576
+        if (!isset($linkItem['share_type'])) {
2577
+            return true;
2578
+        }
2579
+        if (!isset($linkItem['id'])) {
2580
+            return true;
2581
+        }
2582
+
2583
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
2584
+            return true;
2585
+        }
2586
+
2587
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
2588
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
2589
+            return true;
2590
+        }
2591
+
2592
+        return false;
2593
+    }
2594
+
2595
+    /**
2596
+     * construct select statement
2597
+     * @param int $format
2598
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
2599
+     * @param string $uidOwner
2600
+     * @return string select statement
2601
+     */
2602
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
2603
+        $select = '*';
2604
+        if ($format == self::FORMAT_STATUSES) {
2605
+            if ($fileDependent) {
2606
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
2607
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
2608
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2609
+                    . '`uid_initiator`';
2610
+            } else {
2611
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
2612
+            }
2613
+        } else {
2614
+            if (isset($uidOwner)) {
2615
+                if ($fileDependent) {
2616
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
2617
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
2618
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
2619
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2620
+                } else {
2621
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
2622
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
2623
+                }
2624
+            } else {
2625
+                if ($fileDependent) {
2626
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
2627
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
2628
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
2629
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2630
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
2631
+                    } else {
2632
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
2633
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
2634
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
2635
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
2636
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2637
+                    }
2638
+                }
2639
+            }
2640
+        }
2641
+        return $select;
2642
+    }
2643
+
2644
+
2645
+    /**
2646
+     * transform db results
2647
+     * @param array $row result
2648
+     */
2649
+    private static function transformDBResults(&$row) {
2650
+        if (isset($row['id'])) {
2651
+            $row['id'] = (int) $row['id'];
2652
+        }
2653
+        if (isset($row['share_type'])) {
2654
+            $row['share_type'] = (int) $row['share_type'];
2655
+        }
2656
+        if (isset($row['parent'])) {
2657
+            $row['parent'] = (int) $row['parent'];
2658
+        }
2659
+        if (isset($row['file_parent'])) {
2660
+            $row['file_parent'] = (int) $row['file_parent'];
2661
+        }
2662
+        if (isset($row['file_source'])) {
2663
+            $row['file_source'] = (int) $row['file_source'];
2664
+        }
2665
+        if (isset($row['permissions'])) {
2666
+            $row['permissions'] = (int) $row['permissions'];
2667
+        }
2668
+        if (isset($row['storage'])) {
2669
+            $row['storage'] = (int) $row['storage'];
2670
+        }
2671
+        if (isset($row['stime'])) {
2672
+            $row['stime'] = (int) $row['stime'];
2673
+        }
2674
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2675
+            // discard expiration date for non-link shares, which might have been
2676
+            // set by ancient bugs
2677
+            $row['expiration'] = null;
2678
+        }
2679
+    }
2680
+
2681
+    /**
2682
+     * format result
2683
+     * @param array $items result
2684
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2685
+     * @param \OCP\Share_Backend $backend sharing backend
2686
+     * @param int $format
2687
+     * @param array $parameters additional format parameters
2688
+     * @return array format result
2689
+     */
2690
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2691
+        if ($format === self::FORMAT_NONE) {
2692
+            return $items;
2693
+        } else if ($format === self::FORMAT_STATUSES) {
2694
+            $statuses = array();
2695
+            foreach ($items as $item) {
2696
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2697
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2698
+                        continue;
2699
+                    }
2700
+                    $statuses[$item[$column]]['link'] = true;
2701
+                } else if (!isset($statuses[$item[$column]])) {
2702
+                    $statuses[$item[$column]]['link'] = false;
2703
+                }
2704
+                if (!empty($item['file_target'])) {
2705
+                    $statuses[$item[$column]]['path'] = $item['path'];
2706
+                }
2707
+            }
2708
+            return $statuses;
2709
+        } else {
2710
+            return $backend->formatItems($items, $format, $parameters);
2711
+        }
2712
+    }
2713
+
2714
+    /**
2715
+     * remove protocol from URL
2716
+     *
2717
+     * @param string $url
2718
+     * @return string
2719
+     */
2720
+    public static function removeProtocolFromUrl($url) {
2721
+        if (strpos($url, 'https://') === 0) {
2722
+            return substr($url, strlen('https://'));
2723
+        } else if (strpos($url, 'http://') === 0) {
2724
+            return substr($url, strlen('http://'));
2725
+        }
2726
+
2727
+        return $url;
2728
+    }
2729
+
2730
+    /**
2731
+     * try http post first with https and then with http as a fallback
2732
+     *
2733
+     * @param string $remoteDomain
2734
+     * @param string $urlSuffix
2735
+     * @param array $fields post parameters
2736
+     * @return array
2737
+     */
2738
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2739
+        $protocol = 'https://';
2740
+        $result = [
2741
+            'success' => false,
2742
+            'result' => '',
2743
+        ];
2744
+        $try = 0;
2745
+        $discoveryManager = new DiscoveryManager(
2746
+            \OC::$server->getMemCacheFactory(),
2747
+            \OC::$server->getHTTPClientService()
2748
+        );
2749
+        while ($result['success'] === false && $try < 2) {
2750
+            $endpoint = $discoveryManager->getShareEndpoint($protocol . $remoteDomain);
2751
+            $result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2752
+            $try++;
2753
+            $protocol = 'http://';
2754
+        }
2755
+
2756
+        return $result;
2757
+    }
2758
+
2759
+    /**
2760
+     * send server-to-server share to remote server
2761
+     *
2762
+     * @param string $token
2763
+     * @param string $shareWith
2764
+     * @param string $name
2765
+     * @param int $remote_id
2766
+     * @param string $owner
2767
+     * @return bool
2768
+     */
2769
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2770
+
2771
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2772
+
2773
+        if ($user && $remote) {
2774
+            $url = $remote;
2775
+
2776
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2777
+
2778
+            $fields = array(
2779
+                'shareWith' => $user,
2780
+                'token' => $token,
2781
+                'name' => $name,
2782
+                'remoteId' => $remote_id,
2783
+                'owner' => $owner,
2784
+                'remote' => $local,
2785
+            );
2786
+
2787
+            $url = self::removeProtocolFromUrl($url);
2788
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2789
+            $status = json_decode($result['result'], true);
2790
+
2791
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2792
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2793
+                return true;
2794
+            }
2795
+
2796
+        }
2797
+
2798
+        return false;
2799
+    }
2800
+
2801
+    /**
2802
+     * send server-to-server unshare to remote server
2803
+     *
2804
+     * @param string $remote url
2805
+     * @param int $id share id
2806
+     * @param string $token
2807
+     * @return bool
2808
+     */
2809
+    private static function sendRemoteUnshare($remote, $id, $token) {
2810
+        $url = rtrim($remote, '/');
2811
+        $fields = array('token' => $token, 'format' => 'json');
2812
+        $url = self::removeProtocolFromUrl($url);
2813
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2814
+        $status = json_decode($result['result'], true);
2815
+
2816
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2817
+    }
2818
+
2819
+    /**
2820
+     * check if user can only share with group members
2821
+     * @return bool
2822
+     */
2823
+    public static function shareWithGroupMembersOnly() {
2824
+        $value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no');
2825
+        return ($value === 'yes') ? true : false;
2826
+    }
2827
+
2828
+    /**
2829
+     * @return bool
2830
+     */
2831
+    public static function isDefaultExpireDateEnabled() {
2832
+        $defaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
2833
+        return ($defaultExpireDateEnabled === "yes") ? true : false;
2834
+    }
2835
+
2836
+    /**
2837
+     * @return bool
2838
+     */
2839
+    public static function enforceDefaultExpireDate() {
2840
+        $enforceDefaultExpireDate = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2841
+        return ($enforceDefaultExpireDate === "yes") ? true : false;
2842
+    }
2843
+
2844
+    /**
2845
+     * @return int
2846
+     */
2847
+    public static function getExpireInterval() {
2848
+        return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
2849
+    }
2850
+
2851
+    /**
2852
+     * Checks whether the given path is reachable for the given owner
2853
+     *
2854
+     * @param string $path path relative to files
2855
+     * @param string $ownerStorageId storage id of the owner
2856
+     *
2857
+     * @return boolean true if file is reachable, false otherwise
2858
+     */
2859
+    private static function isFileReachable($path, $ownerStorageId) {
2860
+        // if outside the home storage, file is always considered reachable
2861
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2862
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2863
+        )) {
2864
+            return true;
2865
+        }
2866
+
2867
+        // if inside the home storage, the file has to be under "/files/"
2868
+        $path = ltrim($path, '/');
2869
+        if (substr($path, 0, 6) === 'files/') {
2870
+            return true;
2871
+        }
2872
+
2873
+        return false;
2874
+    }
2875
+
2876
+    /**
2877
+     * @param IConfig $config
2878
+     * @return bool
2879
+     */
2880
+    public static function enforcePassword(IConfig $config) {
2881
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2882
+        return ($enforcePassword === "yes") ? true : false;
2883
+    }
2884
+
2885
+    /**
2886
+     * Get all share entries, including non-unique group items
2887
+     *
2888
+     * @param string $owner
2889
+     * @return array
2890
+     */
2891
+    public static function getAllSharesForOwner($owner) {
2892
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2893
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2894
+        return $result->fetchAll();
2895
+    }
2896
+
2897
+    /**
2898
+     * Get all share entries, including non-unique group items for a file
2899
+     *
2900
+     * @param int $id
2901
+     * @return array
2902
+     */
2903
+    public static function getAllSharesForFileId($id) {
2904
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2905
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2906
+        return $result->fetchAll();
2907
+    }
2908
+
2909
+    /**
2910
+     * @param string $password
2911
+     * @throws \Exception
2912
+     */
2913
+    private static function verifyPassword($password) {
2914
+
2915
+        $accepted = true;
2916
+        $message = '';
2917
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2918
+            'password' => $password,
2919
+            'accepted' => &$accepted,
2920
+            'message' => &$message
2921
+        ]);
2922
+
2923
+        if (!$accepted) {
2924
+            throw new \Exception($message);
2925
+        }
2926
+    }
2927 2927
 }
Please login to merge, or discard this patch.