Passed
Push — master ( 659ea6...1da559 )
by Morris
43:46 queued 30:39
created
lib/private/Share/Helper.php 2 patches
Indentation   +232 added lines, -232 removed lines patch added patch discarded remove patch
@@ -36,263 +36,263 @@
 block discarded – undo
36 36
 
37 37
 class Helper extends \OC\Share\Constants {
38 38
 
39
-	/**
40
-	 * Generate a unique target for the item
41
-	 * @param string $itemType
42
-	 * @param string $itemSource
43
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
44
-	 * @param string $shareWith User or group the item is being shared with
45
-	 * @param string $uidOwner User that is the owner of shared item
46
-	 * @param string $suggestedTarget The suggested target originating from a reshare (optional)
47
-	 * @param int $groupParent The id of the parent group share (optional)
48
-	 * @throws \Exception
49
-	 * @return string Item target
50
-	 */
51
-	public static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedTarget = null, $groupParent = null) {
52
-		// FIXME: $uidOwner and $groupParent seems to be unused
53
-		$backend = \OC\Share\Share::getBackend($itemType);
54
-		if ($shareType === IShare::TYPE_LINK || $shareType === IShare::TYPE_REMOTE) {
55
-			if (isset($suggestedTarget)) {
56
-				return $suggestedTarget;
57
-			}
58
-			return $backend->generateTarget($itemSource, false);
59
-		} else {
60
-			if ($shareType == IShare::TYPE_USER) {
61
-				// Share with is a user, so set share type to user and groups
62
-				$shareType = self::$shareTypeUserAndGroups;
63
-			}
39
+    /**
40
+     * Generate a unique target for the item
41
+     * @param string $itemType
42
+     * @param string $itemSource
43
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
44
+     * @param string $shareWith User or group the item is being shared with
45
+     * @param string $uidOwner User that is the owner of shared item
46
+     * @param string $suggestedTarget The suggested target originating from a reshare (optional)
47
+     * @param int $groupParent The id of the parent group share (optional)
48
+     * @throws \Exception
49
+     * @return string Item target
50
+     */
51
+    public static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedTarget = null, $groupParent = null) {
52
+        // FIXME: $uidOwner and $groupParent seems to be unused
53
+        $backend = \OC\Share\Share::getBackend($itemType);
54
+        if ($shareType === IShare::TYPE_LINK || $shareType === IShare::TYPE_REMOTE) {
55
+            if (isset($suggestedTarget)) {
56
+                return $suggestedTarget;
57
+            }
58
+            return $backend->generateTarget($itemSource, false);
59
+        } else {
60
+            if ($shareType == IShare::TYPE_USER) {
61
+                // Share with is a user, so set share type to user and groups
62
+                $shareType = self::$shareTypeUserAndGroups;
63
+            }
64 64
 
65
-			// Check if suggested target exists first
66
-			if (!isset($suggestedTarget)) {
67
-				$suggestedTarget = $itemSource;
68
-			}
69
-			if ($shareType == IShare::TYPE_GROUP) {
70
-				$target = $backend->generateTarget($suggestedTarget, false);
71
-			} else {
72
-				$target = $backend->generateTarget($suggestedTarget, $shareWith);
73
-			}
65
+            // Check if suggested target exists first
66
+            if (!isset($suggestedTarget)) {
67
+                $suggestedTarget = $itemSource;
68
+            }
69
+            if ($shareType == IShare::TYPE_GROUP) {
70
+                $target = $backend->generateTarget($suggestedTarget, false);
71
+            } else {
72
+                $target = $backend->generateTarget($suggestedTarget, $shareWith);
73
+            }
74 74
 
75
-			return $target;
76
-		}
77
-	}
75
+            return $target;
76
+        }
77
+    }
78 78
 
79
-	/**
80
-	 * Delete all reshares and group share children of an item
81
-	 * @param int $parent Id of item to delete
82
-	 * @param bool $excludeParent If true, exclude the parent from the delete (optional)
83
-	 * @param string $uidOwner The user that the parent was shared with (optional)
84
-	 * @param int $newParent new parent for the childrens
85
-	 * @param bool $excludeGroupChildren exclude group children elements
86
-	 */
87
-	public static function delete($parent, $excludeParent = false, $uidOwner = null, $newParent = null, $excludeGroupChildren = false) {
88
-		$ids = [$parent];
89
-		$deletedItems = [];
90
-		$changeParent = [];
91
-		$parents = [$parent];
92
-		while (!empty($parents)) {
93
-			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
94
-			$query->select(
95
-				'id', 'share_with', 'item_type', 'share_type',
96
-				'item_target', 'file_target', 'parent'
97
-				)
98
-				->from('share')
99
-				->where($query->expr()->in('parent', $query->createNamedParameter(
100
-					$parents, IQueryBuilder::PARAM_INT_ARRAY
101
-				)));
79
+    /**
80
+     * Delete all reshares and group share children of an item
81
+     * @param int $parent Id of item to delete
82
+     * @param bool $excludeParent If true, exclude the parent from the delete (optional)
83
+     * @param string $uidOwner The user that the parent was shared with (optional)
84
+     * @param int $newParent new parent for the childrens
85
+     * @param bool $excludeGroupChildren exclude group children elements
86
+     */
87
+    public static function delete($parent, $excludeParent = false, $uidOwner = null, $newParent = null, $excludeGroupChildren = false) {
88
+        $ids = [$parent];
89
+        $deletedItems = [];
90
+        $changeParent = [];
91
+        $parents = [$parent];
92
+        while (!empty($parents)) {
93
+            $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
94
+            $query->select(
95
+                'id', 'share_with', 'item_type', 'share_type',
96
+                'item_target', 'file_target', 'parent'
97
+                )
98
+                ->from('share')
99
+                ->where($query->expr()->in('parent', $query->createNamedParameter(
100
+                    $parents, IQueryBuilder::PARAM_INT_ARRAY
101
+                )));
102 102
 
103
-			if (count($ids) === 1 && isset($uidOwner)) {
104
-				// Check the owner on the first search of reshares, useful for
105
-				// finding and deleting the reshares by a single user of a group share
106
-				$query->andWhere($query->expr()->eq('uid_owner', $uidOwner));
107
-			}
103
+            if (count($ids) === 1 && isset($uidOwner)) {
104
+                // Check the owner on the first search of reshares, useful for
105
+                // finding and deleting the reshares by a single user of a group share
106
+                $query->andWhere($query->expr()->eq('uid_owner', $uidOwner));
107
+            }
108 108
 
109
-			if ($excludeGroupChildren) {
110
-				$query->andWhere($query->expr()->eq('share_type', self::$shareTypeGroupUserUnique));
111
-			}
109
+            if ($excludeGroupChildren) {
110
+                $query->andWhere($query->expr()->eq('share_type', self::$shareTypeGroupUserUnique));
111
+            }
112 112
 
113
-			$result = $query->execute();
114
-			// Reset parents array, only go through loop again if items are found
115
-			$parents = [];
116
-			while ($item = $result->fetch()) {
117
-				$tmpItem = [
118
-					'id' => $item['id'],
119
-					'shareWith' => $item['share_with'],
120
-					'itemTarget' => $item['item_target'],
121
-					'itemType' => $item['item_type'],
122
-					'shareType' => (int)$item['share_type'],
123
-				];
124
-				if (isset($item['file_target'])) {
125
-					$tmpItem['fileTarget'] = $item['file_target'];
126
-				}
127
-				// if we have a new parent for the child we remember the child
128
-				// to update the parent, if not we add it to the list of items
129
-				// which should be deleted
130
-				if ($newParent !== null) {
131
-					$changeParent[] = $item['id'];
132
-				} else {
133
-					$deletedItems[] = $tmpItem;
134
-					$ids[] = $item['id'];
135
-					$parents[] = $item['id'];
136
-				}
137
-			}
138
-			$result->closeCursor();
139
-		}
140
-		if ($excludeParent) {
141
-			unset($ids[0]);
142
-		}
113
+            $result = $query->execute();
114
+            // Reset parents array, only go through loop again if items are found
115
+            $parents = [];
116
+            while ($item = $result->fetch()) {
117
+                $tmpItem = [
118
+                    'id' => $item['id'],
119
+                    'shareWith' => $item['share_with'],
120
+                    'itemTarget' => $item['item_target'],
121
+                    'itemType' => $item['item_type'],
122
+                    'shareType' => (int)$item['share_type'],
123
+                ];
124
+                if (isset($item['file_target'])) {
125
+                    $tmpItem['fileTarget'] = $item['file_target'];
126
+                }
127
+                // if we have a new parent for the child we remember the child
128
+                // to update the parent, if not we add it to the list of items
129
+                // which should be deleted
130
+                if ($newParent !== null) {
131
+                    $changeParent[] = $item['id'];
132
+                } else {
133
+                    $deletedItems[] = $tmpItem;
134
+                    $ids[] = $item['id'];
135
+                    $parents[] = $item['id'];
136
+                }
137
+            }
138
+            $result->closeCursor();
139
+        }
140
+        if ($excludeParent) {
141
+            unset($ids[0]);
142
+        }
143 143
 
144
-		if (!empty($changeParent)) {
145
-			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
146
-			$query->update('share')
147
-				->set('parent', $query->createNamedParameter($newParent, IQueryBuilder::PARAM_INT))
148
-				->where($query->expr()->in('id', $query->createNamedParameter($changeParent, IQueryBuilder::PARAM_INT_ARRAY)));
149
-			$query->execute();
150
-		}
144
+        if (!empty($changeParent)) {
145
+            $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
146
+            $query->update('share')
147
+                ->set('parent', $query->createNamedParameter($newParent, IQueryBuilder::PARAM_INT))
148
+                ->where($query->expr()->in('id', $query->createNamedParameter($changeParent, IQueryBuilder::PARAM_INT_ARRAY)));
149
+            $query->execute();
150
+        }
151 151
 
152
-		if (!empty($ids)) {
153
-			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
154
-			$query->delete('share')
155
-				->where($query->expr()->in('id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
156
-			$query->execute();
157
-		}
152
+        if (!empty($ids)) {
153
+            $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
154
+            $query->delete('share')
155
+                ->where($query->expr()->in('id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
156
+            $query->execute();
157
+        }
158 158
 
159
-		return $deletedItems;
160
-	}
159
+        return $deletedItems;
160
+    }
161 161
 
162
-	/**
163
-	 * get default expire settings defined by the admin
164
-	 * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
165
-	 */
166
-	public static function getDefaultExpireSetting() {
167
-		$config = \OC::$server->getConfig();
162
+    /**
163
+     * get default expire settings defined by the admin
164
+     * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
165
+     */
166
+    public static function getDefaultExpireSetting() {
167
+        $config = \OC::$server->getConfig();
168 168
 
169
-		$defaultExpireSettings = ['defaultExpireDateSet' => false];
169
+        $defaultExpireSettings = ['defaultExpireDateSet' => false];
170 170
 
171
-		// get default expire settings
172
-		$defaultExpireDate = $config->getAppValue('core', 'shareapi_default_expire_date', 'no');
173
-		if ($defaultExpireDate === 'yes') {
174
-			$enforceExpireDate = $config->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
175
-			$defaultExpireSettings['defaultExpireDateSet'] = true;
176
-			$defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
177
-			$defaultExpireSettings['enforceExpireDate'] = $enforceExpireDate === 'yes';
178
-		}
171
+        // get default expire settings
172
+        $defaultExpireDate = $config->getAppValue('core', 'shareapi_default_expire_date', 'no');
173
+        if ($defaultExpireDate === 'yes') {
174
+            $enforceExpireDate = $config->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
175
+            $defaultExpireSettings['defaultExpireDateSet'] = true;
176
+            $defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
177
+            $defaultExpireSettings['enforceExpireDate'] = $enforceExpireDate === 'yes';
178
+        }
179 179
 
180
-		return $defaultExpireSettings;
181
-	}
180
+        return $defaultExpireSettings;
181
+    }
182 182
 
183
-	public static function calcExpireDate() {
184
-		$expireAfter = \OC\Share\Share::getExpireInterval() * 24 * 60 * 60;
185
-		$expireAt = time() + $expireAfter;
186
-		$date = new \DateTime();
187
-		$date->setTimestamp($expireAt);
188
-		$date->setTime(0, 0, 0);
189
-		//$dateString = $date->format('Y-m-d') . ' 00:00:00';
183
+    public static function calcExpireDate() {
184
+        $expireAfter = \OC\Share\Share::getExpireInterval() * 24 * 60 * 60;
185
+        $expireAt = time() + $expireAfter;
186
+        $date = new \DateTime();
187
+        $date->setTimestamp($expireAt);
188
+        $date->setTime(0, 0, 0);
189
+        //$dateString = $date->format('Y-m-d') . ' 00:00:00';
190 190
 
191
-		return $date;
192
-	}
191
+        return $date;
192
+    }
193 193
 
194
-	/**
195
-	 * calculate expire date
196
-	 * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
197
-	 * @param int $creationTime timestamp when the share was created
198
-	 * @param int $userExpireDate expire timestamp set by the user
199
-	 * @return mixed integer timestamp or False
200
-	 */
201
-	public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) {
202
-		$expires = false;
203
-		$defaultExpires = null;
194
+    /**
195
+     * calculate expire date
196
+     * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
197
+     * @param int $creationTime timestamp when the share was created
198
+     * @param int $userExpireDate expire timestamp set by the user
199
+     * @return mixed integer timestamp or False
200
+     */
201
+    public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) {
202
+        $expires = false;
203
+        $defaultExpires = null;
204 204
 
205
-		if (!empty($defaultExpireSettings['defaultExpireDateSet'])) {
206
-			$defaultExpires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400;
207
-		}
205
+        if (!empty($defaultExpireSettings['defaultExpireDateSet'])) {
206
+            $defaultExpires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400;
207
+        }
208 208
 
209 209
 
210
-		if (isset($userExpireDate)) {
211
-			// if the admin decided to enforce the default expire date then we only take
212
-			// the user defined expire date of it is before the default expire date
213
-			if ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
214
-				$expires = min($userExpireDate, $defaultExpires);
215
-			} else {
216
-				$expires = $userExpireDate;
217
-			}
218
-		} elseif ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
219
-			$expires = $defaultExpires;
220
-		}
210
+        if (isset($userExpireDate)) {
211
+            // if the admin decided to enforce the default expire date then we only take
212
+            // the user defined expire date of it is before the default expire date
213
+            if ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
214
+                $expires = min($userExpireDate, $defaultExpires);
215
+            } else {
216
+                $expires = $userExpireDate;
217
+            }
218
+        } elseif ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
219
+            $expires = $defaultExpires;
220
+        }
221 221
 
222
-		return $expires;
223
-	}
222
+        return $expires;
223
+    }
224 224
 
225
-	/**
226
-	 * Strips away a potential file names and trailing slashes:
227
-	 * - http://localhost
228
-	 * - http://localhost/
229
-	 * - http://localhost/index.php
230
-	 * - http://localhost/index.php/s/{shareToken}
231
-	 *
232
-	 * all return: http://localhost
233
-	 *
234
-	 * @param string $remote
235
-	 * @return string
236
-	 */
237
-	protected static function fixRemoteURL($remote) {
238
-		$remote = str_replace('\\', '/', $remote);
239
-		if ($fileNamePosition = strpos($remote, '/index.php')) {
240
-			$remote = substr($remote, 0, $fileNamePosition);
241
-		}
242
-		$remote = rtrim($remote, '/');
225
+    /**
226
+     * Strips away a potential file names and trailing slashes:
227
+     * - http://localhost
228
+     * - http://localhost/
229
+     * - http://localhost/index.php
230
+     * - http://localhost/index.php/s/{shareToken}
231
+     *
232
+     * all return: http://localhost
233
+     *
234
+     * @param string $remote
235
+     * @return string
236
+     */
237
+    protected static function fixRemoteURL($remote) {
238
+        $remote = str_replace('\\', '/', $remote);
239
+        if ($fileNamePosition = strpos($remote, '/index.php')) {
240
+            $remote = substr($remote, 0, $fileNamePosition);
241
+        }
242
+        $remote = rtrim($remote, '/');
243 243
 
244
-		return $remote;
245
-	}
244
+        return $remote;
245
+    }
246 246
 
247
-	/**
248
-	 * split user and remote from federated cloud id
249
-	 *
250
-	 * @param string $id
251
-	 * @return string[]
252
-	 * @throws HintException
253
-	 */
254
-	public static function splitUserRemote($id) {
255
-		try {
256
-			$cloudId = \OC::$server->getCloudIdManager()->resolveCloudId($id);
257
-			return [$cloudId->getUser(), $cloudId->getRemote()];
258
-		} catch (\InvalidArgumentException $e) {
259
-			$l = \OC::$server->getL10N('core');
260
-			$hint = $l->t('Invalid Federated Cloud ID');
261
-			throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
262
-		}
263
-	}
247
+    /**
248
+     * split user and remote from federated cloud id
249
+     *
250
+     * @param string $id
251
+     * @return string[]
252
+     * @throws HintException
253
+     */
254
+    public static function splitUserRemote($id) {
255
+        try {
256
+            $cloudId = \OC::$server->getCloudIdManager()->resolveCloudId($id);
257
+            return [$cloudId->getUser(), $cloudId->getRemote()];
258
+        } catch (\InvalidArgumentException $e) {
259
+            $l = \OC::$server->getL10N('core');
260
+            $hint = $l->t('Invalid Federated Cloud ID');
261
+            throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
262
+        }
263
+    }
264 264
 
265
-	/**
266
-	 * check if two federated cloud IDs refer to the same user
267
-	 *
268
-	 * @param string $user1
269
-	 * @param string $server1
270
-	 * @param string $user2
271
-	 * @param string $server2
272
-	 * @return bool true if both users and servers are the same
273
-	 */
274
-	public static function isSameUserOnSameServer($user1, $server1, $user2, $server2) {
275
-		$normalizedServer1 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server1));
276
-		$normalizedServer2 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server2));
265
+    /**
266
+     * check if two federated cloud IDs refer to the same user
267
+     *
268
+     * @param string $user1
269
+     * @param string $server1
270
+     * @param string $user2
271
+     * @param string $server2
272
+     * @return bool true if both users and servers are the same
273
+     */
274
+    public static function isSameUserOnSameServer($user1, $server1, $user2, $server2) {
275
+        $normalizedServer1 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server1));
276
+        $normalizedServer2 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server2));
277 277
 
278
-		if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
279
-			// FIXME this should be a method in the user management instead
280
-			\OCP\Util::emitHook(
281
-					'\OCA\Files_Sharing\API\Server2Server',
282
-					'preLoginNameUsedAsUserName',
283
-					['uid' => &$user1]
284
-			);
285
-			\OCP\Util::emitHook(
286
-					'\OCA\Files_Sharing\API\Server2Server',
287
-					'preLoginNameUsedAsUserName',
288
-					['uid' => &$user2]
289
-			);
278
+        if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
279
+            // FIXME this should be a method in the user management instead
280
+            \OCP\Util::emitHook(
281
+                    '\OCA\Files_Sharing\API\Server2Server',
282
+                    'preLoginNameUsedAsUserName',
283
+                    ['uid' => &$user1]
284
+            );
285
+            \OCP\Util::emitHook(
286
+                    '\OCA\Files_Sharing\API\Server2Server',
287
+                    'preLoginNameUsedAsUserName',
288
+                    ['uid' => &$user2]
289
+            );
290 290
 
291
-			if ($user1 === $user2) {
292
-				return true;
293
-			}
294
-		}
291
+            if ($user1 === $user2) {
292
+                return true;
293
+            }
294
+        }
295 295
 
296
-		return false;
297
-	}
296
+        return false;
297
+    }
298 298
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 					'shareWith' => $item['share_with'],
120 120
 					'itemTarget' => $item['item_target'],
121 121
 					'itemType' => $item['item_type'],
122
-					'shareType' => (int)$item['share_type'],
122
+					'shareType' => (int) $item['share_type'],
123 123
 				];
124 124
 				if (isset($item['file_target'])) {
125 125
 					$tmpItem['fileTarget'] = $item['file_target'];
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 		if ($defaultExpireDate === 'yes') {
174 174
 			$enforceExpireDate = $config->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
175 175
 			$defaultExpireSettings['defaultExpireDateSet'] = true;
176
-			$defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
176
+			$defaultExpireSettings['expireAfterDays'] = (int) $config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
177 177
 			$defaultExpireSettings['enforceExpireDate'] = $enforceExpireDate === 'yes';
178 178
 		}
179 179
 
Please login to merge, or discard this patch.
lib/private/Share/Share.php 2 patches
Indentation   +1096 added lines, -1096 removed lines patch added patch discarded remove patch
@@ -50,1100 +50,1100 @@
 block discarded – undo
50 50
  */
51 51
 class Share extends Constants {
52 52
 
53
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
54
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
55
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
56
-	 *
57
-	 * Check if permission is granted with And (&) e.g. Check if delete is
58
-	 * granted: if ($permissions & PERMISSION_DELETE)
59
-	 *
60
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
61
-	 * permission: $permissions &= ~PERMISSION_UPDATE
62
-	 *
63
-	 * Apps are required to handle permissions on their own, this class only
64
-	 * stores and manages the permissions of shares
65
-	 * @see lib/public/constants.php
66
-	 */
67
-
68
-	/**
69
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
70
-	 * @param string $itemType Item type
71
-	 * @param string $class Backend class
72
-	 * @param string $collectionOf (optional) Depends on item type
73
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
74
-	 * @return boolean true if backend is registered or false if error
75
-	 */
76
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
77
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
78
-			if (!isset(self::$backendTypes[$itemType])) {
79
-				self::$backendTypes[$itemType] = [
80
-					'class' => $class,
81
-					'collectionOf' => $collectionOf,
82
-					'supportedFileExtensions' => $supportedFileExtensions
83
-				];
84
-				return true;
85
-			}
86
-			\OCP\Util::writeLog('OCP\Share',
87
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
88
-				.' is already registered for '.$itemType,
89
-				ILogger::WARN);
90
-		}
91
-		return false;
92
-	}
93
-
94
-	/**
95
-	 * Get the items of item type shared with the current user
96
-	 * @param string $itemType
97
-	 * @param int $format (optional) Format type must be defined by the backend
98
-	 * @param mixed $parameters (optional)
99
-	 * @param int $limit Number of items to return (optional) Returns all by default
100
-	 * @param boolean $includeCollections (optional)
101
-	 * @return mixed Return depends on format
102
-	 * @deprecated TESTS ONLY - this methods is only used by tests
103
-	 * called like this:
104
-	 * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
105
-	 */
106
-	public static function getItemsSharedWith() {
107
-		return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
108
-			null, -1, false);
109
-	}
110
-
111
-	/**
112
-	 * Get the items of item type shared with a user
113
-	 * @param string $itemType
114
-	 * @param string $user id for which user we want the shares
115
-	 * @param int $format (optional) Format type must be defined by the backend
116
-	 * @param mixed $parameters (optional)
117
-	 * @param int $limit Number of items to return (optional) Returns all by default
118
-	 * @param boolean $includeCollections (optional)
119
-	 * @return mixed Return depends on format
120
-	 */
121
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
122
-												  $parameters = null, $limit = -1, $includeCollections = false) {
123
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
124
-			$parameters, $limit, $includeCollections);
125
-	}
126
-
127
-	/**
128
-	 * Get the item of item type shared with a given user by source
129
-	 * @param string $itemType
130
-	 * @param string $itemSource
131
-	 * @param string $user User to whom the item was shared
132
-	 * @param string $owner Owner of the share
133
-	 * @param int $shareType only look for a specific share type
134
-	 * @return array Return list of items with file_target, permissions and expiration
135
-	 */
136
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
137
-		$shares = [];
138
-		$fileDependent = false;
139
-
140
-		$where = 'WHERE';
141
-		$fileDependentWhere = '';
142
-		if ($itemType === 'file' || $itemType === 'folder') {
143
-			$fileDependent = true;
144
-			$column = 'file_source';
145
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
146
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
147
-		} else {
148
-			$column = 'item_source';
149
-		}
150
-
151
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
152
-
153
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
154
-		$arguments = [$itemSource, $itemType];
155
-		// for link shares $user === null
156
-		if ($user !== null) {
157
-			$where .= ' AND `share_with` = ? ';
158
-			$arguments[] = $user;
159
-		}
160
-
161
-		if ($shareType !== null) {
162
-			$where .= ' AND `share_type` = ? ';
163
-			$arguments[] = $shareType;
164
-		}
165
-
166
-		if ($owner !== null) {
167
-			$where .= ' AND `uid_owner` = ? ';
168
-			$arguments[] = $owner;
169
-		}
170
-
171
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
172
-
173
-		$result = \OC_DB::executeAudited($query, $arguments);
174
-
175
-		while ($row = $result->fetchRow()) {
176
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
177
-				continue;
178
-			}
179
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
180
-				// if it is a mount point we need to get the path from the mount manager
181
-				$mountManager = \OC\Files\Filesystem::getMountManager();
182
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
183
-				if (!empty($mountPoint)) {
184
-					$path = $mountPoint[0]->getMountPoint();
185
-					$path = trim($path, '/');
186
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
187
-					$row['path'] = $path;
188
-				} else {
189
-					\OC::$server->getLogger()->warning(
190
-						'Could not resolve mount point for ' . $row['storage_id'],
191
-						['app' => 'OCP\Share']
192
-					);
193
-				}
194
-			}
195
-			$shares[] = $row;
196
-		}
197
-
198
-		//if didn't found a result than let's look for a group share.
199
-		if (empty($shares) && $user !== null) {
200
-			$userObject = \OC::$server->getUserManager()->get($user);
201
-			$groups = [];
202
-			if ($userObject) {
203
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
204
-			}
205
-
206
-			if (!empty($groups)) {
207
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
208
-				$arguments = [$itemSource, $itemType, $groups];
209
-				$types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
210
-
211
-				if ($owner !== null) {
212
-					$where .= ' AND `uid_owner` = ?';
213
-					$arguments[] = $owner;
214
-					$types[] = null;
215
-				}
216
-
217
-				// TODO: inject connection, hopefully one day in the future when this
218
-				// class isn't static anymore...
219
-				$conn = \OC::$server->getDatabaseConnection();
220
-				$result = $conn->executeQuery(
221
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
222
-					$arguments,
223
-					$types
224
-				);
225
-
226
-				while ($row = $result->fetch()) {
227
-					$shares[] = $row;
228
-				}
229
-			}
230
-		}
231
-
232
-		return $shares;
233
-	}
234
-
235
-	/**
236
-	 * Get the item of item type shared with the current user by source
237
-	 * @param string $itemType
238
-	 * @param string $itemSource
239
-	 * @param int $format (optional) Format type must be defined by the backend
240
-	 * @param mixed $parameters
241
-	 * @param boolean $includeCollections
242
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
243
-	 * @return array
244
-	 */
245
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
246
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
247
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
248
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
249
-			$parameters, 1, $includeCollections, true);
250
-	}
251
-
252
-	/**
253
-	 * Get the shared item of item type owned by the current user
254
-	 * @param string $itemType
255
-	 * @param string $itemSource
256
-	 * @param int $format (optional) Format type must be defined by the backend
257
-	 * @param mixed $parameters
258
-	 * @param boolean $includeCollections
259
-	 * @return mixed Return depends on format
260
-	 */
261
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
262
-										 $parameters = null, $includeCollections = false) {
263
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
264
-			$parameters, -1, $includeCollections);
265
-	}
266
-
267
-	/**
268
-	 * Unshare an item from a user, group, or delete a private link
269
-	 * @param string $itemType
270
-	 * @param string $itemSource
271
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
272
-	 * @param string $shareWith User or group the item is being shared with
273
-	 * @param string $owner owner of the share, if null the current user is used
274
-	 * @return boolean true on success or false on failure
275
-	 */
276
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
277
-
278
-		// check if it is a valid itemType
279
-		self::getBackend($itemType);
280
-
281
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
282
-
283
-		$toDelete = [];
284
-		$newParent = null;
285
-		$currentUser = $owner ? $owner : \OC_User::getUser();
286
-		foreach ($items as $item) {
287
-			// delete the item with the expected share_type and owner
288
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
289
-				$toDelete = $item;
290
-			// if there is more then one result we don't have to delete the children
291
-				// but update their parent. For group shares the new parent should always be
292
-				// the original group share and not the db entry with the unique name
293
-			} elseif ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
294
-				$newParent = $item['parent'];
295
-			} else {
296
-				$newParent = $item['id'];
297
-			}
298
-		}
299
-
300
-		if (!empty($toDelete)) {
301
-			self::unshareItem($toDelete, $newParent);
302
-			return true;
303
-		}
304
-		return false;
305
-	}
306
-
307
-	/**
308
-	 * Checks whether a share has expired, calls unshareItem() if yes.
309
-	 * @param array $item Share data (usually database row)
310
-	 * @return boolean True if item was expired, false otherwise.
311
-	 */
312
-	protected static function expireItem(array $item) {
313
-		$result = false;
314
-
315
-		// only use default expiration date for link shares
316
-		if ((int) $item['share_type'] === IShare::TYPE_LINK) {
317
-
318
-			// calculate expiration date
319
-			if (!empty($item['expiration'])) {
320
-				$userDefinedExpire = new \DateTime($item['expiration']);
321
-				$expires = $userDefinedExpire->getTimestamp();
322
-			} else {
323
-				$expires = null;
324
-			}
325
-
326
-
327
-			// get default expiration settings
328
-			$defaultSettings = Helper::getDefaultExpireSetting();
329
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
330
-
331
-
332
-			if (is_int($expires)) {
333
-				$now = time();
334
-				if ($now > $expires) {
335
-					self::unshareItem($item);
336
-					$result = true;
337
-				}
338
-			}
339
-		}
340
-		return $result;
341
-	}
342
-
343
-	/**
344
-	 * Unshares a share given a share data array
345
-	 * @param array $item Share data (usually database row)
346
-	 * @param int $newParent parent ID
347
-	 * @return null
348
-	 */
349
-	protected static function unshareItem(array $item, $newParent = null) {
350
-		$shareType = (int)$item['share_type'];
351
-		$shareWith = null;
352
-		if ($shareType !== IShare::TYPE_LINK) {
353
-			$shareWith = $item['share_with'];
354
-		}
355
-
356
-		// Pass all the vars we have for now, they may be useful
357
-		$hookParams = [
358
-			'id' => $item['id'],
359
-			'itemType' => $item['item_type'],
360
-			'itemSource' => $item['item_source'],
361
-			'shareType' => $shareType,
362
-			'shareWith' => $shareWith,
363
-			'itemParent' => $item['parent'],
364
-			'uidOwner' => $item['uid_owner'],
365
-		];
366
-		if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
367
-			$hookParams['fileSource'] = $item['file_source'];
368
-			$hookParams['fileTarget'] = $item['file_target'];
369
-		}
370
-
371
-		\OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
372
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
373
-		$deletedShares[] = $hookParams;
374
-		$hookParams['deletedShares'] = $deletedShares;
375
-		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
376
-		if ((int)$item['share_type'] === IShare::TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
377
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
378
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
379
-		}
380
-	}
381
-
382
-	/**
383
-	 * Get the backend class for the specified item type
384
-	 * @param string $itemType
385
-	 * @throws \Exception
386
-	 * @return \OCP\Share_Backend
387
-	 */
388
-	public static function getBackend($itemType) {
389
-		$l = \OC::$server->getL10N('lib');
390
-		if (isset(self::$backends[$itemType])) {
391
-			return self::$backends[$itemType];
392
-		} elseif (isset(self::$backendTypes[$itemType]['class'])) {
393
-			$class = self::$backendTypes[$itemType]['class'];
394
-			if (class_exists($class)) {
395
-				self::$backends[$itemType] = new $class;
396
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
397
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
398
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
399
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
400
-					throw new \Exception($message_t);
401
-				}
402
-				return self::$backends[$itemType];
403
-			} else {
404
-				$message = 'Sharing backend %s not found';
405
-				$message_t = $l->t('Sharing backend %s not found', [$class]);
406
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
407
-				throw new \Exception($message_t);
408
-			}
409
-		}
410
-		$message = 'Sharing backend for %s not found';
411
-		$message_t = $l->t('Sharing backend for %s not found', [$itemType]);
412
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
413
-		throw new \Exception($message_t);
414
-	}
415
-
416
-	/**
417
-	 * Check if resharing is allowed
418
-	 * @return boolean true if allowed or false
419
-	 *
420
-	 * Resharing is allowed by default if not configured
421
-	 */
422
-	public static function isResharingAllowed() {
423
-		if (!isset(self::$isResharingAllowed)) {
424
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
425
-				self::$isResharingAllowed = true;
426
-			} else {
427
-				self::$isResharingAllowed = false;
428
-			}
429
-		}
430
-		return self::$isResharingAllowed;
431
-	}
432
-
433
-	/**
434
-	 * Get a list of collection item types for the specified item type
435
-	 * @param string $itemType
436
-	 * @return array
437
-	 */
438
-	private static function getCollectionItemTypes($itemType) {
439
-		$collectionTypes = [$itemType];
440
-		foreach (self::$backendTypes as $type => $backend) {
441
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
442
-				$collectionTypes[] = $type;
443
-			}
444
-		}
445
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
446
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
447
-			unset($collectionTypes[0]);
448
-		}
449
-		// Return array if collections were found or the item type is a
450
-		// collection itself - collections can be inside collections
451
-		if (count($collectionTypes) > 0) {
452
-			return $collectionTypes;
453
-		}
454
-		return false;
455
-	}
456
-
457
-	/**
458
-	 * Get shared items from the database
459
-	 * @param string $itemType
460
-	 * @param string $item Item source or target (optional)
461
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
462
-	 * @param string $shareWith User or group the item is being shared with
463
-	 * @param string $uidOwner User that is the owner of shared items (optional)
464
-	 * @param int $format Format to convert items to with formatItems() (optional)
465
-	 * @param mixed $parameters to pass to formatItems() (optional)
466
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
467
-	 * @param boolean $includeCollections Include collection item types (optional)
468
-	 * @param boolean $itemShareWithBySource (optional)
469
-	 * @param boolean $checkExpireDate
470
-	 * @return array
471
-	 *
472
-	 * See public functions getItem(s)... for parameter usage
473
-	 *
474
-	 */
475
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
476
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
477
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
478
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
479
-			return [];
480
-		}
481
-		$backend = self::getBackend($itemType);
482
-		$collectionTypes = false;
483
-		// Get filesystem root to add it to the file target and remove from the
484
-		// file source, match file_source with the file cache
485
-		if ($itemType == 'file' || $itemType == 'folder') {
486
-			if (!is_null($uidOwner)) {
487
-				$root = \OC\Files\Filesystem::getRoot();
488
-			} else {
489
-				$root = '';
490
-			}
491
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
492
-			if (!isset($item)) {
493
-				$where .= ' AND `file_target` IS NOT NULL ';
494
-			}
495
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
496
-			$fileDependent = true;
497
-			$queryArgs = [];
498
-		} else {
499
-			$fileDependent = false;
500
-			$root = '';
501
-			$collectionTypes = self::getCollectionItemTypes($itemType);
502
-			if ($includeCollections && !isset($item) && $collectionTypes) {
503
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
504
-				if (!in_array($itemType, $collectionTypes)) {
505
-					$itemTypes = array_merge([$itemType], $collectionTypes);
506
-				} else {
507
-					$itemTypes = $collectionTypes;
508
-				}
509
-				$placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
510
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
511
-				$queryArgs = $itemTypes;
512
-			} else {
513
-				$where = ' WHERE `item_type` = ?';
514
-				$queryArgs = [$itemType];
515
-			}
516
-		}
517
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
518
-			$where .= ' AND `share_type` != ?';
519
-			$queryArgs[] = IShare::TYPE_LINK;
520
-		}
521
-		if (isset($shareType)) {
522
-			// Include all user and group items
523
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
524
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
525
-				$queryArgs[] = IShare::TYPE_USER;
526
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
527
-				$queryArgs[] = $shareWith;
528
-
529
-				$user = \OC::$server->getUserManager()->get($shareWith);
530
-				$groups = [];
531
-				if ($user) {
532
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
533
-				}
534
-				if (!empty($groups)) {
535
-					$placeholders = implode(',', array_fill(0, count($groups), '?'));
536
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
537
-					$queryArgs[] = IShare::TYPE_GROUP;
538
-					$queryArgs = array_merge($queryArgs, $groups);
539
-				}
540
-				$where .= ')';
541
-				// Don't include own group shares
542
-				$where .= ' AND `uid_owner` != ?';
543
-				$queryArgs[] = $shareWith;
544
-			} else {
545
-				$where .= ' AND `share_type` = ?';
546
-				$queryArgs[] = $shareType;
547
-				if (isset($shareWith)) {
548
-					$where .= ' AND `share_with` = ?';
549
-					$queryArgs[] = $shareWith;
550
-				}
551
-			}
552
-		}
553
-		if (isset($uidOwner)) {
554
-			$where .= ' AND `uid_owner` = ?';
555
-			$queryArgs[] = $uidOwner;
556
-			if (!isset($shareType)) {
557
-				// Prevent unique user targets for group shares from being selected
558
-				$where .= ' AND `share_type` != ?';
559
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
560
-			}
561
-			if ($fileDependent) {
562
-				$column = 'file_source';
563
-			} else {
564
-				$column = 'item_source';
565
-			}
566
-		} else {
567
-			if ($fileDependent) {
568
-				$column = 'file_target';
569
-			} else {
570
-				$column = 'item_target';
571
-			}
572
-		}
573
-		if (isset($item)) {
574
-			$collectionTypes = self::getCollectionItemTypes($itemType);
575
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
576
-				$where .= ' AND (';
577
-			} else {
578
-				$where .= ' AND';
579
-			}
580
-			// If looking for own shared items, check item_source else check item_target
581
-			if (isset($uidOwner) || $itemShareWithBySource) {
582
-				// If item type is a file, file source needs to be checked in case the item was converted
583
-				if ($fileDependent) {
584
-					$where .= ' `file_source` = ?';
585
-					$column = 'file_source';
586
-				} else {
587
-					$where .= ' `item_source` = ?';
588
-					$column = 'item_source';
589
-				}
590
-			} else {
591
-				if ($fileDependent) {
592
-					$where .= ' `file_target` = ?';
593
-					$item = \OC\Files\Filesystem::normalizePath($item);
594
-				} else {
595
-					$where .= ' `item_target` = ?';
596
-				}
597
-			}
598
-			$queryArgs[] = $item;
599
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
600
-				$placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
601
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
602
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
603
-			}
604
-		}
605
-
606
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
607
-			// Make sure the unique user target is returned if it exists,
608
-			// unique targets should follow the group share in the database
609
-			// If the limit is not 1, the filtering can be done later
610
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
611
-		} else {
612
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
613
-		}
614
-
615
-		if ($limit != -1 && !$includeCollections) {
616
-			// The limit must be at least 3, because filtering needs to be done
617
-			if ($limit < 3) {
618
-				$queryLimit = 3;
619
-			} else {
620
-				$queryLimit = $limit;
621
-			}
622
-		} else {
623
-			$queryLimit = null;
624
-		}
625
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
626
-		$root = strlen($root);
627
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
628
-		$result = $query->execute($queryArgs);
629
-		if ($result === false) {
630
-			\OCP\Util::writeLog('OCP\Share',
631
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
632
-				ILogger::ERROR);
633
-		}
634
-		$items = [];
635
-		$targets = [];
636
-		$switchedItems = [];
637
-		$mounts = [];
638
-		while ($row = $result->fetchRow()) {
639
-			self::transformDBResults($row);
640
-			// Filter out duplicate group shares for users with unique targets
641
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
642
-				continue;
643
-			}
644
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
645
-				$row['share_type'] = IShare::TYPE_GROUP;
646
-				$row['unique_name'] = true; // remember that we use a unique name for this user
647
-				$row['share_with'] = $items[$row['parent']]['share_with'];
648
-				// if the group share was unshared from the user we keep the permission, otherwise
649
-				// we take the permission from the parent because this is always the up-to-date
650
-				// permission for the group share
651
-				if ($row['permissions'] > 0) {
652
-					$row['permissions'] = $items[$row['parent']]['permissions'];
653
-				}
654
-				// Remove the parent group share
655
-				unset($items[$row['parent']]);
656
-				if ($row['permissions'] == 0) {
657
-					continue;
658
-				}
659
-			} elseif (!isset($uidOwner)) {
660
-				// Check if the same target already exists
661
-				if (isset($targets[$row['id']])) {
662
-					// Check if the same owner shared with the user twice
663
-					// through a group and user share - this is allowed
664
-					$id = $targets[$row['id']];
665
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
666
-						// Switch to group share type to ensure resharing conditions aren't bypassed
667
-						if ($items[$id]['share_type'] != IShare::TYPE_GROUP) {
668
-							$items[$id]['share_type'] = IShare::TYPE_GROUP;
669
-							$items[$id]['share_with'] = $row['share_with'];
670
-						}
671
-						// Switch ids if sharing permission is granted on only
672
-						// one share to ensure correct parent is used if resharing
673
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
674
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
675
-							$items[$row['id']] = $items[$id];
676
-							$switchedItems[$id] = $row['id'];
677
-							unset($items[$id]);
678
-							$id = $row['id'];
679
-						}
680
-						$items[$id]['permissions'] |= (int)$row['permissions'];
681
-					}
682
-					continue;
683
-				} elseif (!empty($row['parent'])) {
684
-					$targets[$row['parent']] = $row['id'];
685
-				}
686
-			}
687
-			// Remove root from file source paths if retrieving own shared items
688
-			if (isset($uidOwner) && isset($row['path'])) {
689
-				if (isset($row['parent'])) {
690
-					$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
691
-					$query->select('file_target')
692
-						->from('share')
693
-						->where($query->expr()->eq('id', $query->createNamedParameter($row['parent'])));
694
-
695
-					$result = $query->execute();
696
-					$parentRow = $result->fetch();
697
-					$result->closeCursor();
698
-
699
-					if ($parentRow === false) {
700
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
701
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
702
-							ILogger::ERROR);
703
-					} else {
704
-						$tmpPath = $parentRow['file_target'];
705
-						// find the right position where the row path continues from the target path
706
-						$pos = strrpos($row['path'], $parentRow['file_target']);
707
-						$subPath = substr($row['path'], $pos);
708
-						$splitPath = explode('/', $subPath);
709
-						foreach (array_slice($splitPath, 2) as $pathPart) {
710
-							$tmpPath = $tmpPath . '/' . $pathPart;
711
-						}
712
-						$row['path'] = $tmpPath;
713
-					}
714
-				} else {
715
-					if (!isset($mounts[$row['storage']])) {
716
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
717
-						if (is_array($mountPoints) && !empty($mountPoints)) {
718
-							$mounts[$row['storage']] = current($mountPoints);
719
-						}
720
-					}
721
-					if (!empty($mounts[$row['storage']])) {
722
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
723
-						$relPath = substr($path, $root); // path relative to data/user
724
-						$row['path'] = rtrim($relPath, '/');
725
-					}
726
-				}
727
-			}
728
-
729
-			if ($checkExpireDate) {
730
-				if (self::expireItem($row)) {
731
-					continue;
732
-				}
733
-			}
734
-			// Check if resharing is allowed, if not remove share permission
735
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
736
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
737
-			}
738
-			// Add display names to result
739
-			$row['share_with_displayname'] = $row['share_with'];
740
-			if (isset($row['share_with']) && $row['share_with'] != '' &&
741
-				$row['share_type'] === IShare::TYPE_USER) {
742
-				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
743
-				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
744
-			} elseif (isset($row['share_with']) && $row['share_with'] != '' &&
745
-				$row['share_type'] === IShare::TYPE_REMOTE) {
746
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
747
-				foreach ($addressBookEntries as $entry) {
748
-					foreach ($entry['CLOUD'] as $cloudID) {
749
-						if ($cloudID === $row['share_with']) {
750
-							$row['share_with_displayname'] = $entry['FN'];
751
-						}
752
-					}
753
-				}
754
-			}
755
-			if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
756
-				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
757
-				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
758
-			}
759
-
760
-			if ($row['permissions'] > 0) {
761
-				$items[$row['id']] = $row;
762
-			}
763
-		}
764
-
765
-		// group items if we are looking for items shared with the current user
766
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
767
-			$items = self::groupItems($items, $itemType);
768
-		}
769
-
770
-		if (!empty($items)) {
771
-			$collectionItems = [];
772
-			foreach ($items as &$row) {
773
-				// Return only the item instead of a 2-dimensional array
774
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
775
-					if ($format == self::FORMAT_NONE) {
776
-						return $row;
777
-					} else {
778
-						break;
779
-					}
780
-				}
781
-				// Check if this is a collection of the requested item type
782
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
783
-					if (($collectionBackend = self::getBackend($row['item_type']))
784
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
785
-						// Collections can be inside collections, check if the item is a collection
786
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
787
-							$collectionItems[] = $row;
788
-						} else {
789
-							$collection = [];
790
-							$collection['item_type'] = $row['item_type'];
791
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
792
-								$collection['path'] = basename($row['path']);
793
-							}
794
-							$row['collection'] = $collection;
795
-							// Fetch all of the children sources
796
-							$children = $collectionBackend->getChildren($row[$column]);
797
-							foreach ($children as $child) {
798
-								$childItem = $row;
799
-								$childItem['item_type'] = $itemType;
800
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
801
-									$childItem['item_source'] = $child['source'];
802
-									$childItem['item_target'] = $child['target'];
803
-								}
804
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
805
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
806
-										$childItem['file_source'] = $child['source'];
807
-									} else { // TODO is this really needed if we already know that we use the file backend?
808
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
809
-										$childItem['file_source'] = $meta['fileid'];
810
-									}
811
-									$childItem['file_target'] =
812
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
813
-								}
814
-								if (isset($item)) {
815
-									if ($childItem[$column] == $item) {
816
-										// Return only the item instead of a 2-dimensional array
817
-										if ($limit == 1) {
818
-											if ($format == self::FORMAT_NONE) {
819
-												return $childItem;
820
-											} else {
821
-												// Unset the items array and break out of both loops
822
-												$items = [];
823
-												$items[] = $childItem;
824
-												break 2;
825
-											}
826
-										} else {
827
-											$collectionItems[] = $childItem;
828
-										}
829
-									}
830
-								} else {
831
-									$collectionItems[] = $childItem;
832
-								}
833
-							}
834
-						}
835
-					}
836
-					// Remove collection item
837
-					$toRemove = $row['id'];
838
-					if (array_key_exists($toRemove, $switchedItems)) {
839
-						$toRemove = $switchedItems[$toRemove];
840
-					}
841
-					unset($items[$toRemove]);
842
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
843
-					// FIXME: Thats a dirty hack to improve file sharing performance,
844
-					// see github issue #10588 for more details
845
-					// Need to find a solution which works for all back-ends
846
-					$collectionBackend = self::getBackend($row['item_type']);
847
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
848
-					foreach ($sharedParents as $parent) {
849
-						$collectionItems[] = $parent;
850
-					}
851
-				}
852
-			}
853
-			if (!empty($collectionItems)) {
854
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
855
-				$items = array_merge($items, $collectionItems);
856
-			}
857
-
858
-			// filter out invalid items, these can appear when subshare entries exist
859
-			// for a group in which the requested user isn't a member any more
860
-			$items = array_filter($items, function ($item) {
861
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
862
-			});
863
-
864
-			return self::formatResult($items, $column, $backend, $format, $parameters);
865
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
866
-			// FIXME: Thats a dirty hack to improve file sharing performance,
867
-			// see github issue #10588 for more details
868
-			// Need to find a solution which works for all back-ends
869
-			$collectionItems = [];
870
-			$collectionBackend = self::getBackend('folder');
871
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
872
-			foreach ($sharedParents as $parent) {
873
-				$collectionItems[] = $parent;
874
-			}
875
-			if ($limit === 1) {
876
-				return reset($collectionItems);
877
-			}
878
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
879
-		}
880
-
881
-		return [];
882
-	}
883
-
884
-	/**
885
-	 * group items with link to the same source
886
-	 *
887
-	 * @param array $items
888
-	 * @param string $itemType
889
-	 * @return array of grouped items
890
-	 */
891
-	protected static function groupItems($items, $itemType) {
892
-		$fileSharing = $itemType === 'file' || $itemType === 'folder';
893
-
894
-		$result = [];
895
-
896
-		foreach ($items as $item) {
897
-			$grouped = false;
898
-			foreach ($result as $key => $r) {
899
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
900
-				// only group shares if they already point to the same target, otherwise the file where shared
901
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
902
-				if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
903
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
904
-					// add the first item to the list of grouped shares
905
-					if (!isset($result[$key]['grouped'])) {
906
-						$result[$key]['grouped'][] = $result[$key];
907
-					}
908
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
909
-					$result[$key]['grouped'][] = $item;
910
-					$grouped = true;
911
-					break;
912
-				}
913
-			}
914
-
915
-			if (!$grouped) {
916
-				$result[] = $item;
917
-			}
918
-		}
919
-
920
-		return $result;
921
-	}
922
-
923
-	/**
924
-	 * construct select statement
925
-	 * @param int $format
926
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
927
-	 * @param string $uidOwner
928
-	 * @return string select statement
929
-	 */
930
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
931
-		$select = '*';
932
-		if ($format == self::FORMAT_STATUSES) {
933
-			if ($fileDependent) {
934
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
935
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
936
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
937
-					. '`uid_initiator`';
938
-			} else {
939
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
940
-			}
941
-		} else {
942
-			if (isset($uidOwner)) {
943
-				if ($fileDependent) {
944
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
945
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
946
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
947
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
948
-				} else {
949
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
950
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
951
-				}
952
-			} else {
953
-				if ($fileDependent) {
954
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
955
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
956
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
957
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
958
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
959
-					} else {
960
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
961
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
962
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
963
-							. '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
964
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
965
-					}
966
-				}
967
-			}
968
-		}
969
-		return $select;
970
-	}
971
-
972
-
973
-	/**
974
-	 * transform db results
975
-	 * @param array $row result
976
-	 */
977
-	private static function transformDBResults(&$row) {
978
-		if (isset($row['id'])) {
979
-			$row['id'] = (int) $row['id'];
980
-		}
981
-		if (isset($row['share_type'])) {
982
-			$row['share_type'] = (int) $row['share_type'];
983
-		}
984
-		if (isset($row['parent'])) {
985
-			$row['parent'] = (int) $row['parent'];
986
-		}
987
-		if (isset($row['file_parent'])) {
988
-			$row['file_parent'] = (int) $row['file_parent'];
989
-		}
990
-		if (isset($row['file_source'])) {
991
-			$row['file_source'] = (int) $row['file_source'];
992
-		}
993
-		if (isset($row['permissions'])) {
994
-			$row['permissions'] = (int) $row['permissions'];
995
-		}
996
-		if (isset($row['storage'])) {
997
-			$row['storage'] = (int) $row['storage'];
998
-		}
999
-		if (isset($row['stime'])) {
1000
-			$row['stime'] = (int) $row['stime'];
1001
-		}
1002
-		if (isset($row['expiration']) && $row['share_type'] !== IShare::TYPE_LINK) {
1003
-			// discard expiration date for non-link shares, which might have been
1004
-			// set by ancient bugs
1005
-			$row['expiration'] = null;
1006
-		}
1007
-	}
1008
-
1009
-	/**
1010
-	 * format result
1011
-	 * @param array $items result
1012
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1013
-	 * @param \OCP\Share_Backend $backend sharing backend
1014
-	 * @param int $format
1015
-	 * @param array $parameters additional format parameters
1016
-	 * @return array format result
1017
-	 */
1018
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1019
-		if ($format === self::FORMAT_NONE) {
1020
-			return $items;
1021
-		} elseif ($format === self::FORMAT_STATUSES) {
1022
-			$statuses = [];
1023
-			foreach ($items as $item) {
1024
-				if ($item['share_type'] === IShare::TYPE_LINK) {
1025
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1026
-						continue;
1027
-					}
1028
-					$statuses[$item[$column]]['link'] = true;
1029
-				} elseif (!isset($statuses[$item[$column]])) {
1030
-					$statuses[$item[$column]]['link'] = false;
1031
-				}
1032
-				if (!empty($item['file_target'])) {
1033
-					$statuses[$item[$column]]['path'] = $item['path'];
1034
-				}
1035
-			}
1036
-			return $statuses;
1037
-		} else {
1038
-			return $backend->formatItems($items, $format, $parameters);
1039
-		}
1040
-	}
1041
-
1042
-	/**
1043
-	 * remove protocol from URL
1044
-	 *
1045
-	 * @param string $url
1046
-	 * @return string
1047
-	 */
1048
-	public static function removeProtocolFromUrl($url) {
1049
-		if (strpos($url, 'https://') === 0) {
1050
-			return substr($url, strlen('https://'));
1051
-		} elseif (strpos($url, 'http://') === 0) {
1052
-			return substr($url, strlen('http://'));
1053
-		}
1054
-
1055
-		return $url;
1056
-	}
1057
-
1058
-	/**
1059
-	 * try http post first with https and then with http as a fallback
1060
-	 *
1061
-	 * @param string $remoteDomain
1062
-	 * @param string $urlSuffix
1063
-	 * @param array $fields post parameters
1064
-	 * @return array
1065
-	 */
1066
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1067
-		$protocol = 'https://';
1068
-		$result = [
1069
-			'success' => false,
1070
-			'result' => '',
1071
-		];
1072
-		$try = 0;
1073
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1074
-		while ($result['success'] === false && $try < 2) {
1075
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1076
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1077
-			$client = \OC::$server->getHTTPClientService()->newClient();
1078
-
1079
-			try {
1080
-				$response = $client->post(
1081
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1082
-					[
1083
-						'body' => $fields,
1084
-						'connect_timeout' => 10,
1085
-					]
1086
-				);
1087
-
1088
-				$result = ['success' => true, 'result' => $response->getBody()];
1089
-			} catch (\Exception $e) {
1090
-				$result = ['success' => false, 'result' => $e->getMessage()];
1091
-			}
1092
-
1093
-			$try++;
1094
-			$protocol = 'http://';
1095
-		}
1096
-
1097
-		return $result;
1098
-	}
1099
-
1100
-	/**
1101
-	 * send server-to-server unshare to remote server
1102
-	 *
1103
-	 * @param string $remote url
1104
-	 * @param int $id share id
1105
-	 * @param string $token
1106
-	 * @return bool
1107
-	 */
1108
-	private static function sendRemoteUnshare($remote, $id, $token) {
1109
-		$url = rtrim($remote, '/');
1110
-		$fields = ['token' => $token, 'format' => 'json'];
1111
-		$url = self::removeProtocolFromUrl($url);
1112
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
1113
-		$status = json_decode($result['result'], true);
1114
-
1115
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
1116
-	}
1117
-
1118
-	/**
1119
-	 * @return int
1120
-	 */
1121
-	public static function getExpireInterval() {
1122
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1123
-	}
1124
-
1125
-	/**
1126
-	 * Checks whether the given path is reachable for the given owner
1127
-	 *
1128
-	 * @param string $path path relative to files
1129
-	 * @param string $ownerStorageId storage id of the owner
1130
-	 *
1131
-	 * @return boolean true if file is reachable, false otherwise
1132
-	 */
1133
-	private static function isFileReachable($path, $ownerStorageId) {
1134
-		// if outside the home storage, file is always considered reachable
1135
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
1136
-			substr($ownerStorageId, 0, 13) === 'object::user:'
1137
-		)) {
1138
-			return true;
1139
-		}
1140
-
1141
-		// if inside the home storage, the file has to be under "/files/"
1142
-		$path = ltrim($path, '/');
1143
-		if (substr($path, 0, 6) === 'files/') {
1144
-			return true;
1145
-		}
1146
-
1147
-		return false;
1148
-	}
53
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
54
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
55
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
56
+     *
57
+     * Check if permission is granted with And (&) e.g. Check if delete is
58
+     * granted: if ($permissions & PERMISSION_DELETE)
59
+     *
60
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
61
+     * permission: $permissions &= ~PERMISSION_UPDATE
62
+     *
63
+     * Apps are required to handle permissions on their own, this class only
64
+     * stores and manages the permissions of shares
65
+     * @see lib/public/constants.php
66
+     */
67
+
68
+    /**
69
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
70
+     * @param string $itemType Item type
71
+     * @param string $class Backend class
72
+     * @param string $collectionOf (optional) Depends on item type
73
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
74
+     * @return boolean true if backend is registered or false if error
75
+     */
76
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
77
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
78
+            if (!isset(self::$backendTypes[$itemType])) {
79
+                self::$backendTypes[$itemType] = [
80
+                    'class' => $class,
81
+                    'collectionOf' => $collectionOf,
82
+                    'supportedFileExtensions' => $supportedFileExtensions
83
+                ];
84
+                return true;
85
+            }
86
+            \OCP\Util::writeLog('OCP\Share',
87
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
88
+                .' is already registered for '.$itemType,
89
+                ILogger::WARN);
90
+        }
91
+        return false;
92
+    }
93
+
94
+    /**
95
+     * Get the items of item type shared with the current user
96
+     * @param string $itemType
97
+     * @param int $format (optional) Format type must be defined by the backend
98
+     * @param mixed $parameters (optional)
99
+     * @param int $limit Number of items to return (optional) Returns all by default
100
+     * @param boolean $includeCollections (optional)
101
+     * @return mixed Return depends on format
102
+     * @deprecated TESTS ONLY - this methods is only used by tests
103
+     * called like this:
104
+     * \OC\Share\Share::getItemsSharedWith('folder'); (apps/files_sharing/tests/UpdaterTest.php)
105
+     */
106
+    public static function getItemsSharedWith() {
107
+        return self::getItems('folder', null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, self::FORMAT_NONE,
108
+            null, -1, false);
109
+    }
110
+
111
+    /**
112
+     * Get the items of item type shared with a user
113
+     * @param string $itemType
114
+     * @param string $user id for which user we want the shares
115
+     * @param int $format (optional) Format type must be defined by the backend
116
+     * @param mixed $parameters (optional)
117
+     * @param int $limit Number of items to return (optional) Returns all by default
118
+     * @param boolean $includeCollections (optional)
119
+     * @return mixed Return depends on format
120
+     */
121
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
122
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
123
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
124
+            $parameters, $limit, $includeCollections);
125
+    }
126
+
127
+    /**
128
+     * Get the item of item type shared with a given user by source
129
+     * @param string $itemType
130
+     * @param string $itemSource
131
+     * @param string $user User to whom the item was shared
132
+     * @param string $owner Owner of the share
133
+     * @param int $shareType only look for a specific share type
134
+     * @return array Return list of items with file_target, permissions and expiration
135
+     */
136
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
137
+        $shares = [];
138
+        $fileDependent = false;
139
+
140
+        $where = 'WHERE';
141
+        $fileDependentWhere = '';
142
+        if ($itemType === 'file' || $itemType === 'folder') {
143
+            $fileDependent = true;
144
+            $column = 'file_source';
145
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
146
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
147
+        } else {
148
+            $column = 'item_source';
149
+        }
150
+
151
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
152
+
153
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
154
+        $arguments = [$itemSource, $itemType];
155
+        // for link shares $user === null
156
+        if ($user !== null) {
157
+            $where .= ' AND `share_with` = ? ';
158
+            $arguments[] = $user;
159
+        }
160
+
161
+        if ($shareType !== null) {
162
+            $where .= ' AND `share_type` = ? ';
163
+            $arguments[] = $shareType;
164
+        }
165
+
166
+        if ($owner !== null) {
167
+            $where .= ' AND `uid_owner` = ? ';
168
+            $arguments[] = $owner;
169
+        }
170
+
171
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
172
+
173
+        $result = \OC_DB::executeAudited($query, $arguments);
174
+
175
+        while ($row = $result->fetchRow()) {
176
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
177
+                continue;
178
+            }
179
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
180
+                // if it is a mount point we need to get the path from the mount manager
181
+                $mountManager = \OC\Files\Filesystem::getMountManager();
182
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
183
+                if (!empty($mountPoint)) {
184
+                    $path = $mountPoint[0]->getMountPoint();
185
+                    $path = trim($path, '/');
186
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
187
+                    $row['path'] = $path;
188
+                } else {
189
+                    \OC::$server->getLogger()->warning(
190
+                        'Could not resolve mount point for ' . $row['storage_id'],
191
+                        ['app' => 'OCP\Share']
192
+                    );
193
+                }
194
+            }
195
+            $shares[] = $row;
196
+        }
197
+
198
+        //if didn't found a result than let's look for a group share.
199
+        if (empty($shares) && $user !== null) {
200
+            $userObject = \OC::$server->getUserManager()->get($user);
201
+            $groups = [];
202
+            if ($userObject) {
203
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
204
+            }
205
+
206
+            if (!empty($groups)) {
207
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
208
+                $arguments = [$itemSource, $itemType, $groups];
209
+                $types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
210
+
211
+                if ($owner !== null) {
212
+                    $where .= ' AND `uid_owner` = ?';
213
+                    $arguments[] = $owner;
214
+                    $types[] = null;
215
+                }
216
+
217
+                // TODO: inject connection, hopefully one day in the future when this
218
+                // class isn't static anymore...
219
+                $conn = \OC::$server->getDatabaseConnection();
220
+                $result = $conn->executeQuery(
221
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
222
+                    $arguments,
223
+                    $types
224
+                );
225
+
226
+                while ($row = $result->fetch()) {
227
+                    $shares[] = $row;
228
+                }
229
+            }
230
+        }
231
+
232
+        return $shares;
233
+    }
234
+
235
+    /**
236
+     * Get the item of item type shared with the current user by source
237
+     * @param string $itemType
238
+     * @param string $itemSource
239
+     * @param int $format (optional) Format type must be defined by the backend
240
+     * @param mixed $parameters
241
+     * @param boolean $includeCollections
242
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
243
+     * @return array
244
+     */
245
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
246
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
247
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
248
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
249
+            $parameters, 1, $includeCollections, true);
250
+    }
251
+
252
+    /**
253
+     * Get the shared item of item type owned by the current user
254
+     * @param string $itemType
255
+     * @param string $itemSource
256
+     * @param int $format (optional) Format type must be defined by the backend
257
+     * @param mixed $parameters
258
+     * @param boolean $includeCollections
259
+     * @return mixed Return depends on format
260
+     */
261
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
262
+                                            $parameters = null, $includeCollections = false) {
263
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
264
+            $parameters, -1, $includeCollections);
265
+    }
266
+
267
+    /**
268
+     * Unshare an item from a user, group, or delete a private link
269
+     * @param string $itemType
270
+     * @param string $itemSource
271
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
272
+     * @param string $shareWith User or group the item is being shared with
273
+     * @param string $owner owner of the share, if null the current user is used
274
+     * @return boolean true on success or false on failure
275
+     */
276
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
277
+
278
+        // check if it is a valid itemType
279
+        self::getBackend($itemType);
280
+
281
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
282
+
283
+        $toDelete = [];
284
+        $newParent = null;
285
+        $currentUser = $owner ? $owner : \OC_User::getUser();
286
+        foreach ($items as $item) {
287
+            // delete the item with the expected share_type and owner
288
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
289
+                $toDelete = $item;
290
+            // if there is more then one result we don't have to delete the children
291
+                // but update their parent. For group shares the new parent should always be
292
+                // the original group share and not the db entry with the unique name
293
+            } elseif ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
294
+                $newParent = $item['parent'];
295
+            } else {
296
+                $newParent = $item['id'];
297
+            }
298
+        }
299
+
300
+        if (!empty($toDelete)) {
301
+            self::unshareItem($toDelete, $newParent);
302
+            return true;
303
+        }
304
+        return false;
305
+    }
306
+
307
+    /**
308
+     * Checks whether a share has expired, calls unshareItem() if yes.
309
+     * @param array $item Share data (usually database row)
310
+     * @return boolean True if item was expired, false otherwise.
311
+     */
312
+    protected static function expireItem(array $item) {
313
+        $result = false;
314
+
315
+        // only use default expiration date for link shares
316
+        if ((int) $item['share_type'] === IShare::TYPE_LINK) {
317
+
318
+            // calculate expiration date
319
+            if (!empty($item['expiration'])) {
320
+                $userDefinedExpire = new \DateTime($item['expiration']);
321
+                $expires = $userDefinedExpire->getTimestamp();
322
+            } else {
323
+                $expires = null;
324
+            }
325
+
326
+
327
+            // get default expiration settings
328
+            $defaultSettings = Helper::getDefaultExpireSetting();
329
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
330
+
331
+
332
+            if (is_int($expires)) {
333
+                $now = time();
334
+                if ($now > $expires) {
335
+                    self::unshareItem($item);
336
+                    $result = true;
337
+                }
338
+            }
339
+        }
340
+        return $result;
341
+    }
342
+
343
+    /**
344
+     * Unshares a share given a share data array
345
+     * @param array $item Share data (usually database row)
346
+     * @param int $newParent parent ID
347
+     * @return null
348
+     */
349
+    protected static function unshareItem(array $item, $newParent = null) {
350
+        $shareType = (int)$item['share_type'];
351
+        $shareWith = null;
352
+        if ($shareType !== IShare::TYPE_LINK) {
353
+            $shareWith = $item['share_with'];
354
+        }
355
+
356
+        // Pass all the vars we have for now, they may be useful
357
+        $hookParams = [
358
+            'id' => $item['id'],
359
+            'itemType' => $item['item_type'],
360
+            'itemSource' => $item['item_source'],
361
+            'shareType' => $shareType,
362
+            'shareWith' => $shareWith,
363
+            'itemParent' => $item['parent'],
364
+            'uidOwner' => $item['uid_owner'],
365
+        ];
366
+        if ($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
367
+            $hookParams['fileSource'] = $item['file_source'];
368
+            $hookParams['fileTarget'] = $item['file_target'];
369
+        }
370
+
371
+        \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
372
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
373
+        $deletedShares[] = $hookParams;
374
+        $hookParams['deletedShares'] = $deletedShares;
375
+        \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
376
+        if ((int)$item['share_type'] === IShare::TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
377
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
378
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
379
+        }
380
+    }
381
+
382
+    /**
383
+     * Get the backend class for the specified item type
384
+     * @param string $itemType
385
+     * @throws \Exception
386
+     * @return \OCP\Share_Backend
387
+     */
388
+    public static function getBackend($itemType) {
389
+        $l = \OC::$server->getL10N('lib');
390
+        if (isset(self::$backends[$itemType])) {
391
+            return self::$backends[$itemType];
392
+        } elseif (isset(self::$backendTypes[$itemType]['class'])) {
393
+            $class = self::$backendTypes[$itemType]['class'];
394
+            if (class_exists($class)) {
395
+                self::$backends[$itemType] = new $class;
396
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
397
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
398
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', [$class]);
399
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
400
+                    throw new \Exception($message_t);
401
+                }
402
+                return self::$backends[$itemType];
403
+            } else {
404
+                $message = 'Sharing backend %s not found';
405
+                $message_t = $l->t('Sharing backend %s not found', [$class]);
406
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
407
+                throw new \Exception($message_t);
408
+            }
409
+        }
410
+        $message = 'Sharing backend for %s not found';
411
+        $message_t = $l->t('Sharing backend for %s not found', [$itemType]);
412
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
413
+        throw new \Exception($message_t);
414
+    }
415
+
416
+    /**
417
+     * Check if resharing is allowed
418
+     * @return boolean true if allowed or false
419
+     *
420
+     * Resharing is allowed by default if not configured
421
+     */
422
+    public static function isResharingAllowed() {
423
+        if (!isset(self::$isResharingAllowed)) {
424
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
425
+                self::$isResharingAllowed = true;
426
+            } else {
427
+                self::$isResharingAllowed = false;
428
+            }
429
+        }
430
+        return self::$isResharingAllowed;
431
+    }
432
+
433
+    /**
434
+     * Get a list of collection item types for the specified item type
435
+     * @param string $itemType
436
+     * @return array
437
+     */
438
+    private static function getCollectionItemTypes($itemType) {
439
+        $collectionTypes = [$itemType];
440
+        foreach (self::$backendTypes as $type => $backend) {
441
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
442
+                $collectionTypes[] = $type;
443
+            }
444
+        }
445
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
446
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
447
+            unset($collectionTypes[0]);
448
+        }
449
+        // Return array if collections were found or the item type is a
450
+        // collection itself - collections can be inside collections
451
+        if (count($collectionTypes) > 0) {
452
+            return $collectionTypes;
453
+        }
454
+        return false;
455
+    }
456
+
457
+    /**
458
+     * Get shared items from the database
459
+     * @param string $itemType
460
+     * @param string $item Item source or target (optional)
461
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
462
+     * @param string $shareWith User or group the item is being shared with
463
+     * @param string $uidOwner User that is the owner of shared items (optional)
464
+     * @param int $format Format to convert items to with formatItems() (optional)
465
+     * @param mixed $parameters to pass to formatItems() (optional)
466
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
467
+     * @param boolean $includeCollections Include collection item types (optional)
468
+     * @param boolean $itemShareWithBySource (optional)
469
+     * @param boolean $checkExpireDate
470
+     * @return array
471
+     *
472
+     * See public functions getItem(s)... for parameter usage
473
+     *
474
+     */
475
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
476
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
477
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
478
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
479
+            return [];
480
+        }
481
+        $backend = self::getBackend($itemType);
482
+        $collectionTypes = false;
483
+        // Get filesystem root to add it to the file target and remove from the
484
+        // file source, match file_source with the file cache
485
+        if ($itemType == 'file' || $itemType == 'folder') {
486
+            if (!is_null($uidOwner)) {
487
+                $root = \OC\Files\Filesystem::getRoot();
488
+            } else {
489
+                $root = '';
490
+            }
491
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
492
+            if (!isset($item)) {
493
+                $where .= ' AND `file_target` IS NOT NULL ';
494
+            }
495
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
496
+            $fileDependent = true;
497
+            $queryArgs = [];
498
+        } else {
499
+            $fileDependent = false;
500
+            $root = '';
501
+            $collectionTypes = self::getCollectionItemTypes($itemType);
502
+            if ($includeCollections && !isset($item) && $collectionTypes) {
503
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
504
+                if (!in_array($itemType, $collectionTypes)) {
505
+                    $itemTypes = array_merge([$itemType], $collectionTypes);
506
+                } else {
507
+                    $itemTypes = $collectionTypes;
508
+                }
509
+                $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
510
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
511
+                $queryArgs = $itemTypes;
512
+            } else {
513
+                $where = ' WHERE `item_type` = ?';
514
+                $queryArgs = [$itemType];
515
+            }
516
+        }
517
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
518
+            $where .= ' AND `share_type` != ?';
519
+            $queryArgs[] = IShare::TYPE_LINK;
520
+        }
521
+        if (isset($shareType)) {
522
+            // Include all user and group items
523
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
524
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
525
+                $queryArgs[] = IShare::TYPE_USER;
526
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
527
+                $queryArgs[] = $shareWith;
528
+
529
+                $user = \OC::$server->getUserManager()->get($shareWith);
530
+                $groups = [];
531
+                if ($user) {
532
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
533
+                }
534
+                if (!empty($groups)) {
535
+                    $placeholders = implode(',', array_fill(0, count($groups), '?'));
536
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
537
+                    $queryArgs[] = IShare::TYPE_GROUP;
538
+                    $queryArgs = array_merge($queryArgs, $groups);
539
+                }
540
+                $where .= ')';
541
+                // Don't include own group shares
542
+                $where .= ' AND `uid_owner` != ?';
543
+                $queryArgs[] = $shareWith;
544
+            } else {
545
+                $where .= ' AND `share_type` = ?';
546
+                $queryArgs[] = $shareType;
547
+                if (isset($shareWith)) {
548
+                    $where .= ' AND `share_with` = ?';
549
+                    $queryArgs[] = $shareWith;
550
+                }
551
+            }
552
+        }
553
+        if (isset($uidOwner)) {
554
+            $where .= ' AND `uid_owner` = ?';
555
+            $queryArgs[] = $uidOwner;
556
+            if (!isset($shareType)) {
557
+                // Prevent unique user targets for group shares from being selected
558
+                $where .= ' AND `share_type` != ?';
559
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
560
+            }
561
+            if ($fileDependent) {
562
+                $column = 'file_source';
563
+            } else {
564
+                $column = 'item_source';
565
+            }
566
+        } else {
567
+            if ($fileDependent) {
568
+                $column = 'file_target';
569
+            } else {
570
+                $column = 'item_target';
571
+            }
572
+        }
573
+        if (isset($item)) {
574
+            $collectionTypes = self::getCollectionItemTypes($itemType);
575
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
576
+                $where .= ' AND (';
577
+            } else {
578
+                $where .= ' AND';
579
+            }
580
+            // If looking for own shared items, check item_source else check item_target
581
+            if (isset($uidOwner) || $itemShareWithBySource) {
582
+                // If item type is a file, file source needs to be checked in case the item was converted
583
+                if ($fileDependent) {
584
+                    $where .= ' `file_source` = ?';
585
+                    $column = 'file_source';
586
+                } else {
587
+                    $where .= ' `item_source` = ?';
588
+                    $column = 'item_source';
589
+                }
590
+            } else {
591
+                if ($fileDependent) {
592
+                    $where .= ' `file_target` = ?';
593
+                    $item = \OC\Files\Filesystem::normalizePath($item);
594
+                } else {
595
+                    $where .= ' `item_target` = ?';
596
+                }
597
+            }
598
+            $queryArgs[] = $item;
599
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
600
+                $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
601
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
602
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
603
+            }
604
+        }
605
+
606
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
607
+            // Make sure the unique user target is returned if it exists,
608
+            // unique targets should follow the group share in the database
609
+            // If the limit is not 1, the filtering can be done later
610
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
611
+        } else {
612
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
613
+        }
614
+
615
+        if ($limit != -1 && !$includeCollections) {
616
+            // The limit must be at least 3, because filtering needs to be done
617
+            if ($limit < 3) {
618
+                $queryLimit = 3;
619
+            } else {
620
+                $queryLimit = $limit;
621
+            }
622
+        } else {
623
+            $queryLimit = null;
624
+        }
625
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
626
+        $root = strlen($root);
627
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
628
+        $result = $query->execute($queryArgs);
629
+        if ($result === false) {
630
+            \OCP\Util::writeLog('OCP\Share',
631
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
632
+                ILogger::ERROR);
633
+        }
634
+        $items = [];
635
+        $targets = [];
636
+        $switchedItems = [];
637
+        $mounts = [];
638
+        while ($row = $result->fetchRow()) {
639
+            self::transformDBResults($row);
640
+            // Filter out duplicate group shares for users with unique targets
641
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
642
+                continue;
643
+            }
644
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
645
+                $row['share_type'] = IShare::TYPE_GROUP;
646
+                $row['unique_name'] = true; // remember that we use a unique name for this user
647
+                $row['share_with'] = $items[$row['parent']]['share_with'];
648
+                // if the group share was unshared from the user we keep the permission, otherwise
649
+                // we take the permission from the parent because this is always the up-to-date
650
+                // permission for the group share
651
+                if ($row['permissions'] > 0) {
652
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
653
+                }
654
+                // Remove the parent group share
655
+                unset($items[$row['parent']]);
656
+                if ($row['permissions'] == 0) {
657
+                    continue;
658
+                }
659
+            } elseif (!isset($uidOwner)) {
660
+                // Check if the same target already exists
661
+                if (isset($targets[$row['id']])) {
662
+                    // Check if the same owner shared with the user twice
663
+                    // through a group and user share - this is allowed
664
+                    $id = $targets[$row['id']];
665
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
666
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
667
+                        if ($items[$id]['share_type'] != IShare::TYPE_GROUP) {
668
+                            $items[$id]['share_type'] = IShare::TYPE_GROUP;
669
+                            $items[$id]['share_with'] = $row['share_with'];
670
+                        }
671
+                        // Switch ids if sharing permission is granted on only
672
+                        // one share to ensure correct parent is used if resharing
673
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
674
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
675
+                            $items[$row['id']] = $items[$id];
676
+                            $switchedItems[$id] = $row['id'];
677
+                            unset($items[$id]);
678
+                            $id = $row['id'];
679
+                        }
680
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
681
+                    }
682
+                    continue;
683
+                } elseif (!empty($row['parent'])) {
684
+                    $targets[$row['parent']] = $row['id'];
685
+                }
686
+            }
687
+            // Remove root from file source paths if retrieving own shared items
688
+            if (isset($uidOwner) && isset($row['path'])) {
689
+                if (isset($row['parent'])) {
690
+                    $query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
691
+                    $query->select('file_target')
692
+                        ->from('share')
693
+                        ->where($query->expr()->eq('id', $query->createNamedParameter($row['parent'])));
694
+
695
+                    $result = $query->execute();
696
+                    $parentRow = $result->fetch();
697
+                    $result->closeCursor();
698
+
699
+                    if ($parentRow === false) {
700
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
701
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
702
+                            ILogger::ERROR);
703
+                    } else {
704
+                        $tmpPath = $parentRow['file_target'];
705
+                        // find the right position where the row path continues from the target path
706
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
707
+                        $subPath = substr($row['path'], $pos);
708
+                        $splitPath = explode('/', $subPath);
709
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
710
+                            $tmpPath = $tmpPath . '/' . $pathPart;
711
+                        }
712
+                        $row['path'] = $tmpPath;
713
+                    }
714
+                } else {
715
+                    if (!isset($mounts[$row['storage']])) {
716
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
717
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
718
+                            $mounts[$row['storage']] = current($mountPoints);
719
+                        }
720
+                    }
721
+                    if (!empty($mounts[$row['storage']])) {
722
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
723
+                        $relPath = substr($path, $root); // path relative to data/user
724
+                        $row['path'] = rtrim($relPath, '/');
725
+                    }
726
+                }
727
+            }
728
+
729
+            if ($checkExpireDate) {
730
+                if (self::expireItem($row)) {
731
+                    continue;
732
+                }
733
+            }
734
+            // Check if resharing is allowed, if not remove share permission
735
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
736
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
737
+            }
738
+            // Add display names to result
739
+            $row['share_with_displayname'] = $row['share_with'];
740
+            if (isset($row['share_with']) && $row['share_with'] != '' &&
741
+                $row['share_type'] === IShare::TYPE_USER) {
742
+                $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
743
+                $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
744
+            } elseif (isset($row['share_with']) && $row['share_with'] != '' &&
745
+                $row['share_type'] === IShare::TYPE_REMOTE) {
746
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
747
+                foreach ($addressBookEntries as $entry) {
748
+                    foreach ($entry['CLOUD'] as $cloudID) {
749
+                        if ($cloudID === $row['share_with']) {
750
+                            $row['share_with_displayname'] = $entry['FN'];
751
+                        }
752
+                    }
753
+                }
754
+            }
755
+            if (isset($row['uid_owner']) && $row['uid_owner'] != '') {
756
+                $ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
757
+                $row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
758
+            }
759
+
760
+            if ($row['permissions'] > 0) {
761
+                $items[$row['id']] = $row;
762
+            }
763
+        }
764
+
765
+        // group items if we are looking for items shared with the current user
766
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
767
+            $items = self::groupItems($items, $itemType);
768
+        }
769
+
770
+        if (!empty($items)) {
771
+            $collectionItems = [];
772
+            foreach ($items as &$row) {
773
+                // Return only the item instead of a 2-dimensional array
774
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
775
+                    if ($format == self::FORMAT_NONE) {
776
+                        return $row;
777
+                    } else {
778
+                        break;
779
+                    }
780
+                }
781
+                // Check if this is a collection of the requested item type
782
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
783
+                    if (($collectionBackend = self::getBackend($row['item_type']))
784
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
785
+                        // Collections can be inside collections, check if the item is a collection
786
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
787
+                            $collectionItems[] = $row;
788
+                        } else {
789
+                            $collection = [];
790
+                            $collection['item_type'] = $row['item_type'];
791
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
792
+                                $collection['path'] = basename($row['path']);
793
+                            }
794
+                            $row['collection'] = $collection;
795
+                            // Fetch all of the children sources
796
+                            $children = $collectionBackend->getChildren($row[$column]);
797
+                            foreach ($children as $child) {
798
+                                $childItem = $row;
799
+                                $childItem['item_type'] = $itemType;
800
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
801
+                                    $childItem['item_source'] = $child['source'];
802
+                                    $childItem['item_target'] = $child['target'];
803
+                                }
804
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
805
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
806
+                                        $childItem['file_source'] = $child['source'];
807
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
808
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
809
+                                        $childItem['file_source'] = $meta['fileid'];
810
+                                    }
811
+                                    $childItem['file_target'] =
812
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
813
+                                }
814
+                                if (isset($item)) {
815
+                                    if ($childItem[$column] == $item) {
816
+                                        // Return only the item instead of a 2-dimensional array
817
+                                        if ($limit == 1) {
818
+                                            if ($format == self::FORMAT_NONE) {
819
+                                                return $childItem;
820
+                                            } else {
821
+                                                // Unset the items array and break out of both loops
822
+                                                $items = [];
823
+                                                $items[] = $childItem;
824
+                                                break 2;
825
+                                            }
826
+                                        } else {
827
+                                            $collectionItems[] = $childItem;
828
+                                        }
829
+                                    }
830
+                                } else {
831
+                                    $collectionItems[] = $childItem;
832
+                                }
833
+                            }
834
+                        }
835
+                    }
836
+                    // Remove collection item
837
+                    $toRemove = $row['id'];
838
+                    if (array_key_exists($toRemove, $switchedItems)) {
839
+                        $toRemove = $switchedItems[$toRemove];
840
+                    }
841
+                    unset($items[$toRemove]);
842
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
843
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
844
+                    // see github issue #10588 for more details
845
+                    // Need to find a solution which works for all back-ends
846
+                    $collectionBackend = self::getBackend($row['item_type']);
847
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
848
+                    foreach ($sharedParents as $parent) {
849
+                        $collectionItems[] = $parent;
850
+                    }
851
+                }
852
+            }
853
+            if (!empty($collectionItems)) {
854
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
855
+                $items = array_merge($items, $collectionItems);
856
+            }
857
+
858
+            // filter out invalid items, these can appear when subshare entries exist
859
+            // for a group in which the requested user isn't a member any more
860
+            $items = array_filter($items, function ($item) {
861
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
862
+            });
863
+
864
+            return self::formatResult($items, $column, $backend, $format, $parameters);
865
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
866
+            // FIXME: Thats a dirty hack to improve file sharing performance,
867
+            // see github issue #10588 for more details
868
+            // Need to find a solution which works for all back-ends
869
+            $collectionItems = [];
870
+            $collectionBackend = self::getBackend('folder');
871
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
872
+            foreach ($sharedParents as $parent) {
873
+                $collectionItems[] = $parent;
874
+            }
875
+            if ($limit === 1) {
876
+                return reset($collectionItems);
877
+            }
878
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
879
+        }
880
+
881
+        return [];
882
+    }
883
+
884
+    /**
885
+     * group items with link to the same source
886
+     *
887
+     * @param array $items
888
+     * @param string $itemType
889
+     * @return array of grouped items
890
+     */
891
+    protected static function groupItems($items, $itemType) {
892
+        $fileSharing = $itemType === 'file' || $itemType === 'folder';
893
+
894
+        $result = [];
895
+
896
+        foreach ($items as $item) {
897
+            $grouped = false;
898
+            foreach ($result as $key => $r) {
899
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
900
+                // only group shares if they already point to the same target, otherwise the file where shared
901
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
902
+                if (($fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
903
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
904
+                    // add the first item to the list of grouped shares
905
+                    if (!isset($result[$key]['grouped'])) {
906
+                        $result[$key]['grouped'][] = $result[$key];
907
+                    }
908
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
909
+                    $result[$key]['grouped'][] = $item;
910
+                    $grouped = true;
911
+                    break;
912
+                }
913
+            }
914
+
915
+            if (!$grouped) {
916
+                $result[] = $item;
917
+            }
918
+        }
919
+
920
+        return $result;
921
+    }
922
+
923
+    /**
924
+     * construct select statement
925
+     * @param int $format
926
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
927
+     * @param string $uidOwner
928
+     * @return string select statement
929
+     */
930
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
931
+        $select = '*';
932
+        if ($format == self::FORMAT_STATUSES) {
933
+            if ($fileDependent) {
934
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
935
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
936
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
937
+                    . '`uid_initiator`';
938
+            } else {
939
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
940
+            }
941
+        } else {
942
+            if (isset($uidOwner)) {
943
+                if ($fileDependent) {
944
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
945
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
946
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
947
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
948
+                } else {
949
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
950
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
951
+                }
952
+            } else {
953
+                if ($fileDependent) {
954
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
955
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
956
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
957
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
958
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
959
+                    } else {
960
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
961
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
962
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
963
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
964
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
965
+                    }
966
+                }
967
+            }
968
+        }
969
+        return $select;
970
+    }
971
+
972
+
973
+    /**
974
+     * transform db results
975
+     * @param array $row result
976
+     */
977
+    private static function transformDBResults(&$row) {
978
+        if (isset($row['id'])) {
979
+            $row['id'] = (int) $row['id'];
980
+        }
981
+        if (isset($row['share_type'])) {
982
+            $row['share_type'] = (int) $row['share_type'];
983
+        }
984
+        if (isset($row['parent'])) {
985
+            $row['parent'] = (int) $row['parent'];
986
+        }
987
+        if (isset($row['file_parent'])) {
988
+            $row['file_parent'] = (int) $row['file_parent'];
989
+        }
990
+        if (isset($row['file_source'])) {
991
+            $row['file_source'] = (int) $row['file_source'];
992
+        }
993
+        if (isset($row['permissions'])) {
994
+            $row['permissions'] = (int) $row['permissions'];
995
+        }
996
+        if (isset($row['storage'])) {
997
+            $row['storage'] = (int) $row['storage'];
998
+        }
999
+        if (isset($row['stime'])) {
1000
+            $row['stime'] = (int) $row['stime'];
1001
+        }
1002
+        if (isset($row['expiration']) && $row['share_type'] !== IShare::TYPE_LINK) {
1003
+            // discard expiration date for non-link shares, which might have been
1004
+            // set by ancient bugs
1005
+            $row['expiration'] = null;
1006
+        }
1007
+    }
1008
+
1009
+    /**
1010
+     * format result
1011
+     * @param array $items result
1012
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1013
+     * @param \OCP\Share_Backend $backend sharing backend
1014
+     * @param int $format
1015
+     * @param array $parameters additional format parameters
1016
+     * @return array format result
1017
+     */
1018
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1019
+        if ($format === self::FORMAT_NONE) {
1020
+            return $items;
1021
+        } elseif ($format === self::FORMAT_STATUSES) {
1022
+            $statuses = [];
1023
+            foreach ($items as $item) {
1024
+                if ($item['share_type'] === IShare::TYPE_LINK) {
1025
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1026
+                        continue;
1027
+                    }
1028
+                    $statuses[$item[$column]]['link'] = true;
1029
+                } elseif (!isset($statuses[$item[$column]])) {
1030
+                    $statuses[$item[$column]]['link'] = false;
1031
+                }
1032
+                if (!empty($item['file_target'])) {
1033
+                    $statuses[$item[$column]]['path'] = $item['path'];
1034
+                }
1035
+            }
1036
+            return $statuses;
1037
+        } else {
1038
+            return $backend->formatItems($items, $format, $parameters);
1039
+        }
1040
+    }
1041
+
1042
+    /**
1043
+     * remove protocol from URL
1044
+     *
1045
+     * @param string $url
1046
+     * @return string
1047
+     */
1048
+    public static function removeProtocolFromUrl($url) {
1049
+        if (strpos($url, 'https://') === 0) {
1050
+            return substr($url, strlen('https://'));
1051
+        } elseif (strpos($url, 'http://') === 0) {
1052
+            return substr($url, strlen('http://'));
1053
+        }
1054
+
1055
+        return $url;
1056
+    }
1057
+
1058
+    /**
1059
+     * try http post first with https and then with http as a fallback
1060
+     *
1061
+     * @param string $remoteDomain
1062
+     * @param string $urlSuffix
1063
+     * @param array $fields post parameters
1064
+     * @return array
1065
+     */
1066
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1067
+        $protocol = 'https://';
1068
+        $result = [
1069
+            'success' => false,
1070
+            'result' => '',
1071
+        ];
1072
+        $try = 0;
1073
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1074
+        while ($result['success'] === false && $try < 2) {
1075
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1076
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1077
+            $client = \OC::$server->getHTTPClientService()->newClient();
1078
+
1079
+            try {
1080
+                $response = $client->post(
1081
+                    $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1082
+                    [
1083
+                        'body' => $fields,
1084
+                        'connect_timeout' => 10,
1085
+                    ]
1086
+                );
1087
+
1088
+                $result = ['success' => true, 'result' => $response->getBody()];
1089
+            } catch (\Exception $e) {
1090
+                $result = ['success' => false, 'result' => $e->getMessage()];
1091
+            }
1092
+
1093
+            $try++;
1094
+            $protocol = 'http://';
1095
+        }
1096
+
1097
+        return $result;
1098
+    }
1099
+
1100
+    /**
1101
+     * send server-to-server unshare to remote server
1102
+     *
1103
+     * @param string $remote url
1104
+     * @param int $id share id
1105
+     * @param string $token
1106
+     * @return bool
1107
+     */
1108
+    private static function sendRemoteUnshare($remote, $id, $token) {
1109
+        $url = rtrim($remote, '/');
1110
+        $fields = ['token' => $token, 'format' => 'json'];
1111
+        $url = self::removeProtocolFromUrl($url);
1112
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
1113
+        $status = json_decode($result['result'], true);
1114
+
1115
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
1116
+    }
1117
+
1118
+    /**
1119
+     * @return int
1120
+     */
1121
+    public static function getExpireInterval() {
1122
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1123
+    }
1124
+
1125
+    /**
1126
+     * Checks whether the given path is reachable for the given owner
1127
+     *
1128
+     * @param string $path path relative to files
1129
+     * @param string $ownerStorageId storage id of the owner
1130
+     *
1131
+     * @return boolean true if file is reachable, false otherwise
1132
+     */
1133
+    private static function isFileReachable($path, $ownerStorageId) {
1134
+        // if outside the home storage, file is always considered reachable
1135
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
1136
+            substr($ownerStorageId, 0, 13) === 'object::user:'
1137
+        )) {
1138
+            return true;
1139
+        }
1140
+
1141
+        // if inside the home storage, the file has to be under "/files/"
1142
+        $path = ltrim($path, '/');
1143
+        if (substr($path, 0, 6) === 'files/') {
1144
+            return true;
1145
+        }
1146
+
1147
+        return false;
1148
+    }
1149 1149
 }
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 
151 151
 		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
152 152
 
153
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
153
+		$where .= ' `'.$column.'` = ? AND `item_type` = ? ';
154 154
 		$arguments = [$itemSource, $itemType];
155 155
 		// for link shares $user === null
156 156
 		if ($user !== null) {
@@ -168,7 +168,7 @@  discard block
 block discarded – undo
168 168
 			$arguments[] = $owner;
169 169
 		}
170 170
 
171
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
171
+		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$fileDependentWhere.$where);
172 172
 
173 173
 		$result = \OC_DB::executeAudited($query, $arguments);
174 174
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
177 177
 				continue;
178 178
 			}
179
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
179
+			if ($fileDependent && (int) $row['file_parent'] === -1) {
180 180
 				// if it is a mount point we need to get the path from the mount manager
181 181
 				$mountManager = \OC\Files\Filesystem::getMountManager();
182 182
 				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 					$row['path'] = $path;
188 188
 				} else {
189 189
 					\OC::$server->getLogger()->warning(
190
-						'Could not resolve mount point for ' . $row['storage_id'],
190
+						'Could not resolve mount point for '.$row['storage_id'],
191 191
 						['app' => 'OCP\Share']
192 192
 					);
193 193
 				}
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 			}
205 205
 
206 206
 			if (!empty($groups)) {
207
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
207
+				$where = $fileDependentWhere.' WHERE `'.$column.'` = ? AND `item_type` = ? AND `share_with` in (?)';
208 208
 				$arguments = [$itemSource, $itemType, $groups];
209 209
 				$types = [null, null, IQueryBuilder::PARAM_STR_ARRAY];
210 210
 
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 				// class isn't static anymore...
219 219
 				$conn = \OC::$server->getDatabaseConnection();
220 220
 				$result = $conn->executeQuery(
221
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
221
+					'SELECT '.$select.' FROM `*PREFIX*share` '.$where,
222 222
 					$arguments,
223 223
 					$types
224 224
 				);
@@ -285,12 +285,12 @@  discard block
 block discarded – undo
285 285
 		$currentUser = $owner ? $owner : \OC_User::getUser();
286 286
 		foreach ($items as $item) {
287 287
 			// delete the item with the expected share_type and owner
288
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
288
+			if ((int) $item['share_type'] === (int) $shareType && $item['uid_owner'] === $currentUser) {
289 289
 				$toDelete = $item;
290 290
 			// if there is more then one result we don't have to delete the children
291 291
 				// but update their parent. For group shares the new parent should always be
292 292
 				// the original group share and not the db entry with the unique name
293
-			} elseif ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
293
+			} elseif ((int) $item['share_type'] === self::$shareTypeGroupUserUnique) {
294 294
 				$newParent = $item['parent'];
295 295
 			} else {
296 296
 				$newParent = $item['id'];
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 	 * @return null
348 348
 	 */
349 349
 	protected static function unshareItem(array $item, $newParent = null) {
350
-		$shareType = (int)$item['share_type'];
350
+		$shareType = (int) $item['share_type'];
351 351
 		$shareWith = null;
352 352
 		if ($shareType !== IShare::TYPE_LINK) {
353 353
 			$shareWith = $item['share_with'];
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 		$deletedShares[] = $hookParams;
374 374
 		$hookParams['deletedShares'] = $deletedShares;
375 375
 		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
376
-		if ((int)$item['share_type'] === IShare::TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
376
+		if ((int) $item['share_type'] === IShare::TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
377 377
 			list(, $remote) = Helper::splitUserRemote($item['share_with']);
378 378
 			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
379 379
 		}
@@ -628,7 +628,7 @@  discard block
 block discarded – undo
628 628
 		$result = $query->execute($queryArgs);
629 629
 		if ($result === false) {
630 630
 			\OCP\Util::writeLog('OCP\Share',
631
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
631
+				\OC_DB::getErrorMessage().', select='.$select.' where=',
632 632
 				ILogger::ERROR);
633 633
 		}
634 634
 		$items = [];
@@ -670,14 +670,14 @@  discard block
 block discarded – undo
670 670
 						}
671 671
 						// Switch ids if sharing permission is granted on only
672 672
 						// one share to ensure correct parent is used if resharing
673
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
674
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
673
+						if (~(int) $items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
674
+							&& (int) $row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
675 675
 							$items[$row['id']] = $items[$id];
676 676
 							$switchedItems[$id] = $row['id'];
677 677
 							unset($items[$id]);
678 678
 							$id = $row['id'];
679 679
 						}
680
-						$items[$id]['permissions'] |= (int)$row['permissions'];
680
+						$items[$id]['permissions'] |= (int) $row['permissions'];
681 681
 					}
682 682
 					continue;
683 683
 				} elseif (!empty($row['parent'])) {
@@ -697,8 +697,8 @@  discard block
 block discarded – undo
697 697
 					$result->closeCursor();
698 698
 
699 699
 					if ($parentRow === false) {
700
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
701
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
700
+						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: '.
701
+							\OC_DB::getErrorMessage().', select='.$select.' where='.$where,
702 702
 							ILogger::ERROR);
703 703
 					} else {
704 704
 						$tmpPath = $parentRow['file_target'];
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
 						$subPath = substr($row['path'], $pos);
708 708
 						$splitPath = explode('/', $subPath);
709 709
 						foreach (array_slice($splitPath, 2) as $pathPart) {
710
-							$tmpPath = $tmpPath . '/' . $pathPart;
710
+							$tmpPath = $tmpPath.'/'.$pathPart;
711 711
 						}
712 712
 						$row['path'] = $tmpPath;
713 713
 					}
@@ -857,7 +857,7 @@  discard block
 block discarded – undo
857 857
 
858 858
 			// filter out invalid items, these can appear when subshare entries exist
859 859
 			// for a group in which the requested user isn't a member any more
860
-			$items = array_filter($items, function ($item) {
860
+			$items = array_filter($items, function($item) {
861 861
 				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
862 862
 			});
863 863
 
@@ -1015,7 +1015,7 @@  discard block
 block discarded – undo
1015 1015
 	 * @param array $parameters additional format parameters
1016 1016
 	 * @return array format result
1017 1017
 	 */
1018
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1018
+	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE, $parameters = null) {
1019 1019
 		if ($format === self::FORMAT_NONE) {
1020 1020
 			return $items;
1021 1021
 		} elseif ($format === self::FORMAT_STATUSES) {
@@ -1072,13 +1072,13 @@  discard block
 block discarded – undo
1072 1072
 		$try = 0;
1073 1073
 		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1074 1074
 		while ($result['success'] === false && $try < 2) {
1075
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1075
+			$federationEndpoints = $discoveryService->discover($protocol.$remoteDomain, 'FEDERATED_SHARING');
1076 1076
 			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1077 1077
 			$client = \OC::$server->getHTTPClientService()->newClient();
1078 1078
 
1079 1079
 			try {
1080 1080
 				$response = $client->post(
1081
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1081
+					$protocol.$remoteDomain.$endpoint.$urlSuffix.'?format='.self::RESPONSE_FORMAT,
1082 1082
 					[
1083 1083
 						'body' => $fields,
1084 1084
 						'connect_timeout' => 10,
@@ -1119,7 +1119,7 @@  discard block
 block discarded – undo
1119 1119
 	 * @return int
1120 1120
 	 */
1121 1121
 	public static function getExpireInterval() {
1122
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1122
+		return (int) \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
1123 1123
 	}
1124 1124
 
1125 1125
 	/**
Please login to merge, or discard this patch.