Completed
Pull Request — master (#3614)
by Björn
46:53 queued 31:40
created
lib/private/Share/Share.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -43,7 +43,6 @@
 block discarded – undo
43 43
 namespace OC\Share;
44 44
 
45 45
 use OC\Files\Filesystem;
46
-use OCA\FederatedFileSharing\DiscoveryManager;
47 46
 use OCP\DB\QueryBuilder\IQueryBuilder;
48 47
 use OCP\ILogger;
49 48
 use OCP\IUserManager;
Please login to merge, or discard this patch.
Indentation   +2836 added lines, -2836 removed lines patch added patch discarded remove patch
@@ -60,2873 +60,2873 @@
 block discarded – undo
60 60
  */
61 61
 class Share extends Constants {
62 62
 
63
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
64
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
65
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
66
-	 *
67
-	 * Check if permission is granted with And (&) e.g. Check if delete is
68
-	 * granted: if ($permissions & PERMISSION_DELETE)
69
-	 *
70
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
71
-	 * permission: $permissions &= ~PERMISSION_UPDATE
72
-	 *
73
-	 * Apps are required to handle permissions on their own, this class only
74
-	 * stores and manages the permissions of shares
75
-	 * @see lib/public/constants.php
76
-	 */
77
-
78
-	/**
79
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
80
-	 * @param string $itemType Item type
81
-	 * @param string $class Backend class
82
-	 * @param string $collectionOf (optional) Depends on item type
83
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
84
-	 * @return boolean true if backend is registered or false if error
85
-	 */
86
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
87
-		if (self::isEnabled()) {
88
-			if (!isset(self::$backendTypes[$itemType])) {
89
-				self::$backendTypes[$itemType] = array(
90
-					'class' => $class,
91
-					'collectionOf' => $collectionOf,
92
-					'supportedFileExtensions' => $supportedFileExtensions
93
-				);
94
-				if(count(self::$backendTypes) === 1) {
95
-					\OC_Util::addScript('core', 'shareconfigmodel');
96
-					\OC_Util::addScript('core', 'shareitemmodel');
97
-					\OC_Util::addScript('core', 'sharesocialmanager');
98
-					\OC_Util::addScript('core', 'sharedialogresharerinfoview');
99
-					\OC_Util::addScript('core', 'sharedialoglinkshareview');
100
-					\OC_Util::addScript('core', 'sharedialogexpirationview');
101
-					\OC_Util::addScript('core', 'sharedialogshareelistview');
102
-					\OC_Util::addScript('core', 'sharedialogview');
103
-					\OC_Util::addScript('core', 'share');
104
-					\OC_Util::addStyle('core', 'share');
105
-				}
106
-				return true;
107
-			}
108
-			\OCP\Util::writeLog('OCP\Share',
109
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
110
-				.' is already registered for '.$itemType,
111
-				\OCP\Util::WARN);
112
-		}
113
-		return false;
114
-	}
115
-
116
-	/**
117
-	 * Check if the Share API is enabled
118
-	 * @return boolean true if enabled or false
119
-	 *
120
-	 * The Share API is enabled by default if not configured
121
-	 */
122
-	public static function isEnabled() {
123
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
124
-			return true;
125
-		}
126
-		return false;
127
-	}
128
-
129
-	/**
130
-	 * Find which users can access a shared item
131
-	 * @param string $path to the file
132
-	 * @param string $ownerUser owner of the file
133
-	 * @param IUserManager $userManager
134
-	 * @param ILogger $logger
135
-	 * @param boolean $includeOwner include owner to the list of users with access to the file
136
-	 * @param boolean $returnUserPaths Return an array with the user => path map
137
-	 * @param boolean $recursive take all parent folders into account (default true)
138
-	 * @return array
139
-	 * @note $path needs to be relative to user data dir, e.g. 'file.txt'
140
-	 *       not '/admin/data/file.txt'
141
-	 * @throws \OC\User\NoUserException
142
-	 */
143
-	public static function getUsersSharingFile($path,
144
-											   $ownerUser,
145
-											   IUserManager $userManager,
146
-											   ILogger $logger,
147
-											   $includeOwner = false,
148
-											   $returnUserPaths = false,
149
-											   $recursive = true) {
150
-		$userObject = $userManager->get($ownerUser);
151
-
152
-		if (is_null($userObject)) {
153
-			$logger->error(
154
-				sprintf(
155
-					'Backends provided no user object for %s',
156
-					$ownerUser
157
-				),
158
-				[
159
-					'app' => 'files',
160
-				]
161
-			);
162
-			throw new \OC\User\NoUserException('Backends provided no user object');
163
-		}
164
-
165
-		$ownerUser = $userObject->getUID();
166
-
167
-		Filesystem::initMountPoints($ownerUser);
168
-		$shares = $sharePaths = $fileTargets = array();
169
-		$publicShare = false;
170
-		$remoteShare = false;
171
-		$source = -1;
172
-		$cache = $mountPath = false;
173
-
174
-		$view = new \OC\Files\View('/' . $ownerUser . '/files');
175
-		$meta = $view->getFileInfo($path);
176
-		if ($meta) {
177
-			$path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
178
-		} else {
179
-			// if the file doesn't exists yet we start with the parent folder
180
-			$meta = $view->getFileInfo(dirname($path));
181
-		}
182
-
183
-		if($meta !== false) {
184
-			$source = $meta['fileid'];
185
-			$cache = new \OC\Files\Cache\Cache($meta['storage']);
186
-
187
-			$mountPath = $meta->getMountPoint()->getMountPoint();
188
-			if ($mountPath !== false) {
189
-				$mountPath = substr($mountPath, strlen('/' . $ownerUser . '/files'));
190
-			}
191
-		}
192
-
193
-		$paths = [];
194
-		while ($source !== -1) {
195
-			// Fetch all shares with another user
196
-			if (!$returnUserPaths) {
197
-				$query = \OC_DB::prepare(
198
-					'SELECT `share_with`, `file_source`, `file_target`
63
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
64
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
65
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
66
+     *
67
+     * Check if permission is granted with And (&) e.g. Check if delete is
68
+     * granted: if ($permissions & PERMISSION_DELETE)
69
+     *
70
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
71
+     * permission: $permissions &= ~PERMISSION_UPDATE
72
+     *
73
+     * Apps are required to handle permissions on their own, this class only
74
+     * stores and manages the permissions of shares
75
+     * @see lib/public/constants.php
76
+     */
77
+
78
+    /**
79
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
80
+     * @param string $itemType Item type
81
+     * @param string $class Backend class
82
+     * @param string $collectionOf (optional) Depends on item type
83
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
84
+     * @return boolean true if backend is registered or false if error
85
+     */
86
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
87
+        if (self::isEnabled()) {
88
+            if (!isset(self::$backendTypes[$itemType])) {
89
+                self::$backendTypes[$itemType] = array(
90
+                    'class' => $class,
91
+                    'collectionOf' => $collectionOf,
92
+                    'supportedFileExtensions' => $supportedFileExtensions
93
+                );
94
+                if(count(self::$backendTypes) === 1) {
95
+                    \OC_Util::addScript('core', 'shareconfigmodel');
96
+                    \OC_Util::addScript('core', 'shareitemmodel');
97
+                    \OC_Util::addScript('core', 'sharesocialmanager');
98
+                    \OC_Util::addScript('core', 'sharedialogresharerinfoview');
99
+                    \OC_Util::addScript('core', 'sharedialoglinkshareview');
100
+                    \OC_Util::addScript('core', 'sharedialogexpirationview');
101
+                    \OC_Util::addScript('core', 'sharedialogshareelistview');
102
+                    \OC_Util::addScript('core', 'sharedialogview');
103
+                    \OC_Util::addScript('core', 'share');
104
+                    \OC_Util::addStyle('core', 'share');
105
+                }
106
+                return true;
107
+            }
108
+            \OCP\Util::writeLog('OCP\Share',
109
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
110
+                .' is already registered for '.$itemType,
111
+                \OCP\Util::WARN);
112
+        }
113
+        return false;
114
+    }
115
+
116
+    /**
117
+     * Check if the Share API is enabled
118
+     * @return boolean true if enabled or false
119
+     *
120
+     * The Share API is enabled by default if not configured
121
+     */
122
+    public static function isEnabled() {
123
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
124
+            return true;
125
+        }
126
+        return false;
127
+    }
128
+
129
+    /**
130
+     * Find which users can access a shared item
131
+     * @param string $path to the file
132
+     * @param string $ownerUser owner of the file
133
+     * @param IUserManager $userManager
134
+     * @param ILogger $logger
135
+     * @param boolean $includeOwner include owner to the list of users with access to the file
136
+     * @param boolean $returnUserPaths Return an array with the user => path map
137
+     * @param boolean $recursive take all parent folders into account (default true)
138
+     * @return array
139
+     * @note $path needs to be relative to user data dir, e.g. 'file.txt'
140
+     *       not '/admin/data/file.txt'
141
+     * @throws \OC\User\NoUserException
142
+     */
143
+    public static function getUsersSharingFile($path,
144
+                                                $ownerUser,
145
+                                                IUserManager $userManager,
146
+                                                ILogger $logger,
147
+                                                $includeOwner = false,
148
+                                                $returnUserPaths = false,
149
+                                                $recursive = true) {
150
+        $userObject = $userManager->get($ownerUser);
151
+
152
+        if (is_null($userObject)) {
153
+            $logger->error(
154
+                sprintf(
155
+                    'Backends provided no user object for %s',
156
+                    $ownerUser
157
+                ),
158
+                [
159
+                    'app' => 'files',
160
+                ]
161
+            );
162
+            throw new \OC\User\NoUserException('Backends provided no user object');
163
+        }
164
+
165
+        $ownerUser = $userObject->getUID();
166
+
167
+        Filesystem::initMountPoints($ownerUser);
168
+        $shares = $sharePaths = $fileTargets = array();
169
+        $publicShare = false;
170
+        $remoteShare = false;
171
+        $source = -1;
172
+        $cache = $mountPath = false;
173
+
174
+        $view = new \OC\Files\View('/' . $ownerUser . '/files');
175
+        $meta = $view->getFileInfo($path);
176
+        if ($meta) {
177
+            $path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
178
+        } else {
179
+            // if the file doesn't exists yet we start with the parent folder
180
+            $meta = $view->getFileInfo(dirname($path));
181
+        }
182
+
183
+        if($meta !== false) {
184
+            $source = $meta['fileid'];
185
+            $cache = new \OC\Files\Cache\Cache($meta['storage']);
186
+
187
+            $mountPath = $meta->getMountPoint()->getMountPoint();
188
+            if ($mountPath !== false) {
189
+                $mountPath = substr($mountPath, strlen('/' . $ownerUser . '/files'));
190
+            }
191
+        }
192
+
193
+        $paths = [];
194
+        while ($source !== -1) {
195
+            // Fetch all shares with another user
196
+            if (!$returnUserPaths) {
197
+                $query = \OC_DB::prepare(
198
+                    'SELECT `share_with`, `file_source`, `file_target`
199 199
 					FROM
200 200
 					`*PREFIX*share`
201 201
 					WHERE
202 202
 					`item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
203
-				);
204
-				$result = $query->execute(array($source, self::SHARE_TYPE_USER));
205
-			} else {
206
-				$query = \OC_DB::prepare(
207
-					'SELECT `share_with`, `file_source`, `file_target`
203
+                );
204
+                $result = $query->execute(array($source, self::SHARE_TYPE_USER));
205
+            } else {
206
+                $query = \OC_DB::prepare(
207
+                    'SELECT `share_with`, `file_source`, `file_target`
208 208
 				FROM
209 209
 				`*PREFIX*share`
210 210
 				WHERE
211 211
 				`item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')'
212
-				);
213
-				$result = $query->execute(array($source, self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique));
214
-			}
215
-
216
-			if (\OCP\DB::isError($result)) {
217
-				\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
218
-			} else {
219
-				while ($row = $result->fetchRow()) {
220
-					$shares[] = $row['share_with'];
221
-					if ($returnUserPaths) {
222
-						$fileTargets[(int) $row['file_source']][$row['share_with']] = $row;
223
-					}
224
-				}
225
-			}
226
-
227
-			// We also need to take group shares into account
228
-			$query = \OC_DB::prepare(
229
-				'SELECT `share_with`, `file_source`, `file_target`
212
+                );
213
+                $result = $query->execute(array($source, self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique));
214
+            }
215
+
216
+            if (\OCP\DB::isError($result)) {
217
+                \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
218
+            } else {
219
+                while ($row = $result->fetchRow()) {
220
+                    $shares[] = $row['share_with'];
221
+                    if ($returnUserPaths) {
222
+                        $fileTargets[(int) $row['file_source']][$row['share_with']] = $row;
223
+                    }
224
+                }
225
+            }
226
+
227
+            // We also need to take group shares into account
228
+            $query = \OC_DB::prepare(
229
+                'SELECT `share_with`, `file_source`, `file_target`
230 230
 				FROM
231 231
 				`*PREFIX*share`
232 232
 				WHERE
233 233
 				`item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
234
-			);
235
-
236
-			$result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
237
-
238
-			if (\OCP\DB::isError($result)) {
239
-				\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
240
-			} else {
241
-				$groupManager = \OC::$server->getGroupManager();
242
-				while ($row = $result->fetchRow()) {
243
-
244
-					$usersInGroup = [];
245
-					$group = $groupManager->get($row['share_with']);
246
-					if ($group) {
247
-						$users = $group->searchUsers('', -1, 0);
248
-						$userIds = array();
249
-						foreach ($users as $user) {
250
-							$userIds[] = $user->getUID();
251
-						}
252
-						$usersInGroup = $userIds;
253
-					}
254
-					$shares = array_merge($shares, $usersInGroup);
255
-					if ($returnUserPaths) {
256
-						foreach ($usersInGroup as $user) {
257
-							if (!isset($fileTargets[(int) $row['file_source']][$user])) {
258
-								// When the user already has an entry for this file source
259
-								// the file is either shared directly with him as well, or
260
-								// he has an exception entry (because of naming conflict).
261
-								$fileTargets[(int) $row['file_source']][$user] = $row;
262
-							}
263
-						}
264
-					}
265
-				}
266
-			}
267
-
268
-			//check for public link shares
269
-			if (!$publicShare) {
270
-				$query = \OC_DB::prepare('
234
+            );
235
+
236
+            $result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
237
+
238
+            if (\OCP\DB::isError($result)) {
239
+                \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
240
+            } else {
241
+                $groupManager = \OC::$server->getGroupManager();
242
+                while ($row = $result->fetchRow()) {
243
+
244
+                    $usersInGroup = [];
245
+                    $group = $groupManager->get($row['share_with']);
246
+                    if ($group) {
247
+                        $users = $group->searchUsers('', -1, 0);
248
+                        $userIds = array();
249
+                        foreach ($users as $user) {
250
+                            $userIds[] = $user->getUID();
251
+                        }
252
+                        $usersInGroup = $userIds;
253
+                    }
254
+                    $shares = array_merge($shares, $usersInGroup);
255
+                    if ($returnUserPaths) {
256
+                        foreach ($usersInGroup as $user) {
257
+                            if (!isset($fileTargets[(int) $row['file_source']][$user])) {
258
+                                // When the user already has an entry for this file source
259
+                                // the file is either shared directly with him as well, or
260
+                                // he has an exception entry (because of naming conflict).
261
+                                $fileTargets[(int) $row['file_source']][$user] = $row;
262
+                            }
263
+                        }
264
+                    }
265
+                }
266
+            }
267
+
268
+            //check for public link shares
269
+            if (!$publicShare) {
270
+                $query = \OC_DB::prepare('
271 271
 					SELECT `share_with`
272 272
 					FROM `*PREFIX*share`
273 273
 					WHERE `item_source` = ? AND `share_type` IN (?, ?) AND `item_type` IN (\'file\', \'folder\')', 1
274
-				);
275
-
276
-				$result = $query->execute(array($source, self::SHARE_TYPE_LINK, self::SHARE_TYPE_EMAIL));
277
-
278
-				if (\OCP\DB::isError($result)) {
279
-					\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
280
-				} else {
281
-					if ($result->fetchRow()) {
282
-						$publicShare = true;
283
-					}
284
-				}
285
-			}
286
-
287
-			//check for remote share
288
-			if (!$remoteShare) {
289
-				$query = \OC_DB::prepare('
274
+                );
275
+
276
+                $result = $query->execute(array($source, self::SHARE_TYPE_LINK, self::SHARE_TYPE_EMAIL));
277
+
278
+                if (\OCP\DB::isError($result)) {
279
+                    \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
280
+                } else {
281
+                    if ($result->fetchRow()) {
282
+                        $publicShare = true;
283
+                    }
284
+                }
285
+            }
286
+
287
+            //check for remote share
288
+            if (!$remoteShare) {
289
+                $query = \OC_DB::prepare('
290 290
 					SELECT `share_with`
291 291
 					FROM `*PREFIX*share`
292 292
 					WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1
293
-				);
294
-
295
-				$result = $query->execute(array($source, self::SHARE_TYPE_REMOTE));
296
-
297
-				if (\OCP\DB::isError($result)) {
298
-					\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
299
-				} else {
300
-					if ($result->fetchRow()) {
301
-						$remoteShare = true;
302
-					}
303
-				}
304
-			}
305
-
306
-			// let's get the parent for the next round
307
-			$meta = $cache->get((int)$source);
308
-			if ($recursive === true && $meta !== false) {
309
-				$paths[$source] = $meta['path'];
310
-				$source = (int)$meta['parent'];
311
-			} else {
312
-				$source = -1;
313
-			}
314
-		}
315
-
316
-		// Include owner in list of users, if requested
317
-		if ($includeOwner) {
318
-			$shares[] = $ownerUser;
319
-		}
320
-
321
-		if ($returnUserPaths) {
322
-			$fileTargetIDs = array_keys($fileTargets);
323
-			$fileTargetIDs = array_unique($fileTargetIDs);
324
-
325
-			if (!empty($fileTargetIDs)) {
326
-				$query = \OC_DB::prepare(
327
-					'SELECT `fileid`, `path`
293
+                );
294
+
295
+                $result = $query->execute(array($source, self::SHARE_TYPE_REMOTE));
296
+
297
+                if (\OCP\DB::isError($result)) {
298
+                    \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
299
+                } else {
300
+                    if ($result->fetchRow()) {
301
+                        $remoteShare = true;
302
+                    }
303
+                }
304
+            }
305
+
306
+            // let's get the parent for the next round
307
+            $meta = $cache->get((int)$source);
308
+            if ($recursive === true && $meta !== false) {
309
+                $paths[$source] = $meta['path'];
310
+                $source = (int)$meta['parent'];
311
+            } else {
312
+                $source = -1;
313
+            }
314
+        }
315
+
316
+        // Include owner in list of users, if requested
317
+        if ($includeOwner) {
318
+            $shares[] = $ownerUser;
319
+        }
320
+
321
+        if ($returnUserPaths) {
322
+            $fileTargetIDs = array_keys($fileTargets);
323
+            $fileTargetIDs = array_unique($fileTargetIDs);
324
+
325
+            if (!empty($fileTargetIDs)) {
326
+                $query = \OC_DB::prepare(
327
+                    'SELECT `fileid`, `path`
328 328
 					FROM `*PREFIX*filecache`
329 329
 					WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'
330
-				);
331
-				$result = $query->execute();
332
-
333
-				if (\OCP\DB::isError($result)) {
334
-					\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
335
-				} else {
336
-					while ($row = $result->fetchRow()) {
337
-						foreach ($fileTargets[$row['fileid']] as $uid => $shareData) {
338
-							if ($mountPath !== false) {
339
-								$sharedPath = $shareData['file_target'];
340
-								$sharedPath .= substr($path, strlen($mountPath) + strlen($paths[$row['fileid']]));
341
-								$sharePaths[$uid] = $sharedPath;
342
-							} else {
343
-								$sharedPath = $shareData['file_target'];
344
-								$sharedPath .= substr($path, strlen($row['path']) -5);
345
-								$sharePaths[$uid] = $sharedPath;
346
-							}
347
-						}
348
-					}
349
-				}
350
-			}
351
-
352
-			if ($includeOwner) {
353
-				$sharePaths[$ownerUser] = $path;
354
-			} else {
355
-				unset($sharePaths[$ownerUser]);
356
-			}
357
-
358
-			return $sharePaths;
359
-		}
360
-
361
-		return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare);
362
-	}
363
-
364
-	/**
365
-	 * Get the items of item type shared with the current user
366
-	 * @param string $itemType
367
-	 * @param int $format (optional) Format type must be defined by the backend
368
-	 * @param mixed $parameters (optional)
369
-	 * @param int $limit Number of items to return (optional) Returns all by default
370
-	 * @param boolean $includeCollections (optional)
371
-	 * @return mixed Return depends on format
372
-	 */
373
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
374
-											  $parameters = null, $limit = -1, $includeCollections = false) {
375
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
376
-			$parameters, $limit, $includeCollections);
377
-	}
378
-
379
-	/**
380
-	 * Get the items of item type shared with a user
381
-	 * @param string $itemType
382
-	 * @param string $user id for which user we want the shares
383
-	 * @param int $format (optional) Format type must be defined by the backend
384
-	 * @param mixed $parameters (optional)
385
-	 * @param int $limit Number of items to return (optional) Returns all by default
386
-	 * @param boolean $includeCollections (optional)
387
-	 * @return mixed Return depends on format
388
-	 */
389
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
390
-												  $parameters = null, $limit = -1, $includeCollections = false) {
391
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
392
-			$parameters, $limit, $includeCollections);
393
-	}
394
-
395
-	/**
396
-	 * Get the item of item type shared with the current user
397
-	 * @param string $itemType
398
-	 * @param string $itemTarget
399
-	 * @param int $format (optional) Format type must be defined by the backend
400
-	 * @param mixed $parameters (optional)
401
-	 * @param boolean $includeCollections (optional)
402
-	 * @return mixed Return depends on format
403
-	 */
404
-	public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
405
-											 $parameters = null, $includeCollections = false) {
406
-		return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
407
-			$parameters, 1, $includeCollections);
408
-	}
409
-
410
-	/**
411
-	 * Get the item of item type shared with a given user by source
412
-	 * @param string $itemType
413
-	 * @param string $itemSource
414
-	 * @param string $user User to whom the item was shared
415
-	 * @param string $owner Owner of the share
416
-	 * @param int $shareType only look for a specific share type
417
-	 * @return array Return list of items with file_target, permissions and expiration
418
-	 */
419
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
420
-		$shares = array();
421
-		$fileDependent = false;
422
-
423
-		$where = 'WHERE';
424
-		$fileDependentWhere = '';
425
-		if ($itemType === 'file' || $itemType === 'folder') {
426
-			$fileDependent = true;
427
-			$column = 'file_source';
428
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
429
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
430
-		} else {
431
-			$column = 'item_source';
432
-		}
433
-
434
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
435
-
436
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
437
-		$arguments = array($itemSource, $itemType);
438
-		// for link shares $user === null
439
-		if ($user !== null) {
440
-			$where .= ' AND `share_with` = ? ';
441
-			$arguments[] = $user;
442
-		}
443
-
444
-		if ($shareType !== null) {
445
-			$where .= ' AND `share_type` = ? ';
446
-			$arguments[] = $shareType;
447
-		}
448
-
449
-		if ($owner !== null) {
450
-			$where .= ' AND `uid_owner` = ? ';
451
-			$arguments[] = $owner;
452
-		}
453
-
454
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
455
-
456
-		$result = \OC_DB::executeAudited($query, $arguments);
457
-
458
-		while ($row = $result->fetchRow()) {
459
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
460
-				continue;
461
-			}
462
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
463
-				// if it is a mount point we need to get the path from the mount manager
464
-				$mountManager = \OC\Files\Filesystem::getMountManager();
465
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
466
-				if (!empty($mountPoint)) {
467
-					$path = $mountPoint[0]->getMountPoint();
468
-					$path = trim($path, '/');
469
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
470
-					$row['path'] = $path;
471
-				} else {
472
-					\OC::$server->getLogger()->warning(
473
-						'Could not resolve mount point for ' . $row['storage_id'],
474
-						['app' => 'OCP\Share']
475
-					);
476
-				}
477
-			}
478
-			$shares[] = $row;
479
-		}
480
-
481
-		//if didn't found a result than let's look for a group share.
482
-		if(empty($shares) && $user !== null) {
483
-			$userObject = \OC::$server->getUserManager()->get($user);
484
-			$groups = [];
485
-			if ($userObject) {
486
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
487
-			}
488
-
489
-			if (!empty($groups)) {
490
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
491
-				$arguments = array($itemSource, $itemType, $groups);
492
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
493
-
494
-				if ($owner !== null) {
495
-					$where .= ' AND `uid_owner` = ?';
496
-					$arguments[] = $owner;
497
-					$types[] = null;
498
-				}
499
-
500
-				// TODO: inject connection, hopefully one day in the future when this
501
-				// class isn't static anymore...
502
-				$conn = \OC::$server->getDatabaseConnection();
503
-				$result = $conn->executeQuery(
504
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
505
-					$arguments,
506
-					$types
507
-				);
508
-
509
-				while ($row = $result->fetch()) {
510
-					$shares[] = $row;
511
-				}
512
-			}
513
-		}
514
-
515
-		return $shares;
516
-
517
-	}
518
-
519
-	/**
520
-	 * Get the item of item type shared with the current user by source
521
-	 * @param string $itemType
522
-	 * @param string $itemSource
523
-	 * @param int $format (optional) Format type must be defined by the backend
524
-	 * @param mixed $parameters
525
-	 * @param boolean $includeCollections
526
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
527
-	 * @return array
528
-	 */
529
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
530
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
531
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
532
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
533
-			$parameters, 1, $includeCollections, true);
534
-	}
535
-
536
-	/**
537
-	 * Get the item of item type shared by a link
538
-	 * @param string $itemType
539
-	 * @param string $itemSource
540
-	 * @param string $uidOwner Owner of link
541
-	 * @return array
542
-	 */
543
-	public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
544
-		return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
545
-			null, 1);
546
-	}
547
-
548
-	/**
549
-	 * Based on the given token the share information will be returned - password protected shares will be verified
550
-	 * @param string $token
551
-	 * @param bool $checkPasswordProtection
552
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
553
-	 */
554
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
555
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
556
-		$result = $query->execute(array($token));
557
-		if ($result === false) {
558
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
559
-		}
560
-		$row = $result->fetchRow();
561
-		if ($row === false) {
562
-			return false;
563
-		}
564
-		if (is_array($row) and self::expireItem($row)) {
565
-			return false;
566
-		}
567
-
568
-		// password protected shares need to be authenticated
569
-		if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
570
-			return false;
571
-		}
572
-
573
-		return $row;
574
-	}
575
-
576
-	/**
577
-	 * resolves reshares down to the last real share
578
-	 * @param array $linkItem
579
-	 * @return array file owner
580
-	 */
581
-	public static function resolveReShare($linkItem)
582
-	{
583
-		if (isset($linkItem['parent'])) {
584
-			$parent = $linkItem['parent'];
585
-			while (isset($parent)) {
586
-				$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
587
-				$item = $query->execute(array($parent))->fetchRow();
588
-				if (isset($item['parent'])) {
589
-					$parent = $item['parent'];
590
-				} else {
591
-					return $item;
592
-				}
593
-			}
594
-		}
595
-		return $linkItem;
596
-	}
597
-
598
-
599
-	/**
600
-	 * Get the shared items of item type owned by the current user
601
-	 * @param string $itemType
602
-	 * @param int $format (optional) Format type must be defined by the backend
603
-	 * @param mixed $parameters
604
-	 * @param int $limit Number of items to return (optional) Returns all by default
605
-	 * @param boolean $includeCollections
606
-	 * @return mixed Return depends on format
607
-	 */
608
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
609
-										  $limit = -1, $includeCollections = false) {
610
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
611
-			$parameters, $limit, $includeCollections);
612
-	}
613
-
614
-	/**
615
-	 * Get the shared item of item type owned by the current user
616
-	 * @param string $itemType
617
-	 * @param string $itemSource
618
-	 * @param int $format (optional) Format type must be defined by the backend
619
-	 * @param mixed $parameters
620
-	 * @param boolean $includeCollections
621
-	 * @return mixed Return depends on format
622
-	 */
623
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
624
-										 $parameters = null, $includeCollections = false) {
625
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
626
-			$parameters, -1, $includeCollections);
627
-	}
628
-
629
-	/**
630
-	 * Get all users an item is shared with
631
-	 * @param string $itemType
632
-	 * @param string $itemSource
633
-	 * @param string $uidOwner
634
-	 * @param boolean $includeCollections
635
-	 * @param boolean $checkExpireDate
636
-	 * @return array Return array of users
637
-	 */
638
-	public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
639
-
640
-		$users = array();
641
-		$items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
642
-		if ($items) {
643
-			foreach ($items as $item) {
644
-				if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
645
-					$users[] = $item['share_with'];
646
-				} else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
647
-
648
-					$group = \OC::$server->getGroupManager()->get($item['share_with']);
649
-					$userIds = [];
650
-					if ($group) {
651
-						$users = $group->searchUsers('', -1, 0);
652
-						foreach ($users as $user) {
653
-							$userIds[] = $user->getUID();
654
-						}
655
-						return $userIds;
656
-					}
657
-
658
-					$users = array_merge($users, $userIds);
659
-				}
660
-			}
661
-		}
662
-		return $users;
663
-	}
664
-
665
-	/**
666
-	 * Share an item with a user, group, or via private link
667
-	 * @param string $itemType
668
-	 * @param string $itemSource
669
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
670
-	 * @param string $shareWith User or group the item is being shared with
671
-	 * @param int $permissions CRUDS
672
-	 * @param string $itemSourceName
673
-	 * @param \DateTime $expirationDate
674
-	 * @param bool $passwordChanged
675
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
676
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
677
-	 * @throws \Exception
678
-	 */
679
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
680
-
681
-		$backend = self::getBackend($itemType);
682
-		$l = \OC::$server->getL10N('lib');
683
-
684
-		if ($backend->isShareTypeAllowed($shareType) === false) {
685
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
686
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
687
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
688
-			throw new \Exception($message_t);
689
-		}
690
-
691
-		$uidOwner = \OC_User::getUser();
692
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
693
-
694
-		if (is_null($itemSourceName)) {
695
-			$itemSourceName = $itemSource;
696
-		}
697
-		$itemName = $itemSourceName;
698
-
699
-		// check if file can be shared
700
-		if ($itemType === 'file' or $itemType === 'folder') {
701
-			$path = \OC\Files\Filesystem::getPath($itemSource);
702
-			$itemName = $path;
703
-
704
-			// verify that the file exists before we try to share it
705
-			if (!$path) {
706
-				$message = 'Sharing %s failed, because the file does not exist';
707
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
708
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
709
-				throw new \Exception($message_t);
710
-			}
711
-			// verify that the user has share permission
712
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
713
-				$message = 'You are not allowed to share %s';
714
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
715
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
716
-				throw new \Exception($message_t);
717
-			}
718
-		}
719
-
720
-		//verify that we don't share a folder which already contains a share mount point
721
-		if ($itemType === 'folder') {
722
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
723
-			$mountManager = \OC\Files\Filesystem::getMountManager();
724
-			$mounts = $mountManager->findIn($path);
725
-			foreach ($mounts as $mount) {
726
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
727
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
728
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
729
-					throw new \Exception($message);
730
-				}
731
-
732
-			}
733
-		}
734
-
735
-		// single file shares should never have delete permissions
736
-		if ($itemType === 'file') {
737
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
738
-		}
739
-
740
-		//Validate expirationDate
741
-		if ($expirationDate !== null) {
742
-			try {
743
-				/*
330
+                );
331
+                $result = $query->execute();
332
+
333
+                if (\OCP\DB::isError($result)) {
334
+                    \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
335
+                } else {
336
+                    while ($row = $result->fetchRow()) {
337
+                        foreach ($fileTargets[$row['fileid']] as $uid => $shareData) {
338
+                            if ($mountPath !== false) {
339
+                                $sharedPath = $shareData['file_target'];
340
+                                $sharedPath .= substr($path, strlen($mountPath) + strlen($paths[$row['fileid']]));
341
+                                $sharePaths[$uid] = $sharedPath;
342
+                            } else {
343
+                                $sharedPath = $shareData['file_target'];
344
+                                $sharedPath .= substr($path, strlen($row['path']) -5);
345
+                                $sharePaths[$uid] = $sharedPath;
346
+                            }
347
+                        }
348
+                    }
349
+                }
350
+            }
351
+
352
+            if ($includeOwner) {
353
+                $sharePaths[$ownerUser] = $path;
354
+            } else {
355
+                unset($sharePaths[$ownerUser]);
356
+            }
357
+
358
+            return $sharePaths;
359
+        }
360
+
361
+        return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare);
362
+    }
363
+
364
+    /**
365
+     * Get the items of item type shared with the current user
366
+     * @param string $itemType
367
+     * @param int $format (optional) Format type must be defined by the backend
368
+     * @param mixed $parameters (optional)
369
+     * @param int $limit Number of items to return (optional) Returns all by default
370
+     * @param boolean $includeCollections (optional)
371
+     * @return mixed Return depends on format
372
+     */
373
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
374
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
375
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
376
+            $parameters, $limit, $includeCollections);
377
+    }
378
+
379
+    /**
380
+     * Get the items of item type shared with a user
381
+     * @param string $itemType
382
+     * @param string $user id for which user we want the shares
383
+     * @param int $format (optional) Format type must be defined by the backend
384
+     * @param mixed $parameters (optional)
385
+     * @param int $limit Number of items to return (optional) Returns all by default
386
+     * @param boolean $includeCollections (optional)
387
+     * @return mixed Return depends on format
388
+     */
389
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
390
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
391
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
392
+            $parameters, $limit, $includeCollections);
393
+    }
394
+
395
+    /**
396
+     * Get the item of item type shared with the current user
397
+     * @param string $itemType
398
+     * @param string $itemTarget
399
+     * @param int $format (optional) Format type must be defined by the backend
400
+     * @param mixed $parameters (optional)
401
+     * @param boolean $includeCollections (optional)
402
+     * @return mixed Return depends on format
403
+     */
404
+    public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
405
+                                                $parameters = null, $includeCollections = false) {
406
+        return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
407
+            $parameters, 1, $includeCollections);
408
+    }
409
+
410
+    /**
411
+     * Get the item of item type shared with a given user by source
412
+     * @param string $itemType
413
+     * @param string $itemSource
414
+     * @param string $user User to whom the item was shared
415
+     * @param string $owner Owner of the share
416
+     * @param int $shareType only look for a specific share type
417
+     * @return array Return list of items with file_target, permissions and expiration
418
+     */
419
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
420
+        $shares = array();
421
+        $fileDependent = false;
422
+
423
+        $where = 'WHERE';
424
+        $fileDependentWhere = '';
425
+        if ($itemType === 'file' || $itemType === 'folder') {
426
+            $fileDependent = true;
427
+            $column = 'file_source';
428
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
429
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
430
+        } else {
431
+            $column = 'item_source';
432
+        }
433
+
434
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
435
+
436
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
437
+        $arguments = array($itemSource, $itemType);
438
+        // for link shares $user === null
439
+        if ($user !== null) {
440
+            $where .= ' AND `share_with` = ? ';
441
+            $arguments[] = $user;
442
+        }
443
+
444
+        if ($shareType !== null) {
445
+            $where .= ' AND `share_type` = ? ';
446
+            $arguments[] = $shareType;
447
+        }
448
+
449
+        if ($owner !== null) {
450
+            $where .= ' AND `uid_owner` = ? ';
451
+            $arguments[] = $owner;
452
+        }
453
+
454
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
455
+
456
+        $result = \OC_DB::executeAudited($query, $arguments);
457
+
458
+        while ($row = $result->fetchRow()) {
459
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
460
+                continue;
461
+            }
462
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
463
+                // if it is a mount point we need to get the path from the mount manager
464
+                $mountManager = \OC\Files\Filesystem::getMountManager();
465
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
466
+                if (!empty($mountPoint)) {
467
+                    $path = $mountPoint[0]->getMountPoint();
468
+                    $path = trim($path, '/');
469
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
470
+                    $row['path'] = $path;
471
+                } else {
472
+                    \OC::$server->getLogger()->warning(
473
+                        'Could not resolve mount point for ' . $row['storage_id'],
474
+                        ['app' => 'OCP\Share']
475
+                    );
476
+                }
477
+            }
478
+            $shares[] = $row;
479
+        }
480
+
481
+        //if didn't found a result than let's look for a group share.
482
+        if(empty($shares) && $user !== null) {
483
+            $userObject = \OC::$server->getUserManager()->get($user);
484
+            $groups = [];
485
+            if ($userObject) {
486
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
487
+            }
488
+
489
+            if (!empty($groups)) {
490
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
491
+                $arguments = array($itemSource, $itemType, $groups);
492
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
493
+
494
+                if ($owner !== null) {
495
+                    $where .= ' AND `uid_owner` = ?';
496
+                    $arguments[] = $owner;
497
+                    $types[] = null;
498
+                }
499
+
500
+                // TODO: inject connection, hopefully one day in the future when this
501
+                // class isn't static anymore...
502
+                $conn = \OC::$server->getDatabaseConnection();
503
+                $result = $conn->executeQuery(
504
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
505
+                    $arguments,
506
+                    $types
507
+                );
508
+
509
+                while ($row = $result->fetch()) {
510
+                    $shares[] = $row;
511
+                }
512
+            }
513
+        }
514
+
515
+        return $shares;
516
+
517
+    }
518
+
519
+    /**
520
+     * Get the item of item type shared with the current user by source
521
+     * @param string $itemType
522
+     * @param string $itemSource
523
+     * @param int $format (optional) Format type must be defined by the backend
524
+     * @param mixed $parameters
525
+     * @param boolean $includeCollections
526
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
527
+     * @return array
528
+     */
529
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
530
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
531
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
532
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
533
+            $parameters, 1, $includeCollections, true);
534
+    }
535
+
536
+    /**
537
+     * Get the item of item type shared by a link
538
+     * @param string $itemType
539
+     * @param string $itemSource
540
+     * @param string $uidOwner Owner of link
541
+     * @return array
542
+     */
543
+    public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
544
+        return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
545
+            null, 1);
546
+    }
547
+
548
+    /**
549
+     * Based on the given token the share information will be returned - password protected shares will be verified
550
+     * @param string $token
551
+     * @param bool $checkPasswordProtection
552
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
553
+     */
554
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
555
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
556
+        $result = $query->execute(array($token));
557
+        if ($result === false) {
558
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
559
+        }
560
+        $row = $result->fetchRow();
561
+        if ($row === false) {
562
+            return false;
563
+        }
564
+        if (is_array($row) and self::expireItem($row)) {
565
+            return false;
566
+        }
567
+
568
+        // password protected shares need to be authenticated
569
+        if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
570
+            return false;
571
+        }
572
+
573
+        return $row;
574
+    }
575
+
576
+    /**
577
+     * resolves reshares down to the last real share
578
+     * @param array $linkItem
579
+     * @return array file owner
580
+     */
581
+    public static function resolveReShare($linkItem)
582
+    {
583
+        if (isset($linkItem['parent'])) {
584
+            $parent = $linkItem['parent'];
585
+            while (isset($parent)) {
586
+                $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
587
+                $item = $query->execute(array($parent))->fetchRow();
588
+                if (isset($item['parent'])) {
589
+                    $parent = $item['parent'];
590
+                } else {
591
+                    return $item;
592
+                }
593
+            }
594
+        }
595
+        return $linkItem;
596
+    }
597
+
598
+
599
+    /**
600
+     * Get the shared items of item type owned by the current user
601
+     * @param string $itemType
602
+     * @param int $format (optional) Format type must be defined by the backend
603
+     * @param mixed $parameters
604
+     * @param int $limit Number of items to return (optional) Returns all by default
605
+     * @param boolean $includeCollections
606
+     * @return mixed Return depends on format
607
+     */
608
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
609
+                                            $limit = -1, $includeCollections = false) {
610
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
611
+            $parameters, $limit, $includeCollections);
612
+    }
613
+
614
+    /**
615
+     * Get the shared item of item type owned by the current user
616
+     * @param string $itemType
617
+     * @param string $itemSource
618
+     * @param int $format (optional) Format type must be defined by the backend
619
+     * @param mixed $parameters
620
+     * @param boolean $includeCollections
621
+     * @return mixed Return depends on format
622
+     */
623
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
624
+                                            $parameters = null, $includeCollections = false) {
625
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
626
+            $parameters, -1, $includeCollections);
627
+    }
628
+
629
+    /**
630
+     * Get all users an item is shared with
631
+     * @param string $itemType
632
+     * @param string $itemSource
633
+     * @param string $uidOwner
634
+     * @param boolean $includeCollections
635
+     * @param boolean $checkExpireDate
636
+     * @return array Return array of users
637
+     */
638
+    public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
639
+
640
+        $users = array();
641
+        $items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
642
+        if ($items) {
643
+            foreach ($items as $item) {
644
+                if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
645
+                    $users[] = $item['share_with'];
646
+                } else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
647
+
648
+                    $group = \OC::$server->getGroupManager()->get($item['share_with']);
649
+                    $userIds = [];
650
+                    if ($group) {
651
+                        $users = $group->searchUsers('', -1, 0);
652
+                        foreach ($users as $user) {
653
+                            $userIds[] = $user->getUID();
654
+                        }
655
+                        return $userIds;
656
+                    }
657
+
658
+                    $users = array_merge($users, $userIds);
659
+                }
660
+            }
661
+        }
662
+        return $users;
663
+    }
664
+
665
+    /**
666
+     * Share an item with a user, group, or via private link
667
+     * @param string $itemType
668
+     * @param string $itemSource
669
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
670
+     * @param string $shareWith User or group the item is being shared with
671
+     * @param int $permissions CRUDS
672
+     * @param string $itemSourceName
673
+     * @param \DateTime $expirationDate
674
+     * @param bool $passwordChanged
675
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
676
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
677
+     * @throws \Exception
678
+     */
679
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
680
+
681
+        $backend = self::getBackend($itemType);
682
+        $l = \OC::$server->getL10N('lib');
683
+
684
+        if ($backend->isShareTypeAllowed($shareType) === false) {
685
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
686
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
687
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
688
+            throw new \Exception($message_t);
689
+        }
690
+
691
+        $uidOwner = \OC_User::getUser();
692
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
693
+
694
+        if (is_null($itemSourceName)) {
695
+            $itemSourceName = $itemSource;
696
+        }
697
+        $itemName = $itemSourceName;
698
+
699
+        // check if file can be shared
700
+        if ($itemType === 'file' or $itemType === 'folder') {
701
+            $path = \OC\Files\Filesystem::getPath($itemSource);
702
+            $itemName = $path;
703
+
704
+            // verify that the file exists before we try to share it
705
+            if (!$path) {
706
+                $message = 'Sharing %s failed, because the file does not exist';
707
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
708
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
709
+                throw new \Exception($message_t);
710
+            }
711
+            // verify that the user has share permission
712
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
713
+                $message = 'You are not allowed to share %s';
714
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
715
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
716
+                throw new \Exception($message_t);
717
+            }
718
+        }
719
+
720
+        //verify that we don't share a folder which already contains a share mount point
721
+        if ($itemType === 'folder') {
722
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
723
+            $mountManager = \OC\Files\Filesystem::getMountManager();
724
+            $mounts = $mountManager->findIn($path);
725
+            foreach ($mounts as $mount) {
726
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
727
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
728
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
729
+                    throw new \Exception($message);
730
+                }
731
+
732
+            }
733
+        }
734
+
735
+        // single file shares should never have delete permissions
736
+        if ($itemType === 'file') {
737
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
738
+        }
739
+
740
+        //Validate expirationDate
741
+        if ($expirationDate !== null) {
742
+            try {
743
+                /*
744 744
 				 * Reuse the validateExpireDate.
745 745
 				 * We have to pass time() since the second arg is the time
746 746
 				 * the file was shared, since it is not shared yet we just use
747 747
 				 * the current time.
748 748
 				 */
749
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
750
-			} catch (\Exception $e) {
751
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
752
-			}
753
-		}
754
-
755
-		// Verify share type and sharing conditions are met
756
-		if ($shareType === self::SHARE_TYPE_USER) {
757
-			if ($shareWith == $uidOwner) {
758
-				$message = 'Sharing %s failed, because you can not share with yourself';
759
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
760
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
761
-				throw new \Exception($message_t);
762
-			}
763
-			if (!\OC_User::userExists($shareWith)) {
764
-				$message = 'Sharing %s failed, because the user %s does not exist';
765
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
766
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
767
-				throw new \Exception($message_t);
768
-			}
769
-			if ($shareWithinGroupOnly) {
770
-				$userManager = \OC::$server->getUserManager();
771
-				$groupManager = \OC::$server->getGroupManager();
772
-				$userOwner = $userManager->get($uidOwner);
773
-				$userShareWith = $userManager->get($shareWith);
774
-				$groupsOwner = [];
775
-				$groupsShareWith = [];
776
-				if ($userOwner) {
777
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
778
-				}
779
-				if ($userShareWith) {
780
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
781
-				}
782
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
783
-				if (empty($inGroup)) {
784
-					$message = 'Sharing %s failed, because the user '
785
-						.'%s is not a member of any groups that %s is a member of';
786
-					$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));
787
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
788
-					throw new \Exception($message_t);
789
-				}
790
-			}
791
-			// Check if the item source is already shared with the user, either from the same owner or a different user
792
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
793
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
794
-				// Only allow the same share to occur again if it is the same
795
-				// owner and is not a user share, this use case is for increasing
796
-				// permissions for a specific user
797
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
798
-					$message = 'Sharing %s failed, because this item is already shared with %s';
799
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
800
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
801
-					throw new \Exception($message_t);
802
-				}
803
-			}
804
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
805
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
806
-				// Only allow the same share to occur again if it is the same
807
-				// owner and is not a user share, this use case is for increasing
808
-				// permissions for a specific user
809
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
810
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
811
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
812
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
813
-					throw new \Exception($message_t);
814
-				}
815
-			}
816
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
817
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
818
-				$message = 'Sharing %s failed, because the group %s does not exist';
819
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
820
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
821
-				throw new \Exception($message_t);
822
-			}
823
-			if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
824
-				$group = \OC::$server->getGroupManager()->get($shareWith);
825
-				$user = \OC::$server->getUserManager()->get($uidOwner);
826
-				if (!$group || !$user || !$group->inGroup($user)) {
827
-					$message = 'Sharing %s failed, because '
828
-						. '%s is not a member of the group %s';
829
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
830
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
831
-					throw new \Exception($message_t);
832
-				}
833
-			}
834
-			// Check if the item source is already shared with the group, either from the same owner or a different user
835
-			// The check for each user in the group is done inside the put() function
836
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
837
-				null, self::FORMAT_NONE, null, 1, true, true)) {
838
-
839
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
840
-					$message = 'Sharing %s failed, because this item is already shared with %s';
841
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
842
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
843
-					throw new \Exception($message_t);
844
-				}
845
-			}
846
-			// Convert share with into an array with the keys group and users
847
-			$group = $shareWith;
848
-			$shareWith = array();
849
-			$shareWith['group'] = $group;
850
-
851
-
852
-			$groupObject = \OC::$server->getGroupManager()->get($group);
853
-			$userIds = [];
854
-			if ($groupObject) {
855
-				$users = $groupObject->searchUsers('', -1, 0);
856
-				foreach ($users as $user) {
857
-					$userIds[] = $user->getUID();
858
-				}
859
-			}
860
-
861
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
862
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
863
-			$updateExistingShare = false;
864
-			if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
865
-
866
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
867
-				if ($passwordChanged === true) {
868
-					self::verifyPassword($shareWith);
869
-				}
870
-
871
-				// when updating a link share
872
-				// FIXME Don't delete link if we update it
873
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
874
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
875
-					// remember old token
876
-					$oldToken = $checkExists['token'];
877
-					$oldPermissions = $checkExists['permissions'];
878
-					//delete the old share
879
-					Helper::delete($checkExists['id']);
880
-					$updateExistingShare = true;
881
-				}
882
-
883
-				if ($passwordChanged === null) {
884
-					// Generate hash of password - same method as user passwords
885
-					if (is_string($shareWith) && $shareWith !== '') {
886
-						self::verifyPassword($shareWith);
887
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
888
-					} else {
889
-						// reuse the already set password, but only if we change permissions
890
-						// otherwise the user disabled the password protection
891
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
892
-							$shareWith = $checkExists['share_with'];
893
-						}
894
-					}
895
-				} else {
896
-					if ($passwordChanged === true) {
897
-						if (is_string($shareWith) && $shareWith !== '') {
898
-							self::verifyPassword($shareWith);
899
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
900
-						}
901
-					} else if ($updateExistingShare) {
902
-						$shareWith = $checkExists['share_with'];
903
-					}
904
-				}
905
-
906
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
907
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
908
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
909
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
910
-					throw new \Exception($message_t);
911
-				}
912
-
913
-				if ($updateExistingShare === false &&
914
-					self::isDefaultExpireDateEnabled() &&
915
-					empty($expirationDate)) {
916
-					$expirationDate = Helper::calcExpireDate();
917
-				}
918
-
919
-				// Generate token
920
-				if (isset($oldToken)) {
921
-					$token = $oldToken;
922
-				} else {
923
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
924
-						\OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
925
-						\OCP\Security\ISecureRandom::CHAR_DIGITS
926
-					);
927
-				}
928
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
929
-					null, $token, $itemSourceName, $expirationDate);
930
-				if ($result) {
931
-					return $token;
932
-				} else {
933
-					return false;
934
-				}
935
-			}
936
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
937
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
938
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
939
-			throw new \Exception($message_t);
940
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
941
-
942
-			/*
749
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
750
+            } catch (\Exception $e) {
751
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
752
+            }
753
+        }
754
+
755
+        // Verify share type and sharing conditions are met
756
+        if ($shareType === self::SHARE_TYPE_USER) {
757
+            if ($shareWith == $uidOwner) {
758
+                $message = 'Sharing %s failed, because you can not share with yourself';
759
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
760
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
761
+                throw new \Exception($message_t);
762
+            }
763
+            if (!\OC_User::userExists($shareWith)) {
764
+                $message = 'Sharing %s failed, because the user %s does not exist';
765
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
766
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
767
+                throw new \Exception($message_t);
768
+            }
769
+            if ($shareWithinGroupOnly) {
770
+                $userManager = \OC::$server->getUserManager();
771
+                $groupManager = \OC::$server->getGroupManager();
772
+                $userOwner = $userManager->get($uidOwner);
773
+                $userShareWith = $userManager->get($shareWith);
774
+                $groupsOwner = [];
775
+                $groupsShareWith = [];
776
+                if ($userOwner) {
777
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
778
+                }
779
+                if ($userShareWith) {
780
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
781
+                }
782
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
783
+                if (empty($inGroup)) {
784
+                    $message = 'Sharing %s failed, because the user '
785
+                        .'%s is not a member of any groups that %s is a member of';
786
+                    $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));
787
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
788
+                    throw new \Exception($message_t);
789
+                }
790
+            }
791
+            // Check if the item source is already shared with the user, either from the same owner or a different user
792
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
793
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
794
+                // Only allow the same share to occur again if it is the same
795
+                // owner and is not a user share, this use case is for increasing
796
+                // permissions for a specific user
797
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
798
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
799
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
800
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
801
+                    throw new \Exception($message_t);
802
+                }
803
+            }
804
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
805
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
806
+                // Only allow the same share to occur again if it is the same
807
+                // owner and is not a user share, this use case is for increasing
808
+                // permissions for a specific user
809
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
810
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
811
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
812
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
813
+                    throw new \Exception($message_t);
814
+                }
815
+            }
816
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
817
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
818
+                $message = 'Sharing %s failed, because the group %s does not exist';
819
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
820
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
821
+                throw new \Exception($message_t);
822
+            }
823
+            if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
824
+                $group = \OC::$server->getGroupManager()->get($shareWith);
825
+                $user = \OC::$server->getUserManager()->get($uidOwner);
826
+                if (!$group || !$user || !$group->inGroup($user)) {
827
+                    $message = 'Sharing %s failed, because '
828
+                        . '%s is not a member of the group %s';
829
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
830
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
831
+                    throw new \Exception($message_t);
832
+                }
833
+            }
834
+            // Check if the item source is already shared with the group, either from the same owner or a different user
835
+            // The check for each user in the group is done inside the put() function
836
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
837
+                null, self::FORMAT_NONE, null, 1, true, true)) {
838
+
839
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
840
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
841
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
842
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
843
+                    throw new \Exception($message_t);
844
+                }
845
+            }
846
+            // Convert share with into an array with the keys group and users
847
+            $group = $shareWith;
848
+            $shareWith = array();
849
+            $shareWith['group'] = $group;
850
+
851
+
852
+            $groupObject = \OC::$server->getGroupManager()->get($group);
853
+            $userIds = [];
854
+            if ($groupObject) {
855
+                $users = $groupObject->searchUsers('', -1, 0);
856
+                foreach ($users as $user) {
857
+                    $userIds[] = $user->getUID();
858
+                }
859
+            }
860
+
861
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
862
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
863
+            $updateExistingShare = false;
864
+            if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
865
+
866
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
867
+                if ($passwordChanged === true) {
868
+                    self::verifyPassword($shareWith);
869
+                }
870
+
871
+                // when updating a link share
872
+                // FIXME Don't delete link if we update it
873
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
874
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
875
+                    // remember old token
876
+                    $oldToken = $checkExists['token'];
877
+                    $oldPermissions = $checkExists['permissions'];
878
+                    //delete the old share
879
+                    Helper::delete($checkExists['id']);
880
+                    $updateExistingShare = true;
881
+                }
882
+
883
+                if ($passwordChanged === null) {
884
+                    // Generate hash of password - same method as user passwords
885
+                    if (is_string($shareWith) && $shareWith !== '') {
886
+                        self::verifyPassword($shareWith);
887
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
888
+                    } else {
889
+                        // reuse the already set password, but only if we change permissions
890
+                        // otherwise the user disabled the password protection
891
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
892
+                            $shareWith = $checkExists['share_with'];
893
+                        }
894
+                    }
895
+                } else {
896
+                    if ($passwordChanged === true) {
897
+                        if (is_string($shareWith) && $shareWith !== '') {
898
+                            self::verifyPassword($shareWith);
899
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
900
+                        }
901
+                    } else if ($updateExistingShare) {
902
+                        $shareWith = $checkExists['share_with'];
903
+                    }
904
+                }
905
+
906
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
907
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
908
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
909
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
910
+                    throw new \Exception($message_t);
911
+                }
912
+
913
+                if ($updateExistingShare === false &&
914
+                    self::isDefaultExpireDateEnabled() &&
915
+                    empty($expirationDate)) {
916
+                    $expirationDate = Helper::calcExpireDate();
917
+                }
918
+
919
+                // Generate token
920
+                if (isset($oldToken)) {
921
+                    $token = $oldToken;
922
+                } else {
923
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
924
+                        \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
925
+                        \OCP\Security\ISecureRandom::CHAR_DIGITS
926
+                    );
927
+                }
928
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
929
+                    null, $token, $itemSourceName, $expirationDate);
930
+                if ($result) {
931
+                    return $token;
932
+                } else {
933
+                    return false;
934
+                }
935
+            }
936
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
937
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
938
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
939
+            throw new \Exception($message_t);
940
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
941
+
942
+            /*
943 943
 			 * Check if file is not already shared with the remote user
944 944
 			 */
945
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
946
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
947
-					$message = 'Sharing %s failed, because this item is already shared with %s';
948
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
949
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
950
-					throw new \Exception($message_t);
951
-			}
952
-
953
-			// don't allow federated shares if source and target server are the same
954
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
955
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
956
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
957
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
958
-				$message = 'Not allowed to create a federated share with the same user.';
959
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
960
-				\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
961
-				throw new \Exception($message_t);
962
-			}
963
-
964
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
965
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
966
-
967
-			$shareWith = $user . '@' . $remote;
968
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
969
-
970
-			$send = false;
971
-			if ($shareId) {
972
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
973
-			}
974
-
975
-			if ($send === false) {
976
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
977
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
978
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
979
-				throw new \Exception($message_t);
980
-			}
981
-
982
-			return $send;
983
-		} else {
984
-			// Future share types need to include their own conditions
985
-			$message = 'Share type %s is not valid for %s';
986
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
987
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
988
-			throw new \Exception($message_t);
989
-		}
990
-
991
-		// Put the item into the database
992
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
993
-
994
-		return $result ? true : false;
995
-	}
996
-
997
-	/**
998
-	 * Unshare an item from a user, group, or delete a private link
999
-	 * @param string $itemType
1000
-	 * @param string $itemSource
1001
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1002
-	 * @param string $shareWith User or group the item is being shared with
1003
-	 * @param string $owner owner of the share, if null the current user is used
1004
-	 * @return boolean true on success or false on failure
1005
-	 */
1006
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
1007
-
1008
-		// check if it is a valid itemType
1009
-		self::getBackend($itemType);
1010
-
1011
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
1012
-
1013
-		$toDelete = array();
1014
-		$newParent = null;
1015
-		$currentUser = $owner ? $owner : \OC_User::getUser();
1016
-		foreach ($items as $item) {
1017
-			// delete the item with the expected share_type and owner
1018
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
1019
-				$toDelete = $item;
1020
-				// if there is more then one result we don't have to delete the children
1021
-				// but update their parent. For group shares the new parent should always be
1022
-				// the original group share and not the db entry with the unique name
1023
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
1024
-				$newParent = $item['parent'];
1025
-			} else {
1026
-				$newParent = $item['id'];
1027
-			}
1028
-		}
1029
-
1030
-		if (!empty($toDelete)) {
1031
-			self::unshareItem($toDelete, $newParent);
1032
-			return true;
1033
-		}
1034
-		return false;
1035
-	}
1036
-
1037
-	/**
1038
-	 * Unshare an item from all users, groups, and remove all links
1039
-	 * @param string $itemType
1040
-	 * @param string $itemSource
1041
-	 * @return boolean true on success or false on failure
1042
-	 */
1043
-	public static function unshareAll($itemType, $itemSource) {
1044
-		// Get all of the owners of shares of this item.
1045
-		$query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
1046
-		$result = $query->execute(array($itemType, $itemSource));
1047
-		$shares = array();
1048
-		// Add each owner's shares to the array of all shares for this item.
1049
-		while ($row = $result->fetchRow()) {
1050
-			$shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
1051
-		}
1052
-		if (!empty($shares)) {
1053
-			// Pass all the vars we have for now, they may be useful
1054
-			$hookParams = array(
1055
-				'itemType' => $itemType,
1056
-				'itemSource' => $itemSource,
1057
-				'shares' => $shares,
1058
-			);
1059
-			\OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
1060
-			foreach ($shares as $share) {
1061
-				self::unshareItem($share);
1062
-			}
1063
-			\OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
1064
-			return true;
1065
-		}
1066
-		return false;
1067
-	}
1068
-
1069
-	/**
1070
-	 * Unshare an item shared with the current user
1071
-	 * @param string $itemType
1072
-	 * @param string $itemOrigin Item target or source
1073
-	 * @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
1074
-	 * @return boolean true on success or false on failure
1075
-	 *
1076
-	 * Unsharing from self is not allowed for items inside collections
1077
-	 */
1078
-	public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
1079
-		$originType = ($originIsSource) ? 'source' : 'target';
1080
-		$uid = \OCP\User::getUser();
1081
-
1082
-		if ($itemType === 'file' || $itemType === 'folder') {
1083
-			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
1084
-		} else {
1085
-			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
1086
-		}
1087
-
1088
-		$query = \OCP\DB::prepare($statement);
1089
-		$result = $query->execute(array($itemType, $itemOrigin));
1090
-
1091
-		$shares = $result->fetchAll();
1092
-
1093
-		$listOfUnsharedItems = array();
1094
-
1095
-		$itemUnshared = false;
1096
-		foreach ($shares as $share) {
1097
-			if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
1098
-				$share['share_with'] === $uid) {
1099
-				$deletedShares = Helper::delete($share['id']);
1100
-				$shareTmp = array(
1101
-					'id' => $share['id'],
1102
-					'shareWith' => $share['share_with'],
1103
-					'itemTarget' => $share['item_target'],
1104
-					'itemType' => $share['item_type'],
1105
-					'shareType' => (int)$share['share_type'],
1106
-				);
1107
-				if (isset($share['file_target'])) {
1108
-					$shareTmp['fileTarget'] = $share['file_target'];
1109
-				}
1110
-				$listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
1111
-				$itemUnshared = true;
1112
-				break;
1113
-			} elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
1114
-				$group = \OC::$server->getGroupManager()->get($share['share_with']);
1115
-				$user = \OC::$server->getUserManager()->get($uid);
1116
-				if ($group && $user && $group->inGroup($user)) {
1117
-					$groupShare = $share;
1118
-				}
1119
-			} elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
1120
-				$share['share_with'] === $uid) {
1121
-				$uniqueGroupShare = $share;
1122
-			}
1123
-		}
1124
-
1125
-		if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
1126
-			$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
1127
-				.' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
1128
-				.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
1129
-				.' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
1130
-			$query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
1131
-				$groupShare['id'], self::$shareTypeGroupUserUnique,
1132
-				\OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
1133
-				$groupShare['file_target']));
1134
-			$shareTmp = array(
1135
-				'id' => $groupShare['id'],
1136
-				'shareWith' => $groupShare['share_with'],
1137
-				'itemTarget' => $groupShare['item_target'],
1138
-				'itemType' => $groupShare['item_type'],
1139
-				'shareType' => (int)$groupShare['share_type'],
1140
-			);
1141
-			if (isset($groupShare['file_target'])) {
1142
-				$shareTmp['fileTarget'] = $groupShare['file_target'];
1143
-			}
1144
-			$listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1145
-			$itemUnshared = true;
1146
-		} elseif (!$itemUnshared && isset($uniqueGroupShare)) {
1147
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
1148
-			$query->execute(array(0, $uniqueGroupShare['id']));
1149
-			$shareTmp = array(
1150
-				'id' => $uniqueGroupShare['id'],
1151
-				'shareWith' => $uniqueGroupShare['share_with'],
1152
-				'itemTarget' => $uniqueGroupShare['item_target'],
1153
-				'itemType' => $uniqueGroupShare['item_type'],
1154
-				'shareType' => (int)$uniqueGroupShare['share_type'],
1155
-			);
1156
-			if (isset($uniqueGroupShare['file_target'])) {
1157
-				$shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
1158
-			}
1159
-			$listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1160
-			$itemUnshared = true;
1161
-		}
1162
-
1163
-		if ($itemUnshared) {
1164
-			\OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
1165
-				array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
1166
-		}
1167
-
1168
-		return $itemUnshared;
1169
-	}
1170
-
1171
-	/**
1172
-	 * sent status if users got informed by mail about share
1173
-	 * @param string $itemType
1174
-	 * @param string $itemSource
1175
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1176
-	 * @param string $recipient with whom was the file shared
1177
-	 * @param boolean $status
1178
-	 */
1179
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
1180
-		$status = $status ? 1 : 0;
1181
-
1182
-		$query = \OC_DB::prepare(
1183
-			'UPDATE `*PREFIX*share`
945
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
946
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
947
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
948
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
949
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
950
+                    throw new \Exception($message_t);
951
+            }
952
+
953
+            // don't allow federated shares if source and target server are the same
954
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
955
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
956
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
957
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
958
+                $message = 'Not allowed to create a federated share with the same user.';
959
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
960
+                \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
961
+                throw new \Exception($message_t);
962
+            }
963
+
964
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
965
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
966
+
967
+            $shareWith = $user . '@' . $remote;
968
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
969
+
970
+            $send = false;
971
+            if ($shareId) {
972
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
973
+            }
974
+
975
+            if ($send === false) {
976
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
977
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
978
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
979
+                throw new \Exception($message_t);
980
+            }
981
+
982
+            return $send;
983
+        } else {
984
+            // Future share types need to include their own conditions
985
+            $message = 'Share type %s is not valid for %s';
986
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
987
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
988
+            throw new \Exception($message_t);
989
+        }
990
+
991
+        // Put the item into the database
992
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
993
+
994
+        return $result ? true : false;
995
+    }
996
+
997
+    /**
998
+     * Unshare an item from a user, group, or delete a private link
999
+     * @param string $itemType
1000
+     * @param string $itemSource
1001
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1002
+     * @param string $shareWith User or group the item is being shared with
1003
+     * @param string $owner owner of the share, if null the current user is used
1004
+     * @return boolean true on success or false on failure
1005
+     */
1006
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
1007
+
1008
+        // check if it is a valid itemType
1009
+        self::getBackend($itemType);
1010
+
1011
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
1012
+
1013
+        $toDelete = array();
1014
+        $newParent = null;
1015
+        $currentUser = $owner ? $owner : \OC_User::getUser();
1016
+        foreach ($items as $item) {
1017
+            // delete the item with the expected share_type and owner
1018
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
1019
+                $toDelete = $item;
1020
+                // if there is more then one result we don't have to delete the children
1021
+                // but update their parent. For group shares the new parent should always be
1022
+                // the original group share and not the db entry with the unique name
1023
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
1024
+                $newParent = $item['parent'];
1025
+            } else {
1026
+                $newParent = $item['id'];
1027
+            }
1028
+        }
1029
+
1030
+        if (!empty($toDelete)) {
1031
+            self::unshareItem($toDelete, $newParent);
1032
+            return true;
1033
+        }
1034
+        return false;
1035
+    }
1036
+
1037
+    /**
1038
+     * Unshare an item from all users, groups, and remove all links
1039
+     * @param string $itemType
1040
+     * @param string $itemSource
1041
+     * @return boolean true on success or false on failure
1042
+     */
1043
+    public static function unshareAll($itemType, $itemSource) {
1044
+        // Get all of the owners of shares of this item.
1045
+        $query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
1046
+        $result = $query->execute(array($itemType, $itemSource));
1047
+        $shares = array();
1048
+        // Add each owner's shares to the array of all shares for this item.
1049
+        while ($row = $result->fetchRow()) {
1050
+            $shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
1051
+        }
1052
+        if (!empty($shares)) {
1053
+            // Pass all the vars we have for now, they may be useful
1054
+            $hookParams = array(
1055
+                'itemType' => $itemType,
1056
+                'itemSource' => $itemSource,
1057
+                'shares' => $shares,
1058
+            );
1059
+            \OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
1060
+            foreach ($shares as $share) {
1061
+                self::unshareItem($share);
1062
+            }
1063
+            \OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
1064
+            return true;
1065
+        }
1066
+        return false;
1067
+    }
1068
+
1069
+    /**
1070
+     * Unshare an item shared with the current user
1071
+     * @param string $itemType
1072
+     * @param string $itemOrigin Item target or source
1073
+     * @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
1074
+     * @return boolean true on success or false on failure
1075
+     *
1076
+     * Unsharing from self is not allowed for items inside collections
1077
+     */
1078
+    public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
1079
+        $originType = ($originIsSource) ? 'source' : 'target';
1080
+        $uid = \OCP\User::getUser();
1081
+
1082
+        if ($itemType === 'file' || $itemType === 'folder') {
1083
+            $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
1084
+        } else {
1085
+            $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
1086
+        }
1087
+
1088
+        $query = \OCP\DB::prepare($statement);
1089
+        $result = $query->execute(array($itemType, $itemOrigin));
1090
+
1091
+        $shares = $result->fetchAll();
1092
+
1093
+        $listOfUnsharedItems = array();
1094
+
1095
+        $itemUnshared = false;
1096
+        foreach ($shares as $share) {
1097
+            if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
1098
+                $share['share_with'] === $uid) {
1099
+                $deletedShares = Helper::delete($share['id']);
1100
+                $shareTmp = array(
1101
+                    'id' => $share['id'],
1102
+                    'shareWith' => $share['share_with'],
1103
+                    'itemTarget' => $share['item_target'],
1104
+                    'itemType' => $share['item_type'],
1105
+                    'shareType' => (int)$share['share_type'],
1106
+                );
1107
+                if (isset($share['file_target'])) {
1108
+                    $shareTmp['fileTarget'] = $share['file_target'];
1109
+                }
1110
+                $listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
1111
+                $itemUnshared = true;
1112
+                break;
1113
+            } elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
1114
+                $group = \OC::$server->getGroupManager()->get($share['share_with']);
1115
+                $user = \OC::$server->getUserManager()->get($uid);
1116
+                if ($group && $user && $group->inGroup($user)) {
1117
+                    $groupShare = $share;
1118
+                }
1119
+            } elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
1120
+                $share['share_with'] === $uid) {
1121
+                $uniqueGroupShare = $share;
1122
+            }
1123
+        }
1124
+
1125
+        if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
1126
+            $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
1127
+                .' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
1128
+                .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
1129
+                .' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
1130
+            $query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
1131
+                $groupShare['id'], self::$shareTypeGroupUserUnique,
1132
+                \OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
1133
+                $groupShare['file_target']));
1134
+            $shareTmp = array(
1135
+                'id' => $groupShare['id'],
1136
+                'shareWith' => $groupShare['share_with'],
1137
+                'itemTarget' => $groupShare['item_target'],
1138
+                'itemType' => $groupShare['item_type'],
1139
+                'shareType' => (int)$groupShare['share_type'],
1140
+            );
1141
+            if (isset($groupShare['file_target'])) {
1142
+                $shareTmp['fileTarget'] = $groupShare['file_target'];
1143
+            }
1144
+            $listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1145
+            $itemUnshared = true;
1146
+        } elseif (!$itemUnshared && isset($uniqueGroupShare)) {
1147
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
1148
+            $query->execute(array(0, $uniqueGroupShare['id']));
1149
+            $shareTmp = array(
1150
+                'id' => $uniqueGroupShare['id'],
1151
+                'shareWith' => $uniqueGroupShare['share_with'],
1152
+                'itemTarget' => $uniqueGroupShare['item_target'],
1153
+                'itemType' => $uniqueGroupShare['item_type'],
1154
+                'shareType' => (int)$uniqueGroupShare['share_type'],
1155
+            );
1156
+            if (isset($uniqueGroupShare['file_target'])) {
1157
+                $shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
1158
+            }
1159
+            $listOfUnsharedItems = array_merge($listOfUnsharedItems, [$shareTmp]);
1160
+            $itemUnshared = true;
1161
+        }
1162
+
1163
+        if ($itemUnshared) {
1164
+            \OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
1165
+                array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
1166
+        }
1167
+
1168
+        return $itemUnshared;
1169
+    }
1170
+
1171
+    /**
1172
+     * sent status if users got informed by mail about share
1173
+     * @param string $itemType
1174
+     * @param string $itemSource
1175
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1176
+     * @param string $recipient with whom was the file shared
1177
+     * @param boolean $status
1178
+     */
1179
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
1180
+        $status = $status ? 1 : 0;
1181
+
1182
+        $query = \OC_DB::prepare(
1183
+            'UPDATE `*PREFIX*share`
1184 1184
 					SET `mail_send` = ?
1185 1185
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
1186 1186
 
1187
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
1188
-
1189
-		if($result === false) {
1190
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
1191
-		}
1192
-	}
1193
-
1194
-	/**
1195
-	 * Set the permissions of an item for a specific user or group
1196
-	 * @param string $itemType
1197
-	 * @param string $itemSource
1198
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1199
-	 * @param string $shareWith User or group the item is being shared with
1200
-	 * @param int $permissions CRUDS permissions
1201
-	 * @return boolean true on success or false on failure
1202
-	 * @throws \Exception when trying to grant more permissions then the user has himself
1203
-	 */
1204
-	public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
1205
-		$l = \OC::$server->getL10N('lib');
1206
-		$connection = \OC::$server->getDatabaseConnection();
1207
-
1208
-		$intArrayToLiteralArray = function($intArray, $eb) {
1209
-			return array_map(function($int) use ($eb) {
1210
-				return $eb->literal((int)$int, 'integer');
1211
-			}, $intArray);
1212
-		};
1213
-		$sanitizeItem = function($item) {
1214
-			$item['id'] = (int)$item['id'];
1215
-			$item['premissions'] = (int)$item['permissions'];
1216
-			return $item;
1217
-		};
1218
-
1219
-		if ($rootItem = self::getItems($itemType, $itemSource, $shareType, $shareWith,
1220
-			\OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
1221
-			// Check if this item is a reshare and verify that the permissions
1222
-			// granted don't exceed the parent shared item
1223
-			if (isset($rootItem['parent'])) {
1224
-				$qb = $connection->getQueryBuilder();
1225
-				$qb->select('permissions')
1226
-					->from('share')
1227
-					->where($qb->expr()->eq('id', $qb->createParameter('id')))
1228
-					->setParameter(':id', $rootItem['parent']);
1229
-				$dbresult = $qb->execute();
1230
-
1231
-				$result = $dbresult->fetch();
1232
-				$dbresult->closeCursor();
1233
-				if (~(int)$result['permissions'] & $permissions) {
1234
-					$message = 'Setting permissions for %s failed,'
1235
-						.' because the permissions exceed permissions granted to %s';
1236
-					$message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
1237
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG);
1238
-					throw new \Exception($message_t);
1239
-				}
1240
-			}
1241
-			$qb = $connection->getQueryBuilder();
1242
-			$qb->update('share')
1243
-				->set('permissions', $qb->createParameter('permissions'))
1244
-				->where($qb->expr()->eq('id', $qb->createParameter('id')))
1245
-				->setParameter(':id', $rootItem['id'])
1246
-				->setParameter(':permissions', $permissions);
1247
-			$qb->execute();
1248
-			if ($itemType === 'file' || $itemType === 'folder') {
1249
-				\OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
1250
-					'itemType' => $itemType,
1251
-					'itemSource' => $itemSource,
1252
-					'shareType' => $shareType,
1253
-					'shareWith' => $shareWith,
1254
-					'uidOwner' => \OC_User::getUser(),
1255
-					'permissions' => $permissions,
1256
-					'path' => $rootItem['path'],
1257
-					'share' => $rootItem
1258
-				));
1259
-			}
1260
-
1261
-			// Share id's to update with the new permissions
1262
-			$ids = [];
1263
-			$items = [];
1264
-
1265
-			// Check if permissions were removed
1266
-			if ((int)$rootItem['permissions'] & ~$permissions) {
1267
-				// If share permission is removed all reshares must be deleted
1268
-				if (($rootItem['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
1269
-					// delete all shares, keep parent and group children
1270
-					Helper::delete($rootItem['id'], true, null, null, true);
1271
-				}
1272
-
1273
-				// Remove permission from all children
1274
-				$parents = [$rootItem['id']];
1275
-				while (!empty($parents)) {
1276
-					$parents = $intArrayToLiteralArray($parents, $qb->expr());
1277
-					$qb = $connection->getQueryBuilder();
1278
-					$qb->select('id', 'permissions', 'item_type')
1279
-						->from('share')
1280
-						->where($qb->expr()->in('parent', $parents));
1281
-					$result = $qb->execute();
1282
-					// Reset parents array, only go through loop again if
1283
-					// items are found that need permissions removed
1284
-					$parents = [];
1285
-					while ($item = $result->fetch()) {
1286
-						$item = $sanitizeItem($item);
1287
-
1288
-						$items[] = $item;
1289
-						// Check if permissions need to be removed
1290
-						if ($item['permissions'] & ~$permissions) {
1291
-							// Add to list of items that need permissions removed
1292
-							$ids[] = $item['id'];
1293
-							$parents[] = $item['id'];
1294
-						}
1295
-					}
1296
-					$result->closeCursor();
1297
-				}
1298
-
1299
-				// Remove the permissions for all reshares of this item
1300
-				if (!empty($ids)) {
1301
-					$ids = "'".implode("','", $ids)."'";
1302
-					// TODO this should be done with Doctrine platform objects
1303
-					if (\OC::$server->getConfig()->getSystemValue("dbtype") === 'oci') {
1304
-						$andOp = 'BITAND(`permissions`, ?)';
1305
-					} else {
1306
-						$andOp = '`permissions` & ?';
1307
-					}
1308
-					$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
1309
-						.' WHERE `id` IN ('.$ids.')');
1310
-					$query->execute(array($permissions));
1311
-				}
1312
-
1313
-			}
1314
-
1315
-			/*
1187
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
1188
+
1189
+        if($result === false) {
1190
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
1191
+        }
1192
+    }
1193
+
1194
+    /**
1195
+     * Set the permissions of an item for a specific user or group
1196
+     * @param string $itemType
1197
+     * @param string $itemSource
1198
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1199
+     * @param string $shareWith User or group the item is being shared with
1200
+     * @param int $permissions CRUDS permissions
1201
+     * @return boolean true on success or false on failure
1202
+     * @throws \Exception when trying to grant more permissions then the user has himself
1203
+     */
1204
+    public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
1205
+        $l = \OC::$server->getL10N('lib');
1206
+        $connection = \OC::$server->getDatabaseConnection();
1207
+
1208
+        $intArrayToLiteralArray = function($intArray, $eb) {
1209
+            return array_map(function($int) use ($eb) {
1210
+                return $eb->literal((int)$int, 'integer');
1211
+            }, $intArray);
1212
+        };
1213
+        $sanitizeItem = function($item) {
1214
+            $item['id'] = (int)$item['id'];
1215
+            $item['premissions'] = (int)$item['permissions'];
1216
+            return $item;
1217
+        };
1218
+
1219
+        if ($rootItem = self::getItems($itemType, $itemSource, $shareType, $shareWith,
1220
+            \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
1221
+            // Check if this item is a reshare and verify that the permissions
1222
+            // granted don't exceed the parent shared item
1223
+            if (isset($rootItem['parent'])) {
1224
+                $qb = $connection->getQueryBuilder();
1225
+                $qb->select('permissions')
1226
+                    ->from('share')
1227
+                    ->where($qb->expr()->eq('id', $qb->createParameter('id')))
1228
+                    ->setParameter(':id', $rootItem['parent']);
1229
+                $dbresult = $qb->execute();
1230
+
1231
+                $result = $dbresult->fetch();
1232
+                $dbresult->closeCursor();
1233
+                if (~(int)$result['permissions'] & $permissions) {
1234
+                    $message = 'Setting permissions for %s failed,'
1235
+                        .' because the permissions exceed permissions granted to %s';
1236
+                    $message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
1237
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OCP\Util::DEBUG);
1238
+                    throw new \Exception($message_t);
1239
+                }
1240
+            }
1241
+            $qb = $connection->getQueryBuilder();
1242
+            $qb->update('share')
1243
+                ->set('permissions', $qb->createParameter('permissions'))
1244
+                ->where($qb->expr()->eq('id', $qb->createParameter('id')))
1245
+                ->setParameter(':id', $rootItem['id'])
1246
+                ->setParameter(':permissions', $permissions);
1247
+            $qb->execute();
1248
+            if ($itemType === 'file' || $itemType === 'folder') {
1249
+                \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
1250
+                    'itemType' => $itemType,
1251
+                    'itemSource' => $itemSource,
1252
+                    'shareType' => $shareType,
1253
+                    'shareWith' => $shareWith,
1254
+                    'uidOwner' => \OC_User::getUser(),
1255
+                    'permissions' => $permissions,
1256
+                    'path' => $rootItem['path'],
1257
+                    'share' => $rootItem
1258
+                ));
1259
+            }
1260
+
1261
+            // Share id's to update with the new permissions
1262
+            $ids = [];
1263
+            $items = [];
1264
+
1265
+            // Check if permissions were removed
1266
+            if ((int)$rootItem['permissions'] & ~$permissions) {
1267
+                // If share permission is removed all reshares must be deleted
1268
+                if (($rootItem['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
1269
+                    // delete all shares, keep parent and group children
1270
+                    Helper::delete($rootItem['id'], true, null, null, true);
1271
+                }
1272
+
1273
+                // Remove permission from all children
1274
+                $parents = [$rootItem['id']];
1275
+                while (!empty($parents)) {
1276
+                    $parents = $intArrayToLiteralArray($parents, $qb->expr());
1277
+                    $qb = $connection->getQueryBuilder();
1278
+                    $qb->select('id', 'permissions', 'item_type')
1279
+                        ->from('share')
1280
+                        ->where($qb->expr()->in('parent', $parents));
1281
+                    $result = $qb->execute();
1282
+                    // Reset parents array, only go through loop again if
1283
+                    // items are found that need permissions removed
1284
+                    $parents = [];
1285
+                    while ($item = $result->fetch()) {
1286
+                        $item = $sanitizeItem($item);
1287
+
1288
+                        $items[] = $item;
1289
+                        // Check if permissions need to be removed
1290
+                        if ($item['permissions'] & ~$permissions) {
1291
+                            // Add to list of items that need permissions removed
1292
+                            $ids[] = $item['id'];
1293
+                            $parents[] = $item['id'];
1294
+                        }
1295
+                    }
1296
+                    $result->closeCursor();
1297
+                }
1298
+
1299
+                // Remove the permissions for all reshares of this item
1300
+                if (!empty($ids)) {
1301
+                    $ids = "'".implode("','", $ids)."'";
1302
+                    // TODO this should be done with Doctrine platform objects
1303
+                    if (\OC::$server->getConfig()->getSystemValue("dbtype") === 'oci') {
1304
+                        $andOp = 'BITAND(`permissions`, ?)';
1305
+                    } else {
1306
+                        $andOp = '`permissions` & ?';
1307
+                    }
1308
+                    $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
1309
+                        .' WHERE `id` IN ('.$ids.')');
1310
+                    $query->execute(array($permissions));
1311
+                }
1312
+
1313
+            }
1314
+
1315
+            /*
1316 1316
 			 * Permissions were added
1317 1317
 			 * Update all USERGROUP shares. (So group shares where the user moved their mountpoint).
1318 1318
 			 */
1319
-			if ($permissions & ~(int)$rootItem['permissions']) {
1320
-				$qb = $connection->getQueryBuilder();
1321
-				$qb->select('id', 'permissions', 'item_type')
1322
-					->from('share')
1323
-					->where($qb->expr()->eq('parent', $qb->createParameter('parent')))
1324
-					->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
1325
-					->andWhere($qb->expr()->neq('permissions', $qb->createParameter('shareDeleted')))
1326
-					->setParameter(':parent', (int)$rootItem['id'])
1327
-					->setParameter(':share_type', 2)
1328
-					->setParameter(':shareDeleted', 0);
1329
-				$result = $qb->execute();
1330
-
1331
-				$ids = [];
1332
-				while ($item = $result->fetch()) {
1333
-					$item = $sanitizeItem($item);
1334
-					$items[] = $item;
1335
-					$ids[] = $item['id'];
1336
-				}
1337
-				$result->closeCursor();
1338
-
1339
-				// Add permssions for all USERGROUP shares of this item
1340
-				if (!empty($ids)) {
1341
-					$ids = $intArrayToLiteralArray($ids, $qb->expr());
1342
-
1343
-					$qb = $connection->getQueryBuilder();
1344
-					$qb->update('share')
1345
-						->set('permissions', $qb->createParameter('permissions'))
1346
-						->where($qb->expr()->in('id', $ids))
1347
-						->setParameter(':permissions', $permissions);
1348
-					$qb->execute();
1349
-				}
1350
-			}
1351
-
1352
-			foreach ($items as $item) {
1353
-				\OC_Hook::emit('OCP\Share', 'post_update_permissions', ['share' => $item]);
1354
-			}
1355
-
1356
-			return true;
1357
-		}
1358
-		$message = 'Setting permissions for %s failed, because the item was not found';
1359
-		$message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
1360
-
1361
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1362
-		throw new \Exception($message_t);
1363
-	}
1364
-
1365
-	/**
1366
-	 * validate expiration date if it meets all constraints
1367
-	 *
1368
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
1369
-	 * @param string $shareTime timestamp when the file was shared
1370
-	 * @param string $itemType
1371
-	 * @param string $itemSource
1372
-	 * @return \DateTime validated date
1373
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
1374
-	 */
1375
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
1376
-		$l = \OC::$server->getL10N('lib');
1377
-		$date = new \DateTime($expireDate);
1378
-		$today = new \DateTime('now');
1379
-
1380
-		// if the user doesn't provide a share time we need to get it from the database
1381
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
1382
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
1383
-		if ($defaultExpireDateEnforced && $shareTime === null) {
1384
-			$items = self::getItemShared($itemType, $itemSource);
1385
-			$firstItem = reset($items);
1386
-			$shareTime = (int)$firstItem['stime'];
1387
-		}
1388
-
1389
-		if ($defaultExpireDateEnforced) {
1390
-			// initialize max date with share time
1391
-			$maxDate = new \DateTime();
1392
-			$maxDate->setTimestamp($shareTime);
1393
-			$maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
1394
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
1395
-			if ($date > $maxDate) {
1396
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
1397
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
1398
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1399
-				throw new \Exception($warning_t);
1400
-			}
1401
-		}
1402
-
1403
-		if ($date < $today) {
1404
-			$message = 'Cannot set expiration date. Expiration date is in the past';
1405
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
1406
-			\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
1407
-			throw new \Exception($message_t);
1408
-		}
1409
-
1410
-		return $date;
1411
-	}
1412
-
1413
-	/**
1414
-	 * Set expiration date for a share
1415
-	 * @param string $itemType
1416
-	 * @param string $itemSource
1417
-	 * @param string $date expiration date
1418
-	 * @param int $shareTime timestamp from when the file was shared
1419
-	 * @return boolean
1420
-	 * @throws \Exception when the expire date is not set, in the past or further in the future then the enforced date
1421
-	 */
1422
-	public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
1423
-		$user = \OC_User::getUser();
1424
-		$l = \OC::$server->getL10N('lib');
1425
-
1426
-		if ($date == '') {
1427
-			if (\OCP\Util::isDefaultExpireDateEnforced()) {
1428
-				$warning = 'Cannot clear expiration date. Shares are required to have an expiration date.';
1429
-				$warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.');
1430
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1431
-				throw new \Exception($warning_t);
1432
-			} else {
1433
-				$date = null;
1434
-			}
1435
-		} else {
1436
-			$date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
1437
-		}
1438
-		$query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ?  AND `uid_owner` = ? AND `share_type` = ?');
1439
-		$query->bindValue(1, $date, 'datetime');
1440
-		$query->bindValue(2, $itemType);
1441
-		$query->bindValue(3, $itemSource);
1442
-		$query->bindValue(4, $user);
1443
-		$query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
1444
-
1445
-		$query->execute();
1446
-
1447
-		\OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
1448
-			'itemType' => $itemType,
1449
-			'itemSource' => $itemSource,
1450
-			'date' => $date,
1451
-			'uidOwner' => $user
1452
-		));
1453
-
1454
-		return true;
1455
-	}
1456
-
1457
-	/**
1458
-	 * Retrieve the owner of a connection
1459
-	 *
1460
-	 * @param IDBConnection $connection
1461
-	 * @param int $shareId
1462
-	 * @throws \Exception
1463
-	 * @return string uid of share owner
1464
-	 */
1465
-	private static function getShareOwner(IDBConnection $connection, $shareId) {
1466
-		$qb = $connection->getQueryBuilder();
1467
-
1468
-		$qb->select('uid_owner')
1469
-			->from('share')
1470
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1471
-			->setParameter(':shareId', $shareId);
1472
-		$result = $qb->execute();
1473
-		$result = $result->fetch();
1474
-
1475
-		if (empty($result)) {
1476
-			throw new \Exception('Share not found');
1477
-		}
1478
-
1479
-		return $result['uid_owner'];
1480
-	}
1481
-
1482
-	/**
1483
-	 * Set password for a public link share
1484
-	 *
1485
-	 * @param IUserSession $userSession
1486
-	 * @param IDBConnection $connection
1487
-	 * @param IConfig $config
1488
-	 * @param int $shareId
1489
-	 * @param string $password
1490
-	 * @throws \Exception
1491
-	 * @return boolean
1492
-	 */
1493
-	public static function setPassword(IUserSession $userSession,
1494
-	                                   IDBConnection $connection,
1495
-	                                   IConfig $config,
1496
-	                                   $shareId, $password) {
1497
-		$user = $userSession->getUser();
1498
-		if (is_null($user)) {
1499
-			throw new \Exception("User not logged in");
1500
-		}
1501
-
1502
-		$uid = self::getShareOwner($connection, $shareId);
1503
-
1504
-		if ($uid !== $user->getUID()) {
1505
-			throw new \Exception('Cannot update share of a different user');
1506
-		}
1507
-
1508
-		if ($password === '') {
1509
-			$password = null;
1510
-		}
1511
-
1512
-		//If passwords are enforced the password can't be null
1513
-		if (self::enforcePassword($config) && is_null($password)) {
1514
-			throw new \Exception('Cannot remove password');
1515
-		}
1516
-
1517
-		self::verifyPassword($password);
1518
-
1519
-		$qb = $connection->getQueryBuilder();
1520
-		$qb->update('share')
1521
-			->set('share_with', $qb->createParameter('pass'))
1522
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1523
-			->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
1524
-			->setParameter(':shareId', $shareId);
1525
-
1526
-		$qb->execute();
1527
-
1528
-		return true;
1529
-	}
1530
-
1531
-	/**
1532
-	 * Checks whether a share has expired, calls unshareItem() if yes.
1533
-	 * @param array $item Share data (usually database row)
1534
-	 * @return boolean True if item was expired, false otherwise.
1535
-	 */
1536
-	protected static function expireItem(array $item) {
1537
-
1538
-		$result = false;
1539
-
1540
-		// only use default expiration date for link shares
1541
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
1542
-
1543
-			// calculate expiration date
1544
-			if (!empty($item['expiration'])) {
1545
-				$userDefinedExpire = new \DateTime($item['expiration']);
1546
-				$expires = $userDefinedExpire->getTimestamp();
1547
-			} else {
1548
-				$expires = null;
1549
-			}
1550
-
1551
-
1552
-			// get default expiration settings
1553
-			$defaultSettings = Helper::getDefaultExpireSetting();
1554
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
1555
-
1556
-
1557
-			if (is_int($expires)) {
1558
-				$now = time();
1559
-				if ($now > $expires) {
1560
-					self::unshareItem($item);
1561
-					$result = true;
1562
-				}
1563
-			}
1564
-		}
1565
-		return $result;
1566
-	}
1567
-
1568
-	/**
1569
-	 * Unshares a share given a share data array
1570
-	 * @param array $item Share data (usually database row)
1571
-	 * @param int $newParent parent ID
1572
-	 * @return null
1573
-	 */
1574
-	protected static function unshareItem(array $item, $newParent = null) {
1575
-
1576
-		$shareType = (int)$item['share_type'];
1577
-		$shareWith = null;
1578
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
1579
-			$shareWith = $item['share_with'];
1580
-		}
1581
-
1582
-		// Pass all the vars we have for now, they may be useful
1583
-		$hookParams = array(
1584
-			'id'            => $item['id'],
1585
-			'itemType'      => $item['item_type'],
1586
-			'itemSource'    => $item['item_source'],
1587
-			'shareType'     => $shareType,
1588
-			'shareWith'     => $shareWith,
1589
-			'itemParent'    => $item['parent'],
1590
-			'uidOwner'      => $item['uid_owner'],
1591
-		);
1592
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
1593
-			$hookParams['fileSource'] = $item['file_source'];
1594
-			$hookParams['fileTarget'] = $item['file_target'];
1595
-		}
1596
-
1597
-		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
1598
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
1599
-		$deletedShares[] = $hookParams;
1600
-		$hookParams['deletedShares'] = $deletedShares;
1601
-		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
1602
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
1603
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
1604
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
1605
-		}
1606
-	}
1607
-
1608
-	/**
1609
-	 * Get the backend class for the specified item type
1610
-	 * @param string $itemType
1611
-	 * @throws \Exception
1612
-	 * @return \OCP\Share_Backend
1613
-	 */
1614
-	public static function getBackend($itemType) {
1615
-		$l = \OC::$server->getL10N('lib');
1616
-		if (isset(self::$backends[$itemType])) {
1617
-			return self::$backends[$itemType];
1618
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
1619
-			$class = self::$backendTypes[$itemType]['class'];
1620
-			if (class_exists($class)) {
1621
-				self::$backends[$itemType] = new $class;
1622
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
1623
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
1624
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
1625
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1626
-					throw new \Exception($message_t);
1627
-				}
1628
-				return self::$backends[$itemType];
1629
-			} else {
1630
-				$message = 'Sharing backend %s not found';
1631
-				$message_t = $l->t('Sharing backend %s not found', array($class));
1632
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1633
-				throw new \Exception($message_t);
1634
-			}
1635
-		}
1636
-		$message = 'Sharing backend for %s not found';
1637
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
1638
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
1639
-		throw new \Exception($message_t);
1640
-	}
1641
-
1642
-	/**
1643
-	 * Check if resharing is allowed
1644
-	 * @return boolean true if allowed or false
1645
-	 *
1646
-	 * Resharing is allowed by default if not configured
1647
-	 */
1648
-	public static function isResharingAllowed() {
1649
-		if (!isset(self::$isResharingAllowed)) {
1650
-			if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
1651
-				self::$isResharingAllowed = true;
1652
-			} else {
1653
-				self::$isResharingAllowed = false;
1654
-			}
1655
-		}
1656
-		return self::$isResharingAllowed;
1657
-	}
1658
-
1659
-	/**
1660
-	 * Get a list of collection item types for the specified item type
1661
-	 * @param string $itemType
1662
-	 * @return array
1663
-	 */
1664
-	private static function getCollectionItemTypes($itemType) {
1665
-		$collectionTypes = array($itemType);
1666
-		foreach (self::$backendTypes as $type => $backend) {
1667
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
1668
-				$collectionTypes[] = $type;
1669
-			}
1670
-		}
1671
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1672
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1673
-			unset($collectionTypes[0]);
1674
-		}
1675
-		// Return array if collections were found or the item type is a
1676
-		// collection itself - collections can be inside collections
1677
-		if (count($collectionTypes) > 0) {
1678
-			return $collectionTypes;
1679
-		}
1680
-		return false;
1681
-	}
1682
-
1683
-	/**
1684
-	 * Get the owners of items shared with a user.
1685
-	 *
1686
-	 * @param string $user The user the items are shared with.
1687
-	 * @param string $type The type of the items shared with the user.
1688
-	 * @param boolean $includeCollections Include collection item types (optional)
1689
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1690
-	 * @return array
1691
-	 */
1692
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1693
-		// First, we find out if $type is part of a collection (and if that collection is part of
1694
-		// another one and so on).
1695
-		$collectionTypes = array();
1696
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1697
-			$collectionTypes[] = $type;
1698
-		}
1699
-
1700
-		// Of these collection types, along with our original $type, we make a
1701
-		// list of the ones for which a sharing backend has been registered.
1702
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1703
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1704
-		$allMaybeSharedItems = array();
1705
-		foreach ($collectionTypes as $collectionType) {
1706
-			if (isset(self::$backends[$collectionType])) {
1707
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1708
-					$collectionType,
1709
-					$user,
1710
-					self::FORMAT_NONE
1711
-				);
1712
-			}
1713
-		}
1714
-
1715
-		$owners = array();
1716
-		if ($includeOwner) {
1717
-			$owners[] = $user;
1718
-		}
1719
-
1720
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
1721
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
1722
-		// and return them as elements of a list that look like "Tag (owner)".
1723
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1724
-			foreach ($maybeSharedItems as $sharedItem) {
1725
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1726
-					$owners[] = $sharedItem['uid_owner'];
1727
-				}
1728
-			}
1729
-		}
1730
-
1731
-		return $owners;
1732
-	}
1733
-
1734
-	/**
1735
-	 * Get shared items from the database
1736
-	 * @param string $itemType
1737
-	 * @param string $item Item source or target (optional)
1738
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1739
-	 * @param string $shareWith User or group the item is being shared with
1740
-	 * @param string $uidOwner User that is the owner of shared items (optional)
1741
-	 * @param int $format Format to convert items to with formatItems() (optional)
1742
-	 * @param mixed $parameters to pass to formatItems() (optional)
1743
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
1744
-	 * @param boolean $includeCollections Include collection item types (optional)
1745
-	 * @param boolean $itemShareWithBySource (optional)
1746
-	 * @param boolean $checkExpireDate
1747
-	 * @return array
1748
-	 *
1749
-	 * See public functions getItem(s)... for parameter usage
1750
-	 *
1751
-	 */
1752
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1753
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1754
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1755
-		if (!self::isEnabled()) {
1756
-			return array();
1757
-		}
1758
-		$backend = self::getBackend($itemType);
1759
-		$collectionTypes = false;
1760
-		// Get filesystem root to add it to the file target and remove from the
1761
-		// file source, match file_source with the file cache
1762
-		if ($itemType == 'file' || $itemType == 'folder') {
1763
-			if(!is_null($uidOwner)) {
1764
-				$root = \OC\Files\Filesystem::getRoot();
1765
-			} else {
1766
-				$root = '';
1767
-			}
1768
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1769
-			if (!isset($item)) {
1770
-				$where .= ' AND `file_target` IS NOT NULL ';
1771
-			}
1772
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1773
-			$fileDependent = true;
1774
-			$queryArgs = array();
1775
-		} else {
1776
-			$fileDependent = false;
1777
-			$root = '';
1778
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1779
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1780
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1781
-				if (!in_array($itemType, $collectionTypes)) {
1782
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1783
-				} else {
1784
-					$itemTypes = $collectionTypes;
1785
-				}
1786
-				$placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1787
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1788
-				$queryArgs = $itemTypes;
1789
-			} else {
1790
-				$where = ' WHERE `item_type` = ?';
1791
-				$queryArgs = array($itemType);
1792
-			}
1793
-		}
1794
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1795
-			$where .= ' AND `share_type` != ?';
1796
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1797
-		}
1798
-		if (isset($shareType)) {
1799
-			// Include all user and group items
1800
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1801
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1802
-				$queryArgs[] = self::SHARE_TYPE_USER;
1803
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1804
-				$queryArgs[] = $shareWith;
1805
-
1806
-				$user = \OC::$server->getUserManager()->get($shareWith);
1807
-				$groups = [];
1808
-				if ($user) {
1809
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1810
-				}
1811
-				if (!empty($groups)) {
1812
-					$placeholders = join(',', array_fill(0, count($groups), '?'));
1813
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1814
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1815
-					$queryArgs = array_merge($queryArgs, $groups);
1816
-				}
1817
-				$where .= ')';
1818
-				// Don't include own group shares
1819
-				$where .= ' AND `uid_owner` != ?';
1820
-				$queryArgs[] = $shareWith;
1821
-			} else {
1822
-				$where .= ' AND `share_type` = ?';
1823
-				$queryArgs[] = $shareType;
1824
-				if (isset($shareWith)) {
1825
-					$where .= ' AND `share_with` = ?';
1826
-					$queryArgs[] = $shareWith;
1827
-				}
1828
-			}
1829
-		}
1830
-		if (isset($uidOwner)) {
1831
-			$where .= ' AND `uid_owner` = ?';
1832
-			$queryArgs[] = $uidOwner;
1833
-			if (!isset($shareType)) {
1834
-				// Prevent unique user targets for group shares from being selected
1835
-				$where .= ' AND `share_type` != ?';
1836
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1837
-			}
1838
-			if ($fileDependent) {
1839
-				$column = 'file_source';
1840
-			} else {
1841
-				$column = 'item_source';
1842
-			}
1843
-		} else {
1844
-			if ($fileDependent) {
1845
-				$column = 'file_target';
1846
-			} else {
1847
-				$column = 'item_target';
1848
-			}
1849
-		}
1850
-		if (isset($item)) {
1851
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1852
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1853
-				$where .= ' AND (';
1854
-			} else {
1855
-				$where .= ' AND';
1856
-			}
1857
-			// If looking for own shared items, check item_source else check item_target
1858
-			if (isset($uidOwner) || $itemShareWithBySource) {
1859
-				// If item type is a file, file source needs to be checked in case the item was converted
1860
-				if ($fileDependent) {
1861
-					$where .= ' `file_source` = ?';
1862
-					$column = 'file_source';
1863
-				} else {
1864
-					$where .= ' `item_source` = ?';
1865
-					$column = 'item_source';
1866
-				}
1867
-			} else {
1868
-				if ($fileDependent) {
1869
-					$where .= ' `file_target` = ?';
1870
-					$item = \OC\Files\Filesystem::normalizePath($item);
1871
-				} else {
1872
-					$where .= ' `item_target` = ?';
1873
-				}
1874
-			}
1875
-			$queryArgs[] = $item;
1876
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1877
-				$placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1878
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1879
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1880
-			}
1881
-		}
1882
-
1883
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1884
-			// Make sure the unique user target is returned if it exists,
1885
-			// unique targets should follow the group share in the database
1886
-			// If the limit is not 1, the filtering can be done later
1887
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1888
-		} else {
1889
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1890
-		}
1891
-
1892
-		if ($limit != -1 && !$includeCollections) {
1893
-			// The limit must be at least 3, because filtering needs to be done
1894
-			if ($limit < 3) {
1895
-				$queryLimit = 3;
1896
-			} else {
1897
-				$queryLimit = $limit;
1898
-			}
1899
-		} else {
1900
-			$queryLimit = null;
1901
-		}
1902
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1903
-		$root = strlen($root);
1904
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1905
-		$result = $query->execute($queryArgs);
1906
-		if ($result === false) {
1907
-			\OCP\Util::writeLog('OCP\Share',
1908
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1909
-				\OCP\Util::ERROR);
1910
-		}
1911
-		$items = array();
1912
-		$targets = array();
1913
-		$switchedItems = array();
1914
-		$mounts = array();
1915
-		while ($row = $result->fetchRow()) {
1916
-			self::transformDBResults($row);
1917
-			// Filter out duplicate group shares for users with unique targets
1918
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1919
-				continue;
1920
-			}
1921
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1922
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1923
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1924
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1925
-				// if the group share was unshared from the user we keep the permission, otherwise
1926
-				// we take the permission from the parent because this is always the up-to-date
1927
-				// permission for the group share
1928
-				if ($row['permissions'] > 0) {
1929
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1930
-				}
1931
-				// Remove the parent group share
1932
-				unset($items[$row['parent']]);
1933
-				if ($row['permissions'] == 0) {
1934
-					continue;
1935
-				}
1936
-			} else if (!isset($uidOwner)) {
1937
-				// Check if the same target already exists
1938
-				if (isset($targets[$row['id']])) {
1939
-					// Check if the same owner shared with the user twice
1940
-					// through a group and user share - this is allowed
1941
-					$id = $targets[$row['id']];
1942
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1943
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1944
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1945
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1946
-							$items[$id]['share_with'] = $row['share_with'];
1947
-						}
1948
-						// Switch ids if sharing permission is granted on only
1949
-						// one share to ensure correct parent is used if resharing
1950
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1951
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1952
-							$items[$row['id']] = $items[$id];
1953
-							$switchedItems[$id] = $row['id'];
1954
-							unset($items[$id]);
1955
-							$id = $row['id'];
1956
-						}
1957
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1958
-
1959
-					}
1960
-					continue;
1961
-				} elseif (!empty($row['parent'])) {
1962
-					$targets[$row['parent']] = $row['id'];
1963
-				}
1964
-			}
1965
-			// Remove root from file source paths if retrieving own shared items
1966
-			if (isset($uidOwner) && isset($row['path'])) {
1967
-				if (isset($row['parent'])) {
1968
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1969
-					$parentResult = $query->execute(array($row['parent']));
1970
-					if ($result === false) {
1971
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1972
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1973
-							\OCP\Util::ERROR);
1974
-					} else {
1975
-						$parentRow = $parentResult->fetchRow();
1976
-						$tmpPath = $parentRow['file_target'];
1977
-						// find the right position where the row path continues from the target path
1978
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1979
-						$subPath = substr($row['path'], $pos);
1980
-						$splitPath = explode('/', $subPath);
1981
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1982
-							$tmpPath = $tmpPath . '/' . $pathPart;
1983
-						}
1984
-						$row['path'] = $tmpPath;
1985
-					}
1986
-				} else {
1987
-					if (!isset($mounts[$row['storage']])) {
1988
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1989
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1990
-							$mounts[$row['storage']] = current($mountPoints);
1991
-						}
1992
-					}
1993
-					if (!empty($mounts[$row['storage']])) {
1994
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1995
-						$relPath = substr($path, $root); // path relative to data/user
1996
-						$row['path'] = rtrim($relPath, '/');
1997
-					}
1998
-				}
1999
-			}
2000
-
2001
-			if($checkExpireDate) {
2002
-				if (self::expireItem($row)) {
2003
-					continue;
2004
-				}
2005
-			}
2006
-			// Check if resharing is allowed, if not remove share permission
2007
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
2008
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
2009
-			}
2010
-			// Add display names to result
2011
-			$row['share_with_displayname'] = $row['share_with'];
2012
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
2013
-				$row['share_type'] === self::SHARE_TYPE_USER) {
2014
-				$row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
2015
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
2016
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
2017
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
2018
-				foreach ($addressBookEntries as $entry) {
2019
-					foreach ($entry['CLOUD'] as $cloudID) {
2020
-						if ($cloudID === $row['share_with']) {
2021
-							$row['share_with_displayname'] = $entry['FN'];
2022
-						}
2023
-					}
2024
-				}
2025
-			}
2026
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
2027
-				$row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
2028
-			}
2029
-
2030
-			if ($row['permissions'] > 0) {
2031
-				$items[$row['id']] = $row;
2032
-			}
2033
-
2034
-		}
2035
-
2036
-		// group items if we are looking for items shared with the current user
2037
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
2038
-			$items = self::groupItems($items, $itemType);
2039
-		}
2040
-
2041
-		if (!empty($items)) {
2042
-			$collectionItems = array();
2043
-			foreach ($items as &$row) {
2044
-				// Return only the item instead of a 2-dimensional array
2045
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
2046
-					if ($format == self::FORMAT_NONE) {
2047
-						return $row;
2048
-					} else {
2049
-						break;
2050
-					}
2051
-				}
2052
-				// Check if this is a collection of the requested item type
2053
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
2054
-					if (($collectionBackend = self::getBackend($row['item_type']))
2055
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
2056
-						// Collections can be inside collections, check if the item is a collection
2057
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
2058
-							$collectionItems[] = $row;
2059
-						} else {
2060
-							$collection = array();
2061
-							$collection['item_type'] = $row['item_type'];
2062
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2063
-								$collection['path'] = basename($row['path']);
2064
-							}
2065
-							$row['collection'] = $collection;
2066
-							// Fetch all of the children sources
2067
-							$children = $collectionBackend->getChildren($row[$column]);
2068
-							foreach ($children as $child) {
2069
-								$childItem = $row;
2070
-								$childItem['item_type'] = $itemType;
2071
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
2072
-									$childItem['item_source'] = $child['source'];
2073
-									$childItem['item_target'] = $child['target'];
2074
-								}
2075
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2076
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2077
-										$childItem['file_source'] = $child['source'];
2078
-									} else { // TODO is this really needed if we already know that we use the file backend?
2079
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
2080
-										$childItem['file_source'] = $meta['fileid'];
2081
-									}
2082
-									$childItem['file_target'] =
2083
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
2084
-								}
2085
-								if (isset($item)) {
2086
-									if ($childItem[$column] == $item) {
2087
-										// Return only the item instead of a 2-dimensional array
2088
-										if ($limit == 1) {
2089
-											if ($format == self::FORMAT_NONE) {
2090
-												return $childItem;
2091
-											} else {
2092
-												// Unset the items array and break out of both loops
2093
-												$items = array();
2094
-												$items[] = $childItem;
2095
-												break 2;
2096
-											}
2097
-										} else {
2098
-											$collectionItems[] = $childItem;
2099
-										}
2100
-									}
2101
-								} else {
2102
-									$collectionItems[] = $childItem;
2103
-								}
2104
-							}
2105
-						}
2106
-					}
2107
-					// Remove collection item
2108
-					$toRemove = $row['id'];
2109
-					if (array_key_exists($toRemove, $switchedItems)) {
2110
-						$toRemove = $switchedItems[$toRemove];
2111
-					}
2112
-					unset($items[$toRemove]);
2113
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
2114
-					// FIXME: Thats a dirty hack to improve file sharing performance,
2115
-					// see github issue #10588 for more details
2116
-					// Need to find a solution which works for all back-ends
2117
-					$collectionBackend = self::getBackend($row['item_type']);
2118
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
2119
-					foreach ($sharedParents as $parent) {
2120
-						$collectionItems[] = $parent;
2121
-					}
2122
-				}
2123
-			}
2124
-			if (!empty($collectionItems)) {
2125
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
2126
-				$items = array_merge($items, $collectionItems);
2127
-			}
2128
-
2129
-			// filter out invalid items, these can appear when subshare entries exist
2130
-			// for a group in which the requested user isn't a member any more
2131
-			$items = array_filter($items, function($item) {
2132
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
2133
-			});
2134
-
2135
-			return self::formatResult($items, $column, $backend, $format, $parameters);
2136
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
2137
-			// FIXME: Thats a dirty hack to improve file sharing performance,
2138
-			// see github issue #10588 for more details
2139
-			// Need to find a solution which works for all back-ends
2140
-			$collectionItems = array();
2141
-			$collectionBackend = self::getBackend('folder');
2142
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
2143
-			foreach ($sharedParents as $parent) {
2144
-				$collectionItems[] = $parent;
2145
-			}
2146
-			if ($limit === 1) {
2147
-				return reset($collectionItems);
2148
-			}
2149
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
2150
-		}
2151
-
2152
-		return array();
2153
-	}
2154
-
2155
-	/**
2156
-	 * group items with link to the same source
2157
-	 *
2158
-	 * @param array $items
2159
-	 * @param string $itemType
2160
-	 * @return array of grouped items
2161
-	 */
2162
-	protected static function groupItems($items, $itemType) {
2163
-
2164
-		$fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
2165
-
2166
-		$result = array();
2167
-
2168
-		foreach ($items as $item) {
2169
-			$grouped = false;
2170
-			foreach ($result as $key => $r) {
2171
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
2172
-				// only group shares if they already point to the same target, otherwise the file where shared
2173
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
2174
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
2175
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
2176
-					// add the first item to the list of grouped shares
2177
-					if (!isset($result[$key]['grouped'])) {
2178
-						$result[$key]['grouped'][] = $result[$key];
2179
-					}
2180
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
2181
-					$result[$key]['grouped'][] = $item;
2182
-					$grouped = true;
2183
-					break;
2184
-				}
2185
-			}
2186
-
2187
-			if (!$grouped) {
2188
-				$result[] = $item;
2189
-			}
2190
-
2191
-		}
2192
-
2193
-		return $result;
2194
-	}
2195
-
2196
-	/**
2197
-	 * Put shared item into the database
2198
-	 * @param string $itemType Item type
2199
-	 * @param string $itemSource Item source
2200
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
2201
-	 * @param string $shareWith User or group the item is being shared with
2202
-	 * @param string $uidOwner User that is the owner of shared item
2203
-	 * @param int $permissions CRUDS permissions
2204
-	 * @param boolean|array $parentFolder Parent folder target (optional)
2205
-	 * @param string $token (optional)
2206
-	 * @param string $itemSourceName name of the source item (optional)
2207
-	 * @param \DateTime $expirationDate (optional)
2208
-	 * @throws \Exception
2209
-	 * @return mixed id of the new share or false
2210
-	 */
2211
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2212
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
2213
-
2214
-		$queriesToExecute = array();
2215
-		$suggestedItemTarget = null;
2216
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
2217
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
2218
-
2219
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
2220
-		if(!empty($result)) {
2221
-			$parent = $result['parent'];
2222
-			$itemSource = $result['itemSource'];
2223
-			$fileSource = $result['fileSource'];
2224
-			$suggestedItemTarget = $result['suggestedItemTarget'];
2225
-			$suggestedFileTarget = $result['suggestedFileTarget'];
2226
-			$filePath = $result['filePath'];
2227
-		}
2228
-
2229
-		$isGroupShare = false;
2230
-		if ($shareType == self::SHARE_TYPE_GROUP) {
2231
-			$isGroupShare = true;
2232
-			if (isset($shareWith['users'])) {
2233
-				$users = $shareWith['users'];
2234
-			} else {
2235
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
2236
-				if ($group) {
2237
-					$users = $group->searchUsers('', -1, 0);
2238
-					$userIds = [];
2239
-					foreach ($users as $user) {
2240
-						$userIds[] = $user->getUID();
2241
-					}
2242
-					$users = $userIds;
2243
-				} else {
2244
-					$users = [];
2245
-				}
2246
-			}
2247
-			// remove current user from list
2248
-			if (in_array(\OCP\User::getUser(), $users)) {
2249
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
2250
-			}
2251
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
2252
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
2253
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
2254
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
2255
-
2256
-			// add group share to table and remember the id as parent
2257
-			$queriesToExecute['groupShare'] = array(
2258
-				'itemType'			=> $itemType,
2259
-				'itemSource'		=> $itemSource,
2260
-				'itemTarget'		=> $groupItemTarget,
2261
-				'shareType'			=> $shareType,
2262
-				'shareWith'			=> $shareWith['group'],
2263
-				'uidOwner'			=> $uidOwner,
2264
-				'permissions'		=> $permissions,
2265
-				'shareTime'			=> time(),
2266
-				'fileSource'		=> $fileSource,
2267
-				'fileTarget'		=> $groupFileTarget,
2268
-				'token'				=> $token,
2269
-				'parent'			=> $parent,
2270
-				'expiration'		=> $expirationDate,
2271
-			);
2272
-
2273
-		} else {
2274
-			$users = array($shareWith);
2275
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2276
-				$suggestedItemTarget);
2277
-		}
2278
-
2279
-		$run = true;
2280
-		$error = '';
2281
-		$preHookData = array(
2282
-			'itemType' => $itemType,
2283
-			'itemSource' => $itemSource,
2284
-			'shareType' => $shareType,
2285
-			'uidOwner' => $uidOwner,
2286
-			'permissions' => $permissions,
2287
-			'fileSource' => $fileSource,
2288
-			'expiration' => $expirationDate,
2289
-			'token' => $token,
2290
-			'run' => &$run,
2291
-			'error' => &$error
2292
-		);
2293
-
2294
-		$preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2295
-		$preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2296
-
2297
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
2298
-
2299
-		if ($run === false) {
2300
-			throw new \Exception($error);
2301
-		}
2302
-
2303
-		foreach ($users as $user) {
2304
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
2305
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
2306
-
2307
-			$userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
2308
-
2309
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
2310
-				$fileTarget = $sourceExists['file_target'];
2311
-				$itemTarget = $sourceExists['item_target'];
2312
-
2313
-				// for group shares we don't need a additional entry if the target is the same
2314
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
2315
-					continue;
2316
-				}
2317
-
2318
-			} elseif(!$sourceExists && !$isGroupShare)  {
2319
-
2320
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
2321
-					$uidOwner, $suggestedItemTarget, $parent);
2322
-				if (isset($fileSource)) {
2323
-					if ($parentFolder) {
2324
-						if ($parentFolder === true) {
2325
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
2326
-								$uidOwner, $suggestedFileTarget, $parent);
2327
-							if ($fileTarget != $groupFileTarget) {
2328
-								$parentFolders[$user]['folder'] = $fileTarget;
2329
-							}
2330
-						} else if (isset($parentFolder[$user])) {
2331
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
2332
-							$parent = $parentFolder[$user]['id'];
2333
-						}
2334
-					} else {
2335
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
2336
-							$user, $uidOwner, $suggestedFileTarget, $parent);
2337
-					}
2338
-				} else {
2339
-					$fileTarget = null;
2340
-				}
2341
-
2342
-			} else {
2343
-
2344
-				// group share which doesn't exists until now, check if we need a unique target for this user
2345
-
2346
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
2347
-					$uidOwner, $suggestedItemTarget, $parent);
2348
-
2349
-				// do we also need a file target
2350
-				if (isset($fileSource)) {
2351
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
2352
-						$uidOwner, $suggestedFileTarget, $parent);
2353
-				} else {
2354
-					$fileTarget = null;
2355
-				}
2356
-
2357
-				if (($itemTarget === $groupItemTarget) &&
2358
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
2359
-					continue;
2360
-				}
2361
-			}
2362
-
2363
-			$queriesToExecute[] = array(
2364
-				'itemType'			=> $itemType,
2365
-				'itemSource'		=> $itemSource,
2366
-				'itemTarget'		=> $itemTarget,
2367
-				'shareType'			=> $userShareType,
2368
-				'shareWith'			=> $user,
2369
-				'uidOwner'			=> $uidOwner,
2370
-				'permissions'		=> $permissions,
2371
-				'shareTime'			=> time(),
2372
-				'fileSource'		=> $fileSource,
2373
-				'fileTarget'		=> $fileTarget,
2374
-				'token'				=> $token,
2375
-				'parent'			=> $parent,
2376
-				'expiration'		=> $expirationDate,
2377
-			);
2378
-
2379
-		}
2380
-
2381
-		$id = false;
2382
-		if ($isGroupShare) {
2383
-			$id = self::insertShare($queriesToExecute['groupShare']);
2384
-			// Save this id, any extra rows for this group share will need to reference it
2385
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2386
-			unset($queriesToExecute['groupShare']);
2387
-		}
2388
-
2389
-		foreach ($queriesToExecute as $shareQuery) {
2390
-			$shareQuery['parent'] = $parent;
2391
-			$id = self::insertShare($shareQuery);
2392
-		}
2393
-
2394
-		$postHookData = array(
2395
-			'itemType' => $itemType,
2396
-			'itemSource' => $itemSource,
2397
-			'parent' => $parent,
2398
-			'shareType' => $shareType,
2399
-			'uidOwner' => $uidOwner,
2400
-			'permissions' => $permissions,
2401
-			'fileSource' => $fileSource,
2402
-			'id' => $parent,
2403
-			'token' => $token,
2404
-			'expirationDate' => $expirationDate,
2405
-		);
2406
-
2407
-		$postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2408
-		$postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2409
-		$postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
2410
-
2411
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
2412
-
2413
-
2414
-		return $id ? $id : false;
2415
-	}
2416
-
2417
-	/**
2418
-	 * @param string $itemType
2419
-	 * @param string $itemSource
2420
-	 * @param int $shareType
2421
-	 * @param string $shareWith
2422
-	 * @param string $uidOwner
2423
-	 * @param int $permissions
2424
-	 * @param string|null $itemSourceName
2425
-	 * @param null|\DateTime $expirationDate
2426
-	 */
2427
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
2428
-		$backend = self::getBackend($itemType);
2429
-
2430
-		$l = \OC::$server->getL10N('lib');
2431
-		$result = array();
2432
-
2433
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
2434
-
2435
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
2436
-		if ($checkReshare) {
2437
-			// Check if attempting to share back to owner
2438
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
2439
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
2440
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
2441
-
2442
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
2443
-				throw new \Exception($message_t);
2444
-			}
2445
-		}
2446
-
2447
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
2448
-			// Check if share permissions is granted
2449
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
2450
-				if (~(int)$checkReshare['permissions'] & $permissions) {
2451
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
2452
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
2453
-
2454
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
2455
-					throw new \Exception($message_t);
2456
-				} else {
2457
-					// TODO Don't check if inside folder
2458
-					$result['parent'] = $checkReshare['id'];
2459
-
2460
-					$result['expirationDate'] = $expirationDate;
2461
-					// $checkReshare['expiration'] could be null and then is always less than any value
2462
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
2463
-						$result['expirationDate'] = $checkReshare['expiration'];
2464
-					}
2465
-
2466
-					// only suggest the same name as new target if it is a reshare of the
2467
-					// same file/folder and not the reshare of a child
2468
-					if ($checkReshare[$column] === $itemSource) {
2469
-						$result['filePath'] = $checkReshare['file_target'];
2470
-						$result['itemSource'] = $checkReshare['item_source'];
2471
-						$result['fileSource'] = $checkReshare['file_source'];
2472
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
2473
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
2474
-					} else {
2475
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
2476
-						$result['suggestedItemTarget'] = null;
2477
-						$result['suggestedFileTarget'] = null;
2478
-						$result['itemSource'] = $itemSource;
2479
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
2480
-					}
2481
-				}
2482
-			} else {
2483
-				$message = 'Sharing %s failed, because resharing is not allowed';
2484
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
2485
-
2486
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
2487
-				throw new \Exception($message_t);
2488
-			}
2489
-		} else {
2490
-			$result['parent'] = null;
2491
-			$result['suggestedItemTarget'] = null;
2492
-			$result['suggestedFileTarget'] = null;
2493
-			$result['itemSource'] = $itemSource;
2494
-			$result['expirationDate'] = $expirationDate;
2495
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
2496
-				$message = 'Sharing %s failed, because the sharing backend for '
2497
-					.'%s could not find its source';
2498
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
2499
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
2500
-				throw new \Exception($message_t);
2501
-			}
2502
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2503
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
2504
-				if ($itemType == 'file' || $itemType == 'folder') {
2505
-					$result['fileSource'] = $itemSource;
2506
-				} else {
2507
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
2508
-					$result['fileSource'] = $meta['fileid'];
2509
-				}
2510
-				if ($result['fileSource'] == -1) {
2511
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
2512
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
2513
-
2514
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
2515
-					throw new \Exception($message_t);
2516
-				}
2517
-			} else {
2518
-				$result['filePath'] = null;
2519
-				$result['fileSource'] = null;
2520
-			}
2521
-		}
2522
-
2523
-		return $result;
2524
-	}
2525
-
2526
-	/**
2527
-	 *
2528
-	 * @param array $shareData
2529
-	 * @return mixed false in case of a failure or the id of the new share
2530
-	 */
2531
-	private static function insertShare(array $shareData) {
2532
-
2533
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
2534
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
2535
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
2536
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
2537
-		$query->bindValue(1, $shareData['itemType']);
2538
-		$query->bindValue(2, $shareData['itemSource']);
2539
-		$query->bindValue(3, $shareData['itemTarget']);
2540
-		$query->bindValue(4, $shareData['shareType']);
2541
-		$query->bindValue(5, $shareData['shareWith']);
2542
-		$query->bindValue(6, $shareData['uidOwner']);
2543
-		$query->bindValue(7, $shareData['permissions']);
2544
-		$query->bindValue(8, $shareData['shareTime']);
2545
-		$query->bindValue(9, $shareData['fileSource']);
2546
-		$query->bindValue(10, $shareData['fileTarget']);
2547
-		$query->bindValue(11, $shareData['token']);
2548
-		$query->bindValue(12, $shareData['parent']);
2549
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
2550
-		$result = $query->execute();
2551
-
2552
-		$id = false;
2553
-		if ($result) {
2554
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2555
-		}
2556
-
2557
-		return $id;
2558
-
2559
-	}
2560
-
2561
-	/**
2562
-	 * Delete all shares with type SHARE_TYPE_LINK
2563
-	 */
2564
-	public static function removeAllLinkShares() {
2565
-		// Delete any link shares
2566
-		$query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
2567
-		$result = $query->execute(array(self::SHARE_TYPE_LINK));
2568
-		while ($item = $result->fetchRow()) {
2569
-			Helper::delete($item['id']);
2570
-		}
2571
-	}
2572
-
2573
-	/**
2574
-	 * In case a password protected link is not yet authenticated this function will return false
2575
-	 *
2576
-	 * @param array $linkItem
2577
-	 * @return boolean
2578
-	 */
2579
-	public static function checkPasswordProtectedShare(array $linkItem) {
2580
-		if (!isset($linkItem['share_with'])) {
2581
-			return true;
2582
-		}
2583
-		if (!isset($linkItem['share_type'])) {
2584
-			return true;
2585
-		}
2586
-		if (!isset($linkItem['id'])) {
2587
-			return true;
2588
-		}
2589
-
2590
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
2591
-			return true;
2592
-		}
2593
-
2594
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
2595
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
2596
-			return true;
2597
-		}
2598
-
2599
-		return false;
2600
-	}
2601
-
2602
-	/**
2603
-	 * construct select statement
2604
-	 * @param int $format
2605
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
2606
-	 * @param string $uidOwner
2607
-	 * @return string select statement
2608
-	 */
2609
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
2610
-		$select = '*';
2611
-		if ($format == self::FORMAT_STATUSES) {
2612
-			if ($fileDependent) {
2613
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
2614
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
2615
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2616
-					. '`uid_initiator`';
2617
-			} else {
2618
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
2619
-			}
2620
-		} else {
2621
-			if (isset($uidOwner)) {
2622
-				if ($fileDependent) {
2623
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
2624
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
2625
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
2626
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2627
-				} else {
2628
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
2629
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
2630
-				}
2631
-			} else {
2632
-				if ($fileDependent) {
2633
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
2634
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
2635
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
2636
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2637
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
2638
-					} else {
2639
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
2640
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
2641
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
2642
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
2643
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2644
-					}
2645
-				}
2646
-			}
2647
-		}
2648
-		return $select;
2649
-	}
2650
-
2651
-
2652
-	/**
2653
-	 * transform db results
2654
-	 * @param array $row result
2655
-	 */
2656
-	private static function transformDBResults(&$row) {
2657
-		if (isset($row['id'])) {
2658
-			$row['id'] = (int) $row['id'];
2659
-		}
2660
-		if (isset($row['share_type'])) {
2661
-			$row['share_type'] = (int) $row['share_type'];
2662
-		}
2663
-		if (isset($row['parent'])) {
2664
-			$row['parent'] = (int) $row['parent'];
2665
-		}
2666
-		if (isset($row['file_parent'])) {
2667
-			$row['file_parent'] = (int) $row['file_parent'];
2668
-		}
2669
-		if (isset($row['file_source'])) {
2670
-			$row['file_source'] = (int) $row['file_source'];
2671
-		}
2672
-		if (isset($row['permissions'])) {
2673
-			$row['permissions'] = (int) $row['permissions'];
2674
-		}
2675
-		if (isset($row['storage'])) {
2676
-			$row['storage'] = (int) $row['storage'];
2677
-		}
2678
-		if (isset($row['stime'])) {
2679
-			$row['stime'] = (int) $row['stime'];
2680
-		}
2681
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2682
-			// discard expiration date for non-link shares, which might have been
2683
-			// set by ancient bugs
2684
-			$row['expiration'] = null;
2685
-		}
2686
-	}
2687
-
2688
-	/**
2689
-	 * format result
2690
-	 * @param array $items result
2691
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2692
-	 * @param \OCP\Share_Backend $backend sharing backend
2693
-	 * @param int $format
2694
-	 * @param array $parameters additional format parameters
2695
-	 * @return array format result
2696
-	 */
2697
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2698
-		if ($format === self::FORMAT_NONE) {
2699
-			return $items;
2700
-		} else if ($format === self::FORMAT_STATUSES) {
2701
-			$statuses = array();
2702
-			foreach ($items as $item) {
2703
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2704
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2705
-						continue;
2706
-					}
2707
-					$statuses[$item[$column]]['link'] = true;
2708
-				} else if (!isset($statuses[$item[$column]])) {
2709
-					$statuses[$item[$column]]['link'] = false;
2710
-				}
2711
-				if (!empty($item['file_target'])) {
2712
-					$statuses[$item[$column]]['path'] = $item['path'];
2713
-				}
2714
-			}
2715
-			return $statuses;
2716
-		} else {
2717
-			return $backend->formatItems($items, $format, $parameters);
2718
-		}
2719
-	}
2720
-
2721
-	/**
2722
-	 * remove protocol from URL
2723
-	 *
2724
-	 * @param string $url
2725
-	 * @return string
2726
-	 */
2727
-	public static function removeProtocolFromUrl($url) {
2728
-		if (strpos($url, 'https://') === 0) {
2729
-			return substr($url, strlen('https://'));
2730
-		} else if (strpos($url, 'http://') === 0) {
2731
-			return substr($url, strlen('http://'));
2732
-		}
2733
-
2734
-		return $url;
2735
-	}
2736
-
2737
-	/**
2738
-	 * try http post first with https and then with http as a fallback
2739
-	 *
2740
-	 * @param string $remoteDomain
2741
-	 * @param string $urlSuffix
2742
-	 * @param array $fields post parameters
2743
-	 * @return array
2744
-	 */
2745
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2746
-		$protocol = 'https://';
2747
-		$result = [
2748
-			'success' => false,
2749
-			'result' => '',
2750
-		];
2751
-		$try = 0;
2752
-		$discoveryService = \OC::$server->getOCSDiscoveryService();
2753
-		while ($result['success'] === false && $try < 2) {
2754
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2755
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2756
-			$result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2757
-			$try++;
2758
-			$protocol = 'http://';
2759
-		}
2760
-
2761
-		return $result;
2762
-	}
2763
-
2764
-	/**
2765
-	 * send server-to-server share to remote server
2766
-	 *
2767
-	 * @param string $token
2768
-	 * @param string $shareWith
2769
-	 * @param string $name
2770
-	 * @param int $remote_id
2771
-	 * @param string $owner
2772
-	 * @return bool
2773
-	 */
2774
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2775
-
2776
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2777
-
2778
-		if ($user && $remote) {
2779
-			$url = $remote;
2780
-
2781
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2782
-
2783
-			$fields = array(
2784
-				'shareWith' => $user,
2785
-				'token' => $token,
2786
-				'name' => $name,
2787
-				'remoteId' => $remote_id,
2788
-				'owner' => $owner,
2789
-				'remote' => $local,
2790
-			);
2791
-
2792
-			$url = self::removeProtocolFromUrl($url);
2793
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2794
-			$status = json_decode($result['result'], true);
2795
-
2796
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2797
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2798
-				return true;
2799
-			}
2800
-
2801
-		}
2802
-
2803
-		return false;
2804
-	}
2805
-
2806
-	/**
2807
-	 * send server-to-server unshare to remote server
2808
-	 *
2809
-	 * @param string $remote url
2810
-	 * @param int $id share id
2811
-	 * @param string $token
2812
-	 * @return bool
2813
-	 */
2814
-	private static function sendRemoteUnshare($remote, $id, $token) {
2815
-		$url = rtrim($remote, '/');
2816
-		$fields = array('token' => $token, 'format' => 'json');
2817
-		$url = self::removeProtocolFromUrl($url);
2818
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2819
-		$status = json_decode($result['result'], true);
2820
-
2821
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2822
-	}
2823
-
2824
-	/**
2825
-	 * check if user can only share with group members
2826
-	 * @return bool
2827
-	 */
2828
-	public static function shareWithGroupMembersOnly() {
2829
-		$value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no');
2830
-		return ($value === 'yes') ? true : false;
2831
-	}
2832
-
2833
-	/**
2834
-	 * @return bool
2835
-	 */
2836
-	public static function isDefaultExpireDateEnabled() {
2837
-		$defaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
2838
-		return ($defaultExpireDateEnabled === "yes") ? true : false;
2839
-	}
2840
-
2841
-	/**
2842
-	 * @return bool
2843
-	 */
2844
-	public static function enforceDefaultExpireDate() {
2845
-		$enforceDefaultExpireDate = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2846
-		return ($enforceDefaultExpireDate === "yes") ? true : false;
2847
-	}
2848
-
2849
-	/**
2850
-	 * @return int
2851
-	 */
2852
-	public static function getExpireInterval() {
2853
-		return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
2854
-	}
2855
-
2856
-	/**
2857
-	 * Checks whether the given path is reachable for the given owner
2858
-	 *
2859
-	 * @param string $path path relative to files
2860
-	 * @param string $ownerStorageId storage id of the owner
2861
-	 *
2862
-	 * @return boolean true if file is reachable, false otherwise
2863
-	 */
2864
-	private static function isFileReachable($path, $ownerStorageId) {
2865
-		// if outside the home storage, file is always considered reachable
2866
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2867
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2868
-		)) {
2869
-			return true;
2870
-		}
2871
-
2872
-		// if inside the home storage, the file has to be under "/files/"
2873
-		$path = ltrim($path, '/');
2874
-		if (substr($path, 0, 6) === 'files/') {
2875
-			return true;
2876
-		}
2877
-
2878
-		return false;
2879
-	}
2880
-
2881
-	/**
2882
-	 * @param IConfig $config
2883
-	 * @return bool
2884
-	 */
2885
-	public static function enforcePassword(IConfig $config) {
2886
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2887
-		return ($enforcePassword === "yes") ? true : false;
2888
-	}
2889
-
2890
-	/**
2891
-	 * Get all share entries, including non-unique group items
2892
-	 *
2893
-	 * @param string $owner
2894
-	 * @return array
2895
-	 */
2896
-	public static function getAllSharesForOwner($owner) {
2897
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2898
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2899
-		return $result->fetchAll();
2900
-	}
2901
-
2902
-	/**
2903
-	 * Get all share entries, including non-unique group items for a file
2904
-	 *
2905
-	 * @param int $id
2906
-	 * @return array
2907
-	 */
2908
-	public static function getAllSharesForFileId($id) {
2909
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2910
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2911
-		return $result->fetchAll();
2912
-	}
2913
-
2914
-	/**
2915
-	 * @param string $password
2916
-	 * @throws \Exception
2917
-	 */
2918
-	private static function verifyPassword($password) {
2919
-
2920
-		$accepted = true;
2921
-		$message = '';
2922
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2923
-			'password' => $password,
2924
-			'accepted' => &$accepted,
2925
-			'message' => &$message
2926
-		]);
2927
-
2928
-		if (!$accepted) {
2929
-			throw new \Exception($message);
2930
-		}
2931
-	}
1319
+            if ($permissions & ~(int)$rootItem['permissions']) {
1320
+                $qb = $connection->getQueryBuilder();
1321
+                $qb->select('id', 'permissions', 'item_type')
1322
+                    ->from('share')
1323
+                    ->where($qb->expr()->eq('parent', $qb->createParameter('parent')))
1324
+                    ->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
1325
+                    ->andWhere($qb->expr()->neq('permissions', $qb->createParameter('shareDeleted')))
1326
+                    ->setParameter(':parent', (int)$rootItem['id'])
1327
+                    ->setParameter(':share_type', 2)
1328
+                    ->setParameter(':shareDeleted', 0);
1329
+                $result = $qb->execute();
1330
+
1331
+                $ids = [];
1332
+                while ($item = $result->fetch()) {
1333
+                    $item = $sanitizeItem($item);
1334
+                    $items[] = $item;
1335
+                    $ids[] = $item['id'];
1336
+                }
1337
+                $result->closeCursor();
1338
+
1339
+                // Add permssions for all USERGROUP shares of this item
1340
+                if (!empty($ids)) {
1341
+                    $ids = $intArrayToLiteralArray($ids, $qb->expr());
1342
+
1343
+                    $qb = $connection->getQueryBuilder();
1344
+                    $qb->update('share')
1345
+                        ->set('permissions', $qb->createParameter('permissions'))
1346
+                        ->where($qb->expr()->in('id', $ids))
1347
+                        ->setParameter(':permissions', $permissions);
1348
+                    $qb->execute();
1349
+                }
1350
+            }
1351
+
1352
+            foreach ($items as $item) {
1353
+                \OC_Hook::emit('OCP\Share', 'post_update_permissions', ['share' => $item]);
1354
+            }
1355
+
1356
+            return true;
1357
+        }
1358
+        $message = 'Setting permissions for %s failed, because the item was not found';
1359
+        $message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
1360
+
1361
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1362
+        throw new \Exception($message_t);
1363
+    }
1364
+
1365
+    /**
1366
+     * validate expiration date if it meets all constraints
1367
+     *
1368
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
1369
+     * @param string $shareTime timestamp when the file was shared
1370
+     * @param string $itemType
1371
+     * @param string $itemSource
1372
+     * @return \DateTime validated date
1373
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
1374
+     */
1375
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
1376
+        $l = \OC::$server->getL10N('lib');
1377
+        $date = new \DateTime($expireDate);
1378
+        $today = new \DateTime('now');
1379
+
1380
+        // if the user doesn't provide a share time we need to get it from the database
1381
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
1382
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
1383
+        if ($defaultExpireDateEnforced && $shareTime === null) {
1384
+            $items = self::getItemShared($itemType, $itemSource);
1385
+            $firstItem = reset($items);
1386
+            $shareTime = (int)$firstItem['stime'];
1387
+        }
1388
+
1389
+        if ($defaultExpireDateEnforced) {
1390
+            // initialize max date with share time
1391
+            $maxDate = new \DateTime();
1392
+            $maxDate->setTimestamp($shareTime);
1393
+            $maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
1394
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
1395
+            if ($date > $maxDate) {
1396
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
1397
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
1398
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1399
+                throw new \Exception($warning_t);
1400
+            }
1401
+        }
1402
+
1403
+        if ($date < $today) {
1404
+            $message = 'Cannot set expiration date. Expiration date is in the past';
1405
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
1406
+            \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
1407
+            throw new \Exception($message_t);
1408
+        }
1409
+
1410
+        return $date;
1411
+    }
1412
+
1413
+    /**
1414
+     * Set expiration date for a share
1415
+     * @param string $itemType
1416
+     * @param string $itemSource
1417
+     * @param string $date expiration date
1418
+     * @param int $shareTime timestamp from when the file was shared
1419
+     * @return boolean
1420
+     * @throws \Exception when the expire date is not set, in the past or further in the future then the enforced date
1421
+     */
1422
+    public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
1423
+        $user = \OC_User::getUser();
1424
+        $l = \OC::$server->getL10N('lib');
1425
+
1426
+        if ($date == '') {
1427
+            if (\OCP\Util::isDefaultExpireDateEnforced()) {
1428
+                $warning = 'Cannot clear expiration date. Shares are required to have an expiration date.';
1429
+                $warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.');
1430
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1431
+                throw new \Exception($warning_t);
1432
+            } else {
1433
+                $date = null;
1434
+            }
1435
+        } else {
1436
+            $date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
1437
+        }
1438
+        $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ?  AND `uid_owner` = ? AND `share_type` = ?');
1439
+        $query->bindValue(1, $date, 'datetime');
1440
+        $query->bindValue(2, $itemType);
1441
+        $query->bindValue(3, $itemSource);
1442
+        $query->bindValue(4, $user);
1443
+        $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
1444
+
1445
+        $query->execute();
1446
+
1447
+        \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
1448
+            'itemType' => $itemType,
1449
+            'itemSource' => $itemSource,
1450
+            'date' => $date,
1451
+            'uidOwner' => $user
1452
+        ));
1453
+
1454
+        return true;
1455
+    }
1456
+
1457
+    /**
1458
+     * Retrieve the owner of a connection
1459
+     *
1460
+     * @param IDBConnection $connection
1461
+     * @param int $shareId
1462
+     * @throws \Exception
1463
+     * @return string uid of share owner
1464
+     */
1465
+    private static function getShareOwner(IDBConnection $connection, $shareId) {
1466
+        $qb = $connection->getQueryBuilder();
1467
+
1468
+        $qb->select('uid_owner')
1469
+            ->from('share')
1470
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1471
+            ->setParameter(':shareId', $shareId);
1472
+        $result = $qb->execute();
1473
+        $result = $result->fetch();
1474
+
1475
+        if (empty($result)) {
1476
+            throw new \Exception('Share not found');
1477
+        }
1478
+
1479
+        return $result['uid_owner'];
1480
+    }
1481
+
1482
+    /**
1483
+     * Set password for a public link share
1484
+     *
1485
+     * @param IUserSession $userSession
1486
+     * @param IDBConnection $connection
1487
+     * @param IConfig $config
1488
+     * @param int $shareId
1489
+     * @param string $password
1490
+     * @throws \Exception
1491
+     * @return boolean
1492
+     */
1493
+    public static function setPassword(IUserSession $userSession,
1494
+                                        IDBConnection $connection,
1495
+                                        IConfig $config,
1496
+                                        $shareId, $password) {
1497
+        $user = $userSession->getUser();
1498
+        if (is_null($user)) {
1499
+            throw new \Exception("User not logged in");
1500
+        }
1501
+
1502
+        $uid = self::getShareOwner($connection, $shareId);
1503
+
1504
+        if ($uid !== $user->getUID()) {
1505
+            throw new \Exception('Cannot update share of a different user');
1506
+        }
1507
+
1508
+        if ($password === '') {
1509
+            $password = null;
1510
+        }
1511
+
1512
+        //If passwords are enforced the password can't be null
1513
+        if (self::enforcePassword($config) && is_null($password)) {
1514
+            throw new \Exception('Cannot remove password');
1515
+        }
1516
+
1517
+        self::verifyPassword($password);
1518
+
1519
+        $qb = $connection->getQueryBuilder();
1520
+        $qb->update('share')
1521
+            ->set('share_with', $qb->createParameter('pass'))
1522
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
1523
+            ->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
1524
+            ->setParameter(':shareId', $shareId);
1525
+
1526
+        $qb->execute();
1527
+
1528
+        return true;
1529
+    }
1530
+
1531
+    /**
1532
+     * Checks whether a share has expired, calls unshareItem() if yes.
1533
+     * @param array $item Share data (usually database row)
1534
+     * @return boolean True if item was expired, false otherwise.
1535
+     */
1536
+    protected static function expireItem(array $item) {
1537
+
1538
+        $result = false;
1539
+
1540
+        // only use default expiration date for link shares
1541
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
1542
+
1543
+            // calculate expiration date
1544
+            if (!empty($item['expiration'])) {
1545
+                $userDefinedExpire = new \DateTime($item['expiration']);
1546
+                $expires = $userDefinedExpire->getTimestamp();
1547
+            } else {
1548
+                $expires = null;
1549
+            }
1550
+
1551
+
1552
+            // get default expiration settings
1553
+            $defaultSettings = Helper::getDefaultExpireSetting();
1554
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
1555
+
1556
+
1557
+            if (is_int($expires)) {
1558
+                $now = time();
1559
+                if ($now > $expires) {
1560
+                    self::unshareItem($item);
1561
+                    $result = true;
1562
+                }
1563
+            }
1564
+        }
1565
+        return $result;
1566
+    }
1567
+
1568
+    /**
1569
+     * Unshares a share given a share data array
1570
+     * @param array $item Share data (usually database row)
1571
+     * @param int $newParent parent ID
1572
+     * @return null
1573
+     */
1574
+    protected static function unshareItem(array $item, $newParent = null) {
1575
+
1576
+        $shareType = (int)$item['share_type'];
1577
+        $shareWith = null;
1578
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
1579
+            $shareWith = $item['share_with'];
1580
+        }
1581
+
1582
+        // Pass all the vars we have for now, they may be useful
1583
+        $hookParams = array(
1584
+            'id'            => $item['id'],
1585
+            'itemType'      => $item['item_type'],
1586
+            'itemSource'    => $item['item_source'],
1587
+            'shareType'     => $shareType,
1588
+            'shareWith'     => $shareWith,
1589
+            'itemParent'    => $item['parent'],
1590
+            'uidOwner'      => $item['uid_owner'],
1591
+        );
1592
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
1593
+            $hookParams['fileSource'] = $item['file_source'];
1594
+            $hookParams['fileTarget'] = $item['file_target'];
1595
+        }
1596
+
1597
+        \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
1598
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
1599
+        $deletedShares[] = $hookParams;
1600
+        $hookParams['deletedShares'] = $deletedShares;
1601
+        \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
1602
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
1603
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
1604
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
1605
+        }
1606
+    }
1607
+
1608
+    /**
1609
+     * Get the backend class for the specified item type
1610
+     * @param string $itemType
1611
+     * @throws \Exception
1612
+     * @return \OCP\Share_Backend
1613
+     */
1614
+    public static function getBackend($itemType) {
1615
+        $l = \OC::$server->getL10N('lib');
1616
+        if (isset(self::$backends[$itemType])) {
1617
+            return self::$backends[$itemType];
1618
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
1619
+            $class = self::$backendTypes[$itemType]['class'];
1620
+            if (class_exists($class)) {
1621
+                self::$backends[$itemType] = new $class;
1622
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
1623
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
1624
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
1625
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1626
+                    throw new \Exception($message_t);
1627
+                }
1628
+                return self::$backends[$itemType];
1629
+            } else {
1630
+                $message = 'Sharing backend %s not found';
1631
+                $message_t = $l->t('Sharing backend %s not found', array($class));
1632
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
1633
+                throw new \Exception($message_t);
1634
+            }
1635
+        }
1636
+        $message = 'Sharing backend for %s not found';
1637
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
1638
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
1639
+        throw new \Exception($message_t);
1640
+    }
1641
+
1642
+    /**
1643
+     * Check if resharing is allowed
1644
+     * @return boolean true if allowed or false
1645
+     *
1646
+     * Resharing is allowed by default if not configured
1647
+     */
1648
+    public static function isResharingAllowed() {
1649
+        if (!isset(self::$isResharingAllowed)) {
1650
+            if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
1651
+                self::$isResharingAllowed = true;
1652
+            } else {
1653
+                self::$isResharingAllowed = false;
1654
+            }
1655
+        }
1656
+        return self::$isResharingAllowed;
1657
+    }
1658
+
1659
+    /**
1660
+     * Get a list of collection item types for the specified item type
1661
+     * @param string $itemType
1662
+     * @return array
1663
+     */
1664
+    private static function getCollectionItemTypes($itemType) {
1665
+        $collectionTypes = array($itemType);
1666
+        foreach (self::$backendTypes as $type => $backend) {
1667
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
1668
+                $collectionTypes[] = $type;
1669
+            }
1670
+        }
1671
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1672
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1673
+            unset($collectionTypes[0]);
1674
+        }
1675
+        // Return array if collections were found or the item type is a
1676
+        // collection itself - collections can be inside collections
1677
+        if (count($collectionTypes) > 0) {
1678
+            return $collectionTypes;
1679
+        }
1680
+        return false;
1681
+    }
1682
+
1683
+    /**
1684
+     * Get the owners of items shared with a user.
1685
+     *
1686
+     * @param string $user The user the items are shared with.
1687
+     * @param string $type The type of the items shared with the user.
1688
+     * @param boolean $includeCollections Include collection item types (optional)
1689
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1690
+     * @return array
1691
+     */
1692
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1693
+        // First, we find out if $type is part of a collection (and if that collection is part of
1694
+        // another one and so on).
1695
+        $collectionTypes = array();
1696
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1697
+            $collectionTypes[] = $type;
1698
+        }
1699
+
1700
+        // Of these collection types, along with our original $type, we make a
1701
+        // list of the ones for which a sharing backend has been registered.
1702
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1703
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1704
+        $allMaybeSharedItems = array();
1705
+        foreach ($collectionTypes as $collectionType) {
1706
+            if (isset(self::$backends[$collectionType])) {
1707
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1708
+                    $collectionType,
1709
+                    $user,
1710
+                    self::FORMAT_NONE
1711
+                );
1712
+            }
1713
+        }
1714
+
1715
+        $owners = array();
1716
+        if ($includeOwner) {
1717
+            $owners[] = $user;
1718
+        }
1719
+
1720
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
1721
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
1722
+        // and return them as elements of a list that look like "Tag (owner)".
1723
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1724
+            foreach ($maybeSharedItems as $sharedItem) {
1725
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1726
+                    $owners[] = $sharedItem['uid_owner'];
1727
+                }
1728
+            }
1729
+        }
1730
+
1731
+        return $owners;
1732
+    }
1733
+
1734
+    /**
1735
+     * Get shared items from the database
1736
+     * @param string $itemType
1737
+     * @param string $item Item source or target (optional)
1738
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1739
+     * @param string $shareWith User or group the item is being shared with
1740
+     * @param string $uidOwner User that is the owner of shared items (optional)
1741
+     * @param int $format Format to convert items to with formatItems() (optional)
1742
+     * @param mixed $parameters to pass to formatItems() (optional)
1743
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
1744
+     * @param boolean $includeCollections Include collection item types (optional)
1745
+     * @param boolean $itemShareWithBySource (optional)
1746
+     * @param boolean $checkExpireDate
1747
+     * @return array
1748
+     *
1749
+     * See public functions getItem(s)... for parameter usage
1750
+     *
1751
+     */
1752
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1753
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1754
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1755
+        if (!self::isEnabled()) {
1756
+            return array();
1757
+        }
1758
+        $backend = self::getBackend($itemType);
1759
+        $collectionTypes = false;
1760
+        // Get filesystem root to add it to the file target and remove from the
1761
+        // file source, match file_source with the file cache
1762
+        if ($itemType == 'file' || $itemType == 'folder') {
1763
+            if(!is_null($uidOwner)) {
1764
+                $root = \OC\Files\Filesystem::getRoot();
1765
+            } else {
1766
+                $root = '';
1767
+            }
1768
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1769
+            if (!isset($item)) {
1770
+                $where .= ' AND `file_target` IS NOT NULL ';
1771
+            }
1772
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1773
+            $fileDependent = true;
1774
+            $queryArgs = array();
1775
+        } else {
1776
+            $fileDependent = false;
1777
+            $root = '';
1778
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1779
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1780
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1781
+                if (!in_array($itemType, $collectionTypes)) {
1782
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1783
+                } else {
1784
+                    $itemTypes = $collectionTypes;
1785
+                }
1786
+                $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1787
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1788
+                $queryArgs = $itemTypes;
1789
+            } else {
1790
+                $where = ' WHERE `item_type` = ?';
1791
+                $queryArgs = array($itemType);
1792
+            }
1793
+        }
1794
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1795
+            $where .= ' AND `share_type` != ?';
1796
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1797
+        }
1798
+        if (isset($shareType)) {
1799
+            // Include all user and group items
1800
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1801
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1802
+                $queryArgs[] = self::SHARE_TYPE_USER;
1803
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1804
+                $queryArgs[] = $shareWith;
1805
+
1806
+                $user = \OC::$server->getUserManager()->get($shareWith);
1807
+                $groups = [];
1808
+                if ($user) {
1809
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1810
+                }
1811
+                if (!empty($groups)) {
1812
+                    $placeholders = join(',', array_fill(0, count($groups), '?'));
1813
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1814
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1815
+                    $queryArgs = array_merge($queryArgs, $groups);
1816
+                }
1817
+                $where .= ')';
1818
+                // Don't include own group shares
1819
+                $where .= ' AND `uid_owner` != ?';
1820
+                $queryArgs[] = $shareWith;
1821
+            } else {
1822
+                $where .= ' AND `share_type` = ?';
1823
+                $queryArgs[] = $shareType;
1824
+                if (isset($shareWith)) {
1825
+                    $where .= ' AND `share_with` = ?';
1826
+                    $queryArgs[] = $shareWith;
1827
+                }
1828
+            }
1829
+        }
1830
+        if (isset($uidOwner)) {
1831
+            $where .= ' AND `uid_owner` = ?';
1832
+            $queryArgs[] = $uidOwner;
1833
+            if (!isset($shareType)) {
1834
+                // Prevent unique user targets for group shares from being selected
1835
+                $where .= ' AND `share_type` != ?';
1836
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1837
+            }
1838
+            if ($fileDependent) {
1839
+                $column = 'file_source';
1840
+            } else {
1841
+                $column = 'item_source';
1842
+            }
1843
+        } else {
1844
+            if ($fileDependent) {
1845
+                $column = 'file_target';
1846
+            } else {
1847
+                $column = 'item_target';
1848
+            }
1849
+        }
1850
+        if (isset($item)) {
1851
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1852
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1853
+                $where .= ' AND (';
1854
+            } else {
1855
+                $where .= ' AND';
1856
+            }
1857
+            // If looking for own shared items, check item_source else check item_target
1858
+            if (isset($uidOwner) || $itemShareWithBySource) {
1859
+                // If item type is a file, file source needs to be checked in case the item was converted
1860
+                if ($fileDependent) {
1861
+                    $where .= ' `file_source` = ?';
1862
+                    $column = 'file_source';
1863
+                } else {
1864
+                    $where .= ' `item_source` = ?';
1865
+                    $column = 'item_source';
1866
+                }
1867
+            } else {
1868
+                if ($fileDependent) {
1869
+                    $where .= ' `file_target` = ?';
1870
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1871
+                } else {
1872
+                    $where .= ' `item_target` = ?';
1873
+                }
1874
+            }
1875
+            $queryArgs[] = $item;
1876
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1877
+                $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1878
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1879
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1880
+            }
1881
+        }
1882
+
1883
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1884
+            // Make sure the unique user target is returned if it exists,
1885
+            // unique targets should follow the group share in the database
1886
+            // If the limit is not 1, the filtering can be done later
1887
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1888
+        } else {
1889
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1890
+        }
1891
+
1892
+        if ($limit != -1 && !$includeCollections) {
1893
+            // The limit must be at least 3, because filtering needs to be done
1894
+            if ($limit < 3) {
1895
+                $queryLimit = 3;
1896
+            } else {
1897
+                $queryLimit = $limit;
1898
+            }
1899
+        } else {
1900
+            $queryLimit = null;
1901
+        }
1902
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1903
+        $root = strlen($root);
1904
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1905
+        $result = $query->execute($queryArgs);
1906
+        if ($result === false) {
1907
+            \OCP\Util::writeLog('OCP\Share',
1908
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1909
+                \OCP\Util::ERROR);
1910
+        }
1911
+        $items = array();
1912
+        $targets = array();
1913
+        $switchedItems = array();
1914
+        $mounts = array();
1915
+        while ($row = $result->fetchRow()) {
1916
+            self::transformDBResults($row);
1917
+            // Filter out duplicate group shares for users with unique targets
1918
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1919
+                continue;
1920
+            }
1921
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1922
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1923
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1924
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1925
+                // if the group share was unshared from the user we keep the permission, otherwise
1926
+                // we take the permission from the parent because this is always the up-to-date
1927
+                // permission for the group share
1928
+                if ($row['permissions'] > 0) {
1929
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1930
+                }
1931
+                // Remove the parent group share
1932
+                unset($items[$row['parent']]);
1933
+                if ($row['permissions'] == 0) {
1934
+                    continue;
1935
+                }
1936
+            } else if (!isset($uidOwner)) {
1937
+                // Check if the same target already exists
1938
+                if (isset($targets[$row['id']])) {
1939
+                    // Check if the same owner shared with the user twice
1940
+                    // through a group and user share - this is allowed
1941
+                    $id = $targets[$row['id']];
1942
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1943
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1944
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1945
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1946
+                            $items[$id]['share_with'] = $row['share_with'];
1947
+                        }
1948
+                        // Switch ids if sharing permission is granted on only
1949
+                        // one share to ensure correct parent is used if resharing
1950
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1951
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1952
+                            $items[$row['id']] = $items[$id];
1953
+                            $switchedItems[$id] = $row['id'];
1954
+                            unset($items[$id]);
1955
+                            $id = $row['id'];
1956
+                        }
1957
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1958
+
1959
+                    }
1960
+                    continue;
1961
+                } elseif (!empty($row['parent'])) {
1962
+                    $targets[$row['parent']] = $row['id'];
1963
+                }
1964
+            }
1965
+            // Remove root from file source paths if retrieving own shared items
1966
+            if (isset($uidOwner) && isset($row['path'])) {
1967
+                if (isset($row['parent'])) {
1968
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1969
+                    $parentResult = $query->execute(array($row['parent']));
1970
+                    if ($result === false) {
1971
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1972
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1973
+                            \OCP\Util::ERROR);
1974
+                    } else {
1975
+                        $parentRow = $parentResult->fetchRow();
1976
+                        $tmpPath = $parentRow['file_target'];
1977
+                        // find the right position where the row path continues from the target path
1978
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1979
+                        $subPath = substr($row['path'], $pos);
1980
+                        $splitPath = explode('/', $subPath);
1981
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1982
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1983
+                        }
1984
+                        $row['path'] = $tmpPath;
1985
+                    }
1986
+                } else {
1987
+                    if (!isset($mounts[$row['storage']])) {
1988
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1989
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1990
+                            $mounts[$row['storage']] = current($mountPoints);
1991
+                        }
1992
+                    }
1993
+                    if (!empty($mounts[$row['storage']])) {
1994
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1995
+                        $relPath = substr($path, $root); // path relative to data/user
1996
+                        $row['path'] = rtrim($relPath, '/');
1997
+                    }
1998
+                }
1999
+            }
2000
+
2001
+            if($checkExpireDate) {
2002
+                if (self::expireItem($row)) {
2003
+                    continue;
2004
+                }
2005
+            }
2006
+            // Check if resharing is allowed, if not remove share permission
2007
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
2008
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
2009
+            }
2010
+            // Add display names to result
2011
+            $row['share_with_displayname'] = $row['share_with'];
2012
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
2013
+                $row['share_type'] === self::SHARE_TYPE_USER) {
2014
+                $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
2015
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
2016
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
2017
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
2018
+                foreach ($addressBookEntries as $entry) {
2019
+                    foreach ($entry['CLOUD'] as $cloudID) {
2020
+                        if ($cloudID === $row['share_with']) {
2021
+                            $row['share_with_displayname'] = $entry['FN'];
2022
+                        }
2023
+                    }
2024
+                }
2025
+            }
2026
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
2027
+                $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
2028
+            }
2029
+
2030
+            if ($row['permissions'] > 0) {
2031
+                $items[$row['id']] = $row;
2032
+            }
2033
+
2034
+        }
2035
+
2036
+        // group items if we are looking for items shared with the current user
2037
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
2038
+            $items = self::groupItems($items, $itemType);
2039
+        }
2040
+
2041
+        if (!empty($items)) {
2042
+            $collectionItems = array();
2043
+            foreach ($items as &$row) {
2044
+                // Return only the item instead of a 2-dimensional array
2045
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
2046
+                    if ($format == self::FORMAT_NONE) {
2047
+                        return $row;
2048
+                    } else {
2049
+                        break;
2050
+                    }
2051
+                }
2052
+                // Check if this is a collection of the requested item type
2053
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
2054
+                    if (($collectionBackend = self::getBackend($row['item_type']))
2055
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
2056
+                        // Collections can be inside collections, check if the item is a collection
2057
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
2058
+                            $collectionItems[] = $row;
2059
+                        } else {
2060
+                            $collection = array();
2061
+                            $collection['item_type'] = $row['item_type'];
2062
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2063
+                                $collection['path'] = basename($row['path']);
2064
+                            }
2065
+                            $row['collection'] = $collection;
2066
+                            // Fetch all of the children sources
2067
+                            $children = $collectionBackend->getChildren($row[$column]);
2068
+                            foreach ($children as $child) {
2069
+                                $childItem = $row;
2070
+                                $childItem['item_type'] = $itemType;
2071
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
2072
+                                    $childItem['item_source'] = $child['source'];
2073
+                                    $childItem['item_target'] = $child['target'];
2074
+                                }
2075
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2076
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
2077
+                                        $childItem['file_source'] = $child['source'];
2078
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
2079
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
2080
+                                        $childItem['file_source'] = $meta['fileid'];
2081
+                                    }
2082
+                                    $childItem['file_target'] =
2083
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
2084
+                                }
2085
+                                if (isset($item)) {
2086
+                                    if ($childItem[$column] == $item) {
2087
+                                        // Return only the item instead of a 2-dimensional array
2088
+                                        if ($limit == 1) {
2089
+                                            if ($format == self::FORMAT_NONE) {
2090
+                                                return $childItem;
2091
+                                            } else {
2092
+                                                // Unset the items array and break out of both loops
2093
+                                                $items = array();
2094
+                                                $items[] = $childItem;
2095
+                                                break 2;
2096
+                                            }
2097
+                                        } else {
2098
+                                            $collectionItems[] = $childItem;
2099
+                                        }
2100
+                                    }
2101
+                                } else {
2102
+                                    $collectionItems[] = $childItem;
2103
+                                }
2104
+                            }
2105
+                        }
2106
+                    }
2107
+                    // Remove collection item
2108
+                    $toRemove = $row['id'];
2109
+                    if (array_key_exists($toRemove, $switchedItems)) {
2110
+                        $toRemove = $switchedItems[$toRemove];
2111
+                    }
2112
+                    unset($items[$toRemove]);
2113
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
2114
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
2115
+                    // see github issue #10588 for more details
2116
+                    // Need to find a solution which works for all back-ends
2117
+                    $collectionBackend = self::getBackend($row['item_type']);
2118
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
2119
+                    foreach ($sharedParents as $parent) {
2120
+                        $collectionItems[] = $parent;
2121
+                    }
2122
+                }
2123
+            }
2124
+            if (!empty($collectionItems)) {
2125
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
2126
+                $items = array_merge($items, $collectionItems);
2127
+            }
2128
+
2129
+            // filter out invalid items, these can appear when subshare entries exist
2130
+            // for a group in which the requested user isn't a member any more
2131
+            $items = array_filter($items, function($item) {
2132
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
2133
+            });
2134
+
2135
+            return self::formatResult($items, $column, $backend, $format, $parameters);
2136
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
2137
+            // FIXME: Thats a dirty hack to improve file sharing performance,
2138
+            // see github issue #10588 for more details
2139
+            // Need to find a solution which works for all back-ends
2140
+            $collectionItems = array();
2141
+            $collectionBackend = self::getBackend('folder');
2142
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
2143
+            foreach ($sharedParents as $parent) {
2144
+                $collectionItems[] = $parent;
2145
+            }
2146
+            if ($limit === 1) {
2147
+                return reset($collectionItems);
2148
+            }
2149
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
2150
+        }
2151
+
2152
+        return array();
2153
+    }
2154
+
2155
+    /**
2156
+     * group items with link to the same source
2157
+     *
2158
+     * @param array $items
2159
+     * @param string $itemType
2160
+     * @return array of grouped items
2161
+     */
2162
+    protected static function groupItems($items, $itemType) {
2163
+
2164
+        $fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
2165
+
2166
+        $result = array();
2167
+
2168
+        foreach ($items as $item) {
2169
+            $grouped = false;
2170
+            foreach ($result as $key => $r) {
2171
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
2172
+                // only group shares if they already point to the same target, otherwise the file where shared
2173
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
2174
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
2175
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
2176
+                    // add the first item to the list of grouped shares
2177
+                    if (!isset($result[$key]['grouped'])) {
2178
+                        $result[$key]['grouped'][] = $result[$key];
2179
+                    }
2180
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
2181
+                    $result[$key]['grouped'][] = $item;
2182
+                    $grouped = true;
2183
+                    break;
2184
+                }
2185
+            }
2186
+
2187
+            if (!$grouped) {
2188
+                $result[] = $item;
2189
+            }
2190
+
2191
+        }
2192
+
2193
+        return $result;
2194
+    }
2195
+
2196
+    /**
2197
+     * Put shared item into the database
2198
+     * @param string $itemType Item type
2199
+     * @param string $itemSource Item source
2200
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
2201
+     * @param string $shareWith User or group the item is being shared with
2202
+     * @param string $uidOwner User that is the owner of shared item
2203
+     * @param int $permissions CRUDS permissions
2204
+     * @param boolean|array $parentFolder Parent folder target (optional)
2205
+     * @param string $token (optional)
2206
+     * @param string $itemSourceName name of the source item (optional)
2207
+     * @param \DateTime $expirationDate (optional)
2208
+     * @throws \Exception
2209
+     * @return mixed id of the new share or false
2210
+     */
2211
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2212
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
2213
+
2214
+        $queriesToExecute = array();
2215
+        $suggestedItemTarget = null;
2216
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
2217
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
2218
+
2219
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
2220
+        if(!empty($result)) {
2221
+            $parent = $result['parent'];
2222
+            $itemSource = $result['itemSource'];
2223
+            $fileSource = $result['fileSource'];
2224
+            $suggestedItemTarget = $result['suggestedItemTarget'];
2225
+            $suggestedFileTarget = $result['suggestedFileTarget'];
2226
+            $filePath = $result['filePath'];
2227
+        }
2228
+
2229
+        $isGroupShare = false;
2230
+        if ($shareType == self::SHARE_TYPE_GROUP) {
2231
+            $isGroupShare = true;
2232
+            if (isset($shareWith['users'])) {
2233
+                $users = $shareWith['users'];
2234
+            } else {
2235
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
2236
+                if ($group) {
2237
+                    $users = $group->searchUsers('', -1, 0);
2238
+                    $userIds = [];
2239
+                    foreach ($users as $user) {
2240
+                        $userIds[] = $user->getUID();
2241
+                    }
2242
+                    $users = $userIds;
2243
+                } else {
2244
+                    $users = [];
2245
+                }
2246
+            }
2247
+            // remove current user from list
2248
+            if (in_array(\OCP\User::getUser(), $users)) {
2249
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
2250
+            }
2251
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
2252
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
2253
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
2254
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
2255
+
2256
+            // add group share to table and remember the id as parent
2257
+            $queriesToExecute['groupShare'] = array(
2258
+                'itemType'			=> $itemType,
2259
+                'itemSource'		=> $itemSource,
2260
+                'itemTarget'		=> $groupItemTarget,
2261
+                'shareType'			=> $shareType,
2262
+                'shareWith'			=> $shareWith['group'],
2263
+                'uidOwner'			=> $uidOwner,
2264
+                'permissions'		=> $permissions,
2265
+                'shareTime'			=> time(),
2266
+                'fileSource'		=> $fileSource,
2267
+                'fileTarget'		=> $groupFileTarget,
2268
+                'token'				=> $token,
2269
+                'parent'			=> $parent,
2270
+                'expiration'		=> $expirationDate,
2271
+            );
2272
+
2273
+        } else {
2274
+            $users = array($shareWith);
2275
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
2276
+                $suggestedItemTarget);
2277
+        }
2278
+
2279
+        $run = true;
2280
+        $error = '';
2281
+        $preHookData = array(
2282
+            'itemType' => $itemType,
2283
+            'itemSource' => $itemSource,
2284
+            'shareType' => $shareType,
2285
+            'uidOwner' => $uidOwner,
2286
+            'permissions' => $permissions,
2287
+            'fileSource' => $fileSource,
2288
+            'expiration' => $expirationDate,
2289
+            'token' => $token,
2290
+            'run' => &$run,
2291
+            'error' => &$error
2292
+        );
2293
+
2294
+        $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2295
+        $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2296
+
2297
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
2298
+
2299
+        if ($run === false) {
2300
+            throw new \Exception($error);
2301
+        }
2302
+
2303
+        foreach ($users as $user) {
2304
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
2305
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
2306
+
2307
+            $userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
2308
+
2309
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
2310
+                $fileTarget = $sourceExists['file_target'];
2311
+                $itemTarget = $sourceExists['item_target'];
2312
+
2313
+                // for group shares we don't need a additional entry if the target is the same
2314
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
2315
+                    continue;
2316
+                }
2317
+
2318
+            } elseif(!$sourceExists && !$isGroupShare)  {
2319
+
2320
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
2321
+                    $uidOwner, $suggestedItemTarget, $parent);
2322
+                if (isset($fileSource)) {
2323
+                    if ($parentFolder) {
2324
+                        if ($parentFolder === true) {
2325
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
2326
+                                $uidOwner, $suggestedFileTarget, $parent);
2327
+                            if ($fileTarget != $groupFileTarget) {
2328
+                                $parentFolders[$user]['folder'] = $fileTarget;
2329
+                            }
2330
+                        } else if (isset($parentFolder[$user])) {
2331
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
2332
+                            $parent = $parentFolder[$user]['id'];
2333
+                        }
2334
+                    } else {
2335
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
2336
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
2337
+                    }
2338
+                } else {
2339
+                    $fileTarget = null;
2340
+                }
2341
+
2342
+            } else {
2343
+
2344
+                // group share which doesn't exists until now, check if we need a unique target for this user
2345
+
2346
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
2347
+                    $uidOwner, $suggestedItemTarget, $parent);
2348
+
2349
+                // do we also need a file target
2350
+                if (isset($fileSource)) {
2351
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
2352
+                        $uidOwner, $suggestedFileTarget, $parent);
2353
+                } else {
2354
+                    $fileTarget = null;
2355
+                }
2356
+
2357
+                if (($itemTarget === $groupItemTarget) &&
2358
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
2359
+                    continue;
2360
+                }
2361
+            }
2362
+
2363
+            $queriesToExecute[] = array(
2364
+                'itemType'			=> $itemType,
2365
+                'itemSource'		=> $itemSource,
2366
+                'itemTarget'		=> $itemTarget,
2367
+                'shareType'			=> $userShareType,
2368
+                'shareWith'			=> $user,
2369
+                'uidOwner'			=> $uidOwner,
2370
+                'permissions'		=> $permissions,
2371
+                'shareTime'			=> time(),
2372
+                'fileSource'		=> $fileSource,
2373
+                'fileTarget'		=> $fileTarget,
2374
+                'token'				=> $token,
2375
+                'parent'			=> $parent,
2376
+                'expiration'		=> $expirationDate,
2377
+            );
2378
+
2379
+        }
2380
+
2381
+        $id = false;
2382
+        if ($isGroupShare) {
2383
+            $id = self::insertShare($queriesToExecute['groupShare']);
2384
+            // Save this id, any extra rows for this group share will need to reference it
2385
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2386
+            unset($queriesToExecute['groupShare']);
2387
+        }
2388
+
2389
+        foreach ($queriesToExecute as $shareQuery) {
2390
+            $shareQuery['parent'] = $parent;
2391
+            $id = self::insertShare($shareQuery);
2392
+        }
2393
+
2394
+        $postHookData = array(
2395
+            'itemType' => $itemType,
2396
+            'itemSource' => $itemSource,
2397
+            'parent' => $parent,
2398
+            'shareType' => $shareType,
2399
+            'uidOwner' => $uidOwner,
2400
+            'permissions' => $permissions,
2401
+            'fileSource' => $fileSource,
2402
+            'id' => $parent,
2403
+            'token' => $token,
2404
+            'expirationDate' => $expirationDate,
2405
+        );
2406
+
2407
+        $postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
2408
+        $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
2409
+        $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
2410
+
2411
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
2412
+
2413
+
2414
+        return $id ? $id : false;
2415
+    }
2416
+
2417
+    /**
2418
+     * @param string $itemType
2419
+     * @param string $itemSource
2420
+     * @param int $shareType
2421
+     * @param string $shareWith
2422
+     * @param string $uidOwner
2423
+     * @param int $permissions
2424
+     * @param string|null $itemSourceName
2425
+     * @param null|\DateTime $expirationDate
2426
+     */
2427
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
2428
+        $backend = self::getBackend($itemType);
2429
+
2430
+        $l = \OC::$server->getL10N('lib');
2431
+        $result = array();
2432
+
2433
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
2434
+
2435
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
2436
+        if ($checkReshare) {
2437
+            // Check if attempting to share back to owner
2438
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
2439
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
2440
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
2441
+
2442
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
2443
+                throw new \Exception($message_t);
2444
+            }
2445
+        }
2446
+
2447
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
2448
+            // Check if share permissions is granted
2449
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
2450
+                if (~(int)$checkReshare['permissions'] & $permissions) {
2451
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
2452
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
2453
+
2454
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
2455
+                    throw new \Exception($message_t);
2456
+                } else {
2457
+                    // TODO Don't check if inside folder
2458
+                    $result['parent'] = $checkReshare['id'];
2459
+
2460
+                    $result['expirationDate'] = $expirationDate;
2461
+                    // $checkReshare['expiration'] could be null and then is always less than any value
2462
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
2463
+                        $result['expirationDate'] = $checkReshare['expiration'];
2464
+                    }
2465
+
2466
+                    // only suggest the same name as new target if it is a reshare of the
2467
+                    // same file/folder and not the reshare of a child
2468
+                    if ($checkReshare[$column] === $itemSource) {
2469
+                        $result['filePath'] = $checkReshare['file_target'];
2470
+                        $result['itemSource'] = $checkReshare['item_source'];
2471
+                        $result['fileSource'] = $checkReshare['file_source'];
2472
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
2473
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
2474
+                    } else {
2475
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
2476
+                        $result['suggestedItemTarget'] = null;
2477
+                        $result['suggestedFileTarget'] = null;
2478
+                        $result['itemSource'] = $itemSource;
2479
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
2480
+                    }
2481
+                }
2482
+            } else {
2483
+                $message = 'Sharing %s failed, because resharing is not allowed';
2484
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
2485
+
2486
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
2487
+                throw new \Exception($message_t);
2488
+            }
2489
+        } else {
2490
+            $result['parent'] = null;
2491
+            $result['suggestedItemTarget'] = null;
2492
+            $result['suggestedFileTarget'] = null;
2493
+            $result['itemSource'] = $itemSource;
2494
+            $result['expirationDate'] = $expirationDate;
2495
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
2496
+                $message = 'Sharing %s failed, because the sharing backend for '
2497
+                    .'%s could not find its source';
2498
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
2499
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
2500
+                throw new \Exception($message_t);
2501
+            }
2502
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
2503
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
2504
+                if ($itemType == 'file' || $itemType == 'folder') {
2505
+                    $result['fileSource'] = $itemSource;
2506
+                } else {
2507
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
2508
+                    $result['fileSource'] = $meta['fileid'];
2509
+                }
2510
+                if ($result['fileSource'] == -1) {
2511
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
2512
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
2513
+
2514
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
2515
+                    throw new \Exception($message_t);
2516
+                }
2517
+            } else {
2518
+                $result['filePath'] = null;
2519
+                $result['fileSource'] = null;
2520
+            }
2521
+        }
2522
+
2523
+        return $result;
2524
+    }
2525
+
2526
+    /**
2527
+     *
2528
+     * @param array $shareData
2529
+     * @return mixed false in case of a failure or the id of the new share
2530
+     */
2531
+    private static function insertShare(array $shareData) {
2532
+
2533
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
2534
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
2535
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
2536
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
2537
+        $query->bindValue(1, $shareData['itemType']);
2538
+        $query->bindValue(2, $shareData['itemSource']);
2539
+        $query->bindValue(3, $shareData['itemTarget']);
2540
+        $query->bindValue(4, $shareData['shareType']);
2541
+        $query->bindValue(5, $shareData['shareWith']);
2542
+        $query->bindValue(6, $shareData['uidOwner']);
2543
+        $query->bindValue(7, $shareData['permissions']);
2544
+        $query->bindValue(8, $shareData['shareTime']);
2545
+        $query->bindValue(9, $shareData['fileSource']);
2546
+        $query->bindValue(10, $shareData['fileTarget']);
2547
+        $query->bindValue(11, $shareData['token']);
2548
+        $query->bindValue(12, $shareData['parent']);
2549
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
2550
+        $result = $query->execute();
2551
+
2552
+        $id = false;
2553
+        if ($result) {
2554
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2555
+        }
2556
+
2557
+        return $id;
2558
+
2559
+    }
2560
+
2561
+    /**
2562
+     * Delete all shares with type SHARE_TYPE_LINK
2563
+     */
2564
+    public static function removeAllLinkShares() {
2565
+        // Delete any link shares
2566
+        $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
2567
+        $result = $query->execute(array(self::SHARE_TYPE_LINK));
2568
+        while ($item = $result->fetchRow()) {
2569
+            Helper::delete($item['id']);
2570
+        }
2571
+    }
2572
+
2573
+    /**
2574
+     * In case a password protected link is not yet authenticated this function will return false
2575
+     *
2576
+     * @param array $linkItem
2577
+     * @return boolean
2578
+     */
2579
+    public static function checkPasswordProtectedShare(array $linkItem) {
2580
+        if (!isset($linkItem['share_with'])) {
2581
+            return true;
2582
+        }
2583
+        if (!isset($linkItem['share_type'])) {
2584
+            return true;
2585
+        }
2586
+        if (!isset($linkItem['id'])) {
2587
+            return true;
2588
+        }
2589
+
2590
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
2591
+            return true;
2592
+        }
2593
+
2594
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
2595
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
2596
+            return true;
2597
+        }
2598
+
2599
+        return false;
2600
+    }
2601
+
2602
+    /**
2603
+     * construct select statement
2604
+     * @param int $format
2605
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
2606
+     * @param string $uidOwner
2607
+     * @return string select statement
2608
+     */
2609
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
2610
+        $select = '*';
2611
+        if ($format == self::FORMAT_STATUSES) {
2612
+            if ($fileDependent) {
2613
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
2614
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
2615
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2616
+                    . '`uid_initiator`';
2617
+            } else {
2618
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
2619
+            }
2620
+        } else {
2621
+            if (isset($uidOwner)) {
2622
+                if ($fileDependent) {
2623
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
2624
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
2625
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
2626
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2627
+                } else {
2628
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
2629
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
2630
+                }
2631
+            } else {
2632
+                if ($fileDependent) {
2633
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
2634
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
2635
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
2636
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
2637
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
2638
+                    } else {
2639
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
2640
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
2641
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
2642
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
2643
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
2644
+                    }
2645
+                }
2646
+            }
2647
+        }
2648
+        return $select;
2649
+    }
2650
+
2651
+
2652
+    /**
2653
+     * transform db results
2654
+     * @param array $row result
2655
+     */
2656
+    private static function transformDBResults(&$row) {
2657
+        if (isset($row['id'])) {
2658
+            $row['id'] = (int) $row['id'];
2659
+        }
2660
+        if (isset($row['share_type'])) {
2661
+            $row['share_type'] = (int) $row['share_type'];
2662
+        }
2663
+        if (isset($row['parent'])) {
2664
+            $row['parent'] = (int) $row['parent'];
2665
+        }
2666
+        if (isset($row['file_parent'])) {
2667
+            $row['file_parent'] = (int) $row['file_parent'];
2668
+        }
2669
+        if (isset($row['file_source'])) {
2670
+            $row['file_source'] = (int) $row['file_source'];
2671
+        }
2672
+        if (isset($row['permissions'])) {
2673
+            $row['permissions'] = (int) $row['permissions'];
2674
+        }
2675
+        if (isset($row['storage'])) {
2676
+            $row['storage'] = (int) $row['storage'];
2677
+        }
2678
+        if (isset($row['stime'])) {
2679
+            $row['stime'] = (int) $row['stime'];
2680
+        }
2681
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2682
+            // discard expiration date for non-link shares, which might have been
2683
+            // set by ancient bugs
2684
+            $row['expiration'] = null;
2685
+        }
2686
+    }
2687
+
2688
+    /**
2689
+     * format result
2690
+     * @param array $items result
2691
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2692
+     * @param \OCP\Share_Backend $backend sharing backend
2693
+     * @param int $format
2694
+     * @param array $parameters additional format parameters
2695
+     * @return array format result
2696
+     */
2697
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2698
+        if ($format === self::FORMAT_NONE) {
2699
+            return $items;
2700
+        } else if ($format === self::FORMAT_STATUSES) {
2701
+            $statuses = array();
2702
+            foreach ($items as $item) {
2703
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2704
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2705
+                        continue;
2706
+                    }
2707
+                    $statuses[$item[$column]]['link'] = true;
2708
+                } else if (!isset($statuses[$item[$column]])) {
2709
+                    $statuses[$item[$column]]['link'] = false;
2710
+                }
2711
+                if (!empty($item['file_target'])) {
2712
+                    $statuses[$item[$column]]['path'] = $item['path'];
2713
+                }
2714
+            }
2715
+            return $statuses;
2716
+        } else {
2717
+            return $backend->formatItems($items, $format, $parameters);
2718
+        }
2719
+    }
2720
+
2721
+    /**
2722
+     * remove protocol from URL
2723
+     *
2724
+     * @param string $url
2725
+     * @return string
2726
+     */
2727
+    public static function removeProtocolFromUrl($url) {
2728
+        if (strpos($url, 'https://') === 0) {
2729
+            return substr($url, strlen('https://'));
2730
+        } else if (strpos($url, 'http://') === 0) {
2731
+            return substr($url, strlen('http://'));
2732
+        }
2733
+
2734
+        return $url;
2735
+    }
2736
+
2737
+    /**
2738
+     * try http post first with https and then with http as a fallback
2739
+     *
2740
+     * @param string $remoteDomain
2741
+     * @param string $urlSuffix
2742
+     * @param array $fields post parameters
2743
+     * @return array
2744
+     */
2745
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2746
+        $protocol = 'https://';
2747
+        $result = [
2748
+            'success' => false,
2749
+            'result' => '',
2750
+        ];
2751
+        $try = 0;
2752
+        $discoveryService = \OC::$server->getOCSDiscoveryService();
2753
+        while ($result['success'] === false && $try < 2) {
2754
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2755
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2756
+            $result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2757
+            $try++;
2758
+            $protocol = 'http://';
2759
+        }
2760
+
2761
+        return $result;
2762
+    }
2763
+
2764
+    /**
2765
+     * send server-to-server share to remote server
2766
+     *
2767
+     * @param string $token
2768
+     * @param string $shareWith
2769
+     * @param string $name
2770
+     * @param int $remote_id
2771
+     * @param string $owner
2772
+     * @return bool
2773
+     */
2774
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2775
+
2776
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2777
+
2778
+        if ($user && $remote) {
2779
+            $url = $remote;
2780
+
2781
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2782
+
2783
+            $fields = array(
2784
+                'shareWith' => $user,
2785
+                'token' => $token,
2786
+                'name' => $name,
2787
+                'remoteId' => $remote_id,
2788
+                'owner' => $owner,
2789
+                'remote' => $local,
2790
+            );
2791
+
2792
+            $url = self::removeProtocolFromUrl($url);
2793
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2794
+            $status = json_decode($result['result'], true);
2795
+
2796
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2797
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2798
+                return true;
2799
+            }
2800
+
2801
+        }
2802
+
2803
+        return false;
2804
+    }
2805
+
2806
+    /**
2807
+     * send server-to-server unshare to remote server
2808
+     *
2809
+     * @param string $remote url
2810
+     * @param int $id share id
2811
+     * @param string $token
2812
+     * @return bool
2813
+     */
2814
+    private static function sendRemoteUnshare($remote, $id, $token) {
2815
+        $url = rtrim($remote, '/');
2816
+        $fields = array('token' => $token, 'format' => 'json');
2817
+        $url = self::removeProtocolFromUrl($url);
2818
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2819
+        $status = json_decode($result['result'], true);
2820
+
2821
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2822
+    }
2823
+
2824
+    /**
2825
+     * check if user can only share with group members
2826
+     * @return bool
2827
+     */
2828
+    public static function shareWithGroupMembersOnly() {
2829
+        $value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no');
2830
+        return ($value === 'yes') ? true : false;
2831
+    }
2832
+
2833
+    /**
2834
+     * @return bool
2835
+     */
2836
+    public static function isDefaultExpireDateEnabled() {
2837
+        $defaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
2838
+        return ($defaultExpireDateEnabled === "yes") ? true : false;
2839
+    }
2840
+
2841
+    /**
2842
+     * @return bool
2843
+     */
2844
+    public static function enforceDefaultExpireDate() {
2845
+        $enforceDefaultExpireDate = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2846
+        return ($enforceDefaultExpireDate === "yes") ? true : false;
2847
+    }
2848
+
2849
+    /**
2850
+     * @return int
2851
+     */
2852
+    public static function getExpireInterval() {
2853
+        return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
2854
+    }
2855
+
2856
+    /**
2857
+     * Checks whether the given path is reachable for the given owner
2858
+     *
2859
+     * @param string $path path relative to files
2860
+     * @param string $ownerStorageId storage id of the owner
2861
+     *
2862
+     * @return boolean true if file is reachable, false otherwise
2863
+     */
2864
+    private static function isFileReachable($path, $ownerStorageId) {
2865
+        // if outside the home storage, file is always considered reachable
2866
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2867
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2868
+        )) {
2869
+            return true;
2870
+        }
2871
+
2872
+        // if inside the home storage, the file has to be under "/files/"
2873
+        $path = ltrim($path, '/');
2874
+        if (substr($path, 0, 6) === 'files/') {
2875
+            return true;
2876
+        }
2877
+
2878
+        return false;
2879
+    }
2880
+
2881
+    /**
2882
+     * @param IConfig $config
2883
+     * @return bool
2884
+     */
2885
+    public static function enforcePassword(IConfig $config) {
2886
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2887
+        return ($enforcePassword === "yes") ? true : false;
2888
+    }
2889
+
2890
+    /**
2891
+     * Get all share entries, including non-unique group items
2892
+     *
2893
+     * @param string $owner
2894
+     * @return array
2895
+     */
2896
+    public static function getAllSharesForOwner($owner) {
2897
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2898
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2899
+        return $result->fetchAll();
2900
+    }
2901
+
2902
+    /**
2903
+     * Get all share entries, including non-unique group items for a file
2904
+     *
2905
+     * @param int $id
2906
+     * @return array
2907
+     */
2908
+    public static function getAllSharesForFileId($id) {
2909
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2910
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2911
+        return $result->fetchAll();
2912
+    }
2913
+
2914
+    /**
2915
+     * @param string $password
2916
+     * @throws \Exception
2917
+     */
2918
+    private static function verifyPassword($password) {
2919
+
2920
+        $accepted = true;
2921
+        $message = '';
2922
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2923
+            'password' => $password,
2924
+            'accepted' => &$accepted,
2925
+            'message' => &$message
2926
+        ]);
2927
+
2928
+        if (!$accepted) {
2929
+            throw new \Exception($message);
2930
+        }
2931
+    }
2932 2932
 }
Please login to merge, or discard this patch.
Spacing   +76 added lines, -76 removed lines patch added patch discarded remove patch
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 					'collectionOf' => $collectionOf,
92 92
 					'supportedFileExtensions' => $supportedFileExtensions
93 93
 				);
94
-				if(count(self::$backendTypes) === 1) {
94
+				if (count(self::$backendTypes) === 1) {
95 95
 					\OC_Util::addScript('core', 'shareconfigmodel');
96 96
 					\OC_Util::addScript('core', 'shareitemmodel');
97 97
 					\OC_Util::addScript('core', 'sharesocialmanager');
@@ -171,22 +171,22 @@  discard block
 block discarded – undo
171 171
 		$source = -1;
172 172
 		$cache = $mountPath = false;
173 173
 
174
-		$view = new \OC\Files\View('/' . $ownerUser . '/files');
174
+		$view = new \OC\Files\View('/'.$ownerUser.'/files');
175 175
 		$meta = $view->getFileInfo($path);
176 176
 		if ($meta) {
177
-			$path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
177
+			$path = substr($meta->getPath(), strlen('/'.$ownerUser.'/files'));
178 178
 		} else {
179 179
 			// if the file doesn't exists yet we start with the parent folder
180 180
 			$meta = $view->getFileInfo(dirname($path));
181 181
 		}
182 182
 
183
-		if($meta !== false) {
183
+		if ($meta !== false) {
184 184
 			$source = $meta['fileid'];
185 185
 			$cache = new \OC\Files\Cache\Cache($meta['storage']);
186 186
 
187 187
 			$mountPath = $meta->getMountPoint()->getMountPoint();
188 188
 			if ($mountPath !== false) {
189
-				$mountPath = substr($mountPath, strlen('/' . $ownerUser . '/files'));
189
+				$mountPath = substr($mountPath, strlen('/'.$ownerUser.'/files'));
190 190
 			}
191 191
 		}
192 192
 
@@ -304,10 +304,10 @@  discard block
 block discarded – undo
304 304
 			}
305 305
 
306 306
 			// let's get the parent for the next round
307
-			$meta = $cache->get((int)$source);
307
+			$meta = $cache->get((int) $source);
308 308
 			if ($recursive === true && $meta !== false) {
309 309
 				$paths[$source] = $meta['path'];
310
-				$source = (int)$meta['parent'];
310
+				$source = (int) $meta['parent'];
311 311
 			} else {
312 312
 				$source = -1;
313 313
 			}
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 				$query = \OC_DB::prepare(
327 327
 					'SELECT `fileid`, `path`
328 328
 					FROM `*PREFIX*filecache`
329
-					WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'
329
+					WHERE `fileid` IN (' . implode(',', $fileTargetIDs).')'
330 330
 				);
331 331
 				$result = $query->execute();
332 332
 
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 								$sharePaths[$uid] = $sharedPath;
342 342
 							} else {
343 343
 								$sharedPath = $shareData['file_target'];
344
-								$sharedPath .= substr($path, strlen($row['path']) -5);
344
+								$sharedPath .= substr($path, strlen($row['path']) - 5);
345 345
 								$sharePaths[$uid] = $sharedPath;
346 346
 							}
347 347
 						}
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 
434 434
 		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
435 435
 
436
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
436
+		$where .= ' `'.$column.'` = ? AND `item_type` = ? ';
437 437
 		$arguments = array($itemSource, $itemType);
438 438
 		// for link shares $user === null
439 439
 		if ($user !== null) {
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 			$arguments[] = $owner;
452 452
 		}
453 453
 
454
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
454
+		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$fileDependentWhere.$where);
455 455
 
456 456
 		$result = \OC_DB::executeAudited($query, $arguments);
457 457
 
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
460 460
 				continue;
461 461
 			}
462
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
462
+			if ($fileDependent && (int) $row['file_parent'] === -1) {
463 463
 				// if it is a mount point we need to get the path from the mount manager
464 464
 				$mountManager = \OC\Files\Filesystem::getMountManager();
465 465
 				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 					$row['path'] = $path;
471 471
 				} else {
472 472
 					\OC::$server->getLogger()->warning(
473
-						'Could not resolve mount point for ' . $row['storage_id'],
473
+						'Could not resolve mount point for '.$row['storage_id'],
474 474
 						['app' => 'OCP\Share']
475 475
 					);
476 476
 				}
@@ -479,7 +479,7 @@  discard block
 block discarded – undo
479 479
 		}
480 480
 
481 481
 		//if didn't found a result than let's look for a group share.
482
-		if(empty($shares) && $user !== null) {
482
+		if (empty($shares) && $user !== null) {
483 483
 			$userObject = \OC::$server->getUserManager()->get($user);
484 484
 			$groups = [];
485 485
 			if ($userObject) {
@@ -487,7 +487,7 @@  discard block
 block discarded – undo
487 487
 			}
488 488
 
489 489
 			if (!empty($groups)) {
490
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
490
+				$where = $fileDependentWhere.' WHERE `'.$column.'` = ? AND `item_type` = ? AND `share_with` in (?)';
491 491
 				$arguments = array($itemSource, $itemType, $groups);
492 492
 				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
493 493
 
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
 				// class isn't static anymore...
502 502
 				$conn = \OC::$server->getDatabaseConnection();
503 503
 				$result = $conn->executeQuery(
504
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
504
+					'SELECT '.$select.' FROM `*PREFIX*share` '.$where,
505 505
 					$arguments,
506 506
 					$types
507 507
 				);
@@ -555,7 +555,7 @@  discard block
 block discarded – undo
555 555
 		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
556 556
 		$result = $query->execute(array($token));
557 557
 		if ($result === false) {
558
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
558
+			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage().', token='.$token, \OCP\Util::ERROR);
559 559
 		}
560 560
 		$row = $result->fetchRow();
561 561
 		if ($row === false) {
@@ -641,9 +641,9 @@  discard block
 block discarded – undo
641 641
 		$items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
642 642
 		if ($items) {
643 643
 			foreach ($items as $item) {
644
-				if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
644
+				if ((int) $item['share_type'] === self::SHARE_TYPE_USER) {
645 645
 					$users[] = $item['share_with'];
646
-				} else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
646
+				} else if ((int) $item['share_type'] === self::SHARE_TYPE_GROUP) {
647 647
 
648 648
 					$group = \OC::$server->getGroupManager()->get($item['share_with']);
649 649
 					$userIds = [];
@@ -719,12 +719,12 @@  discard block
 block discarded – undo
719 719
 
720 720
 		//verify that we don't share a folder which already contains a share mount point
721 721
 		if ($itemType === 'folder') {
722
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
722
+			$path = '/'.$uidOwner.'/files'.\OC\Files\Filesystem::getPath($itemSource).'/';
723 723
 			$mountManager = \OC\Files\Filesystem::getMountManager();
724 724
 			$mounts = $mountManager->findIn($path);
725 725
 			foreach ($mounts as $mount) {
726 726
 				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
727
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
727
+					$message = 'Sharing "'.$itemSourceName.'" failed, because it contains files shared with you!';
728 728
 					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
729 729
 					throw new \Exception($message);
730 730
 				}
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 
735 735
 		// single file shares should never have delete permissions
736 736
 		if ($itemType === 'file') {
737
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
737
+			$permissions = (int) $permissions & ~\OCP\Constants::PERMISSION_DELETE;
738 738
 		}
739 739
 
740 740
 		//Validate expirationDate
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
 					} else {
889 889
 						// reuse the already set password, but only if we change permissions
890 890
 						// otherwise the user disabled the password protection
891
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
891
+						if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
892 892
 							$shareWith = $checkExists['share_with'];
893 893
 						}
894 894
 					}
@@ -961,10 +961,10 @@  discard block
 block discarded – undo
961 961
 				throw new \Exception($message_t);
962 962
 			}
963 963
 
964
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
964
+			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
965 965
 				\OCP\Security\ISecureRandom::CHAR_DIGITS);
966 966
 
967
-			$shareWith = $user . '@' . $remote;
967
+			$shareWith = $user.'@'.$remote;
968 968
 			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
969 969
 
970 970
 			$send = false;
@@ -1015,12 +1015,12 @@  discard block
 block discarded – undo
1015 1015
 		$currentUser = $owner ? $owner : \OC_User::getUser();
1016 1016
 		foreach ($items as $item) {
1017 1017
 			// delete the item with the expected share_type and owner
1018
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
1018
+			if ((int) $item['share_type'] === (int) $shareType && $item['uid_owner'] === $currentUser) {
1019 1019
 				$toDelete = $item;
1020 1020
 				// if there is more then one result we don't have to delete the children
1021 1021
 				// but update their parent. For group shares the new parent should always be
1022 1022
 				// the original group share and not the db entry with the unique name
1023
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
1023
+			} else if ((int) $item['share_type'] === self::$shareTypeGroupUserUnique) {
1024 1024
 				$newParent = $item['parent'];
1025 1025
 			} else {
1026 1026
 				$newParent = $item['id'];
@@ -1042,7 +1042,7 @@  discard block
 block discarded – undo
1042 1042
 	 */
1043 1043
 	public static function unshareAll($itemType, $itemSource) {
1044 1044
 		// Get all of the owners of shares of this item.
1045
-		$query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
1045
+		$query = \OC_DB::prepare('SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?');
1046 1046
 		$result = $query->execute(array($itemType, $itemSource));
1047 1047
 		$shares = array();
1048 1048
 		// Add each owner's shares to the array of all shares for this item.
@@ -1080,9 +1080,9 @@  discard block
 block discarded – undo
1080 1080
 		$uid = \OCP\User::getUser();
1081 1081
 
1082 1082
 		if ($itemType === 'file' || $itemType === 'folder') {
1083
-			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
1083
+			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_'.$originType.'` = ?';
1084 1084
 		} else {
1085
-			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
1085
+			$statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_'.$originType.'` = ?';
1086 1086
 		}
1087 1087
 
1088 1088
 		$query = \OCP\DB::prepare($statement);
@@ -1094,7 +1094,7 @@  discard block
 block discarded – undo
1094 1094
 
1095 1095
 		$itemUnshared = false;
1096 1096
 		foreach ($shares as $share) {
1097
-			if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
1097
+			if ((int) $share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
1098 1098
 				$share['share_with'] === $uid) {
1099 1099
 				$deletedShares = Helper::delete($share['id']);
1100 1100
 				$shareTmp = array(
@@ -1102,7 +1102,7 @@  discard block
 block discarded – undo
1102 1102
 					'shareWith' => $share['share_with'],
1103 1103
 					'itemTarget' => $share['item_target'],
1104 1104
 					'itemType' => $share['item_type'],
1105
-					'shareType' => (int)$share['share_type'],
1105
+					'shareType' => (int) $share['share_type'],
1106 1106
 				);
1107 1107
 				if (isset($share['file_target'])) {
1108 1108
 					$shareTmp['fileTarget'] = $share['file_target'];
@@ -1110,13 +1110,13 @@  discard block
 block discarded – undo
1110 1110
 				$listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
1111 1111
 				$itemUnshared = true;
1112 1112
 				break;
1113
-			} elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
1113
+			} elseif ((int) $share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
1114 1114
 				$group = \OC::$server->getGroupManager()->get($share['share_with']);
1115 1115
 				$user = \OC::$server->getUserManager()->get($uid);
1116 1116
 				if ($group && $user && $group->inGroup($user)) {
1117 1117
 					$groupShare = $share;
1118 1118
 				}
1119
-			} elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
1119
+			} elseif ((int) $share['share_type'] === self::$shareTypeGroupUserUnique &&
1120 1120
 				$share['share_with'] === $uid) {
1121 1121
 				$uniqueGroupShare = $share;
1122 1122
 			}
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 				'shareWith' => $groupShare['share_with'],
1137 1137
 				'itemTarget' => $groupShare['item_target'],
1138 1138
 				'itemType' => $groupShare['item_type'],
1139
-				'shareType' => (int)$groupShare['share_type'],
1139
+				'shareType' => (int) $groupShare['share_type'],
1140 1140
 			);
1141 1141
 			if (isset($groupShare['file_target'])) {
1142 1142
 				$shareTmp['fileTarget'] = $groupShare['file_target'];
@@ -1151,7 +1151,7 @@  discard block
 block discarded – undo
1151 1151
 				'shareWith' => $uniqueGroupShare['share_with'],
1152 1152
 				'itemTarget' => $uniqueGroupShare['item_target'],
1153 1153
 				'itemType' => $uniqueGroupShare['item_type'],
1154
-				'shareType' => (int)$uniqueGroupShare['share_type'],
1154
+				'shareType' => (int) $uniqueGroupShare['share_type'],
1155 1155
 			);
1156 1156
 			if (isset($uniqueGroupShare['file_target'])) {
1157 1157
 				$shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
 
1187 1187
 		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
1188 1188
 
1189
-		if($result === false) {
1189
+		if ($result === false) {
1190 1190
 			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
1191 1191
 		}
1192 1192
 	}
@@ -1207,12 +1207,12 @@  discard block
 block discarded – undo
1207 1207
 
1208 1208
 		$intArrayToLiteralArray = function($intArray, $eb) {
1209 1209
 			return array_map(function($int) use ($eb) {
1210
-				return $eb->literal((int)$int, 'integer');
1210
+				return $eb->literal((int) $int, 'integer');
1211 1211
 			}, $intArray);
1212 1212
 		};
1213 1213
 		$sanitizeItem = function($item) {
1214
-			$item['id'] = (int)$item['id'];
1215
-			$item['premissions'] = (int)$item['permissions'];
1214
+			$item['id'] = (int) $item['id'];
1215
+			$item['premissions'] = (int) $item['permissions'];
1216 1216
 			return $item;
1217 1217
 		};
1218 1218
 
@@ -1230,7 +1230,7 @@  discard block
 block discarded – undo
1230 1230
 
1231 1231
 				$result = $dbresult->fetch();
1232 1232
 				$dbresult->closeCursor();
1233
-				if (~(int)$result['permissions'] & $permissions) {
1233
+				if (~(int) $result['permissions'] & $permissions) {
1234 1234
 					$message = 'Setting permissions for %s failed,'
1235 1235
 						.' because the permissions exceed permissions granted to %s';
1236 1236
 					$message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
 			$items = [];
1264 1264
 
1265 1265
 			// Check if permissions were removed
1266
-			if ((int)$rootItem['permissions'] & ~$permissions) {
1266
+			if ((int) $rootItem['permissions'] & ~$permissions) {
1267 1267
 				// If share permission is removed all reshares must be deleted
1268 1268
 				if (($rootItem['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
1269 1269
 					// delete all shares, keep parent and group children
@@ -1316,14 +1316,14 @@  discard block
 block discarded – undo
1316 1316
 			 * Permissions were added
1317 1317
 			 * Update all USERGROUP shares. (So group shares where the user moved their mountpoint).
1318 1318
 			 */
1319
-			if ($permissions & ~(int)$rootItem['permissions']) {
1319
+			if ($permissions & ~(int) $rootItem['permissions']) {
1320 1320
 				$qb = $connection->getQueryBuilder();
1321 1321
 				$qb->select('id', 'permissions', 'item_type')
1322 1322
 					->from('share')
1323 1323
 					->where($qb->expr()->eq('parent', $qb->createParameter('parent')))
1324 1324
 					->andWhere($qb->expr()->eq('share_type', $qb->createParameter('share_type')))
1325 1325
 					->andWhere($qb->expr()->neq('permissions', $qb->createParameter('shareDeleted')))
1326
-					->setParameter(':parent', (int)$rootItem['id'])
1326
+					->setParameter(':parent', (int) $rootItem['id'])
1327 1327
 					->setParameter(':share_type', 2)
1328 1328
 					->setParameter(':shareDeleted', 0);
1329 1329
 				$result = $qb->execute();
@@ -1383,7 +1383,7 @@  discard block
 block discarded – undo
1383 1383
 		if ($defaultExpireDateEnforced && $shareTime === null) {
1384 1384
 			$items = self::getItemShared($itemType, $itemSource);
1385 1385
 			$firstItem = reset($items);
1386
-			$shareTime = (int)$firstItem['stime'];
1386
+			$shareTime = (int) $firstItem['stime'];
1387 1387
 		}
1388 1388
 
1389 1389
 		if ($defaultExpireDateEnforced) {
@@ -1391,9 +1391,9 @@  discard block
 block discarded – undo
1391 1391
 			$maxDate = new \DateTime();
1392 1392
 			$maxDate->setTimestamp($shareTime);
1393 1393
 			$maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
1394
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
1394
+			$maxDate->add(new \DateInterval('P'.$maxDays.'D'));
1395 1395
 			if ($date > $maxDate) {
1396
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
1396
+				$warning = 'Cannot set expiration date. Shares cannot expire later than '.$maxDays.' after they have been shared';
1397 1397
 				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
1398 1398
 				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
1399 1399
 				throw new \Exception($warning_t);
@@ -1573,7 +1573,7 @@  discard block
 block discarded – undo
1573 1573
 	 */
1574 1574
 	protected static function unshareItem(array $item, $newParent = null) {
1575 1575
 
1576
-		$shareType = (int)$item['share_type'];
1576
+		$shareType = (int) $item['share_type'];
1577 1577
 		$shareWith = null;
1578 1578
 		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
1579 1579
 			$shareWith = $item['share_with'];
@@ -1589,7 +1589,7 @@  discard block
 block discarded – undo
1589 1589
 			'itemParent'    => $item['parent'],
1590 1590
 			'uidOwner'      => $item['uid_owner'],
1591 1591
 		);
1592
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
1592
+		if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
1593 1593
 			$hookParams['fileSource'] = $item['file_source'];
1594 1594
 			$hookParams['fileTarget'] = $item['file_target'];
1595 1595
 		}
@@ -1599,7 +1599,7 @@  discard block
 block discarded – undo
1599 1599
 		$deletedShares[] = $hookParams;
1600 1600
 		$hookParams['deletedShares'] = $deletedShares;
1601 1601
 		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
1602
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
1602
+		if ((int) $item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
1603 1603
 			list(, $remote) = Helper::splitUserRemote($item['share_with']);
1604 1604
 			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
1605 1605
 		}
@@ -1760,7 +1760,7 @@  discard block
 block discarded – undo
1760 1760
 		// Get filesystem root to add it to the file target and remove from the
1761 1761
 		// file source, match file_source with the file cache
1762 1762
 		if ($itemType == 'file' || $itemType == 'folder') {
1763
-			if(!is_null($uidOwner)) {
1763
+			if (!is_null($uidOwner)) {
1764 1764
 				$root = \OC\Files\Filesystem::getRoot();
1765 1765
 			} else {
1766 1766
 				$root = '';
@@ -1905,7 +1905,7 @@  discard block
 block discarded – undo
1905 1905
 		$result = $query->execute($queryArgs);
1906 1906
 		if ($result === false) {
1907 1907
 			\OCP\Util::writeLog('OCP\Share',
1908
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1908
+				\OC_DB::getErrorMessage().', select='.$select.' where=',
1909 1909
 				\OCP\Util::ERROR);
1910 1910
 		}
1911 1911
 		$items = array();
@@ -1947,14 +1947,14 @@  discard block
 block discarded – undo
1947 1947
 						}
1948 1948
 						// Switch ids if sharing permission is granted on only
1949 1949
 						// one share to ensure correct parent is used if resharing
1950
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1951
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1950
+						if (~(int) $items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1951
+							&& (int) $row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1952 1952
 							$items[$row['id']] = $items[$id];
1953 1953
 							$switchedItems[$id] = $row['id'];
1954 1954
 							unset($items[$id]);
1955 1955
 							$id = $row['id'];
1956 1956
 						}
1957
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1957
+						$items[$id]['permissions'] |= (int) $row['permissions'];
1958 1958
 
1959 1959
 					}
1960 1960
 					continue;
@@ -1968,8 +1968,8 @@  discard block
 block discarded – undo
1968 1968
 					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1969 1969
 					$parentResult = $query->execute(array($row['parent']));
1970 1970
 					if ($result === false) {
1971
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1972
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1971
+						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: '.
1972
+							\OC_DB::getErrorMessage().', select='.$select.' where='.$where,
1973 1973
 							\OCP\Util::ERROR);
1974 1974
 					} else {
1975 1975
 						$parentRow = $parentResult->fetchRow();
@@ -1979,7 +1979,7 @@  discard block
 block discarded – undo
1979 1979
 						$subPath = substr($row['path'], $pos);
1980 1980
 						$splitPath = explode('/', $subPath);
1981 1981
 						foreach (array_slice($splitPath, 2) as $pathPart) {
1982
-							$tmpPath = $tmpPath . '/' . $pathPart;
1982
+							$tmpPath = $tmpPath.'/'.$pathPart;
1983 1983
 						}
1984 1984
 						$row['path'] = $tmpPath;
1985 1985
 					}
@@ -1998,7 +1998,7 @@  discard block
 block discarded – undo
1998 1998
 				}
1999 1999
 			}
2000 2000
 
2001
-			if($checkExpireDate) {
2001
+			if ($checkExpireDate) {
2002 2002
 				if (self::expireItem($row)) {
2003 2003
 					continue;
2004 2004
 				}
@@ -2009,10 +2009,10 @@  discard block
 block discarded – undo
2009 2009
 			}
2010 2010
 			// Add display names to result
2011 2011
 			$row['share_with_displayname'] = $row['share_with'];
2012
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
2012
+			if (isset($row['share_with']) && $row['share_with'] != '' &&
2013 2013
 				$row['share_type'] === self::SHARE_TYPE_USER) {
2014 2014
 				$row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
2015
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
2015
+			} else if (isset($row['share_with']) && $row['share_with'] != '' &&
2016 2016
 				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
2017 2017
 				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
2018 2018
 				foreach ($addressBookEntries as $entry) {
@@ -2023,7 +2023,7 @@  discard block
 block discarded – undo
2023 2023
 					}
2024 2024
 				}
2025 2025
 			}
2026
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
2026
+			if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
2027 2027
 				$row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
2028 2028
 			}
2029 2029
 
@@ -2171,7 +2171,7 @@  discard block
 block discarded – undo
2171 2171
 				// for file/folder shares we need to compare file_source, otherwise we compare item_source
2172 2172
 				// only group shares if they already point to the same target, otherwise the file where shared
2173 2173
 				// before grouping of shares was added. In this case we don't group them toi avoid confusions
2174
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
2174
+				if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
2175 2175
 					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
2176 2176
 					// add the first item to the list of grouped shares
2177 2177
 					if (!isset($result[$key]['grouped'])) {
@@ -2217,7 +2217,7 @@  discard block
 block discarded – undo
2217 2217
 		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
2218 2218
 
2219 2219
 		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
2220
-		if(!empty($result)) {
2220
+		if (!empty($result)) {
2221 2221
 			$parent = $result['parent'];
2222 2222
 			$itemSource = $result['itemSource'];
2223 2223
 			$fileSource = $result['fileSource'];
@@ -2311,11 +2311,11 @@  discard block
 block discarded – undo
2311 2311
 				$itemTarget = $sourceExists['item_target'];
2312 2312
 
2313 2313
 				// for group shares we don't need a additional entry if the target is the same
2314
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
2314
+				if ($isGroupShare && $groupItemTarget === $itemTarget) {
2315 2315
 					continue;
2316 2316
 				}
2317 2317
 
2318
-			} elseif(!$sourceExists && !$isGroupShare)  {
2318
+			} elseif (!$sourceExists && !$isGroupShare) {
2319 2319
 
2320 2320
 				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
2321 2321
 					$uidOwner, $suggestedItemTarget, $parent);
@@ -2446,8 +2446,8 @@  discard block
 block discarded – undo
2446 2446
 
2447 2447
 		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
2448 2448
 			// Check if share permissions is granted
2449
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
2450
-				if (~(int)$checkReshare['permissions'] & $permissions) {
2449
+			if (self::isResharingAllowed() && (int) $checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
2450
+				if (~(int) $checkReshare['permissions'] & $permissions) {
2451 2451
 					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
2452 2452
 					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
2453 2453
 
@@ -2459,7 +2459,7 @@  discard block
 block discarded – undo
2459 2459
 
2460 2460
 					$result['expirationDate'] = $expirationDate;
2461 2461
 					// $checkReshare['expiration'] could be null and then is always less than any value
2462
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
2462
+					if (isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
2463 2463
 						$result['expirationDate'] = $checkReshare['expiration'];
2464 2464
 					}
2465 2465
 
@@ -2551,7 +2551,7 @@  discard block
 block discarded – undo
2551 2551
 
2552 2552
 		$id = false;
2553 2553
 		if ($result) {
2554
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2554
+			$id = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
2555 2555
 		}
2556 2556
 
2557 2557
 		return $id;
@@ -2591,8 +2591,8 @@  discard block
 block discarded – undo
2591 2591
 			return true;
2592 2592
 		}
2593 2593
 
2594
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
2595
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
2594
+		if (\OC::$server->getSession()->exists('public_link_authenticated')
2595
+			&& \OC::$server->getSession()->get('public_link_authenticated') === (string) $linkItem['id']) {
2596 2596
 			return true;
2597 2597
 		}
2598 2598
 
@@ -2694,7 +2694,7 @@  discard block
 block discarded – undo
2694 2694
 	 * @param array $parameters additional format parameters
2695 2695
 	 * @return array format result
2696 2696
 	 */
2697
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2697
+	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE, $parameters = null) {
2698 2698
 		if ($format === self::FORMAT_NONE) {
2699 2699
 			return $items;
2700 2700
 		} else if ($format === self::FORMAT_STATUSES) {
@@ -2751,9 +2751,9 @@  discard block
 block discarded – undo
2751 2751
 		$try = 0;
2752 2752
 		$discoveryService = \OC::$server->getOCSDiscoveryService();
2753 2753
 		while ($result['success'] === false && $try < 2) {
2754
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2754
+			$federationEndpoints = $discoveryService->discover($protocol.$remoteDomain, 'FEDERATED_SHARING');
2755 2755
 			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2756
-			$result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2756
+			$result = \OC::$server->getHTTPHelper()->post($protocol.$remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT, $fields);
2757 2757
 			$try++;
2758 2758
 			$protocol = 'http://';
2759 2759
 		}
@@ -2850,7 +2850,7 @@  discard block
 block discarded – undo
2850 2850
 	 * @return int
2851 2851
 	 */
2852 2852
 	public static function getExpireInterval() {
2853
-		return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
2853
+		return (int) \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
2854 2854
 	}
2855 2855
 
2856 2856
 	/**
Please login to merge, or discard this patch.
lib/private/Share20/ProviderFactory.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -24,7 +24,6 @@
 block discarded – undo
24 24
 namespace OC\Share20;
25 25
 
26 26
 use OCA\FederatedFileSharing\AddressHandler;
27
-use OCA\FederatedFileSharing\DiscoveryManager;
28 27
 use OCA\FederatedFileSharing\FederatedShareProvider;
29 28
 use OCA\FederatedFileSharing\Notifications;
30 29
 use OCA\FederatedFileSharing\TokenHandler;
Please login to merge, or discard this patch.
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -40,220 +40,220 @@
 block discarded – undo
40 40
  */
41 41
 class ProviderFactory implements IProviderFactory {
42 42
 
43
-	/** @var IServerContainer */
44
-	private $serverContainer;
45
-	/** @var DefaultShareProvider */
46
-	private $defaultProvider = null;
47
-	/** @var FederatedShareProvider */
48
-	private $federatedProvider = null;
49
-	/** @var  ShareByMailProvider */
50
-	private $shareByMailProvider;
51
-	/** @var  \OCA\Circles\ShareByCircleProvider;
52
-	 * ShareByCircleProvider */
53
-	private $shareByCircleProvider;
54
-
55
-	/**
56
-	 * IProviderFactory constructor.
57
-	 *
58
-	 * @param IServerContainer $serverContainer
59
-	 */
60
-	public function __construct(IServerContainer $serverContainer) {
61
-		$this->serverContainer = $serverContainer;
62
-	}
63
-
64
-	/**
65
-	 * Create the default share provider.
66
-	 *
67
-	 * @return DefaultShareProvider
68
-	 */
69
-	protected function defaultShareProvider() {
70
-		if ($this->defaultProvider === null) {
71
-			$this->defaultProvider = new DefaultShareProvider(
72
-				$this->serverContainer->getDatabaseConnection(),
73
-				$this->serverContainer->getUserManager(),
74
-				$this->serverContainer->getGroupManager(),
75
-				$this->serverContainer->getLazyRootFolder()
76
-			);
77
-		}
78
-
79
-		return $this->defaultProvider;
80
-	}
81
-
82
-	/**
83
-	 * Create the federated share provider
84
-	 *
85
-	 * @return FederatedShareProvider
86
-	 */
87
-	protected function federatedShareProvider() {
88
-		if ($this->federatedProvider === null) {
89
-			/*
43
+    /** @var IServerContainer */
44
+    private $serverContainer;
45
+    /** @var DefaultShareProvider */
46
+    private $defaultProvider = null;
47
+    /** @var FederatedShareProvider */
48
+    private $federatedProvider = null;
49
+    /** @var  ShareByMailProvider */
50
+    private $shareByMailProvider;
51
+    /** @var  \OCA\Circles\ShareByCircleProvider;
52
+     * ShareByCircleProvider */
53
+    private $shareByCircleProvider;
54
+
55
+    /**
56
+     * IProviderFactory constructor.
57
+     *
58
+     * @param IServerContainer $serverContainer
59
+     */
60
+    public function __construct(IServerContainer $serverContainer) {
61
+        $this->serverContainer = $serverContainer;
62
+    }
63
+
64
+    /**
65
+     * Create the default share provider.
66
+     *
67
+     * @return DefaultShareProvider
68
+     */
69
+    protected function defaultShareProvider() {
70
+        if ($this->defaultProvider === null) {
71
+            $this->defaultProvider = new DefaultShareProvider(
72
+                $this->serverContainer->getDatabaseConnection(),
73
+                $this->serverContainer->getUserManager(),
74
+                $this->serverContainer->getGroupManager(),
75
+                $this->serverContainer->getLazyRootFolder()
76
+            );
77
+        }
78
+
79
+        return $this->defaultProvider;
80
+    }
81
+
82
+    /**
83
+     * Create the federated share provider
84
+     *
85
+     * @return FederatedShareProvider
86
+     */
87
+    protected function federatedShareProvider() {
88
+        if ($this->federatedProvider === null) {
89
+            /*
90 90
 			 * Check if the app is enabled
91 91
 			 */
92
-			$appManager = $this->serverContainer->getAppManager();
93
-			if (!$appManager->isEnabledForUser('federatedfilesharing')) {
94
-				return null;
95
-			}
92
+            $appManager = $this->serverContainer->getAppManager();
93
+            if (!$appManager->isEnabledForUser('federatedfilesharing')) {
94
+                return null;
95
+            }
96 96
 
97
-			/*
97
+            /*
98 98
 			 * TODO: add factory to federated sharing app
99 99
 			 */
100
-			$l = $this->serverContainer->getL10N('federatedfilessharing');
101
-			$addressHandler = new AddressHandler(
102
-				$this->serverContainer->getURLGenerator(),
103
-				$l,
104
-				$this->serverContainer->getCloudIdManager()
105
-			);
106
-			$notifications = new Notifications(
107
-				$addressHandler,
108
-				$this->serverContainer->getHTTPClientService(),
109
-				$this->serverContainer->getOCSDiscoveryService(),
110
-				$this->serverContainer->getJobList()
111
-			);
112
-			$tokenHandler = new TokenHandler(
113
-				$this->serverContainer->getSecureRandom()
114
-			);
115
-
116
-			$this->federatedProvider = new FederatedShareProvider(
117
-				$this->serverContainer->getDatabaseConnection(),
118
-				$addressHandler,
119
-				$notifications,
120
-				$tokenHandler,
121
-				$l,
122
-				$this->serverContainer->getLogger(),
123
-				$this->serverContainer->getLazyRootFolder(),
124
-				$this->serverContainer->getConfig(),
125
-				$this->serverContainer->getUserManager(),
126
-				$this->serverContainer->getCloudIdManager()
127
-			);
128
-		}
129
-
130
-		return $this->federatedProvider;
131
-	}
132
-
133
-	/**
134
-	 * Create the federated share provider
135
-	 *
136
-	 * @return ShareByMailProvider
137
-	 */
138
-	protected function getShareByMailProvider() {
139
-		if ($this->shareByMailProvider === null) {
140
-			/*
100
+            $l = $this->serverContainer->getL10N('federatedfilessharing');
101
+            $addressHandler = new AddressHandler(
102
+                $this->serverContainer->getURLGenerator(),
103
+                $l,
104
+                $this->serverContainer->getCloudIdManager()
105
+            );
106
+            $notifications = new Notifications(
107
+                $addressHandler,
108
+                $this->serverContainer->getHTTPClientService(),
109
+                $this->serverContainer->getOCSDiscoveryService(),
110
+                $this->serverContainer->getJobList()
111
+            );
112
+            $tokenHandler = new TokenHandler(
113
+                $this->serverContainer->getSecureRandom()
114
+            );
115
+
116
+            $this->federatedProvider = new FederatedShareProvider(
117
+                $this->serverContainer->getDatabaseConnection(),
118
+                $addressHandler,
119
+                $notifications,
120
+                $tokenHandler,
121
+                $l,
122
+                $this->serverContainer->getLogger(),
123
+                $this->serverContainer->getLazyRootFolder(),
124
+                $this->serverContainer->getConfig(),
125
+                $this->serverContainer->getUserManager(),
126
+                $this->serverContainer->getCloudIdManager()
127
+            );
128
+        }
129
+
130
+        return $this->federatedProvider;
131
+    }
132
+
133
+    /**
134
+     * Create the federated share provider
135
+     *
136
+     * @return ShareByMailProvider
137
+     */
138
+    protected function getShareByMailProvider() {
139
+        if ($this->shareByMailProvider === null) {
140
+            /*
141 141
 			 * Check if the app is enabled
142 142
 			 */
143
-			$appManager = $this->serverContainer->getAppManager();
144
-			if (!$appManager->isEnabledForUser('sharebymail')) {
145
-				return null;
146
-			}
147
-
148
-			$l = $this->serverContainer->getL10N('sharebymail');
149
-
150
-			$this->shareByMailProvider = new ShareByMailProvider(
151
-				$this->serverContainer->getDatabaseConnection(),
152
-				$this->serverContainer->getSecureRandom(),
153
-				$this->serverContainer->getUserManager(),
154
-				$this->serverContainer->getLazyRootFolder(),
155
-				$l,
156
-				$this->serverContainer->getLogger(),
157
-				$this->serverContainer->getMailer(),
158
-				$this->serverContainer->getURLGenerator(),
159
-				$this->serverContainer->getActivityManager()
160
-			);
161
-		}
162
-
163
-		return $this->shareByMailProvider;
164
-	}
165
-
166
-
167
-	/**
168
-	 * Create the circle share provider
169
-	 *
170
-	 * @return FederatedShareProvider
171
-	 */
172
-	protected function getShareByCircleProvider() {
173
-
174
-		$appManager = $this->serverContainer->getAppManager();
175
-		if (!$appManager->isEnabledForUser('circles')) {
176
-			return null;
177
-		}
178
-
179
-
180
-		if ($this->shareByCircleProvider === null) {
181
-
182
-			$this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
183
-				$this->serverContainer->getDatabaseConnection(),
184
-				$this->serverContainer->getSecureRandom(),
185
-				$this->serverContainer->getUserManager(),
186
-				$this->serverContainer->getLazyRootFolder(),
187
-				$this->serverContainer->getL10N('circles'),
188
-				$this->serverContainer->getLogger(),
189
-				$this->serverContainer->getURLGenerator()
190
-			);
191
-		}
192
-
193
-		return $this->shareByCircleProvider;
194
-	}
195
-
196
-
197
-	/**
198
-	 * @inheritdoc
199
-	 */
200
-	public function getProvider($id) {
201
-		$provider = null;
202
-		if ($id === 'ocinternal') {
203
-			$provider = $this->defaultShareProvider();
204
-		} else if ($id === 'ocFederatedSharing') {
205
-			$provider = $this->federatedShareProvider();
206
-		} else if ($id === 'ocMailShare') {
207
-			$provider = $this->getShareByMailProvider();
208
-		} else if ($id === 'ocCircleShare') {
209
-			$provider = $this->getShareByCircleProvider();
210
-		}
211
-
212
-		if ($provider === null) {
213
-			throw new ProviderException('No provider with id .' . $id . ' found.');
214
-		}
215
-
216
-		return $provider;
217
-	}
218
-
219
-	/**
220
-	 * @inheritdoc
221
-	 */
222
-	public function getProviderForType($shareType) {
223
-		$provider = null;
224
-
225
-		if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
226
-			$shareType === \OCP\Share::SHARE_TYPE_GROUP ||
227
-			$shareType === \OCP\Share::SHARE_TYPE_LINK
228
-		) {
229
-			$provider = $this->defaultShareProvider();
230
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
231
-			$provider = $this->federatedShareProvider();
232
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
233
-			$provider = $this->getShareByMailProvider();
234
-		} else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
235
-			$provider = $this->getShareByCircleProvider();
236
-		}
237
-
238
-
239
-		if ($provider === null) {
240
-			throw new ProviderException('No share provider for share type ' . $shareType);
241
-		}
242
-
243
-		return $provider;
244
-	}
245
-
246
-	public function getAllProviders() {
247
-		$shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
248
-		$shareByMail = $this->getShareByMailProvider();
249
-		if ($shareByMail !== null) {
250
-			$shares[] = $shareByMail;
251
-		}
252
-		$shareByCircle = $this->getShareByCircleProvider();
253
-		if ($shareByCircle !== null) {
254
-			$shares[] = $shareByCircle;
255
-		}
256
-
257
-		return $shares;
258
-	}
143
+            $appManager = $this->serverContainer->getAppManager();
144
+            if (!$appManager->isEnabledForUser('sharebymail')) {
145
+                return null;
146
+            }
147
+
148
+            $l = $this->serverContainer->getL10N('sharebymail');
149
+
150
+            $this->shareByMailProvider = new ShareByMailProvider(
151
+                $this->serverContainer->getDatabaseConnection(),
152
+                $this->serverContainer->getSecureRandom(),
153
+                $this->serverContainer->getUserManager(),
154
+                $this->serverContainer->getLazyRootFolder(),
155
+                $l,
156
+                $this->serverContainer->getLogger(),
157
+                $this->serverContainer->getMailer(),
158
+                $this->serverContainer->getURLGenerator(),
159
+                $this->serverContainer->getActivityManager()
160
+            );
161
+        }
162
+
163
+        return $this->shareByMailProvider;
164
+    }
165
+
166
+
167
+    /**
168
+     * Create the circle share provider
169
+     *
170
+     * @return FederatedShareProvider
171
+     */
172
+    protected function getShareByCircleProvider() {
173
+
174
+        $appManager = $this->serverContainer->getAppManager();
175
+        if (!$appManager->isEnabledForUser('circles')) {
176
+            return null;
177
+        }
178
+
179
+
180
+        if ($this->shareByCircleProvider === null) {
181
+
182
+            $this->shareByCircleProvider = new \OCA\Circles\ShareByCircleProvider(
183
+                $this->serverContainer->getDatabaseConnection(),
184
+                $this->serverContainer->getSecureRandom(),
185
+                $this->serverContainer->getUserManager(),
186
+                $this->serverContainer->getLazyRootFolder(),
187
+                $this->serverContainer->getL10N('circles'),
188
+                $this->serverContainer->getLogger(),
189
+                $this->serverContainer->getURLGenerator()
190
+            );
191
+        }
192
+
193
+        return $this->shareByCircleProvider;
194
+    }
195
+
196
+
197
+    /**
198
+     * @inheritdoc
199
+     */
200
+    public function getProvider($id) {
201
+        $provider = null;
202
+        if ($id === 'ocinternal') {
203
+            $provider = $this->defaultShareProvider();
204
+        } else if ($id === 'ocFederatedSharing') {
205
+            $provider = $this->federatedShareProvider();
206
+        } else if ($id === 'ocMailShare') {
207
+            $provider = $this->getShareByMailProvider();
208
+        } else if ($id === 'ocCircleShare') {
209
+            $provider = $this->getShareByCircleProvider();
210
+        }
211
+
212
+        if ($provider === null) {
213
+            throw new ProviderException('No provider with id .' . $id . ' found.');
214
+        }
215
+
216
+        return $provider;
217
+    }
218
+
219
+    /**
220
+     * @inheritdoc
221
+     */
222
+    public function getProviderForType($shareType) {
223
+        $provider = null;
224
+
225
+        if ($shareType === \OCP\Share::SHARE_TYPE_USER ||
226
+            $shareType === \OCP\Share::SHARE_TYPE_GROUP ||
227
+            $shareType === \OCP\Share::SHARE_TYPE_LINK
228
+        ) {
229
+            $provider = $this->defaultShareProvider();
230
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_REMOTE) {
231
+            $provider = $this->federatedShareProvider();
232
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_EMAIL) {
233
+            $provider = $this->getShareByMailProvider();
234
+        } else if ($shareType === \OCP\Share::SHARE_TYPE_CIRCLE) {
235
+            $provider = $this->getShareByCircleProvider();
236
+        }
237
+
238
+
239
+        if ($provider === null) {
240
+            throw new ProviderException('No share provider for share type ' . $shareType);
241
+        }
242
+
243
+        return $provider;
244
+    }
245
+
246
+    public function getAllProviders() {
247
+        $shares = [$this->defaultShareProvider(), $this->federatedShareProvider()];
248
+        $shareByMail = $this->getShareByMailProvider();
249
+        if ($shareByMail !== null) {
250
+            $shares[] = $shareByMail;
251
+        }
252
+        $shareByCircle = $this->getShareByCircleProvider();
253
+        if ($shareByCircle !== null) {
254
+            $shares[] = $shareByCircle;
255
+        }
256
+
257
+        return $shares;
258
+    }
259 259
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/AppInfo/Application.php 1 patch
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -33,91 +33,91 @@
 block discarded – undo
33 33
 
34 34
 class Application extends App {
35 35
 
36
-	/** @var FederatedShareProvider */
37
-	protected $federatedShareProvider;
36
+    /** @var FederatedShareProvider */
37
+    protected $federatedShareProvider;
38 38
 
39
-	public function __construct() {
40
-		parent::__construct('federatedfilesharing');
39
+    public function __construct() {
40
+        parent::__construct('federatedfilesharing');
41 41
 
42
-		$container = $this->getContainer();
43
-		$server = $container->getServer();
42
+        $container = $this->getContainer();
43
+        $server = $container->getServer();
44 44
 
45
-		$container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
46
-			$addressHandler = new AddressHandler(
47
-				$server->getURLGenerator(),
48
-				$server->getL10N('federatedfilesharing'),
49
-				$server->getCloudIdManager()
50
-			);
51
-			$notification = new Notifications(
52
-				$addressHandler,
53
-				$server->getHTTPClientService(),
54
-				$server->getOCSDiscoveryService(),
55
-				\OC::$server->getJobList()
56
-			);
57
-			return new RequestHandlerController(
58
-				$c->query('AppName'),
59
-				$server->getRequest(),
60
-				$this->getFederatedShareProvider(),
61
-				$server->getDatabaseConnection(),
62
-				$server->getShareManager(),
63
-				$notification,
64
-				$addressHandler,
65
-				$server->getUserManager(),
66
-				$server->getCloudIdManager()
67
-			);
68
-		});
69
-	}
45
+        $container->registerService('RequestHandlerController', function(SimpleContainer $c) use ($server) {
46
+            $addressHandler = new AddressHandler(
47
+                $server->getURLGenerator(),
48
+                $server->getL10N('federatedfilesharing'),
49
+                $server->getCloudIdManager()
50
+            );
51
+            $notification = new Notifications(
52
+                $addressHandler,
53
+                $server->getHTTPClientService(),
54
+                $server->getOCSDiscoveryService(),
55
+                \OC::$server->getJobList()
56
+            );
57
+            return new RequestHandlerController(
58
+                $c->query('AppName'),
59
+                $server->getRequest(),
60
+                $this->getFederatedShareProvider(),
61
+                $server->getDatabaseConnection(),
62
+                $server->getShareManager(),
63
+                $notification,
64
+                $addressHandler,
65
+                $server->getUserManager(),
66
+                $server->getCloudIdManager()
67
+            );
68
+        });
69
+    }
70 70
 
71
-	/**
72
-	 * register personal and admin settings page
73
-	 */
74
-	public function registerSettings() {
75
-		\OCP\App::registerPersonal('federatedfilesharing', 'settings-personal');
76
-	}
71
+    /**
72
+     * register personal and admin settings page
73
+     */
74
+    public function registerSettings() {
75
+        \OCP\App::registerPersonal('federatedfilesharing', 'settings-personal');
76
+    }
77 77
 
78
-	/**
79
-	 * get instance of federated share provider
80
-	 *
81
-	 * @return FederatedShareProvider
82
-	 */
83
-	public function getFederatedShareProvider() {
84
-		if ($this->federatedShareProvider === null) {
85
-			$this->initFederatedShareProvider();
86
-		}
87
-		return $this->federatedShareProvider;
88
-	}
78
+    /**
79
+     * get instance of federated share provider
80
+     *
81
+     * @return FederatedShareProvider
82
+     */
83
+    public function getFederatedShareProvider() {
84
+        if ($this->federatedShareProvider === null) {
85
+            $this->initFederatedShareProvider();
86
+        }
87
+        return $this->federatedShareProvider;
88
+    }
89 89
 
90
-	/**
91
-	 * initialize federated share provider
92
-	 */
93
-	protected function initFederatedShareProvider() {
94
-		$addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
95
-			\OC::$server->getURLGenerator(),
96
-			\OC::$server->getL10N('federatedfilesharing'),
97
-			\OC::$server->getCloudIdManager()
98
-		);
99
-		$notifications = new \OCA\FederatedFileSharing\Notifications(
100
-			$addressHandler,
101
-			\OC::$server->getHTTPClientService(),
102
-			\OC::$server->getOCSDiscoveryService(),
103
-			\OC::$server->getJobList()
104
-		);
105
-		$tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
106
-			\OC::$server->getSecureRandom()
107
-		);
90
+    /**
91
+     * initialize federated share provider
92
+     */
93
+    protected function initFederatedShareProvider() {
94
+        $addressHandler = new \OCA\FederatedFileSharing\AddressHandler(
95
+            \OC::$server->getURLGenerator(),
96
+            \OC::$server->getL10N('federatedfilesharing'),
97
+            \OC::$server->getCloudIdManager()
98
+        );
99
+        $notifications = new \OCA\FederatedFileSharing\Notifications(
100
+            $addressHandler,
101
+            \OC::$server->getHTTPClientService(),
102
+            \OC::$server->getOCSDiscoveryService(),
103
+            \OC::$server->getJobList()
104
+        );
105
+        $tokenHandler = new \OCA\FederatedFileSharing\TokenHandler(
106
+            \OC::$server->getSecureRandom()
107
+        );
108 108
 
109
-		$this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
110
-			\OC::$server->getDatabaseConnection(),
111
-			$addressHandler,
112
-			$notifications,
113
-			$tokenHandler,
114
-			\OC::$server->getL10N('federatedfilesharing'),
115
-			\OC::$server->getLogger(),
116
-			\OC::$server->getLazyRootFolder(),
117
-			\OC::$server->getConfig(),
118
-			\OC::$server->getUserManager(),
119
-			\OC::$server->getCloudIdManager()
120
-		);
121
-	}
109
+        $this->federatedShareProvider = new \OCA\FederatedFileSharing\FederatedShareProvider(
110
+            \OC::$server->getDatabaseConnection(),
111
+            $addressHandler,
112
+            $notifications,
113
+            $tokenHandler,
114
+            \OC::$server->getL10N('federatedfilesharing'),
115
+            \OC::$server->getLogger(),
116
+            \OC::$server->getLazyRootFolder(),
117
+            \OC::$server->getConfig(),
118
+            \OC::$server->getUserManager(),
119
+            \OC::$server->getCloudIdManager()
120
+        );
121
+    }
122 122
 
123 123
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/BackgroundJob/RetryJob.php 1 patch
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -42,103 +42,103 @@
 block discarded – undo
42 42
  */
43 43
 class RetryJob extends Job {
44 44
 
45
-	/** @var  bool */
46
-	private $retainJob = true;
47
-
48
-	/** @var Notifications */
49
-	private $notifications;
50
-
51
-	/** @var int max number of attempts to send the request */
52
-	private $maxTry = 20;
53
-
54
-	/** @var int how much time should be between two tries (10 minutes) */
55
-	private $interval = 600;
56
-
57
-	/**
58
-	 * UnShare constructor.
59
-	 *
60
-	 * @param Notifications $notifications
61
-	 */
62
-	public function __construct(Notifications $notifications = null) {
63
-		if ($notifications) {
64
-			$this->notifications = $notifications;
65
-		} else {
66
-			$addressHandler = new AddressHandler(
67
-				\OC::$server->getURLGenerator(),
68
-				\OC::$server->getL10N('federatedfilesharing'),
69
-				\OC::$server->getCloudIdManager()
70
-			);
71
-			$this->notifications = new Notifications(
72
-				$addressHandler,
73
-				\OC::$server->getHTTPClientService(),
74
-				\OC::$server->getOCSDiscoveryService(),
75
-				\OC::$server->getJobList()
76
-			);
77
-		}
78
-
79
-	}
80
-
81
-	/**
82
-	 * run the job, then remove it from the jobList
83
-	 *
84
-	 * @param JobList $jobList
85
-	 * @param ILogger $logger
86
-	 */
87
-	public function execute($jobList, ILogger $logger = null) {
88
-
89
-		if ($this->shouldRun($this->argument)) {
90
-			parent::execute($jobList, $logger);
91
-			$jobList->remove($this, $this->argument);
92
-			if ($this->retainJob) {
93
-				$this->reAddJob($jobList, $this->argument);
94
-			}
95
-		}
96
-	}
97
-
98
-	protected function run($argument) {
99
-		$remote = $argument['remote'];
100
-		$remoteId = $argument['remoteId'];
101
-		$token = $argument['token'];
102
-		$action = $argument['action'];
103
-		$data = json_decode($argument['data'], true);
104
-		$try = (int)$argument['try'] + 1;
105
-
106
-		$result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
107
-
108
-		if ($result === true || $try > $this->maxTry) {
109
-			$this->retainJob = false;
110
-		}
111
-	}
112
-
113
-	/**
114
-	 * re-add background job with new arguments
115
-	 *
116
-	 * @param IJobList $jobList
117
-	 * @param array $argument
118
-	 */
119
-	protected function reAddJob(IJobList $jobList, array $argument) {
120
-		$jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
121
-			[
122
-				'remote' => $argument['remote'],
123
-				'remoteId' => $argument['remoteId'],
124
-				'token' => $argument['token'],
125
-				'data' => $argument['data'],
126
-				'action' => $argument['action'],
127
-				'try' => (int)$argument['try'] + 1,
128
-				'lastRun' => time()
129
-			]
130
-		);
131
-	}
132
-
133
-	/**
134
-	 * test if it is time for the next run
135
-	 *
136
-	 * @param array $argument
137
-	 * @return bool
138
-	 */
139
-	protected function shouldRun(array $argument) {
140
-		$lastRun = (int)$argument['lastRun'];
141
-		return ((time() - $lastRun) > $this->interval);
142
-	}
45
+    /** @var  bool */
46
+    private $retainJob = true;
47
+
48
+    /** @var Notifications */
49
+    private $notifications;
50
+
51
+    /** @var int max number of attempts to send the request */
52
+    private $maxTry = 20;
53
+
54
+    /** @var int how much time should be between two tries (10 minutes) */
55
+    private $interval = 600;
56
+
57
+    /**
58
+     * UnShare constructor.
59
+     *
60
+     * @param Notifications $notifications
61
+     */
62
+    public function __construct(Notifications $notifications = null) {
63
+        if ($notifications) {
64
+            $this->notifications = $notifications;
65
+        } else {
66
+            $addressHandler = new AddressHandler(
67
+                \OC::$server->getURLGenerator(),
68
+                \OC::$server->getL10N('federatedfilesharing'),
69
+                \OC::$server->getCloudIdManager()
70
+            );
71
+            $this->notifications = new Notifications(
72
+                $addressHandler,
73
+                \OC::$server->getHTTPClientService(),
74
+                \OC::$server->getOCSDiscoveryService(),
75
+                \OC::$server->getJobList()
76
+            );
77
+        }
78
+
79
+    }
80
+
81
+    /**
82
+     * run the job, then remove it from the jobList
83
+     *
84
+     * @param JobList $jobList
85
+     * @param ILogger $logger
86
+     */
87
+    public function execute($jobList, ILogger $logger = null) {
88
+
89
+        if ($this->shouldRun($this->argument)) {
90
+            parent::execute($jobList, $logger);
91
+            $jobList->remove($this, $this->argument);
92
+            if ($this->retainJob) {
93
+                $this->reAddJob($jobList, $this->argument);
94
+            }
95
+        }
96
+    }
97
+
98
+    protected function run($argument) {
99
+        $remote = $argument['remote'];
100
+        $remoteId = $argument['remoteId'];
101
+        $token = $argument['token'];
102
+        $action = $argument['action'];
103
+        $data = json_decode($argument['data'], true);
104
+        $try = (int)$argument['try'] + 1;
105
+
106
+        $result = $this->notifications->sendUpdateToRemote($remote, $remoteId, $token, $action, $data, $try);
107
+
108
+        if ($result === true || $try > $this->maxTry) {
109
+            $this->retainJob = false;
110
+        }
111
+    }
112
+
113
+    /**
114
+     * re-add background job with new arguments
115
+     *
116
+     * @param IJobList $jobList
117
+     * @param array $argument
118
+     */
119
+    protected function reAddJob(IJobList $jobList, array $argument) {
120
+        $jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
121
+            [
122
+                'remote' => $argument['remote'],
123
+                'remoteId' => $argument['remoteId'],
124
+                'token' => $argument['token'],
125
+                'data' => $argument['data'],
126
+                'action' => $argument['action'],
127
+                'try' => (int)$argument['try'] + 1,
128
+                'lastRun' => time()
129
+            ]
130
+        );
131
+    }
132
+
133
+    /**
134
+     * test if it is time for the next run
135
+     *
136
+     * @param array $argument
137
+     * @return bool
138
+     */
139
+    protected function shouldRun(array $argument) {
140
+        $lastRun = (int)$argument['lastRun'];
141
+        return ((time() - $lastRun) > $this->interval);
142
+    }
143 143
 
144 144
 }
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Notifications.php 2 patches
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -33,280 +33,280 @@
 block discarded – undo
33 33
 use OCP\OCS\IDiscoveryService;
34 34
 
35 35
 class Notifications {
36
-	const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
-
38
-	/** @var AddressHandler */
39
-	private $addressHandler;
40
-
41
-	/** @var IClientService */
42
-	private $httpClientService;
43
-
44
-	/** @var IDiscoveryService */
45
-	private $discoveryService;
46
-
47
-	/** @var IJobList  */
48
-	private $jobList;
49
-
50
-	/**
51
-	 * @param AddressHandler $addressHandler
52
-	 * @param IClientService $httpClientService
53
-	 * @param IDiscoveryService $discoveryService
54
-	 * @param IJobList $jobList
55
-	 */
56
-	public function __construct(
57
-		AddressHandler $addressHandler,
58
-		IClientService $httpClientService,
59
-		IDiscoveryService $discoveryService,
60
-		IJobList $jobList
61
-	) {
62
-		$this->addressHandler = $addressHandler;
63
-		$this->httpClientService = $httpClientService;
64
-		$this->discoveryService = $discoveryService;
65
-		$this->jobList = $jobList;
66
-	}
67
-
68
-	/**
69
-	 * send server-to-server share to remote server
70
-	 *
71
-	 * @param string $token
72
-	 * @param string $shareWith
73
-	 * @param string $name
74
-	 * @param int $remote_id
75
-	 * @param string $owner
76
-	 * @param string $ownerFederatedId
77
-	 * @param string $sharedBy
78
-	 * @param string $sharedByFederatedId
79
-	 * @return bool
80
-	 * @throws \OC\HintException
81
-	 * @throws \OC\ServerNotAvailableException
82
-	 */
83
-	public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
84
-
85
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
86
-
87
-		if ($user && $remote) {
88
-			$local = $this->addressHandler->generateRemoteURL();
89
-
90
-			$fields = array(
91
-				'shareWith' => $user,
92
-				'token' => $token,
93
-				'name' => $name,
94
-				'remoteId' => $remote_id,
95
-				'owner' => $owner,
96
-				'ownerFederatedId' => $ownerFederatedId,
97
-				'sharedBy' => $sharedBy,
98
-				'sharedByFederatedId' => $sharedByFederatedId,
99
-				'remote' => $local,
100
-			);
101
-
102
-			$result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
103
-			$status = json_decode($result['result'], true);
104
-
105
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
106
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
107
-				return true;
108
-			}
109
-
110
-		}
111
-
112
-		return false;
113
-	}
114
-
115
-	/**
116
-	 * ask owner to re-share the file with the given user
117
-	 *
118
-	 * @param string $token
119
-	 * @param int $id remote Id
120
-	 * @param int $shareId internal share Id
121
-	 * @param string $remote remote address of the owner
122
-	 * @param string $shareWith
123
-	 * @param int $permission
124
-	 * @return bool
125
-	 * @throws \OC\HintException
126
-	 * @throws \OC\ServerNotAvailableException
127
-	 */
128
-	public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission) {
129
-
130
-		$fields = array(
131
-			'shareWith' => $shareWith,
132
-			'token' => $token,
133
-			'permission' => $permission,
134
-			'remoteId' => $shareId
135
-		);
136
-
137
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
138
-		$status = json_decode($result['result'], true);
139
-
140
-		$httpRequestSuccessful = $result['success'];
141
-		$ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
142
-		$validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
143
-		$validRemoteId = isset($status['ocs']['data']['remoteId']);
144
-
145
-		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
146
-			return [
147
-				$status['ocs']['data']['token'],
148
-				(int)$status['ocs']['data']['remoteId']
149
-			];
150
-		}
151
-
152
-		return false;
153
-	}
154
-
155
-	/**
156
-	 * send server-to-server unshare to remote server
157
-	 *
158
-	 * @param string $remote url
159
-	 * @param int $id share id
160
-	 * @param string $token
161
-	 * @return bool
162
-	 */
163
-	public function sendRemoteUnShare($remote, $id, $token) {
164
-		$this->sendUpdateToRemote($remote, $id, $token, 'unshare');
165
-	}
166
-
167
-	/**
168
-	 * send server-to-server unshare to remote server
169
-	 *
170
-	 * @param string $remote url
171
-	 * @param int $id share id
172
-	 * @param string $token
173
-	 * @return bool
174
-	 */
175
-	public function sendRevokeShare($remote, $id, $token) {
176
-		$this->sendUpdateToRemote($remote, $id, $token, 'revoke');
177
-	}
178
-
179
-	/**
180
-	 * send notification to remote server if the permissions was changed
181
-	 *
182
-	 * @param string $remote
183
-	 * @param int $remoteId
184
-	 * @param string $token
185
-	 * @param int $permissions
186
-	 * @return bool
187
-	 */
188
-	public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
189
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
190
-	}
191
-
192
-	/**
193
-	 * forward accept reShare to remote server
194
-	 *
195
-	 * @param string $remote
196
-	 * @param int $remoteId
197
-	 * @param string $token
198
-	 */
199
-	public function sendAcceptShare($remote, $remoteId, $token) {
200
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
201
-	}
202
-
203
-	/**
204
-	 * forward decline reShare to remote server
205
-	 *
206
-	 * @param string $remote
207
-	 * @param int $remoteId
208
-	 * @param string $token
209
-	 */
210
-	public function sendDeclineShare($remote, $remoteId, $token) {
211
-		$this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
212
-	}
213
-
214
-	/**
215
-	 * inform remote server whether server-to-server share was accepted/declined
216
-	 *
217
-	 * @param string $remote
218
-	 * @param string $token
219
-	 * @param int $remoteId Share id on the remote host
220
-	 * @param string $action possible actions: accept, decline, unshare, revoke, permissions
221
-	 * @param array $data
222
-	 * @param int $try
223
-	 * @return boolean
224
-	 */
225
-	public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
226
-
227
-		$fields = array('token' => $token);
228
-		foreach ($data as $key => $value) {
229
-			$fields[$key] = $value;
230
-		}
231
-
232
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields);
233
-		$status = json_decode($result['result'], true);
234
-
235
-		if ($result['success'] &&
236
-			($status['ocs']['meta']['statuscode'] === 100 ||
237
-				$status['ocs']['meta']['statuscode'] === 200
238
-			)
239
-		) {
240
-			return true;
241
-		} elseif ($try === 0) {
242
-			// only add new job on first try
243
-			$this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
244
-				[
245
-					'remote' => $remote,
246
-					'remoteId' => $remoteId,
247
-					'token' => $token,
248
-					'action' => $action,
249
-					'data' => json_encode($data),
250
-					'try' => $try,
251
-					'lastRun' => $this->getTimestamp()
252
-				]
253
-			);
254
-		}
255
-
256
-		return false;
257
-	}
258
-
259
-
260
-	/**
261
-	 * return current timestamp
262
-	 *
263
-	 * @return int
264
-	 */
265
-	protected function getTimestamp() {
266
-		return time();
267
-	}
268
-
269
-	/**
270
-	 * try http post with the given protocol, if no protocol is given we pick
271
-	 * the secure one (https)
272
-	 *
273
-	 * @param string $remoteDomain
274
-	 * @param string $urlSuffix
275
-	 * @param array $fields post parameters
276
-	 * @return array
277
-	 * @throws \Exception
278
-	 */
279
-	protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
280
-		$client = $this->httpClientService->newClient();
281
-
282
-		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
283
-			$remoteDomain = 'https://' . $remoteDomain;
284
-		}
285
-
286
-		$result = [
287
-			'success' => false,
288
-			'result' => '',
289
-		];
290
-
291
-		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
292
-		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
293
-		try {
294
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
295
-				'body' => $fields,
296
-				'timeout' => 10,
297
-				'connect_timeout' => 10,
298
-			]);
299
-			$result['result'] = $response->getBody();
300
-			$result['success'] = true;
301
-		} catch (\Exception $e) {
302
-			// if flat re-sharing is not supported by the remote server
303
-			// we re-throw the exception and fall back to the old behaviour.
304
-			// (flat re-shares has been introduced in Nextcloud 9.1)
305
-			if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
306
-				throw $e;
307
-			}
308
-		}
309
-
310
-		return $result;
311
-	}
36
+    const RESPONSE_FORMAT = 'json'; // default response format for ocs calls
37
+
38
+    /** @var AddressHandler */
39
+    private $addressHandler;
40
+
41
+    /** @var IClientService */
42
+    private $httpClientService;
43
+
44
+    /** @var IDiscoveryService */
45
+    private $discoveryService;
46
+
47
+    /** @var IJobList  */
48
+    private $jobList;
49
+
50
+    /**
51
+     * @param AddressHandler $addressHandler
52
+     * @param IClientService $httpClientService
53
+     * @param IDiscoveryService $discoveryService
54
+     * @param IJobList $jobList
55
+     */
56
+    public function __construct(
57
+        AddressHandler $addressHandler,
58
+        IClientService $httpClientService,
59
+        IDiscoveryService $discoveryService,
60
+        IJobList $jobList
61
+    ) {
62
+        $this->addressHandler = $addressHandler;
63
+        $this->httpClientService = $httpClientService;
64
+        $this->discoveryService = $discoveryService;
65
+        $this->jobList = $jobList;
66
+    }
67
+
68
+    /**
69
+     * send server-to-server share to remote server
70
+     *
71
+     * @param string $token
72
+     * @param string $shareWith
73
+     * @param string $name
74
+     * @param int $remote_id
75
+     * @param string $owner
76
+     * @param string $ownerFederatedId
77
+     * @param string $sharedBy
78
+     * @param string $sharedByFederatedId
79
+     * @return bool
80
+     * @throws \OC\HintException
81
+     * @throws \OC\ServerNotAvailableException
82
+     */
83
+    public function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner, $ownerFederatedId, $sharedBy, $sharedByFederatedId) {
84
+
85
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
86
+
87
+        if ($user && $remote) {
88
+            $local = $this->addressHandler->generateRemoteURL();
89
+
90
+            $fields = array(
91
+                'shareWith' => $user,
92
+                'token' => $token,
93
+                'name' => $name,
94
+                'remoteId' => $remote_id,
95
+                'owner' => $owner,
96
+                'ownerFederatedId' => $ownerFederatedId,
97
+                'sharedBy' => $sharedBy,
98
+                'sharedByFederatedId' => $sharedByFederatedId,
99
+                'remote' => $local,
100
+            );
101
+
102
+            $result = $this->tryHttpPostToShareEndpoint($remote, '', $fields);
103
+            $status = json_decode($result['result'], true);
104
+
105
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
106
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
107
+                return true;
108
+            }
109
+
110
+        }
111
+
112
+        return false;
113
+    }
114
+
115
+    /**
116
+     * ask owner to re-share the file with the given user
117
+     *
118
+     * @param string $token
119
+     * @param int $id remote Id
120
+     * @param int $shareId internal share Id
121
+     * @param string $remote remote address of the owner
122
+     * @param string $shareWith
123
+     * @param int $permission
124
+     * @return bool
125
+     * @throws \OC\HintException
126
+     * @throws \OC\ServerNotAvailableException
127
+     */
128
+    public function requestReShare($token, $id, $shareId, $remote, $shareWith, $permission) {
129
+
130
+        $fields = array(
131
+            'shareWith' => $shareWith,
132
+            'token' => $token,
133
+            'permission' => $permission,
134
+            'remoteId' => $shareId
135
+        );
136
+
137
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
138
+        $status = json_decode($result['result'], true);
139
+
140
+        $httpRequestSuccessful = $result['success'];
141
+        $ocsCallSuccessful = $status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200;
142
+        $validToken = isset($status['ocs']['data']['token']) && is_string($status['ocs']['data']['token']);
143
+        $validRemoteId = isset($status['ocs']['data']['remoteId']);
144
+
145
+        if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
146
+            return [
147
+                $status['ocs']['data']['token'],
148
+                (int)$status['ocs']['data']['remoteId']
149
+            ];
150
+        }
151
+
152
+        return false;
153
+    }
154
+
155
+    /**
156
+     * send server-to-server unshare to remote server
157
+     *
158
+     * @param string $remote url
159
+     * @param int $id share id
160
+     * @param string $token
161
+     * @return bool
162
+     */
163
+    public function sendRemoteUnShare($remote, $id, $token) {
164
+        $this->sendUpdateToRemote($remote, $id, $token, 'unshare');
165
+    }
166
+
167
+    /**
168
+     * send server-to-server unshare to remote server
169
+     *
170
+     * @param string $remote url
171
+     * @param int $id share id
172
+     * @param string $token
173
+     * @return bool
174
+     */
175
+    public function sendRevokeShare($remote, $id, $token) {
176
+        $this->sendUpdateToRemote($remote, $id, $token, 'revoke');
177
+    }
178
+
179
+    /**
180
+     * send notification to remote server if the permissions was changed
181
+     *
182
+     * @param string $remote
183
+     * @param int $remoteId
184
+     * @param string $token
185
+     * @param int $permissions
186
+     * @return bool
187
+     */
188
+    public function sendPermissionChange($remote, $remoteId, $token, $permissions) {
189
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'permissions', ['permissions' => $permissions]);
190
+    }
191
+
192
+    /**
193
+     * forward accept reShare to remote server
194
+     *
195
+     * @param string $remote
196
+     * @param int $remoteId
197
+     * @param string $token
198
+     */
199
+    public function sendAcceptShare($remote, $remoteId, $token) {
200
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'accept');
201
+    }
202
+
203
+    /**
204
+     * forward decline reShare to remote server
205
+     *
206
+     * @param string $remote
207
+     * @param int $remoteId
208
+     * @param string $token
209
+     */
210
+    public function sendDeclineShare($remote, $remoteId, $token) {
211
+        $this->sendUpdateToRemote($remote, $remoteId, $token, 'decline');
212
+    }
213
+
214
+    /**
215
+     * inform remote server whether server-to-server share was accepted/declined
216
+     *
217
+     * @param string $remote
218
+     * @param string $token
219
+     * @param int $remoteId Share id on the remote host
220
+     * @param string $action possible actions: accept, decline, unshare, revoke, permissions
221
+     * @param array $data
222
+     * @param int $try
223
+     * @return boolean
224
+     */
225
+    public function sendUpdateToRemote($remote, $remoteId, $token, $action, $data = [], $try = 0) {
226
+
227
+        $fields = array('token' => $token);
228
+        foreach ($data as $key => $value) {
229
+            $fields[$key] = $value;
230
+        }
231
+
232
+        $result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields);
233
+        $status = json_decode($result['result'], true);
234
+
235
+        if ($result['success'] &&
236
+            ($status['ocs']['meta']['statuscode'] === 100 ||
237
+                $status['ocs']['meta']['statuscode'] === 200
238
+            )
239
+        ) {
240
+            return true;
241
+        } elseif ($try === 0) {
242
+            // only add new job on first try
243
+            $this->jobList->add('OCA\FederatedFileSharing\BackgroundJob\RetryJob',
244
+                [
245
+                    'remote' => $remote,
246
+                    'remoteId' => $remoteId,
247
+                    'token' => $token,
248
+                    'action' => $action,
249
+                    'data' => json_encode($data),
250
+                    'try' => $try,
251
+                    'lastRun' => $this->getTimestamp()
252
+                ]
253
+            );
254
+        }
255
+
256
+        return false;
257
+    }
258
+
259
+
260
+    /**
261
+     * return current timestamp
262
+     *
263
+     * @return int
264
+     */
265
+    protected function getTimestamp() {
266
+        return time();
267
+    }
268
+
269
+    /**
270
+     * try http post with the given protocol, if no protocol is given we pick
271
+     * the secure one (https)
272
+     *
273
+     * @param string $remoteDomain
274
+     * @param string $urlSuffix
275
+     * @param array $fields post parameters
276
+     * @return array
277
+     * @throws \Exception
278
+     */
279
+    protected function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
280
+        $client = $this->httpClientService->newClient();
281
+
282
+        if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
283
+            $remoteDomain = 'https://' . $remoteDomain;
284
+        }
285
+
286
+        $result = [
287
+            'success' => false,
288
+            'result' => '',
289
+        ];
290
+
291
+        $federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
292
+        $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
293
+        try {
294
+            $response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
295
+                'body' => $fields,
296
+                'timeout' => 10,
297
+                'connect_timeout' => 10,
298
+            ]);
299
+            $result['result'] = $response->getBody();
300
+            $result['success'] = true;
301
+        } catch (\Exception $e) {
302
+            // if flat re-sharing is not supported by the remote server
303
+            // we re-throw the exception and fall back to the old behaviour.
304
+            // (flat re-shares has been introduced in Nextcloud 9.1)
305
+            if ($e->getCode() === Http::STATUS_INTERNAL_SERVER_ERROR) {
306
+                throw $e;
307
+            }
308
+        }
309
+
310
+        return $result;
311
+    }
312 312
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 			'remoteId' => $shareId
135 135
 		);
136 136
 
137
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $id . '/reshare', $fields);
137
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$id.'/reshare', $fields);
138 138
 		$status = json_decode($result['result'], true);
139 139
 
140 140
 		$httpRequestSuccessful = $result['success'];
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 		if ($httpRequestSuccessful && $ocsCallSuccessful && $validToken && $validRemoteId) {
146 146
 			return [
147 147
 				$status['ocs']['data']['token'],
148
-				(int)$status['ocs']['data']['remoteId']
148
+				(int) $status['ocs']['data']['remoteId']
149 149
 			];
150 150
 		}
151 151
 
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 			$fields[$key] = $value;
230 230
 		}
231 231
 
232
-		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/' . $remoteId . '/' . $action, $fields);
232
+		$result = $this->tryHttpPostToShareEndpoint(rtrim($remote, '/'), '/'.$remoteId.'/'.$action, $fields);
233 233
 		$status = json_decode($result['result'], true);
234 234
 
235 235
 		if ($result['success'] &&
@@ -280,7 +280,7 @@  discard block
 block discarded – undo
280 280
 		$client = $this->httpClientService->newClient();
281 281
 
282 282
 		if ($this->addressHandler->urlContainProtocol($remoteDomain) === false) {
283
-			$remoteDomain = 'https://' . $remoteDomain;
283
+			$remoteDomain = 'https://'.$remoteDomain;
284 284
 		}
285 285
 
286 286
 		$result = [
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
 		$federationEndpoints = $this->discoveryService->discover($remoteDomain, 'FEDERATED_SHARING');
292 292
 		$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
293 293
 		try {
294
-			$response = $client->post($remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, [
294
+			$response = $client->post($remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT, [
295 295
 				'body' => $fields,
296 296
 				'timeout' => 10,
297 297
 				'connect_timeout' => 10,
Please login to merge, or discard this patch.
apps/files_sharing/lib/Hooks.php 1 patch
Indentation   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -31,31 +31,31 @@
 block discarded – undo
31 31
 
32 32
 class Hooks {
33 33
 
34
-	public static function deleteUser($params) {
35
-		$manager = new External\Manager(
36
-			\OC::$server->getDatabaseConnection(),
37
-			\OC\Files\Filesystem::getMountManager(),
38
-			\OC\Files\Filesystem::getLoader(),
39
-			\OC::$server->getHTTPClientService(),
40
-			\OC::$server->getNotificationManager(),
41
-			\OC::$server->getOCSDiscoveryService(),
42
-			$params['uid']);
34
+    public static function deleteUser($params) {
35
+        $manager = new External\Manager(
36
+            \OC::$server->getDatabaseConnection(),
37
+            \OC\Files\Filesystem::getMountManager(),
38
+            \OC\Files\Filesystem::getLoader(),
39
+            \OC::$server->getHTTPClientService(),
40
+            \OC::$server->getNotificationManager(),
41
+            \OC::$server->getOCSDiscoveryService(),
42
+            $params['uid']);
43 43
 
44
-		$manager->removeUserShares($params['uid']);
45
-	}
44
+        $manager->removeUserShares($params['uid']);
45
+    }
46 46
 
47
-	public static function unshareChildren($params) {
48
-		$path = Filesystem::getView()->getAbsolutePath($params['path']);
49
-		$view = new \OC\Files\View('/');
47
+    public static function unshareChildren($params) {
48
+        $path = Filesystem::getView()->getAbsolutePath($params['path']);
49
+        $view = new \OC\Files\View('/');
50 50
 
51
-		// find share mount points within $path and unmount them
52
-		$mountManager = \OC\Files\Filesystem::getMountManager();
53
-		$mountedShares = $mountManager->findIn($path);
54
-		foreach ($mountedShares as $mount) {
55
-			if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
56
-				$mountPoint = $mount->getMountPoint();
57
-				$view->unlink($mountPoint);
58
-			}
59
-		}
60
-	}
51
+        // find share mount points within $path and unmount them
52
+        $mountManager = \OC\Files\Filesystem::getMountManager();
53
+        $mountedShares = $mountManager->findIn($path);
54
+        foreach ($mountedShares as $mount) {
55
+            if ($mount->getStorage()->instanceOfStorage('OCA\Files_Sharing\ISharedStorage')) {
56
+                $mountPoint = $mount->getMountPoint();
57
+                $view->unlink($mountPoint);
58
+            }
59
+        }
60
+    }
61 61
 }
Please login to merge, or discard this patch.
lib/public/IServerContainer.php 1 patch
Indentation   +481 added lines, -481 removed lines patch added patch discarded remove patch
@@ -56,485 +56,485 @@
 block discarded – undo
56 56
  */
57 57
 interface IServerContainer extends IContainer {
58 58
 
59
-	/**
60
-	 * The contacts manager will act as a broker between consumers for contacts information and
61
-	 * providers which actual deliver the contact information.
62
-	 *
63
-	 * @return \OCP\Contacts\IManager
64
-	 * @since 6.0.0
65
-	 */
66
-	public function getContactsManager();
67
-
68
-	/**
69
-	 * The current request object holding all information about the request currently being processed
70
-	 * is returned from this method.
71
-	 * In case the current execution was not initiated by a web request null is returned
72
-	 *
73
-	 * @return \OCP\IRequest
74
-	 * @since 6.0.0
75
-	 */
76
-	public function getRequest();
77
-
78
-	/**
79
-	 * Returns the preview manager which can create preview images for a given file
80
-	 *
81
-	 * @return \OCP\IPreview
82
-	 * @since 6.0.0
83
-	 */
84
-	public function getPreviewManager();
85
-
86
-	/**
87
-	 * Returns the tag manager which can get and set tags for different object types
88
-	 *
89
-	 * @see \OCP\ITagManager::load()
90
-	 * @return \OCP\ITagManager
91
-	 * @since 6.0.0
92
-	 */
93
-	public function getTagManager();
94
-
95
-	/**
96
-	 * Returns the root folder of ownCloud's data directory
97
-	 *
98
-	 * @return \OCP\Files\IRootFolder
99
-	 * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder
100
-	 */
101
-	public function getRootFolder();
102
-
103
-	/**
104
-	 * Returns a view to ownCloud's files folder
105
-	 *
106
-	 * @param string $userId user ID
107
-	 * @return \OCP\Files\Folder
108
-	 * @since 6.0.0 - parameter $userId was added in 8.0.0
109
-	 * @see getUserFolder in \OCP\Files\IRootFolder
110
-	 */
111
-	public function getUserFolder($userId = null);
112
-
113
-	/**
114
-	 * Returns an app-specific view in ownClouds data directory
115
-	 *
116
-	 * @return \OCP\Files\Folder
117
-	 * @since 6.0.0
118
-	 * @deprecated since 9.2.0 use IAppData
119
-	 */
120
-	public function getAppFolder();
121
-
122
-	/**
123
-	 * Returns a user manager
124
-	 *
125
-	 * @return \OCP\IUserManager
126
-	 * @since 8.0.0
127
-	 */
128
-	public function getUserManager();
129
-
130
-	/**
131
-	 * Returns a group manager
132
-	 *
133
-	 * @return \OCP\IGroupManager
134
-	 * @since 8.0.0
135
-	 */
136
-	public function getGroupManager();
137
-
138
-	/**
139
-	 * Returns the user session
140
-	 *
141
-	 * @return \OCP\IUserSession
142
-	 * @since 6.0.0
143
-	 */
144
-	public function getUserSession();
145
-
146
-	/**
147
-	 * Returns the navigation manager
148
-	 *
149
-	 * @return \OCP\INavigationManager
150
-	 * @since 6.0.0
151
-	 */
152
-	public function getNavigationManager();
153
-
154
-	/**
155
-	 * Returns the config manager
156
-	 *
157
-	 * @return \OCP\IConfig
158
-	 * @since 6.0.0
159
-	 */
160
-	public function getConfig();
161
-
162
-	/**
163
-	 * Returns a Crypto instance
164
-	 *
165
-	 * @return \OCP\Security\ICrypto
166
-	 * @since 8.0.0
167
-	 */
168
-	public function getCrypto();
169
-
170
-	/**
171
-	 * Returns a Hasher instance
172
-	 *
173
-	 * @return \OCP\Security\IHasher
174
-	 * @since 8.0.0
175
-	 */
176
-	public function getHasher();
177
-
178
-	/**
179
-	 * Returns a SecureRandom instance
180
-	 *
181
-	 * @return \OCP\Security\ISecureRandom
182
-	 * @since 8.1.0
183
-	 */
184
-	public function getSecureRandom();
185
-
186
-	/**
187
-	 * Returns a CredentialsManager instance
188
-	 *
189
-	 * @return \OCP\Security\ICredentialsManager
190
-	 * @since 9.0.0
191
-	 */
192
-	public function getCredentialsManager();
193
-
194
-	/**
195
-	 * Returns the app config manager
196
-	 *
197
-	 * @return \OCP\IAppConfig
198
-	 * @since 7.0.0
199
-	 */
200
-	public function getAppConfig();
201
-
202
-	/**
203
-	 * @return \OCP\L10N\IFactory
204
-	 * @since 8.2.0
205
-	 */
206
-	public function getL10NFactory();
207
-
208
-	/**
209
-	 * get an L10N instance
210
-	 * @param string $app appid
211
-	 * @param string $lang
212
-	 * @return \OCP\IL10N
213
-	 * @since 6.0.0 - parameter $lang was added in 8.0.0
214
-	 */
215
-	public function getL10N($app, $lang = null);
216
-
217
-	/**
218
-	 * @return \OC\Encryption\Manager
219
-	 * @since 8.1.0
220
-	 */
221
-	public function getEncryptionManager();
222
-
223
-	/**
224
-	 * @return \OC\Encryption\File
225
-	 * @since 8.1.0
226
-	 */
227
-	public function getEncryptionFilesHelper();
228
-
229
-	/**
230
-	 * @return \OCP\Encryption\Keys\IStorage
231
-	 * @since 8.1.0
232
-	 */
233
-	public function getEncryptionKeyStorage();
234
-
235
-	/**
236
-	 * Returns the URL generator
237
-	 *
238
-	 * @return \OCP\IURLGenerator
239
-	 * @since 6.0.0
240
-	 */
241
-	public function getURLGenerator();
242
-
243
-	/**
244
-	 * Returns the Helper
245
-	 *
246
-	 * @return \OCP\IHelper
247
-	 * @since 6.0.0
248
-	 */
249
-	public function getHelper();
250
-
251
-	/**
252
-	 * Returns an ICache instance
253
-	 *
254
-	 * @return \OCP\ICache
255
-	 * @since 6.0.0
256
-	 */
257
-	public function getCache();
258
-
259
-	/**
260
-	 * Returns an \OCP\CacheFactory instance
261
-	 *
262
-	 * @return \OCP\ICacheFactory
263
-	 * @since 7.0.0
264
-	 */
265
-	public function getMemCacheFactory();
266
-
267
-	/**
268
-	 * Returns the current session
269
-	 *
270
-	 * @return \OCP\ISession
271
-	 * @since 6.0.0
272
-	 */
273
-	public function getSession();
274
-
275
-	/**
276
-	 * Returns the activity manager
277
-	 *
278
-	 * @return \OCP\Activity\IManager
279
-	 * @since 6.0.0
280
-	 */
281
-	public function getActivityManager();
282
-
283
-	/**
284
-	 * Returns the current session
285
-	 *
286
-	 * @return \OCP\IDBConnection
287
-	 * @since 6.0.0
288
-	 */
289
-	public function getDatabaseConnection();
290
-
291
-	/**
292
-	 * Returns an avatar manager, used for avatar functionality
293
-	 *
294
-	 * @return \OCP\IAvatarManager
295
-	 * @since 6.0.0
296
-	 */
297
-	public function getAvatarManager();
298
-
299
-	/**
300
-	 * Returns an job list for controlling background jobs
301
-	 *
302
-	 * @return \OCP\BackgroundJob\IJobList
303
-	 * @since 7.0.0
304
-	 */
305
-	public function getJobList();
306
-
307
-	/**
308
-	 * Returns a logger instance
309
-	 *
310
-	 * @return \OCP\ILogger
311
-	 * @since 8.0.0
312
-	 */
313
-	public function getLogger();
314
-
315
-	/**
316
-	 * Returns a router for generating and matching urls
317
-	 *
318
-	 * @return \OCP\Route\IRouter
319
-	 * @since 7.0.0
320
-	 */
321
-	public function getRouter();
322
-
323
-	/**
324
-	 * Returns a search instance
325
-	 *
326
-	 * @return \OCP\ISearch
327
-	 * @since 7.0.0
328
-	 */
329
-	public function getSearch();
330
-
331
-	/**
332
-	 * Get the certificate manager for the user
333
-	 *
334
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
335
-	 * @return \OCP\ICertificateManager | null if $userId is null and no user is logged in
336
-	 * @since 8.0.0
337
-	 */
338
-	public function getCertificateManager($userId = null);
339
-
340
-	/**
341
-	 * Create a new event source
342
-	 *
343
-	 * @return \OCP\IEventSource
344
-	 * @since 8.0.0
345
-	 */
346
-	public function createEventSource();
347
-
348
-	/**
349
-	 * Returns an instance of the HTTP helper class
350
-	 * @return \OC\HTTPHelper
351
-	 * @deprecated 8.1.0 Use \OCP\Http\Client\IClientService
352
-	 * @since 8.0.0
353
-	 */
354
-	public function getHTTPHelper();
355
-
356
-	/**
357
-	 * Returns an instance of the HTTP client service
358
-	 *
359
-	 * @return \OCP\Http\Client\IClientService
360
-	 * @since 8.1.0
361
-	 */
362
-	public function getHTTPClientService();
363
-
364
-	/**
365
-	 * Get the active event logger
366
-	 *
367
-	 * @return \OCP\Diagnostics\IEventLogger
368
-	 * @since 8.0.0
369
-	 */
370
-	public function getEventLogger();
371
-
372
-	/**
373
-	 * Get the active query logger
374
-	 *
375
-	 * The returned logger only logs data when debug mode is enabled
376
-	 *
377
-	 * @return \OCP\Diagnostics\IQueryLogger
378
-	 * @since 8.0.0
379
-	 */
380
-	public function getQueryLogger();
381
-
382
-	/**
383
-	 * Get the manager for temporary files and folders
384
-	 *
385
-	 * @return \OCP\ITempManager
386
-	 * @since 8.0.0
387
-	 */
388
-	public function getTempManager();
389
-
390
-	/**
391
-	 * Get the app manager
392
-	 *
393
-	 * @return \OCP\App\IAppManager
394
-	 * @since 8.0.0
395
-	 */
396
-	public function getAppManager();
397
-
398
-	/**
399
-	 * Get the webroot
400
-	 *
401
-	 * @return string
402
-	 * @since 8.0.0
403
-	 */
404
-	public function getWebRoot();
405
-
406
-	/**
407
-	 * @return \OCP\Files\Config\IMountProviderCollection
408
-	 * @since 8.0.0
409
-	 */
410
-	public function getMountProviderCollection();
411
-
412
-	/**
413
-	 * Get the IniWrapper
414
-	 *
415
-	 * @return \bantu\IniGetWrapper\IniGetWrapper
416
-	 * @since 8.0.0
417
-	 */
418
-	public function getIniWrapper();
419
-	/**
420
-	 * @return \OCP\Command\IBus
421
-	 * @since 8.1.0
422
-	 */
423
-	public function getCommandBus();
424
-
425
-	/**
426
-	 * Creates a new mailer
427
-	 *
428
-	 * @return \OCP\Mail\IMailer
429
-	 * @since 8.1.0
430
-	 */
431
-	public function getMailer();
432
-
433
-	/**
434
-	 * Get the locking provider
435
-	 *
436
-	 * @return \OCP\Lock\ILockingProvider
437
-	 * @since 8.1.0
438
-	 */
439
-	public function getLockingProvider();
440
-
441
-	/**
442
-	 * @return \OCP\Files\Mount\IMountManager
443
-	 * @since 8.2.0
444
-	 */
445
-	public function getMountManager();
446
-
447
-	/**
448
-	 * Get the MimeTypeDetector
449
-	 *
450
-	 * @return \OCP\Files\IMimeTypeDetector
451
-	 * @since 8.2.0
452
-	 */
453
-	public function getMimeTypeDetector();
454
-
455
-	/**
456
-	 * Get the MimeTypeLoader
457
-	 *
458
-	 * @return \OCP\Files\IMimeTypeLoader
459
-	 * @since 8.2.0
460
-	 */
461
-	public function getMimeTypeLoader();
462
-
463
-	/**
464
-	 * Get the EventDispatcher
465
-	 *
466
-	 * @return EventDispatcherInterface
467
-	 * @since 8.2.0
468
-	 */
469
-	public function getEventDispatcher();
470
-
471
-	/**
472
-	 * Get the Notification Manager
473
-	 *
474
-	 * @return \OCP\Notification\IManager
475
-	 * @since 9.0.0
476
-	 */
477
-	public function getNotificationManager();
478
-
479
-	/**
480
-	 * @return \OCP\Comments\ICommentsManager
481
-	 * @since 9.0.0
482
-	 */
483
-	public function getCommentsManager();
484
-
485
-	/**
486
-	 * Returns the system-tag manager
487
-	 *
488
-	 * @return \OCP\SystemTag\ISystemTagManager
489
-	 *
490
-	 * @since 9.0.0
491
-	 */
492
-	public function getSystemTagManager();
493
-
494
-	/**
495
-	 * Returns the system-tag object mapper
496
-	 *
497
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
498
-	 *
499
-	 * @since 9.0.0
500
-	 */
501
-	public function getSystemTagObjectMapper();
502
-
503
-	/**
504
-	 * Returns the share manager
505
-	 *
506
-	 * @return \OCP\Share\IManager
507
-	 * @since 9.0.0
508
-	 */
509
-	public function getShareManager();
510
-
511
-	/**
512
-	 * @return IContentSecurityPolicyManager
513
-	 * @since 9.0.0
514
-	 */
515
-	public function getContentSecurityPolicyManager();
516
-
517
-	/**
518
-	 * @return \OCP\IDateTimeZone
519
-	 * @since 8.0.0
520
-	 */
521
-	public function getDateTimeZone();
522
-
523
-	/**
524
-	 * @return \OCP\IDateTimeFormatter
525
-	 * @since 8.0.0
526
-	 */
527
-	public function getDateTimeFormatter();
528
-
529
-	/**
530
-	 * @return \OCP\Federation\ICloudIdManager
531
-	 * @since 12.0.0
532
-	 */
533
-	public function getCloudIdManager();
534
-
535
-	/**
536
-	 * @return \OC\OCS\DiscoveryService
537
-	 * @since 12.0.0
538
-	 */
539
-	public function getOCSDiscoveryService();
59
+    /**
60
+     * The contacts manager will act as a broker between consumers for contacts information and
61
+     * providers which actual deliver the contact information.
62
+     *
63
+     * @return \OCP\Contacts\IManager
64
+     * @since 6.0.0
65
+     */
66
+    public function getContactsManager();
67
+
68
+    /**
69
+     * The current request object holding all information about the request currently being processed
70
+     * is returned from this method.
71
+     * In case the current execution was not initiated by a web request null is returned
72
+     *
73
+     * @return \OCP\IRequest
74
+     * @since 6.0.0
75
+     */
76
+    public function getRequest();
77
+
78
+    /**
79
+     * Returns the preview manager which can create preview images for a given file
80
+     *
81
+     * @return \OCP\IPreview
82
+     * @since 6.0.0
83
+     */
84
+    public function getPreviewManager();
85
+
86
+    /**
87
+     * Returns the tag manager which can get and set tags for different object types
88
+     *
89
+     * @see \OCP\ITagManager::load()
90
+     * @return \OCP\ITagManager
91
+     * @since 6.0.0
92
+     */
93
+    public function getTagManager();
94
+
95
+    /**
96
+     * Returns the root folder of ownCloud's data directory
97
+     *
98
+     * @return \OCP\Files\IRootFolder
99
+     * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder
100
+     */
101
+    public function getRootFolder();
102
+
103
+    /**
104
+     * Returns a view to ownCloud's files folder
105
+     *
106
+     * @param string $userId user ID
107
+     * @return \OCP\Files\Folder
108
+     * @since 6.0.0 - parameter $userId was added in 8.0.0
109
+     * @see getUserFolder in \OCP\Files\IRootFolder
110
+     */
111
+    public function getUserFolder($userId = null);
112
+
113
+    /**
114
+     * Returns an app-specific view in ownClouds data directory
115
+     *
116
+     * @return \OCP\Files\Folder
117
+     * @since 6.0.0
118
+     * @deprecated since 9.2.0 use IAppData
119
+     */
120
+    public function getAppFolder();
121
+
122
+    /**
123
+     * Returns a user manager
124
+     *
125
+     * @return \OCP\IUserManager
126
+     * @since 8.0.0
127
+     */
128
+    public function getUserManager();
129
+
130
+    /**
131
+     * Returns a group manager
132
+     *
133
+     * @return \OCP\IGroupManager
134
+     * @since 8.0.0
135
+     */
136
+    public function getGroupManager();
137
+
138
+    /**
139
+     * Returns the user session
140
+     *
141
+     * @return \OCP\IUserSession
142
+     * @since 6.0.0
143
+     */
144
+    public function getUserSession();
145
+
146
+    /**
147
+     * Returns the navigation manager
148
+     *
149
+     * @return \OCP\INavigationManager
150
+     * @since 6.0.0
151
+     */
152
+    public function getNavigationManager();
153
+
154
+    /**
155
+     * Returns the config manager
156
+     *
157
+     * @return \OCP\IConfig
158
+     * @since 6.0.0
159
+     */
160
+    public function getConfig();
161
+
162
+    /**
163
+     * Returns a Crypto instance
164
+     *
165
+     * @return \OCP\Security\ICrypto
166
+     * @since 8.0.0
167
+     */
168
+    public function getCrypto();
169
+
170
+    /**
171
+     * Returns a Hasher instance
172
+     *
173
+     * @return \OCP\Security\IHasher
174
+     * @since 8.0.0
175
+     */
176
+    public function getHasher();
177
+
178
+    /**
179
+     * Returns a SecureRandom instance
180
+     *
181
+     * @return \OCP\Security\ISecureRandom
182
+     * @since 8.1.0
183
+     */
184
+    public function getSecureRandom();
185
+
186
+    /**
187
+     * Returns a CredentialsManager instance
188
+     *
189
+     * @return \OCP\Security\ICredentialsManager
190
+     * @since 9.0.0
191
+     */
192
+    public function getCredentialsManager();
193
+
194
+    /**
195
+     * Returns the app config manager
196
+     *
197
+     * @return \OCP\IAppConfig
198
+     * @since 7.0.0
199
+     */
200
+    public function getAppConfig();
201
+
202
+    /**
203
+     * @return \OCP\L10N\IFactory
204
+     * @since 8.2.0
205
+     */
206
+    public function getL10NFactory();
207
+
208
+    /**
209
+     * get an L10N instance
210
+     * @param string $app appid
211
+     * @param string $lang
212
+     * @return \OCP\IL10N
213
+     * @since 6.0.0 - parameter $lang was added in 8.0.0
214
+     */
215
+    public function getL10N($app, $lang = null);
216
+
217
+    /**
218
+     * @return \OC\Encryption\Manager
219
+     * @since 8.1.0
220
+     */
221
+    public function getEncryptionManager();
222
+
223
+    /**
224
+     * @return \OC\Encryption\File
225
+     * @since 8.1.0
226
+     */
227
+    public function getEncryptionFilesHelper();
228
+
229
+    /**
230
+     * @return \OCP\Encryption\Keys\IStorage
231
+     * @since 8.1.0
232
+     */
233
+    public function getEncryptionKeyStorage();
234
+
235
+    /**
236
+     * Returns the URL generator
237
+     *
238
+     * @return \OCP\IURLGenerator
239
+     * @since 6.0.0
240
+     */
241
+    public function getURLGenerator();
242
+
243
+    /**
244
+     * Returns the Helper
245
+     *
246
+     * @return \OCP\IHelper
247
+     * @since 6.0.0
248
+     */
249
+    public function getHelper();
250
+
251
+    /**
252
+     * Returns an ICache instance
253
+     *
254
+     * @return \OCP\ICache
255
+     * @since 6.0.0
256
+     */
257
+    public function getCache();
258
+
259
+    /**
260
+     * Returns an \OCP\CacheFactory instance
261
+     *
262
+     * @return \OCP\ICacheFactory
263
+     * @since 7.0.0
264
+     */
265
+    public function getMemCacheFactory();
266
+
267
+    /**
268
+     * Returns the current session
269
+     *
270
+     * @return \OCP\ISession
271
+     * @since 6.0.0
272
+     */
273
+    public function getSession();
274
+
275
+    /**
276
+     * Returns the activity manager
277
+     *
278
+     * @return \OCP\Activity\IManager
279
+     * @since 6.0.0
280
+     */
281
+    public function getActivityManager();
282
+
283
+    /**
284
+     * Returns the current session
285
+     *
286
+     * @return \OCP\IDBConnection
287
+     * @since 6.0.0
288
+     */
289
+    public function getDatabaseConnection();
290
+
291
+    /**
292
+     * Returns an avatar manager, used for avatar functionality
293
+     *
294
+     * @return \OCP\IAvatarManager
295
+     * @since 6.0.0
296
+     */
297
+    public function getAvatarManager();
298
+
299
+    /**
300
+     * Returns an job list for controlling background jobs
301
+     *
302
+     * @return \OCP\BackgroundJob\IJobList
303
+     * @since 7.0.0
304
+     */
305
+    public function getJobList();
306
+
307
+    /**
308
+     * Returns a logger instance
309
+     *
310
+     * @return \OCP\ILogger
311
+     * @since 8.0.0
312
+     */
313
+    public function getLogger();
314
+
315
+    /**
316
+     * Returns a router for generating and matching urls
317
+     *
318
+     * @return \OCP\Route\IRouter
319
+     * @since 7.0.0
320
+     */
321
+    public function getRouter();
322
+
323
+    /**
324
+     * Returns a search instance
325
+     *
326
+     * @return \OCP\ISearch
327
+     * @since 7.0.0
328
+     */
329
+    public function getSearch();
330
+
331
+    /**
332
+     * Get the certificate manager for the user
333
+     *
334
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
335
+     * @return \OCP\ICertificateManager | null if $userId is null and no user is logged in
336
+     * @since 8.0.0
337
+     */
338
+    public function getCertificateManager($userId = null);
339
+
340
+    /**
341
+     * Create a new event source
342
+     *
343
+     * @return \OCP\IEventSource
344
+     * @since 8.0.0
345
+     */
346
+    public function createEventSource();
347
+
348
+    /**
349
+     * Returns an instance of the HTTP helper class
350
+     * @return \OC\HTTPHelper
351
+     * @deprecated 8.1.0 Use \OCP\Http\Client\IClientService
352
+     * @since 8.0.0
353
+     */
354
+    public function getHTTPHelper();
355
+
356
+    /**
357
+     * Returns an instance of the HTTP client service
358
+     *
359
+     * @return \OCP\Http\Client\IClientService
360
+     * @since 8.1.0
361
+     */
362
+    public function getHTTPClientService();
363
+
364
+    /**
365
+     * Get the active event logger
366
+     *
367
+     * @return \OCP\Diagnostics\IEventLogger
368
+     * @since 8.0.0
369
+     */
370
+    public function getEventLogger();
371
+
372
+    /**
373
+     * Get the active query logger
374
+     *
375
+     * The returned logger only logs data when debug mode is enabled
376
+     *
377
+     * @return \OCP\Diagnostics\IQueryLogger
378
+     * @since 8.0.0
379
+     */
380
+    public function getQueryLogger();
381
+
382
+    /**
383
+     * Get the manager for temporary files and folders
384
+     *
385
+     * @return \OCP\ITempManager
386
+     * @since 8.0.0
387
+     */
388
+    public function getTempManager();
389
+
390
+    /**
391
+     * Get the app manager
392
+     *
393
+     * @return \OCP\App\IAppManager
394
+     * @since 8.0.0
395
+     */
396
+    public function getAppManager();
397
+
398
+    /**
399
+     * Get the webroot
400
+     *
401
+     * @return string
402
+     * @since 8.0.0
403
+     */
404
+    public function getWebRoot();
405
+
406
+    /**
407
+     * @return \OCP\Files\Config\IMountProviderCollection
408
+     * @since 8.0.0
409
+     */
410
+    public function getMountProviderCollection();
411
+
412
+    /**
413
+     * Get the IniWrapper
414
+     *
415
+     * @return \bantu\IniGetWrapper\IniGetWrapper
416
+     * @since 8.0.0
417
+     */
418
+    public function getIniWrapper();
419
+    /**
420
+     * @return \OCP\Command\IBus
421
+     * @since 8.1.0
422
+     */
423
+    public function getCommandBus();
424
+
425
+    /**
426
+     * Creates a new mailer
427
+     *
428
+     * @return \OCP\Mail\IMailer
429
+     * @since 8.1.0
430
+     */
431
+    public function getMailer();
432
+
433
+    /**
434
+     * Get the locking provider
435
+     *
436
+     * @return \OCP\Lock\ILockingProvider
437
+     * @since 8.1.0
438
+     */
439
+    public function getLockingProvider();
440
+
441
+    /**
442
+     * @return \OCP\Files\Mount\IMountManager
443
+     * @since 8.2.0
444
+     */
445
+    public function getMountManager();
446
+
447
+    /**
448
+     * Get the MimeTypeDetector
449
+     *
450
+     * @return \OCP\Files\IMimeTypeDetector
451
+     * @since 8.2.0
452
+     */
453
+    public function getMimeTypeDetector();
454
+
455
+    /**
456
+     * Get the MimeTypeLoader
457
+     *
458
+     * @return \OCP\Files\IMimeTypeLoader
459
+     * @since 8.2.0
460
+     */
461
+    public function getMimeTypeLoader();
462
+
463
+    /**
464
+     * Get the EventDispatcher
465
+     *
466
+     * @return EventDispatcherInterface
467
+     * @since 8.2.0
468
+     */
469
+    public function getEventDispatcher();
470
+
471
+    /**
472
+     * Get the Notification Manager
473
+     *
474
+     * @return \OCP\Notification\IManager
475
+     * @since 9.0.0
476
+     */
477
+    public function getNotificationManager();
478
+
479
+    /**
480
+     * @return \OCP\Comments\ICommentsManager
481
+     * @since 9.0.0
482
+     */
483
+    public function getCommentsManager();
484
+
485
+    /**
486
+     * Returns the system-tag manager
487
+     *
488
+     * @return \OCP\SystemTag\ISystemTagManager
489
+     *
490
+     * @since 9.0.0
491
+     */
492
+    public function getSystemTagManager();
493
+
494
+    /**
495
+     * Returns the system-tag object mapper
496
+     *
497
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
498
+     *
499
+     * @since 9.0.0
500
+     */
501
+    public function getSystemTagObjectMapper();
502
+
503
+    /**
504
+     * Returns the share manager
505
+     *
506
+     * @return \OCP\Share\IManager
507
+     * @since 9.0.0
508
+     */
509
+    public function getShareManager();
510
+
511
+    /**
512
+     * @return IContentSecurityPolicyManager
513
+     * @since 9.0.0
514
+     */
515
+    public function getContentSecurityPolicyManager();
516
+
517
+    /**
518
+     * @return \OCP\IDateTimeZone
519
+     * @since 8.0.0
520
+     */
521
+    public function getDateTimeZone();
522
+
523
+    /**
524
+     * @return \OCP\IDateTimeFormatter
525
+     * @since 8.0.0
526
+     */
527
+    public function getDateTimeFormatter();
528
+
529
+    /**
530
+     * @return \OCP\Federation\ICloudIdManager
531
+     * @since 12.0.0
532
+     */
533
+    public function getCloudIdManager();
534
+
535
+    /**
536
+     * @return \OC\OCS\DiscoveryService
537
+     * @since 12.0.0
538
+     */
539
+    public function getOCSDiscoveryService();
540 540
 }
Please login to merge, or discard this patch.
apps/federation/lib/Controller/OCSAuthAPIController.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -46,169 +46,169 @@
 block discarded – undo
46 46
  */
47 47
 class OCSAuthAPIController extends OCSController{
48 48
 
49
-	/** @var ISecureRandom  */
50
-	private $secureRandom;
51
-
52
-	/** @var IJobList */
53
-	private $jobList;
54
-
55
-	/** @var TrustedServers */
56
-	private $trustedServers;
57
-
58
-	/** @var DbHandler */
59
-	private $dbHandler;
60
-
61
-	/** @var ILogger */
62
-	private $logger;
63
-
64
-	/**
65
-	 * OCSAuthAPI constructor.
66
-	 *
67
-	 * @param string $appName
68
-	 * @param IRequest $request
69
-	 * @param ISecureRandom $secureRandom
70
-	 * @param IJobList $jobList
71
-	 * @param TrustedServers $trustedServers
72
-	 * @param DbHandler $dbHandler
73
-	 * @param ILogger $logger
74
-	 */
75
-	public function __construct(
76
-		$appName,
77
-		IRequest $request,
78
-		ISecureRandom $secureRandom,
79
-		IJobList $jobList,
80
-		TrustedServers $trustedServers,
81
-		DbHandler $dbHandler,
82
-		ILogger $logger
83
-	) {
84
-		parent::__construct($appName, $request);
85
-
86
-		$this->secureRandom = $secureRandom;
87
-		$this->jobList = $jobList;
88
-		$this->trustedServers = $trustedServers;
89
-		$this->dbHandler = $dbHandler;
90
-		$this->logger = $logger;
91
-	}
92
-
93
-	/**
94
-	 * @NoCSRFRequired
95
-	 * @PublicPage
96
-	 *
97
-	 * request received to ask remote server for a shared secret, for legacy end-points
98
-	 *
99
-	 * @param string $url
100
-	 * @param string $token
101
-	 * @return Http\DataResponse
102
-	 * @throws OCSForbiddenException
103
-	 */
104
-	public function requestSharedSecretLegacy($url, $token) {
105
-		return $this->requestSharedSecret($url, $token);
106
-	}
107
-
108
-
109
-	/**
110
-	 * @NoCSRFRequired
111
-	 * @PublicPage
112
-	 *
113
-	 * create shared secret and return it, for legacy end-points
114
-	 *
115
-	 * @param string $url
116
-	 * @param string $token
117
-	 * @return Http\DataResponse
118
-	 * @throws OCSForbiddenException
119
-	 */
120
-	public function getSharedSecretLegacy($url, $token) {
121
-		return $this->getSharedSecret($url, $token);
122
-	}
123
-
124
-	/**
125
-	 * @NoCSRFRequired
126
-	 * @PublicPage
127
-	 *
128
-	 * request received to ask remote server for a shared secret
129
-	 *
130
-	 * @param string $url
131
-	 * @param string $token
132
-	 * @return Http\DataResponse
133
-	 * @throws OCSForbiddenException
134
-	 */
135
-	public function requestSharedSecret($url, $token) {
136
-		if ($this->trustedServers->isTrustedServer($url) === false) {
137
-			$this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
138
-			throw new OCSForbiddenException();
139
-		}
140
-
141
-		// if both server initiated the exchange of the shared secret the greater
142
-		// token wins
143
-		$localToken = $this->dbHandler->getToken($url);
144
-		if (strcmp($localToken, $token) > 0) {
145
-			$this->logger->info(
146
-				'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
147
-				['app' => 'federation']
148
-			);
149
-			throw new OCSForbiddenException();
150
-		}
151
-
152
-		// we ask for the shared secret so we no longer have to ask the other server
153
-		// to request the shared secret
154
-		$this->jobList->remove('OCA\Federation\BackgroundJob\RequestSharedSecret',
155
-			[
156
-				'url' => $url,
157
-				'token' => $localToken
158
-			]
159
-		);
160
-
161
-		$this->jobList->add(
162
-			'OCA\Federation\BackgroundJob\GetSharedSecret',
163
-			[
164
-				'url' => $url,
165
-				'token' => $token,
166
-			]
167
-		);
168
-
169
-		return new Http\DataResponse();
170
-	}
171
-
172
-	/**
173
-	 * @NoCSRFRequired
174
-	 * @PublicPage
175
-	 *
176
-	 * create shared secret and return it
177
-	 *
178
-	 * @param string $url
179
-	 * @param string $token
180
-	 * @return Http\DataResponse
181
-	 * @throws OCSForbiddenException
182
-	 */
183
-	public function getSharedSecret($url, $token) {
184
-		if ($this->trustedServers->isTrustedServer($url) === false) {
185
-			$this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
186
-			throw new OCSForbiddenException();
187
-		}
188
-
189
-		if ($this->isValidToken($url, $token) === false) {
190
-			$expectedToken = $this->dbHandler->getToken($url);
191
-			$this->logger->error(
192
-				'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
193
-				['app' => 'federation']
194
-			);
195
-			throw new OCSForbiddenException();
196
-		}
197
-
198
-		$sharedSecret = $this->secureRandom->generate(32);
199
-
200
-		$this->trustedServers->addSharedSecret($url, $sharedSecret);
201
-		// reset token after the exchange of the shared secret was successful
202
-		$this->dbHandler->addToken($url, '');
203
-
204
-		return new Http\DataResponse([
205
-			'sharedSecret' => $sharedSecret
206
-		]);
207
-	}
208
-
209
-	protected function isValidToken($url, $token) {
210
-		$storedToken = $this->dbHandler->getToken($url);
211
-		return hash_equals($storedToken, $token);
212
-	}
49
+    /** @var ISecureRandom  */
50
+    private $secureRandom;
51
+
52
+    /** @var IJobList */
53
+    private $jobList;
54
+
55
+    /** @var TrustedServers */
56
+    private $trustedServers;
57
+
58
+    /** @var DbHandler */
59
+    private $dbHandler;
60
+
61
+    /** @var ILogger */
62
+    private $logger;
63
+
64
+    /**
65
+     * OCSAuthAPI constructor.
66
+     *
67
+     * @param string $appName
68
+     * @param IRequest $request
69
+     * @param ISecureRandom $secureRandom
70
+     * @param IJobList $jobList
71
+     * @param TrustedServers $trustedServers
72
+     * @param DbHandler $dbHandler
73
+     * @param ILogger $logger
74
+     */
75
+    public function __construct(
76
+        $appName,
77
+        IRequest $request,
78
+        ISecureRandom $secureRandom,
79
+        IJobList $jobList,
80
+        TrustedServers $trustedServers,
81
+        DbHandler $dbHandler,
82
+        ILogger $logger
83
+    ) {
84
+        parent::__construct($appName, $request);
85
+
86
+        $this->secureRandom = $secureRandom;
87
+        $this->jobList = $jobList;
88
+        $this->trustedServers = $trustedServers;
89
+        $this->dbHandler = $dbHandler;
90
+        $this->logger = $logger;
91
+    }
92
+
93
+    /**
94
+     * @NoCSRFRequired
95
+     * @PublicPage
96
+     *
97
+     * request received to ask remote server for a shared secret, for legacy end-points
98
+     *
99
+     * @param string $url
100
+     * @param string $token
101
+     * @return Http\DataResponse
102
+     * @throws OCSForbiddenException
103
+     */
104
+    public function requestSharedSecretLegacy($url, $token) {
105
+        return $this->requestSharedSecret($url, $token);
106
+    }
107
+
108
+
109
+    /**
110
+     * @NoCSRFRequired
111
+     * @PublicPage
112
+     *
113
+     * create shared secret and return it, for legacy end-points
114
+     *
115
+     * @param string $url
116
+     * @param string $token
117
+     * @return Http\DataResponse
118
+     * @throws OCSForbiddenException
119
+     */
120
+    public function getSharedSecretLegacy($url, $token) {
121
+        return $this->getSharedSecret($url, $token);
122
+    }
123
+
124
+    /**
125
+     * @NoCSRFRequired
126
+     * @PublicPage
127
+     *
128
+     * request received to ask remote server for a shared secret
129
+     *
130
+     * @param string $url
131
+     * @param string $token
132
+     * @return Http\DataResponse
133
+     * @throws OCSForbiddenException
134
+     */
135
+    public function requestSharedSecret($url, $token) {
136
+        if ($this->trustedServers->isTrustedServer($url) === false) {
137
+            $this->logger->error('remote server not trusted (' . $url . ') while requesting shared secret', ['app' => 'federation']);
138
+            throw new OCSForbiddenException();
139
+        }
140
+
141
+        // if both server initiated the exchange of the shared secret the greater
142
+        // token wins
143
+        $localToken = $this->dbHandler->getToken($url);
144
+        if (strcmp($localToken, $token) > 0) {
145
+            $this->logger->info(
146
+                'remote server (' . $url . ') presented lower token. We will initiate the exchange of the shared secret.',
147
+                ['app' => 'federation']
148
+            );
149
+            throw new OCSForbiddenException();
150
+        }
151
+
152
+        // we ask for the shared secret so we no longer have to ask the other server
153
+        // to request the shared secret
154
+        $this->jobList->remove('OCA\Federation\BackgroundJob\RequestSharedSecret',
155
+            [
156
+                'url' => $url,
157
+                'token' => $localToken
158
+            ]
159
+        );
160
+
161
+        $this->jobList->add(
162
+            'OCA\Federation\BackgroundJob\GetSharedSecret',
163
+            [
164
+                'url' => $url,
165
+                'token' => $token,
166
+            ]
167
+        );
168
+
169
+        return new Http\DataResponse();
170
+    }
171
+
172
+    /**
173
+     * @NoCSRFRequired
174
+     * @PublicPage
175
+     *
176
+     * create shared secret and return it
177
+     *
178
+     * @param string $url
179
+     * @param string $token
180
+     * @return Http\DataResponse
181
+     * @throws OCSForbiddenException
182
+     */
183
+    public function getSharedSecret($url, $token) {
184
+        if ($this->trustedServers->isTrustedServer($url) === false) {
185
+            $this->logger->error('remote server not trusted (' . $url . ') while getting shared secret', ['app' => 'federation']);
186
+            throw new OCSForbiddenException();
187
+        }
188
+
189
+        if ($this->isValidToken($url, $token) === false) {
190
+            $expectedToken = $this->dbHandler->getToken($url);
191
+            $this->logger->error(
192
+                'remote server (' . $url . ') didn\'t send a valid token (got "' . $token . '" but expected "'. $expectedToken . '") while getting shared secret',
193
+                ['app' => 'federation']
194
+            );
195
+            throw new OCSForbiddenException();
196
+        }
197
+
198
+        $sharedSecret = $this->secureRandom->generate(32);
199
+
200
+        $this->trustedServers->addSharedSecret($url, $sharedSecret);
201
+        // reset token after the exchange of the shared secret was successful
202
+        $this->dbHandler->addToken($url, '');
203
+
204
+        return new Http\DataResponse([
205
+            'sharedSecret' => $sharedSecret
206
+        ]);
207
+    }
208
+
209
+    protected function isValidToken($url, $token) {
210
+        $storedToken = $this->dbHandler->getToken($url);
211
+        return hash_equals($storedToken, $token);
212
+    }
213 213
 
214 214
 }
Please login to merge, or discard this patch.
apps/federation/appinfo/routes.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -23,50 +23,50 @@
 block discarded – undo
23 23
 $application = new \OCA\Federation\AppInfo\Application();
24 24
 
25 25
 $application->registerRoutes(
26
-	$this,
27
-	[
28
-		'routes' => [
29
-			[
30
-				'name' => 'Settings#addServer',
31
-				'url' => '/trusted-servers',
32
-				'verb' => 'POST'
33
-			],
34
-			[
35
-				'name' => 'Settings#removeServer',
36
-				'url' => '/trusted-servers/{id}',
37
-				'verb' => 'DELETE'
38
-			],
39
-			[
40
-				'name' => 'Settings#autoAddServers',
41
-				'url' => '/auto-add-servers',
42
-				'verb' => 'POST'
43
-			],
44
-		],
45
-		'ocs' => [
46
-			// old endpoints, only used by Nextcloud and ownCloud
47
-			[
48
-				'name' => 'OCSAuthAPI#getSharedSecretLegacy',
49
-				'url' => '/api/v1/shared-secret',
50
-				'verb' => 'GET',
51
-			],
52
-			[
53
-				'name' => 'OCSAuthAPI#requestSharedSecretLegacy',
54
-				'url' => '/api/v1/request-shared-secret',
55
-				'verb' => 'POST',
56
-			],
57
-			// new endpoints, published as public api
58
-			[
59
-				'name' => 'OCSAuthAPI#getSharedSecret',
60
-				'root' => '/cloud',
61
-				'url' => '/shared-secret',
62
-				'verb' => 'GET',
63
-			],
64
-			[
65
-				'name' => 'OCSAuthAPI#requestSharedSecret',
66
-				'root' => '/cloud',
67
-				'url' => '/shared-secret',
68
-				'verb' => 'POST',
69
-			],
70
-		],
71
-	]
26
+    $this,
27
+    [
28
+        'routes' => [
29
+            [
30
+                'name' => 'Settings#addServer',
31
+                'url' => '/trusted-servers',
32
+                'verb' => 'POST'
33
+            ],
34
+            [
35
+                'name' => 'Settings#removeServer',
36
+                'url' => '/trusted-servers/{id}',
37
+                'verb' => 'DELETE'
38
+            ],
39
+            [
40
+                'name' => 'Settings#autoAddServers',
41
+                'url' => '/auto-add-servers',
42
+                'verb' => 'POST'
43
+            ],
44
+        ],
45
+        'ocs' => [
46
+            // old endpoints, only used by Nextcloud and ownCloud
47
+            [
48
+                'name' => 'OCSAuthAPI#getSharedSecretLegacy',
49
+                'url' => '/api/v1/shared-secret',
50
+                'verb' => 'GET',
51
+            ],
52
+            [
53
+                'name' => 'OCSAuthAPI#requestSharedSecretLegacy',
54
+                'url' => '/api/v1/request-shared-secret',
55
+                'verb' => 'POST',
56
+            ],
57
+            // new endpoints, published as public api
58
+            [
59
+                'name' => 'OCSAuthAPI#getSharedSecret',
60
+                'root' => '/cloud',
61
+                'url' => '/shared-secret',
62
+                'verb' => 'GET',
63
+            ],
64
+            [
65
+                'name' => 'OCSAuthAPI#requestSharedSecret',
66
+                'root' => '/cloud',
67
+                'url' => '/shared-secret',
68
+                'verb' => 'POST',
69
+            ],
70
+        ],
71
+    ]
72 72
 );
Please login to merge, or discard this patch.