Completed
Pull Request — master (#9293)
by Blizzz
18:49
created
lib/private/Share/Share.php 1 patch
Indentation   +2067 added lines, -2067 removed lines patch added patch discarded remove patch
@@ -53,2081 +53,2081 @@
 block discarded – undo
53 53
  */
54 54
 class Share extends Constants {
55 55
 
56
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
57
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
58
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
59
-	 *
60
-	 * Check if permission is granted with And (&) e.g. Check if delete is
61
-	 * granted: if ($permissions & PERMISSION_DELETE)
62
-	 *
63
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
64
-	 * permission: $permissions &= ~PERMISSION_UPDATE
65
-	 *
66
-	 * Apps are required to handle permissions on their own, this class only
67
-	 * stores and manages the permissions of shares
68
-	 * @see lib/public/constants.php
69
-	 */
70
-
71
-	/**
72
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
73
-	 * @param string $itemType Item type
74
-	 * @param string $class Backend class
75
-	 * @param string $collectionOf (optional) Depends on item type
76
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
77
-	 * @return boolean true if backend is registered or false if error
78
-	 */
79
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
80
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
81
-			if (!isset(self::$backendTypes[$itemType])) {
82
-				self::$backendTypes[$itemType] = array(
83
-					'class' => $class,
84
-					'collectionOf' => $collectionOf,
85
-					'supportedFileExtensions' => $supportedFileExtensions
86
-				);
87
-				if(count(self::$backendTypes) === 1) {
88
-					Util::addScript('core', 'merged-share-backend');
89
-					\OC_Util::addStyle('core', 'share');
90
-				}
91
-				return true;
92
-			}
93
-			\OCP\Util::writeLog('OCP\Share',
94
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
95
-				.' is already registered for '.$itemType,
96
-				ILogger::WARN);
97
-		}
98
-		return false;
99
-	}
100
-
101
-	/**
102
-	 * Get the items of item type shared with the current user
103
-	 * @param string $itemType
104
-	 * @param int $format (optional) Format type must be defined by the backend
105
-	 * @param mixed $parameters (optional)
106
-	 * @param int $limit Number of items to return (optional) Returns all by default
107
-	 * @param boolean $includeCollections (optional)
108
-	 * @return mixed Return depends on format
109
-	 */
110
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
111
-											  $parameters = null, $limit = -1, $includeCollections = false) {
112
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
113
-			$parameters, $limit, $includeCollections);
114
-	}
115
-
116
-	/**
117
-	 * Get the items of item type shared with a user
118
-	 * @param string $itemType
119
-	 * @param string $user id for which user we want the shares
120
-	 * @param int $format (optional) Format type must be defined by the backend
121
-	 * @param mixed $parameters (optional)
122
-	 * @param int $limit Number of items to return (optional) Returns all by default
123
-	 * @param boolean $includeCollections (optional)
124
-	 * @return mixed Return depends on format
125
-	 */
126
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
127
-												  $parameters = null, $limit = -1, $includeCollections = false) {
128
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
129
-			$parameters, $limit, $includeCollections);
130
-	}
131
-
132
-	/**
133
-	 * Get the item of item type shared with a given user by source
134
-	 * @param string $itemType
135
-	 * @param string $itemSource
136
-	 * @param string $user User to whom the item was shared
137
-	 * @param string $owner Owner of the share
138
-	 * @param int $shareType only look for a specific share type
139
-	 * @return array Return list of items with file_target, permissions and expiration
140
-	 */
141
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
142
-		$shares = array();
143
-		$fileDependent = false;
144
-
145
-		$where = 'WHERE';
146
-		$fileDependentWhere = '';
147
-		if ($itemType === 'file' || $itemType === 'folder') {
148
-			$fileDependent = true;
149
-			$column = 'file_source';
150
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
151
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
152
-		} else {
153
-			$column = 'item_source';
154
-		}
155
-
156
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
157
-
158
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
159
-		$arguments = array($itemSource, $itemType);
160
-		// for link shares $user === null
161
-		if ($user !== null) {
162
-			$where .= ' AND `share_with` = ? ';
163
-			$arguments[] = $user;
164
-		}
165
-
166
-		if ($shareType !== null) {
167
-			$where .= ' AND `share_type` = ? ';
168
-			$arguments[] = $shareType;
169
-		}
170
-
171
-		if ($owner !== null) {
172
-			$where .= ' AND `uid_owner` = ? ';
173
-			$arguments[] = $owner;
174
-		}
175
-
176
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
177
-
178
-		$result = \OC_DB::executeAudited($query, $arguments);
179
-
180
-		while ($row = $result->fetchRow()) {
181
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
182
-				continue;
183
-			}
184
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
185
-				// if it is a mount point we need to get the path from the mount manager
186
-				$mountManager = \OC\Files\Filesystem::getMountManager();
187
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
188
-				if (!empty($mountPoint)) {
189
-					$path = $mountPoint[0]->getMountPoint();
190
-					$path = trim($path, '/');
191
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
192
-					$row['path'] = $path;
193
-				} else {
194
-					\OC::$server->getLogger()->warning(
195
-						'Could not resolve mount point for ' . $row['storage_id'],
196
-						['app' => 'OCP\Share']
197
-					);
198
-				}
199
-			}
200
-			$shares[] = $row;
201
-		}
202
-
203
-		//if didn't found a result than let's look for a group share.
204
-		if(empty($shares) && $user !== null) {
205
-			$userObject = \OC::$server->getUserManager()->get($user);
206
-			$groups = [];
207
-			if ($userObject) {
208
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
209
-			}
210
-
211
-			if (!empty($groups)) {
212
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
213
-				$arguments = array($itemSource, $itemType, $groups);
214
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
215
-
216
-				if ($owner !== null) {
217
-					$where .= ' AND `uid_owner` = ?';
218
-					$arguments[] = $owner;
219
-					$types[] = null;
220
-				}
221
-
222
-				// TODO: inject connection, hopefully one day in the future when this
223
-				// class isn't static anymore...
224
-				$conn = \OC::$server->getDatabaseConnection();
225
-				$result = $conn->executeQuery(
226
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
227
-					$arguments,
228
-					$types
229
-				);
230
-
231
-				while ($row = $result->fetch()) {
232
-					$shares[] = $row;
233
-				}
234
-			}
235
-		}
236
-
237
-		return $shares;
238
-
239
-	}
240
-
241
-	/**
242
-	 * Get the item of item type shared with the current user by source
243
-	 * @param string $itemType
244
-	 * @param string $itemSource
245
-	 * @param int $format (optional) Format type must be defined by the backend
246
-	 * @param mixed $parameters
247
-	 * @param boolean $includeCollections
248
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
249
-	 * @return array
250
-	 */
251
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
252
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
253
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
254
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
255
-			$parameters, 1, $includeCollections, true);
256
-	}
257
-
258
-	/**
259
-	 * Based on the given token the share information will be returned - password protected shares will be verified
260
-	 * @param string $token
261
-	 * @param bool $checkPasswordProtection
262
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
263
-	 */
264
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
265
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
266
-		$result = $query->execute(array($token));
267
-		if ($result === false) {
268
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, ILogger::ERROR);
269
-		}
270
-		$row = $result->fetchRow();
271
-		if ($row === false) {
272
-			return false;
273
-		}
274
-		if (is_array($row) and self::expireItem($row)) {
275
-			return false;
276
-		}
277
-
278
-		// password protected shares need to be authenticated
279
-		if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
280
-			return false;
281
-		}
282
-
283
-		return $row;
284
-	}
285
-
286
-	/**
287
-	 * Get the shared items of item type owned by the current user
288
-	 * @param string $itemType
289
-	 * @param int $format (optional) Format type must be defined by the backend
290
-	 * @param mixed $parameters
291
-	 * @param int $limit Number of items to return (optional) Returns all by default
292
-	 * @param boolean $includeCollections
293
-	 * @return mixed Return depends on format
294
-	 */
295
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
296
-										  $limit = -1, $includeCollections = false) {
297
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
298
-			$parameters, $limit, $includeCollections);
299
-	}
300
-
301
-	/**
302
-	 * Get the shared item of item type owned by the current user
303
-	 * @param string $itemType
304
-	 * @param string $itemSource
305
-	 * @param int $format (optional) Format type must be defined by the backend
306
-	 * @param mixed $parameters
307
-	 * @param boolean $includeCollections
308
-	 * @return mixed Return depends on format
309
-	 */
310
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
311
-										 $parameters = null, $includeCollections = false) {
312
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
313
-			$parameters, -1, $includeCollections);
314
-	}
315
-
316
-	/**
317
-	 * Share an item with a user, group, or via private link
318
-	 * @param string $itemType
319
-	 * @param string $itemSource
320
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
321
-	 * @param string $shareWith User or group the item is being shared with
322
-	 * @param int $permissions CRUDS
323
-	 * @param string $itemSourceName
324
-	 * @param \DateTime|null $expirationDate
325
-	 * @param bool|null $passwordChanged
326
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
327
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
328
-	 * @throws \Exception
329
-	 * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
330
-	 */
331
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
332
-
333
-		$backend = self::getBackend($itemType);
334
-		$l = \OC::$server->getL10N('lib');
335
-
336
-		if ($backend->isShareTypeAllowed($shareType) === false) {
337
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
338
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
339
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), ILogger::DEBUG);
340
-			throw new \Exception($message_t);
341
-		}
342
-
343
-		$uidOwner = \OC_User::getUser();
344
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
345
-
346
-		if (is_null($itemSourceName)) {
347
-			$itemSourceName = $itemSource;
348
-		}
349
-		$itemName = $itemSourceName;
350
-
351
-		// check if file can be shared
352
-		if ($itemType === 'file' or $itemType === 'folder') {
353
-			$path = \OC\Files\Filesystem::getPath($itemSource);
354
-			$itemName = $path;
355
-
356
-			// verify that the file exists before we try to share it
357
-			if (!$path) {
358
-				$message = 'Sharing %s failed, because the file does not exist';
359
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
360
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
361
-				throw new \Exception($message_t);
362
-			}
363
-			// verify that the user has share permission
364
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
365
-				$message = 'You are not allowed to share %s';
366
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
367
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), ILogger::DEBUG);
368
-				throw new \Exception($message_t);
369
-			}
370
-		}
371
-
372
-		//verify that we don't share a folder which already contains a share mount point
373
-		if ($itemType === 'folder') {
374
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
375
-			$mountManager = \OC\Files\Filesystem::getMountManager();
376
-			$mounts = $mountManager->findIn($path);
377
-			foreach ($mounts as $mount) {
378
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
379
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
380
-					\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
381
-					throw new \Exception($message);
382
-				}
383
-
384
-			}
385
-		}
386
-
387
-		// single file shares should never have delete permissions
388
-		if ($itemType === 'file') {
389
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
390
-		}
391
-
392
-		//Validate expirationDate
393
-		if ($expirationDate !== null) {
394
-			try {
395
-				/*
56
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
57
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
58
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
59
+     *
60
+     * Check if permission is granted with And (&) e.g. Check if delete is
61
+     * granted: if ($permissions & PERMISSION_DELETE)
62
+     *
63
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
64
+     * permission: $permissions &= ~PERMISSION_UPDATE
65
+     *
66
+     * Apps are required to handle permissions on their own, this class only
67
+     * stores and manages the permissions of shares
68
+     * @see lib/public/constants.php
69
+     */
70
+
71
+    /**
72
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
73
+     * @param string $itemType Item type
74
+     * @param string $class Backend class
75
+     * @param string $collectionOf (optional) Depends on item type
76
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
77
+     * @return boolean true if backend is registered or false if error
78
+     */
79
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
80
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') == 'yes') {
81
+            if (!isset(self::$backendTypes[$itemType])) {
82
+                self::$backendTypes[$itemType] = array(
83
+                    'class' => $class,
84
+                    'collectionOf' => $collectionOf,
85
+                    'supportedFileExtensions' => $supportedFileExtensions
86
+                );
87
+                if(count(self::$backendTypes) === 1) {
88
+                    Util::addScript('core', 'merged-share-backend');
89
+                    \OC_Util::addStyle('core', 'share');
90
+                }
91
+                return true;
92
+            }
93
+            \OCP\Util::writeLog('OCP\Share',
94
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
95
+                .' is already registered for '.$itemType,
96
+                ILogger::WARN);
97
+        }
98
+        return false;
99
+    }
100
+
101
+    /**
102
+     * Get the items of item type shared with the current user
103
+     * @param string $itemType
104
+     * @param int $format (optional) Format type must be defined by the backend
105
+     * @param mixed $parameters (optional)
106
+     * @param int $limit Number of items to return (optional) Returns all by default
107
+     * @param boolean $includeCollections (optional)
108
+     * @return mixed Return depends on format
109
+     */
110
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
111
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
112
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
113
+            $parameters, $limit, $includeCollections);
114
+    }
115
+
116
+    /**
117
+     * Get the items of item type shared with a user
118
+     * @param string $itemType
119
+     * @param string $user id for which user we want the shares
120
+     * @param int $format (optional) Format type must be defined by the backend
121
+     * @param mixed $parameters (optional)
122
+     * @param int $limit Number of items to return (optional) Returns all by default
123
+     * @param boolean $includeCollections (optional)
124
+     * @return mixed Return depends on format
125
+     */
126
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
127
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
128
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
129
+            $parameters, $limit, $includeCollections);
130
+    }
131
+
132
+    /**
133
+     * Get the item of item type shared with a given user by source
134
+     * @param string $itemType
135
+     * @param string $itemSource
136
+     * @param string $user User to whom the item was shared
137
+     * @param string $owner Owner of the share
138
+     * @param int $shareType only look for a specific share type
139
+     * @return array Return list of items with file_target, permissions and expiration
140
+     */
141
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
142
+        $shares = array();
143
+        $fileDependent = false;
144
+
145
+        $where = 'WHERE';
146
+        $fileDependentWhere = '';
147
+        if ($itemType === 'file' || $itemType === 'folder') {
148
+            $fileDependent = true;
149
+            $column = 'file_source';
150
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
151
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
152
+        } else {
153
+            $column = 'item_source';
154
+        }
155
+
156
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
157
+
158
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
159
+        $arguments = array($itemSource, $itemType);
160
+        // for link shares $user === null
161
+        if ($user !== null) {
162
+            $where .= ' AND `share_with` = ? ';
163
+            $arguments[] = $user;
164
+        }
165
+
166
+        if ($shareType !== null) {
167
+            $where .= ' AND `share_type` = ? ';
168
+            $arguments[] = $shareType;
169
+        }
170
+
171
+        if ($owner !== null) {
172
+            $where .= ' AND `uid_owner` = ? ';
173
+            $arguments[] = $owner;
174
+        }
175
+
176
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
177
+
178
+        $result = \OC_DB::executeAudited($query, $arguments);
179
+
180
+        while ($row = $result->fetchRow()) {
181
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
182
+                continue;
183
+            }
184
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
185
+                // if it is a mount point we need to get the path from the mount manager
186
+                $mountManager = \OC\Files\Filesystem::getMountManager();
187
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
188
+                if (!empty($mountPoint)) {
189
+                    $path = $mountPoint[0]->getMountPoint();
190
+                    $path = trim($path, '/');
191
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
192
+                    $row['path'] = $path;
193
+                } else {
194
+                    \OC::$server->getLogger()->warning(
195
+                        'Could not resolve mount point for ' . $row['storage_id'],
196
+                        ['app' => 'OCP\Share']
197
+                    );
198
+                }
199
+            }
200
+            $shares[] = $row;
201
+        }
202
+
203
+        //if didn't found a result than let's look for a group share.
204
+        if(empty($shares) && $user !== null) {
205
+            $userObject = \OC::$server->getUserManager()->get($user);
206
+            $groups = [];
207
+            if ($userObject) {
208
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
209
+            }
210
+
211
+            if (!empty($groups)) {
212
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
213
+                $arguments = array($itemSource, $itemType, $groups);
214
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
215
+
216
+                if ($owner !== null) {
217
+                    $where .= ' AND `uid_owner` = ?';
218
+                    $arguments[] = $owner;
219
+                    $types[] = null;
220
+                }
221
+
222
+                // TODO: inject connection, hopefully one day in the future when this
223
+                // class isn't static anymore...
224
+                $conn = \OC::$server->getDatabaseConnection();
225
+                $result = $conn->executeQuery(
226
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
227
+                    $arguments,
228
+                    $types
229
+                );
230
+
231
+                while ($row = $result->fetch()) {
232
+                    $shares[] = $row;
233
+                }
234
+            }
235
+        }
236
+
237
+        return $shares;
238
+
239
+    }
240
+
241
+    /**
242
+     * Get the item of item type shared with the current user by source
243
+     * @param string $itemType
244
+     * @param string $itemSource
245
+     * @param int $format (optional) Format type must be defined by the backend
246
+     * @param mixed $parameters
247
+     * @param boolean $includeCollections
248
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
249
+     * @return array
250
+     */
251
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
252
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
253
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
254
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
255
+            $parameters, 1, $includeCollections, true);
256
+    }
257
+
258
+    /**
259
+     * Based on the given token the share information will be returned - password protected shares will be verified
260
+     * @param string $token
261
+     * @param bool $checkPasswordProtection
262
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
263
+     */
264
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
265
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
266
+        $result = $query->execute(array($token));
267
+        if ($result === false) {
268
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, ILogger::ERROR);
269
+        }
270
+        $row = $result->fetchRow();
271
+        if ($row === false) {
272
+            return false;
273
+        }
274
+        if (is_array($row) and self::expireItem($row)) {
275
+            return false;
276
+        }
277
+
278
+        // password protected shares need to be authenticated
279
+        if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
280
+            return false;
281
+        }
282
+
283
+        return $row;
284
+    }
285
+
286
+    /**
287
+     * Get the shared items of item type owned by the current user
288
+     * @param string $itemType
289
+     * @param int $format (optional) Format type must be defined by the backend
290
+     * @param mixed $parameters
291
+     * @param int $limit Number of items to return (optional) Returns all by default
292
+     * @param boolean $includeCollections
293
+     * @return mixed Return depends on format
294
+     */
295
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
296
+                                            $limit = -1, $includeCollections = false) {
297
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
298
+            $parameters, $limit, $includeCollections);
299
+    }
300
+
301
+    /**
302
+     * Get the shared item of item type owned by the current user
303
+     * @param string $itemType
304
+     * @param string $itemSource
305
+     * @param int $format (optional) Format type must be defined by the backend
306
+     * @param mixed $parameters
307
+     * @param boolean $includeCollections
308
+     * @return mixed Return depends on format
309
+     */
310
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
311
+                                            $parameters = null, $includeCollections = false) {
312
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
313
+            $parameters, -1, $includeCollections);
314
+    }
315
+
316
+    /**
317
+     * Share an item with a user, group, or via private link
318
+     * @param string $itemType
319
+     * @param string $itemSource
320
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
321
+     * @param string $shareWith User or group the item is being shared with
322
+     * @param int $permissions CRUDS
323
+     * @param string $itemSourceName
324
+     * @param \DateTime|null $expirationDate
325
+     * @param bool|null $passwordChanged
326
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
327
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
328
+     * @throws \Exception
329
+     * @since 5.0.0 - parameter $itemSourceName was added in 6.0.0, parameter $expirationDate was added in 7.0.0, parameter $passwordChanged added in 9.0.0
330
+     */
331
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
332
+
333
+        $backend = self::getBackend($itemType);
334
+        $l = \OC::$server->getL10N('lib');
335
+
336
+        if ($backend->isShareTypeAllowed($shareType) === false) {
337
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
338
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
339
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), ILogger::DEBUG);
340
+            throw new \Exception($message_t);
341
+        }
342
+
343
+        $uidOwner = \OC_User::getUser();
344
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
345
+
346
+        if (is_null($itemSourceName)) {
347
+            $itemSourceName = $itemSource;
348
+        }
349
+        $itemName = $itemSourceName;
350
+
351
+        // check if file can be shared
352
+        if ($itemType === 'file' or $itemType === 'folder') {
353
+            $path = \OC\Files\Filesystem::getPath($itemSource);
354
+            $itemName = $path;
355
+
356
+            // verify that the file exists before we try to share it
357
+            if (!$path) {
358
+                $message = 'Sharing %s failed, because the file does not exist';
359
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
360
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
361
+                throw new \Exception($message_t);
362
+            }
363
+            // verify that the user has share permission
364
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
365
+                $message = 'You are not allowed to share %s';
366
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
367
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), ILogger::DEBUG);
368
+                throw new \Exception($message_t);
369
+            }
370
+        }
371
+
372
+        //verify that we don't share a folder which already contains a share mount point
373
+        if ($itemType === 'folder') {
374
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
375
+            $mountManager = \OC\Files\Filesystem::getMountManager();
376
+            $mounts = $mountManager->findIn($path);
377
+            foreach ($mounts as $mount) {
378
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
379
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
380
+                    \OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
381
+                    throw new \Exception($message);
382
+                }
383
+
384
+            }
385
+        }
386
+
387
+        // single file shares should never have delete permissions
388
+        if ($itemType === 'file') {
389
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
390
+        }
391
+
392
+        //Validate expirationDate
393
+        if ($expirationDate !== null) {
394
+            try {
395
+                /*
396 396
 				 * Reuse the validateExpireDate.
397 397
 				 * We have to pass time() since the second arg is the time
398 398
 				 * the file was shared, since it is not shared yet we just use
399 399
 				 * the current time.
400 400
 				 */
401
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
402
-			} catch (\Exception $e) {
403
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
404
-			}
405
-		}
406
-
407
-		// Verify share type and sharing conditions are met
408
-		if ($shareType === self::SHARE_TYPE_USER) {
409
-			if ($shareWith == $uidOwner) {
410
-				$message = 'Sharing %s failed, because you can not share with yourself';
411
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
412
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
413
-				throw new \Exception($message_t);
414
-			}
415
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
416
-				$message = 'Sharing %s failed, because the user %s does not exist';
417
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
418
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
419
-				throw new \Exception($message_t);
420
-			}
421
-			if ($shareWithinGroupOnly) {
422
-				$userManager = \OC::$server->getUserManager();
423
-				$groupManager = \OC::$server->getGroupManager();
424
-				$userOwner = $userManager->get($uidOwner);
425
-				$userShareWith = $userManager->get($shareWith);
426
-				$groupsOwner = [];
427
-				$groupsShareWith = [];
428
-				if ($userOwner) {
429
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
430
-				}
431
-				if ($userShareWith) {
432
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
433
-				}
434
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
435
-				if (empty($inGroup)) {
436
-					$message = 'Sharing %s failed, because the user '
437
-						.'%s is not a member of any groups that %s is a member of';
438
-					$message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
439
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), ILogger::DEBUG);
440
-					throw new \Exception($message_t);
441
-				}
442
-			}
443
-			// Check if the item source is already shared with the user, either from the same owner or a different user
444
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
445
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
446
-				// Only allow the same share to occur again if it is the same
447
-				// owner and is not a user share, this use case is for increasing
448
-				// permissions for a specific user
449
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
450
-					$message = 'Sharing %s failed, because this item is already shared with %s';
451
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
452
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
453
-					throw new \Exception($message_t);
454
-				}
455
-			}
456
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
457
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
458
-				// Only allow the same share to occur again if it is the same
459
-				// owner and is not a user share, this use case is for increasing
460
-				// permissions for a specific user
461
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
462
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
463
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
464
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::ERROR);
465
-					throw new \Exception($message_t);
466
-				}
467
-			}
468
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
469
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
470
-				$message = 'Sharing %s failed, because the group %s does not exist';
471
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
472
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
473
-				throw new \Exception($message_t);
474
-			}
475
-			if ($shareWithinGroupOnly) {
476
-				$group = \OC::$server->getGroupManager()->get($shareWith);
477
-				$user = \OC::$server->getUserManager()->get($uidOwner);
478
-				if (!$group || !$user || !$group->inGroup($user)) {
479
-					$message = 'Sharing %s failed, because '
480
-						. '%s is not a member of the group %s';
481
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
482
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), ILogger::DEBUG);
483
-					throw new \Exception($message_t);
484
-				}
485
-			}
486
-			// Check if the item source is already shared with the group, either from the same owner or a different user
487
-			// The check for each user in the group is done inside the put() function
488
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
489
-				null, self::FORMAT_NONE, null, 1, true, true)) {
490
-
491
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
492
-					$message = 'Sharing %s failed, because this item is already shared with %s';
493
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
494
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
495
-					throw new \Exception($message_t);
496
-				}
497
-			}
498
-			// Convert share with into an array with the keys group and users
499
-			$group = $shareWith;
500
-			$shareWith = array();
501
-			$shareWith['group'] = $group;
502
-
503
-
504
-			$groupObject = \OC::$server->getGroupManager()->get($group);
505
-			$userIds = [];
506
-			if ($groupObject) {
507
-				$users = $groupObject->searchUsers('', -1, 0);
508
-				foreach ($users as $user) {
509
-					$userIds[] = $user->getUID();
510
-				}
511
-			}
512
-
513
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
514
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
515
-			$updateExistingShare = false;
516
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
517
-
518
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
519
-				if ($passwordChanged === true) {
520
-					self::verifyPassword($shareWith);
521
-				}
522
-
523
-				// when updating a link share
524
-				// FIXME Don't delete link if we update it
525
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
526
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
527
-					// remember old token
528
-					$oldToken = $checkExists['token'];
529
-					$oldPermissions = $checkExists['permissions'];
530
-					//delete the old share
531
-					Helper::delete($checkExists['id']);
532
-					$updateExistingShare = true;
533
-				}
534
-
535
-				if ($passwordChanged === null) {
536
-					// Generate hash of password - same method as user passwords
537
-					if (is_string($shareWith) && $shareWith !== '') {
538
-						self::verifyPassword($shareWith);
539
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
540
-					} else {
541
-						// reuse the already set password, but only if we change permissions
542
-						// otherwise the user disabled the password protection
543
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
544
-							$shareWith = $checkExists['share_with'];
545
-						}
546
-					}
547
-				} else {
548
-					if ($passwordChanged === true) {
549
-						if (is_string($shareWith) && $shareWith !== '') {
550
-							self::verifyPassword($shareWith);
551
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
552
-						}
553
-					} else if ($updateExistingShare) {
554
-						$shareWith = $checkExists['share_with'];
555
-					}
556
-				}
557
-
558
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
559
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
560
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
561
-					\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
562
-					throw new \Exception($message_t);
563
-				}
564
-
565
-				if ($updateExistingShare === false &&
566
-					self::isDefaultExpireDateEnabled() &&
567
-					empty($expirationDate)) {
568
-					$expirationDate = Helper::calcExpireDate();
569
-				}
570
-
571
-				// Generate token
572
-				if (isset($oldToken)) {
573
-					$token = $oldToken;
574
-				} else {
575
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
576
-						\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
577
-					);
578
-				}
579
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
580
-					null, $token, $itemSourceName, $expirationDate);
581
-				if ($result) {
582
-					return $token;
583
-				} else {
584
-					return false;
585
-				}
586
-			}
587
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
588
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
589
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
590
-			throw new \Exception($message_t);
591
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
592
-
593
-			/*
401
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
402
+            } catch (\Exception $e) {
403
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
404
+            }
405
+        }
406
+
407
+        // Verify share type and sharing conditions are met
408
+        if ($shareType === self::SHARE_TYPE_USER) {
409
+            if ($shareWith == $uidOwner) {
410
+                $message = 'Sharing %s failed, because you can not share with yourself';
411
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
412
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
413
+                throw new \Exception($message_t);
414
+            }
415
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
416
+                $message = 'Sharing %s failed, because the user %s does not exist';
417
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
418
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
419
+                throw new \Exception($message_t);
420
+            }
421
+            if ($shareWithinGroupOnly) {
422
+                $userManager = \OC::$server->getUserManager();
423
+                $groupManager = \OC::$server->getGroupManager();
424
+                $userOwner = $userManager->get($uidOwner);
425
+                $userShareWith = $userManager->get($shareWith);
426
+                $groupsOwner = [];
427
+                $groupsShareWith = [];
428
+                if ($userOwner) {
429
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
430
+                }
431
+                if ($userShareWith) {
432
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
433
+                }
434
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
435
+                if (empty($inGroup)) {
436
+                    $message = 'Sharing %s failed, because the user '
437
+                        .'%s is not a member of any groups that %s is a member of';
438
+                    $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemName, $shareWith, $uidOwner));
439
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), ILogger::DEBUG);
440
+                    throw new \Exception($message_t);
441
+                }
442
+            }
443
+            // Check if the item source is already shared with the user, either from the same owner or a different user
444
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
445
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
446
+                // Only allow the same share to occur again if it is the same
447
+                // owner and is not a user share, this use case is for increasing
448
+                // permissions for a specific user
449
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
450
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
451
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
452
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
453
+                    throw new \Exception($message_t);
454
+                }
455
+            }
456
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
457
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
458
+                // Only allow the same share to occur again if it is the same
459
+                // owner and is not a user share, this use case is for increasing
460
+                // permissions for a specific user
461
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
462
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
463
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
464
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::ERROR);
465
+                    throw new \Exception($message_t);
466
+                }
467
+            }
468
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
469
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
470
+                $message = 'Sharing %s failed, because the group %s does not exist';
471
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
472
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
473
+                throw new \Exception($message_t);
474
+            }
475
+            if ($shareWithinGroupOnly) {
476
+                $group = \OC::$server->getGroupManager()->get($shareWith);
477
+                $user = \OC::$server->getUserManager()->get($uidOwner);
478
+                if (!$group || !$user || !$group->inGroup($user)) {
479
+                    $message = 'Sharing %s failed, because '
480
+                        . '%s is not a member of the group %s';
481
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
482
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), ILogger::DEBUG);
483
+                    throw new \Exception($message_t);
484
+                }
485
+            }
486
+            // Check if the item source is already shared with the group, either from the same owner or a different user
487
+            // The check for each user in the group is done inside the put() function
488
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
489
+                null, self::FORMAT_NONE, null, 1, true, true)) {
490
+
491
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
492
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
493
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
494
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
495
+                    throw new \Exception($message_t);
496
+                }
497
+            }
498
+            // Convert share with into an array with the keys group and users
499
+            $group = $shareWith;
500
+            $shareWith = array();
501
+            $shareWith['group'] = $group;
502
+
503
+
504
+            $groupObject = \OC::$server->getGroupManager()->get($group);
505
+            $userIds = [];
506
+            if ($groupObject) {
507
+                $users = $groupObject->searchUsers('', -1, 0);
508
+                foreach ($users as $user) {
509
+                    $userIds[] = $user->getUID();
510
+                }
511
+            }
512
+
513
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
514
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
515
+            $updateExistingShare = false;
516
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
517
+
518
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
519
+                if ($passwordChanged === true) {
520
+                    self::verifyPassword($shareWith);
521
+                }
522
+
523
+                // when updating a link share
524
+                // FIXME Don't delete link if we update it
525
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
526
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
527
+                    // remember old token
528
+                    $oldToken = $checkExists['token'];
529
+                    $oldPermissions = $checkExists['permissions'];
530
+                    //delete the old share
531
+                    Helper::delete($checkExists['id']);
532
+                    $updateExistingShare = true;
533
+                }
534
+
535
+                if ($passwordChanged === null) {
536
+                    // Generate hash of password - same method as user passwords
537
+                    if (is_string($shareWith) && $shareWith !== '') {
538
+                        self::verifyPassword($shareWith);
539
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
540
+                    } else {
541
+                        // reuse the already set password, but only if we change permissions
542
+                        // otherwise the user disabled the password protection
543
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
544
+                            $shareWith = $checkExists['share_with'];
545
+                        }
546
+                    }
547
+                } else {
548
+                    if ($passwordChanged === true) {
549
+                        if (is_string($shareWith) && $shareWith !== '') {
550
+                            self::verifyPassword($shareWith);
551
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
552
+                        }
553
+                    } else if ($updateExistingShare) {
554
+                        $shareWith = $checkExists['share_with'];
555
+                    }
556
+                }
557
+
558
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
559
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
560
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
561
+                    \OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
562
+                    throw new \Exception($message_t);
563
+                }
564
+
565
+                if ($updateExistingShare === false &&
566
+                    self::isDefaultExpireDateEnabled() &&
567
+                    empty($expirationDate)) {
568
+                    $expirationDate = Helper::calcExpireDate();
569
+                }
570
+
571
+                // Generate token
572
+                if (isset($oldToken)) {
573
+                    $token = $oldToken;
574
+                } else {
575
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
576
+                        \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
577
+                    );
578
+                }
579
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
580
+                    null, $token, $itemSourceName, $expirationDate);
581
+                if ($result) {
582
+                    return $token;
583
+                } else {
584
+                    return false;
585
+                }
586
+            }
587
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
588
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
589
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
590
+            throw new \Exception($message_t);
591
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
592
+
593
+            /*
594 594
 			 * Check if file is not already shared with the remote user
595 595
 			 */
596
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
597
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
598
-					$message = 'Sharing %s failed, because this item is already shared with %s';
599
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
600
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
601
-					throw new \Exception($message_t);
602
-			}
603
-
604
-			// don't allow federated shares if source and target server are the same
605
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
606
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
607
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
608
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
609
-				$message = 'Not allowed to create a federated share with the same user.';
610
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
611
-				\OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
612
-				throw new \Exception($message_t);
613
-			}
614
-
615
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
616
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
617
-
618
-			$shareWith = $user . '@' . $remote;
619
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
620
-
621
-			$send = false;
622
-			if ($shareId) {
623
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
624
-			}
625
-
626
-			if ($send === false) {
627
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
628
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
629
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
630
-				throw new \Exception($message_t);
631
-			}
632
-
633
-			return $send;
634
-		} else {
635
-			// Future share types need to include their own conditions
636
-			$message = 'Share type %s is not valid for %s';
637
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
638
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), ILogger::DEBUG);
639
-			throw new \Exception($message_t);
640
-		}
641
-
642
-		// Put the item into the database
643
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
644
-
645
-		return $result ? true : false;
646
-	}
647
-
648
-	/**
649
-	 * Unshare an item from a user, group, or delete a private link
650
-	 * @param string $itemType
651
-	 * @param string $itemSource
652
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
653
-	 * @param string $shareWith User or group the item is being shared with
654
-	 * @param string $owner owner of the share, if null the current user is used
655
-	 * @return boolean true on success or false on failure
656
-	 */
657
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
658
-
659
-		// check if it is a valid itemType
660
-		self::getBackend($itemType);
661
-
662
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
663
-
664
-		$toDelete = array();
665
-		$newParent = null;
666
-		$currentUser = $owner ? $owner : \OC_User::getUser();
667
-		foreach ($items as $item) {
668
-			// delete the item with the expected share_type and owner
669
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
670
-				$toDelete = $item;
671
-				// if there is more then one result we don't have to delete the children
672
-				// but update their parent. For group shares the new parent should always be
673
-				// the original group share and not the db entry with the unique name
674
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
675
-				$newParent = $item['parent'];
676
-			} else {
677
-				$newParent = $item['id'];
678
-			}
679
-		}
680
-
681
-		if (!empty($toDelete)) {
682
-			self::unshareItem($toDelete, $newParent);
683
-			return true;
684
-		}
685
-		return false;
686
-	}
687
-
688
-	/**
689
-	 * sent status if users got informed by mail about share
690
-	 * @param string $itemType
691
-	 * @param string $itemSource
692
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
693
-	 * @param string $recipient with whom was the file shared
694
-	 * @param boolean $status
695
-	 */
696
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
697
-		$status = $status ? 1 : 0;
698
-
699
-		$query = \OC_DB::prepare(
700
-			'UPDATE `*PREFIX*share`
596
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
597
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
598
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
599
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
600
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
601
+                    throw new \Exception($message_t);
602
+            }
603
+
604
+            // don't allow federated shares if source and target server are the same
605
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
606
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
607
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
608
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
609
+                $message = 'Not allowed to create a federated share with the same user.';
610
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
611
+                \OCP\Util::writeLog('OCP\Share', $message, ILogger::DEBUG);
612
+                throw new \Exception($message_t);
613
+            }
614
+
615
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
616
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
617
+
618
+            $shareWith = $user . '@' . $remote;
619
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
620
+
621
+            $send = false;
622
+            if ($shareId) {
623
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
624
+            }
625
+
626
+            if ($send === false) {
627
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
628
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
629
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
630
+                throw new \Exception($message_t);
631
+            }
632
+
633
+            return $send;
634
+        } else {
635
+            // Future share types need to include their own conditions
636
+            $message = 'Share type %s is not valid for %s';
637
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
638
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), ILogger::DEBUG);
639
+            throw new \Exception($message_t);
640
+        }
641
+
642
+        // Put the item into the database
643
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
644
+
645
+        return $result ? true : false;
646
+    }
647
+
648
+    /**
649
+     * Unshare an item from a user, group, or delete a private link
650
+     * @param string $itemType
651
+     * @param string $itemSource
652
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
653
+     * @param string $shareWith User or group the item is being shared with
654
+     * @param string $owner owner of the share, if null the current user is used
655
+     * @return boolean true on success or false on failure
656
+     */
657
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
658
+
659
+        // check if it is a valid itemType
660
+        self::getBackend($itemType);
661
+
662
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
663
+
664
+        $toDelete = array();
665
+        $newParent = null;
666
+        $currentUser = $owner ? $owner : \OC_User::getUser();
667
+        foreach ($items as $item) {
668
+            // delete the item with the expected share_type and owner
669
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
670
+                $toDelete = $item;
671
+                // if there is more then one result we don't have to delete the children
672
+                // but update their parent. For group shares the new parent should always be
673
+                // the original group share and not the db entry with the unique name
674
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
675
+                $newParent = $item['parent'];
676
+            } else {
677
+                $newParent = $item['id'];
678
+            }
679
+        }
680
+
681
+        if (!empty($toDelete)) {
682
+            self::unshareItem($toDelete, $newParent);
683
+            return true;
684
+        }
685
+        return false;
686
+    }
687
+
688
+    /**
689
+     * sent status if users got informed by mail about share
690
+     * @param string $itemType
691
+     * @param string $itemSource
692
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
693
+     * @param string $recipient with whom was the file shared
694
+     * @param boolean $status
695
+     */
696
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
697
+        $status = $status ? 1 : 0;
698
+
699
+        $query = \OC_DB::prepare(
700
+            'UPDATE `*PREFIX*share`
701 701
 					SET `mail_send` = ?
702 702
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
703 703
 
704
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
705
-
706
-		if($result === false) {
707
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', ILogger::ERROR);
708
-		}
709
-	}
710
-
711
-	/**
712
-	 * validate expiration date if it meets all constraints
713
-	 *
714
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
715
-	 * @param string $shareTime timestamp when the file was shared
716
-	 * @param string $itemType
717
-	 * @param string $itemSource
718
-	 * @return \DateTime validated date
719
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
720
-	 */
721
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
722
-		$l = \OC::$server->getL10N('lib');
723
-		$date = new \DateTime($expireDate);
724
-		$today = new \DateTime('now');
725
-
726
-		// if the user doesn't provide a share time we need to get it from the database
727
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
728
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
729
-		if ($defaultExpireDateEnforced && $shareTime === null) {
730
-			$items = self::getItemShared($itemType, $itemSource);
731
-			$firstItem = reset($items);
732
-			$shareTime = (int)$firstItem['stime'];
733
-		}
734
-
735
-		if ($defaultExpireDateEnforced) {
736
-			// initialize max date with share time
737
-			$maxDate = new \DateTime();
738
-			$maxDate->setTimestamp($shareTime);
739
-			$maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
740
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
741
-			if ($date > $maxDate) {
742
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
743
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
744
-				\OCP\Util::writeLog('OCP\Share', $warning, ILogger::WARN);
745
-				throw new \Exception($warning_t);
746
-			}
747
-		}
748
-
749
-		if ($date < $today) {
750
-			$message = 'Cannot set expiration date. Expiration date is in the past';
751
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
752
-			\OCP\Util::writeLog('OCP\Share', $message, ILogger::WARN);
753
-			throw new \Exception($message_t);
754
-		}
755
-
756
-		return $date;
757
-	}
758
-
759
-	/**
760
-	 * Checks whether a share has expired, calls unshareItem() if yes.
761
-	 * @param array $item Share data (usually database row)
762
-	 * @return boolean True if item was expired, false otherwise.
763
-	 */
764
-	protected static function expireItem(array $item) {
765
-
766
-		$result = false;
767
-
768
-		// only use default expiration date for link shares
769
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
770
-
771
-			// calculate expiration date
772
-			if (!empty($item['expiration'])) {
773
-				$userDefinedExpire = new \DateTime($item['expiration']);
774
-				$expires = $userDefinedExpire->getTimestamp();
775
-			} else {
776
-				$expires = null;
777
-			}
778
-
779
-
780
-			// get default expiration settings
781
-			$defaultSettings = Helper::getDefaultExpireSetting();
782
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
783
-
784
-
785
-			if (is_int($expires)) {
786
-				$now = time();
787
-				if ($now > $expires) {
788
-					self::unshareItem($item);
789
-					$result = true;
790
-				}
791
-			}
792
-		}
793
-		return $result;
794
-	}
795
-
796
-	/**
797
-	 * Unshares a share given a share data array
798
-	 * @param array $item Share data (usually database row)
799
-	 * @param int $newParent parent ID
800
-	 * @return null
801
-	 */
802
-	protected static function unshareItem(array $item, $newParent = null) {
803
-
804
-		$shareType = (int)$item['share_type'];
805
-		$shareWith = null;
806
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
807
-			$shareWith = $item['share_with'];
808
-		}
809
-
810
-		// Pass all the vars we have for now, they may be useful
811
-		$hookParams = array(
812
-			'id'            => $item['id'],
813
-			'itemType'      => $item['item_type'],
814
-			'itemSource'    => $item['item_source'],
815
-			'shareType'     => $shareType,
816
-			'shareWith'     => $shareWith,
817
-			'itemParent'    => $item['parent'],
818
-			'uidOwner'      => $item['uid_owner'],
819
-		);
820
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
821
-			$hookParams['fileSource'] = $item['file_source'];
822
-			$hookParams['fileTarget'] = $item['file_target'];
823
-		}
824
-
825
-		\OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
826
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
827
-		$deletedShares[] = $hookParams;
828
-		$hookParams['deletedShares'] = $deletedShares;
829
-		\OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
830
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
831
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
832
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
833
-		}
834
-	}
835
-
836
-	/**
837
-	 * Get the backend class for the specified item type
838
-	 * @param string $itemType
839
-	 * @throws \Exception
840
-	 * @return \OCP\Share_Backend
841
-	 */
842
-	public static function getBackend($itemType) {
843
-		$l = \OC::$server->getL10N('lib');
844
-		if (isset(self::$backends[$itemType])) {
845
-			return self::$backends[$itemType];
846
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
847
-			$class = self::$backendTypes[$itemType]['class'];
848
-			if (class_exists($class)) {
849
-				self::$backends[$itemType] = new $class;
850
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
851
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
852
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
853
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
854
-					throw new \Exception($message_t);
855
-				}
856
-				return self::$backends[$itemType];
857
-			} else {
858
-				$message = 'Sharing backend %s not found';
859
-				$message_t = $l->t('Sharing backend %s not found', array($class));
860
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
861
-				throw new \Exception($message_t);
862
-			}
863
-		}
864
-		$message = 'Sharing backend for %s not found';
865
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
866
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
867
-		throw new \Exception($message_t);
868
-	}
869
-
870
-	/**
871
-	 * Check if resharing is allowed
872
-	 * @return boolean true if allowed or false
873
-	 *
874
-	 * Resharing is allowed by default if not configured
875
-	 */
876
-	public static function isResharingAllowed() {
877
-		if (!isset(self::$isResharingAllowed)) {
878
-			if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
879
-				self::$isResharingAllowed = true;
880
-			} else {
881
-				self::$isResharingAllowed = false;
882
-			}
883
-		}
884
-		return self::$isResharingAllowed;
885
-	}
886
-
887
-	/**
888
-	 * Get a list of collection item types for the specified item type
889
-	 * @param string $itemType
890
-	 * @return array
891
-	 */
892
-	private static function getCollectionItemTypes($itemType) {
893
-		$collectionTypes = array($itemType);
894
-		foreach (self::$backendTypes as $type => $backend) {
895
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
896
-				$collectionTypes[] = $type;
897
-			}
898
-		}
899
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
900
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
901
-			unset($collectionTypes[0]);
902
-		}
903
-		// Return array if collections were found or the item type is a
904
-		// collection itself - collections can be inside collections
905
-		if (count($collectionTypes) > 0) {
906
-			return $collectionTypes;
907
-		}
908
-		return false;
909
-	}
910
-
911
-	/**
912
-	 * Get the owners of items shared with a user.
913
-	 *
914
-	 * @param string $user The user the items are shared with.
915
-	 * @param string $type The type of the items shared with the user.
916
-	 * @param boolean $includeCollections Include collection item types (optional)
917
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
918
-	 * @return array
919
-	 */
920
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
921
-		// First, we find out if $type is part of a collection (and if that collection is part of
922
-		// another one and so on).
923
-		$collectionTypes = array();
924
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
925
-			$collectionTypes[] = $type;
926
-		}
927
-
928
-		// Of these collection types, along with our original $type, we make a
929
-		// list of the ones for which a sharing backend has been registered.
930
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
931
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
932
-		$allMaybeSharedItems = array();
933
-		foreach ($collectionTypes as $collectionType) {
934
-			if (isset(self::$backends[$collectionType])) {
935
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
936
-					$collectionType,
937
-					$user,
938
-					self::FORMAT_NONE
939
-				);
940
-			}
941
-		}
942
-
943
-		$owners = array();
944
-		if ($includeOwner) {
945
-			$owners[] = $user;
946
-		}
947
-
948
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
949
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
950
-		// and return them as elements of a list that look like "Tag (owner)".
951
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
952
-			foreach ($maybeSharedItems as $sharedItem) {
953
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
954
-					$owners[] = $sharedItem['uid_owner'];
955
-				}
956
-			}
957
-		}
958
-
959
-		return $owners;
960
-	}
961
-
962
-	/**
963
-	 * Get shared items from the database
964
-	 * @param string $itemType
965
-	 * @param string $item Item source or target (optional)
966
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
967
-	 * @param string $shareWith User or group the item is being shared with
968
-	 * @param string $uidOwner User that is the owner of shared items (optional)
969
-	 * @param int $format Format to convert items to with formatItems() (optional)
970
-	 * @param mixed $parameters to pass to formatItems() (optional)
971
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
972
-	 * @param boolean $includeCollections Include collection item types (optional)
973
-	 * @param boolean $itemShareWithBySource (optional)
974
-	 * @param boolean $checkExpireDate
975
-	 * @return array
976
-	 *
977
-	 * See public functions getItem(s)... for parameter usage
978
-	 *
979
-	 */
980
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
981
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
982
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
983
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
984
-			return array();
985
-		}
986
-		$backend = self::getBackend($itemType);
987
-		$collectionTypes = false;
988
-		// Get filesystem root to add it to the file target and remove from the
989
-		// file source, match file_source with the file cache
990
-		if ($itemType == 'file' || $itemType == 'folder') {
991
-			if(!is_null($uidOwner)) {
992
-				$root = \OC\Files\Filesystem::getRoot();
993
-			} else {
994
-				$root = '';
995
-			}
996
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
997
-			if (!isset($item)) {
998
-				$where .= ' AND `file_target` IS NOT NULL ';
999
-			}
1000
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1001
-			$fileDependent = true;
1002
-			$queryArgs = array();
1003
-		} else {
1004
-			$fileDependent = false;
1005
-			$root = '';
1006
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1007
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1008
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1009
-				if (!in_array($itemType, $collectionTypes)) {
1010
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1011
-				} else {
1012
-					$itemTypes = $collectionTypes;
1013
-				}
1014
-				$placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
1015
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1016
-				$queryArgs = $itemTypes;
1017
-			} else {
1018
-				$where = ' WHERE `item_type` = ?';
1019
-				$queryArgs = array($itemType);
1020
-			}
1021
-		}
1022
-		if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1023
-			$where .= ' AND `share_type` != ?';
1024
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1025
-		}
1026
-		if (isset($shareType)) {
1027
-			// Include all user and group items
1028
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1029
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1030
-				$queryArgs[] = self::SHARE_TYPE_USER;
1031
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1032
-				$queryArgs[] = $shareWith;
1033
-
1034
-				$user = \OC::$server->getUserManager()->get($shareWith);
1035
-				$groups = [];
1036
-				if ($user) {
1037
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1038
-				}
1039
-				if (!empty($groups)) {
1040
-					$placeholders = implode(',', array_fill(0, count($groups), '?'));
1041
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1042
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1043
-					$queryArgs = array_merge($queryArgs, $groups);
1044
-				}
1045
-				$where .= ')';
1046
-				// Don't include own group shares
1047
-				$where .= ' AND `uid_owner` != ?';
1048
-				$queryArgs[] = $shareWith;
1049
-			} else {
1050
-				$where .= ' AND `share_type` = ?';
1051
-				$queryArgs[] = $shareType;
1052
-				if (isset($shareWith)) {
1053
-					$where .= ' AND `share_with` = ?';
1054
-					$queryArgs[] = $shareWith;
1055
-				}
1056
-			}
1057
-		}
1058
-		if (isset($uidOwner)) {
1059
-			$where .= ' AND `uid_owner` = ?';
1060
-			$queryArgs[] = $uidOwner;
1061
-			if (!isset($shareType)) {
1062
-				// Prevent unique user targets for group shares from being selected
1063
-				$where .= ' AND `share_type` != ?';
1064
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1065
-			}
1066
-			if ($fileDependent) {
1067
-				$column = 'file_source';
1068
-			} else {
1069
-				$column = 'item_source';
1070
-			}
1071
-		} else {
1072
-			if ($fileDependent) {
1073
-				$column = 'file_target';
1074
-			} else {
1075
-				$column = 'item_target';
1076
-			}
1077
-		}
1078
-		if (isset($item)) {
1079
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1080
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1081
-				$where .= ' AND (';
1082
-			} else {
1083
-				$where .= ' AND';
1084
-			}
1085
-			// If looking for own shared items, check item_source else check item_target
1086
-			if (isset($uidOwner) || $itemShareWithBySource) {
1087
-				// If item type is a file, file source needs to be checked in case the item was converted
1088
-				if ($fileDependent) {
1089
-					$where .= ' `file_source` = ?';
1090
-					$column = 'file_source';
1091
-				} else {
1092
-					$where .= ' `item_source` = ?';
1093
-					$column = 'item_source';
1094
-				}
1095
-			} else {
1096
-				if ($fileDependent) {
1097
-					$where .= ' `file_target` = ?';
1098
-					$item = \OC\Files\Filesystem::normalizePath($item);
1099
-				} else {
1100
-					$where .= ' `item_target` = ?';
1101
-				}
1102
-			}
1103
-			$queryArgs[] = $item;
1104
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1105
-				$placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
1106
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1107
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1108
-			}
1109
-		}
1110
-
1111
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1112
-			// Make sure the unique user target is returned if it exists,
1113
-			// unique targets should follow the group share in the database
1114
-			// If the limit is not 1, the filtering can be done later
1115
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1116
-		} else {
1117
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1118
-		}
1119
-
1120
-		if ($limit != -1 && !$includeCollections) {
1121
-			// The limit must be at least 3, because filtering needs to be done
1122
-			if ($limit < 3) {
1123
-				$queryLimit = 3;
1124
-			} else {
1125
-				$queryLimit = $limit;
1126
-			}
1127
-		} else {
1128
-			$queryLimit = null;
1129
-		}
1130
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1131
-		$root = strlen($root);
1132
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1133
-		$result = $query->execute($queryArgs);
1134
-		if ($result === false) {
1135
-			\OCP\Util::writeLog('OCP\Share',
1136
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1137
-				ILogger::ERROR);
1138
-		}
1139
-		$items = array();
1140
-		$targets = array();
1141
-		$switchedItems = array();
1142
-		$mounts = array();
1143
-		while ($row = $result->fetchRow()) {
1144
-			self::transformDBResults($row);
1145
-			// Filter out duplicate group shares for users with unique targets
1146
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1147
-				continue;
1148
-			}
1149
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1150
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1151
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1152
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1153
-				// if the group share was unshared from the user we keep the permission, otherwise
1154
-				// we take the permission from the parent because this is always the up-to-date
1155
-				// permission for the group share
1156
-				if ($row['permissions'] > 0) {
1157
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1158
-				}
1159
-				// Remove the parent group share
1160
-				unset($items[$row['parent']]);
1161
-				if ($row['permissions'] == 0) {
1162
-					continue;
1163
-				}
1164
-			} else if (!isset($uidOwner)) {
1165
-				// Check if the same target already exists
1166
-				if (isset($targets[$row['id']])) {
1167
-					// Check if the same owner shared with the user twice
1168
-					// through a group and user share - this is allowed
1169
-					$id = $targets[$row['id']];
1170
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1171
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1172
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1173
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1174
-							$items[$id]['share_with'] = $row['share_with'];
1175
-						}
1176
-						// Switch ids if sharing permission is granted on only
1177
-						// one share to ensure correct parent is used if resharing
1178
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1179
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1180
-							$items[$row['id']] = $items[$id];
1181
-							$switchedItems[$id] = $row['id'];
1182
-							unset($items[$id]);
1183
-							$id = $row['id'];
1184
-						}
1185
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1186
-
1187
-					}
1188
-					continue;
1189
-				} elseif (!empty($row['parent'])) {
1190
-					$targets[$row['parent']] = $row['id'];
1191
-				}
1192
-			}
1193
-			// Remove root from file source paths if retrieving own shared items
1194
-			if (isset($uidOwner) && isset($row['path'])) {
1195
-				if (isset($row['parent'])) {
1196
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1197
-					$parentResult = $query->execute(array($row['parent']));
1198
-					if ($result === false) {
1199
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1200
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1201
-							ILogger::ERROR);
1202
-					} else {
1203
-						$parentRow = $parentResult->fetchRow();
1204
-						$tmpPath = $parentRow['file_target'];
1205
-						// find the right position where the row path continues from the target path
1206
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1207
-						$subPath = substr($row['path'], $pos);
1208
-						$splitPath = explode('/', $subPath);
1209
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1210
-							$tmpPath = $tmpPath . '/' . $pathPart;
1211
-						}
1212
-						$row['path'] = $tmpPath;
1213
-					}
1214
-				} else {
1215
-					if (!isset($mounts[$row['storage']])) {
1216
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1217
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1218
-							$mounts[$row['storage']] = current($mountPoints);
1219
-						}
1220
-					}
1221
-					if (!empty($mounts[$row['storage']])) {
1222
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1223
-						$relPath = substr($path, $root); // path relative to data/user
1224
-						$row['path'] = rtrim($relPath, '/');
1225
-					}
1226
-				}
1227
-			}
1228
-
1229
-			if($checkExpireDate) {
1230
-				if (self::expireItem($row)) {
1231
-					continue;
1232
-				}
1233
-			}
1234
-			// Check if resharing is allowed, if not remove share permission
1235
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1236
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1237
-			}
1238
-			// Add display names to result
1239
-			$row['share_with_displayname'] = $row['share_with'];
1240
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
1241
-				$row['share_type'] === self::SHARE_TYPE_USER) {
1242
-				$shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
1243
-				$row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
1244
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
1245
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
1246
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1247
-				foreach ($addressBookEntries as $entry) {
1248
-					foreach ($entry['CLOUD'] as $cloudID) {
1249
-						if ($cloudID === $row['share_with']) {
1250
-							$row['share_with_displayname'] = $entry['FN'];
1251
-						}
1252
-					}
1253
-				}
1254
-			}
1255
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1256
-				$ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
1257
-				$row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
1258
-			}
1259
-
1260
-			if ($row['permissions'] > 0) {
1261
-				$items[$row['id']] = $row;
1262
-			}
1263
-
1264
-		}
1265
-
1266
-		// group items if we are looking for items shared with the current user
1267
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1268
-			$items = self::groupItems($items, $itemType);
1269
-		}
1270
-
1271
-		if (!empty($items)) {
1272
-			$collectionItems = array();
1273
-			foreach ($items as &$row) {
1274
-				// Return only the item instead of a 2-dimensional array
1275
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1276
-					if ($format == self::FORMAT_NONE) {
1277
-						return $row;
1278
-					} else {
1279
-						break;
1280
-					}
1281
-				}
1282
-				// Check if this is a collection of the requested item type
1283
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1284
-					if (($collectionBackend = self::getBackend($row['item_type']))
1285
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1286
-						// Collections can be inside collections, check if the item is a collection
1287
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1288
-							$collectionItems[] = $row;
1289
-						} else {
1290
-							$collection = array();
1291
-							$collection['item_type'] = $row['item_type'];
1292
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1293
-								$collection['path'] = basename($row['path']);
1294
-							}
1295
-							$row['collection'] = $collection;
1296
-							// Fetch all of the children sources
1297
-							$children = $collectionBackend->getChildren($row[$column]);
1298
-							foreach ($children as $child) {
1299
-								$childItem = $row;
1300
-								$childItem['item_type'] = $itemType;
1301
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1302
-									$childItem['item_source'] = $child['source'];
1303
-									$childItem['item_target'] = $child['target'];
1304
-								}
1305
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1306
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1307
-										$childItem['file_source'] = $child['source'];
1308
-									} else { // TODO is this really needed if we already know that we use the file backend?
1309
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1310
-										$childItem['file_source'] = $meta['fileid'];
1311
-									}
1312
-									$childItem['file_target'] =
1313
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
1314
-								}
1315
-								if (isset($item)) {
1316
-									if ($childItem[$column] == $item) {
1317
-										// Return only the item instead of a 2-dimensional array
1318
-										if ($limit == 1) {
1319
-											if ($format == self::FORMAT_NONE) {
1320
-												return $childItem;
1321
-											} else {
1322
-												// Unset the items array and break out of both loops
1323
-												$items = array();
1324
-												$items[] = $childItem;
1325
-												break 2;
1326
-											}
1327
-										} else {
1328
-											$collectionItems[] = $childItem;
1329
-										}
1330
-									}
1331
-								} else {
1332
-									$collectionItems[] = $childItem;
1333
-								}
1334
-							}
1335
-						}
1336
-					}
1337
-					// Remove collection item
1338
-					$toRemove = $row['id'];
1339
-					if (array_key_exists($toRemove, $switchedItems)) {
1340
-						$toRemove = $switchedItems[$toRemove];
1341
-					}
1342
-					unset($items[$toRemove]);
1343
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1344
-					// FIXME: Thats a dirty hack to improve file sharing performance,
1345
-					// see github issue #10588 for more details
1346
-					// Need to find a solution which works for all back-ends
1347
-					$collectionBackend = self::getBackend($row['item_type']);
1348
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
1349
-					foreach ($sharedParents as $parent) {
1350
-						$collectionItems[] = $parent;
1351
-					}
1352
-				}
1353
-			}
1354
-			if (!empty($collectionItems)) {
1355
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
1356
-				$items = array_merge($items, $collectionItems);
1357
-			}
1358
-
1359
-			// filter out invalid items, these can appear when subshare entries exist
1360
-			// for a group in which the requested user isn't a member any more
1361
-			$items = array_filter($items, function($item) {
1362
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1363
-			});
1364
-
1365
-			return self::formatResult($items, $column, $backend, $format, $parameters);
1366
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1367
-			// FIXME: Thats a dirty hack to improve file sharing performance,
1368
-			// see github issue #10588 for more details
1369
-			// Need to find a solution which works for all back-ends
1370
-			$collectionItems = array();
1371
-			$collectionBackend = self::getBackend('folder');
1372
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1373
-			foreach ($sharedParents as $parent) {
1374
-				$collectionItems[] = $parent;
1375
-			}
1376
-			if ($limit === 1) {
1377
-				return reset($collectionItems);
1378
-			}
1379
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1380
-		}
1381
-
1382
-		return array();
1383
-	}
1384
-
1385
-	/**
1386
-	 * group items with link to the same source
1387
-	 *
1388
-	 * @param array $items
1389
-	 * @param string $itemType
1390
-	 * @return array of grouped items
1391
-	 */
1392
-	protected static function groupItems($items, $itemType) {
1393
-
1394
-		$fileSharing = $itemType === 'file' || $itemType === 'folder';
1395
-
1396
-		$result = array();
1397
-
1398
-		foreach ($items as $item) {
1399
-			$grouped = false;
1400
-			foreach ($result as $key => $r) {
1401
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1402
-				// only group shares if they already point to the same target, otherwise the file where shared
1403
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1404
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1405
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1406
-					// add the first item to the list of grouped shares
1407
-					if (!isset($result[$key]['grouped'])) {
1408
-						$result[$key]['grouped'][] = $result[$key];
1409
-					}
1410
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1411
-					$result[$key]['grouped'][] = $item;
1412
-					$grouped = true;
1413
-					break;
1414
-				}
1415
-			}
1416
-
1417
-			if (!$grouped) {
1418
-				$result[] = $item;
1419
-			}
1420
-
1421
-		}
1422
-
1423
-		return $result;
1424
-	}
1425
-
1426
-	/**
1427
-	 * Put shared item into the database
1428
-	 * @param string $itemType Item type
1429
-	 * @param string $itemSource Item source
1430
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1431
-	 * @param string $shareWith User or group the item is being shared with
1432
-	 * @param string $uidOwner User that is the owner of shared item
1433
-	 * @param int $permissions CRUDS permissions
1434
-	 * @param boolean|array $parentFolder Parent folder target (optional)
1435
-	 * @param string $token (optional)
1436
-	 * @param string $itemSourceName name of the source item (optional)
1437
-	 * @param \DateTime $expirationDate (optional)
1438
-	 * @throws \Exception
1439
-	 * @return mixed id of the new share or false
1440
-	 */
1441
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1442
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1443
-
1444
-		$queriesToExecute = array();
1445
-		$suggestedItemTarget = null;
1446
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1447
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1448
-
1449
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1450
-		if(!empty($result)) {
1451
-			$parent = $result['parent'];
1452
-			$itemSource = $result['itemSource'];
1453
-			$fileSource = $result['fileSource'];
1454
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1455
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1456
-			$filePath = $result['filePath'];
1457
-		}
1458
-
1459
-		$isGroupShare = false;
1460
-		if ($shareType == self::SHARE_TYPE_GROUP) {
1461
-			$isGroupShare = true;
1462
-			if (isset($shareWith['users'])) {
1463
-				$users = $shareWith['users'];
1464
-			} else {
1465
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
1466
-				if ($group) {
1467
-					$users = $group->searchUsers('', -1, 0);
1468
-					$userIds = [];
1469
-					foreach ($users as $user) {
1470
-						$userIds[] = $user->getUID();
1471
-					}
1472
-					$users = $userIds;
1473
-				} else {
1474
-					$users = [];
1475
-				}
1476
-			}
1477
-			// remove current user from list
1478
-			if (in_array(\OCP\User::getUser(), $users)) {
1479
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
1480
-			}
1481
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1482
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1483
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1484
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
1485
-
1486
-			// add group share to table and remember the id as parent
1487
-			$queriesToExecute['groupShare'] = array(
1488
-				'itemType'			=> $itemType,
1489
-				'itemSource'		=> $itemSource,
1490
-				'itemTarget'		=> $groupItemTarget,
1491
-				'shareType'			=> $shareType,
1492
-				'shareWith'			=> $shareWith['group'],
1493
-				'uidOwner'			=> $uidOwner,
1494
-				'permissions'		=> $permissions,
1495
-				'shareTime'			=> time(),
1496
-				'fileSource'		=> $fileSource,
1497
-				'fileTarget'		=> $groupFileTarget,
1498
-				'token'				=> $token,
1499
-				'parent'			=> $parent,
1500
-				'expiration'		=> $expirationDate,
1501
-			);
1502
-
1503
-		} else {
1504
-			$users = array($shareWith);
1505
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1506
-				$suggestedItemTarget);
1507
-		}
1508
-
1509
-		$run = true;
1510
-		$error = '';
1511
-		$preHookData = array(
1512
-			'itemType' => $itemType,
1513
-			'itemSource' => $itemSource,
1514
-			'shareType' => $shareType,
1515
-			'uidOwner' => $uidOwner,
1516
-			'permissions' => $permissions,
1517
-			'fileSource' => $fileSource,
1518
-			'expiration' => $expirationDate,
1519
-			'token' => $token,
1520
-			'run' => &$run,
1521
-			'error' => &$error
1522
-		);
1523
-
1524
-		$preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1525
-		$preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1526
-
1527
-		\OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1528
-
1529
-		if ($run === false) {
1530
-			throw new \Exception($error);
1531
-		}
1532
-
1533
-		foreach ($users as $user) {
1534
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1535
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1536
-
1537
-			$userShareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType;
1538
-
1539
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1540
-				$fileTarget = $sourceExists['file_target'];
1541
-				$itemTarget = $sourceExists['item_target'];
1542
-
1543
-				// for group shares we don't need a additional entry if the target is the same
1544
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
1545
-					continue;
1546
-				}
1547
-
1548
-			} elseif(!$sourceExists && !$isGroupShare)  {
1549
-
1550
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1551
-					$uidOwner, $suggestedItemTarget, $parent);
1552
-				if (isset($fileSource)) {
1553
-					if ($parentFolder) {
1554
-						if ($parentFolder === true) {
1555
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1556
-								$uidOwner, $suggestedFileTarget, $parent);
1557
-							if ($fileTarget != $groupFileTarget) {
1558
-								$parentFolders[$user]['folder'] = $fileTarget;
1559
-							}
1560
-						} else if (isset($parentFolder[$user])) {
1561
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
1562
-							$parent = $parentFolder[$user]['id'];
1563
-						}
1564
-					} else {
1565
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1566
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1567
-					}
1568
-				} else {
1569
-					$fileTarget = null;
1570
-				}
1571
-
1572
-			} else {
1573
-
1574
-				// group share which doesn't exists until now, check if we need a unique target for this user
1575
-
1576
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1577
-					$uidOwner, $suggestedItemTarget, $parent);
1578
-
1579
-				// do we also need a file target
1580
-				if (isset($fileSource)) {
1581
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1582
-						$uidOwner, $suggestedFileTarget, $parent);
1583
-				} else {
1584
-					$fileTarget = null;
1585
-				}
1586
-
1587
-				if (($itemTarget === $groupItemTarget) &&
1588
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1589
-					continue;
1590
-				}
1591
-			}
1592
-
1593
-			$queriesToExecute[] = array(
1594
-				'itemType'			=> $itemType,
1595
-				'itemSource'		=> $itemSource,
1596
-				'itemTarget'		=> $itemTarget,
1597
-				'shareType'			=> $userShareType,
1598
-				'shareWith'			=> $user,
1599
-				'uidOwner'			=> $uidOwner,
1600
-				'permissions'		=> $permissions,
1601
-				'shareTime'			=> time(),
1602
-				'fileSource'		=> $fileSource,
1603
-				'fileTarget'		=> $fileTarget,
1604
-				'token'				=> $token,
1605
-				'parent'			=> $parent,
1606
-				'expiration'		=> $expirationDate,
1607
-			);
1608
-
1609
-		}
1610
-
1611
-		$id = false;
1612
-		if ($isGroupShare) {
1613
-			$id = self::insertShare($queriesToExecute['groupShare']);
1614
-			// Save this id, any extra rows for this group share will need to reference it
1615
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1616
-			unset($queriesToExecute['groupShare']);
1617
-		}
1618
-
1619
-		foreach ($queriesToExecute as $shareQuery) {
1620
-			$shareQuery['parent'] = $parent;
1621
-			$id = self::insertShare($shareQuery);
1622
-		}
1623
-
1624
-		$postHookData = array(
1625
-			'itemType' => $itemType,
1626
-			'itemSource' => $itemSource,
1627
-			'parent' => $parent,
1628
-			'shareType' => $shareType,
1629
-			'uidOwner' => $uidOwner,
1630
-			'permissions' => $permissions,
1631
-			'fileSource' => $fileSource,
1632
-			'id' => $parent,
1633
-			'token' => $token,
1634
-			'expirationDate' => $expirationDate,
1635
-		);
1636
-
1637
-		$postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1638
-		$postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1639
-		$postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1640
-
1641
-		\OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1642
-
1643
-
1644
-		return $id ? $id : false;
1645
-	}
1646
-
1647
-	/**
1648
-	 * @param string $itemType
1649
-	 * @param string $itemSource
1650
-	 * @param int $shareType
1651
-	 * @param string $shareWith
1652
-	 * @param string $uidOwner
1653
-	 * @param int $permissions
1654
-	 * @param string|null $itemSourceName
1655
-	 * @param null|\DateTime $expirationDate
1656
-	 */
1657
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1658
-		$backend = self::getBackend($itemType);
1659
-
1660
-		$l = \OC::$server->getL10N('lib');
1661
-		$result = array();
1662
-
1663
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1664
-
1665
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1666
-		if ($checkReshare) {
1667
-			// Check if attempting to share back to owner
1668
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1669
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
1670
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1671
-
1672
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
1673
-				throw new \Exception($message_t);
1674
-			}
1675
-		}
1676
-
1677
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1678
-			// Check if share permissions is granted
1679
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1680
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1681
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1682
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1683
-
1684
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), ILogger::DEBUG);
1685
-					throw new \Exception($message_t);
1686
-				} else {
1687
-					// TODO Don't check if inside folder
1688
-					$result['parent'] = $checkReshare['id'];
1689
-
1690
-					$result['expirationDate'] = $expirationDate;
1691
-					// $checkReshare['expiration'] could be null and then is always less than any value
1692
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1693
-						$result['expirationDate'] = $checkReshare['expiration'];
1694
-					}
1695
-
1696
-					// only suggest the same name as new target if it is a reshare of the
1697
-					// same file/folder and not the reshare of a child
1698
-					if ($checkReshare[$column] === $itemSource) {
1699
-						$result['filePath'] = $checkReshare['file_target'];
1700
-						$result['itemSource'] = $checkReshare['item_source'];
1701
-						$result['fileSource'] = $checkReshare['file_source'];
1702
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1703
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1704
-					} else {
1705
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1706
-						$result['suggestedItemTarget'] = null;
1707
-						$result['suggestedFileTarget'] = null;
1708
-						$result['itemSource'] = $itemSource;
1709
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1710
-					}
1711
-				}
1712
-			} else {
1713
-				$message = 'Sharing %s failed, because resharing is not allowed';
1714
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1715
-
1716
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
1717
-				throw new \Exception($message_t);
1718
-			}
1719
-		} else {
1720
-			$result['parent'] = null;
1721
-			$result['suggestedItemTarget'] = null;
1722
-			$result['suggestedFileTarget'] = null;
1723
-			$result['itemSource'] = $itemSource;
1724
-			$result['expirationDate'] = $expirationDate;
1725
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1726
-				$message = 'Sharing %s failed, because the sharing backend for '
1727
-					.'%s could not find its source';
1728
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1729
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), ILogger::DEBUG);
1730
-				throw new \Exception($message_t);
1731
-			}
1732
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1733
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1734
-				if ($itemType == 'file' || $itemType == 'folder') {
1735
-					$result['fileSource'] = $itemSource;
1736
-				} else {
1737
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1738
-					$result['fileSource'] = $meta['fileid'];
1739
-				}
1740
-				if ($result['fileSource'] == -1) {
1741
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1742
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1743
-
1744
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), ILogger::DEBUG);
1745
-					throw new \Exception($message_t);
1746
-				}
1747
-			} else {
1748
-				$result['filePath'] = null;
1749
-				$result['fileSource'] = null;
1750
-			}
1751
-		}
1752
-
1753
-		return $result;
1754
-	}
1755
-
1756
-	/**
1757
-	 *
1758
-	 * @param array $shareData
1759
-	 * @return mixed false in case of a failure or the id of the new share
1760
-	 */
1761
-	private static function insertShare(array $shareData) {
1762
-
1763
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1764
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1765
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1766
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1767
-		$query->bindValue(1, $shareData['itemType']);
1768
-		$query->bindValue(2, $shareData['itemSource']);
1769
-		$query->bindValue(3, $shareData['itemTarget']);
1770
-		$query->bindValue(4, $shareData['shareType']);
1771
-		$query->bindValue(5, $shareData['shareWith']);
1772
-		$query->bindValue(6, $shareData['uidOwner']);
1773
-		$query->bindValue(7, $shareData['permissions']);
1774
-		$query->bindValue(8, $shareData['shareTime']);
1775
-		$query->bindValue(9, $shareData['fileSource']);
1776
-		$query->bindValue(10, $shareData['fileTarget']);
1777
-		$query->bindValue(11, $shareData['token']);
1778
-		$query->bindValue(12, $shareData['parent']);
1779
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1780
-		$result = $query->execute();
1781
-
1782
-		$id = false;
1783
-		if ($result) {
1784
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1785
-		}
1786
-
1787
-		return $id;
1788
-
1789
-	}
1790
-
1791
-	/**
1792
-	 * In case a password protected link is not yet authenticated this function will return false
1793
-	 *
1794
-	 * @param array $linkItem
1795
-	 * @return boolean
1796
-	 */
1797
-	public static function checkPasswordProtectedShare(array $linkItem) {
1798
-		if (!isset($linkItem['share_with'])) {
1799
-			return true;
1800
-		}
1801
-		if (!isset($linkItem['share_type'])) {
1802
-			return true;
1803
-		}
1804
-		if (!isset($linkItem['id'])) {
1805
-			return true;
1806
-		}
1807
-
1808
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1809
-			return true;
1810
-		}
1811
-
1812
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
1813
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1814
-			return true;
1815
-		}
1816
-
1817
-		return false;
1818
-	}
1819
-
1820
-	/**
1821
-	 * construct select statement
1822
-	 * @param int $format
1823
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1824
-	 * @param string $uidOwner
1825
-	 * @return string select statement
1826
-	 */
1827
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1828
-		$select = '*';
1829
-		if ($format == self::FORMAT_STATUSES) {
1830
-			if ($fileDependent) {
1831
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1832
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1833
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1834
-					. '`uid_initiator`';
1835
-			} else {
1836
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1837
-			}
1838
-		} else {
1839
-			if (isset($uidOwner)) {
1840
-				if ($fileDependent) {
1841
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1842
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1843
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1844
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1845
-				} else {
1846
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1847
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1848
-				}
1849
-			} else {
1850
-				if ($fileDependent) {
1851
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1852
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1853
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1854
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1855
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1856
-					} else {
1857
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1858
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1859
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1860
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1861
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1862
-					}
1863
-				}
1864
-			}
1865
-		}
1866
-		return $select;
1867
-	}
1868
-
1869
-
1870
-	/**
1871
-	 * transform db results
1872
-	 * @param array $row result
1873
-	 */
1874
-	private static function transformDBResults(&$row) {
1875
-		if (isset($row['id'])) {
1876
-			$row['id'] = (int) $row['id'];
1877
-		}
1878
-		if (isset($row['share_type'])) {
1879
-			$row['share_type'] = (int) $row['share_type'];
1880
-		}
1881
-		if (isset($row['parent'])) {
1882
-			$row['parent'] = (int) $row['parent'];
1883
-		}
1884
-		if (isset($row['file_parent'])) {
1885
-			$row['file_parent'] = (int) $row['file_parent'];
1886
-		}
1887
-		if (isset($row['file_source'])) {
1888
-			$row['file_source'] = (int) $row['file_source'];
1889
-		}
1890
-		if (isset($row['permissions'])) {
1891
-			$row['permissions'] = (int) $row['permissions'];
1892
-		}
1893
-		if (isset($row['storage'])) {
1894
-			$row['storage'] = (int) $row['storage'];
1895
-		}
1896
-		if (isset($row['stime'])) {
1897
-			$row['stime'] = (int) $row['stime'];
1898
-		}
1899
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1900
-			// discard expiration date for non-link shares, which might have been
1901
-			// set by ancient bugs
1902
-			$row['expiration'] = null;
1903
-		}
1904
-	}
1905
-
1906
-	/**
1907
-	 * format result
1908
-	 * @param array $items result
1909
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1910
-	 * @param \OCP\Share_Backend $backend sharing backend
1911
-	 * @param int $format
1912
-	 * @param array $parameters additional format parameters
1913
-	 * @return array format result
1914
-	 */
1915
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1916
-		if ($format === self::FORMAT_NONE) {
1917
-			return $items;
1918
-		} else if ($format === self::FORMAT_STATUSES) {
1919
-			$statuses = array();
1920
-			foreach ($items as $item) {
1921
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1922
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1923
-						continue;
1924
-					}
1925
-					$statuses[$item[$column]]['link'] = true;
1926
-				} else if (!isset($statuses[$item[$column]])) {
1927
-					$statuses[$item[$column]]['link'] = false;
1928
-				}
1929
-				if (!empty($item['file_target'])) {
1930
-					$statuses[$item[$column]]['path'] = $item['path'];
1931
-				}
1932
-			}
1933
-			return $statuses;
1934
-		} else {
1935
-			return $backend->formatItems($items, $format, $parameters);
1936
-		}
1937
-	}
1938
-
1939
-	/**
1940
-	 * remove protocol from URL
1941
-	 *
1942
-	 * @param string $url
1943
-	 * @return string
1944
-	 */
1945
-	public static function removeProtocolFromUrl($url) {
1946
-		if (strpos($url, 'https://') === 0) {
1947
-			return substr($url, strlen('https://'));
1948
-		} else if (strpos($url, 'http://') === 0) {
1949
-			return substr($url, strlen('http://'));
1950
-		}
1951
-
1952
-		return $url;
1953
-	}
1954
-
1955
-	/**
1956
-	 * try http post first with https and then with http as a fallback
1957
-	 *
1958
-	 * @param string $remoteDomain
1959
-	 * @param string $urlSuffix
1960
-	 * @param array $fields post parameters
1961
-	 * @return array
1962
-	 */
1963
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1964
-		$protocol = 'https://';
1965
-		$result = [
1966
-			'success' => false,
1967
-			'result' => '',
1968
-		];
1969
-		$try = 0;
1970
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1971
-		while ($result['success'] === false && $try < 2) {
1972
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1973
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1974
-			$client = \OC::$server->getHTTPClientService()->newClient();
1975
-
1976
-			try {
1977
-				$response = $client->post(
1978
-					$protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1979
-					[
1980
-						'body' => $fields,
1981
-						'connect_timeout' => 10,
1982
-					]
1983
-				);
1984
-
1985
-				$result = ['success' => true, 'result' => $response->getBody()];
1986
-			} catch (\Exception $e) {
1987
-				$result = ['success' => false, 'result' => $e->getMessage()];
1988
-			}
1989
-
1990
-			$try++;
1991
-			$protocol = 'http://';
1992
-		}
1993
-
1994
-		return $result;
1995
-	}
1996
-
1997
-	/**
1998
-	 * send server-to-server share to remote server
1999
-	 *
2000
-	 * @param string $token
2001
-	 * @param string $shareWith
2002
-	 * @param string $name
2003
-	 * @param int $remote_id
2004
-	 * @param string $owner
2005
-	 * @return bool
2006
-	 */
2007
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2008
-
2009
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2010
-
2011
-		if ($user && $remote) {
2012
-			$url = $remote;
2013
-
2014
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2015
-
2016
-			$fields = array(
2017
-				'shareWith' => $user,
2018
-				'token' => $token,
2019
-				'name' => $name,
2020
-				'remoteId' => $remote_id,
2021
-				'owner' => $owner,
2022
-				'remote' => $local,
2023
-			);
2024
-
2025
-			$url = self::removeProtocolFromUrl($url);
2026
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2027
-			$status = json_decode($result['result'], true);
2028
-
2029
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2030
-				\OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]);
2031
-				return true;
2032
-			}
2033
-
2034
-		}
2035
-
2036
-		return false;
2037
-	}
2038
-
2039
-	/**
2040
-	 * send server-to-server unshare to remote server
2041
-	 *
2042
-	 * @param string $remote url
2043
-	 * @param int $id share id
2044
-	 * @param string $token
2045
-	 * @return bool
2046
-	 */
2047
-	private static function sendRemoteUnshare($remote, $id, $token) {
2048
-		$url = rtrim($remote, '/');
2049
-		$fields = array('token' => $token, 'format' => 'json');
2050
-		$url = self::removeProtocolFromUrl($url);
2051
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2052
-		$status = json_decode($result['result'], true);
2053
-
2054
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2055
-	}
2056
-
2057
-	/**
2058
-	 * check if user can only share with group members
2059
-	 * @return bool
2060
-	 */
2061
-	public static function shareWithGroupMembersOnly() {
2062
-		$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2063
-		return $value === 'yes';
2064
-	}
2065
-
2066
-	/**
2067
-	 * @return bool
2068
-	 */
2069
-	public static function isDefaultExpireDateEnabled() {
2070
-		$defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2071
-		return $defaultExpireDateEnabled === 'yes';
2072
-	}
2073
-
2074
-	/**
2075
-	 * @return int
2076
-	 */
2077
-	public static function getExpireInterval() {
2078
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2079
-	}
2080
-
2081
-	/**
2082
-	 * Checks whether the given path is reachable for the given owner
2083
-	 *
2084
-	 * @param string $path path relative to files
2085
-	 * @param string $ownerStorageId storage id of the owner
2086
-	 *
2087
-	 * @return boolean true if file is reachable, false otherwise
2088
-	 */
2089
-	private static function isFileReachable($path, $ownerStorageId) {
2090
-		// if outside the home storage, file is always considered reachable
2091
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2092
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2093
-		)) {
2094
-			return true;
2095
-		}
2096
-
2097
-		// if inside the home storage, the file has to be under "/files/"
2098
-		$path = ltrim($path, '/');
2099
-		if (substr($path, 0, 6) === 'files/') {
2100
-			return true;
2101
-		}
2102
-
2103
-		return false;
2104
-	}
2105
-
2106
-	/**
2107
-	 * @param IConfig $config
2108
-	 * @return bool
2109
-	 */
2110
-	public static function enforcePassword(IConfig $config) {
2111
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2112
-		return $enforcePassword === 'yes';
2113
-	}
2114
-
2115
-	/**
2116
-	 * @param string $password
2117
-	 * @throws \Exception
2118
-	 */
2119
-	private static function verifyPassword($password) {
2120
-
2121
-		$accepted = true;
2122
-		$message = '';
2123
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2124
-			'password' => $password,
2125
-			'accepted' => &$accepted,
2126
-			'message' => &$message
2127
-		]);
2128
-
2129
-		if (!$accepted) {
2130
-			throw new \Exception($message);
2131
-		}
2132
-	}
704
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
705
+
706
+        if($result === false) {
707
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', ILogger::ERROR);
708
+        }
709
+    }
710
+
711
+    /**
712
+     * validate expiration date if it meets all constraints
713
+     *
714
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
715
+     * @param string $shareTime timestamp when the file was shared
716
+     * @param string $itemType
717
+     * @param string $itemSource
718
+     * @return \DateTime validated date
719
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
720
+     */
721
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
722
+        $l = \OC::$server->getL10N('lib');
723
+        $date = new \DateTime($expireDate);
724
+        $today = new \DateTime('now');
725
+
726
+        // if the user doesn't provide a share time we need to get it from the database
727
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
728
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
729
+        if ($defaultExpireDateEnforced && $shareTime === null) {
730
+            $items = self::getItemShared($itemType, $itemSource);
731
+            $firstItem = reset($items);
732
+            $shareTime = (int)$firstItem['stime'];
733
+        }
734
+
735
+        if ($defaultExpireDateEnforced) {
736
+            // initialize max date with share time
737
+            $maxDate = new \DateTime();
738
+            $maxDate->setTimestamp($shareTime);
739
+            $maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
740
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
741
+            if ($date > $maxDate) {
742
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
743
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
744
+                \OCP\Util::writeLog('OCP\Share', $warning, ILogger::WARN);
745
+                throw new \Exception($warning_t);
746
+            }
747
+        }
748
+
749
+        if ($date < $today) {
750
+            $message = 'Cannot set expiration date. Expiration date is in the past';
751
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
752
+            \OCP\Util::writeLog('OCP\Share', $message, ILogger::WARN);
753
+            throw new \Exception($message_t);
754
+        }
755
+
756
+        return $date;
757
+    }
758
+
759
+    /**
760
+     * Checks whether a share has expired, calls unshareItem() if yes.
761
+     * @param array $item Share data (usually database row)
762
+     * @return boolean True if item was expired, false otherwise.
763
+     */
764
+    protected static function expireItem(array $item) {
765
+
766
+        $result = false;
767
+
768
+        // only use default expiration date for link shares
769
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
770
+
771
+            // calculate expiration date
772
+            if (!empty($item['expiration'])) {
773
+                $userDefinedExpire = new \DateTime($item['expiration']);
774
+                $expires = $userDefinedExpire->getTimestamp();
775
+            } else {
776
+                $expires = null;
777
+            }
778
+
779
+
780
+            // get default expiration settings
781
+            $defaultSettings = Helper::getDefaultExpireSetting();
782
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
783
+
784
+
785
+            if (is_int($expires)) {
786
+                $now = time();
787
+                if ($now > $expires) {
788
+                    self::unshareItem($item);
789
+                    $result = true;
790
+                }
791
+            }
792
+        }
793
+        return $result;
794
+    }
795
+
796
+    /**
797
+     * Unshares a share given a share data array
798
+     * @param array $item Share data (usually database row)
799
+     * @param int $newParent parent ID
800
+     * @return null
801
+     */
802
+    protected static function unshareItem(array $item, $newParent = null) {
803
+
804
+        $shareType = (int)$item['share_type'];
805
+        $shareWith = null;
806
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
807
+            $shareWith = $item['share_with'];
808
+        }
809
+
810
+        // Pass all the vars we have for now, they may be useful
811
+        $hookParams = array(
812
+            'id'            => $item['id'],
813
+            'itemType'      => $item['item_type'],
814
+            'itemSource'    => $item['item_source'],
815
+            'shareType'     => $shareType,
816
+            'shareWith'     => $shareWith,
817
+            'itemParent'    => $item['parent'],
818
+            'uidOwner'      => $item['uid_owner'],
819
+        );
820
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
821
+            $hookParams['fileSource'] = $item['file_source'];
822
+            $hookParams['fileTarget'] = $item['file_target'];
823
+        }
824
+
825
+        \OC_Hook::emit(\OCP\Share::class, 'pre_unshare', $hookParams);
826
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
827
+        $deletedShares[] = $hookParams;
828
+        $hookParams['deletedShares'] = $deletedShares;
829
+        \OC_Hook::emit(\OCP\Share::class, 'post_unshare', $hookParams);
830
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
831
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
832
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
833
+        }
834
+    }
835
+
836
+    /**
837
+     * Get the backend class for the specified item type
838
+     * @param string $itemType
839
+     * @throws \Exception
840
+     * @return \OCP\Share_Backend
841
+     */
842
+    public static function getBackend($itemType) {
843
+        $l = \OC::$server->getL10N('lib');
844
+        if (isset(self::$backends[$itemType])) {
845
+            return self::$backends[$itemType];
846
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
847
+            $class = self::$backendTypes[$itemType]['class'];
848
+            if (class_exists($class)) {
849
+                self::$backends[$itemType] = new $class;
850
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
851
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
852
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
853
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
854
+                    throw new \Exception($message_t);
855
+                }
856
+                return self::$backends[$itemType];
857
+            } else {
858
+                $message = 'Sharing backend %s not found';
859
+                $message_t = $l->t('Sharing backend %s not found', array($class));
860
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), ILogger::ERROR);
861
+                throw new \Exception($message_t);
862
+            }
863
+        }
864
+        $message = 'Sharing backend for %s not found';
865
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
866
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), ILogger::ERROR);
867
+        throw new \Exception($message_t);
868
+    }
869
+
870
+    /**
871
+     * Check if resharing is allowed
872
+     * @return boolean true if allowed or false
873
+     *
874
+     * Resharing is allowed by default if not configured
875
+     */
876
+    public static function isResharingAllowed() {
877
+        if (!isset(self::$isResharingAllowed)) {
878
+            if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
879
+                self::$isResharingAllowed = true;
880
+            } else {
881
+                self::$isResharingAllowed = false;
882
+            }
883
+        }
884
+        return self::$isResharingAllowed;
885
+    }
886
+
887
+    /**
888
+     * Get a list of collection item types for the specified item type
889
+     * @param string $itemType
890
+     * @return array
891
+     */
892
+    private static function getCollectionItemTypes($itemType) {
893
+        $collectionTypes = array($itemType);
894
+        foreach (self::$backendTypes as $type => $backend) {
895
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
896
+                $collectionTypes[] = $type;
897
+            }
898
+        }
899
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
900
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
901
+            unset($collectionTypes[0]);
902
+        }
903
+        // Return array if collections were found or the item type is a
904
+        // collection itself - collections can be inside collections
905
+        if (count($collectionTypes) > 0) {
906
+            return $collectionTypes;
907
+        }
908
+        return false;
909
+    }
910
+
911
+    /**
912
+     * Get the owners of items shared with a user.
913
+     *
914
+     * @param string $user The user the items are shared with.
915
+     * @param string $type The type of the items shared with the user.
916
+     * @param boolean $includeCollections Include collection item types (optional)
917
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
918
+     * @return array
919
+     */
920
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
921
+        // First, we find out if $type is part of a collection (and if that collection is part of
922
+        // another one and so on).
923
+        $collectionTypes = array();
924
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
925
+            $collectionTypes[] = $type;
926
+        }
927
+
928
+        // Of these collection types, along with our original $type, we make a
929
+        // list of the ones for which a sharing backend has been registered.
930
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
931
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
932
+        $allMaybeSharedItems = array();
933
+        foreach ($collectionTypes as $collectionType) {
934
+            if (isset(self::$backends[$collectionType])) {
935
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
936
+                    $collectionType,
937
+                    $user,
938
+                    self::FORMAT_NONE
939
+                );
940
+            }
941
+        }
942
+
943
+        $owners = array();
944
+        if ($includeOwner) {
945
+            $owners[] = $user;
946
+        }
947
+
948
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
949
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
950
+        // and return them as elements of a list that look like "Tag (owner)".
951
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
952
+            foreach ($maybeSharedItems as $sharedItem) {
953
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
954
+                    $owners[] = $sharedItem['uid_owner'];
955
+                }
956
+            }
957
+        }
958
+
959
+        return $owners;
960
+    }
961
+
962
+    /**
963
+     * Get shared items from the database
964
+     * @param string $itemType
965
+     * @param string $item Item source or target (optional)
966
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
967
+     * @param string $shareWith User or group the item is being shared with
968
+     * @param string $uidOwner User that is the owner of shared items (optional)
969
+     * @param int $format Format to convert items to with formatItems() (optional)
970
+     * @param mixed $parameters to pass to formatItems() (optional)
971
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
972
+     * @param boolean $includeCollections Include collection item types (optional)
973
+     * @param boolean $itemShareWithBySource (optional)
974
+     * @param boolean $checkExpireDate
975
+     * @return array
976
+     *
977
+     * See public functions getItem(s)... for parameter usage
978
+     *
979
+     */
980
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
981
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
982
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
983
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_enabled', 'yes') != 'yes') {
984
+            return array();
985
+        }
986
+        $backend = self::getBackend($itemType);
987
+        $collectionTypes = false;
988
+        // Get filesystem root to add it to the file target and remove from the
989
+        // file source, match file_source with the file cache
990
+        if ($itemType == 'file' || $itemType == 'folder') {
991
+            if(!is_null($uidOwner)) {
992
+                $root = \OC\Files\Filesystem::getRoot();
993
+            } else {
994
+                $root = '';
995
+            }
996
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
997
+            if (!isset($item)) {
998
+                $where .= ' AND `file_target` IS NOT NULL ';
999
+            }
1000
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1001
+            $fileDependent = true;
1002
+            $queryArgs = array();
1003
+        } else {
1004
+            $fileDependent = false;
1005
+            $root = '';
1006
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1007
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1008
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1009
+                if (!in_array($itemType, $collectionTypes)) {
1010
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1011
+                } else {
1012
+                    $itemTypes = $collectionTypes;
1013
+                }
1014
+                $placeholders = implode(',', array_fill(0, count($itemTypes), '?'));
1015
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1016
+                $queryArgs = $itemTypes;
1017
+            } else {
1018
+                $where = ' WHERE `item_type` = ?';
1019
+                $queryArgs = array($itemType);
1020
+            }
1021
+        }
1022
+        if (\OC::$server->getConfig()->getAppValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1023
+            $where .= ' AND `share_type` != ?';
1024
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1025
+        }
1026
+        if (isset($shareType)) {
1027
+            // Include all user and group items
1028
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1029
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1030
+                $queryArgs[] = self::SHARE_TYPE_USER;
1031
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1032
+                $queryArgs[] = $shareWith;
1033
+
1034
+                $user = \OC::$server->getUserManager()->get($shareWith);
1035
+                $groups = [];
1036
+                if ($user) {
1037
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1038
+                }
1039
+                if (!empty($groups)) {
1040
+                    $placeholders = implode(',', array_fill(0, count($groups), '?'));
1041
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1042
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1043
+                    $queryArgs = array_merge($queryArgs, $groups);
1044
+                }
1045
+                $where .= ')';
1046
+                // Don't include own group shares
1047
+                $where .= ' AND `uid_owner` != ?';
1048
+                $queryArgs[] = $shareWith;
1049
+            } else {
1050
+                $where .= ' AND `share_type` = ?';
1051
+                $queryArgs[] = $shareType;
1052
+                if (isset($shareWith)) {
1053
+                    $where .= ' AND `share_with` = ?';
1054
+                    $queryArgs[] = $shareWith;
1055
+                }
1056
+            }
1057
+        }
1058
+        if (isset($uidOwner)) {
1059
+            $where .= ' AND `uid_owner` = ?';
1060
+            $queryArgs[] = $uidOwner;
1061
+            if (!isset($shareType)) {
1062
+                // Prevent unique user targets for group shares from being selected
1063
+                $where .= ' AND `share_type` != ?';
1064
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1065
+            }
1066
+            if ($fileDependent) {
1067
+                $column = 'file_source';
1068
+            } else {
1069
+                $column = 'item_source';
1070
+            }
1071
+        } else {
1072
+            if ($fileDependent) {
1073
+                $column = 'file_target';
1074
+            } else {
1075
+                $column = 'item_target';
1076
+            }
1077
+        }
1078
+        if (isset($item)) {
1079
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1080
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1081
+                $where .= ' AND (';
1082
+            } else {
1083
+                $where .= ' AND';
1084
+            }
1085
+            // If looking for own shared items, check item_source else check item_target
1086
+            if (isset($uidOwner) || $itemShareWithBySource) {
1087
+                // If item type is a file, file source needs to be checked in case the item was converted
1088
+                if ($fileDependent) {
1089
+                    $where .= ' `file_source` = ?';
1090
+                    $column = 'file_source';
1091
+                } else {
1092
+                    $where .= ' `item_source` = ?';
1093
+                    $column = 'item_source';
1094
+                }
1095
+            } else {
1096
+                if ($fileDependent) {
1097
+                    $where .= ' `file_target` = ?';
1098
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1099
+                } else {
1100
+                    $where .= ' `item_target` = ?';
1101
+                }
1102
+            }
1103
+            $queryArgs[] = $item;
1104
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1105
+                $placeholders = implode(',', array_fill(0, count($collectionTypes), '?'));
1106
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1107
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1108
+            }
1109
+        }
1110
+
1111
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1112
+            // Make sure the unique user target is returned if it exists,
1113
+            // unique targets should follow the group share in the database
1114
+            // If the limit is not 1, the filtering can be done later
1115
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1116
+        } else {
1117
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1118
+        }
1119
+
1120
+        if ($limit != -1 && !$includeCollections) {
1121
+            // The limit must be at least 3, because filtering needs to be done
1122
+            if ($limit < 3) {
1123
+                $queryLimit = 3;
1124
+            } else {
1125
+                $queryLimit = $limit;
1126
+            }
1127
+        } else {
1128
+            $queryLimit = null;
1129
+        }
1130
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1131
+        $root = strlen($root);
1132
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1133
+        $result = $query->execute($queryArgs);
1134
+        if ($result === false) {
1135
+            \OCP\Util::writeLog('OCP\Share',
1136
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1137
+                ILogger::ERROR);
1138
+        }
1139
+        $items = array();
1140
+        $targets = array();
1141
+        $switchedItems = array();
1142
+        $mounts = array();
1143
+        while ($row = $result->fetchRow()) {
1144
+            self::transformDBResults($row);
1145
+            // Filter out duplicate group shares for users with unique targets
1146
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1147
+                continue;
1148
+            }
1149
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1150
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1151
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1152
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1153
+                // if the group share was unshared from the user we keep the permission, otherwise
1154
+                // we take the permission from the parent because this is always the up-to-date
1155
+                // permission for the group share
1156
+                if ($row['permissions'] > 0) {
1157
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1158
+                }
1159
+                // Remove the parent group share
1160
+                unset($items[$row['parent']]);
1161
+                if ($row['permissions'] == 0) {
1162
+                    continue;
1163
+                }
1164
+            } else if (!isset($uidOwner)) {
1165
+                // Check if the same target already exists
1166
+                if (isset($targets[$row['id']])) {
1167
+                    // Check if the same owner shared with the user twice
1168
+                    // through a group and user share - this is allowed
1169
+                    $id = $targets[$row['id']];
1170
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1171
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1172
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1173
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1174
+                            $items[$id]['share_with'] = $row['share_with'];
1175
+                        }
1176
+                        // Switch ids if sharing permission is granted on only
1177
+                        // one share to ensure correct parent is used if resharing
1178
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1179
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1180
+                            $items[$row['id']] = $items[$id];
1181
+                            $switchedItems[$id] = $row['id'];
1182
+                            unset($items[$id]);
1183
+                            $id = $row['id'];
1184
+                        }
1185
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1186
+
1187
+                    }
1188
+                    continue;
1189
+                } elseif (!empty($row['parent'])) {
1190
+                    $targets[$row['parent']] = $row['id'];
1191
+                }
1192
+            }
1193
+            // Remove root from file source paths if retrieving own shared items
1194
+            if (isset($uidOwner) && isset($row['path'])) {
1195
+                if (isset($row['parent'])) {
1196
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1197
+                    $parentResult = $query->execute(array($row['parent']));
1198
+                    if ($result === false) {
1199
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1200
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1201
+                            ILogger::ERROR);
1202
+                    } else {
1203
+                        $parentRow = $parentResult->fetchRow();
1204
+                        $tmpPath = $parentRow['file_target'];
1205
+                        // find the right position where the row path continues from the target path
1206
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1207
+                        $subPath = substr($row['path'], $pos);
1208
+                        $splitPath = explode('/', $subPath);
1209
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1210
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1211
+                        }
1212
+                        $row['path'] = $tmpPath;
1213
+                    }
1214
+                } else {
1215
+                    if (!isset($mounts[$row['storage']])) {
1216
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1217
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1218
+                            $mounts[$row['storage']] = current($mountPoints);
1219
+                        }
1220
+                    }
1221
+                    if (!empty($mounts[$row['storage']])) {
1222
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1223
+                        $relPath = substr($path, $root); // path relative to data/user
1224
+                        $row['path'] = rtrim($relPath, '/');
1225
+                    }
1226
+                }
1227
+            }
1228
+
1229
+            if($checkExpireDate) {
1230
+                if (self::expireItem($row)) {
1231
+                    continue;
1232
+                }
1233
+            }
1234
+            // Check if resharing is allowed, if not remove share permission
1235
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1236
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1237
+            }
1238
+            // Add display names to result
1239
+            $row['share_with_displayname'] = $row['share_with'];
1240
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
1241
+                $row['share_type'] === self::SHARE_TYPE_USER) {
1242
+                $shareWithUser = \OC::$server->getUserManager()->get($row['share_with']);
1243
+                $row['share_with_displayname'] = $shareWithUser === null ? $row['share_with'] : $shareWithUser->getDisplayName();
1244
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
1245
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
1246
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1247
+                foreach ($addressBookEntries as $entry) {
1248
+                    foreach ($entry['CLOUD'] as $cloudID) {
1249
+                        if ($cloudID === $row['share_with']) {
1250
+                            $row['share_with_displayname'] = $entry['FN'];
1251
+                        }
1252
+                    }
1253
+                }
1254
+            }
1255
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1256
+                $ownerUser = \OC::$server->getUserManager()->get($row['uid_owner']);
1257
+                $row['displayname_owner'] = $ownerUser === null ? $row['uid_owner'] : $ownerUser->getDisplayName();
1258
+            }
1259
+
1260
+            if ($row['permissions'] > 0) {
1261
+                $items[$row['id']] = $row;
1262
+            }
1263
+
1264
+        }
1265
+
1266
+        // group items if we are looking for items shared with the current user
1267
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1268
+            $items = self::groupItems($items, $itemType);
1269
+        }
1270
+
1271
+        if (!empty($items)) {
1272
+            $collectionItems = array();
1273
+            foreach ($items as &$row) {
1274
+                // Return only the item instead of a 2-dimensional array
1275
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1276
+                    if ($format == self::FORMAT_NONE) {
1277
+                        return $row;
1278
+                    } else {
1279
+                        break;
1280
+                    }
1281
+                }
1282
+                // Check if this is a collection of the requested item type
1283
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1284
+                    if (($collectionBackend = self::getBackend($row['item_type']))
1285
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1286
+                        // Collections can be inside collections, check if the item is a collection
1287
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1288
+                            $collectionItems[] = $row;
1289
+                        } else {
1290
+                            $collection = array();
1291
+                            $collection['item_type'] = $row['item_type'];
1292
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1293
+                                $collection['path'] = basename($row['path']);
1294
+                            }
1295
+                            $row['collection'] = $collection;
1296
+                            // Fetch all of the children sources
1297
+                            $children = $collectionBackend->getChildren($row[$column]);
1298
+                            foreach ($children as $child) {
1299
+                                $childItem = $row;
1300
+                                $childItem['item_type'] = $itemType;
1301
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1302
+                                    $childItem['item_source'] = $child['source'];
1303
+                                    $childItem['item_target'] = $child['target'];
1304
+                                }
1305
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1306
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1307
+                                        $childItem['file_source'] = $child['source'];
1308
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
1309
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1310
+                                        $childItem['file_source'] = $meta['fileid'];
1311
+                                    }
1312
+                                    $childItem['file_target'] =
1313
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
1314
+                                }
1315
+                                if (isset($item)) {
1316
+                                    if ($childItem[$column] == $item) {
1317
+                                        // Return only the item instead of a 2-dimensional array
1318
+                                        if ($limit == 1) {
1319
+                                            if ($format == self::FORMAT_NONE) {
1320
+                                                return $childItem;
1321
+                                            } else {
1322
+                                                // Unset the items array and break out of both loops
1323
+                                                $items = array();
1324
+                                                $items[] = $childItem;
1325
+                                                break 2;
1326
+                                            }
1327
+                                        } else {
1328
+                                            $collectionItems[] = $childItem;
1329
+                                        }
1330
+                                    }
1331
+                                } else {
1332
+                                    $collectionItems[] = $childItem;
1333
+                                }
1334
+                            }
1335
+                        }
1336
+                    }
1337
+                    // Remove collection item
1338
+                    $toRemove = $row['id'];
1339
+                    if (array_key_exists($toRemove, $switchedItems)) {
1340
+                        $toRemove = $switchedItems[$toRemove];
1341
+                    }
1342
+                    unset($items[$toRemove]);
1343
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1344
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
1345
+                    // see github issue #10588 for more details
1346
+                    // Need to find a solution which works for all back-ends
1347
+                    $collectionBackend = self::getBackend($row['item_type']);
1348
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
1349
+                    foreach ($sharedParents as $parent) {
1350
+                        $collectionItems[] = $parent;
1351
+                    }
1352
+                }
1353
+            }
1354
+            if (!empty($collectionItems)) {
1355
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
1356
+                $items = array_merge($items, $collectionItems);
1357
+            }
1358
+
1359
+            // filter out invalid items, these can appear when subshare entries exist
1360
+            // for a group in which the requested user isn't a member any more
1361
+            $items = array_filter($items, function($item) {
1362
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1363
+            });
1364
+
1365
+            return self::formatResult($items, $column, $backend, $format, $parameters);
1366
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1367
+            // FIXME: Thats a dirty hack to improve file sharing performance,
1368
+            // see github issue #10588 for more details
1369
+            // Need to find a solution which works for all back-ends
1370
+            $collectionItems = array();
1371
+            $collectionBackend = self::getBackend('folder');
1372
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1373
+            foreach ($sharedParents as $parent) {
1374
+                $collectionItems[] = $parent;
1375
+            }
1376
+            if ($limit === 1) {
1377
+                return reset($collectionItems);
1378
+            }
1379
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1380
+        }
1381
+
1382
+        return array();
1383
+    }
1384
+
1385
+    /**
1386
+     * group items with link to the same source
1387
+     *
1388
+     * @param array $items
1389
+     * @param string $itemType
1390
+     * @return array of grouped items
1391
+     */
1392
+    protected static function groupItems($items, $itemType) {
1393
+
1394
+        $fileSharing = $itemType === 'file' || $itemType === 'folder';
1395
+
1396
+        $result = array();
1397
+
1398
+        foreach ($items as $item) {
1399
+            $grouped = false;
1400
+            foreach ($result as $key => $r) {
1401
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1402
+                // only group shares if they already point to the same target, otherwise the file where shared
1403
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1404
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1405
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1406
+                    // add the first item to the list of grouped shares
1407
+                    if (!isset($result[$key]['grouped'])) {
1408
+                        $result[$key]['grouped'][] = $result[$key];
1409
+                    }
1410
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1411
+                    $result[$key]['grouped'][] = $item;
1412
+                    $grouped = true;
1413
+                    break;
1414
+                }
1415
+            }
1416
+
1417
+            if (!$grouped) {
1418
+                $result[] = $item;
1419
+            }
1420
+
1421
+        }
1422
+
1423
+        return $result;
1424
+    }
1425
+
1426
+    /**
1427
+     * Put shared item into the database
1428
+     * @param string $itemType Item type
1429
+     * @param string $itemSource Item source
1430
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1431
+     * @param string $shareWith User or group the item is being shared with
1432
+     * @param string $uidOwner User that is the owner of shared item
1433
+     * @param int $permissions CRUDS permissions
1434
+     * @param boolean|array $parentFolder Parent folder target (optional)
1435
+     * @param string $token (optional)
1436
+     * @param string $itemSourceName name of the source item (optional)
1437
+     * @param \DateTime $expirationDate (optional)
1438
+     * @throws \Exception
1439
+     * @return mixed id of the new share or false
1440
+     */
1441
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1442
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1443
+
1444
+        $queriesToExecute = array();
1445
+        $suggestedItemTarget = null;
1446
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1447
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1448
+
1449
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1450
+        if(!empty($result)) {
1451
+            $parent = $result['parent'];
1452
+            $itemSource = $result['itemSource'];
1453
+            $fileSource = $result['fileSource'];
1454
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1455
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1456
+            $filePath = $result['filePath'];
1457
+        }
1458
+
1459
+        $isGroupShare = false;
1460
+        if ($shareType == self::SHARE_TYPE_GROUP) {
1461
+            $isGroupShare = true;
1462
+            if (isset($shareWith['users'])) {
1463
+                $users = $shareWith['users'];
1464
+            } else {
1465
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
1466
+                if ($group) {
1467
+                    $users = $group->searchUsers('', -1, 0);
1468
+                    $userIds = [];
1469
+                    foreach ($users as $user) {
1470
+                        $userIds[] = $user->getUID();
1471
+                    }
1472
+                    $users = $userIds;
1473
+                } else {
1474
+                    $users = [];
1475
+                }
1476
+            }
1477
+            // remove current user from list
1478
+            if (in_array(\OCP\User::getUser(), $users)) {
1479
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
1480
+            }
1481
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1482
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1483
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1484
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
1485
+
1486
+            // add group share to table and remember the id as parent
1487
+            $queriesToExecute['groupShare'] = array(
1488
+                'itemType'			=> $itemType,
1489
+                'itemSource'		=> $itemSource,
1490
+                'itemTarget'		=> $groupItemTarget,
1491
+                'shareType'			=> $shareType,
1492
+                'shareWith'			=> $shareWith['group'],
1493
+                'uidOwner'			=> $uidOwner,
1494
+                'permissions'		=> $permissions,
1495
+                'shareTime'			=> time(),
1496
+                'fileSource'		=> $fileSource,
1497
+                'fileTarget'		=> $groupFileTarget,
1498
+                'token'				=> $token,
1499
+                'parent'			=> $parent,
1500
+                'expiration'		=> $expirationDate,
1501
+            );
1502
+
1503
+        } else {
1504
+            $users = array($shareWith);
1505
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1506
+                $suggestedItemTarget);
1507
+        }
1508
+
1509
+        $run = true;
1510
+        $error = '';
1511
+        $preHookData = array(
1512
+            'itemType' => $itemType,
1513
+            'itemSource' => $itemSource,
1514
+            'shareType' => $shareType,
1515
+            'uidOwner' => $uidOwner,
1516
+            'permissions' => $permissions,
1517
+            'fileSource' => $fileSource,
1518
+            'expiration' => $expirationDate,
1519
+            'token' => $token,
1520
+            'run' => &$run,
1521
+            'error' => &$error
1522
+        );
1523
+
1524
+        $preHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1525
+        $preHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1526
+
1527
+        \OC_Hook::emit(\OCP\Share::class, 'pre_shared', $preHookData);
1528
+
1529
+        if ($run === false) {
1530
+            throw new \Exception($error);
1531
+        }
1532
+
1533
+        foreach ($users as $user) {
1534
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1535
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1536
+
1537
+            $userShareType = $isGroupShare ? self::$shareTypeGroupUserUnique : $shareType;
1538
+
1539
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1540
+                $fileTarget = $sourceExists['file_target'];
1541
+                $itemTarget = $sourceExists['item_target'];
1542
+
1543
+                // for group shares we don't need a additional entry if the target is the same
1544
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
1545
+                    continue;
1546
+                }
1547
+
1548
+            } elseif(!$sourceExists && !$isGroupShare)  {
1549
+
1550
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1551
+                    $uidOwner, $suggestedItemTarget, $parent);
1552
+                if (isset($fileSource)) {
1553
+                    if ($parentFolder) {
1554
+                        if ($parentFolder === true) {
1555
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1556
+                                $uidOwner, $suggestedFileTarget, $parent);
1557
+                            if ($fileTarget != $groupFileTarget) {
1558
+                                $parentFolders[$user]['folder'] = $fileTarget;
1559
+                            }
1560
+                        } else if (isset($parentFolder[$user])) {
1561
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
1562
+                            $parent = $parentFolder[$user]['id'];
1563
+                        }
1564
+                    } else {
1565
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1566
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1567
+                    }
1568
+                } else {
1569
+                    $fileTarget = null;
1570
+                }
1571
+
1572
+            } else {
1573
+
1574
+                // group share which doesn't exists until now, check if we need a unique target for this user
1575
+
1576
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1577
+                    $uidOwner, $suggestedItemTarget, $parent);
1578
+
1579
+                // do we also need a file target
1580
+                if (isset($fileSource)) {
1581
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1582
+                        $uidOwner, $suggestedFileTarget, $parent);
1583
+                } else {
1584
+                    $fileTarget = null;
1585
+                }
1586
+
1587
+                if (($itemTarget === $groupItemTarget) &&
1588
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1589
+                    continue;
1590
+                }
1591
+            }
1592
+
1593
+            $queriesToExecute[] = array(
1594
+                'itemType'			=> $itemType,
1595
+                'itemSource'		=> $itemSource,
1596
+                'itemTarget'		=> $itemTarget,
1597
+                'shareType'			=> $userShareType,
1598
+                'shareWith'			=> $user,
1599
+                'uidOwner'			=> $uidOwner,
1600
+                'permissions'		=> $permissions,
1601
+                'shareTime'			=> time(),
1602
+                'fileSource'		=> $fileSource,
1603
+                'fileTarget'		=> $fileTarget,
1604
+                'token'				=> $token,
1605
+                'parent'			=> $parent,
1606
+                'expiration'		=> $expirationDate,
1607
+            );
1608
+
1609
+        }
1610
+
1611
+        $id = false;
1612
+        if ($isGroupShare) {
1613
+            $id = self::insertShare($queriesToExecute['groupShare']);
1614
+            // Save this id, any extra rows for this group share will need to reference it
1615
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1616
+            unset($queriesToExecute['groupShare']);
1617
+        }
1618
+
1619
+        foreach ($queriesToExecute as $shareQuery) {
1620
+            $shareQuery['parent'] = $parent;
1621
+            $id = self::insertShare($shareQuery);
1622
+        }
1623
+
1624
+        $postHookData = array(
1625
+            'itemType' => $itemType,
1626
+            'itemSource' => $itemSource,
1627
+            'parent' => $parent,
1628
+            'shareType' => $shareType,
1629
+            'uidOwner' => $uidOwner,
1630
+            'permissions' => $permissions,
1631
+            'fileSource' => $fileSource,
1632
+            'id' => $parent,
1633
+            'token' => $token,
1634
+            'expirationDate' => $expirationDate,
1635
+        );
1636
+
1637
+        $postHookData['shareWith'] = $isGroupShare ? $shareWith['group'] : $shareWith;
1638
+        $postHookData['itemTarget'] = $isGroupShare ? $groupItemTarget : $itemTarget;
1639
+        $postHookData['fileTarget'] = $isGroupShare ? $groupFileTarget : $fileTarget;
1640
+
1641
+        \OC_Hook::emit(\OCP\Share::class, 'post_shared', $postHookData);
1642
+
1643
+
1644
+        return $id ? $id : false;
1645
+    }
1646
+
1647
+    /**
1648
+     * @param string $itemType
1649
+     * @param string $itemSource
1650
+     * @param int $shareType
1651
+     * @param string $shareWith
1652
+     * @param string $uidOwner
1653
+     * @param int $permissions
1654
+     * @param string|null $itemSourceName
1655
+     * @param null|\DateTime $expirationDate
1656
+     */
1657
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1658
+        $backend = self::getBackend($itemType);
1659
+
1660
+        $l = \OC::$server->getL10N('lib');
1661
+        $result = array();
1662
+
1663
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1664
+
1665
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1666
+        if ($checkReshare) {
1667
+            // Check if attempting to share back to owner
1668
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1669
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
1670
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1671
+
1672
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), ILogger::DEBUG);
1673
+                throw new \Exception($message_t);
1674
+            }
1675
+        }
1676
+
1677
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1678
+            // Check if share permissions is granted
1679
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1680
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1681
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1682
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1683
+
1684
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), ILogger::DEBUG);
1685
+                    throw new \Exception($message_t);
1686
+                } else {
1687
+                    // TODO Don't check if inside folder
1688
+                    $result['parent'] = $checkReshare['id'];
1689
+
1690
+                    $result['expirationDate'] = $expirationDate;
1691
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1692
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1693
+                        $result['expirationDate'] = $checkReshare['expiration'];
1694
+                    }
1695
+
1696
+                    // only suggest the same name as new target if it is a reshare of the
1697
+                    // same file/folder and not the reshare of a child
1698
+                    if ($checkReshare[$column] === $itemSource) {
1699
+                        $result['filePath'] = $checkReshare['file_target'];
1700
+                        $result['itemSource'] = $checkReshare['item_source'];
1701
+                        $result['fileSource'] = $checkReshare['file_source'];
1702
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1703
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1704
+                    } else {
1705
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1706
+                        $result['suggestedItemTarget'] = null;
1707
+                        $result['suggestedFileTarget'] = null;
1708
+                        $result['itemSource'] = $itemSource;
1709
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1710
+                    }
1711
+                }
1712
+            } else {
1713
+                $message = 'Sharing %s failed, because resharing is not allowed';
1714
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1715
+
1716
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), ILogger::DEBUG);
1717
+                throw new \Exception($message_t);
1718
+            }
1719
+        } else {
1720
+            $result['parent'] = null;
1721
+            $result['suggestedItemTarget'] = null;
1722
+            $result['suggestedFileTarget'] = null;
1723
+            $result['itemSource'] = $itemSource;
1724
+            $result['expirationDate'] = $expirationDate;
1725
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1726
+                $message = 'Sharing %s failed, because the sharing backend for '
1727
+                    .'%s could not find its source';
1728
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1729
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), ILogger::DEBUG);
1730
+                throw new \Exception($message_t);
1731
+            }
1732
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1733
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1734
+                if ($itemType == 'file' || $itemType == 'folder') {
1735
+                    $result['fileSource'] = $itemSource;
1736
+                } else {
1737
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1738
+                    $result['fileSource'] = $meta['fileid'];
1739
+                }
1740
+                if ($result['fileSource'] == -1) {
1741
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1742
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1743
+
1744
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), ILogger::DEBUG);
1745
+                    throw new \Exception($message_t);
1746
+                }
1747
+            } else {
1748
+                $result['filePath'] = null;
1749
+                $result['fileSource'] = null;
1750
+            }
1751
+        }
1752
+
1753
+        return $result;
1754
+    }
1755
+
1756
+    /**
1757
+     *
1758
+     * @param array $shareData
1759
+     * @return mixed false in case of a failure or the id of the new share
1760
+     */
1761
+    private static function insertShare(array $shareData) {
1762
+
1763
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1764
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1765
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1766
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1767
+        $query->bindValue(1, $shareData['itemType']);
1768
+        $query->bindValue(2, $shareData['itemSource']);
1769
+        $query->bindValue(3, $shareData['itemTarget']);
1770
+        $query->bindValue(4, $shareData['shareType']);
1771
+        $query->bindValue(5, $shareData['shareWith']);
1772
+        $query->bindValue(6, $shareData['uidOwner']);
1773
+        $query->bindValue(7, $shareData['permissions']);
1774
+        $query->bindValue(8, $shareData['shareTime']);
1775
+        $query->bindValue(9, $shareData['fileSource']);
1776
+        $query->bindValue(10, $shareData['fileTarget']);
1777
+        $query->bindValue(11, $shareData['token']);
1778
+        $query->bindValue(12, $shareData['parent']);
1779
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1780
+        $result = $query->execute();
1781
+
1782
+        $id = false;
1783
+        if ($result) {
1784
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1785
+        }
1786
+
1787
+        return $id;
1788
+
1789
+    }
1790
+
1791
+    /**
1792
+     * In case a password protected link is not yet authenticated this function will return false
1793
+     *
1794
+     * @param array $linkItem
1795
+     * @return boolean
1796
+     */
1797
+    public static function checkPasswordProtectedShare(array $linkItem) {
1798
+        if (!isset($linkItem['share_with'])) {
1799
+            return true;
1800
+        }
1801
+        if (!isset($linkItem['share_type'])) {
1802
+            return true;
1803
+        }
1804
+        if (!isset($linkItem['id'])) {
1805
+            return true;
1806
+        }
1807
+
1808
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1809
+            return true;
1810
+        }
1811
+
1812
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
1813
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1814
+            return true;
1815
+        }
1816
+
1817
+        return false;
1818
+    }
1819
+
1820
+    /**
1821
+     * construct select statement
1822
+     * @param int $format
1823
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1824
+     * @param string $uidOwner
1825
+     * @return string select statement
1826
+     */
1827
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1828
+        $select = '*';
1829
+        if ($format == self::FORMAT_STATUSES) {
1830
+            if ($fileDependent) {
1831
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1832
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1833
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1834
+                    . '`uid_initiator`';
1835
+            } else {
1836
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1837
+            }
1838
+        } else {
1839
+            if (isset($uidOwner)) {
1840
+                if ($fileDependent) {
1841
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1842
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1843
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1844
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1845
+                } else {
1846
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1847
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1848
+                }
1849
+            } else {
1850
+                if ($fileDependent) {
1851
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1852
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1853
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1854
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1855
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1856
+                    } else {
1857
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1858
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1859
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1860
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1861
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1862
+                    }
1863
+                }
1864
+            }
1865
+        }
1866
+        return $select;
1867
+    }
1868
+
1869
+
1870
+    /**
1871
+     * transform db results
1872
+     * @param array $row result
1873
+     */
1874
+    private static function transformDBResults(&$row) {
1875
+        if (isset($row['id'])) {
1876
+            $row['id'] = (int) $row['id'];
1877
+        }
1878
+        if (isset($row['share_type'])) {
1879
+            $row['share_type'] = (int) $row['share_type'];
1880
+        }
1881
+        if (isset($row['parent'])) {
1882
+            $row['parent'] = (int) $row['parent'];
1883
+        }
1884
+        if (isset($row['file_parent'])) {
1885
+            $row['file_parent'] = (int) $row['file_parent'];
1886
+        }
1887
+        if (isset($row['file_source'])) {
1888
+            $row['file_source'] = (int) $row['file_source'];
1889
+        }
1890
+        if (isset($row['permissions'])) {
1891
+            $row['permissions'] = (int) $row['permissions'];
1892
+        }
1893
+        if (isset($row['storage'])) {
1894
+            $row['storage'] = (int) $row['storage'];
1895
+        }
1896
+        if (isset($row['stime'])) {
1897
+            $row['stime'] = (int) $row['stime'];
1898
+        }
1899
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
1900
+            // discard expiration date for non-link shares, which might have been
1901
+            // set by ancient bugs
1902
+            $row['expiration'] = null;
1903
+        }
1904
+    }
1905
+
1906
+    /**
1907
+     * format result
1908
+     * @param array $items result
1909
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
1910
+     * @param \OCP\Share_Backend $backend sharing backend
1911
+     * @param int $format
1912
+     * @param array $parameters additional format parameters
1913
+     * @return array format result
1914
+     */
1915
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
1916
+        if ($format === self::FORMAT_NONE) {
1917
+            return $items;
1918
+        } else if ($format === self::FORMAT_STATUSES) {
1919
+            $statuses = array();
1920
+            foreach ($items as $item) {
1921
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
1922
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
1923
+                        continue;
1924
+                    }
1925
+                    $statuses[$item[$column]]['link'] = true;
1926
+                } else if (!isset($statuses[$item[$column]])) {
1927
+                    $statuses[$item[$column]]['link'] = false;
1928
+                }
1929
+                if (!empty($item['file_target'])) {
1930
+                    $statuses[$item[$column]]['path'] = $item['path'];
1931
+                }
1932
+            }
1933
+            return $statuses;
1934
+        } else {
1935
+            return $backend->formatItems($items, $format, $parameters);
1936
+        }
1937
+    }
1938
+
1939
+    /**
1940
+     * remove protocol from URL
1941
+     *
1942
+     * @param string $url
1943
+     * @return string
1944
+     */
1945
+    public static function removeProtocolFromUrl($url) {
1946
+        if (strpos($url, 'https://') === 0) {
1947
+            return substr($url, strlen('https://'));
1948
+        } else if (strpos($url, 'http://') === 0) {
1949
+            return substr($url, strlen('http://'));
1950
+        }
1951
+
1952
+        return $url;
1953
+    }
1954
+
1955
+    /**
1956
+     * try http post first with https and then with http as a fallback
1957
+     *
1958
+     * @param string $remoteDomain
1959
+     * @param string $urlSuffix
1960
+     * @param array $fields post parameters
1961
+     * @return array
1962
+     */
1963
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
1964
+        $protocol = 'https://';
1965
+        $result = [
1966
+            'success' => false,
1967
+            'result' => '',
1968
+        ];
1969
+        $try = 0;
1970
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
1971
+        while ($result['success'] === false && $try < 2) {
1972
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
1973
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
1974
+            $client = \OC::$server->getHTTPClientService()->newClient();
1975
+
1976
+            try {
1977
+                $response = $client->post(
1978
+                    $protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT,
1979
+                    [
1980
+                        'body' => $fields,
1981
+                        'connect_timeout' => 10,
1982
+                    ]
1983
+                );
1984
+
1985
+                $result = ['success' => true, 'result' => $response->getBody()];
1986
+            } catch (\Exception $e) {
1987
+                $result = ['success' => false, 'result' => $e->getMessage()];
1988
+            }
1989
+
1990
+            $try++;
1991
+            $protocol = 'http://';
1992
+        }
1993
+
1994
+        return $result;
1995
+    }
1996
+
1997
+    /**
1998
+     * send server-to-server share to remote server
1999
+     *
2000
+     * @param string $token
2001
+     * @param string $shareWith
2002
+     * @param string $name
2003
+     * @param int $remote_id
2004
+     * @param string $owner
2005
+     * @return bool
2006
+     */
2007
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2008
+
2009
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2010
+
2011
+        if ($user && $remote) {
2012
+            $url = $remote;
2013
+
2014
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2015
+
2016
+            $fields = array(
2017
+                'shareWith' => $user,
2018
+                'token' => $token,
2019
+                'name' => $name,
2020
+                'remoteId' => $remote_id,
2021
+                'owner' => $owner,
2022
+                'remote' => $local,
2023
+            );
2024
+
2025
+            $url = self::removeProtocolFromUrl($url);
2026
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2027
+            $status = json_decode($result['result'], true);
2028
+
2029
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2030
+                \OC_Hook::emit(\OCP\Share::class, 'federated_share_added', ['server' => $remote]);
2031
+                return true;
2032
+            }
2033
+
2034
+        }
2035
+
2036
+        return false;
2037
+    }
2038
+
2039
+    /**
2040
+     * send server-to-server unshare to remote server
2041
+     *
2042
+     * @param string $remote url
2043
+     * @param int $id share id
2044
+     * @param string $token
2045
+     * @return bool
2046
+     */
2047
+    private static function sendRemoteUnshare($remote, $id, $token) {
2048
+        $url = rtrim($remote, '/');
2049
+        $fields = array('token' => $token, 'format' => 'json');
2050
+        $url = self::removeProtocolFromUrl($url);
2051
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2052
+        $status = json_decode($result['result'], true);
2053
+
2054
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2055
+    }
2056
+
2057
+    /**
2058
+     * check if user can only share with group members
2059
+     * @return bool
2060
+     */
2061
+    public static function shareWithGroupMembersOnly() {
2062
+        $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_only_share_with_group_members', 'no');
2063
+        return $value === 'yes';
2064
+    }
2065
+
2066
+    /**
2067
+     * @return bool
2068
+     */
2069
+    public static function isDefaultExpireDateEnabled() {
2070
+        $defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2071
+        return $defaultExpireDateEnabled === 'yes';
2072
+    }
2073
+
2074
+    /**
2075
+     * @return int
2076
+     */
2077
+    public static function getExpireInterval() {
2078
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2079
+    }
2080
+
2081
+    /**
2082
+     * Checks whether the given path is reachable for the given owner
2083
+     *
2084
+     * @param string $path path relative to files
2085
+     * @param string $ownerStorageId storage id of the owner
2086
+     *
2087
+     * @return boolean true if file is reachable, false otherwise
2088
+     */
2089
+    private static function isFileReachable($path, $ownerStorageId) {
2090
+        // if outside the home storage, file is always considered reachable
2091
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2092
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2093
+        )) {
2094
+            return true;
2095
+        }
2096
+
2097
+        // if inside the home storage, the file has to be under "/files/"
2098
+        $path = ltrim($path, '/');
2099
+        if (substr($path, 0, 6) === 'files/') {
2100
+            return true;
2101
+        }
2102
+
2103
+        return false;
2104
+    }
2105
+
2106
+    /**
2107
+     * @param IConfig $config
2108
+     * @return bool
2109
+     */
2110
+    public static function enforcePassword(IConfig $config) {
2111
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2112
+        return $enforcePassword === 'yes';
2113
+    }
2114
+
2115
+    /**
2116
+     * @param string $password
2117
+     * @throws \Exception
2118
+     */
2119
+    private static function verifyPassword($password) {
2120
+
2121
+        $accepted = true;
2122
+        $message = '';
2123
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2124
+            'password' => $password,
2125
+            'accepted' => &$accepted,
2126
+            'message' => &$message
2127
+        ]);
2128
+
2129
+        if (!$accepted) {
2130
+            throw new \Exception($message);
2131
+        }
2132
+    }
2133 2133
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 1 patch
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -68,384 +68,384 @@
 block discarded – undo
68 68
 
69 69
 class DIContainer extends SimpleContainer implements IAppContainer {
70 70
 
71
-	/**
72
-	 * @var array
73
-	 */
74
-	private $middleWares = array();
75
-
76
-	/** @var ServerContainer */
77
-	private $server;
78
-
79
-	/**
80
-	 * Put your class dependencies in here
81
-	 * @param string $appName the name of the app
82
-	 * @param array $urlParams
83
-	 * @param ServerContainer|null $server
84
-	 */
85
-	public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
86
-		parent::__construct();
87
-		$this['AppName'] = $appName;
88
-		$this['urlParams'] = $urlParams;
89
-
90
-		/** @var \OC\ServerContainer $server */
91
-		if ($server === null) {
92
-			$server = \OC::$server;
93
-		}
94
-		$this->server = $server;
95
-		$this->server->registerAppContainer($appName, $this);
96
-
97
-		// aliases
98
-		$this->registerAlias('appName', 'AppName');
99
-		$this->registerAlias('webRoot', 'WebRoot');
100
-		$this->registerAlias('userId', 'UserId');
101
-
102
-		/**
103
-		 * Core services
104
-		 */
105
-		$this->registerService(IOutput::class, function($c){
106
-			return new Output($this->getServer()->getWebRoot());
107
-		});
108
-
109
-		$this->registerService(Folder::class, function() {
110
-			return $this->getServer()->getUserFolder();
111
-		});
112
-
113
-		$this->registerService(IAppData::class, function (SimpleContainer $c) {
114
-			return $this->getServer()->getAppDataDir($c->query('AppName'));
115
-		});
116
-
117
-		$this->registerService(IL10N::class, function($c) {
118
-			return $this->getServer()->getL10N($c->query('AppName'));
119
-		});
120
-
121
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
122
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
123
-
124
-		$this->registerService(IRequest::class, function() {
125
-			return $this->getServer()->query(IRequest::class);
126
-		});
127
-		$this->registerAlias('Request', IRequest::class);
128
-
129
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
130
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
131
-
132
-		$this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
133
-
134
-		$this->registerService(IServerContainer::class, function ($c) {
135
-			return $this->getServer();
136
-		});
137
-		$this->registerAlias('ServerContainer', IServerContainer::class);
138
-
139
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
140
-			return $c->query(Manager::class);
141
-		});
142
-
143
-		$this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
144
-			return $c;
145
-		});
146
-
147
-		// commonly used attributes
148
-		$this->registerService('UserId', function ($c) {
149
-			return $c->query(IUserSession::class)->getSession()->get('user_id');
150
-		});
151
-
152
-		$this->registerService('WebRoot', function ($c) {
153
-			return $c->query('ServerContainer')->getWebRoot();
154
-		});
155
-
156
-		$this->registerService('OC_Defaults', function ($c) {
157
-			return $c->getServer()->getThemingDefaults();
158
-		});
159
-
160
-		$this->registerService(IManager::class, function ($c) {
161
-			return $this->getServer()->getEncryptionManager();
162
-		});
163
-
164
-		$this->registerService(IConfig::class, function ($c) {
165
-			return $c->query(OC\GlobalScale\Config::class);
166
-		});
167
-
168
-		$this->registerService(IValidator::class, function($c) {
169
-			return $c->query(Validator::class);
170
-		});
171
-
172
-		$this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
173
-			return new \OC\Security\IdentityProof\Manager(
174
-				$this->getServer()->query(\OC\Files\AppData\Factory::class),
175
-				$this->getServer()->getCrypto(),
176
-				$this->getServer()->getConfig()
177
-			);
178
-		});
179
-
180
-		$this->registerService('Protocol', function($c){
181
-			/** @var \OC\Server $server */
182
-			$server = $c->query('ServerContainer');
183
-			$protocol = $server->getRequest()->getHttpProtocol();
184
-			return new Http($_SERVER, $protocol);
185
-		});
186
-
187
-		$this->registerService('Dispatcher', function($c) {
188
-			return new Dispatcher(
189
-				$c['Protocol'],
190
-				$c['MiddlewareDispatcher'],
191
-				$c['ControllerMethodReflector'],
192
-				$c['Request']
193
-			);
194
-		});
195
-
196
-		/**
197
-		 * App Framework default arguments
198
-		 */
199
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
200
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
201
-		$this->registerParameter('corsMaxAge', 1728000);
202
-
203
-		/**
204
-		 * Middleware
205
-		 */
206
-		$app = $this;
207
-		$this->registerService('SecurityMiddleware', function($c) use ($app){
208
-			/** @var \OC\Server $server */
209
-			$server = $app->getServer();
210
-
211
-			return new SecurityMiddleware(
212
-				$c['Request'],
213
-				$c['ControllerMethodReflector'],
214
-				$server->getNavigationManager(),
215
-				$server->getURLGenerator(),
216
-				$server->getLogger(),
217
-				$c['AppName'],
218
-				$server->getUserSession()->isLoggedIn(),
219
-				$server->getGroupManager()->isAdmin($this->getUserId()),
220
-				$server->getContentSecurityPolicyManager(),
221
-				$server->getCsrfTokenManager(),
222
-				$server->getContentSecurityPolicyNonceManager(),
223
-				$server->getAppManager(),
224
-				$server->getL10N('lib')
225
-			);
226
-		});
227
-
228
-		$this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
229
-			/** @var \OC\Server $server */
230
-			$server = $app->getServer();
231
-
232
-			return new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
233
-				$c['ControllerMethodReflector'],
234
-				$server->getSession(),
235
-				$server->getUserSession(),
236
-				$server->query(ITimeFactory::class)
237
-			);
238
-		});
239
-
240
-		$this->registerService('BruteForceMiddleware', function($c) use ($app) {
241
-			/** @var \OC\Server $server */
242
-			$server = $app->getServer();
243
-
244
-			return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
245
-				$c['ControllerMethodReflector'],
246
-				$server->getBruteForceThrottler(),
247
-				$server->getRequest()
248
-			);
249
-		});
250
-
251
-		$this->registerService('RateLimitingMiddleware', function($c) use ($app) {
252
-			/** @var \OC\Server $server */
253
-			$server = $app->getServer();
254
-
255
-			return new RateLimitingMiddleware(
256
-				$server->getRequest(),
257
-				$server->getUserSession(),
258
-				$c['ControllerMethodReflector'],
259
-				$c->query(OC\Security\RateLimiting\Limiter::class)
260
-			);
261
-		});
262
-
263
-		$this->registerService('CORSMiddleware', function($c) {
264
-			return new CORSMiddleware(
265
-				$c['Request'],
266
-				$c['ControllerMethodReflector'],
267
-				$c->query(IUserSession::class),
268
-				$c->getServer()->getBruteForceThrottler()
269
-			);
270
-		});
271
-
272
-		$this->registerService('SessionMiddleware', function($c) use ($app) {
273
-			return new SessionMiddleware(
274
-				$c['Request'],
275
-				$c['ControllerMethodReflector'],
276
-				$app->getServer()->getSession()
277
-			);
278
-		});
279
-
280
-		$this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
281
-			$twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
282
-			$userSession = $app->getServer()->getUserSession();
283
-			$session = $app->getServer()->getSession();
284
-			$urlGenerator = $app->getServer()->getURLGenerator();
285
-			$reflector = $c['ControllerMethodReflector'];
286
-			$request = $app->getServer()->getRequest();
287
-			return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
288
-		});
289
-
290
-		$this->registerService('OCSMiddleware', function (SimpleContainer $c) {
291
-			return new OCSMiddleware(
292
-				$c['Request']
293
-			);
294
-		});
295
-
296
-		$this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
297
-			return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
298
-				$c['Request'],
299
-				$c['ControllerMethodReflector']
300
-			);
301
-		});
302
-
303
-		$middleWares = &$this->middleWares;
304
-		$this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
305
-			$dispatcher = new MiddlewareDispatcher();
306
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
307
-			$dispatcher->registerMiddleware($c['CORSMiddleware']);
308
-			$dispatcher->registerMiddleware($c['OCSMiddleware']);
309
-			$dispatcher->registerMiddleware($c['SecurityMiddleware']);
310
-			$dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class]);
311
-			$dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
312
-			$dispatcher->registerMiddleware($c['BruteForceMiddleware']);
313
-			$dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
314
-
315
-			foreach($middleWares as $middleWare) {
316
-				$dispatcher->registerMiddleware($c[$middleWare]);
317
-			}
318
-
319
-			$dispatcher->registerMiddleware($c['SessionMiddleware']);
320
-			return $dispatcher;
321
-		});
322
-
323
-	}
324
-
325
-	/**
326
-	 * @return \OCP\IServerContainer
327
-	 */
328
-	public function getServer()
329
-	{
330
-		return $this->server;
331
-	}
332
-
333
-	/**
334
-	 * @param string $middleWare
335
-	 * @return boolean|null
336
-	 */
337
-	public function registerMiddleWare($middleWare) {
338
-		$this->middleWares[] = $middleWare;
339
-	}
340
-
341
-	/**
342
-	 * used to return the appname of the set application
343
-	 * @return string the name of your application
344
-	 */
345
-	public function getAppName() {
346
-		return $this->query('AppName');
347
-	}
348
-
349
-	/**
350
-	 * @deprecated use IUserSession->isLoggedIn()
351
-	 * @return boolean
352
-	 */
353
-	public function isLoggedIn() {
354
-		return \OC::$server->getUserSession()->isLoggedIn();
355
-	}
356
-
357
-	/**
358
-	 * @deprecated use IGroupManager->isAdmin($userId)
359
-	 * @return boolean
360
-	 */
361
-	public function isAdminUser() {
362
-		$uid = $this->getUserId();
363
-		return \OC_User::isAdminUser($uid);
364
-	}
365
-
366
-	private function getUserId() {
367
-		return $this->getServer()->getSession()->get('user_id');
368
-	}
369
-
370
-	/**
371
-	 * @deprecated use the ILogger instead
372
-	 * @param string $message
373
-	 * @param string $level
374
-	 * @return mixed
375
-	 */
376
-	public function log($message, $level) {
377
-		switch($level){
378
-			case 'debug':
379
-				$level = ILogger::DEBUG;
380
-				break;
381
-			case 'info':
382
-				$level = ILogger::INFO;
383
-				break;
384
-			case 'warn':
385
-				$level = ILogger::WARN;
386
-				break;
387
-			case 'fatal':
388
-				$level = ILogger::FATAL;
389
-				break;
390
-			default:
391
-				$level = ILogger::ERROR;
392
-				break;
393
-		}
394
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
395
-	}
396
-
397
-	/**
398
-	 * Register a capability
399
-	 *
400
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
401
-	 */
402
-	public function registerCapability($serviceName) {
403
-		$this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
404
-			return $this->query($serviceName);
405
-		});
406
-	}
407
-
408
-	/**
409
-	 * @param string $name
410
-	 * @return mixed
411
-	 * @throws QueryException if the query could not be resolved
412
-	 */
413
-	public function query($name) {
414
-		try {
415
-			return $this->queryNoFallback($name);
416
-		} catch (QueryException $firstException) {
417
-			try {
418
-				return $this->getServer()->query($name);
419
-			} catch (QueryException $secondException) {
420
-				if ($firstException->getCode() === 1) {
421
-					throw $secondException;
422
-				}
423
-				throw $firstException;
424
-			}
425
-		}
426
-	}
427
-
428
-	/**
429
-	 * @param string $name
430
-	 * @return mixed
431
-	 * @throws QueryException if the query could not be resolved
432
-	 */
433
-	public function queryNoFallback($name) {
434
-		$name = $this->sanitizeName($name);
435
-
436
-		if ($this->offsetExists($name)) {
437
-			return parent::query($name);
438
-		} else {
439
-			if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
440
-				return parent::query($name);
441
-			} else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
442
-				return parent::query($name);
443
-			} else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
444
-				return parent::query($name);
445
-			}
446
-		}
447
-
448
-		throw new QueryException('Could not resolve ' . $name . '!' .
449
-			' Class can not be instantiated', 1);
450
-	}
71
+    /**
72
+     * @var array
73
+     */
74
+    private $middleWares = array();
75
+
76
+    /** @var ServerContainer */
77
+    private $server;
78
+
79
+    /**
80
+     * Put your class dependencies in here
81
+     * @param string $appName the name of the app
82
+     * @param array $urlParams
83
+     * @param ServerContainer|null $server
84
+     */
85
+    public function __construct($appName, $urlParams = array(), ServerContainer $server = null){
86
+        parent::__construct();
87
+        $this['AppName'] = $appName;
88
+        $this['urlParams'] = $urlParams;
89
+
90
+        /** @var \OC\ServerContainer $server */
91
+        if ($server === null) {
92
+            $server = \OC::$server;
93
+        }
94
+        $this->server = $server;
95
+        $this->server->registerAppContainer($appName, $this);
96
+
97
+        // aliases
98
+        $this->registerAlias('appName', 'AppName');
99
+        $this->registerAlias('webRoot', 'WebRoot');
100
+        $this->registerAlias('userId', 'UserId');
101
+
102
+        /**
103
+         * Core services
104
+         */
105
+        $this->registerService(IOutput::class, function($c){
106
+            return new Output($this->getServer()->getWebRoot());
107
+        });
108
+
109
+        $this->registerService(Folder::class, function() {
110
+            return $this->getServer()->getUserFolder();
111
+        });
112
+
113
+        $this->registerService(IAppData::class, function (SimpleContainer $c) {
114
+            return $this->getServer()->getAppDataDir($c->query('AppName'));
115
+        });
116
+
117
+        $this->registerService(IL10N::class, function($c) {
118
+            return $this->getServer()->getL10N($c->query('AppName'));
119
+        });
120
+
121
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
122
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
123
+
124
+        $this->registerService(IRequest::class, function() {
125
+            return $this->getServer()->query(IRequest::class);
126
+        });
127
+        $this->registerAlias('Request', IRequest::class);
128
+
129
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
130
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
131
+
132
+        $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class);
133
+
134
+        $this->registerService(IServerContainer::class, function ($c) {
135
+            return $this->getServer();
136
+        });
137
+        $this->registerAlias('ServerContainer', IServerContainer::class);
138
+
139
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) {
140
+            return $c->query(Manager::class);
141
+        });
142
+
143
+        $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) {
144
+            return $c;
145
+        });
146
+
147
+        // commonly used attributes
148
+        $this->registerService('UserId', function ($c) {
149
+            return $c->query(IUserSession::class)->getSession()->get('user_id');
150
+        });
151
+
152
+        $this->registerService('WebRoot', function ($c) {
153
+            return $c->query('ServerContainer')->getWebRoot();
154
+        });
155
+
156
+        $this->registerService('OC_Defaults', function ($c) {
157
+            return $c->getServer()->getThemingDefaults();
158
+        });
159
+
160
+        $this->registerService(IManager::class, function ($c) {
161
+            return $this->getServer()->getEncryptionManager();
162
+        });
163
+
164
+        $this->registerService(IConfig::class, function ($c) {
165
+            return $c->query(OC\GlobalScale\Config::class);
166
+        });
167
+
168
+        $this->registerService(IValidator::class, function($c) {
169
+            return $c->query(Validator::class);
170
+        });
171
+
172
+        $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) {
173
+            return new \OC\Security\IdentityProof\Manager(
174
+                $this->getServer()->query(\OC\Files\AppData\Factory::class),
175
+                $this->getServer()->getCrypto(),
176
+                $this->getServer()->getConfig()
177
+            );
178
+        });
179
+
180
+        $this->registerService('Protocol', function($c){
181
+            /** @var \OC\Server $server */
182
+            $server = $c->query('ServerContainer');
183
+            $protocol = $server->getRequest()->getHttpProtocol();
184
+            return new Http($_SERVER, $protocol);
185
+        });
186
+
187
+        $this->registerService('Dispatcher', function($c) {
188
+            return new Dispatcher(
189
+                $c['Protocol'],
190
+                $c['MiddlewareDispatcher'],
191
+                $c['ControllerMethodReflector'],
192
+                $c['Request']
193
+            );
194
+        });
195
+
196
+        /**
197
+         * App Framework default arguments
198
+         */
199
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
200
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
201
+        $this->registerParameter('corsMaxAge', 1728000);
202
+
203
+        /**
204
+         * Middleware
205
+         */
206
+        $app = $this;
207
+        $this->registerService('SecurityMiddleware', function($c) use ($app){
208
+            /** @var \OC\Server $server */
209
+            $server = $app->getServer();
210
+
211
+            return new SecurityMiddleware(
212
+                $c['Request'],
213
+                $c['ControllerMethodReflector'],
214
+                $server->getNavigationManager(),
215
+                $server->getURLGenerator(),
216
+                $server->getLogger(),
217
+                $c['AppName'],
218
+                $server->getUserSession()->isLoggedIn(),
219
+                $server->getGroupManager()->isAdmin($this->getUserId()),
220
+                $server->getContentSecurityPolicyManager(),
221
+                $server->getCsrfTokenManager(),
222
+                $server->getContentSecurityPolicyNonceManager(),
223
+                $server->getAppManager(),
224
+                $server->getL10N('lib')
225
+            );
226
+        });
227
+
228
+        $this->registerService(OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class, function ($c) use ($app) {
229
+            /** @var \OC\Server $server */
230
+            $server = $app->getServer();
231
+
232
+            return new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
233
+                $c['ControllerMethodReflector'],
234
+                $server->getSession(),
235
+                $server->getUserSession(),
236
+                $server->query(ITimeFactory::class)
237
+            );
238
+        });
239
+
240
+        $this->registerService('BruteForceMiddleware', function($c) use ($app) {
241
+            /** @var \OC\Server $server */
242
+            $server = $app->getServer();
243
+
244
+            return new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
245
+                $c['ControllerMethodReflector'],
246
+                $server->getBruteForceThrottler(),
247
+                $server->getRequest()
248
+            );
249
+        });
250
+
251
+        $this->registerService('RateLimitingMiddleware', function($c) use ($app) {
252
+            /** @var \OC\Server $server */
253
+            $server = $app->getServer();
254
+
255
+            return new RateLimitingMiddleware(
256
+                $server->getRequest(),
257
+                $server->getUserSession(),
258
+                $c['ControllerMethodReflector'],
259
+                $c->query(OC\Security\RateLimiting\Limiter::class)
260
+            );
261
+        });
262
+
263
+        $this->registerService('CORSMiddleware', function($c) {
264
+            return new CORSMiddleware(
265
+                $c['Request'],
266
+                $c['ControllerMethodReflector'],
267
+                $c->query(IUserSession::class),
268
+                $c->getServer()->getBruteForceThrottler()
269
+            );
270
+        });
271
+
272
+        $this->registerService('SessionMiddleware', function($c) use ($app) {
273
+            return new SessionMiddleware(
274
+                $c['Request'],
275
+                $c['ControllerMethodReflector'],
276
+                $app->getServer()->getSession()
277
+            );
278
+        });
279
+
280
+        $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) {
281
+            $twoFactorManager = $c->getServer()->getTwoFactorAuthManager();
282
+            $userSession = $app->getServer()->getUserSession();
283
+            $session = $app->getServer()->getSession();
284
+            $urlGenerator = $app->getServer()->getURLGenerator();
285
+            $reflector = $c['ControllerMethodReflector'];
286
+            $request = $app->getServer()->getRequest();
287
+            return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request);
288
+        });
289
+
290
+        $this->registerService('OCSMiddleware', function (SimpleContainer $c) {
291
+            return new OCSMiddleware(
292
+                $c['Request']
293
+            );
294
+        });
295
+
296
+        $this->registerService(OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class, function (SimpleContainer $c) {
297
+            return new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
298
+                $c['Request'],
299
+                $c['ControllerMethodReflector']
300
+            );
301
+        });
302
+
303
+        $middleWares = &$this->middleWares;
304
+        $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) {
305
+            $dispatcher = new MiddlewareDispatcher();
306
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware::class]);
307
+            $dispatcher->registerMiddleware($c['CORSMiddleware']);
308
+            $dispatcher->registerMiddleware($c['OCSMiddleware']);
309
+            $dispatcher->registerMiddleware($c['SecurityMiddleware']);
310
+            $dispatcher->registerMiddleware($c[OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware::class]);
311
+            $dispatcher->registerMiddleware($c['TwoFactorMiddleware']);
312
+            $dispatcher->registerMiddleware($c['BruteForceMiddleware']);
313
+            $dispatcher->registerMiddleware($c['RateLimitingMiddleware']);
314
+
315
+            foreach($middleWares as $middleWare) {
316
+                $dispatcher->registerMiddleware($c[$middleWare]);
317
+            }
318
+
319
+            $dispatcher->registerMiddleware($c['SessionMiddleware']);
320
+            return $dispatcher;
321
+        });
322
+
323
+    }
324
+
325
+    /**
326
+     * @return \OCP\IServerContainer
327
+     */
328
+    public function getServer()
329
+    {
330
+        return $this->server;
331
+    }
332
+
333
+    /**
334
+     * @param string $middleWare
335
+     * @return boolean|null
336
+     */
337
+    public function registerMiddleWare($middleWare) {
338
+        $this->middleWares[] = $middleWare;
339
+    }
340
+
341
+    /**
342
+     * used to return the appname of the set application
343
+     * @return string the name of your application
344
+     */
345
+    public function getAppName() {
346
+        return $this->query('AppName');
347
+    }
348
+
349
+    /**
350
+     * @deprecated use IUserSession->isLoggedIn()
351
+     * @return boolean
352
+     */
353
+    public function isLoggedIn() {
354
+        return \OC::$server->getUserSession()->isLoggedIn();
355
+    }
356
+
357
+    /**
358
+     * @deprecated use IGroupManager->isAdmin($userId)
359
+     * @return boolean
360
+     */
361
+    public function isAdminUser() {
362
+        $uid = $this->getUserId();
363
+        return \OC_User::isAdminUser($uid);
364
+    }
365
+
366
+    private function getUserId() {
367
+        return $this->getServer()->getSession()->get('user_id');
368
+    }
369
+
370
+    /**
371
+     * @deprecated use the ILogger instead
372
+     * @param string $message
373
+     * @param string $level
374
+     * @return mixed
375
+     */
376
+    public function log($message, $level) {
377
+        switch($level){
378
+            case 'debug':
379
+                $level = ILogger::DEBUG;
380
+                break;
381
+            case 'info':
382
+                $level = ILogger::INFO;
383
+                break;
384
+            case 'warn':
385
+                $level = ILogger::WARN;
386
+                break;
387
+            case 'fatal':
388
+                $level = ILogger::FATAL;
389
+                break;
390
+            default:
391
+                $level = ILogger::ERROR;
392
+                break;
393
+        }
394
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
395
+    }
396
+
397
+    /**
398
+     * Register a capability
399
+     *
400
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
401
+     */
402
+    public function registerCapability($serviceName) {
403
+        $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) {
404
+            return $this->query($serviceName);
405
+        });
406
+    }
407
+
408
+    /**
409
+     * @param string $name
410
+     * @return mixed
411
+     * @throws QueryException if the query could not be resolved
412
+     */
413
+    public function query($name) {
414
+        try {
415
+            return $this->queryNoFallback($name);
416
+        } catch (QueryException $firstException) {
417
+            try {
418
+                return $this->getServer()->query($name);
419
+            } catch (QueryException $secondException) {
420
+                if ($firstException->getCode() === 1) {
421
+                    throw $secondException;
422
+                }
423
+                throw $firstException;
424
+            }
425
+        }
426
+    }
427
+
428
+    /**
429
+     * @param string $name
430
+     * @return mixed
431
+     * @throws QueryException if the query could not be resolved
432
+     */
433
+    public function queryNoFallback($name) {
434
+        $name = $this->sanitizeName($name);
435
+
436
+        if ($this->offsetExists($name)) {
437
+            return parent::query($name);
438
+        } else {
439
+            if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
440
+                return parent::query($name);
441
+            } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
442
+                return parent::query($name);
443
+            } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
444
+                return parent::query($name);
445
+            }
446
+        }
447
+
448
+        throw new QueryException('Could not resolve ' . $name . '!' .
449
+            ' Class can not be instantiated', 1);
450
+    }
451 451
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Middleware/Security/SecurityMiddleware.php 1 patch
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -66,98 +66,98 @@  discard block
 block discarded – undo
66 66
  * check fails
67 67
  */
68 68
 class SecurityMiddleware extends Middleware {
69
-	/** @var INavigationManager */
70
-	private $navigationManager;
71
-	/** @var IRequest */
72
-	private $request;
73
-	/** @var ControllerMethodReflector */
74
-	private $reflector;
75
-	/** @var string */
76
-	private $appName;
77
-	/** @var IURLGenerator */
78
-	private $urlGenerator;
79
-	/** @var ILogger */
80
-	private $logger;
81
-	/** @var bool */
82
-	private $isLoggedIn;
83
-	/** @var bool */
84
-	private $isAdminUser;
85
-	/** @var ContentSecurityPolicyManager */
86
-	private $contentSecurityPolicyManager;
87
-	/** @var CsrfTokenManager */
88
-	private $csrfTokenManager;
89
-	/** @var ContentSecurityPolicyNonceManager */
90
-	private $cspNonceManager;
91
-	/** @var IAppManager */
92
-	private $appManager;
93
-	/** @var IL10N */
94
-	private $l10n;
69
+    /** @var INavigationManager */
70
+    private $navigationManager;
71
+    /** @var IRequest */
72
+    private $request;
73
+    /** @var ControllerMethodReflector */
74
+    private $reflector;
75
+    /** @var string */
76
+    private $appName;
77
+    /** @var IURLGenerator */
78
+    private $urlGenerator;
79
+    /** @var ILogger */
80
+    private $logger;
81
+    /** @var bool */
82
+    private $isLoggedIn;
83
+    /** @var bool */
84
+    private $isAdminUser;
85
+    /** @var ContentSecurityPolicyManager */
86
+    private $contentSecurityPolicyManager;
87
+    /** @var CsrfTokenManager */
88
+    private $csrfTokenManager;
89
+    /** @var ContentSecurityPolicyNonceManager */
90
+    private $cspNonceManager;
91
+    /** @var IAppManager */
92
+    private $appManager;
93
+    /** @var IL10N */
94
+    private $l10n;
95 95
 
96
-	public function __construct(IRequest $request,
97
-								ControllerMethodReflector $reflector,
98
-								INavigationManager $navigationManager,
99
-								IURLGenerator $urlGenerator,
100
-								ILogger $logger,
101
-								string $appName,
102
-								bool $isLoggedIn,
103
-								bool $isAdminUser,
104
-								ContentSecurityPolicyManager $contentSecurityPolicyManager,
105
-								CsrfTokenManager $csrfTokenManager,
106
-								ContentSecurityPolicyNonceManager $cspNonceManager,
107
-								IAppManager $appManager,
108
-								IL10N $l10n
109
-	) {
110
-		$this->navigationManager = $navigationManager;
111
-		$this->request = $request;
112
-		$this->reflector = $reflector;
113
-		$this->appName = $appName;
114
-		$this->urlGenerator = $urlGenerator;
115
-		$this->logger = $logger;
116
-		$this->isLoggedIn = $isLoggedIn;
117
-		$this->isAdminUser = $isAdminUser;
118
-		$this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
119
-		$this->csrfTokenManager = $csrfTokenManager;
120
-		$this->cspNonceManager = $cspNonceManager;
121
-		$this->appManager = $appManager;
122
-		$this->l10n = $l10n;
123
-	}
96
+    public function __construct(IRequest $request,
97
+                                ControllerMethodReflector $reflector,
98
+                                INavigationManager $navigationManager,
99
+                                IURLGenerator $urlGenerator,
100
+                                ILogger $logger,
101
+                                string $appName,
102
+                                bool $isLoggedIn,
103
+                                bool $isAdminUser,
104
+                                ContentSecurityPolicyManager $contentSecurityPolicyManager,
105
+                                CsrfTokenManager $csrfTokenManager,
106
+                                ContentSecurityPolicyNonceManager $cspNonceManager,
107
+                                IAppManager $appManager,
108
+                                IL10N $l10n
109
+    ) {
110
+        $this->navigationManager = $navigationManager;
111
+        $this->request = $request;
112
+        $this->reflector = $reflector;
113
+        $this->appName = $appName;
114
+        $this->urlGenerator = $urlGenerator;
115
+        $this->logger = $logger;
116
+        $this->isLoggedIn = $isLoggedIn;
117
+        $this->isAdminUser = $isAdminUser;
118
+        $this->contentSecurityPolicyManager = $contentSecurityPolicyManager;
119
+        $this->csrfTokenManager = $csrfTokenManager;
120
+        $this->cspNonceManager = $cspNonceManager;
121
+        $this->appManager = $appManager;
122
+        $this->l10n = $l10n;
123
+    }
124 124
 
125
-	/**
126
-	 * This runs all the security checks before a method call. The
127
-	 * security checks are determined by inspecting the controller method
128
-	 * annotations
129
-	 * @param Controller $controller the controller
130
-	 * @param string $methodName the name of the method
131
-	 * @throws SecurityException when a security check fails
132
-	 */
133
-	public function beforeController($controller, $methodName) {
125
+    /**
126
+     * This runs all the security checks before a method call. The
127
+     * security checks are determined by inspecting the controller method
128
+     * annotations
129
+     * @param Controller $controller the controller
130
+     * @param string $methodName the name of the method
131
+     * @throws SecurityException when a security check fails
132
+     */
133
+    public function beforeController($controller, $methodName) {
134 134
 
135
-		// this will set the current navigation entry of the app, use this only
136
-		// for normal HTML requests and not for AJAX requests
137
-		$this->navigationManager->setActiveEntry($this->appName);
135
+        // this will set the current navigation entry of the app, use this only
136
+        // for normal HTML requests and not for AJAX requests
137
+        $this->navigationManager->setActiveEntry($this->appName);
138 138
 
139
-		// security checks
140
-		$isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
-		if(!$isPublicPage) {
142
-			if(!$this->isLoggedIn) {
143
-				throw new NotLoggedInException();
144
-			}
139
+        // security checks
140
+        $isPublicPage = $this->reflector->hasAnnotation('PublicPage');
141
+        if(!$isPublicPage) {
142
+            if(!$this->isLoggedIn) {
143
+                throw new NotLoggedInException();
144
+            }
145 145
 
146
-			if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147
-				throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148
-			}
149
-		}
146
+            if(!$this->reflector->hasAnnotation('NoAdminRequired') && !$this->isAdminUser) {
147
+                throw new NotAdminException($this->l10n->t('Logged in user must be an admin'));
148
+            }
149
+        }
150 150
 
151
-		// Check for strict cookie requirement
152
-		if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
-			if(!$this->request->passesStrictCookieCheck()) {
154
-				throw new StrictCookieMissingException();
155
-			}
156
-		}
157
-		// CSRF check - also registers the CSRF token since the session may be closed later
158
-		Util::callRegister();
159
-		if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160
-			/*
151
+        // Check for strict cookie requirement
152
+        if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) {
153
+            if(!$this->request->passesStrictCookieCheck()) {
154
+                throw new StrictCookieMissingException();
155
+            }
156
+        }
157
+        // CSRF check - also registers the CSRF token since the session may be closed later
158
+        Util::callRegister();
159
+        if(!$this->reflector->hasAnnotation('NoCSRFRequired')) {
160
+            /*
161 161
 			 * Only allow the CSRF check to fail on OCS Requests. This kind of
162 162
 			 * hacks around that we have no full token auth in place yet and we
163 163
 			 * do want to offer CSRF checks for web requests.
@@ -165,103 +165,103 @@  discard block
 block discarded – undo
165 165
 			 * Additionally we allow Bearer authenticated requests to pass on OCS routes.
166 166
 			 * This allows oauth apps (e.g. moodle) to use the OCS endpoints
167 167
 			 */
168
-			if(!$this->request->passesCSRFCheck() && !(
169
-					$controller instanceof OCSController && (
170
-						$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171
-						strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
172
-					)
173
-				)) {
174
-				throw new CrossSiteRequestForgeryException();
175
-			}
176
-		}
168
+            if(!$this->request->passesCSRFCheck() && !(
169
+                    $controller instanceof OCSController && (
170
+                        $this->request->getHeader('OCS-APIREQUEST') === 'true' ||
171
+                        strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
172
+                    )
173
+                )) {
174
+                throw new CrossSiteRequestForgeryException();
175
+            }
176
+        }
177 177
 
178
-		/**
179
-		 * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
180
-		 * The getAppPath() check is here since components such as settings also use the AppFramework and
181
-		 * therefore won't pass this check.
182
-		 * If page is public, app does not need to be enabled for current user/visitor
183
-		 */
184
-		try {
185
-			$appPath = $this->appManager->getAppPath($this->appName);
186
-		} catch (AppPathNotFoundException $e) {
187
-			$appPath = false;
188
-		}
178
+        /**
179
+         * Checks if app is enabled (also includes a check whether user is allowed to access the resource)
180
+         * The getAppPath() check is here since components such as settings also use the AppFramework and
181
+         * therefore won't pass this check.
182
+         * If page is public, app does not need to be enabled for current user/visitor
183
+         */
184
+        try {
185
+            $appPath = $this->appManager->getAppPath($this->appName);
186
+        } catch (AppPathNotFoundException $e) {
187
+            $appPath = false;
188
+        }
189 189
 
190
-		if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
191
-			throw new AppNotEnabledException();
192
-		}
193
-	}
190
+        if ($appPath !== false && !$isPublicPage && !$this->appManager->isEnabledForUser($this->appName)) {
191
+            throw new AppNotEnabledException();
192
+        }
193
+    }
194 194
 
195
-	/**
196
-	 * Performs the default CSP modifications that may be injected by other
197
-	 * applications
198
-	 *
199
-	 * @param Controller $controller
200
-	 * @param string $methodName
201
-	 * @param Response $response
202
-	 * @return Response
203
-	 */
204
-	public function afterController($controller, $methodName, Response $response): Response {
205
-		$policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
195
+    /**
196
+     * Performs the default CSP modifications that may be injected by other
197
+     * applications
198
+     *
199
+     * @param Controller $controller
200
+     * @param string $methodName
201
+     * @param Response $response
202
+     * @return Response
203
+     */
204
+    public function afterController($controller, $methodName, Response $response): Response {
205
+        $policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy();
206 206
 
207
-		if (get_class($policy) === EmptyContentSecurityPolicy::class) {
208
-			return $response;
209
-		}
207
+        if (get_class($policy) === EmptyContentSecurityPolicy::class) {
208
+            return $response;
209
+        }
210 210
 
211
-		$defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212
-		$defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
211
+        $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy();
212
+        $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy);
213 213
 
214
-		if($this->cspNonceManager->browserSupportsCspV3()) {
215
-			$defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216
-		}
214
+        if($this->cspNonceManager->browserSupportsCspV3()) {
215
+            $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue());
216
+        }
217 217
 
218
-		$response->setContentSecurityPolicy($defaultPolicy);
218
+        $response->setContentSecurityPolicy($defaultPolicy);
219 219
 
220
-		return $response;
221
-	}
220
+        return $response;
221
+    }
222 222
 
223
-	/**
224
-	 * If an SecurityException is being caught, ajax requests return a JSON error
225
-	 * response and non ajax requests redirect to the index
226
-	 * @param Controller $controller the controller that is being called
227
-	 * @param string $methodName the name of the method that will be called on
228
-	 *                           the controller
229
-	 * @param \Exception $exception the thrown exception
230
-	 * @throws \Exception the passed in exception if it can't handle it
231
-	 * @return Response a Response object or null in case that the exception could not be handled
232
-	 */
233
-	public function afterException($controller, $methodName, \Exception $exception): Response {
234
-		if($exception instanceof SecurityException) {
235
-			if($exception instanceof StrictCookieMissingException) {
236
-				return new RedirectResponse(\OC::$WEBROOT);
237
- 			}
238
-			if (stripos($this->request->getHeader('Accept'),'html') === false) {
239
-				$response = new JSONResponse(
240
-					['message' => $exception->getMessage()],
241
-					$exception->getCode()
242
-				);
243
-			} else {
244
-				if($exception instanceof NotLoggedInException) {
245
-					$params = [];
246
-					if (isset($this->request->server['REQUEST_URI'])) {
247
-						$params['redirect_url'] = $this->request->server['REQUEST_URI'];
248
-					}
249
-					$url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
250
-					$response = new RedirectResponse($url);
251
-				} else {
252
-					$response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
253
-					$response->setStatus($exception->getCode());
254
-				}
255
-			}
223
+    /**
224
+     * If an SecurityException is being caught, ajax requests return a JSON error
225
+     * response and non ajax requests redirect to the index
226
+     * @param Controller $controller the controller that is being called
227
+     * @param string $methodName the name of the method that will be called on
228
+     *                           the controller
229
+     * @param \Exception $exception the thrown exception
230
+     * @throws \Exception the passed in exception if it can't handle it
231
+     * @return Response a Response object or null in case that the exception could not be handled
232
+     */
233
+    public function afterException($controller, $methodName, \Exception $exception): Response {
234
+        if($exception instanceof SecurityException) {
235
+            if($exception instanceof StrictCookieMissingException) {
236
+                return new RedirectResponse(\OC::$WEBROOT);
237
+                }
238
+            if (stripos($this->request->getHeader('Accept'),'html') === false) {
239
+                $response = new JSONResponse(
240
+                    ['message' => $exception->getMessage()],
241
+                    $exception->getCode()
242
+                );
243
+            } else {
244
+                if($exception instanceof NotLoggedInException) {
245
+                    $params = [];
246
+                    if (isset($this->request->server['REQUEST_URI'])) {
247
+                        $params['redirect_url'] = $this->request->server['REQUEST_URI'];
248
+                    }
249
+                    $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params);
250
+                    $response = new RedirectResponse($url);
251
+                } else {
252
+                    $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest');
253
+                    $response->setStatus($exception->getCode());
254
+                }
255
+            }
256 256
 
257
-			$this->logger->logException($exception, [
258
-				'level' => ILogger::DEBUG,
259
-				'app' => 'core',
260
-			]);
261
-			return $response;
262
-		}
257
+            $this->logger->logException($exception, [
258
+                'level' => ILogger::DEBUG,
259
+                'app' => 'core',
260
+            ]);
261
+            return $response;
262
+        }
263 263
 
264
-		throw $exception;
265
-	}
264
+        throw $exception;
265
+    }
266 266
 
267 267
 }
Please login to merge, or discard this patch.
lib/private/Archive/ZIP.php 1 patch
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -34,199 +34,199 @@
 block discarded – undo
34 34
 use OCP\ILogger;
35 35
 
36 36
 class ZIP extends Archive{
37
-	/**
38
-	 * @var \ZipArchive zip
39
-	 */
40
-	private $zip=null;
41
-	private $path;
37
+    /**
38
+     * @var \ZipArchive zip
39
+     */
40
+    private $zip=null;
41
+    private $path;
42 42
 
43
-	/**
44
-	 * @param string $source
45
-	 */
46
-	public function __construct($source) {
47
-		$this->path=$source;
48
-		$this->zip=new \ZipArchive();
49
-		if($this->zip->open($source, \ZipArchive::CREATE)) {
50
-		}else{
51
-			\OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN);
52
-		}
53
-	}
54
-	/**
55
-	 * add an empty folder to the archive
56
-	 * @param string $path
57
-	 * @return bool
58
-	 */
59
-	public function addFolder($path) {
60
-		return $this->zip->addEmptyDir($path);
61
-	}
62
-	/**
63
-	 * add a file to the archive
64
-	 * @param string $path
65
-	 * @param string $source either a local file or string data
66
-	 * @return bool
67
-	 */
68
-	public function addFile($path, $source='') {
69
-		if($source and $source[0]=='/' and file_exists($source)) {
70
-			$result=$this->zip->addFile($source, $path);
71
-		}else{
72
-			$result=$this->zip->addFromString($path, $source);
73
-		}
74
-		if($result) {
75
-			$this->zip->close();//close and reopen to save the zip
76
-			$this->zip->open($this->path);
77
-		}
78
-		return $result;
79
-	}
80
-	/**
81
-	 * rename a file or folder in the archive
82
-	 * @param string $source
83
-	 * @param string $dest
84
-	 * @return boolean|null
85
-	 */
86
-	public function rename($source, $dest) {
87
-		$source=$this->stripPath($source);
88
-		$dest=$this->stripPath($dest);
89
-		$this->zip->renameName($source, $dest);
90
-	}
91
-	/**
92
-	 * get the uncompressed size of a file in the archive
93
-	 * @param string $path
94
-	 * @return int
95
-	 */
96
-	public function filesize($path) {
97
-		$stat=$this->zip->statName($path);
98
-		return $stat['size'];
99
-	}
100
-	/**
101
-	 * get the last modified time of a file in the archive
102
-	 * @param string $path
103
-	 * @return int
104
-	 */
105
-	public function mtime($path) {
106
-		return filemtime($this->path);
107
-	}
108
-	/**
109
-	 * get the files in a folder
110
-	 * @param string $path
111
-	 * @return array
112
-	 */
113
-	public function getFolder($path) {
114
-		$files=$this->getFiles();
115
-		$folderContent=array();
116
-		$pathLength=strlen($path);
117
-		foreach($files as $file) {
118
-			if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
-				if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
-					$folderContent[]=substr($file, $pathLength);
121
-				}
122
-			}
123
-		}
124
-		return $folderContent;
125
-	}
126
-	/**
127
-	 * get all files in the archive
128
-	 * @return array
129
-	 */
130
-	public function getFiles() {
131
-		$fileCount=$this->zip->numFiles;
132
-		$files=array();
133
-		for($i=0;$i<$fileCount;$i++) {
134
-			$files[]=$this->zip->getNameIndex($i);
135
-		}
136
-		return $files;
137
-	}
138
-	/**
139
-	 * get the content of a file
140
-	 * @param string $path
141
-	 * @return string
142
-	 */
143
-	public function getFile($path) {
144
-		return $this->zip->getFromName($path);
145
-	}
146
-	/**
147
-	 * extract a single file from the archive
148
-	 * @param string $path
149
-	 * @param string $dest
150
-	 * @return boolean|null
151
-	 */
152
-	public function extractFile($path, $dest) {
153
-		$fp = $this->zip->getStream($path);
154
-		file_put_contents($dest, $fp);
155
-	}
156
-	/**
157
-	 * extract the archive
158
-	 * @param string $dest
159
-	 * @return bool
160
-	 */
161
-	public function extract($dest) {
162
-		return $this->zip->extractTo($dest);
163
-	}
164
-	/**
165
-	 * check if a file or folder exists in the archive
166
-	 * @param string $path
167
-	 * @return bool
168
-	 */
169
-	public function fileExists($path) {
170
-		return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
-	}
172
-	/**
173
-	 * remove a file or folder from the archive
174
-	 * @param string $path
175
-	 * @return bool
176
-	 */
177
-	public function remove($path) {
178
-		if($this->fileExists($path.'/')) {
179
-			return $this->zip->deleteName($path.'/');
180
-		}else{
181
-			return $this->zip->deleteName($path);
182
-		}
183
-	}
184
-	/**
185
-	 * get a file handler
186
-	 * @param string $path
187
-	 * @param string $mode
188
-	 * @return resource
189
-	 */
190
-	public function getStream($path, $mode) {
191
-		if($mode=='r' or $mode=='rb') {
192
-			return $this->zip->getStream($path);
193
-		} else {
194
-			//since we can't directly get a writable stream,
195
-			//make a temp copy of the file and put it back
196
-			//in the archive when the stream is closed
197
-			if(strrpos($path, '.')!==false) {
198
-				$ext=substr($path, strrpos($path, '.'));
199
-			}else{
200
-				$ext='';
201
-			}
202
-			$tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
203
-			if($this->fileExists($path)) {
204
-				$this->extractFile($path, $tmpFile);
205
-			}
206
-			$handle = fopen($tmpFile, $mode);
207
-			return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
-				$this->writeBack($tmpFile, $path);
209
-			});
210
-		}
211
-	}
43
+    /**
44
+     * @param string $source
45
+     */
46
+    public function __construct($source) {
47
+        $this->path=$source;
48
+        $this->zip=new \ZipArchive();
49
+        if($this->zip->open($source, \ZipArchive::CREATE)) {
50
+        }else{
51
+            \OCP\Util::writeLog('files_archive', 'Error while opening archive '.$source, ILogger::WARN);
52
+        }
53
+    }
54
+    /**
55
+     * add an empty folder to the archive
56
+     * @param string $path
57
+     * @return bool
58
+     */
59
+    public function addFolder($path) {
60
+        return $this->zip->addEmptyDir($path);
61
+    }
62
+    /**
63
+     * add a file to the archive
64
+     * @param string $path
65
+     * @param string $source either a local file or string data
66
+     * @return bool
67
+     */
68
+    public function addFile($path, $source='') {
69
+        if($source and $source[0]=='/' and file_exists($source)) {
70
+            $result=$this->zip->addFile($source, $path);
71
+        }else{
72
+            $result=$this->zip->addFromString($path, $source);
73
+        }
74
+        if($result) {
75
+            $this->zip->close();//close and reopen to save the zip
76
+            $this->zip->open($this->path);
77
+        }
78
+        return $result;
79
+    }
80
+    /**
81
+     * rename a file or folder in the archive
82
+     * @param string $source
83
+     * @param string $dest
84
+     * @return boolean|null
85
+     */
86
+    public function rename($source, $dest) {
87
+        $source=$this->stripPath($source);
88
+        $dest=$this->stripPath($dest);
89
+        $this->zip->renameName($source, $dest);
90
+    }
91
+    /**
92
+     * get the uncompressed size of a file in the archive
93
+     * @param string $path
94
+     * @return int
95
+     */
96
+    public function filesize($path) {
97
+        $stat=$this->zip->statName($path);
98
+        return $stat['size'];
99
+    }
100
+    /**
101
+     * get the last modified time of a file in the archive
102
+     * @param string $path
103
+     * @return int
104
+     */
105
+    public function mtime($path) {
106
+        return filemtime($this->path);
107
+    }
108
+    /**
109
+     * get the files in a folder
110
+     * @param string $path
111
+     * @return array
112
+     */
113
+    public function getFolder($path) {
114
+        $files=$this->getFiles();
115
+        $folderContent=array();
116
+        $pathLength=strlen($path);
117
+        foreach($files as $file) {
118
+            if(substr($file, 0, $pathLength)==$path and $file!=$path) {
119
+                if(strrpos(substr($file, 0, -1), '/')<=$pathLength) {
120
+                    $folderContent[]=substr($file, $pathLength);
121
+                }
122
+            }
123
+        }
124
+        return $folderContent;
125
+    }
126
+    /**
127
+     * get all files in the archive
128
+     * @return array
129
+     */
130
+    public function getFiles() {
131
+        $fileCount=$this->zip->numFiles;
132
+        $files=array();
133
+        for($i=0;$i<$fileCount;$i++) {
134
+            $files[]=$this->zip->getNameIndex($i);
135
+        }
136
+        return $files;
137
+    }
138
+    /**
139
+     * get the content of a file
140
+     * @param string $path
141
+     * @return string
142
+     */
143
+    public function getFile($path) {
144
+        return $this->zip->getFromName($path);
145
+    }
146
+    /**
147
+     * extract a single file from the archive
148
+     * @param string $path
149
+     * @param string $dest
150
+     * @return boolean|null
151
+     */
152
+    public function extractFile($path, $dest) {
153
+        $fp = $this->zip->getStream($path);
154
+        file_put_contents($dest, $fp);
155
+    }
156
+    /**
157
+     * extract the archive
158
+     * @param string $dest
159
+     * @return bool
160
+     */
161
+    public function extract($dest) {
162
+        return $this->zip->extractTo($dest);
163
+    }
164
+    /**
165
+     * check if a file or folder exists in the archive
166
+     * @param string $path
167
+     * @return bool
168
+     */
169
+    public function fileExists($path) {
170
+        return ($this->zip->locateName($path)!==false) or ($this->zip->locateName($path.'/')!==false);
171
+    }
172
+    /**
173
+     * remove a file or folder from the archive
174
+     * @param string $path
175
+     * @return bool
176
+     */
177
+    public function remove($path) {
178
+        if($this->fileExists($path.'/')) {
179
+            return $this->zip->deleteName($path.'/');
180
+        }else{
181
+            return $this->zip->deleteName($path);
182
+        }
183
+    }
184
+    /**
185
+     * get a file handler
186
+     * @param string $path
187
+     * @param string $mode
188
+     * @return resource
189
+     */
190
+    public function getStream($path, $mode) {
191
+        if($mode=='r' or $mode=='rb') {
192
+            return $this->zip->getStream($path);
193
+        } else {
194
+            //since we can't directly get a writable stream,
195
+            //make a temp copy of the file and put it back
196
+            //in the archive when the stream is closed
197
+            if(strrpos($path, '.')!==false) {
198
+                $ext=substr($path, strrpos($path, '.'));
199
+            }else{
200
+                $ext='';
201
+            }
202
+            $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
203
+            if($this->fileExists($path)) {
204
+                $this->extractFile($path, $tmpFile);
205
+            }
206
+            $handle = fopen($tmpFile, $mode);
207
+            return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
208
+                $this->writeBack($tmpFile, $path);
209
+            });
210
+        }
211
+    }
212 212
 
213
-	/**
214
-	 * write back temporary files
215
-	 */
216
-	public function writeBack($tmpFile, $path) {
217
-		$this->addFile($path, $tmpFile);
218
-		unlink($tmpFile);
219
-	}
213
+    /**
214
+     * write back temporary files
215
+     */
216
+    public function writeBack($tmpFile, $path) {
217
+        $this->addFile($path, $tmpFile);
218
+        unlink($tmpFile);
219
+    }
220 220
 
221
-	/**
222
-	 * @param string $path
223
-	 * @return string
224
-	 */
225
-	private function stripPath($path) {
226
-		if(!$path || $path[0]=='/') {
227
-			return substr($path, 1);
228
-		}else{
229
-			return $path;
230
-		}
231
-	}
221
+    /**
222
+     * @param string $path
223
+     * @return string
224
+     */
225
+    private function stripPath($path) {
226
+        if(!$path || $path[0]=='/') {
227
+            return substr($path, 1);
228
+        }else{
229
+            return $path;
230
+        }
231
+    }
232 232
 }
Please login to merge, or discard this patch.
lib/private/Server.php 1 patch
Indentation   +1825 added lines, -1825 removed lines patch added patch discarded remove patch
@@ -153,1834 +153,1834 @@
 block discarded – undo
153 153
  * TODO: hookup all manager classes
154 154
  */
155 155
 class Server extends ServerContainer implements IServerContainer {
156
-	/** @var string */
157
-	private $webRoot;
158
-
159
-	/**
160
-	 * @param string $webRoot
161
-	 * @param \OC\Config $config
162
-	 */
163
-	public function __construct($webRoot, \OC\Config $config) {
164
-		parent::__construct();
165
-		$this->webRoot = $webRoot;
166
-
167
-		$this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
168
-			return $c;
169
-		});
170
-
171
-		$this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
172
-		$this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
173
-
174
-		$this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
175
-		$this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
176
-
177
-		$this->registerAlias(IActionFactory::class, ActionFactory::class);
178
-
179
-
180
-		$this->registerService(\OCP\IPreview::class, function (Server $c) {
181
-			return new PreviewManager(
182
-				$c->getConfig(),
183
-				$c->getRootFolder(),
184
-				$c->getAppDataDir('preview'),
185
-				$c->getEventDispatcher(),
186
-				$c->getSession()->get('user_id')
187
-			);
188
-		});
189
-		$this->registerAlias('PreviewManager', \OCP\IPreview::class);
190
-
191
-		$this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
192
-			return new \OC\Preview\Watcher(
193
-				$c->getAppDataDir('preview')
194
-			);
195
-		});
196
-
197
-		$this->registerService('EncryptionManager', function (Server $c) {
198
-			$view = new View();
199
-			$util = new Encryption\Util(
200
-				$view,
201
-				$c->getUserManager(),
202
-				$c->getGroupManager(),
203
-				$c->getConfig()
204
-			);
205
-			return new Encryption\Manager(
206
-				$c->getConfig(),
207
-				$c->getLogger(),
208
-				$c->getL10N('core'),
209
-				new View(),
210
-				$util,
211
-				new ArrayCache()
212
-			);
213
-		});
214
-
215
-		$this->registerService('EncryptionFileHelper', function (Server $c) {
216
-			$util = new Encryption\Util(
217
-				new View(),
218
-				$c->getUserManager(),
219
-				$c->getGroupManager(),
220
-				$c->getConfig()
221
-			);
222
-			return new Encryption\File(
223
-				$util,
224
-				$c->getRootFolder(),
225
-				$c->getShareManager()
226
-			);
227
-		});
228
-
229
-		$this->registerService('EncryptionKeyStorage', function (Server $c) {
230
-			$view = new View();
231
-			$util = new Encryption\Util(
232
-				$view,
233
-				$c->getUserManager(),
234
-				$c->getGroupManager(),
235
-				$c->getConfig()
236
-			);
237
-
238
-			return new Encryption\Keys\Storage($view, $util);
239
-		});
240
-		$this->registerService('TagMapper', function (Server $c) {
241
-			return new TagMapper($c->getDatabaseConnection());
242
-		});
243
-
244
-		$this->registerService(\OCP\ITagManager::class, function (Server $c) {
245
-			$tagMapper = $c->query('TagMapper');
246
-			return new TagManager($tagMapper, $c->getUserSession());
247
-		});
248
-		$this->registerAlias('TagManager', \OCP\ITagManager::class);
249
-
250
-		$this->registerService('SystemTagManagerFactory', function (Server $c) {
251
-			$config = $c->getConfig();
252
-			$factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
253
-			return new $factoryClass($this);
254
-		});
255
-		$this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
256
-			return $c->query('SystemTagManagerFactory')->getManager();
257
-		});
258
-		$this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
259
-
260
-		$this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
261
-			return $c->query('SystemTagManagerFactory')->getObjectMapper();
262
-		});
263
-		$this->registerService('RootFolder', function (Server $c) {
264
-			$manager = \OC\Files\Filesystem::getMountManager(null);
265
-			$view = new View();
266
-			$root = new Root(
267
-				$manager,
268
-				$view,
269
-				null,
270
-				$c->getUserMountCache(),
271
-				$this->getLogger(),
272
-				$this->getUserManager()
273
-			);
274
-			$connector = new HookConnector($root, $view);
275
-			$connector->viewToNode();
276
-
277
-			$previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
278
-			$previewConnector->connectWatcher();
279
-
280
-			return $root;
281
-		});
282
-		$this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
283
-
284
-		$this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
285
-			return new LazyRoot(function () use ($c) {
286
-				return $c->query('RootFolder');
287
-			});
288
-		});
289
-		$this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
290
-
291
-		$this->registerService(\OC\User\Manager::class, function (Server $c) {
292
-			$config = $c->getConfig();
293
-			return new \OC\User\Manager($config);
294
-		});
295
-		$this->registerAlias('UserManager', \OC\User\Manager::class);
296
-		$this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
297
-
298
-		$this->registerService(\OCP\IGroupManager::class, function (Server $c) {
299
-			$groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
300
-			$groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
301
-				\OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
302
-			});
303
-			$groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
304
-				\OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
305
-			});
306
-			$groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
307
-				\OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
308
-			});
309
-			$groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
310
-				\OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
311
-			});
312
-			$groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
-				\OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
314
-			});
315
-			$groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
316
-				\OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
317
-				//Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
318
-				\OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
319
-			});
320
-			return $groupManager;
321
-		});
322
-		$this->registerAlias('GroupManager', \OCP\IGroupManager::class);
323
-
324
-		$this->registerService(Store::class, function (Server $c) {
325
-			$session = $c->getSession();
326
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
327
-				$tokenProvider = $c->query(IProvider::class);
328
-			} else {
329
-				$tokenProvider = null;
330
-			}
331
-			$logger = $c->getLogger();
332
-			return new Store($session, $logger, $tokenProvider);
333
-		});
334
-		$this->registerAlias(IStore::class, Store::class);
335
-		$this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
336
-			$dbConnection = $c->getDatabaseConnection();
337
-			return new Authentication\Token\DefaultTokenMapper($dbConnection);
338
-		});
339
-		$this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
340
-			$mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
341
-			$crypto = $c->getCrypto();
342
-			$config = $c->getConfig();
343
-			$logger = $c->getLogger();
344
-			$timeFactory = new TimeFactory();
345
-			return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
346
-		});
347
-		$this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
348
-
349
-		$this->registerService(\OCP\IUserSession::class, function (Server $c) {
350
-			$manager = $c->getUserManager();
351
-			$session = new \OC\Session\Memory('');
352
-			$timeFactory = new TimeFactory();
353
-			// Token providers might require a working database. This code
354
-			// might however be called when ownCloud is not yet setup.
355
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
356
-				$defaultTokenProvider = $c->query(IProvider::class);
357
-			} else {
358
-				$defaultTokenProvider = null;
359
-			}
360
-
361
-			$dispatcher = $c->getEventDispatcher();
362
-
363
-			$userSession = new \OC\User\Session(
364
-				$manager,
365
-				$session,
366
-				$timeFactory,
367
-				$defaultTokenProvider,
368
-				$c->getConfig(),
369
-				$c->getSecureRandom(),
370
-				$c->getLockdownManager(),
371
-				$c->getLogger()
372
-			);
373
-			$userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
374
-				\OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
375
-			});
376
-			$userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
377
-				/** @var $user \OC\User\User */
378
-				\OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
379
-			});
380
-			$userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
381
-				/** @var $user \OC\User\User */
382
-				\OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
383
-				$dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
384
-			});
385
-			$userSession->listen('\OC\User', 'postDelete', function ($user) {
386
-				/** @var $user \OC\User\User */
387
-				\OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
388
-			});
389
-			$userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
390
-				/** @var $user \OC\User\User */
391
-				\OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392
-			});
393
-			$userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
394
-				/** @var $user \OC\User\User */
395
-				\OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
396
-			});
397
-			$userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
398
-				\OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
399
-			});
400
-			$userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
401
-				/** @var $user \OC\User\User */
402
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403
-			});
404
-			$userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
405
-				/** @var $user \OC\User\User */
406
-				\OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
407
-			});
408
-			$userSession->listen('\OC\User', 'logout', function () {
409
-				\OC_Hook::emit('OC_User', 'logout', array());
410
-			});
411
-			$userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
412
-				/** @var $user \OC\User\User */
413
-				\OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
414
-				$dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
415
-			});
416
-			return $userSession;
417
-		});
418
-		$this->registerAlias('UserSession', \OCP\IUserSession::class);
419
-
420
-		$this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
421
-			return new \OC\Authentication\TwoFactorAuth\Manager(
422
-				$c->getAppManager(),
423
-				$c->getSession(),
424
-				$c->getConfig(),
425
-				$c->getActivityManager(),
426
-				$c->getLogger(),
427
-				$c->query(IProvider::class),
428
-				$c->query(ITimeFactory::class),
429
-				$c->query(EventDispatcherInterface::class)
430
-			);
431
-		});
432
-
433
-		$this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
434
-		$this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
435
-
436
-		$this->registerService(\OC\AllConfig::class, function (Server $c) {
437
-			return new \OC\AllConfig(
438
-				$c->getSystemConfig()
439
-			);
440
-		});
441
-		$this->registerAlias('AllConfig', \OC\AllConfig::class);
442
-		$this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
443
-
444
-		$this->registerService('SystemConfig', function ($c) use ($config) {
445
-			return new \OC\SystemConfig($config);
446
-		});
447
-
448
-		$this->registerService(\OC\AppConfig::class, function (Server $c) {
449
-			return new \OC\AppConfig($c->getDatabaseConnection());
450
-		});
451
-		$this->registerAlias('AppConfig', \OC\AppConfig::class);
452
-		$this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
453
-
454
-		$this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
455
-			return new \OC\L10N\Factory(
456
-				$c->getConfig(),
457
-				$c->getRequest(),
458
-				$c->getUserSession(),
459
-				\OC::$SERVERROOT
460
-			);
461
-		});
462
-		$this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
463
-
464
-		$this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
465
-			$config = $c->getConfig();
466
-			$cacheFactory = $c->getMemCacheFactory();
467
-			$request = $c->getRequest();
468
-			return new \OC\URLGenerator(
469
-				$config,
470
-				$cacheFactory,
471
-				$request
472
-			);
473
-		});
474
-		$this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
475
-
476
-		$this->registerAlias('AppFetcher', AppFetcher::class);
477
-		$this->registerAlias('CategoryFetcher', CategoryFetcher::class);
478
-
479
-		$this->registerService(\OCP\ICache::class, function ($c) {
480
-			return new Cache\File();
481
-		});
482
-		$this->registerAlias('UserCache', \OCP\ICache::class);
483
-
484
-		$this->registerService(Factory::class, function (Server $c) {
485
-
486
-			$arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
487
-				ArrayCache::class,
488
-				ArrayCache::class,
489
-				ArrayCache::class
490
-			);
491
-			$config = $c->getConfig();
492
-			$request = $c->getRequest();
493
-			$urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
494
-
495
-			if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
496
-				$v = \OC_App::getAppVersions();
497
-				$v['core'] = implode(',', \OC_Util::getVersion());
498
-				$version = implode(',', $v);
499
-				$instanceId = \OC_Util::getInstanceId();
500
-				$path = \OC::$SERVERROOT;
501
-				$prefix = md5($instanceId . '-' . $version . '-' . $path);
502
-				return new \OC\Memcache\Factory($prefix, $c->getLogger(),
503
-					$config->getSystemValue('memcache.local', null),
504
-					$config->getSystemValue('memcache.distributed', null),
505
-					$config->getSystemValue('memcache.locking', null)
506
-				);
507
-			}
508
-			return $arrayCacheFactory;
509
-
510
-		});
511
-		$this->registerAlias('MemCacheFactory', Factory::class);
512
-		$this->registerAlias(ICacheFactory::class, Factory::class);
513
-
514
-		$this->registerService('RedisFactory', function (Server $c) {
515
-			$systemConfig = $c->getSystemConfig();
516
-			return new RedisFactory($systemConfig);
517
-		});
518
-
519
-		$this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
520
-			return new \OC\Activity\Manager(
521
-				$c->getRequest(),
522
-				$c->getUserSession(),
523
-				$c->getConfig(),
524
-				$c->query(IValidator::class)
525
-			);
526
-		});
527
-		$this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
528
-
529
-		$this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
530
-			return new \OC\Activity\EventMerger(
531
-				$c->getL10N('lib')
532
-			);
533
-		});
534
-		$this->registerAlias(IValidator::class, Validator::class);
535
-
536
-		$this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
537
-			return new AvatarManager(
538
-				$c->query(\OC\User\Manager::class),
539
-				$c->getAppDataDir('avatar'),
540
-				$c->getL10N('lib'),
541
-				$c->getLogger(),
542
-				$c->getConfig()
543
-			);
544
-		});
545
-		$this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
546
-
547
-		$this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
548
-
549
-		$this->registerService(\OCP\ILogger::class, function (Server $c) {
550
-			$logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
551
-			$factory = new LogFactory($c);
552
-			$logger = $factory->get($logType);
553
-			$registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
554
-
555
-			return new Log($logger, $this->getSystemConfig(), null, $registry);
556
-		});
557
-		$this->registerAlias('Logger', \OCP\ILogger::class);
558
-
559
-		$this->registerService(ILogFactory::class, function (Server $c) {
560
-			return new LogFactory($c);
561
-		});
562
-		$this->registerAlias('LogFactory', ILogFactory::class);
563
-
564
-		$this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
565
-			$config = $c->getConfig();
566
-			return new \OC\BackgroundJob\JobList(
567
-				$c->getDatabaseConnection(),
568
-				$config,
569
-				new TimeFactory()
570
-			);
571
-		});
572
-		$this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
573
-
574
-		$this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
575
-			$cacheFactory = $c->getMemCacheFactory();
576
-			$logger = $c->getLogger();
577
-			if ($cacheFactory->isLocalCacheAvailable()) {
578
-				$router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
579
-			} else {
580
-				$router = new \OC\Route\Router($logger);
581
-			}
582
-			return $router;
583
-		});
584
-		$this->registerAlias('Router', \OCP\Route\IRouter::class);
585
-
586
-		$this->registerService(\OCP\ISearch::class, function ($c) {
587
-			return new Search();
588
-		});
589
-		$this->registerAlias('Search', \OCP\ISearch::class);
590
-
591
-		$this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
592
-			return new \OC\Security\RateLimiting\Limiter(
593
-				$this->getUserSession(),
594
-				$this->getRequest(),
595
-				new \OC\AppFramework\Utility\TimeFactory(),
596
-				$c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
597
-			);
598
-		});
599
-		$this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
600
-			return new \OC\Security\RateLimiting\Backend\MemoryCache(
601
-				$this->getMemCacheFactory(),
602
-				new \OC\AppFramework\Utility\TimeFactory()
603
-			);
604
-		});
605
-
606
-		$this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
607
-			return new SecureRandom();
608
-		});
609
-		$this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
610
-
611
-		$this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
612
-			return new Crypto($c->getConfig(), $c->getSecureRandom());
613
-		});
614
-		$this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
615
-
616
-		$this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
617
-			return new Hasher($c->getConfig());
618
-		});
619
-		$this->registerAlias('Hasher', \OCP\Security\IHasher::class);
620
-
621
-		$this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
622
-			return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
623
-		});
624
-		$this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
625
-
626
-		$this->registerService(IDBConnection::class, function (Server $c) {
627
-			$systemConfig = $c->getSystemConfig();
628
-			$factory = new \OC\DB\ConnectionFactory($systemConfig);
629
-			$type = $systemConfig->getValue('dbtype', 'sqlite');
630
-			if (!$factory->isValidType($type)) {
631
-				throw new \OC\DatabaseException('Invalid database type');
632
-			}
633
-			$connectionParams = $factory->createConnectionParams();
634
-			$connection = $factory->getConnection($type, $connectionParams);
635
-			$connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
636
-			return $connection;
637
-		});
638
-		$this->registerAlias('DatabaseConnection', IDBConnection::class);
639
-
640
-
641
-		$this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
642
-			$user = \OC_User::getUser();
643
-			$uid = $user ? $user : null;
644
-			return new ClientService(
645
-				$c->getConfig(),
646
-				new \OC\Security\CertificateManager(
647
-					$uid,
648
-					new View(),
649
-					$c->getConfig(),
650
-					$c->getLogger(),
651
-					$c->getSecureRandom()
652
-				)
653
-			);
654
-		});
655
-		$this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
656
-		$this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
657
-			$eventLogger = new EventLogger();
658
-			if ($c->getSystemConfig()->getValue('debug', false)) {
659
-				// In debug mode, module is being activated by default
660
-				$eventLogger->activate();
661
-			}
662
-			return $eventLogger;
663
-		});
664
-		$this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
665
-
666
-		$this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
667
-			$queryLogger = new QueryLogger();
668
-			if ($c->getSystemConfig()->getValue('debug', false)) {
669
-				// In debug mode, module is being activated by default
670
-				$queryLogger->activate();
671
-			}
672
-			return $queryLogger;
673
-		});
674
-		$this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
675
-
676
-		$this->registerService(TempManager::class, function (Server $c) {
677
-			return new TempManager(
678
-				$c->getLogger(),
679
-				$c->getConfig()
680
-			);
681
-		});
682
-		$this->registerAlias('TempManager', TempManager::class);
683
-		$this->registerAlias(ITempManager::class, TempManager::class);
684
-
685
-		$this->registerService(AppManager::class, function (Server $c) {
686
-			return new \OC\App\AppManager(
687
-				$c->getUserSession(),
688
-				$c->query(\OC\AppConfig::class),
689
-				$c->getGroupManager(),
690
-				$c->getMemCacheFactory(),
691
-				$c->getEventDispatcher()
692
-			);
693
-		});
694
-		$this->registerAlias('AppManager', AppManager::class);
695
-		$this->registerAlias(IAppManager::class, AppManager::class);
696
-
697
-		$this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
698
-			return new DateTimeZone(
699
-				$c->getConfig(),
700
-				$c->getSession()
701
-			);
702
-		});
703
-		$this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
704
-
705
-		$this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
706
-			$language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
707
-
708
-			return new DateTimeFormatter(
709
-				$c->getDateTimeZone()->getTimeZone(),
710
-				$c->getL10N('lib', $language)
711
-			);
712
-		});
713
-		$this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
714
-
715
-		$this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
716
-			$mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
717
-			$listener = new UserMountCacheListener($mountCache);
718
-			$listener->listen($c->getUserManager());
719
-			return $mountCache;
720
-		});
721
-		$this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
722
-
723
-		$this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
724
-			$loader = \OC\Files\Filesystem::getLoader();
725
-			$mountCache = $c->query('UserMountCache');
726
-			$manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
727
-
728
-			// builtin providers
729
-
730
-			$config = $c->getConfig();
731
-			$manager->registerProvider(new CacheMountProvider($config));
732
-			$manager->registerHomeProvider(new LocalHomeMountProvider());
733
-			$manager->registerHomeProvider(new ObjectHomeMountProvider($config));
734
-
735
-			return $manager;
736
-		});
737
-		$this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
738
-
739
-		$this->registerService('IniWrapper', function ($c) {
740
-			return new IniGetWrapper();
741
-		});
742
-		$this->registerService('AsyncCommandBus', function (Server $c) {
743
-			$busClass = $c->getConfig()->getSystemValue('commandbus');
744
-			if ($busClass) {
745
-				list($app, $class) = explode('::', $busClass, 2);
746
-				if ($c->getAppManager()->isInstalled($app)) {
747
-					\OC_App::loadApp($app);
748
-					return $c->query($class);
749
-				} else {
750
-					throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
751
-				}
752
-			} else {
753
-				$jobList = $c->getJobList();
754
-				return new CronBus($jobList);
755
-			}
756
-		});
757
-		$this->registerService('TrustedDomainHelper', function ($c) {
758
-			return new TrustedDomainHelper($this->getConfig());
759
-		});
760
-		$this->registerService('Throttler', function (Server $c) {
761
-			return new Throttler(
762
-				$c->getDatabaseConnection(),
763
-				new TimeFactory(),
764
-				$c->getLogger(),
765
-				$c->getConfig()
766
-			);
767
-		});
768
-		$this->registerService('IntegrityCodeChecker', function (Server $c) {
769
-			// IConfig and IAppManager requires a working database. This code
770
-			// might however be called when ownCloud is not yet setup.
771
-			if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
772
-				$config = $c->getConfig();
773
-				$appManager = $c->getAppManager();
774
-			} else {
775
-				$config = null;
776
-				$appManager = null;
777
-			}
778
-
779
-			return new Checker(
780
-				new EnvironmentHelper(),
781
-				new FileAccessHelper(),
782
-				new AppLocator(),
783
-				$config,
784
-				$c->getMemCacheFactory(),
785
-				$appManager,
786
-				$c->getTempManager()
787
-			);
788
-		});
789
-		$this->registerService(\OCP\IRequest::class, function ($c) {
790
-			if (isset($this['urlParams'])) {
791
-				$urlParams = $this['urlParams'];
792
-			} else {
793
-				$urlParams = [];
794
-			}
795
-
796
-			if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
797
-				&& in_array('fakeinput', stream_get_wrappers())
798
-			) {
799
-				$stream = 'fakeinput://data';
800
-			} else {
801
-				$stream = 'php://input';
802
-			}
803
-
804
-			return new Request(
805
-				[
806
-					'get' => $_GET,
807
-					'post' => $_POST,
808
-					'files' => $_FILES,
809
-					'server' => $_SERVER,
810
-					'env' => $_ENV,
811
-					'cookies' => $_COOKIE,
812
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
813
-						? $_SERVER['REQUEST_METHOD']
814
-						: '',
815
-					'urlParams' => $urlParams,
816
-				],
817
-				$this->getSecureRandom(),
818
-				$this->getConfig(),
819
-				$this->getCsrfTokenManager(),
820
-				$stream
821
-			);
822
-		});
823
-		$this->registerAlias('Request', \OCP\IRequest::class);
824
-
825
-		$this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
826
-			return new Mailer(
827
-				$c->getConfig(),
828
-				$c->getLogger(),
829
-				$c->query(Defaults::class),
830
-				$c->getURLGenerator(),
831
-				$c->getL10N('lib')
832
-			);
833
-		});
834
-		$this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
835
-
836
-		$this->registerService('LDAPProvider', function (Server $c) {
837
-			$config = $c->getConfig();
838
-			$factoryClass = $config->getSystemValue('ldapProviderFactory', null);
839
-			if (is_null($factoryClass)) {
840
-				throw new \Exception('ldapProviderFactory not set');
841
-			}
842
-			/** @var \OCP\LDAP\ILDAPProviderFactory $factory */
843
-			$factory = new $factoryClass($this);
844
-			return $factory->getLDAPProvider();
845
-		});
846
-		$this->registerService(ILockingProvider::class, function (Server $c) {
847
-			$ini = $c->getIniWrapper();
848
-			$config = $c->getConfig();
849
-			$ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
850
-			if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
851
-				/** @var \OC\Memcache\Factory $memcacheFactory */
852
-				$memcacheFactory = $c->getMemCacheFactory();
853
-				$memcache = $memcacheFactory->createLocking('lock');
854
-				if (!($memcache instanceof \OC\Memcache\NullCache)) {
855
-					return new MemcacheLockingProvider($memcache, $ttl);
856
-				}
857
-				return new DBLockingProvider(
858
-					$c->getDatabaseConnection(),
859
-					$c->getLogger(),
860
-					new TimeFactory(),
861
-					$ttl,
862
-					!\OC::$CLI
863
-				);
864
-			}
865
-			return new NoopLockingProvider();
866
-		});
867
-		$this->registerAlias('LockingProvider', ILockingProvider::class);
868
-
869
-		$this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
870
-			return new \OC\Files\Mount\Manager();
871
-		});
872
-		$this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
873
-
874
-		$this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
875
-			return new \OC\Files\Type\Detection(
876
-				$c->getURLGenerator(),
877
-				\OC::$configDir,
878
-				\OC::$SERVERROOT . '/resources/config/'
879
-			);
880
-		});
881
-		$this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
882
-
883
-		$this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
884
-			return new \OC\Files\Type\Loader(
885
-				$c->getDatabaseConnection()
886
-			);
887
-		});
888
-		$this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
889
-		$this->registerService(BundleFetcher::class, function () {
890
-			return new BundleFetcher($this->getL10N('lib'));
891
-		});
892
-		$this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
893
-			return new Manager(
894
-				$c->query(IValidator::class)
895
-			);
896
-		});
897
-		$this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
898
-
899
-		$this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
900
-			$manager = new \OC\CapabilitiesManager($c->getLogger());
901
-			$manager->registerCapability(function () use ($c) {
902
-				return new \OC\OCS\CoreCapabilities($c->getConfig());
903
-			});
904
-			$manager->registerCapability(function () use ($c) {
905
-				return $c->query(\OC\Security\Bruteforce\Capabilities::class);
906
-			});
907
-			return $manager;
908
-		});
909
-		$this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
910
-
911
-		$this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
912
-			$config = $c->getConfig();
913
-			$factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
914
-			/** @var \OCP\Comments\ICommentsManagerFactory $factory */
915
-			$factory = new $factoryClass($this);
916
-			$manager = $factory->getManager();
917
-
918
-			$manager->registerDisplayNameResolver('user', function($id) use ($c) {
919
-				$manager = $c->getUserManager();
920
-				$user = $manager->get($id);
921
-				if(is_null($user)) {
922
-					$l = $c->getL10N('core');
923
-					$displayName = $l->t('Unknown user');
924
-				} else {
925
-					$displayName = $user->getDisplayName();
926
-				}
927
-				return $displayName;
928
-			});
929
-
930
-			return $manager;
931
-		});
932
-		$this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
933
-
934
-		$this->registerService('ThemingDefaults', function (Server $c) {
935
-			/*
156
+    /** @var string */
157
+    private $webRoot;
158
+
159
+    /**
160
+     * @param string $webRoot
161
+     * @param \OC\Config $config
162
+     */
163
+    public function __construct($webRoot, \OC\Config $config) {
164
+        parent::__construct();
165
+        $this->webRoot = $webRoot;
166
+
167
+        $this->registerService(\OCP\IServerContainer::class, function (IServerContainer $c) {
168
+            return $c;
169
+        });
170
+
171
+        $this->registerAlias(\OCP\Calendar\IManager::class, \OC\Calendar\Manager::class);
172
+        $this->registerAlias('CalendarManager', \OC\Calendar\Manager::class);
173
+
174
+        $this->registerAlias(\OCP\Contacts\IManager::class, \OC\ContactsManager::class);
175
+        $this->registerAlias('ContactsManager', \OCP\Contacts\IManager::class);
176
+
177
+        $this->registerAlias(IActionFactory::class, ActionFactory::class);
178
+
179
+
180
+        $this->registerService(\OCP\IPreview::class, function (Server $c) {
181
+            return new PreviewManager(
182
+                $c->getConfig(),
183
+                $c->getRootFolder(),
184
+                $c->getAppDataDir('preview'),
185
+                $c->getEventDispatcher(),
186
+                $c->getSession()->get('user_id')
187
+            );
188
+        });
189
+        $this->registerAlias('PreviewManager', \OCP\IPreview::class);
190
+
191
+        $this->registerService(\OC\Preview\Watcher::class, function (Server $c) {
192
+            return new \OC\Preview\Watcher(
193
+                $c->getAppDataDir('preview')
194
+            );
195
+        });
196
+
197
+        $this->registerService('EncryptionManager', function (Server $c) {
198
+            $view = new View();
199
+            $util = new Encryption\Util(
200
+                $view,
201
+                $c->getUserManager(),
202
+                $c->getGroupManager(),
203
+                $c->getConfig()
204
+            );
205
+            return new Encryption\Manager(
206
+                $c->getConfig(),
207
+                $c->getLogger(),
208
+                $c->getL10N('core'),
209
+                new View(),
210
+                $util,
211
+                new ArrayCache()
212
+            );
213
+        });
214
+
215
+        $this->registerService('EncryptionFileHelper', function (Server $c) {
216
+            $util = new Encryption\Util(
217
+                new View(),
218
+                $c->getUserManager(),
219
+                $c->getGroupManager(),
220
+                $c->getConfig()
221
+            );
222
+            return new Encryption\File(
223
+                $util,
224
+                $c->getRootFolder(),
225
+                $c->getShareManager()
226
+            );
227
+        });
228
+
229
+        $this->registerService('EncryptionKeyStorage', function (Server $c) {
230
+            $view = new View();
231
+            $util = new Encryption\Util(
232
+                $view,
233
+                $c->getUserManager(),
234
+                $c->getGroupManager(),
235
+                $c->getConfig()
236
+            );
237
+
238
+            return new Encryption\Keys\Storage($view, $util);
239
+        });
240
+        $this->registerService('TagMapper', function (Server $c) {
241
+            return new TagMapper($c->getDatabaseConnection());
242
+        });
243
+
244
+        $this->registerService(\OCP\ITagManager::class, function (Server $c) {
245
+            $tagMapper = $c->query('TagMapper');
246
+            return new TagManager($tagMapper, $c->getUserSession());
247
+        });
248
+        $this->registerAlias('TagManager', \OCP\ITagManager::class);
249
+
250
+        $this->registerService('SystemTagManagerFactory', function (Server $c) {
251
+            $config = $c->getConfig();
252
+            $factoryClass = $config->getSystemValue('systemtags.managerFactory', SystemTagManagerFactory::class);
253
+            return new $factoryClass($this);
254
+        });
255
+        $this->registerService(\OCP\SystemTag\ISystemTagManager::class, function (Server $c) {
256
+            return $c->query('SystemTagManagerFactory')->getManager();
257
+        });
258
+        $this->registerAlias('SystemTagManager', \OCP\SystemTag\ISystemTagManager::class);
259
+
260
+        $this->registerService(\OCP\SystemTag\ISystemTagObjectMapper::class, function (Server $c) {
261
+            return $c->query('SystemTagManagerFactory')->getObjectMapper();
262
+        });
263
+        $this->registerService('RootFolder', function (Server $c) {
264
+            $manager = \OC\Files\Filesystem::getMountManager(null);
265
+            $view = new View();
266
+            $root = new Root(
267
+                $manager,
268
+                $view,
269
+                null,
270
+                $c->getUserMountCache(),
271
+                $this->getLogger(),
272
+                $this->getUserManager()
273
+            );
274
+            $connector = new HookConnector($root, $view);
275
+            $connector->viewToNode();
276
+
277
+            $previewConnector = new \OC\Preview\WatcherConnector($root, $c->getSystemConfig());
278
+            $previewConnector->connectWatcher();
279
+
280
+            return $root;
281
+        });
282
+        $this->registerAlias('SystemTagObjectMapper', \OCP\SystemTag\ISystemTagObjectMapper::class);
283
+
284
+        $this->registerService(\OCP\Files\IRootFolder::class, function (Server $c) {
285
+            return new LazyRoot(function () use ($c) {
286
+                return $c->query('RootFolder');
287
+            });
288
+        });
289
+        $this->registerAlias('LazyRootFolder', \OCP\Files\IRootFolder::class);
290
+
291
+        $this->registerService(\OC\User\Manager::class, function (Server $c) {
292
+            $config = $c->getConfig();
293
+            return new \OC\User\Manager($config);
294
+        });
295
+        $this->registerAlias('UserManager', \OC\User\Manager::class);
296
+        $this->registerAlias(\OCP\IUserManager::class, \OC\User\Manager::class);
297
+
298
+        $this->registerService(\OCP\IGroupManager::class, function (Server $c) {
299
+            $groupManager = new \OC\Group\Manager($this->getUserManager(), $this->getLogger());
300
+            $groupManager->listen('\OC\Group', 'preCreate', function ($gid) {
301
+                \OC_Hook::emit('OC_Group', 'pre_createGroup', array('run' => true, 'gid' => $gid));
302
+            });
303
+            $groupManager->listen('\OC\Group', 'postCreate', function (\OC\Group\Group $gid) {
304
+                \OC_Hook::emit('OC_User', 'post_createGroup', array('gid' => $gid->getGID()));
305
+            });
306
+            $groupManager->listen('\OC\Group', 'preDelete', function (\OC\Group\Group $group) {
307
+                \OC_Hook::emit('OC_Group', 'pre_deleteGroup', array('run' => true, 'gid' => $group->getGID()));
308
+            });
309
+            $groupManager->listen('\OC\Group', 'postDelete', function (\OC\Group\Group $group) {
310
+                \OC_Hook::emit('OC_User', 'post_deleteGroup', array('gid' => $group->getGID()));
311
+            });
312
+            $groupManager->listen('\OC\Group', 'preAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
313
+                \OC_Hook::emit('OC_Group', 'pre_addToGroup', array('run' => true, 'uid' => $user->getUID(), 'gid' => $group->getGID()));
314
+            });
315
+            $groupManager->listen('\OC\Group', 'postAddUser', function (\OC\Group\Group $group, \OC\User\User $user) {
316
+                \OC_Hook::emit('OC_Group', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
317
+                //Minimal fix to keep it backward compatible TODO: clean up all the GroupManager hooks
318
+                \OC_Hook::emit('OC_User', 'post_addToGroup', array('uid' => $user->getUID(), 'gid' => $group->getGID()));
319
+            });
320
+            return $groupManager;
321
+        });
322
+        $this->registerAlias('GroupManager', \OCP\IGroupManager::class);
323
+
324
+        $this->registerService(Store::class, function (Server $c) {
325
+            $session = $c->getSession();
326
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
327
+                $tokenProvider = $c->query(IProvider::class);
328
+            } else {
329
+                $tokenProvider = null;
330
+            }
331
+            $logger = $c->getLogger();
332
+            return new Store($session, $logger, $tokenProvider);
333
+        });
334
+        $this->registerAlias(IStore::class, Store::class);
335
+        $this->registerService(Authentication\Token\DefaultTokenMapper::class, function (Server $c) {
336
+            $dbConnection = $c->getDatabaseConnection();
337
+            return new Authentication\Token\DefaultTokenMapper($dbConnection);
338
+        });
339
+        $this->registerService(Authentication\Token\DefaultTokenProvider::class, function (Server $c) {
340
+            $mapper = $c->query(Authentication\Token\DefaultTokenMapper::class);
341
+            $crypto = $c->getCrypto();
342
+            $config = $c->getConfig();
343
+            $logger = $c->getLogger();
344
+            $timeFactory = new TimeFactory();
345
+            return new \OC\Authentication\Token\DefaultTokenProvider($mapper, $crypto, $config, $logger, $timeFactory);
346
+        });
347
+        $this->registerAlias(IProvider::class, Authentication\Token\DefaultTokenProvider::class);
348
+
349
+        $this->registerService(\OCP\IUserSession::class, function (Server $c) {
350
+            $manager = $c->getUserManager();
351
+            $session = new \OC\Session\Memory('');
352
+            $timeFactory = new TimeFactory();
353
+            // Token providers might require a working database. This code
354
+            // might however be called when ownCloud is not yet setup.
355
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
356
+                $defaultTokenProvider = $c->query(IProvider::class);
357
+            } else {
358
+                $defaultTokenProvider = null;
359
+            }
360
+
361
+            $dispatcher = $c->getEventDispatcher();
362
+
363
+            $userSession = new \OC\User\Session(
364
+                $manager,
365
+                $session,
366
+                $timeFactory,
367
+                $defaultTokenProvider,
368
+                $c->getConfig(),
369
+                $c->getSecureRandom(),
370
+                $c->getLockdownManager(),
371
+                $c->getLogger()
372
+            );
373
+            $userSession->listen('\OC\User', 'preCreateUser', function ($uid, $password) {
374
+                \OC_Hook::emit('OC_User', 'pre_createUser', array('run' => true, 'uid' => $uid, 'password' => $password));
375
+            });
376
+            $userSession->listen('\OC\User', 'postCreateUser', function ($user, $password) {
377
+                /** @var $user \OC\User\User */
378
+                \OC_Hook::emit('OC_User', 'post_createUser', array('uid' => $user->getUID(), 'password' => $password));
379
+            });
380
+            $userSession->listen('\OC\User', 'preDelete', function ($user) use ($dispatcher) {
381
+                /** @var $user \OC\User\User */
382
+                \OC_Hook::emit('OC_User', 'pre_deleteUser', array('run' => true, 'uid' => $user->getUID()));
383
+                $dispatcher->dispatch('OCP\IUser::preDelete', new GenericEvent($user));
384
+            });
385
+            $userSession->listen('\OC\User', 'postDelete', function ($user) {
386
+                /** @var $user \OC\User\User */
387
+                \OC_Hook::emit('OC_User', 'post_deleteUser', array('uid' => $user->getUID()));
388
+            });
389
+            $userSession->listen('\OC\User', 'preSetPassword', function ($user, $password, $recoveryPassword) {
390
+                /** @var $user \OC\User\User */
391
+                \OC_Hook::emit('OC_User', 'pre_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
392
+            });
393
+            $userSession->listen('\OC\User', 'postSetPassword', function ($user, $password, $recoveryPassword) {
394
+                /** @var $user \OC\User\User */
395
+                \OC_Hook::emit('OC_User', 'post_setPassword', array('run' => true, 'uid' => $user->getUID(), 'password' => $password, 'recoveryPassword' => $recoveryPassword));
396
+            });
397
+            $userSession->listen('\OC\User', 'preLogin', function ($uid, $password) {
398
+                \OC_Hook::emit('OC_User', 'pre_login', array('run' => true, 'uid' => $uid, 'password' => $password));
399
+            });
400
+            $userSession->listen('\OC\User', 'postLogin', function ($user, $password) {
401
+                /** @var $user \OC\User\User */
402
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
403
+            });
404
+            $userSession->listen('\OC\User', 'postRememberedLogin', function ($user, $password) {
405
+                /** @var $user \OC\User\User */
406
+                \OC_Hook::emit('OC_User', 'post_login', array('run' => true, 'uid' => $user->getUID(), 'password' => $password));
407
+            });
408
+            $userSession->listen('\OC\User', 'logout', function () {
409
+                \OC_Hook::emit('OC_User', 'logout', array());
410
+            });
411
+            $userSession->listen('\OC\User', 'changeUser', function ($user, $feature, $value, $oldValue) use ($dispatcher) {
412
+                /** @var $user \OC\User\User */
413
+                \OC_Hook::emit('OC_User', 'changeUser', array('run' => true, 'user' => $user, 'feature' => $feature, 'value' => $value, 'old_value' => $oldValue));
414
+                $dispatcher->dispatch('OCP\IUser::changeUser', new GenericEvent($user, ['feature' => $feature, 'oldValue' => $oldValue, 'value' => $value]));
415
+            });
416
+            return $userSession;
417
+        });
418
+        $this->registerAlias('UserSession', \OCP\IUserSession::class);
419
+
420
+        $this->registerService(\OC\Authentication\TwoFactorAuth\Manager::class, function (Server $c) {
421
+            return new \OC\Authentication\TwoFactorAuth\Manager(
422
+                $c->getAppManager(),
423
+                $c->getSession(),
424
+                $c->getConfig(),
425
+                $c->getActivityManager(),
426
+                $c->getLogger(),
427
+                $c->query(IProvider::class),
428
+                $c->query(ITimeFactory::class),
429
+                $c->query(EventDispatcherInterface::class)
430
+            );
431
+        });
432
+
433
+        $this->registerAlias(\OCP\INavigationManager::class, \OC\NavigationManager::class);
434
+        $this->registerAlias('NavigationManager', \OCP\INavigationManager::class);
435
+
436
+        $this->registerService(\OC\AllConfig::class, function (Server $c) {
437
+            return new \OC\AllConfig(
438
+                $c->getSystemConfig()
439
+            );
440
+        });
441
+        $this->registerAlias('AllConfig', \OC\AllConfig::class);
442
+        $this->registerAlias(\OCP\IConfig::class, \OC\AllConfig::class);
443
+
444
+        $this->registerService('SystemConfig', function ($c) use ($config) {
445
+            return new \OC\SystemConfig($config);
446
+        });
447
+
448
+        $this->registerService(\OC\AppConfig::class, function (Server $c) {
449
+            return new \OC\AppConfig($c->getDatabaseConnection());
450
+        });
451
+        $this->registerAlias('AppConfig', \OC\AppConfig::class);
452
+        $this->registerAlias(\OCP\IAppConfig::class, \OC\AppConfig::class);
453
+
454
+        $this->registerService(\OCP\L10N\IFactory::class, function (Server $c) {
455
+            return new \OC\L10N\Factory(
456
+                $c->getConfig(),
457
+                $c->getRequest(),
458
+                $c->getUserSession(),
459
+                \OC::$SERVERROOT
460
+            );
461
+        });
462
+        $this->registerAlias('L10NFactory', \OCP\L10N\IFactory::class);
463
+
464
+        $this->registerService(\OCP\IURLGenerator::class, function (Server $c) {
465
+            $config = $c->getConfig();
466
+            $cacheFactory = $c->getMemCacheFactory();
467
+            $request = $c->getRequest();
468
+            return new \OC\URLGenerator(
469
+                $config,
470
+                $cacheFactory,
471
+                $request
472
+            );
473
+        });
474
+        $this->registerAlias('URLGenerator', \OCP\IURLGenerator::class);
475
+
476
+        $this->registerAlias('AppFetcher', AppFetcher::class);
477
+        $this->registerAlias('CategoryFetcher', CategoryFetcher::class);
478
+
479
+        $this->registerService(\OCP\ICache::class, function ($c) {
480
+            return new Cache\File();
481
+        });
482
+        $this->registerAlias('UserCache', \OCP\ICache::class);
483
+
484
+        $this->registerService(Factory::class, function (Server $c) {
485
+
486
+            $arrayCacheFactory = new \OC\Memcache\Factory('', $c->getLogger(),
487
+                ArrayCache::class,
488
+                ArrayCache::class,
489
+                ArrayCache::class
490
+            );
491
+            $config = $c->getConfig();
492
+            $request = $c->getRequest();
493
+            $urlGenerator = new URLGenerator($config, $arrayCacheFactory, $request);
494
+
495
+            if ($config->getSystemValue('installed', false) && !(defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
496
+                $v = \OC_App::getAppVersions();
497
+                $v['core'] = implode(',', \OC_Util::getVersion());
498
+                $version = implode(',', $v);
499
+                $instanceId = \OC_Util::getInstanceId();
500
+                $path = \OC::$SERVERROOT;
501
+                $prefix = md5($instanceId . '-' . $version . '-' . $path);
502
+                return new \OC\Memcache\Factory($prefix, $c->getLogger(),
503
+                    $config->getSystemValue('memcache.local', null),
504
+                    $config->getSystemValue('memcache.distributed', null),
505
+                    $config->getSystemValue('memcache.locking', null)
506
+                );
507
+            }
508
+            return $arrayCacheFactory;
509
+
510
+        });
511
+        $this->registerAlias('MemCacheFactory', Factory::class);
512
+        $this->registerAlias(ICacheFactory::class, Factory::class);
513
+
514
+        $this->registerService('RedisFactory', function (Server $c) {
515
+            $systemConfig = $c->getSystemConfig();
516
+            return new RedisFactory($systemConfig);
517
+        });
518
+
519
+        $this->registerService(\OCP\Activity\IManager::class, function (Server $c) {
520
+            return new \OC\Activity\Manager(
521
+                $c->getRequest(),
522
+                $c->getUserSession(),
523
+                $c->getConfig(),
524
+                $c->query(IValidator::class)
525
+            );
526
+        });
527
+        $this->registerAlias('ActivityManager', \OCP\Activity\IManager::class);
528
+
529
+        $this->registerService(\OCP\Activity\IEventMerger::class, function (Server $c) {
530
+            return new \OC\Activity\EventMerger(
531
+                $c->getL10N('lib')
532
+            );
533
+        });
534
+        $this->registerAlias(IValidator::class, Validator::class);
535
+
536
+        $this->registerService(\OCP\IAvatarManager::class, function (Server $c) {
537
+            return new AvatarManager(
538
+                $c->query(\OC\User\Manager::class),
539
+                $c->getAppDataDir('avatar'),
540
+                $c->getL10N('lib'),
541
+                $c->getLogger(),
542
+                $c->getConfig()
543
+            );
544
+        });
545
+        $this->registerAlias('AvatarManager', \OCP\IAvatarManager::class);
546
+
547
+        $this->registerAlias(\OCP\Support\CrashReport\IRegistry::class, \OC\Support\CrashReport\Registry::class);
548
+
549
+        $this->registerService(\OCP\ILogger::class, function (Server $c) {
550
+            $logType = $c->query('AllConfig')->getSystemValue('log_type', 'file');
551
+            $factory = new LogFactory($c);
552
+            $logger = $factory->get($logType);
553
+            $registry = $c->query(\OCP\Support\CrashReport\IRegistry::class);
554
+
555
+            return new Log($logger, $this->getSystemConfig(), null, $registry);
556
+        });
557
+        $this->registerAlias('Logger', \OCP\ILogger::class);
558
+
559
+        $this->registerService(ILogFactory::class, function (Server $c) {
560
+            return new LogFactory($c);
561
+        });
562
+        $this->registerAlias('LogFactory', ILogFactory::class);
563
+
564
+        $this->registerService(\OCP\BackgroundJob\IJobList::class, function (Server $c) {
565
+            $config = $c->getConfig();
566
+            return new \OC\BackgroundJob\JobList(
567
+                $c->getDatabaseConnection(),
568
+                $config,
569
+                new TimeFactory()
570
+            );
571
+        });
572
+        $this->registerAlias('JobList', \OCP\BackgroundJob\IJobList::class);
573
+
574
+        $this->registerService(\OCP\Route\IRouter::class, function (Server $c) {
575
+            $cacheFactory = $c->getMemCacheFactory();
576
+            $logger = $c->getLogger();
577
+            if ($cacheFactory->isLocalCacheAvailable()) {
578
+                $router = new \OC\Route\CachingRouter($cacheFactory->createLocal('route'), $logger);
579
+            } else {
580
+                $router = new \OC\Route\Router($logger);
581
+            }
582
+            return $router;
583
+        });
584
+        $this->registerAlias('Router', \OCP\Route\IRouter::class);
585
+
586
+        $this->registerService(\OCP\ISearch::class, function ($c) {
587
+            return new Search();
588
+        });
589
+        $this->registerAlias('Search', \OCP\ISearch::class);
590
+
591
+        $this->registerService(\OC\Security\RateLimiting\Limiter::class, function (Server $c) {
592
+            return new \OC\Security\RateLimiting\Limiter(
593
+                $this->getUserSession(),
594
+                $this->getRequest(),
595
+                new \OC\AppFramework\Utility\TimeFactory(),
596
+                $c->query(\OC\Security\RateLimiting\Backend\IBackend::class)
597
+            );
598
+        });
599
+        $this->registerService(\OC\Security\RateLimiting\Backend\IBackend::class, function ($c) {
600
+            return new \OC\Security\RateLimiting\Backend\MemoryCache(
601
+                $this->getMemCacheFactory(),
602
+                new \OC\AppFramework\Utility\TimeFactory()
603
+            );
604
+        });
605
+
606
+        $this->registerService(\OCP\Security\ISecureRandom::class, function ($c) {
607
+            return new SecureRandom();
608
+        });
609
+        $this->registerAlias('SecureRandom', \OCP\Security\ISecureRandom::class);
610
+
611
+        $this->registerService(\OCP\Security\ICrypto::class, function (Server $c) {
612
+            return new Crypto($c->getConfig(), $c->getSecureRandom());
613
+        });
614
+        $this->registerAlias('Crypto', \OCP\Security\ICrypto::class);
615
+
616
+        $this->registerService(\OCP\Security\IHasher::class, function (Server $c) {
617
+            return new Hasher($c->getConfig());
618
+        });
619
+        $this->registerAlias('Hasher', \OCP\Security\IHasher::class);
620
+
621
+        $this->registerService(\OCP\Security\ICredentialsManager::class, function (Server $c) {
622
+            return new CredentialsManager($c->getCrypto(), $c->getDatabaseConnection());
623
+        });
624
+        $this->registerAlias('CredentialsManager', \OCP\Security\ICredentialsManager::class);
625
+
626
+        $this->registerService(IDBConnection::class, function (Server $c) {
627
+            $systemConfig = $c->getSystemConfig();
628
+            $factory = new \OC\DB\ConnectionFactory($systemConfig);
629
+            $type = $systemConfig->getValue('dbtype', 'sqlite');
630
+            if (!$factory->isValidType($type)) {
631
+                throw new \OC\DatabaseException('Invalid database type');
632
+            }
633
+            $connectionParams = $factory->createConnectionParams();
634
+            $connection = $factory->getConnection($type, $connectionParams);
635
+            $connection->getConfiguration()->setSQLLogger($c->getQueryLogger());
636
+            return $connection;
637
+        });
638
+        $this->registerAlias('DatabaseConnection', IDBConnection::class);
639
+
640
+
641
+        $this->registerService(\OCP\Http\Client\IClientService::class, function (Server $c) {
642
+            $user = \OC_User::getUser();
643
+            $uid = $user ? $user : null;
644
+            return new ClientService(
645
+                $c->getConfig(),
646
+                new \OC\Security\CertificateManager(
647
+                    $uid,
648
+                    new View(),
649
+                    $c->getConfig(),
650
+                    $c->getLogger(),
651
+                    $c->getSecureRandom()
652
+                )
653
+            );
654
+        });
655
+        $this->registerAlias('HttpClientService', \OCP\Http\Client\IClientService::class);
656
+        $this->registerService(\OCP\Diagnostics\IEventLogger::class, function (Server $c) {
657
+            $eventLogger = new EventLogger();
658
+            if ($c->getSystemConfig()->getValue('debug', false)) {
659
+                // In debug mode, module is being activated by default
660
+                $eventLogger->activate();
661
+            }
662
+            return $eventLogger;
663
+        });
664
+        $this->registerAlias('EventLogger', \OCP\Diagnostics\IEventLogger::class);
665
+
666
+        $this->registerService(\OCP\Diagnostics\IQueryLogger::class, function (Server $c) {
667
+            $queryLogger = new QueryLogger();
668
+            if ($c->getSystemConfig()->getValue('debug', false)) {
669
+                // In debug mode, module is being activated by default
670
+                $queryLogger->activate();
671
+            }
672
+            return $queryLogger;
673
+        });
674
+        $this->registerAlias('QueryLogger', \OCP\Diagnostics\IQueryLogger::class);
675
+
676
+        $this->registerService(TempManager::class, function (Server $c) {
677
+            return new TempManager(
678
+                $c->getLogger(),
679
+                $c->getConfig()
680
+            );
681
+        });
682
+        $this->registerAlias('TempManager', TempManager::class);
683
+        $this->registerAlias(ITempManager::class, TempManager::class);
684
+
685
+        $this->registerService(AppManager::class, function (Server $c) {
686
+            return new \OC\App\AppManager(
687
+                $c->getUserSession(),
688
+                $c->query(\OC\AppConfig::class),
689
+                $c->getGroupManager(),
690
+                $c->getMemCacheFactory(),
691
+                $c->getEventDispatcher()
692
+            );
693
+        });
694
+        $this->registerAlias('AppManager', AppManager::class);
695
+        $this->registerAlias(IAppManager::class, AppManager::class);
696
+
697
+        $this->registerService(\OCP\IDateTimeZone::class, function (Server $c) {
698
+            return new DateTimeZone(
699
+                $c->getConfig(),
700
+                $c->getSession()
701
+            );
702
+        });
703
+        $this->registerAlias('DateTimeZone', \OCP\IDateTimeZone::class);
704
+
705
+        $this->registerService(\OCP\IDateTimeFormatter::class, function (Server $c) {
706
+            $language = $c->getConfig()->getUserValue($c->getSession()->get('user_id'), 'core', 'lang', null);
707
+
708
+            return new DateTimeFormatter(
709
+                $c->getDateTimeZone()->getTimeZone(),
710
+                $c->getL10N('lib', $language)
711
+            );
712
+        });
713
+        $this->registerAlias('DateTimeFormatter', \OCP\IDateTimeFormatter::class);
714
+
715
+        $this->registerService(\OCP\Files\Config\IUserMountCache::class, function (Server $c) {
716
+            $mountCache = new UserMountCache($c->getDatabaseConnection(), $c->getUserManager(), $c->getLogger());
717
+            $listener = new UserMountCacheListener($mountCache);
718
+            $listener->listen($c->getUserManager());
719
+            return $mountCache;
720
+        });
721
+        $this->registerAlias('UserMountCache', \OCP\Files\Config\IUserMountCache::class);
722
+
723
+        $this->registerService(\OCP\Files\Config\IMountProviderCollection::class, function (Server $c) {
724
+            $loader = \OC\Files\Filesystem::getLoader();
725
+            $mountCache = $c->query('UserMountCache');
726
+            $manager = new \OC\Files\Config\MountProviderCollection($loader, $mountCache);
727
+
728
+            // builtin providers
729
+
730
+            $config = $c->getConfig();
731
+            $manager->registerProvider(new CacheMountProvider($config));
732
+            $manager->registerHomeProvider(new LocalHomeMountProvider());
733
+            $manager->registerHomeProvider(new ObjectHomeMountProvider($config));
734
+
735
+            return $manager;
736
+        });
737
+        $this->registerAlias('MountConfigManager', \OCP\Files\Config\IMountProviderCollection::class);
738
+
739
+        $this->registerService('IniWrapper', function ($c) {
740
+            return new IniGetWrapper();
741
+        });
742
+        $this->registerService('AsyncCommandBus', function (Server $c) {
743
+            $busClass = $c->getConfig()->getSystemValue('commandbus');
744
+            if ($busClass) {
745
+                list($app, $class) = explode('::', $busClass, 2);
746
+                if ($c->getAppManager()->isInstalled($app)) {
747
+                    \OC_App::loadApp($app);
748
+                    return $c->query($class);
749
+                } else {
750
+                    throw new ServiceUnavailableException("The app providing the command bus ($app) is not enabled");
751
+                }
752
+            } else {
753
+                $jobList = $c->getJobList();
754
+                return new CronBus($jobList);
755
+            }
756
+        });
757
+        $this->registerService('TrustedDomainHelper', function ($c) {
758
+            return new TrustedDomainHelper($this->getConfig());
759
+        });
760
+        $this->registerService('Throttler', function (Server $c) {
761
+            return new Throttler(
762
+                $c->getDatabaseConnection(),
763
+                new TimeFactory(),
764
+                $c->getLogger(),
765
+                $c->getConfig()
766
+            );
767
+        });
768
+        $this->registerService('IntegrityCodeChecker', function (Server $c) {
769
+            // IConfig and IAppManager requires a working database. This code
770
+            // might however be called when ownCloud is not yet setup.
771
+            if (\OC::$server->getSystemConfig()->getValue('installed', false)) {
772
+                $config = $c->getConfig();
773
+                $appManager = $c->getAppManager();
774
+            } else {
775
+                $config = null;
776
+                $appManager = null;
777
+            }
778
+
779
+            return new Checker(
780
+                new EnvironmentHelper(),
781
+                new FileAccessHelper(),
782
+                new AppLocator(),
783
+                $config,
784
+                $c->getMemCacheFactory(),
785
+                $appManager,
786
+                $c->getTempManager()
787
+            );
788
+        });
789
+        $this->registerService(\OCP\IRequest::class, function ($c) {
790
+            if (isset($this['urlParams'])) {
791
+                $urlParams = $this['urlParams'];
792
+            } else {
793
+                $urlParams = [];
794
+            }
795
+
796
+            if (defined('PHPUNIT_RUN') && PHPUNIT_RUN
797
+                && in_array('fakeinput', stream_get_wrappers())
798
+            ) {
799
+                $stream = 'fakeinput://data';
800
+            } else {
801
+                $stream = 'php://input';
802
+            }
803
+
804
+            return new Request(
805
+                [
806
+                    'get' => $_GET,
807
+                    'post' => $_POST,
808
+                    'files' => $_FILES,
809
+                    'server' => $_SERVER,
810
+                    'env' => $_ENV,
811
+                    'cookies' => $_COOKIE,
812
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
813
+                        ? $_SERVER['REQUEST_METHOD']
814
+                        : '',
815
+                    'urlParams' => $urlParams,
816
+                ],
817
+                $this->getSecureRandom(),
818
+                $this->getConfig(),
819
+                $this->getCsrfTokenManager(),
820
+                $stream
821
+            );
822
+        });
823
+        $this->registerAlias('Request', \OCP\IRequest::class);
824
+
825
+        $this->registerService(\OCP\Mail\IMailer::class, function (Server $c) {
826
+            return new Mailer(
827
+                $c->getConfig(),
828
+                $c->getLogger(),
829
+                $c->query(Defaults::class),
830
+                $c->getURLGenerator(),
831
+                $c->getL10N('lib')
832
+            );
833
+        });
834
+        $this->registerAlias('Mailer', \OCP\Mail\IMailer::class);
835
+
836
+        $this->registerService('LDAPProvider', function (Server $c) {
837
+            $config = $c->getConfig();
838
+            $factoryClass = $config->getSystemValue('ldapProviderFactory', null);
839
+            if (is_null($factoryClass)) {
840
+                throw new \Exception('ldapProviderFactory not set');
841
+            }
842
+            /** @var \OCP\LDAP\ILDAPProviderFactory $factory */
843
+            $factory = new $factoryClass($this);
844
+            return $factory->getLDAPProvider();
845
+        });
846
+        $this->registerService(ILockingProvider::class, function (Server $c) {
847
+            $ini = $c->getIniWrapper();
848
+            $config = $c->getConfig();
849
+            $ttl = $config->getSystemValue('filelocking.ttl', max(3600, $ini->getNumeric('max_execution_time')));
850
+            if ($config->getSystemValue('filelocking.enabled', true) or (defined('PHPUNIT_RUN') && PHPUNIT_RUN)) {
851
+                /** @var \OC\Memcache\Factory $memcacheFactory */
852
+                $memcacheFactory = $c->getMemCacheFactory();
853
+                $memcache = $memcacheFactory->createLocking('lock');
854
+                if (!($memcache instanceof \OC\Memcache\NullCache)) {
855
+                    return new MemcacheLockingProvider($memcache, $ttl);
856
+                }
857
+                return new DBLockingProvider(
858
+                    $c->getDatabaseConnection(),
859
+                    $c->getLogger(),
860
+                    new TimeFactory(),
861
+                    $ttl,
862
+                    !\OC::$CLI
863
+                );
864
+            }
865
+            return new NoopLockingProvider();
866
+        });
867
+        $this->registerAlias('LockingProvider', ILockingProvider::class);
868
+
869
+        $this->registerService(\OCP\Files\Mount\IMountManager::class, function () {
870
+            return new \OC\Files\Mount\Manager();
871
+        });
872
+        $this->registerAlias('MountManager', \OCP\Files\Mount\IMountManager::class);
873
+
874
+        $this->registerService(\OCP\Files\IMimeTypeDetector::class, function (Server $c) {
875
+            return new \OC\Files\Type\Detection(
876
+                $c->getURLGenerator(),
877
+                \OC::$configDir,
878
+                \OC::$SERVERROOT . '/resources/config/'
879
+            );
880
+        });
881
+        $this->registerAlias('MimeTypeDetector', \OCP\Files\IMimeTypeDetector::class);
882
+
883
+        $this->registerService(\OCP\Files\IMimeTypeLoader::class, function (Server $c) {
884
+            return new \OC\Files\Type\Loader(
885
+                $c->getDatabaseConnection()
886
+            );
887
+        });
888
+        $this->registerAlias('MimeTypeLoader', \OCP\Files\IMimeTypeLoader::class);
889
+        $this->registerService(BundleFetcher::class, function () {
890
+            return new BundleFetcher($this->getL10N('lib'));
891
+        });
892
+        $this->registerService(\OCP\Notification\IManager::class, function (Server $c) {
893
+            return new Manager(
894
+                $c->query(IValidator::class)
895
+            );
896
+        });
897
+        $this->registerAlias('NotificationManager', \OCP\Notification\IManager::class);
898
+
899
+        $this->registerService(\OC\CapabilitiesManager::class, function (Server $c) {
900
+            $manager = new \OC\CapabilitiesManager($c->getLogger());
901
+            $manager->registerCapability(function () use ($c) {
902
+                return new \OC\OCS\CoreCapabilities($c->getConfig());
903
+            });
904
+            $manager->registerCapability(function () use ($c) {
905
+                return $c->query(\OC\Security\Bruteforce\Capabilities::class);
906
+            });
907
+            return $manager;
908
+        });
909
+        $this->registerAlias('CapabilitiesManager', \OC\CapabilitiesManager::class);
910
+
911
+        $this->registerService(\OCP\Comments\ICommentsManager::class, function (Server $c) {
912
+            $config = $c->getConfig();
913
+            $factoryClass = $config->getSystemValue('comments.managerFactory', CommentsManagerFactory::class);
914
+            /** @var \OCP\Comments\ICommentsManagerFactory $factory */
915
+            $factory = new $factoryClass($this);
916
+            $manager = $factory->getManager();
917
+
918
+            $manager->registerDisplayNameResolver('user', function($id) use ($c) {
919
+                $manager = $c->getUserManager();
920
+                $user = $manager->get($id);
921
+                if(is_null($user)) {
922
+                    $l = $c->getL10N('core');
923
+                    $displayName = $l->t('Unknown user');
924
+                } else {
925
+                    $displayName = $user->getDisplayName();
926
+                }
927
+                return $displayName;
928
+            });
929
+
930
+            return $manager;
931
+        });
932
+        $this->registerAlias('CommentsManager', \OCP\Comments\ICommentsManager::class);
933
+
934
+        $this->registerService('ThemingDefaults', function (Server $c) {
935
+            /*
936 936
 			 * Dark magic for autoloader.
937 937
 			 * If we do a class_exists it will try to load the class which will
938 938
 			 * make composer cache the result. Resulting in errors when enabling
939 939
 			 * the theming app.
940 940
 			 */
941
-			$prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
942
-			if (isset($prefixes['OCA\\Theming\\'])) {
943
-				$classExists = true;
944
-			} else {
945
-				$classExists = false;
946
-			}
947
-
948
-			if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
949
-				return new ThemingDefaults(
950
-					$c->getConfig(),
951
-					$c->getL10N('theming'),
952
-					$c->getURLGenerator(),
953
-					$c->getMemCacheFactory(),
954
-					new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
955
-					new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator()),
956
-					$c->getAppManager()
957
-				);
958
-			}
959
-			return new \OC_Defaults();
960
-		});
961
-		$this->registerService(SCSSCacher::class, function (Server $c) {
962
-			/** @var Factory $cacheFactory */
963
-			$cacheFactory = $c->query(Factory::class);
964
-			return new SCSSCacher(
965
-				$c->getLogger(),
966
-				$c->query(\OC\Files\AppData\Factory::class),
967
-				$c->getURLGenerator(),
968
-				$c->getConfig(),
969
-				$c->getThemingDefaults(),
970
-				\OC::$SERVERROOT,
971
-				$this->getMemCacheFactory()
972
-			);
973
-		});
974
-		$this->registerService(JSCombiner::class, function (Server $c) {
975
-			/** @var Factory $cacheFactory */
976
-			$cacheFactory = $c->query(Factory::class);
977
-			return new JSCombiner(
978
-				$c->getAppDataDir('js'),
979
-				$c->getURLGenerator(),
980
-				$this->getMemCacheFactory(),
981
-				$c->getSystemConfig(),
982
-				$c->getLogger()
983
-			);
984
-		});
985
-		$this->registerService(EventDispatcher::class, function () {
986
-			return new EventDispatcher();
987
-		});
988
-		$this->registerAlias('EventDispatcher', EventDispatcher::class);
989
-		$this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
990
-
991
-		$this->registerService('CryptoWrapper', function (Server $c) {
992
-			// FIXME: Instantiiated here due to cyclic dependency
993
-			$request = new Request(
994
-				[
995
-					'get' => $_GET,
996
-					'post' => $_POST,
997
-					'files' => $_FILES,
998
-					'server' => $_SERVER,
999
-					'env' => $_ENV,
1000
-					'cookies' => $_COOKIE,
1001
-					'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1002
-						? $_SERVER['REQUEST_METHOD']
1003
-						: null,
1004
-				],
1005
-				$c->getSecureRandom(),
1006
-				$c->getConfig()
1007
-			);
1008
-
1009
-			return new CryptoWrapper(
1010
-				$c->getConfig(),
1011
-				$c->getCrypto(),
1012
-				$c->getSecureRandom(),
1013
-				$request
1014
-			);
1015
-		});
1016
-		$this->registerService('CsrfTokenManager', function (Server $c) {
1017
-			$tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1018
-
1019
-			return new CsrfTokenManager(
1020
-				$tokenGenerator,
1021
-				$c->query(SessionStorage::class)
1022
-			);
1023
-		});
1024
-		$this->registerService(SessionStorage::class, function (Server $c) {
1025
-			return new SessionStorage($c->getSession());
1026
-		});
1027
-		$this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1028
-			return new ContentSecurityPolicyManager();
1029
-		});
1030
-		$this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1031
-
1032
-		$this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1033
-			return new ContentSecurityPolicyNonceManager(
1034
-				$c->getCsrfTokenManager(),
1035
-				$c->getRequest()
1036
-			);
1037
-		});
1038
-
1039
-		$this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1040
-			$config = $c->getConfig();
1041
-			$factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1042
-			/** @var \OCP\Share\IProviderFactory $factory */
1043
-			$factory = new $factoryClass($this);
1044
-
1045
-			$manager = new \OC\Share20\Manager(
1046
-				$c->getLogger(),
1047
-				$c->getConfig(),
1048
-				$c->getSecureRandom(),
1049
-				$c->getHasher(),
1050
-				$c->getMountManager(),
1051
-				$c->getGroupManager(),
1052
-				$c->getL10N('lib'),
1053
-				$c->getL10NFactory(),
1054
-				$factory,
1055
-				$c->getUserManager(),
1056
-				$c->getLazyRootFolder(),
1057
-				$c->getEventDispatcher(),
1058
-				$c->getMailer(),
1059
-				$c->getURLGenerator(),
1060
-				$c->getThemingDefaults()
1061
-			);
1062
-
1063
-			return $manager;
1064
-		});
1065
-		$this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1066
-
1067
-		$this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1068
-			$instance = new Collaboration\Collaborators\Search($c);
1069
-
1070
-			// register default plugins
1071
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1072
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1073
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1074
-			$instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1075
-
1076
-			return $instance;
1077
-		});
1078
-		$this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1079
-
1080
-		$this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1081
-
1082
-		$this->registerService('SettingsManager', function (Server $c) {
1083
-			$manager = new \OC\Settings\Manager(
1084
-				$c->getLogger(),
1085
-				$c->getDatabaseConnection(),
1086
-				$c->getL10N('lib'),
1087
-				$c->getConfig(),
1088
-				$c->getEncryptionManager(),
1089
-				$c->getUserManager(),
1090
-				$c->getLockingProvider(),
1091
-				$c->getRequest(),
1092
-				$c->getURLGenerator(),
1093
-				$c->query(AccountManager::class),
1094
-				$c->getGroupManager(),
1095
-				$c->getL10NFactory(),
1096
-				$c->getAppManager()
1097
-			);
1098
-			return $manager;
1099
-		});
1100
-		$this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1101
-			return new \OC\Files\AppData\Factory(
1102
-				$c->getRootFolder(),
1103
-				$c->getSystemConfig()
1104
-			);
1105
-		});
1106
-
1107
-		$this->registerService('LockdownManager', function (Server $c) {
1108
-			return new LockdownManager(function () use ($c) {
1109
-				return $c->getSession();
1110
-			});
1111
-		});
1112
-
1113
-		$this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1114
-			return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1115
-		});
1116
-
1117
-		$this->registerService(ICloudIdManager::class, function (Server $c) {
1118
-			return new CloudIdManager();
1119
-		});
1120
-
1121
-		$this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1122
-		$this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1123
-
1124
-		$this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1125
-		$this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1126
-
1127
-		$this->registerService(Defaults::class, function (Server $c) {
1128
-			return new Defaults(
1129
-				$c->getThemingDefaults()
1130
-			);
1131
-		});
1132
-		$this->registerAlias('Defaults', \OCP\Defaults::class);
1133
-
1134
-		$this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1135
-			return $c->query(\OCP\IUserSession::class)->getSession();
1136
-		});
1137
-
1138
-		$this->registerService(IShareHelper::class, function (Server $c) {
1139
-			return new ShareHelper(
1140
-				$c->query(\OCP\Share\IManager::class)
1141
-			);
1142
-		});
1143
-
1144
-		$this->registerService(Installer::class, function(Server $c) {
1145
-			return new Installer(
1146
-				$c->getAppFetcher(),
1147
-				$c->getHTTPClientService(),
1148
-				$c->getTempManager(),
1149
-				$c->getLogger(),
1150
-				$c->getConfig()
1151
-			);
1152
-		});
1153
-
1154
-		$this->registerService(IApiFactory::class, function(Server $c) {
1155
-			return new ApiFactory($c->getHTTPClientService());
1156
-		});
1157
-
1158
-		$this->registerService(IInstanceFactory::class, function(Server $c) {
1159
-			$memcacheFactory = $c->getMemCacheFactory();
1160
-			return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1161
-		});
1162
-
1163
-		$this->registerService(IContactsStore::class, function(Server $c) {
1164
-			return new ContactsStore(
1165
-				$c->getContactsManager(),
1166
-				$c->getConfig(),
1167
-				$c->getUserManager(),
1168
-				$c->getGroupManager()
1169
-			);
1170
-		});
1171
-		$this->registerAlias(IContactsStore::class, ContactsStore::class);
1172
-
1173
-		$this->connectDispatcher();
1174
-	}
1175
-
1176
-	/**
1177
-	 * @return \OCP\Calendar\IManager
1178
-	 */
1179
-	public function getCalendarManager() {
1180
-		return $this->query('CalendarManager');
1181
-	}
1182
-
1183
-	private function connectDispatcher() {
1184
-		$dispatcher = $this->getEventDispatcher();
1185
-
1186
-		// Delete avatar on user deletion
1187
-		$dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1188
-			$logger = $this->getLogger();
1189
-			$manager = $this->getAvatarManager();
1190
-			/** @var IUser $user */
1191
-			$user = $e->getSubject();
1192
-
1193
-			try {
1194
-				$avatar = $manager->getAvatar($user->getUID());
1195
-				$avatar->remove();
1196
-			} catch (NotFoundException $e) {
1197
-				// no avatar to remove
1198
-			} catch (\Exception $e) {
1199
-				// Ignore exceptions
1200
-				$logger->info('Could not cleanup avatar of ' . $user->getUID());
1201
-			}
1202
-		});
1203
-
1204
-		$dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1205
-			$manager = $this->getAvatarManager();
1206
-			/** @var IUser $user */
1207
-			$user = $e->getSubject();
1208
-			$feature = $e->getArgument('feature');
1209
-			$oldValue = $e->getArgument('oldValue');
1210
-			$value = $e->getArgument('value');
1211
-
1212
-			try {
1213
-				$avatar = $manager->getAvatar($user->getUID());
1214
-				$avatar->userChanged($feature, $oldValue, $value);
1215
-			} catch (NotFoundException $e) {
1216
-				// no avatar to remove
1217
-			}
1218
-		});
1219
-	}
1220
-
1221
-	/**
1222
-	 * @return \OCP\Contacts\IManager
1223
-	 */
1224
-	public function getContactsManager() {
1225
-		return $this->query('ContactsManager');
1226
-	}
1227
-
1228
-	/**
1229
-	 * @return \OC\Encryption\Manager
1230
-	 */
1231
-	public function getEncryptionManager() {
1232
-		return $this->query('EncryptionManager');
1233
-	}
1234
-
1235
-	/**
1236
-	 * @return \OC\Encryption\File
1237
-	 */
1238
-	public function getEncryptionFilesHelper() {
1239
-		return $this->query('EncryptionFileHelper');
1240
-	}
1241
-
1242
-	/**
1243
-	 * @return \OCP\Encryption\Keys\IStorage
1244
-	 */
1245
-	public function getEncryptionKeyStorage() {
1246
-		return $this->query('EncryptionKeyStorage');
1247
-	}
1248
-
1249
-	/**
1250
-	 * The current request object holding all information about the request
1251
-	 * currently being processed is returned from this method.
1252
-	 * In case the current execution was not initiated by a web request null is returned
1253
-	 *
1254
-	 * @return \OCP\IRequest
1255
-	 */
1256
-	public function getRequest() {
1257
-		return $this->query('Request');
1258
-	}
1259
-
1260
-	/**
1261
-	 * Returns the preview manager which can create preview images for a given file
1262
-	 *
1263
-	 * @return \OCP\IPreview
1264
-	 */
1265
-	public function getPreviewManager() {
1266
-		return $this->query('PreviewManager');
1267
-	}
1268
-
1269
-	/**
1270
-	 * Returns the tag manager which can get and set tags for different object types
1271
-	 *
1272
-	 * @see \OCP\ITagManager::load()
1273
-	 * @return \OCP\ITagManager
1274
-	 */
1275
-	public function getTagManager() {
1276
-		return $this->query('TagManager');
1277
-	}
1278
-
1279
-	/**
1280
-	 * Returns the system-tag manager
1281
-	 *
1282
-	 * @return \OCP\SystemTag\ISystemTagManager
1283
-	 *
1284
-	 * @since 9.0.0
1285
-	 */
1286
-	public function getSystemTagManager() {
1287
-		return $this->query('SystemTagManager');
1288
-	}
1289
-
1290
-	/**
1291
-	 * Returns the system-tag object mapper
1292
-	 *
1293
-	 * @return \OCP\SystemTag\ISystemTagObjectMapper
1294
-	 *
1295
-	 * @since 9.0.0
1296
-	 */
1297
-	public function getSystemTagObjectMapper() {
1298
-		return $this->query('SystemTagObjectMapper');
1299
-	}
1300
-
1301
-	/**
1302
-	 * Returns the avatar manager, used for avatar functionality
1303
-	 *
1304
-	 * @return \OCP\IAvatarManager
1305
-	 */
1306
-	public function getAvatarManager() {
1307
-		return $this->query('AvatarManager');
1308
-	}
1309
-
1310
-	/**
1311
-	 * Returns the root folder of ownCloud's data directory
1312
-	 *
1313
-	 * @return \OCP\Files\IRootFolder
1314
-	 */
1315
-	public function getRootFolder() {
1316
-		return $this->query('LazyRootFolder');
1317
-	}
1318
-
1319
-	/**
1320
-	 * Returns the root folder of ownCloud's data directory
1321
-	 * This is the lazy variant so this gets only initialized once it
1322
-	 * is actually used.
1323
-	 *
1324
-	 * @return \OCP\Files\IRootFolder
1325
-	 */
1326
-	public function getLazyRootFolder() {
1327
-		return $this->query('LazyRootFolder');
1328
-	}
1329
-
1330
-	/**
1331
-	 * Returns a view to ownCloud's files folder
1332
-	 *
1333
-	 * @param string $userId user ID
1334
-	 * @return \OCP\Files\Folder|null
1335
-	 */
1336
-	public function getUserFolder($userId = null) {
1337
-		if ($userId === null) {
1338
-			$user = $this->getUserSession()->getUser();
1339
-			if (!$user) {
1340
-				return null;
1341
-			}
1342
-			$userId = $user->getUID();
1343
-		}
1344
-		$root = $this->getRootFolder();
1345
-		return $root->getUserFolder($userId);
1346
-	}
1347
-
1348
-	/**
1349
-	 * Returns an app-specific view in ownClouds data directory
1350
-	 *
1351
-	 * @return \OCP\Files\Folder
1352
-	 * @deprecated since 9.2.0 use IAppData
1353
-	 */
1354
-	public function getAppFolder() {
1355
-		$dir = '/' . \OC_App::getCurrentApp();
1356
-		$root = $this->getRootFolder();
1357
-		if (!$root->nodeExists($dir)) {
1358
-			$folder = $root->newFolder($dir);
1359
-		} else {
1360
-			$folder = $root->get($dir);
1361
-		}
1362
-		return $folder;
1363
-	}
1364
-
1365
-	/**
1366
-	 * @return \OC\User\Manager
1367
-	 */
1368
-	public function getUserManager() {
1369
-		return $this->query('UserManager');
1370
-	}
1371
-
1372
-	/**
1373
-	 * @return \OC\Group\Manager
1374
-	 */
1375
-	public function getGroupManager() {
1376
-		return $this->query('GroupManager');
1377
-	}
1378
-
1379
-	/**
1380
-	 * @return \OC\User\Session
1381
-	 */
1382
-	public function getUserSession() {
1383
-		return $this->query('UserSession');
1384
-	}
1385
-
1386
-	/**
1387
-	 * @return \OCP\ISession
1388
-	 */
1389
-	public function getSession() {
1390
-		return $this->query('UserSession')->getSession();
1391
-	}
1392
-
1393
-	/**
1394
-	 * @param \OCP\ISession $session
1395
-	 */
1396
-	public function setSession(\OCP\ISession $session) {
1397
-		$this->query(SessionStorage::class)->setSession($session);
1398
-		$this->query('UserSession')->setSession($session);
1399
-		$this->query(Store::class)->setSession($session);
1400
-	}
1401
-
1402
-	/**
1403
-	 * @return \OC\Authentication\TwoFactorAuth\Manager
1404
-	 */
1405
-	public function getTwoFactorAuthManager() {
1406
-		return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1407
-	}
1408
-
1409
-	/**
1410
-	 * @return \OC\NavigationManager
1411
-	 */
1412
-	public function getNavigationManager() {
1413
-		return $this->query('NavigationManager');
1414
-	}
1415
-
1416
-	/**
1417
-	 * @return \OCP\IConfig
1418
-	 */
1419
-	public function getConfig() {
1420
-		return $this->query('AllConfig');
1421
-	}
1422
-
1423
-	/**
1424
-	 * @return \OC\SystemConfig
1425
-	 */
1426
-	public function getSystemConfig() {
1427
-		return $this->query('SystemConfig');
1428
-	}
1429
-
1430
-	/**
1431
-	 * Returns the app config manager
1432
-	 *
1433
-	 * @return \OCP\IAppConfig
1434
-	 */
1435
-	public function getAppConfig() {
1436
-		return $this->query('AppConfig');
1437
-	}
1438
-
1439
-	/**
1440
-	 * @return \OCP\L10N\IFactory
1441
-	 */
1442
-	public function getL10NFactory() {
1443
-		return $this->query('L10NFactory');
1444
-	}
1445
-
1446
-	/**
1447
-	 * get an L10N instance
1448
-	 *
1449
-	 * @param string $app appid
1450
-	 * @param string $lang
1451
-	 * @return IL10N
1452
-	 */
1453
-	public function getL10N($app, $lang = null) {
1454
-		return $this->getL10NFactory()->get($app, $lang);
1455
-	}
1456
-
1457
-	/**
1458
-	 * @return \OCP\IURLGenerator
1459
-	 */
1460
-	public function getURLGenerator() {
1461
-		return $this->query('URLGenerator');
1462
-	}
1463
-
1464
-	/**
1465
-	 * @return AppFetcher
1466
-	 */
1467
-	public function getAppFetcher() {
1468
-		return $this->query(AppFetcher::class);
1469
-	}
1470
-
1471
-	/**
1472
-	 * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1473
-	 * getMemCacheFactory() instead.
1474
-	 *
1475
-	 * @return \OCP\ICache
1476
-	 * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1477
-	 */
1478
-	public function getCache() {
1479
-		return $this->query('UserCache');
1480
-	}
1481
-
1482
-	/**
1483
-	 * Returns an \OCP\CacheFactory instance
1484
-	 *
1485
-	 * @return \OCP\ICacheFactory
1486
-	 */
1487
-	public function getMemCacheFactory() {
1488
-		return $this->query('MemCacheFactory');
1489
-	}
1490
-
1491
-	/**
1492
-	 * Returns an \OC\RedisFactory instance
1493
-	 *
1494
-	 * @return \OC\RedisFactory
1495
-	 */
1496
-	public function getGetRedisFactory() {
1497
-		return $this->query('RedisFactory');
1498
-	}
1499
-
1500
-
1501
-	/**
1502
-	 * Returns the current session
1503
-	 *
1504
-	 * @return \OCP\IDBConnection
1505
-	 */
1506
-	public function getDatabaseConnection() {
1507
-		return $this->query('DatabaseConnection');
1508
-	}
1509
-
1510
-	/**
1511
-	 * Returns the activity manager
1512
-	 *
1513
-	 * @return \OCP\Activity\IManager
1514
-	 */
1515
-	public function getActivityManager() {
1516
-		return $this->query('ActivityManager');
1517
-	}
1518
-
1519
-	/**
1520
-	 * Returns an job list for controlling background jobs
1521
-	 *
1522
-	 * @return \OCP\BackgroundJob\IJobList
1523
-	 */
1524
-	public function getJobList() {
1525
-		return $this->query('JobList');
1526
-	}
1527
-
1528
-	/**
1529
-	 * Returns a logger instance
1530
-	 *
1531
-	 * @return \OCP\ILogger
1532
-	 */
1533
-	public function getLogger() {
1534
-		return $this->query('Logger');
1535
-	}
1536
-
1537
-	/**
1538
-	 * @return ILogFactory
1539
-	 * @throws \OCP\AppFramework\QueryException
1540
-	 */
1541
-	public function getLogFactory() {
1542
-		return $this->query('LogFactory');
1543
-	}
1544
-
1545
-	/**
1546
-	 * Returns a router for generating and matching urls
1547
-	 *
1548
-	 * @return \OCP\Route\IRouter
1549
-	 */
1550
-	public function getRouter() {
1551
-		return $this->query('Router');
1552
-	}
1553
-
1554
-	/**
1555
-	 * Returns a search instance
1556
-	 *
1557
-	 * @return \OCP\ISearch
1558
-	 */
1559
-	public function getSearch() {
1560
-		return $this->query('Search');
1561
-	}
1562
-
1563
-	/**
1564
-	 * Returns a SecureRandom instance
1565
-	 *
1566
-	 * @return \OCP\Security\ISecureRandom
1567
-	 */
1568
-	public function getSecureRandom() {
1569
-		return $this->query('SecureRandom');
1570
-	}
1571
-
1572
-	/**
1573
-	 * Returns a Crypto instance
1574
-	 *
1575
-	 * @return \OCP\Security\ICrypto
1576
-	 */
1577
-	public function getCrypto() {
1578
-		return $this->query('Crypto');
1579
-	}
1580
-
1581
-	/**
1582
-	 * Returns a Hasher instance
1583
-	 *
1584
-	 * @return \OCP\Security\IHasher
1585
-	 */
1586
-	public function getHasher() {
1587
-		return $this->query('Hasher');
1588
-	}
1589
-
1590
-	/**
1591
-	 * Returns a CredentialsManager instance
1592
-	 *
1593
-	 * @return \OCP\Security\ICredentialsManager
1594
-	 */
1595
-	public function getCredentialsManager() {
1596
-		return $this->query('CredentialsManager');
1597
-	}
1598
-
1599
-	/**
1600
-	 * Get the certificate manager for the user
1601
-	 *
1602
-	 * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1603
-	 * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1604
-	 */
1605
-	public function getCertificateManager($userId = '') {
1606
-		if ($userId === '') {
1607
-			$userSession = $this->getUserSession();
1608
-			$user = $userSession->getUser();
1609
-			if (is_null($user)) {
1610
-				return null;
1611
-			}
1612
-			$userId = $user->getUID();
1613
-		}
1614
-		return new CertificateManager(
1615
-			$userId,
1616
-			new View(),
1617
-			$this->getConfig(),
1618
-			$this->getLogger(),
1619
-			$this->getSecureRandom()
1620
-		);
1621
-	}
1622
-
1623
-	/**
1624
-	 * Returns an instance of the HTTP client service
1625
-	 *
1626
-	 * @return \OCP\Http\Client\IClientService
1627
-	 */
1628
-	public function getHTTPClientService() {
1629
-		return $this->query('HttpClientService');
1630
-	}
1631
-
1632
-	/**
1633
-	 * Create a new event source
1634
-	 *
1635
-	 * @return \OCP\IEventSource
1636
-	 */
1637
-	public function createEventSource() {
1638
-		return new \OC_EventSource();
1639
-	}
1640
-
1641
-	/**
1642
-	 * Get the active event logger
1643
-	 *
1644
-	 * The returned logger only logs data when debug mode is enabled
1645
-	 *
1646
-	 * @return \OCP\Diagnostics\IEventLogger
1647
-	 */
1648
-	public function getEventLogger() {
1649
-		return $this->query('EventLogger');
1650
-	}
1651
-
1652
-	/**
1653
-	 * Get the active query logger
1654
-	 *
1655
-	 * The returned logger only logs data when debug mode is enabled
1656
-	 *
1657
-	 * @return \OCP\Diagnostics\IQueryLogger
1658
-	 */
1659
-	public function getQueryLogger() {
1660
-		return $this->query('QueryLogger');
1661
-	}
1662
-
1663
-	/**
1664
-	 * Get the manager for temporary files and folders
1665
-	 *
1666
-	 * @return \OCP\ITempManager
1667
-	 */
1668
-	public function getTempManager() {
1669
-		return $this->query('TempManager');
1670
-	}
1671
-
1672
-	/**
1673
-	 * Get the app manager
1674
-	 *
1675
-	 * @return \OCP\App\IAppManager
1676
-	 */
1677
-	public function getAppManager() {
1678
-		return $this->query('AppManager');
1679
-	}
1680
-
1681
-	/**
1682
-	 * Creates a new mailer
1683
-	 *
1684
-	 * @return \OCP\Mail\IMailer
1685
-	 */
1686
-	public function getMailer() {
1687
-		return $this->query('Mailer');
1688
-	}
1689
-
1690
-	/**
1691
-	 * Get the webroot
1692
-	 *
1693
-	 * @return string
1694
-	 */
1695
-	public function getWebRoot() {
1696
-		return $this->webRoot;
1697
-	}
1698
-
1699
-	/**
1700
-	 * @return \OC\OCSClient
1701
-	 */
1702
-	public function getOcsClient() {
1703
-		return $this->query('OcsClient');
1704
-	}
1705
-
1706
-	/**
1707
-	 * @return \OCP\IDateTimeZone
1708
-	 */
1709
-	public function getDateTimeZone() {
1710
-		return $this->query('DateTimeZone');
1711
-	}
1712
-
1713
-	/**
1714
-	 * @return \OCP\IDateTimeFormatter
1715
-	 */
1716
-	public function getDateTimeFormatter() {
1717
-		return $this->query('DateTimeFormatter');
1718
-	}
1719
-
1720
-	/**
1721
-	 * @return \OCP\Files\Config\IMountProviderCollection
1722
-	 */
1723
-	public function getMountProviderCollection() {
1724
-		return $this->query('MountConfigManager');
1725
-	}
1726
-
1727
-	/**
1728
-	 * Get the IniWrapper
1729
-	 *
1730
-	 * @return IniGetWrapper
1731
-	 */
1732
-	public function getIniWrapper() {
1733
-		return $this->query('IniWrapper');
1734
-	}
1735
-
1736
-	/**
1737
-	 * @return \OCP\Command\IBus
1738
-	 */
1739
-	public function getCommandBus() {
1740
-		return $this->query('AsyncCommandBus');
1741
-	}
1742
-
1743
-	/**
1744
-	 * Get the trusted domain helper
1745
-	 *
1746
-	 * @return TrustedDomainHelper
1747
-	 */
1748
-	public function getTrustedDomainHelper() {
1749
-		return $this->query('TrustedDomainHelper');
1750
-	}
1751
-
1752
-	/**
1753
-	 * Get the locking provider
1754
-	 *
1755
-	 * @return \OCP\Lock\ILockingProvider
1756
-	 * @since 8.1.0
1757
-	 */
1758
-	public function getLockingProvider() {
1759
-		return $this->query('LockingProvider');
1760
-	}
1761
-
1762
-	/**
1763
-	 * @return \OCP\Files\Mount\IMountManager
1764
-	 **/
1765
-	function getMountManager() {
1766
-		return $this->query('MountManager');
1767
-	}
1768
-
1769
-	/** @return \OCP\Files\Config\IUserMountCache */
1770
-	function getUserMountCache() {
1771
-		return $this->query('UserMountCache');
1772
-	}
1773
-
1774
-	/**
1775
-	 * Get the MimeTypeDetector
1776
-	 *
1777
-	 * @return \OCP\Files\IMimeTypeDetector
1778
-	 */
1779
-	public function getMimeTypeDetector() {
1780
-		return $this->query('MimeTypeDetector');
1781
-	}
1782
-
1783
-	/**
1784
-	 * Get the MimeTypeLoader
1785
-	 *
1786
-	 * @return \OCP\Files\IMimeTypeLoader
1787
-	 */
1788
-	public function getMimeTypeLoader() {
1789
-		return $this->query('MimeTypeLoader');
1790
-	}
1791
-
1792
-	/**
1793
-	 * Get the manager of all the capabilities
1794
-	 *
1795
-	 * @return \OC\CapabilitiesManager
1796
-	 */
1797
-	public function getCapabilitiesManager() {
1798
-		return $this->query('CapabilitiesManager');
1799
-	}
1800
-
1801
-	/**
1802
-	 * Get the EventDispatcher
1803
-	 *
1804
-	 * @return EventDispatcherInterface
1805
-	 * @since 8.2.0
1806
-	 */
1807
-	public function getEventDispatcher() {
1808
-		return $this->query('EventDispatcher');
1809
-	}
1810
-
1811
-	/**
1812
-	 * Get the Notification Manager
1813
-	 *
1814
-	 * @return \OCP\Notification\IManager
1815
-	 * @since 8.2.0
1816
-	 */
1817
-	public function getNotificationManager() {
1818
-		return $this->query('NotificationManager');
1819
-	}
1820
-
1821
-	/**
1822
-	 * @return \OCP\Comments\ICommentsManager
1823
-	 */
1824
-	public function getCommentsManager() {
1825
-		return $this->query('CommentsManager');
1826
-	}
1827
-
1828
-	/**
1829
-	 * @return \OCA\Theming\ThemingDefaults
1830
-	 */
1831
-	public function getThemingDefaults() {
1832
-		return $this->query('ThemingDefaults');
1833
-	}
1834
-
1835
-	/**
1836
-	 * @return \OC\IntegrityCheck\Checker
1837
-	 */
1838
-	public function getIntegrityCodeChecker() {
1839
-		return $this->query('IntegrityCodeChecker');
1840
-	}
1841
-
1842
-	/**
1843
-	 * @return \OC\Session\CryptoWrapper
1844
-	 */
1845
-	public function getSessionCryptoWrapper() {
1846
-		return $this->query('CryptoWrapper');
1847
-	}
1848
-
1849
-	/**
1850
-	 * @return CsrfTokenManager
1851
-	 */
1852
-	public function getCsrfTokenManager() {
1853
-		return $this->query('CsrfTokenManager');
1854
-	}
1855
-
1856
-	/**
1857
-	 * @return Throttler
1858
-	 */
1859
-	public function getBruteForceThrottler() {
1860
-		return $this->query('Throttler');
1861
-	}
1862
-
1863
-	/**
1864
-	 * @return IContentSecurityPolicyManager
1865
-	 */
1866
-	public function getContentSecurityPolicyManager() {
1867
-		return $this->query('ContentSecurityPolicyManager');
1868
-	}
1869
-
1870
-	/**
1871
-	 * @return ContentSecurityPolicyNonceManager
1872
-	 */
1873
-	public function getContentSecurityPolicyNonceManager() {
1874
-		return $this->query('ContentSecurityPolicyNonceManager');
1875
-	}
1876
-
1877
-	/**
1878
-	 * Not a public API as of 8.2, wait for 9.0
1879
-	 *
1880
-	 * @return \OCA\Files_External\Service\BackendService
1881
-	 */
1882
-	public function getStoragesBackendService() {
1883
-		return $this->query('OCA\\Files_External\\Service\\BackendService');
1884
-	}
1885
-
1886
-	/**
1887
-	 * Not a public API as of 8.2, wait for 9.0
1888
-	 *
1889
-	 * @return \OCA\Files_External\Service\GlobalStoragesService
1890
-	 */
1891
-	public function getGlobalStoragesService() {
1892
-		return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1893
-	}
1894
-
1895
-	/**
1896
-	 * Not a public API as of 8.2, wait for 9.0
1897
-	 *
1898
-	 * @return \OCA\Files_External\Service\UserGlobalStoragesService
1899
-	 */
1900
-	public function getUserGlobalStoragesService() {
1901
-		return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1902
-	}
1903
-
1904
-	/**
1905
-	 * Not a public API as of 8.2, wait for 9.0
1906
-	 *
1907
-	 * @return \OCA\Files_External\Service\UserStoragesService
1908
-	 */
1909
-	public function getUserStoragesService() {
1910
-		return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1911
-	}
1912
-
1913
-	/**
1914
-	 * @return \OCP\Share\IManager
1915
-	 */
1916
-	public function getShareManager() {
1917
-		return $this->query('ShareManager');
1918
-	}
1919
-
1920
-	/**
1921
-	 * @return \OCP\Collaboration\Collaborators\ISearch
1922
-	 */
1923
-	public function getCollaboratorSearch() {
1924
-		return $this->query('CollaboratorSearch');
1925
-	}
1926
-
1927
-	/**
1928
-	 * @return \OCP\Collaboration\AutoComplete\IManager
1929
-	 */
1930
-	public function getAutoCompleteManager(){
1931
-		return $this->query(IManager::class);
1932
-	}
1933
-
1934
-	/**
1935
-	 * Returns the LDAP Provider
1936
-	 *
1937
-	 * @return \OCP\LDAP\ILDAPProvider
1938
-	 */
1939
-	public function getLDAPProvider() {
1940
-		return $this->query('LDAPProvider');
1941
-	}
1942
-
1943
-	/**
1944
-	 * @return \OCP\Settings\IManager
1945
-	 */
1946
-	public function getSettingsManager() {
1947
-		return $this->query('SettingsManager');
1948
-	}
1949
-
1950
-	/**
1951
-	 * @return \OCP\Files\IAppData
1952
-	 */
1953
-	public function getAppDataDir($app) {
1954
-		/** @var \OC\Files\AppData\Factory $factory */
1955
-		$factory = $this->query(\OC\Files\AppData\Factory::class);
1956
-		return $factory->get($app);
1957
-	}
1958
-
1959
-	/**
1960
-	 * @return \OCP\Lockdown\ILockdownManager
1961
-	 */
1962
-	public function getLockdownManager() {
1963
-		return $this->query('LockdownManager');
1964
-	}
1965
-
1966
-	/**
1967
-	 * @return \OCP\Federation\ICloudIdManager
1968
-	 */
1969
-	public function getCloudIdManager() {
1970
-		return $this->query(ICloudIdManager::class);
1971
-	}
1972
-
1973
-	/**
1974
-	 * @return \OCP\Remote\Api\IApiFactory
1975
-	 */
1976
-	public function getRemoteApiFactory() {
1977
-		return $this->query(IApiFactory::class);
1978
-	}
1979
-
1980
-	/**
1981
-	 * @return \OCP\Remote\IInstanceFactory
1982
-	 */
1983
-	public function getRemoteInstanceFactory() {
1984
-		return $this->query(IInstanceFactory::class);
1985
-	}
941
+            $prefixes = \OC::$composerAutoloader->getPrefixesPsr4();
942
+            if (isset($prefixes['OCA\\Theming\\'])) {
943
+                $classExists = true;
944
+            } else {
945
+                $classExists = false;
946
+            }
947
+
948
+            if ($classExists && $c->getConfig()->getSystemValue('installed', false) && $c->getAppManager()->isInstalled('theming') && $c->getTrustedDomainHelper()->isTrustedDomain($c->getRequest()->getInsecureServerHost())) {
949
+                return new ThemingDefaults(
950
+                    $c->getConfig(),
951
+                    $c->getL10N('theming'),
952
+                    $c->getURLGenerator(),
953
+                    $c->getMemCacheFactory(),
954
+                    new Util($c->getConfig(), $this->getAppManager(), $c->getAppDataDir('theming')),
955
+                    new ImageManager($c->getConfig(), $c->getAppDataDir('theming'), $c->getURLGenerator()),
956
+                    $c->getAppManager()
957
+                );
958
+            }
959
+            return new \OC_Defaults();
960
+        });
961
+        $this->registerService(SCSSCacher::class, function (Server $c) {
962
+            /** @var Factory $cacheFactory */
963
+            $cacheFactory = $c->query(Factory::class);
964
+            return new SCSSCacher(
965
+                $c->getLogger(),
966
+                $c->query(\OC\Files\AppData\Factory::class),
967
+                $c->getURLGenerator(),
968
+                $c->getConfig(),
969
+                $c->getThemingDefaults(),
970
+                \OC::$SERVERROOT,
971
+                $this->getMemCacheFactory()
972
+            );
973
+        });
974
+        $this->registerService(JSCombiner::class, function (Server $c) {
975
+            /** @var Factory $cacheFactory */
976
+            $cacheFactory = $c->query(Factory::class);
977
+            return new JSCombiner(
978
+                $c->getAppDataDir('js'),
979
+                $c->getURLGenerator(),
980
+                $this->getMemCacheFactory(),
981
+                $c->getSystemConfig(),
982
+                $c->getLogger()
983
+            );
984
+        });
985
+        $this->registerService(EventDispatcher::class, function () {
986
+            return new EventDispatcher();
987
+        });
988
+        $this->registerAlias('EventDispatcher', EventDispatcher::class);
989
+        $this->registerAlias(EventDispatcherInterface::class, EventDispatcher::class);
990
+
991
+        $this->registerService('CryptoWrapper', function (Server $c) {
992
+            // FIXME: Instantiiated here due to cyclic dependency
993
+            $request = new Request(
994
+                [
995
+                    'get' => $_GET,
996
+                    'post' => $_POST,
997
+                    'files' => $_FILES,
998
+                    'server' => $_SERVER,
999
+                    'env' => $_ENV,
1000
+                    'cookies' => $_COOKIE,
1001
+                    'method' => (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']))
1002
+                        ? $_SERVER['REQUEST_METHOD']
1003
+                        : null,
1004
+                ],
1005
+                $c->getSecureRandom(),
1006
+                $c->getConfig()
1007
+            );
1008
+
1009
+            return new CryptoWrapper(
1010
+                $c->getConfig(),
1011
+                $c->getCrypto(),
1012
+                $c->getSecureRandom(),
1013
+                $request
1014
+            );
1015
+        });
1016
+        $this->registerService('CsrfTokenManager', function (Server $c) {
1017
+            $tokenGenerator = new CsrfTokenGenerator($c->getSecureRandom());
1018
+
1019
+            return new CsrfTokenManager(
1020
+                $tokenGenerator,
1021
+                $c->query(SessionStorage::class)
1022
+            );
1023
+        });
1024
+        $this->registerService(SessionStorage::class, function (Server $c) {
1025
+            return new SessionStorage($c->getSession());
1026
+        });
1027
+        $this->registerService(\OCP\Security\IContentSecurityPolicyManager::class, function (Server $c) {
1028
+            return new ContentSecurityPolicyManager();
1029
+        });
1030
+        $this->registerAlias('ContentSecurityPolicyManager', \OCP\Security\IContentSecurityPolicyManager::class);
1031
+
1032
+        $this->registerService('ContentSecurityPolicyNonceManager', function (Server $c) {
1033
+            return new ContentSecurityPolicyNonceManager(
1034
+                $c->getCsrfTokenManager(),
1035
+                $c->getRequest()
1036
+            );
1037
+        });
1038
+
1039
+        $this->registerService(\OCP\Share\IManager::class, function (Server $c) {
1040
+            $config = $c->getConfig();
1041
+            $factoryClass = $config->getSystemValue('sharing.managerFactory', ProviderFactory::class);
1042
+            /** @var \OCP\Share\IProviderFactory $factory */
1043
+            $factory = new $factoryClass($this);
1044
+
1045
+            $manager = new \OC\Share20\Manager(
1046
+                $c->getLogger(),
1047
+                $c->getConfig(),
1048
+                $c->getSecureRandom(),
1049
+                $c->getHasher(),
1050
+                $c->getMountManager(),
1051
+                $c->getGroupManager(),
1052
+                $c->getL10N('lib'),
1053
+                $c->getL10NFactory(),
1054
+                $factory,
1055
+                $c->getUserManager(),
1056
+                $c->getLazyRootFolder(),
1057
+                $c->getEventDispatcher(),
1058
+                $c->getMailer(),
1059
+                $c->getURLGenerator(),
1060
+                $c->getThemingDefaults()
1061
+            );
1062
+
1063
+            return $manager;
1064
+        });
1065
+        $this->registerAlias('ShareManager', \OCP\Share\IManager::class);
1066
+
1067
+        $this->registerService(\OCP\Collaboration\Collaborators\ISearch::class, function(Server $c) {
1068
+            $instance = new Collaboration\Collaborators\Search($c);
1069
+
1070
+            // register default plugins
1071
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_USER', 'class' => UserPlugin::class]);
1072
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_GROUP', 'class' => GroupPlugin::class]);
1073
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_EMAIL', 'class' => MailPlugin::class]);
1074
+            $instance->registerPlugin(['shareType' => 'SHARE_TYPE_REMOTE', 'class' => RemotePlugin::class]);
1075
+
1076
+            return $instance;
1077
+        });
1078
+        $this->registerAlias('CollaboratorSearch', \OCP\Collaboration\Collaborators\ISearch::class);
1079
+
1080
+        $this->registerAlias(\OCP\Collaboration\AutoComplete\IManager::class, \OC\Collaboration\AutoComplete\Manager::class);
1081
+
1082
+        $this->registerService('SettingsManager', function (Server $c) {
1083
+            $manager = new \OC\Settings\Manager(
1084
+                $c->getLogger(),
1085
+                $c->getDatabaseConnection(),
1086
+                $c->getL10N('lib'),
1087
+                $c->getConfig(),
1088
+                $c->getEncryptionManager(),
1089
+                $c->getUserManager(),
1090
+                $c->getLockingProvider(),
1091
+                $c->getRequest(),
1092
+                $c->getURLGenerator(),
1093
+                $c->query(AccountManager::class),
1094
+                $c->getGroupManager(),
1095
+                $c->getL10NFactory(),
1096
+                $c->getAppManager()
1097
+            );
1098
+            return $manager;
1099
+        });
1100
+        $this->registerService(\OC\Files\AppData\Factory::class, function (Server $c) {
1101
+            return new \OC\Files\AppData\Factory(
1102
+                $c->getRootFolder(),
1103
+                $c->getSystemConfig()
1104
+            );
1105
+        });
1106
+
1107
+        $this->registerService('LockdownManager', function (Server $c) {
1108
+            return new LockdownManager(function () use ($c) {
1109
+                return $c->getSession();
1110
+            });
1111
+        });
1112
+
1113
+        $this->registerService(\OCP\OCS\IDiscoveryService::class, function (Server $c) {
1114
+            return new DiscoveryService($c->getMemCacheFactory(), $c->getHTTPClientService());
1115
+        });
1116
+
1117
+        $this->registerService(ICloudIdManager::class, function (Server $c) {
1118
+            return new CloudIdManager();
1119
+        });
1120
+
1121
+        $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class);
1122
+        $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class);
1123
+
1124
+        $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class);
1125
+        $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class);
1126
+
1127
+        $this->registerService(Defaults::class, function (Server $c) {
1128
+            return new Defaults(
1129
+                $c->getThemingDefaults()
1130
+            );
1131
+        });
1132
+        $this->registerAlias('Defaults', \OCP\Defaults::class);
1133
+
1134
+        $this->registerService(\OCP\ISession::class, function (SimpleContainer $c) {
1135
+            return $c->query(\OCP\IUserSession::class)->getSession();
1136
+        });
1137
+
1138
+        $this->registerService(IShareHelper::class, function (Server $c) {
1139
+            return new ShareHelper(
1140
+                $c->query(\OCP\Share\IManager::class)
1141
+            );
1142
+        });
1143
+
1144
+        $this->registerService(Installer::class, function(Server $c) {
1145
+            return new Installer(
1146
+                $c->getAppFetcher(),
1147
+                $c->getHTTPClientService(),
1148
+                $c->getTempManager(),
1149
+                $c->getLogger(),
1150
+                $c->getConfig()
1151
+            );
1152
+        });
1153
+
1154
+        $this->registerService(IApiFactory::class, function(Server $c) {
1155
+            return new ApiFactory($c->getHTTPClientService());
1156
+        });
1157
+
1158
+        $this->registerService(IInstanceFactory::class, function(Server $c) {
1159
+            $memcacheFactory = $c->getMemCacheFactory();
1160
+            return new InstanceFactory($memcacheFactory->createLocal('remoteinstance.'), $c->getHTTPClientService());
1161
+        });
1162
+
1163
+        $this->registerService(IContactsStore::class, function(Server $c) {
1164
+            return new ContactsStore(
1165
+                $c->getContactsManager(),
1166
+                $c->getConfig(),
1167
+                $c->getUserManager(),
1168
+                $c->getGroupManager()
1169
+            );
1170
+        });
1171
+        $this->registerAlias(IContactsStore::class, ContactsStore::class);
1172
+
1173
+        $this->connectDispatcher();
1174
+    }
1175
+
1176
+    /**
1177
+     * @return \OCP\Calendar\IManager
1178
+     */
1179
+    public function getCalendarManager() {
1180
+        return $this->query('CalendarManager');
1181
+    }
1182
+
1183
+    private function connectDispatcher() {
1184
+        $dispatcher = $this->getEventDispatcher();
1185
+
1186
+        // Delete avatar on user deletion
1187
+        $dispatcher->addListener('OCP\IUser::preDelete', function(GenericEvent $e) {
1188
+            $logger = $this->getLogger();
1189
+            $manager = $this->getAvatarManager();
1190
+            /** @var IUser $user */
1191
+            $user = $e->getSubject();
1192
+
1193
+            try {
1194
+                $avatar = $manager->getAvatar($user->getUID());
1195
+                $avatar->remove();
1196
+            } catch (NotFoundException $e) {
1197
+                // no avatar to remove
1198
+            } catch (\Exception $e) {
1199
+                // Ignore exceptions
1200
+                $logger->info('Could not cleanup avatar of ' . $user->getUID());
1201
+            }
1202
+        });
1203
+
1204
+        $dispatcher->addListener('OCP\IUser::changeUser', function (GenericEvent $e) {
1205
+            $manager = $this->getAvatarManager();
1206
+            /** @var IUser $user */
1207
+            $user = $e->getSubject();
1208
+            $feature = $e->getArgument('feature');
1209
+            $oldValue = $e->getArgument('oldValue');
1210
+            $value = $e->getArgument('value');
1211
+
1212
+            try {
1213
+                $avatar = $manager->getAvatar($user->getUID());
1214
+                $avatar->userChanged($feature, $oldValue, $value);
1215
+            } catch (NotFoundException $e) {
1216
+                // no avatar to remove
1217
+            }
1218
+        });
1219
+    }
1220
+
1221
+    /**
1222
+     * @return \OCP\Contacts\IManager
1223
+     */
1224
+    public function getContactsManager() {
1225
+        return $this->query('ContactsManager');
1226
+    }
1227
+
1228
+    /**
1229
+     * @return \OC\Encryption\Manager
1230
+     */
1231
+    public function getEncryptionManager() {
1232
+        return $this->query('EncryptionManager');
1233
+    }
1234
+
1235
+    /**
1236
+     * @return \OC\Encryption\File
1237
+     */
1238
+    public function getEncryptionFilesHelper() {
1239
+        return $this->query('EncryptionFileHelper');
1240
+    }
1241
+
1242
+    /**
1243
+     * @return \OCP\Encryption\Keys\IStorage
1244
+     */
1245
+    public function getEncryptionKeyStorage() {
1246
+        return $this->query('EncryptionKeyStorage');
1247
+    }
1248
+
1249
+    /**
1250
+     * The current request object holding all information about the request
1251
+     * currently being processed is returned from this method.
1252
+     * In case the current execution was not initiated by a web request null is returned
1253
+     *
1254
+     * @return \OCP\IRequest
1255
+     */
1256
+    public function getRequest() {
1257
+        return $this->query('Request');
1258
+    }
1259
+
1260
+    /**
1261
+     * Returns the preview manager which can create preview images for a given file
1262
+     *
1263
+     * @return \OCP\IPreview
1264
+     */
1265
+    public function getPreviewManager() {
1266
+        return $this->query('PreviewManager');
1267
+    }
1268
+
1269
+    /**
1270
+     * Returns the tag manager which can get and set tags for different object types
1271
+     *
1272
+     * @see \OCP\ITagManager::load()
1273
+     * @return \OCP\ITagManager
1274
+     */
1275
+    public function getTagManager() {
1276
+        return $this->query('TagManager');
1277
+    }
1278
+
1279
+    /**
1280
+     * Returns the system-tag manager
1281
+     *
1282
+     * @return \OCP\SystemTag\ISystemTagManager
1283
+     *
1284
+     * @since 9.0.0
1285
+     */
1286
+    public function getSystemTagManager() {
1287
+        return $this->query('SystemTagManager');
1288
+    }
1289
+
1290
+    /**
1291
+     * Returns the system-tag object mapper
1292
+     *
1293
+     * @return \OCP\SystemTag\ISystemTagObjectMapper
1294
+     *
1295
+     * @since 9.0.0
1296
+     */
1297
+    public function getSystemTagObjectMapper() {
1298
+        return $this->query('SystemTagObjectMapper');
1299
+    }
1300
+
1301
+    /**
1302
+     * Returns the avatar manager, used for avatar functionality
1303
+     *
1304
+     * @return \OCP\IAvatarManager
1305
+     */
1306
+    public function getAvatarManager() {
1307
+        return $this->query('AvatarManager');
1308
+    }
1309
+
1310
+    /**
1311
+     * Returns the root folder of ownCloud's data directory
1312
+     *
1313
+     * @return \OCP\Files\IRootFolder
1314
+     */
1315
+    public function getRootFolder() {
1316
+        return $this->query('LazyRootFolder');
1317
+    }
1318
+
1319
+    /**
1320
+     * Returns the root folder of ownCloud's data directory
1321
+     * This is the lazy variant so this gets only initialized once it
1322
+     * is actually used.
1323
+     *
1324
+     * @return \OCP\Files\IRootFolder
1325
+     */
1326
+    public function getLazyRootFolder() {
1327
+        return $this->query('LazyRootFolder');
1328
+    }
1329
+
1330
+    /**
1331
+     * Returns a view to ownCloud's files folder
1332
+     *
1333
+     * @param string $userId user ID
1334
+     * @return \OCP\Files\Folder|null
1335
+     */
1336
+    public function getUserFolder($userId = null) {
1337
+        if ($userId === null) {
1338
+            $user = $this->getUserSession()->getUser();
1339
+            if (!$user) {
1340
+                return null;
1341
+            }
1342
+            $userId = $user->getUID();
1343
+        }
1344
+        $root = $this->getRootFolder();
1345
+        return $root->getUserFolder($userId);
1346
+    }
1347
+
1348
+    /**
1349
+     * Returns an app-specific view in ownClouds data directory
1350
+     *
1351
+     * @return \OCP\Files\Folder
1352
+     * @deprecated since 9.2.0 use IAppData
1353
+     */
1354
+    public function getAppFolder() {
1355
+        $dir = '/' . \OC_App::getCurrentApp();
1356
+        $root = $this->getRootFolder();
1357
+        if (!$root->nodeExists($dir)) {
1358
+            $folder = $root->newFolder($dir);
1359
+        } else {
1360
+            $folder = $root->get($dir);
1361
+        }
1362
+        return $folder;
1363
+    }
1364
+
1365
+    /**
1366
+     * @return \OC\User\Manager
1367
+     */
1368
+    public function getUserManager() {
1369
+        return $this->query('UserManager');
1370
+    }
1371
+
1372
+    /**
1373
+     * @return \OC\Group\Manager
1374
+     */
1375
+    public function getGroupManager() {
1376
+        return $this->query('GroupManager');
1377
+    }
1378
+
1379
+    /**
1380
+     * @return \OC\User\Session
1381
+     */
1382
+    public function getUserSession() {
1383
+        return $this->query('UserSession');
1384
+    }
1385
+
1386
+    /**
1387
+     * @return \OCP\ISession
1388
+     */
1389
+    public function getSession() {
1390
+        return $this->query('UserSession')->getSession();
1391
+    }
1392
+
1393
+    /**
1394
+     * @param \OCP\ISession $session
1395
+     */
1396
+    public function setSession(\OCP\ISession $session) {
1397
+        $this->query(SessionStorage::class)->setSession($session);
1398
+        $this->query('UserSession')->setSession($session);
1399
+        $this->query(Store::class)->setSession($session);
1400
+    }
1401
+
1402
+    /**
1403
+     * @return \OC\Authentication\TwoFactorAuth\Manager
1404
+     */
1405
+    public function getTwoFactorAuthManager() {
1406
+        return $this->query('\OC\Authentication\TwoFactorAuth\Manager');
1407
+    }
1408
+
1409
+    /**
1410
+     * @return \OC\NavigationManager
1411
+     */
1412
+    public function getNavigationManager() {
1413
+        return $this->query('NavigationManager');
1414
+    }
1415
+
1416
+    /**
1417
+     * @return \OCP\IConfig
1418
+     */
1419
+    public function getConfig() {
1420
+        return $this->query('AllConfig');
1421
+    }
1422
+
1423
+    /**
1424
+     * @return \OC\SystemConfig
1425
+     */
1426
+    public function getSystemConfig() {
1427
+        return $this->query('SystemConfig');
1428
+    }
1429
+
1430
+    /**
1431
+     * Returns the app config manager
1432
+     *
1433
+     * @return \OCP\IAppConfig
1434
+     */
1435
+    public function getAppConfig() {
1436
+        return $this->query('AppConfig');
1437
+    }
1438
+
1439
+    /**
1440
+     * @return \OCP\L10N\IFactory
1441
+     */
1442
+    public function getL10NFactory() {
1443
+        return $this->query('L10NFactory');
1444
+    }
1445
+
1446
+    /**
1447
+     * get an L10N instance
1448
+     *
1449
+     * @param string $app appid
1450
+     * @param string $lang
1451
+     * @return IL10N
1452
+     */
1453
+    public function getL10N($app, $lang = null) {
1454
+        return $this->getL10NFactory()->get($app, $lang);
1455
+    }
1456
+
1457
+    /**
1458
+     * @return \OCP\IURLGenerator
1459
+     */
1460
+    public function getURLGenerator() {
1461
+        return $this->query('URLGenerator');
1462
+    }
1463
+
1464
+    /**
1465
+     * @return AppFetcher
1466
+     */
1467
+    public function getAppFetcher() {
1468
+        return $this->query(AppFetcher::class);
1469
+    }
1470
+
1471
+    /**
1472
+     * Returns an ICache instance. Since 8.1.0 it returns a fake cache. Use
1473
+     * getMemCacheFactory() instead.
1474
+     *
1475
+     * @return \OCP\ICache
1476
+     * @deprecated 8.1.0 use getMemCacheFactory to obtain a proper cache
1477
+     */
1478
+    public function getCache() {
1479
+        return $this->query('UserCache');
1480
+    }
1481
+
1482
+    /**
1483
+     * Returns an \OCP\CacheFactory instance
1484
+     *
1485
+     * @return \OCP\ICacheFactory
1486
+     */
1487
+    public function getMemCacheFactory() {
1488
+        return $this->query('MemCacheFactory');
1489
+    }
1490
+
1491
+    /**
1492
+     * Returns an \OC\RedisFactory instance
1493
+     *
1494
+     * @return \OC\RedisFactory
1495
+     */
1496
+    public function getGetRedisFactory() {
1497
+        return $this->query('RedisFactory');
1498
+    }
1499
+
1500
+
1501
+    /**
1502
+     * Returns the current session
1503
+     *
1504
+     * @return \OCP\IDBConnection
1505
+     */
1506
+    public function getDatabaseConnection() {
1507
+        return $this->query('DatabaseConnection');
1508
+    }
1509
+
1510
+    /**
1511
+     * Returns the activity manager
1512
+     *
1513
+     * @return \OCP\Activity\IManager
1514
+     */
1515
+    public function getActivityManager() {
1516
+        return $this->query('ActivityManager');
1517
+    }
1518
+
1519
+    /**
1520
+     * Returns an job list for controlling background jobs
1521
+     *
1522
+     * @return \OCP\BackgroundJob\IJobList
1523
+     */
1524
+    public function getJobList() {
1525
+        return $this->query('JobList');
1526
+    }
1527
+
1528
+    /**
1529
+     * Returns a logger instance
1530
+     *
1531
+     * @return \OCP\ILogger
1532
+     */
1533
+    public function getLogger() {
1534
+        return $this->query('Logger');
1535
+    }
1536
+
1537
+    /**
1538
+     * @return ILogFactory
1539
+     * @throws \OCP\AppFramework\QueryException
1540
+     */
1541
+    public function getLogFactory() {
1542
+        return $this->query('LogFactory');
1543
+    }
1544
+
1545
+    /**
1546
+     * Returns a router for generating and matching urls
1547
+     *
1548
+     * @return \OCP\Route\IRouter
1549
+     */
1550
+    public function getRouter() {
1551
+        return $this->query('Router');
1552
+    }
1553
+
1554
+    /**
1555
+     * Returns a search instance
1556
+     *
1557
+     * @return \OCP\ISearch
1558
+     */
1559
+    public function getSearch() {
1560
+        return $this->query('Search');
1561
+    }
1562
+
1563
+    /**
1564
+     * Returns a SecureRandom instance
1565
+     *
1566
+     * @return \OCP\Security\ISecureRandom
1567
+     */
1568
+    public function getSecureRandom() {
1569
+        return $this->query('SecureRandom');
1570
+    }
1571
+
1572
+    /**
1573
+     * Returns a Crypto instance
1574
+     *
1575
+     * @return \OCP\Security\ICrypto
1576
+     */
1577
+    public function getCrypto() {
1578
+        return $this->query('Crypto');
1579
+    }
1580
+
1581
+    /**
1582
+     * Returns a Hasher instance
1583
+     *
1584
+     * @return \OCP\Security\IHasher
1585
+     */
1586
+    public function getHasher() {
1587
+        return $this->query('Hasher');
1588
+    }
1589
+
1590
+    /**
1591
+     * Returns a CredentialsManager instance
1592
+     *
1593
+     * @return \OCP\Security\ICredentialsManager
1594
+     */
1595
+    public function getCredentialsManager() {
1596
+        return $this->query('CredentialsManager');
1597
+    }
1598
+
1599
+    /**
1600
+     * Get the certificate manager for the user
1601
+     *
1602
+     * @param string $userId (optional) if not specified the current loggedin user is used, use null to get the system certificate manager
1603
+     * @return \OCP\ICertificateManager | null if $uid is null and no user is logged in
1604
+     */
1605
+    public function getCertificateManager($userId = '') {
1606
+        if ($userId === '') {
1607
+            $userSession = $this->getUserSession();
1608
+            $user = $userSession->getUser();
1609
+            if (is_null($user)) {
1610
+                return null;
1611
+            }
1612
+            $userId = $user->getUID();
1613
+        }
1614
+        return new CertificateManager(
1615
+            $userId,
1616
+            new View(),
1617
+            $this->getConfig(),
1618
+            $this->getLogger(),
1619
+            $this->getSecureRandom()
1620
+        );
1621
+    }
1622
+
1623
+    /**
1624
+     * Returns an instance of the HTTP client service
1625
+     *
1626
+     * @return \OCP\Http\Client\IClientService
1627
+     */
1628
+    public function getHTTPClientService() {
1629
+        return $this->query('HttpClientService');
1630
+    }
1631
+
1632
+    /**
1633
+     * Create a new event source
1634
+     *
1635
+     * @return \OCP\IEventSource
1636
+     */
1637
+    public function createEventSource() {
1638
+        return new \OC_EventSource();
1639
+    }
1640
+
1641
+    /**
1642
+     * Get the active event logger
1643
+     *
1644
+     * The returned logger only logs data when debug mode is enabled
1645
+     *
1646
+     * @return \OCP\Diagnostics\IEventLogger
1647
+     */
1648
+    public function getEventLogger() {
1649
+        return $this->query('EventLogger');
1650
+    }
1651
+
1652
+    /**
1653
+     * Get the active query logger
1654
+     *
1655
+     * The returned logger only logs data when debug mode is enabled
1656
+     *
1657
+     * @return \OCP\Diagnostics\IQueryLogger
1658
+     */
1659
+    public function getQueryLogger() {
1660
+        return $this->query('QueryLogger');
1661
+    }
1662
+
1663
+    /**
1664
+     * Get the manager for temporary files and folders
1665
+     *
1666
+     * @return \OCP\ITempManager
1667
+     */
1668
+    public function getTempManager() {
1669
+        return $this->query('TempManager');
1670
+    }
1671
+
1672
+    /**
1673
+     * Get the app manager
1674
+     *
1675
+     * @return \OCP\App\IAppManager
1676
+     */
1677
+    public function getAppManager() {
1678
+        return $this->query('AppManager');
1679
+    }
1680
+
1681
+    /**
1682
+     * Creates a new mailer
1683
+     *
1684
+     * @return \OCP\Mail\IMailer
1685
+     */
1686
+    public function getMailer() {
1687
+        return $this->query('Mailer');
1688
+    }
1689
+
1690
+    /**
1691
+     * Get the webroot
1692
+     *
1693
+     * @return string
1694
+     */
1695
+    public function getWebRoot() {
1696
+        return $this->webRoot;
1697
+    }
1698
+
1699
+    /**
1700
+     * @return \OC\OCSClient
1701
+     */
1702
+    public function getOcsClient() {
1703
+        return $this->query('OcsClient');
1704
+    }
1705
+
1706
+    /**
1707
+     * @return \OCP\IDateTimeZone
1708
+     */
1709
+    public function getDateTimeZone() {
1710
+        return $this->query('DateTimeZone');
1711
+    }
1712
+
1713
+    /**
1714
+     * @return \OCP\IDateTimeFormatter
1715
+     */
1716
+    public function getDateTimeFormatter() {
1717
+        return $this->query('DateTimeFormatter');
1718
+    }
1719
+
1720
+    /**
1721
+     * @return \OCP\Files\Config\IMountProviderCollection
1722
+     */
1723
+    public function getMountProviderCollection() {
1724
+        return $this->query('MountConfigManager');
1725
+    }
1726
+
1727
+    /**
1728
+     * Get the IniWrapper
1729
+     *
1730
+     * @return IniGetWrapper
1731
+     */
1732
+    public function getIniWrapper() {
1733
+        return $this->query('IniWrapper');
1734
+    }
1735
+
1736
+    /**
1737
+     * @return \OCP\Command\IBus
1738
+     */
1739
+    public function getCommandBus() {
1740
+        return $this->query('AsyncCommandBus');
1741
+    }
1742
+
1743
+    /**
1744
+     * Get the trusted domain helper
1745
+     *
1746
+     * @return TrustedDomainHelper
1747
+     */
1748
+    public function getTrustedDomainHelper() {
1749
+        return $this->query('TrustedDomainHelper');
1750
+    }
1751
+
1752
+    /**
1753
+     * Get the locking provider
1754
+     *
1755
+     * @return \OCP\Lock\ILockingProvider
1756
+     * @since 8.1.0
1757
+     */
1758
+    public function getLockingProvider() {
1759
+        return $this->query('LockingProvider');
1760
+    }
1761
+
1762
+    /**
1763
+     * @return \OCP\Files\Mount\IMountManager
1764
+     **/
1765
+    function getMountManager() {
1766
+        return $this->query('MountManager');
1767
+    }
1768
+
1769
+    /** @return \OCP\Files\Config\IUserMountCache */
1770
+    function getUserMountCache() {
1771
+        return $this->query('UserMountCache');
1772
+    }
1773
+
1774
+    /**
1775
+     * Get the MimeTypeDetector
1776
+     *
1777
+     * @return \OCP\Files\IMimeTypeDetector
1778
+     */
1779
+    public function getMimeTypeDetector() {
1780
+        return $this->query('MimeTypeDetector');
1781
+    }
1782
+
1783
+    /**
1784
+     * Get the MimeTypeLoader
1785
+     *
1786
+     * @return \OCP\Files\IMimeTypeLoader
1787
+     */
1788
+    public function getMimeTypeLoader() {
1789
+        return $this->query('MimeTypeLoader');
1790
+    }
1791
+
1792
+    /**
1793
+     * Get the manager of all the capabilities
1794
+     *
1795
+     * @return \OC\CapabilitiesManager
1796
+     */
1797
+    public function getCapabilitiesManager() {
1798
+        return $this->query('CapabilitiesManager');
1799
+    }
1800
+
1801
+    /**
1802
+     * Get the EventDispatcher
1803
+     *
1804
+     * @return EventDispatcherInterface
1805
+     * @since 8.2.0
1806
+     */
1807
+    public function getEventDispatcher() {
1808
+        return $this->query('EventDispatcher');
1809
+    }
1810
+
1811
+    /**
1812
+     * Get the Notification Manager
1813
+     *
1814
+     * @return \OCP\Notification\IManager
1815
+     * @since 8.2.0
1816
+     */
1817
+    public function getNotificationManager() {
1818
+        return $this->query('NotificationManager');
1819
+    }
1820
+
1821
+    /**
1822
+     * @return \OCP\Comments\ICommentsManager
1823
+     */
1824
+    public function getCommentsManager() {
1825
+        return $this->query('CommentsManager');
1826
+    }
1827
+
1828
+    /**
1829
+     * @return \OCA\Theming\ThemingDefaults
1830
+     */
1831
+    public function getThemingDefaults() {
1832
+        return $this->query('ThemingDefaults');
1833
+    }
1834
+
1835
+    /**
1836
+     * @return \OC\IntegrityCheck\Checker
1837
+     */
1838
+    public function getIntegrityCodeChecker() {
1839
+        return $this->query('IntegrityCodeChecker');
1840
+    }
1841
+
1842
+    /**
1843
+     * @return \OC\Session\CryptoWrapper
1844
+     */
1845
+    public function getSessionCryptoWrapper() {
1846
+        return $this->query('CryptoWrapper');
1847
+    }
1848
+
1849
+    /**
1850
+     * @return CsrfTokenManager
1851
+     */
1852
+    public function getCsrfTokenManager() {
1853
+        return $this->query('CsrfTokenManager');
1854
+    }
1855
+
1856
+    /**
1857
+     * @return Throttler
1858
+     */
1859
+    public function getBruteForceThrottler() {
1860
+        return $this->query('Throttler');
1861
+    }
1862
+
1863
+    /**
1864
+     * @return IContentSecurityPolicyManager
1865
+     */
1866
+    public function getContentSecurityPolicyManager() {
1867
+        return $this->query('ContentSecurityPolicyManager');
1868
+    }
1869
+
1870
+    /**
1871
+     * @return ContentSecurityPolicyNonceManager
1872
+     */
1873
+    public function getContentSecurityPolicyNonceManager() {
1874
+        return $this->query('ContentSecurityPolicyNonceManager');
1875
+    }
1876
+
1877
+    /**
1878
+     * Not a public API as of 8.2, wait for 9.0
1879
+     *
1880
+     * @return \OCA\Files_External\Service\BackendService
1881
+     */
1882
+    public function getStoragesBackendService() {
1883
+        return $this->query('OCA\\Files_External\\Service\\BackendService');
1884
+    }
1885
+
1886
+    /**
1887
+     * Not a public API as of 8.2, wait for 9.0
1888
+     *
1889
+     * @return \OCA\Files_External\Service\GlobalStoragesService
1890
+     */
1891
+    public function getGlobalStoragesService() {
1892
+        return $this->query('OCA\\Files_External\\Service\\GlobalStoragesService');
1893
+    }
1894
+
1895
+    /**
1896
+     * Not a public API as of 8.2, wait for 9.0
1897
+     *
1898
+     * @return \OCA\Files_External\Service\UserGlobalStoragesService
1899
+     */
1900
+    public function getUserGlobalStoragesService() {
1901
+        return $this->query('OCA\\Files_External\\Service\\UserGlobalStoragesService');
1902
+    }
1903
+
1904
+    /**
1905
+     * Not a public API as of 8.2, wait for 9.0
1906
+     *
1907
+     * @return \OCA\Files_External\Service\UserStoragesService
1908
+     */
1909
+    public function getUserStoragesService() {
1910
+        return $this->query('OCA\\Files_External\\Service\\UserStoragesService');
1911
+    }
1912
+
1913
+    /**
1914
+     * @return \OCP\Share\IManager
1915
+     */
1916
+    public function getShareManager() {
1917
+        return $this->query('ShareManager');
1918
+    }
1919
+
1920
+    /**
1921
+     * @return \OCP\Collaboration\Collaborators\ISearch
1922
+     */
1923
+    public function getCollaboratorSearch() {
1924
+        return $this->query('CollaboratorSearch');
1925
+    }
1926
+
1927
+    /**
1928
+     * @return \OCP\Collaboration\AutoComplete\IManager
1929
+     */
1930
+    public function getAutoCompleteManager(){
1931
+        return $this->query(IManager::class);
1932
+    }
1933
+
1934
+    /**
1935
+     * Returns the LDAP Provider
1936
+     *
1937
+     * @return \OCP\LDAP\ILDAPProvider
1938
+     */
1939
+    public function getLDAPProvider() {
1940
+        return $this->query('LDAPProvider');
1941
+    }
1942
+
1943
+    /**
1944
+     * @return \OCP\Settings\IManager
1945
+     */
1946
+    public function getSettingsManager() {
1947
+        return $this->query('SettingsManager');
1948
+    }
1949
+
1950
+    /**
1951
+     * @return \OCP\Files\IAppData
1952
+     */
1953
+    public function getAppDataDir($app) {
1954
+        /** @var \OC\Files\AppData\Factory $factory */
1955
+        $factory = $this->query(\OC\Files\AppData\Factory::class);
1956
+        return $factory->get($app);
1957
+    }
1958
+
1959
+    /**
1960
+     * @return \OCP\Lockdown\ILockdownManager
1961
+     */
1962
+    public function getLockdownManager() {
1963
+        return $this->query('LockdownManager');
1964
+    }
1965
+
1966
+    /**
1967
+     * @return \OCP\Federation\ICloudIdManager
1968
+     */
1969
+    public function getCloudIdManager() {
1970
+        return $this->query(ICloudIdManager::class);
1971
+    }
1972
+
1973
+    /**
1974
+     * @return \OCP\Remote\Api\IApiFactory
1975
+     */
1976
+    public function getRemoteApiFactory() {
1977
+        return $this->query(IApiFactory::class);
1978
+    }
1979
+
1980
+    /**
1981
+     * @return \OCP\Remote\IInstanceFactory
1982
+     */
1983
+    public function getRemoteInstanceFactory() {
1984
+        return $this->query(IInstanceFactory::class);
1985
+    }
1986 1986
 }
Please login to merge, or discard this patch.
lib/private/NaturalSort.php 1 patch
Indentation   +102 added lines, -102 removed lines patch added patch discarded remove patch
@@ -30,113 +30,113 @@
 block discarded – undo
30 30
 use OCP\ILogger;
31 31
 
32 32
 class NaturalSort {
33
-	private static $instance;
34
-	private $collator;
35
-	private $cache = array();
33
+    private static $instance;
34
+    private $collator;
35
+    private $cache = array();
36 36
 
37
-	/**
38
-	 * Instantiate a new \OC\NaturalSort instance.
39
-	 * @param object $injectedCollator
40
-	 */
41
-	public function __construct($injectedCollator = null) {
42
-		// inject an instance of \Collator('en_US') to force using the php5-intl Collator
43
-		// or inject an instance of \OC\NaturalSort_DefaultCollator to force using Owncloud's default collator
44
-		if (isset($injectedCollator)) {
45
-			$this->collator = $injectedCollator;
46
-			\OCP\Util::writeLog('core', 'forced use of '.get_class($injectedCollator), ILogger::DEBUG);
47
-		}
48
-	}
37
+    /**
38
+     * Instantiate a new \OC\NaturalSort instance.
39
+     * @param object $injectedCollator
40
+     */
41
+    public function __construct($injectedCollator = null) {
42
+        // inject an instance of \Collator('en_US') to force using the php5-intl Collator
43
+        // or inject an instance of \OC\NaturalSort_DefaultCollator to force using Owncloud's default collator
44
+        if (isset($injectedCollator)) {
45
+            $this->collator = $injectedCollator;
46
+            \OCP\Util::writeLog('core', 'forced use of '.get_class($injectedCollator), ILogger::DEBUG);
47
+        }
48
+    }
49 49
 
50
-	/**
51
-	 * Split the given string in chunks of numbers and strings
52
-	 * @param string $t string
53
-	 * @return array of strings and number chunks
54
-	 */
55
-	private function naturalSortChunkify($t) {
56
-		// Adapted and ported to PHP from
57
-		// http://my.opera.com/GreyWyvern/blog/show.dml/1671288
58
-		if (isset($this->cache[$t])) {
59
-			return $this->cache[$t];
60
-		}
61
-		$tz = array();
62
-		$x = 0;
63
-		$y = -1;
64
-		$n = null;
50
+    /**
51
+     * Split the given string in chunks of numbers and strings
52
+     * @param string $t string
53
+     * @return array of strings and number chunks
54
+     */
55
+    private function naturalSortChunkify($t) {
56
+        // Adapted and ported to PHP from
57
+        // http://my.opera.com/GreyWyvern/blog/show.dml/1671288
58
+        if (isset($this->cache[$t])) {
59
+            return $this->cache[$t];
60
+        }
61
+        $tz = array();
62
+        $x = 0;
63
+        $y = -1;
64
+        $n = null;
65 65
 
66
-		while (isset($t[$x])) {
67
-			$c = $t[$x];
68
-			// only include the dot in strings
69
-			$m = ((!$n && $c === '.') || ($c >= '0' && $c <= '9'));
70
-			if ($m !== $n) {
71
-				// next chunk
72
-				$y++;
73
-				$tz[$y] = '';
74
-				$n = $m;
75
-			}
76
-			$tz[$y] .= $c;
77
-			$x++;
78
-		}
79
-		$this->cache[$t] = $tz;
80
-		return $tz;
81
-	}
66
+        while (isset($t[$x])) {
67
+            $c = $t[$x];
68
+            // only include the dot in strings
69
+            $m = ((!$n && $c === '.') || ($c >= '0' && $c <= '9'));
70
+            if ($m !== $n) {
71
+                // next chunk
72
+                $y++;
73
+                $tz[$y] = '';
74
+                $n = $m;
75
+            }
76
+            $tz[$y] .= $c;
77
+            $x++;
78
+        }
79
+        $this->cache[$t] = $tz;
80
+        return $tz;
81
+    }
82 82
 
83
-	/**
84
-	 * Returns the string collator
85
-	 * @return \Collator string collator
86
-	 */
87
-	private function getCollator() {
88
-		if (!isset($this->collator)) {
89
-			// looks like the default is en_US_POSIX which yields wrong sorting with
90
-			// German umlauts, so using en_US instead
91
-			if (class_exists('Collator')) {
92
-				$this->collator = new \Collator('en_US');
93
-			}
94
-			else {
95
-				$this->collator = new \OC\NaturalSort_DefaultCollator();
96
-			}
97
-		}
98
-		return $this->collator;
99
-	}
83
+    /**
84
+     * Returns the string collator
85
+     * @return \Collator string collator
86
+     */
87
+    private function getCollator() {
88
+        if (!isset($this->collator)) {
89
+            // looks like the default is en_US_POSIX which yields wrong sorting with
90
+            // German umlauts, so using en_US instead
91
+            if (class_exists('Collator')) {
92
+                $this->collator = new \Collator('en_US');
93
+            }
94
+            else {
95
+                $this->collator = new \OC\NaturalSort_DefaultCollator();
96
+            }
97
+        }
98
+        return $this->collator;
99
+    }
100 100
 
101
-	/**
102
-	 * Compare two strings to provide a natural sort
103
-	 * @param string $a first string to compare
104
-	 * @param string $b second string to compare
105
-	 * @return int -1 if $b comes before $a, 1 if $a comes before $b
106
-	 * or 0 if the strings are identical
107
-	 */
108
-	public function compare($a, $b) {
109
-		// Needed because PHP doesn't sort correctly when numbers are enclosed in
110
-		// parenthesis, even with NUMERIC_COLLATION enabled.
111
-		// For example it gave ["test (2).txt", "test.txt"]
112
-		// instead of ["test.txt", "test (2).txt"]
113
-		$aa = self::naturalSortChunkify($a);
114
-		$bb = self::naturalSortChunkify($b);
101
+    /**
102
+     * Compare two strings to provide a natural sort
103
+     * @param string $a first string to compare
104
+     * @param string $b second string to compare
105
+     * @return int -1 if $b comes before $a, 1 if $a comes before $b
106
+     * or 0 if the strings are identical
107
+     */
108
+    public function compare($a, $b) {
109
+        // Needed because PHP doesn't sort correctly when numbers are enclosed in
110
+        // parenthesis, even with NUMERIC_COLLATION enabled.
111
+        // For example it gave ["test (2).txt", "test.txt"]
112
+        // instead of ["test.txt", "test (2).txt"]
113
+        $aa = self::naturalSortChunkify($a);
114
+        $bb = self::naturalSortChunkify($b);
115 115
 
116
-		for ($x = 0; isset($aa[$x]) && isset($bb[$x]); $x++) {
117
-			$aChunk = $aa[$x];
118
-			$bChunk = $bb[$x];
119
-			if ($aChunk !== $bChunk) {
120
-				// test first character (character comparison, not number comparison)
121
-				if ($aChunk[0] >= '0' && $aChunk[0] <= '9' && $bChunk[0] >= '0' && $bChunk[0] <= '9') {
122
-					$aNum = (int)$aChunk;
123
-					$bNum = (int)$bChunk;
124
-					return $aNum - $bNum;
125
-				}
126
-				return self::getCollator()->compare($aChunk, $bChunk);
127
-			}
128
-		}
129
-		return count($aa) - count($bb);
130
-	}
116
+        for ($x = 0; isset($aa[$x]) && isset($bb[$x]); $x++) {
117
+            $aChunk = $aa[$x];
118
+            $bChunk = $bb[$x];
119
+            if ($aChunk !== $bChunk) {
120
+                // test first character (character comparison, not number comparison)
121
+                if ($aChunk[0] >= '0' && $aChunk[0] <= '9' && $bChunk[0] >= '0' && $bChunk[0] <= '9') {
122
+                    $aNum = (int)$aChunk;
123
+                    $bNum = (int)$bChunk;
124
+                    return $aNum - $bNum;
125
+                }
126
+                return self::getCollator()->compare($aChunk, $bChunk);
127
+            }
128
+        }
129
+        return count($aa) - count($bb);
130
+    }
131 131
 
132
-	/**
133
-	 * Returns a singleton
134
-	 * @return \OC\NaturalSort instance
135
-	 */
136
-	public static function getInstance() {
137
-		if (!isset(self::$instance)) {
138
-			self::$instance = new \OC\NaturalSort();
139
-		}
140
-		return self::$instance;
141
-	}
132
+    /**
133
+     * Returns a singleton
134
+     * @return \OC\NaturalSort instance
135
+     */
136
+    public static function getInstance() {
137
+        if (!isset(self::$instance)) {
138
+            self::$instance = new \OC\NaturalSort();
139
+        }
140
+        return self::$instance;
141
+    }
142 142
 }
Please login to merge, or discard this patch.
lib/private/Updater.php 1 patch
Indentation   +550 added lines, -550 removed lines patch added patch discarded remove patch
@@ -54,556 +54,556 @@
 block discarded – undo
54 54
  */
55 55
 class Updater extends BasicEmitter {
56 56
 
57
-	/** @var ILogger $log */
58
-	private $log;
59
-
60
-	/** @var IConfig */
61
-	private $config;
62
-
63
-	/** @var Checker */
64
-	private $checker;
65
-
66
-	/** @var Installer */
67
-	private $installer;
68
-
69
-	private $logLevelNames = [
70
-		0 => 'Debug',
71
-		1 => 'Info',
72
-		2 => 'Warning',
73
-		3 => 'Error',
74
-		4 => 'Fatal',
75
-	];
76
-
77
-	/**
78
-	 * @param IConfig $config
79
-	 * @param Checker $checker
80
-	 * @param ILogger $log
81
-	 * @param Installer $installer
82
-	 */
83
-	public function __construct(IConfig $config,
84
-								Checker $checker,
85
-								ILogger $log = null,
86
-								Installer $installer) {
87
-		$this->log = $log;
88
-		$this->config = $config;
89
-		$this->checker = $checker;
90
-		$this->installer = $installer;
91
-	}
92
-
93
-	/**
94
-	 * runs the update actions in maintenance mode, does not upgrade the source files
95
-	 * except the main .htaccess file
96
-	 *
97
-	 * @return bool true if the operation succeeded, false otherwise
98
-	 */
99
-	public function upgrade() {
100
-		$this->emitRepairEvents();
101
-		$this->logAllEvents();
102
-
103
-		$logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
104
-		$this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
105
-		$this->config->setSystemValue('loglevel', ILogger::DEBUG);
106
-
107
-		$wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
108
-
109
-		if(!$wasMaintenanceModeEnabled) {
110
-			$this->config->setSystemValue('maintenance', true);
111
-			$this->emit('\OC\Updater', 'maintenanceEnabled');
112
-		}
113
-
114
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
115
-		$currentVersion = implode('.', \OCP\Util::getVersion());
116
-		$this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
117
-
118
-		$success = true;
119
-		try {
120
-			$this->doUpgrade($currentVersion, $installedVersion);
121
-		} catch (HintException $exception) {
122
-			$this->log->logException($exception, ['app' => 'core']);
123
-			$this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
124
-			$success = false;
125
-		} catch (\Exception $exception) {
126
-			$this->log->logException($exception, ['app' => 'core']);
127
-			$this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
128
-			$success = false;
129
-		}
130
-
131
-		$this->emit('\OC\Updater', 'updateEnd', array($success));
132
-
133
-		if(!$wasMaintenanceModeEnabled && $success) {
134
-			$this->config->setSystemValue('maintenance', false);
135
-			$this->emit('\OC\Updater', 'maintenanceDisabled');
136
-		} else {
137
-			$this->emit('\OC\Updater', 'maintenanceActive');
138
-		}
139
-
140
-		$this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
141
-		$this->config->setSystemValue('loglevel', $logLevel);
142
-		$this->config->setSystemValue('installed', true);
143
-
144
-		return $success;
145
-	}
146
-
147
-	/**
148
-	 * Return version from which this version is allowed to upgrade from
149
-	 *
150
-	 * @return array allowed previous versions per vendor
151
-	 */
152
-	private function getAllowedPreviousVersions() {
153
-		// this should really be a JSON file
154
-		require \OC::$SERVERROOT . '/version.php';
155
-		/** @var array $OC_VersionCanBeUpgradedFrom */
156
-		return $OC_VersionCanBeUpgradedFrom;
157
-	}
158
-
159
-	/**
160
-	 * Return vendor from which this version was published
161
-	 *
162
-	 * @return string Get the vendor
163
-	 */
164
-	private function getVendor() {
165
-		// this should really be a JSON file
166
-		require \OC::$SERVERROOT . '/version.php';
167
-		/** @var string $vendor */
168
-		return (string) $vendor;
169
-	}
170
-
171
-	/**
172
-	 * Whether an upgrade to a specified version is possible
173
-	 * @param string $oldVersion
174
-	 * @param string $newVersion
175
-	 * @param array $allowedPreviousVersions
176
-	 * @return bool
177
-	 */
178
-	public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
179
-		$version = explode('.', $oldVersion);
180
-		$majorMinor = $version[0] . '.' . $version[1];
181
-
182
-		$currentVendor = $this->config->getAppValue('core', 'vendor', '');
183
-
184
-		// Vendor was not set correctly on install, so we have to white-list known versions
185
-		if ($currentVendor === '' && isset($allowedPreviousVersions['owncloud'][$oldVersion])) {
186
-			$currentVendor = 'owncloud';
187
-		}
188
-
189
-		if ($currentVendor === 'nextcloud') {
190
-			return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
191
-				&& (version_compare($oldVersion, $newVersion, '<=') ||
192
-					$this->config->getSystemValue('debug', false));
193
-		}
194
-
195
-		// Check if the instance can be migrated
196
-		return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
197
-			isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
198
-	}
199
-
200
-	/**
201
-	 * runs the update actions in maintenance mode, does not upgrade the source files
202
-	 * except the main .htaccess file
203
-	 *
204
-	 * @param string $currentVersion current version to upgrade to
205
-	 * @param string $installedVersion previous version from which to upgrade from
206
-	 *
207
-	 * @throws \Exception
208
-	 */
209
-	private function doUpgrade($currentVersion, $installedVersion) {
210
-		// Stop update if the update is over several major versions
211
-		$allowedPreviousVersions = $this->getAllowedPreviousVersions();
212
-		if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
213
-			throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
214
-		}
215
-
216
-		// Update .htaccess files
217
-		try {
218
-			Setup::updateHtaccess();
219
-			Setup::protectDataDirectory();
220
-		} catch (\Exception $e) {
221
-			throw new \Exception($e->getMessage());
222
-		}
223
-
224
-		// create empty file in data dir, so we can later find
225
-		// out that this is indeed an ownCloud data directory
226
-		// (in case it didn't exist before)
227
-		file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
228
-
229
-		// pre-upgrade repairs
230
-		$repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
231
-		$repair->run();
232
-
233
-		$this->doCoreUpgrade();
234
-
235
-		try {
236
-			// TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
237
-			Setup::installBackgroundJobs();
238
-		} catch (\Exception $e) {
239
-			throw new \Exception($e->getMessage());
240
-		}
241
-
242
-		// update all shipped apps
243
-		$this->checkAppsRequirements();
244
-		$this->doAppUpgrade();
245
-
246
-		// Update the appfetchers version so it downloads the correct list from the appstore
247
-		\OC::$server->getAppFetcher()->setVersion($currentVersion);
248
-
249
-		// upgrade appstore apps
250
-		$this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
251
-
252
-		// install new shipped apps on upgrade
253
-		OC_App::loadApps(['authentication']);
254
-		$errors = Installer::installShippedApps(true);
255
-		foreach ($errors as $appId => $exception) {
256
-			/** @var \Exception $exception */
257
-			$this->log->logException($exception, ['app' => $appId]);
258
-			$this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
259
-		}
260
-
261
-		// post-upgrade repairs
262
-		$repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
263
-		$repair->run();
264
-
265
-		//Invalidate update feed
266
-		$this->config->setAppValue('core', 'lastupdatedat', 0);
267
-
268
-		// Check for code integrity if not disabled
269
-		if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
270
-			$this->emit('\OC\Updater', 'startCheckCodeIntegrity');
271
-			$this->checker->runInstanceVerification();
272
-			$this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
273
-		}
274
-
275
-		// only set the final version if everything went well
276
-		$this->config->setSystemValue('version', implode('.', Util::getVersion()));
277
-		$this->config->setAppValue('core', 'vendor', $this->getVendor());
278
-	}
279
-
280
-	protected function doCoreUpgrade() {
281
-		$this->emit('\OC\Updater', 'dbUpgradeBefore');
282
-
283
-		// execute core migrations
284
-		$ms = new MigrationService('core', \OC::$server->getDatabaseConnection());
285
-		$ms->migrate();
286
-
287
-		$this->emit('\OC\Updater', 'dbUpgrade');
288
-	}
289
-
290
-	/**
291
-	 * @param string $version the oc version to check app compatibility with
292
-	 */
293
-	protected function checkAppUpgrade($version) {
294
-		$apps = \OC_App::getEnabledApps();
295
-		$this->emit('\OC\Updater', 'appUpgradeCheckBefore');
296
-
297
-		$appManager = \OC::$server->getAppManager();
298
-		foreach ($apps as $appId) {
299
-			$info = \OC_App::getAppInfo($appId);
300
-			$compatible = \OC_App::isAppCompatible($version, $info);
301
-			$isShipped = $appManager->isShipped($appId);
302
-
303
-			if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
304
-				/**
305
-				 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
306
-				 * are not possible anymore within it. - Consider this when touching the code.
307
-				 * @link https://github.com/owncloud/core/issues/10980
308
-				 * @see \OC_App::updateApp
309
-				 */
310
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
311
-					$this->includePreUpdate($appId);
312
-				}
313
-				if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
314
-					$this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
315
-					\OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
316
-				}
317
-			}
318
-		}
319
-
320
-		$this->emit('\OC\Updater', 'appUpgradeCheck');
321
-	}
322
-
323
-	/**
324
-	 * Includes the pre-update file. Done here to prevent namespace mixups.
325
-	 * @param string $appId
326
-	 */
327
-	private function includePreUpdate($appId) {
328
-		include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
329
-	}
330
-
331
-	/**
332
-	 * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
333
-	 * (types authentication, filesystem, logging, in that order) afterwards.
334
-	 *
335
-	 * @throws NeedsUpdateException
336
-	 */
337
-	protected function doAppUpgrade() {
338
-		$apps = \OC_App::getEnabledApps();
339
-		$priorityTypes = array('authentication', 'filesystem', 'logging');
340
-		$pseudoOtherType = 'other';
341
-		$stacks = array($pseudoOtherType => array());
342
-
343
-		foreach ($apps as $appId) {
344
-			$priorityType = false;
345
-			foreach ($priorityTypes as $type) {
346
-				if(!isset($stacks[$type])) {
347
-					$stacks[$type] = array();
348
-				}
349
-				if (\OC_App::isType($appId, [$type])) {
350
-					$stacks[$type][] = $appId;
351
-					$priorityType = true;
352
-					break;
353
-				}
354
-			}
355
-			if (!$priorityType) {
356
-				$stacks[$pseudoOtherType][] = $appId;
357
-			}
358
-		}
359
-		foreach ($stacks as $type => $stack) {
360
-			foreach ($stack as $appId) {
361
-				if (\OC_App::shouldUpgrade($appId)) {
362
-					$this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
363
-					\OC_App::updateApp($appId);
364
-					$this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
365
-				}
366
-				if($type !== $pseudoOtherType) {
367
-					// load authentication, filesystem and logging apps after
368
-					// upgrading them. Other apps my need to rely on modifying
369
-					// user and/or filesystem aspects.
370
-					\OC_App::loadApp($appId);
371
-				}
372
-			}
373
-		}
374
-	}
375
-
376
-	/**
377
-	 * check if the current enabled apps are compatible with the current
378
-	 * ownCloud version. disable them if not.
379
-	 * This is important if you upgrade ownCloud and have non ported 3rd
380
-	 * party apps installed.
381
-	 *
382
-	 * @return array
383
-	 * @throws \Exception
384
-	 */
385
-	private function checkAppsRequirements() {
386
-		$isCoreUpgrade = $this->isCodeUpgrade();
387
-		$apps = OC_App::getEnabledApps();
388
-		$version = implode('.', Util::getVersion());
389
-		$disabledApps = [];
390
-		$appManager = \OC::$server->getAppManager();
391
-		foreach ($apps as $app) {
392
-			// check if the app is compatible with this version of ownCloud
393
-			$info = OC_App::getAppInfo($app);
394
-			if($info === null || !OC_App::isAppCompatible($version, $info)) {
395
-				if ($appManager->isShipped($app)) {
396
-					throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
397
-				}
398
-				\OC::$server->getAppManager()->disableApp($app);
399
-				$this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
400
-			}
401
-			// no need to disable any app in case this is a non-core upgrade
402
-			if (!$isCoreUpgrade) {
403
-				continue;
404
-			}
405
-			// shipped apps will remain enabled
406
-			if ($appManager->isShipped($app)) {
407
-				continue;
408
-			}
409
-			// authentication and session apps will remain enabled as well
410
-			if (OC_App::isType($app, ['session', 'authentication'])) {
411
-				continue;
412
-			}
413
-		}
414
-		return $disabledApps;
415
-	}
416
-
417
-	/**
418
-	 * @return bool
419
-	 */
420
-	private function isCodeUpgrade() {
421
-		$installedVersion = $this->config->getSystemValue('version', '0.0.0');
422
-		$currentVersion = implode('.', Util::getVersion());
423
-		if (version_compare($currentVersion, $installedVersion, '>')) {
424
-			return true;
425
-		}
426
-		return false;
427
-	}
428
-
429
-	/**
430
-	 * @param array $disabledApps
431
-	 * @throws \Exception
432
-	 */
433
-	private function upgradeAppStoreApps(array $disabledApps) {
434
-		foreach($disabledApps as $app) {
435
-			try {
436
-				$this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
437
-				if ($this->installer->isUpdateAvailable($app)) {
438
-					$this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
439
-					$this->installer->updateAppstoreApp($app);
440
-				}
441
-				$this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
442
-			} catch (\Exception $ex) {
443
-				$this->log->logException($ex, ['app' => 'core']);
444
-			}
445
-		}
446
-	}
447
-
448
-	/**
449
-	 * Forward messages emitted by the repair routine
450
-	 */
451
-	private function emitRepairEvents() {
452
-		$dispatcher = \OC::$server->getEventDispatcher();
453
-		$dispatcher->addListener('\OC\Repair::warning', function ($event) {
454
-			if ($event instanceof GenericEvent) {
455
-				$this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
456
-			}
457
-		});
458
-		$dispatcher->addListener('\OC\Repair::error', function ($event) {
459
-			if ($event instanceof GenericEvent) {
460
-				$this->emit('\OC\Updater', 'repairError', $event->getArguments());
461
-			}
462
-		});
463
-		$dispatcher->addListener('\OC\Repair::info', function ($event) {
464
-			if ($event instanceof GenericEvent) {
465
-				$this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
466
-			}
467
-		});
468
-		$dispatcher->addListener('\OC\Repair::step', function ($event) {
469
-			if ($event instanceof GenericEvent) {
470
-				$this->emit('\OC\Updater', 'repairStep', $event->getArguments());
471
-			}
472
-		});
473
-	}
474
-
475
-	private function logAllEvents() {
476
-		$log = $this->log;
477
-
478
-		$dispatcher = \OC::$server->getEventDispatcher();
479
-		$dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
480
-			if (!$event instanceof GenericEvent) {
481
-				return;
482
-			}
483
-			$log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
484
-		});
485
-		$dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
486
-			if (!$event instanceof GenericEvent) {
487
-				return;
488
-			}
489
-			$log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
490
-		});
491
-
492
-		$repairListener = function($event) use ($log) {
493
-			if (!$event instanceof GenericEvent) {
494
-				return;
495
-			}
496
-			switch ($event->getSubject()) {
497
-				case '\OC\Repair::startProgress':
498
-					$log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
499
-					break;
500
-				case '\OC\Repair::advance':
501
-					$desc = $event->getArgument(1);
502
-					if (empty($desc)) {
503
-						$desc = '';
504
-					}
505
-					$log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
506
-
507
-					break;
508
-				case '\OC\Repair::finishProgress':
509
-					$log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
510
-					break;
511
-				case '\OC\Repair::step':
512
-					$log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
513
-					break;
514
-				case '\OC\Repair::info':
515
-					$log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
516
-					break;
517
-				case '\OC\Repair::warning':
518
-					$log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
519
-					break;
520
-				case '\OC\Repair::error':
521
-					$log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
522
-					break;
523
-			}
524
-		};
525
-
526
-		$dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
527
-		$dispatcher->addListener('\OC\Repair::advance', $repairListener);
528
-		$dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
529
-		$dispatcher->addListener('\OC\Repair::step', $repairListener);
530
-		$dispatcher->addListener('\OC\Repair::info', $repairListener);
531
-		$dispatcher->addListener('\OC\Repair::warning', $repairListener);
532
-		$dispatcher->addListener('\OC\Repair::error', $repairListener);
533
-
534
-
535
-		$this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
536
-			$log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
537
-		});
538
-		$this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
539
-			$log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
540
-		});
541
-		$this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
542
-			$log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
543
-		});
544
-		$this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
545
-			if ($success) {
546
-				$log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
547
-			} else {
548
-				$log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
549
-			}
550
-		});
551
-		$this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
552
-			$log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
553
-		});
554
-		$this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
555
-			$log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
556
-		});
557
-		$this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
558
-			$log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
559
-		});
560
-		$this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
561
-			$log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
562
-		});
563
-		$this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
564
-			$log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
565
-		});
566
-		$this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($log) {
567
-			$log->info('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
568
-		});
569
-		$this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
570
-			$log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
571
-		});
572
-		$this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($log) {
573
-			$log->info('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
574
-		});
575
-		$this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
576
-			$log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
577
-		});
578
-		$this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
579
-			$log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
580
-		});
581
-		$this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
582
-			$log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
583
-		});
584
-		$this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
585
-			$log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
586
-		});
587
-		$this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
588
-			$log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
589
-		});
590
-		$this->listen('\OC\Updater', 'failure', function ($message) use($log) {
591
-			$log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
592
-		});
593
-		$this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
594
-			$log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
595
-		});
596
-		$this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
597
-			$log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
598
-		});
599
-		$this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
600
-			$log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
601
-		});
602
-		$this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
603
-			$log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
604
-		});
605
-
606
-	}
57
+    /** @var ILogger $log */
58
+    private $log;
59
+
60
+    /** @var IConfig */
61
+    private $config;
62
+
63
+    /** @var Checker */
64
+    private $checker;
65
+
66
+    /** @var Installer */
67
+    private $installer;
68
+
69
+    private $logLevelNames = [
70
+        0 => 'Debug',
71
+        1 => 'Info',
72
+        2 => 'Warning',
73
+        3 => 'Error',
74
+        4 => 'Fatal',
75
+    ];
76
+
77
+    /**
78
+     * @param IConfig $config
79
+     * @param Checker $checker
80
+     * @param ILogger $log
81
+     * @param Installer $installer
82
+     */
83
+    public function __construct(IConfig $config,
84
+                                Checker $checker,
85
+                                ILogger $log = null,
86
+                                Installer $installer) {
87
+        $this->log = $log;
88
+        $this->config = $config;
89
+        $this->checker = $checker;
90
+        $this->installer = $installer;
91
+    }
92
+
93
+    /**
94
+     * runs the update actions in maintenance mode, does not upgrade the source files
95
+     * except the main .htaccess file
96
+     *
97
+     * @return bool true if the operation succeeded, false otherwise
98
+     */
99
+    public function upgrade() {
100
+        $this->emitRepairEvents();
101
+        $this->logAllEvents();
102
+
103
+        $logLevel = $this->config->getSystemValue('loglevel', ILogger::WARN);
104
+        $this->emit('\OC\Updater', 'setDebugLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
105
+        $this->config->setSystemValue('loglevel', ILogger::DEBUG);
106
+
107
+        $wasMaintenanceModeEnabled = $this->config->getSystemValue('maintenance', false);
108
+
109
+        if(!$wasMaintenanceModeEnabled) {
110
+            $this->config->setSystemValue('maintenance', true);
111
+            $this->emit('\OC\Updater', 'maintenanceEnabled');
112
+        }
113
+
114
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
115
+        $currentVersion = implode('.', \OCP\Util::getVersion());
116
+        $this->log->debug('starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, array('app' => 'core'));
117
+
118
+        $success = true;
119
+        try {
120
+            $this->doUpgrade($currentVersion, $installedVersion);
121
+        } catch (HintException $exception) {
122
+            $this->log->logException($exception, ['app' => 'core']);
123
+            $this->emit('\OC\Updater', 'failure', array($exception->getMessage() . ': ' .$exception->getHint()));
124
+            $success = false;
125
+        } catch (\Exception $exception) {
126
+            $this->log->logException($exception, ['app' => 'core']);
127
+            $this->emit('\OC\Updater', 'failure', array(get_class($exception) . ': ' .$exception->getMessage()));
128
+            $success = false;
129
+        }
130
+
131
+        $this->emit('\OC\Updater', 'updateEnd', array($success));
132
+
133
+        if(!$wasMaintenanceModeEnabled && $success) {
134
+            $this->config->setSystemValue('maintenance', false);
135
+            $this->emit('\OC\Updater', 'maintenanceDisabled');
136
+        } else {
137
+            $this->emit('\OC\Updater', 'maintenanceActive');
138
+        }
139
+
140
+        $this->emit('\OC\Updater', 'resetLogLevel', [ $logLevel, $this->logLevelNames[$logLevel] ]);
141
+        $this->config->setSystemValue('loglevel', $logLevel);
142
+        $this->config->setSystemValue('installed', true);
143
+
144
+        return $success;
145
+    }
146
+
147
+    /**
148
+     * Return version from which this version is allowed to upgrade from
149
+     *
150
+     * @return array allowed previous versions per vendor
151
+     */
152
+    private function getAllowedPreviousVersions() {
153
+        // this should really be a JSON file
154
+        require \OC::$SERVERROOT . '/version.php';
155
+        /** @var array $OC_VersionCanBeUpgradedFrom */
156
+        return $OC_VersionCanBeUpgradedFrom;
157
+    }
158
+
159
+    /**
160
+     * Return vendor from which this version was published
161
+     *
162
+     * @return string Get the vendor
163
+     */
164
+    private function getVendor() {
165
+        // this should really be a JSON file
166
+        require \OC::$SERVERROOT . '/version.php';
167
+        /** @var string $vendor */
168
+        return (string) $vendor;
169
+    }
170
+
171
+    /**
172
+     * Whether an upgrade to a specified version is possible
173
+     * @param string $oldVersion
174
+     * @param string $newVersion
175
+     * @param array $allowedPreviousVersions
176
+     * @return bool
177
+     */
178
+    public function isUpgradePossible($oldVersion, $newVersion, array $allowedPreviousVersions) {
179
+        $version = explode('.', $oldVersion);
180
+        $majorMinor = $version[0] . '.' . $version[1];
181
+
182
+        $currentVendor = $this->config->getAppValue('core', 'vendor', '');
183
+
184
+        // Vendor was not set correctly on install, so we have to white-list known versions
185
+        if ($currentVendor === '' && isset($allowedPreviousVersions['owncloud'][$oldVersion])) {
186
+            $currentVendor = 'owncloud';
187
+        }
188
+
189
+        if ($currentVendor === 'nextcloud') {
190
+            return isset($allowedPreviousVersions[$currentVendor][$majorMinor])
191
+                && (version_compare($oldVersion, $newVersion, '<=') ||
192
+                    $this->config->getSystemValue('debug', false));
193
+        }
194
+
195
+        // Check if the instance can be migrated
196
+        return isset($allowedPreviousVersions[$currentVendor][$majorMinor]) ||
197
+            isset($allowedPreviousVersions[$currentVendor][$oldVersion]);
198
+    }
199
+
200
+    /**
201
+     * runs the update actions in maintenance mode, does not upgrade the source files
202
+     * except the main .htaccess file
203
+     *
204
+     * @param string $currentVersion current version to upgrade to
205
+     * @param string $installedVersion previous version from which to upgrade from
206
+     *
207
+     * @throws \Exception
208
+     */
209
+    private function doUpgrade($currentVersion, $installedVersion) {
210
+        // Stop update if the update is over several major versions
211
+        $allowedPreviousVersions = $this->getAllowedPreviousVersions();
212
+        if (!$this->isUpgradePossible($installedVersion, $currentVersion, $allowedPreviousVersions)) {
213
+            throw new \Exception('Updates between multiple major versions and downgrades are unsupported.');
214
+        }
215
+
216
+        // Update .htaccess files
217
+        try {
218
+            Setup::updateHtaccess();
219
+            Setup::protectDataDirectory();
220
+        } catch (\Exception $e) {
221
+            throw new \Exception($e->getMessage());
222
+        }
223
+
224
+        // create empty file in data dir, so we can later find
225
+        // out that this is indeed an ownCloud data directory
226
+        // (in case it didn't exist before)
227
+        file_put_contents($this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
228
+
229
+        // pre-upgrade repairs
230
+        $repair = new Repair(Repair::getBeforeUpgradeRepairSteps(), \OC::$server->getEventDispatcher());
231
+        $repair->run();
232
+
233
+        $this->doCoreUpgrade();
234
+
235
+        try {
236
+            // TODO: replace with the new repair step mechanism https://github.com/owncloud/core/pull/24378
237
+            Setup::installBackgroundJobs();
238
+        } catch (\Exception $e) {
239
+            throw new \Exception($e->getMessage());
240
+        }
241
+
242
+        // update all shipped apps
243
+        $this->checkAppsRequirements();
244
+        $this->doAppUpgrade();
245
+
246
+        // Update the appfetchers version so it downloads the correct list from the appstore
247
+        \OC::$server->getAppFetcher()->setVersion($currentVersion);
248
+
249
+        // upgrade appstore apps
250
+        $this->upgradeAppStoreApps(\OC::$server->getAppManager()->getInstalledApps());
251
+
252
+        // install new shipped apps on upgrade
253
+        OC_App::loadApps(['authentication']);
254
+        $errors = Installer::installShippedApps(true);
255
+        foreach ($errors as $appId => $exception) {
256
+            /** @var \Exception $exception */
257
+            $this->log->logException($exception, ['app' => $appId]);
258
+            $this->emit('\OC\Updater', 'failure', [$appId . ': ' . $exception->getMessage()]);
259
+        }
260
+
261
+        // post-upgrade repairs
262
+        $repair = new Repair(Repair::getRepairSteps(), \OC::$server->getEventDispatcher());
263
+        $repair->run();
264
+
265
+        //Invalidate update feed
266
+        $this->config->setAppValue('core', 'lastupdatedat', 0);
267
+
268
+        // Check for code integrity if not disabled
269
+        if(\OC::$server->getIntegrityCodeChecker()->isCodeCheckEnforced()) {
270
+            $this->emit('\OC\Updater', 'startCheckCodeIntegrity');
271
+            $this->checker->runInstanceVerification();
272
+            $this->emit('\OC\Updater', 'finishedCheckCodeIntegrity');
273
+        }
274
+
275
+        // only set the final version if everything went well
276
+        $this->config->setSystemValue('version', implode('.', Util::getVersion()));
277
+        $this->config->setAppValue('core', 'vendor', $this->getVendor());
278
+    }
279
+
280
+    protected function doCoreUpgrade() {
281
+        $this->emit('\OC\Updater', 'dbUpgradeBefore');
282
+
283
+        // execute core migrations
284
+        $ms = new MigrationService('core', \OC::$server->getDatabaseConnection());
285
+        $ms->migrate();
286
+
287
+        $this->emit('\OC\Updater', 'dbUpgrade');
288
+    }
289
+
290
+    /**
291
+     * @param string $version the oc version to check app compatibility with
292
+     */
293
+    protected function checkAppUpgrade($version) {
294
+        $apps = \OC_App::getEnabledApps();
295
+        $this->emit('\OC\Updater', 'appUpgradeCheckBefore');
296
+
297
+        $appManager = \OC::$server->getAppManager();
298
+        foreach ($apps as $appId) {
299
+            $info = \OC_App::getAppInfo($appId);
300
+            $compatible = \OC_App::isAppCompatible($version, $info);
301
+            $isShipped = $appManager->isShipped($appId);
302
+
303
+            if ($compatible && $isShipped && \OC_App::shouldUpgrade($appId)) {
304
+                /**
305
+                 * FIXME: The preupdate check is performed before the database migration, otherwise database changes
306
+                 * are not possible anymore within it. - Consider this when touching the code.
307
+                 * @link https://github.com/owncloud/core/issues/10980
308
+                 * @see \OC_App::updateApp
309
+                 */
310
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/preupdate.php')) {
311
+                    $this->includePreUpdate($appId);
312
+                }
313
+                if (file_exists(\OC_App::getAppPath($appId) . '/appinfo/database.xml')) {
314
+                    $this->emit('\OC\Updater', 'appSimulateUpdate', array($appId));
315
+                    \OC_DB::simulateUpdateDbFromStructure(\OC_App::getAppPath($appId) . '/appinfo/database.xml');
316
+                }
317
+            }
318
+        }
319
+
320
+        $this->emit('\OC\Updater', 'appUpgradeCheck');
321
+    }
322
+
323
+    /**
324
+     * Includes the pre-update file. Done here to prevent namespace mixups.
325
+     * @param string $appId
326
+     */
327
+    private function includePreUpdate($appId) {
328
+        include \OC_App::getAppPath($appId) . '/appinfo/preupdate.php';
329
+    }
330
+
331
+    /**
332
+     * upgrades all apps within a major ownCloud upgrade. Also loads "priority"
333
+     * (types authentication, filesystem, logging, in that order) afterwards.
334
+     *
335
+     * @throws NeedsUpdateException
336
+     */
337
+    protected function doAppUpgrade() {
338
+        $apps = \OC_App::getEnabledApps();
339
+        $priorityTypes = array('authentication', 'filesystem', 'logging');
340
+        $pseudoOtherType = 'other';
341
+        $stacks = array($pseudoOtherType => array());
342
+
343
+        foreach ($apps as $appId) {
344
+            $priorityType = false;
345
+            foreach ($priorityTypes as $type) {
346
+                if(!isset($stacks[$type])) {
347
+                    $stacks[$type] = array();
348
+                }
349
+                if (\OC_App::isType($appId, [$type])) {
350
+                    $stacks[$type][] = $appId;
351
+                    $priorityType = true;
352
+                    break;
353
+                }
354
+            }
355
+            if (!$priorityType) {
356
+                $stacks[$pseudoOtherType][] = $appId;
357
+            }
358
+        }
359
+        foreach ($stacks as $type => $stack) {
360
+            foreach ($stack as $appId) {
361
+                if (\OC_App::shouldUpgrade($appId)) {
362
+                    $this->emit('\OC\Updater', 'appUpgradeStarted', [$appId, \OC_App::getAppVersion($appId)]);
363
+                    \OC_App::updateApp($appId);
364
+                    $this->emit('\OC\Updater', 'appUpgrade', [$appId, \OC_App::getAppVersion($appId)]);
365
+                }
366
+                if($type !== $pseudoOtherType) {
367
+                    // load authentication, filesystem and logging apps after
368
+                    // upgrading them. Other apps my need to rely on modifying
369
+                    // user and/or filesystem aspects.
370
+                    \OC_App::loadApp($appId);
371
+                }
372
+            }
373
+        }
374
+    }
375
+
376
+    /**
377
+     * check if the current enabled apps are compatible with the current
378
+     * ownCloud version. disable them if not.
379
+     * This is important if you upgrade ownCloud and have non ported 3rd
380
+     * party apps installed.
381
+     *
382
+     * @return array
383
+     * @throws \Exception
384
+     */
385
+    private function checkAppsRequirements() {
386
+        $isCoreUpgrade = $this->isCodeUpgrade();
387
+        $apps = OC_App::getEnabledApps();
388
+        $version = implode('.', Util::getVersion());
389
+        $disabledApps = [];
390
+        $appManager = \OC::$server->getAppManager();
391
+        foreach ($apps as $app) {
392
+            // check if the app is compatible with this version of ownCloud
393
+            $info = OC_App::getAppInfo($app);
394
+            if($info === null || !OC_App::isAppCompatible($version, $info)) {
395
+                if ($appManager->isShipped($app)) {
396
+                    throw new \UnexpectedValueException('The files of the app "' . $app . '" were not correctly replaced before running the update');
397
+                }
398
+                \OC::$server->getAppManager()->disableApp($app);
399
+                $this->emit('\OC\Updater', 'incompatibleAppDisabled', array($app));
400
+            }
401
+            // no need to disable any app in case this is a non-core upgrade
402
+            if (!$isCoreUpgrade) {
403
+                continue;
404
+            }
405
+            // shipped apps will remain enabled
406
+            if ($appManager->isShipped($app)) {
407
+                continue;
408
+            }
409
+            // authentication and session apps will remain enabled as well
410
+            if (OC_App::isType($app, ['session', 'authentication'])) {
411
+                continue;
412
+            }
413
+        }
414
+        return $disabledApps;
415
+    }
416
+
417
+    /**
418
+     * @return bool
419
+     */
420
+    private function isCodeUpgrade() {
421
+        $installedVersion = $this->config->getSystemValue('version', '0.0.0');
422
+        $currentVersion = implode('.', Util::getVersion());
423
+        if (version_compare($currentVersion, $installedVersion, '>')) {
424
+            return true;
425
+        }
426
+        return false;
427
+    }
428
+
429
+    /**
430
+     * @param array $disabledApps
431
+     * @throws \Exception
432
+     */
433
+    private function upgradeAppStoreApps(array $disabledApps) {
434
+        foreach($disabledApps as $app) {
435
+            try {
436
+                $this->emit('\OC\Updater', 'checkAppStoreAppBefore', [$app]);
437
+                if ($this->installer->isUpdateAvailable($app)) {
438
+                    $this->emit('\OC\Updater', 'upgradeAppStoreApp', [$app]);
439
+                    $this->installer->updateAppstoreApp($app);
440
+                }
441
+                $this->emit('\OC\Updater', 'checkAppStoreApp', [$app]);
442
+            } catch (\Exception $ex) {
443
+                $this->log->logException($ex, ['app' => 'core']);
444
+            }
445
+        }
446
+    }
447
+
448
+    /**
449
+     * Forward messages emitted by the repair routine
450
+     */
451
+    private function emitRepairEvents() {
452
+        $dispatcher = \OC::$server->getEventDispatcher();
453
+        $dispatcher->addListener('\OC\Repair::warning', function ($event) {
454
+            if ($event instanceof GenericEvent) {
455
+                $this->emit('\OC\Updater', 'repairWarning', $event->getArguments());
456
+            }
457
+        });
458
+        $dispatcher->addListener('\OC\Repair::error', function ($event) {
459
+            if ($event instanceof GenericEvent) {
460
+                $this->emit('\OC\Updater', 'repairError', $event->getArguments());
461
+            }
462
+        });
463
+        $dispatcher->addListener('\OC\Repair::info', function ($event) {
464
+            if ($event instanceof GenericEvent) {
465
+                $this->emit('\OC\Updater', 'repairInfo', $event->getArguments());
466
+            }
467
+        });
468
+        $dispatcher->addListener('\OC\Repair::step', function ($event) {
469
+            if ($event instanceof GenericEvent) {
470
+                $this->emit('\OC\Updater', 'repairStep', $event->getArguments());
471
+            }
472
+        });
473
+    }
474
+
475
+    private function logAllEvents() {
476
+        $log = $this->log;
477
+
478
+        $dispatcher = \OC::$server->getEventDispatcher();
479
+        $dispatcher->addListener('\OC\DB\Migrator::executeSql', function($event) use ($log) {
480
+            if (!$event instanceof GenericEvent) {
481
+                return;
482
+            }
483
+            $log->info('\OC\DB\Migrator::executeSql: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
484
+        });
485
+        $dispatcher->addListener('\OC\DB\Migrator::checkTable', function($event) use ($log) {
486
+            if (!$event instanceof GenericEvent) {
487
+                return;
488
+            }
489
+            $log->info('\OC\DB\Migrator::checkTable: ' . $event->getSubject() . ' (' . $event->getArgument(0) . ' of ' . $event->getArgument(1) . ')', ['app' => 'updater']);
490
+        });
491
+
492
+        $repairListener = function($event) use ($log) {
493
+            if (!$event instanceof GenericEvent) {
494
+                return;
495
+            }
496
+            switch ($event->getSubject()) {
497
+                case '\OC\Repair::startProgress':
498
+                    $log->info('\OC\Repair::startProgress: Starting ... ' . $event->getArgument(1) .  ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
499
+                    break;
500
+                case '\OC\Repair::advance':
501
+                    $desc = $event->getArgument(1);
502
+                    if (empty($desc)) {
503
+                        $desc = '';
504
+                    }
505
+                    $log->info('\OC\Repair::advance: ' . $desc . ' (' . $event->getArgument(0) . ')', ['app' => 'updater']);
506
+
507
+                    break;
508
+                case '\OC\Repair::finishProgress':
509
+                    $log->info('\OC\Repair::finishProgress', ['app' => 'updater']);
510
+                    break;
511
+                case '\OC\Repair::step':
512
+                    $log->info('\OC\Repair::step: Repair step: ' . $event->getArgument(0), ['app' => 'updater']);
513
+                    break;
514
+                case '\OC\Repair::info':
515
+                    $log->info('\OC\Repair::info: Repair info: ' . $event->getArgument(0), ['app' => 'updater']);
516
+                    break;
517
+                case '\OC\Repair::warning':
518
+                    $log->warning('\OC\Repair::warning: Repair warning: ' . $event->getArgument(0), ['app' => 'updater']);
519
+                    break;
520
+                case '\OC\Repair::error':
521
+                    $log->error('\OC\Repair::error: Repair error: ' . $event->getArgument(0), ['app' => 'updater']);
522
+                    break;
523
+            }
524
+        };
525
+
526
+        $dispatcher->addListener('\OC\Repair::startProgress', $repairListener);
527
+        $dispatcher->addListener('\OC\Repair::advance', $repairListener);
528
+        $dispatcher->addListener('\OC\Repair::finishProgress', $repairListener);
529
+        $dispatcher->addListener('\OC\Repair::step', $repairListener);
530
+        $dispatcher->addListener('\OC\Repair::info', $repairListener);
531
+        $dispatcher->addListener('\OC\Repair::warning', $repairListener);
532
+        $dispatcher->addListener('\OC\Repair::error', $repairListener);
533
+
534
+
535
+        $this->listen('\OC\Updater', 'maintenanceEnabled', function () use($log) {
536
+            $log->info('\OC\Updater::maintenanceEnabled: Turned on maintenance mode', ['app' => 'updater']);
537
+        });
538
+        $this->listen('\OC\Updater', 'maintenanceDisabled', function () use($log) {
539
+            $log->info('\OC\Updater::maintenanceDisabled: Turned off maintenance mode', ['app' => 'updater']);
540
+        });
541
+        $this->listen('\OC\Updater', 'maintenanceActive', function () use($log) {
542
+            $log->info('\OC\Updater::maintenanceActive: Maintenance mode is kept active', ['app' => 'updater']);
543
+        });
544
+        $this->listen('\OC\Updater', 'updateEnd', function ($success) use($log) {
545
+            if ($success) {
546
+                $log->info('\OC\Updater::updateEnd: Update successful', ['app' => 'updater']);
547
+            } else {
548
+                $log->error('\OC\Updater::updateEnd: Update failed', ['app' => 'updater']);
549
+            }
550
+        });
551
+        $this->listen('\OC\Updater', 'dbUpgradeBefore', function () use($log) {
552
+            $log->info('\OC\Updater::dbUpgradeBefore: Updating database schema', ['app' => 'updater']);
553
+        });
554
+        $this->listen('\OC\Updater', 'dbUpgrade', function () use($log) {
555
+            $log->info('\OC\Updater::dbUpgrade: Updated database', ['app' => 'updater']);
556
+        });
557
+        $this->listen('\OC\Updater', 'dbSimulateUpgradeBefore', function () use($log) {
558
+            $log->info('\OC\Updater::dbSimulateUpgradeBefore: Checking whether the database schema can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
559
+        });
560
+        $this->listen('\OC\Updater', 'dbSimulateUpgrade', function () use($log) {
561
+            $log->info('\OC\Updater::dbSimulateUpgrade: Checked database schema update', ['app' => 'updater']);
562
+        });
563
+        $this->listen('\OC\Updater', 'incompatibleAppDisabled', function ($app) use($log) {
564
+            $log->info('\OC\Updater::incompatibleAppDisabled: Disabled incompatible app: ' . $app, ['app' => 'updater']);
565
+        });
566
+        $this->listen('\OC\Updater', 'checkAppStoreAppBefore', function ($app) use($log) {
567
+            $log->info('\OC\Updater::checkAppStoreAppBefore: Checking for update of app "' . $app . '" in appstore', ['app' => 'updater']);
568
+        });
569
+        $this->listen('\OC\Updater', 'upgradeAppStoreApp', function ($app) use($log) {
570
+            $log->info('\OC\Updater::upgradeAppStoreApp: Update app "' . $app . '" from appstore', ['app' => 'updater']);
571
+        });
572
+        $this->listen('\OC\Updater', 'checkAppStoreApp', function ($app) use($log) {
573
+            $log->info('\OC\Updater::checkAppStoreApp: Checked for update of app "' . $app . '" in appstore', ['app' => 'updater']);
574
+        });
575
+        $this->listen('\OC\Updater', 'appUpgradeCheckBefore', function () use ($log) {
576
+            $log->info('\OC\Updater::appUpgradeCheckBefore: Checking updates of apps', ['app' => 'updater']);
577
+        });
578
+        $this->listen('\OC\Updater', 'appSimulateUpdate', function ($app) use ($log) {
579
+            $log->info('\OC\Updater::appSimulateUpdate: Checking whether the database schema for <' . $app . '> can be updated (this can take a long time depending on the database size)', ['app' => 'updater']);
580
+        });
581
+        $this->listen('\OC\Updater', 'appUpgradeCheck', function () use ($log) {
582
+            $log->info('\OC\Updater::appUpgradeCheck: Checked database schema update for apps', ['app' => 'updater']);
583
+        });
584
+        $this->listen('\OC\Updater', 'appUpgradeStarted', function ($app) use ($log) {
585
+            $log->info('\OC\Updater::appUpgradeStarted: Updating <' . $app . '> ...', ['app' => 'updater']);
586
+        });
587
+        $this->listen('\OC\Updater', 'appUpgrade', function ($app, $version) use ($log) {
588
+            $log->info('\OC\Updater::appUpgrade: Updated <' . $app . '> to ' . $version, ['app' => 'updater']);
589
+        });
590
+        $this->listen('\OC\Updater', 'failure', function ($message) use($log) {
591
+            $log->error('\OC\Updater::failure: ' . $message, ['app' => 'updater']);
592
+        });
593
+        $this->listen('\OC\Updater', 'setDebugLogLevel', function () use($log) {
594
+            $log->info('\OC\Updater::setDebugLogLevel: Set log level to debug', ['app' => 'updater']);
595
+        });
596
+        $this->listen('\OC\Updater', 'resetLogLevel', function ($logLevel, $logLevelName) use($log) {
597
+            $log->info('\OC\Updater::resetLogLevel: Reset log level to ' . $logLevelName . '(' . $logLevel . ')', ['app' => 'updater']);
598
+        });
599
+        $this->listen('\OC\Updater', 'startCheckCodeIntegrity', function () use($log) {
600
+            $log->info('\OC\Updater::startCheckCodeIntegrity: Starting code integrity check...', ['app' => 'updater']);
601
+        });
602
+        $this->listen('\OC\Updater', 'finishedCheckCodeIntegrity', function () use($log) {
603
+            $log->info('\OC\Updater::finishedCheckCodeIntegrity: Finished code integrity check', ['app' => 'updater']);
604
+        });
605
+
606
+    }
607 607
 
608 608
 }
609 609
 
Please login to merge, or discard this patch.
lib/private/Cache/File.php 1 patch
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -35,170 +35,170 @@
 block discarded – undo
35 35
 
36 36
 class File implements ICache {
37 37
 
38
-	/** @var View */
39
-	protected $storage;
38
+    /** @var View */
39
+    protected $storage;
40 40
 
41
-	/**
42
-	 * Returns the cache storage for the logged in user
43
-	 *
44
-	 * @return \OC\Files\View cache storage
45
-	 * @throws \OC\ForbiddenException
46
-	 * @throws \OC\User\NoUserException
47
-	 */
48
-	protected function getStorage() {
49
-		if (isset($this->storage)) {
50
-			return $this->storage;
51
-		}
52
-		if (\OC::$server->getUserSession()->isLoggedIn()) {
53
-			$rootView = new View();
54
-			$user = \OC::$server->getUserSession()->getUser();
55
-			Filesystem::initMountPoints($user->getUID());
56
-			if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
57
-				$rootView->mkdir('/' . $user->getUID() . '/cache');
58
-			}
59
-			$this->storage = new View('/' . $user->getUID() . '/cache');
60
-			return $this->storage;
61
-		} else {
62
-			\OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', ILogger::ERROR);
63
-			throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
64
-		}
65
-	}
41
+    /**
42
+     * Returns the cache storage for the logged in user
43
+     *
44
+     * @return \OC\Files\View cache storage
45
+     * @throws \OC\ForbiddenException
46
+     * @throws \OC\User\NoUserException
47
+     */
48
+    protected function getStorage() {
49
+        if (isset($this->storage)) {
50
+            return $this->storage;
51
+        }
52
+        if (\OC::$server->getUserSession()->isLoggedIn()) {
53
+            $rootView = new View();
54
+            $user = \OC::$server->getUserSession()->getUser();
55
+            Filesystem::initMountPoints($user->getUID());
56
+            if (!$rootView->file_exists('/' . $user->getUID() . '/cache')) {
57
+                $rootView->mkdir('/' . $user->getUID() . '/cache');
58
+            }
59
+            $this->storage = new View('/' . $user->getUID() . '/cache');
60
+            return $this->storage;
61
+        } else {
62
+            \OCP\Util::writeLog('core', 'Can\'t get cache storage, user not logged in', ILogger::ERROR);
63
+            throw new \OC\ForbiddenException('Can\t get cache storage, user not logged in');
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * @param string $key
69
-	 * @return mixed|null
70
-	 * @throws \OC\ForbiddenException
71
-	 */
72
-	public function get($key) {
73
-		$result = null;
74
-		if ($this->hasKey($key)) {
75
-			$storage = $this->getStorage();
76
-			$result = $storage->file_get_contents($key);
77
-		}
78
-		return $result;
79
-	}
67
+    /**
68
+     * @param string $key
69
+     * @return mixed|null
70
+     * @throws \OC\ForbiddenException
71
+     */
72
+    public function get($key) {
73
+        $result = null;
74
+        if ($this->hasKey($key)) {
75
+            $storage = $this->getStorage();
76
+            $result = $storage->file_get_contents($key);
77
+        }
78
+        return $result;
79
+    }
80 80
 
81
-	/**
82
-	 * Returns the size of the stored/cached data
83
-	 *
84
-	 * @param string $key
85
-	 * @return int
86
-	 */
87
-	public function size($key) {
88
-		$result = 0;
89
-		if ($this->hasKey($key)) {
90
-			$storage = $this->getStorage();
91
-			$result = $storage->filesize($key);
92
-		}
93
-		return $result;
94
-	}
81
+    /**
82
+     * Returns the size of the stored/cached data
83
+     *
84
+     * @param string $key
85
+     * @return int
86
+     */
87
+    public function size($key) {
88
+        $result = 0;
89
+        if ($this->hasKey($key)) {
90
+            $storage = $this->getStorage();
91
+            $result = $storage->filesize($key);
92
+        }
93
+        return $result;
94
+    }
95 95
 
96
-	/**
97
-	 * @param string $key
98
-	 * @param mixed $value
99
-	 * @param int $ttl
100
-	 * @return bool|mixed
101
-	 * @throws \OC\ForbiddenException
102
-	 */
103
-	public function set($key, $value, $ttl = 0) {
104
-		$storage = $this->getStorage();
105
-		$result = false;
106
-		// unique id to avoid chunk collision, just in case
107
-		$uniqueId = \OC::$server->getSecureRandom()->generate(
108
-			16,
109
-			ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
110
-		);
96
+    /**
97
+     * @param string $key
98
+     * @param mixed $value
99
+     * @param int $ttl
100
+     * @return bool|mixed
101
+     * @throws \OC\ForbiddenException
102
+     */
103
+    public function set($key, $value, $ttl = 0) {
104
+        $storage = $this->getStorage();
105
+        $result = false;
106
+        // unique id to avoid chunk collision, just in case
107
+        $uniqueId = \OC::$server->getSecureRandom()->generate(
108
+            16,
109
+            ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER
110
+        );
111 111
 
112
-		// use part file to prevent hasKey() to find the key
113
-		// while it is being written
114
-		$keyPart = $key . '.' . $uniqueId . '.part';
115
-		if ($storage and $storage->file_put_contents($keyPart, $value)) {
116
-			if ($ttl === 0) {
117
-				$ttl = 86400; // 60*60*24
118
-			}
119
-			$result = $storage->touch($keyPart, time() + $ttl);
120
-			$result &= $storage->rename($keyPart, $key);
121
-		}
122
-		return $result;
123
-	}
112
+        // use part file to prevent hasKey() to find the key
113
+        // while it is being written
114
+        $keyPart = $key . '.' . $uniqueId . '.part';
115
+        if ($storage and $storage->file_put_contents($keyPart, $value)) {
116
+            if ($ttl === 0) {
117
+                $ttl = 86400; // 60*60*24
118
+            }
119
+            $result = $storage->touch($keyPart, time() + $ttl);
120
+            $result &= $storage->rename($keyPart, $key);
121
+        }
122
+        return $result;
123
+    }
124 124
 
125
-	/**
126
-	 * @param string $key
127
-	 * @return bool
128
-	 * @throws \OC\ForbiddenException
129
-	 */
130
-	public function hasKey($key) {
131
-		$storage = $this->getStorage();
132
-		if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
133
-			return true;
134
-		}
135
-		return false;
136
-	}
125
+    /**
126
+     * @param string $key
127
+     * @return bool
128
+     * @throws \OC\ForbiddenException
129
+     */
130
+    public function hasKey($key) {
131
+        $storage = $this->getStorage();
132
+        if ($storage && $storage->is_file($key) && $storage->isReadable($key)) {
133
+            return true;
134
+        }
135
+        return false;
136
+    }
137 137
 
138
-	/**
139
-	 * @param string $key
140
-	 * @return bool|mixed
141
-	 * @throws \OC\ForbiddenException
142
-	 */
143
-	public function remove($key) {
144
-		$storage = $this->getStorage();
145
-		if (!$storage) {
146
-			return false;
147
-		}
148
-		return $storage->unlink($key);
149
-	}
138
+    /**
139
+     * @param string $key
140
+     * @return bool|mixed
141
+     * @throws \OC\ForbiddenException
142
+     */
143
+    public function remove($key) {
144
+        $storage = $this->getStorage();
145
+        if (!$storage) {
146
+            return false;
147
+        }
148
+        return $storage->unlink($key);
149
+    }
150 150
 
151
-	/**
152
-	 * @param string $prefix
153
-	 * @return bool
154
-	 * @throws \OC\ForbiddenException
155
-	 */
156
-	public function clear($prefix = '') {
157
-		$storage = $this->getStorage();
158
-		if ($storage and $storage->is_dir('/')) {
159
-			$dh = $storage->opendir('/');
160
-			if (is_resource($dh)) {
161
-				while (($file = readdir($dh)) !== false) {
162
-					if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
163
-						$storage->unlink('/' . $file);
164
-					}
165
-				}
166
-			}
167
-		}
168
-		return true;
169
-	}
151
+    /**
152
+     * @param string $prefix
153
+     * @return bool
154
+     * @throws \OC\ForbiddenException
155
+     */
156
+    public function clear($prefix = '') {
157
+        $storage = $this->getStorage();
158
+        if ($storage and $storage->is_dir('/')) {
159
+            $dh = $storage->opendir('/');
160
+            if (is_resource($dh)) {
161
+                while (($file = readdir($dh)) !== false) {
162
+                    if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
163
+                        $storage->unlink('/' . $file);
164
+                    }
165
+                }
166
+            }
167
+        }
168
+        return true;
169
+    }
170 170
 
171
-	/**
172
-	 * Runs GC
173
-	 * @throws \OC\ForbiddenException
174
-	 */
175
-	public function gc() {
176
-		$storage = $this->getStorage();
177
-		if ($storage and $storage->is_dir('/')) {
178
-			// extra hour safety, in case of stray part chunks that take longer to write,
179
-			// because touch() is only called after the chunk was finished
180
-			$now = time() - 3600;
181
-			$dh = $storage->opendir('/');
182
-			if (!is_resource($dh)) {
183
-				return null;
184
-			}
185
-			while (($file = readdir($dh)) !== false) {
186
-				if ($file != '.' and $file != '..') {
187
-					try {
188
-						$mtime = $storage->filemtime('/' . $file);
189
-						if ($mtime < $now) {
190
-							$storage->unlink('/' . $file);
191
-						}
192
-					} catch (\OCP\Lock\LockedException $e) {
193
-						// ignore locked chunks
194
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
195
-					} catch (\OCP\Files\ForbiddenException $e) {
196
-						\OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
197
-					} catch (\OCP\Files\LockNotAcquiredException $e) {
198
-						\OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
199
-					}
200
-				}
201
-			}
202
-		}
203
-	}
171
+    /**
172
+     * Runs GC
173
+     * @throws \OC\ForbiddenException
174
+     */
175
+    public function gc() {
176
+        $storage = $this->getStorage();
177
+        if ($storage and $storage->is_dir('/')) {
178
+            // extra hour safety, in case of stray part chunks that take longer to write,
179
+            // because touch() is only called after the chunk was finished
180
+            $now = time() - 3600;
181
+            $dh = $storage->opendir('/');
182
+            if (!is_resource($dh)) {
183
+                return null;
184
+            }
185
+            while (($file = readdir($dh)) !== false) {
186
+                if ($file != '.' and $file != '..') {
187
+                    try {
188
+                        $mtime = $storage->filemtime('/' . $file);
189
+                        if ($mtime < $now) {
190
+                            $storage->unlink('/' . $file);
191
+                        }
192
+                    } catch (\OCP\Lock\LockedException $e) {
193
+                        // ignore locked chunks
194
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
195
+                    } catch (\OCP\Files\ForbiddenException $e) {
196
+                        \OC::$server->getLogger()->debug('Could not cleanup forbidden chunk "' . $file . '"', array('app' => 'core'));
197
+                    } catch (\OCP\Files\LockNotAcquiredException $e) {
198
+                        \OC::$server->getLogger()->debug('Could not cleanup locked chunk "' . $file . '"', array('app' => 'core'));
199
+                    }
200
+                }
201
+            }
202
+        }
203
+    }
204 204
 }
Please login to merge, or discard this patch.
lib/private/User/Database.php 1 patch
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -76,384 +76,384 @@
 block discarded – undo
76 76
  * Class for user management in a SQL Database (e.g. MySQL, SQLite)
77 77
  */
78 78
 class Database extends ABackend
79
-	implements ICreateUserBackend,
80
-	           ISetPasswordBackend,
81
-	           ISetDisplayNameBackend,
82
-	           IGetDisplayNameBackend,
83
-	           ICheckPasswordBackend,
84
-	           IGetHomeBackend,
85
-	           ICountUsersBackend {
86
-	/** @var CappedMemoryCache */
87
-	private $cache;
88
-
89
-	/** @var EventDispatcher */
90
-	private $eventDispatcher;
91
-
92
-	/** @var IDBConnection */
93
-	private $dbConn;
94
-
95
-	/**
96
-	 * \OC\User\Database constructor.
97
-	 *
98
-	 * @param EventDispatcher $eventDispatcher
99
-	 */
100
-	public function __construct($eventDispatcher = null) {
101
-		$this->cache = new CappedMemoryCache();
102
-		$this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
103
-	}
104
-
105
-	/**
106
-	 * FIXME: This function should not be required!
107
-	 */
108
-	private function fixDI() {
109
-		if ($this->dbConn === null) {
110
-			$this->dbConn = \OC::$server->getDatabaseConnection();
111
-		}
112
-	}
113
-
114
-	/**
115
-	 * Create a new user
116
-	 *
117
-	 * @param string $uid The username of the user to create
118
-	 * @param string $password The password of the new user
119
-	 * @return bool
120
-	 *
121
-	 * Creates a new user. Basic checking of username is done in OC_User
122
-	 * itself, not in its subclasses.
123
-	 */
124
-	public function createUser(string $uid, string $password): bool {
125
-		$this->fixDI();
126
-
127
-		if (!$this->userExists($uid)) {
128
-			$event = new GenericEvent($password);
129
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
130
-
131
-			$qb = $this->dbConn->getQueryBuilder();
132
-			$qb->insert('users')
133
-				->values([
134
-					'uid' => $qb->createNamedParameter($uid),
135
-					'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
136
-					'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
137
-				]);
138
-
139
-			$result = $qb->execute();
140
-
141
-			// Clear cache
142
-			unset($this->cache[$uid]);
143
-
144
-			return $result ? true : false;
145
-		}
146
-
147
-		return false;
148
-	}
149
-
150
-	/**
151
-	 * delete a user
152
-	 *
153
-	 * @param string $uid The username of the user to delete
154
-	 * @return bool
155
-	 *
156
-	 * Deletes a user
157
-	 */
158
-	public function deleteUser($uid) {
159
-		$this->fixDI();
160
-
161
-		// Delete user-group-relation
162
-		$query = \OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
163
-		$result = $query->execute([$uid]);
164
-
165
-		if (isset($this->cache[$uid])) {
166
-			unset($this->cache[$uid]);
167
-		}
168
-
169
-		return $result ? true : false;
170
-	}
171
-
172
-	/**
173
-	 * Set password
174
-	 *
175
-	 * @param string $uid The username
176
-	 * @param string $password The new password
177
-	 * @return bool
178
-	 *
179
-	 * Change the password of a user
180
-	 */
181
-	public function setPassword(string $uid, string $password): bool {
182
-		$this->fixDI();
183
-
184
-		if ($this->userExists($uid)) {
185
-			$event = new GenericEvent($password);
186
-			$this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
187
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
188
-			$result = $query->execute([\OC::$server->getHasher()->hash($password), $uid]);
189
-
190
-			return $result ? true : false;
191
-		}
192
-
193
-		return false;
194
-	}
195
-
196
-	/**
197
-	 * Set display name
198
-	 *
199
-	 * @param string $uid The username
200
-	 * @param string $displayName The new display name
201
-	 * @return bool
202
-	 *
203
-	 * Change the display name of a user
204
-	 */
205
-	public function setDisplayName(string $uid, string $displayName): bool {
206
-		$this->fixDI();
207
-
208
-		if ($this->userExists($uid)) {
209
-			$query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
210
-			$query->execute([$displayName, $uid]);
211
-			$this->cache[$uid]['displayname'] = $displayName;
212
-
213
-			return true;
214
-		}
215
-
216
-		return false;
217
-	}
218
-
219
-	/**
220
-	 * get display name of the user
221
-	 *
222
-	 * @param string $uid user ID of the user
223
-	 * @return string display name
224
-	 */
225
-	public function getDisplayName($uid): string {
226
-		$uid = (string)$uid;
227
-		$this->loadUser($uid);
228
-		return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
229
-	}
230
-
231
-	/**
232
-	 * Get a list of all display names and user ids.
233
-	 *
234
-	 * @param string $search
235
-	 * @param string|null $limit
236
-	 * @param string|null $offset
237
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
238
-	 */
239
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
240
-		$this->fixDI();
241
-
242
-		$query = $this->dbConn->getQueryBuilder();
243
-
244
-		$query->select('uid', 'displayname')
245
-			->from('users', 'u')
246
-			->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
247
-				$query->expr()->eq('userid', 'uid'),
248
-				$query->expr()->eq('appid', $query->expr()->literal('settings')),
249
-				$query->expr()->eq('configkey', $query->expr()->literal('email')))
250
-			)
251
-			// sqlite doesn't like re-using a single named parameter here
252
-			->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
253
-			->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
254
-			->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
255
-			->orderBy($query->func()->lower('displayname'), 'ASC')
256
-			->orderBy($query->func()->lower('uid'), 'ASC')
257
-			->setMaxResults($limit)
258
-			->setFirstResult($offset);
259
-
260
-		$result = $query->execute();
261
-		$displayNames = [];
262
-		while ($row = $result->fetch()) {
263
-			$displayNames[(string)$row['uid']] = (string)$row['displayname'];
264
-		}
265
-
266
-		return $displayNames;
267
-	}
268
-
269
-	/**
270
-	 * Check if the password is correct
271
-	 *
272
-	 * @param string $uid The username
273
-	 * @param string $password The password
274
-	 * @return string
275
-	 *
276
-	 * Check if the password is correct without logging in the user
277
-	 * returns the user id or false
278
-	 */
279
-	public function checkPassword(string $uid, string $password) {
280
-		$this->fixDI();
281
-
282
-		$qb = $this->dbConn->getQueryBuilder();
283
-		$qb->select('uid', 'password')
284
-			->from('users')
285
-			->where(
286
-				$qb->expr()->eq(
287
-					'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
288
-				)
289
-			);
290
-		$result = $qb->execute();
291
-		$row = $result->fetch();
292
-		$result->closeCursor();
293
-
294
-		if ($row) {
295
-			$storedHash = $row['password'];
296
-			$newHash = '';
297
-			if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
298
-				if (!empty($newHash)) {
299
-					$this->setPassword($uid, $password);
300
-				}
301
-				return (string)$row['uid'];
302
-			}
303
-
304
-		}
305
-
306
-		return false;
307
-	}
308
-
309
-	/**
310
-	 * Load an user in the cache
311
-	 *
312
-	 * @param string $uid the username
313
-	 * @return boolean true if user was found, false otherwise
314
-	 */
315
-	private function loadUser($uid) {
316
-		$this->fixDI();
317
-
318
-		$uid = (string)$uid;
319
-		if (!isset($this->cache[$uid])) {
320
-			//guests $uid could be NULL or ''
321
-			if ($uid === '') {
322
-				$this->cache[$uid] = false;
323
-				return true;
324
-			}
325
-
326
-			$qb = $this->dbConn->getQueryBuilder();
327
-			$qb->select('uid', 'displayname')
328
-				->from('users')
329
-				->where(
330
-					$qb->expr()->eq(
331
-						'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
332
-					)
333
-				);
334
-			$result = $qb->execute();
335
-			$row = $result->fetch();
336
-			$result->closeCursor();
337
-
338
-			$this->cache[$uid] = false;
339
-
340
-			// "uid" is primary key, so there can only be a single result
341
-			if ($row !== false) {
342
-				$this->cache[$uid]['uid'] = (string)$row['uid'];
343
-				$this->cache[$uid]['displayname'] = (string)$row['displayname'];
344
-			} else {
345
-				return false;
346
-			}
347
-		}
348
-
349
-		return true;
350
-	}
351
-
352
-	/**
353
-	 * Get a list of all users
354
-	 *
355
-	 * @param string $search
356
-	 * @param null|int $limit
357
-	 * @param null|int $offset
358
-	 * @return string[] an array of all uids
359
-	 */
360
-	public function getUsers($search = '', $limit = null, $offset = null) {
361
-		$users = $this->getDisplayNames($search, $limit, $offset);
362
-		$userIds = array_map(function ($uid) {
363
-			return (string)$uid;
364
-		}, array_keys($users));
365
-		sort($userIds, SORT_STRING | SORT_FLAG_CASE);
366
-		return $userIds;
367
-	}
368
-
369
-	/**
370
-	 * check if a user exists
371
-	 *
372
-	 * @param string $uid the username
373
-	 * @return boolean
374
-	 */
375
-	public function userExists($uid) {
376
-		$this->loadUser($uid);
377
-		return $this->cache[$uid] !== false;
378
-	}
379
-
380
-	/**
381
-	 * get the user's home directory
382
-	 *
383
-	 * @param string $uid the username
384
-	 * @return string|false
385
-	 */
386
-	public function getHome(string $uid) {
387
-		if ($this->userExists($uid)) {
388
-			return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
389
-		}
390
-
391
-		return false;
392
-	}
393
-
394
-	/**
395
-	 * @return bool
396
-	 */
397
-	public function hasUserListings() {
398
-		return true;
399
-	}
400
-
401
-	/**
402
-	 * counts the users in the database
403
-	 *
404
-	 * @return int|bool
405
-	 */
406
-	public function countUsers() {
407
-		$this->fixDI();
408
-
409
-		$query = \OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
410
-		$result = $query->execute();
411
-		if ($result === false) {
412
-			Util::writeLog('core', \OC_DB::getErrorMessage(), ILogger::ERROR);
413
-			return false;
414
-		}
415
-		return $result->fetchOne();
416
-	}
417
-
418
-	/**
419
-	 * returns the username for the given login name in the correct casing
420
-	 *
421
-	 * @param string $loginName
422
-	 * @return string|false
423
-	 */
424
-	public function loginName2UserName($loginName) {
425
-		if ($this->userExists($loginName)) {
426
-			return $this->cache[$loginName]['uid'];
427
-		}
428
-
429
-		return false;
430
-	}
431
-
432
-	/**
433
-	 * Backend name to be shown in user management
434
-	 *
435
-	 * @return string the name of the backend to be shown
436
-	 */
437
-	public function getBackendName() {
438
-		return 'Database';
439
-	}
440
-
441
-	public static function preLoginNameUsedAsUserName($param) {
442
-		if (!isset($param['uid'])) {
443
-			throw new \Exception('key uid is expected to be set in $param');
444
-		}
445
-
446
-		$backends = \OC::$server->getUserManager()->getBackends();
447
-		foreach ($backends as $backend) {
448
-			if ($backend instanceof Database) {
449
-				/** @var \OC\User\Database $backend */
450
-				$uid = $backend->loginName2UserName($param['uid']);
451
-				if ($uid !== false) {
452
-					$param['uid'] = $uid;
453
-					return;
454
-				}
455
-			}
456
-		}
457
-
458
-	}
79
+    implements ICreateUserBackend,
80
+                ISetPasswordBackend,
81
+                ISetDisplayNameBackend,
82
+                IGetDisplayNameBackend,
83
+                ICheckPasswordBackend,
84
+                IGetHomeBackend,
85
+                ICountUsersBackend {
86
+    /** @var CappedMemoryCache */
87
+    private $cache;
88
+
89
+    /** @var EventDispatcher */
90
+    private $eventDispatcher;
91
+
92
+    /** @var IDBConnection */
93
+    private $dbConn;
94
+
95
+    /**
96
+     * \OC\User\Database constructor.
97
+     *
98
+     * @param EventDispatcher $eventDispatcher
99
+     */
100
+    public function __construct($eventDispatcher = null) {
101
+        $this->cache = new CappedMemoryCache();
102
+        $this->eventDispatcher = $eventDispatcher ? $eventDispatcher : \OC::$server->getEventDispatcher();
103
+    }
104
+
105
+    /**
106
+     * FIXME: This function should not be required!
107
+     */
108
+    private function fixDI() {
109
+        if ($this->dbConn === null) {
110
+            $this->dbConn = \OC::$server->getDatabaseConnection();
111
+        }
112
+    }
113
+
114
+    /**
115
+     * Create a new user
116
+     *
117
+     * @param string $uid The username of the user to create
118
+     * @param string $password The password of the new user
119
+     * @return bool
120
+     *
121
+     * Creates a new user. Basic checking of username is done in OC_User
122
+     * itself, not in its subclasses.
123
+     */
124
+    public function createUser(string $uid, string $password): bool {
125
+        $this->fixDI();
126
+
127
+        if (!$this->userExists($uid)) {
128
+            $event = new GenericEvent($password);
129
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
130
+
131
+            $qb = $this->dbConn->getQueryBuilder();
132
+            $qb->insert('users')
133
+                ->values([
134
+                    'uid' => $qb->createNamedParameter($uid),
135
+                    'password' => $qb->createNamedParameter(\OC::$server->getHasher()->hash($password)),
136
+                    'uid_lower' => $qb->createNamedParameter(mb_strtolower($uid)),
137
+                ]);
138
+
139
+            $result = $qb->execute();
140
+
141
+            // Clear cache
142
+            unset($this->cache[$uid]);
143
+
144
+            return $result ? true : false;
145
+        }
146
+
147
+        return false;
148
+    }
149
+
150
+    /**
151
+     * delete a user
152
+     *
153
+     * @param string $uid The username of the user to delete
154
+     * @return bool
155
+     *
156
+     * Deletes a user
157
+     */
158
+    public function deleteUser($uid) {
159
+        $this->fixDI();
160
+
161
+        // Delete user-group-relation
162
+        $query = \OC_DB::prepare('DELETE FROM `*PREFIX*users` WHERE `uid` = ?');
163
+        $result = $query->execute([$uid]);
164
+
165
+        if (isset($this->cache[$uid])) {
166
+            unset($this->cache[$uid]);
167
+        }
168
+
169
+        return $result ? true : false;
170
+    }
171
+
172
+    /**
173
+     * Set password
174
+     *
175
+     * @param string $uid The username
176
+     * @param string $password The new password
177
+     * @return bool
178
+     *
179
+     * Change the password of a user
180
+     */
181
+    public function setPassword(string $uid, string $password): bool {
182
+        $this->fixDI();
183
+
184
+        if ($this->userExists($uid)) {
185
+            $event = new GenericEvent($password);
186
+            $this->eventDispatcher->dispatch('OCP\PasswordPolicy::validate', $event);
187
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `password` = ? WHERE `uid` = ?');
188
+            $result = $query->execute([\OC::$server->getHasher()->hash($password), $uid]);
189
+
190
+            return $result ? true : false;
191
+        }
192
+
193
+        return false;
194
+    }
195
+
196
+    /**
197
+     * Set display name
198
+     *
199
+     * @param string $uid The username
200
+     * @param string $displayName The new display name
201
+     * @return bool
202
+     *
203
+     * Change the display name of a user
204
+     */
205
+    public function setDisplayName(string $uid, string $displayName): bool {
206
+        $this->fixDI();
207
+
208
+        if ($this->userExists($uid)) {
209
+            $query = \OC_DB::prepare('UPDATE `*PREFIX*users` SET `displayname` = ? WHERE LOWER(`uid`) = LOWER(?)');
210
+            $query->execute([$displayName, $uid]);
211
+            $this->cache[$uid]['displayname'] = $displayName;
212
+
213
+            return true;
214
+        }
215
+
216
+        return false;
217
+    }
218
+
219
+    /**
220
+     * get display name of the user
221
+     *
222
+     * @param string $uid user ID of the user
223
+     * @return string display name
224
+     */
225
+    public function getDisplayName($uid): string {
226
+        $uid = (string)$uid;
227
+        $this->loadUser($uid);
228
+        return empty($this->cache[$uid]['displayname']) ? $uid : $this->cache[$uid]['displayname'];
229
+    }
230
+
231
+    /**
232
+     * Get a list of all display names and user ids.
233
+     *
234
+     * @param string $search
235
+     * @param string|null $limit
236
+     * @param string|null $offset
237
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
238
+     */
239
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
240
+        $this->fixDI();
241
+
242
+        $query = $this->dbConn->getQueryBuilder();
243
+
244
+        $query->select('uid', 'displayname')
245
+            ->from('users', 'u')
246
+            ->leftJoin('u', 'preferences', 'p', $query->expr()->andX(
247
+                $query->expr()->eq('userid', 'uid'),
248
+                $query->expr()->eq('appid', $query->expr()->literal('settings')),
249
+                $query->expr()->eq('configkey', $query->expr()->literal('email')))
250
+            )
251
+            // sqlite doesn't like re-using a single named parameter here
252
+            ->where($query->expr()->iLike('uid', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
253
+            ->orWhere($query->expr()->iLike('displayname', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
254
+            ->orWhere($query->expr()->iLike('configvalue', $query->createPositionalParameter('%' . $this->dbConn->escapeLikeParameter($search) . '%')))
255
+            ->orderBy($query->func()->lower('displayname'), 'ASC')
256
+            ->orderBy($query->func()->lower('uid'), 'ASC')
257
+            ->setMaxResults($limit)
258
+            ->setFirstResult($offset);
259
+
260
+        $result = $query->execute();
261
+        $displayNames = [];
262
+        while ($row = $result->fetch()) {
263
+            $displayNames[(string)$row['uid']] = (string)$row['displayname'];
264
+        }
265
+
266
+        return $displayNames;
267
+    }
268
+
269
+    /**
270
+     * Check if the password is correct
271
+     *
272
+     * @param string $uid The username
273
+     * @param string $password The password
274
+     * @return string
275
+     *
276
+     * Check if the password is correct without logging in the user
277
+     * returns the user id or false
278
+     */
279
+    public function checkPassword(string $uid, string $password) {
280
+        $this->fixDI();
281
+
282
+        $qb = $this->dbConn->getQueryBuilder();
283
+        $qb->select('uid', 'password')
284
+            ->from('users')
285
+            ->where(
286
+                $qb->expr()->eq(
287
+                    'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
288
+                )
289
+            );
290
+        $result = $qb->execute();
291
+        $row = $result->fetch();
292
+        $result->closeCursor();
293
+
294
+        if ($row) {
295
+            $storedHash = $row['password'];
296
+            $newHash = '';
297
+            if (\OC::$server->getHasher()->verify($password, $storedHash, $newHash)) {
298
+                if (!empty($newHash)) {
299
+                    $this->setPassword($uid, $password);
300
+                }
301
+                return (string)$row['uid'];
302
+            }
303
+
304
+        }
305
+
306
+        return false;
307
+    }
308
+
309
+    /**
310
+     * Load an user in the cache
311
+     *
312
+     * @param string $uid the username
313
+     * @return boolean true if user was found, false otherwise
314
+     */
315
+    private function loadUser($uid) {
316
+        $this->fixDI();
317
+
318
+        $uid = (string)$uid;
319
+        if (!isset($this->cache[$uid])) {
320
+            //guests $uid could be NULL or ''
321
+            if ($uid === '') {
322
+                $this->cache[$uid] = false;
323
+                return true;
324
+            }
325
+
326
+            $qb = $this->dbConn->getQueryBuilder();
327
+            $qb->select('uid', 'displayname')
328
+                ->from('users')
329
+                ->where(
330
+                    $qb->expr()->eq(
331
+                        'uid_lower', $qb->createNamedParameter(mb_strtolower($uid))
332
+                    )
333
+                );
334
+            $result = $qb->execute();
335
+            $row = $result->fetch();
336
+            $result->closeCursor();
337
+
338
+            $this->cache[$uid] = false;
339
+
340
+            // "uid" is primary key, so there can only be a single result
341
+            if ($row !== false) {
342
+                $this->cache[$uid]['uid'] = (string)$row['uid'];
343
+                $this->cache[$uid]['displayname'] = (string)$row['displayname'];
344
+            } else {
345
+                return false;
346
+            }
347
+        }
348
+
349
+        return true;
350
+    }
351
+
352
+    /**
353
+     * Get a list of all users
354
+     *
355
+     * @param string $search
356
+     * @param null|int $limit
357
+     * @param null|int $offset
358
+     * @return string[] an array of all uids
359
+     */
360
+    public function getUsers($search = '', $limit = null, $offset = null) {
361
+        $users = $this->getDisplayNames($search, $limit, $offset);
362
+        $userIds = array_map(function ($uid) {
363
+            return (string)$uid;
364
+        }, array_keys($users));
365
+        sort($userIds, SORT_STRING | SORT_FLAG_CASE);
366
+        return $userIds;
367
+    }
368
+
369
+    /**
370
+     * check if a user exists
371
+     *
372
+     * @param string $uid the username
373
+     * @return boolean
374
+     */
375
+    public function userExists($uid) {
376
+        $this->loadUser($uid);
377
+        return $this->cache[$uid] !== false;
378
+    }
379
+
380
+    /**
381
+     * get the user's home directory
382
+     *
383
+     * @param string $uid the username
384
+     * @return string|false
385
+     */
386
+    public function getHome(string $uid) {
387
+        if ($this->userExists($uid)) {
388
+            return \OC::$server->getConfig()->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/' . $uid;
389
+        }
390
+
391
+        return false;
392
+    }
393
+
394
+    /**
395
+     * @return bool
396
+     */
397
+    public function hasUserListings() {
398
+        return true;
399
+    }
400
+
401
+    /**
402
+     * counts the users in the database
403
+     *
404
+     * @return int|bool
405
+     */
406
+    public function countUsers() {
407
+        $this->fixDI();
408
+
409
+        $query = \OC_DB::prepare('SELECT COUNT(*) FROM `*PREFIX*users`');
410
+        $result = $query->execute();
411
+        if ($result === false) {
412
+            Util::writeLog('core', \OC_DB::getErrorMessage(), ILogger::ERROR);
413
+            return false;
414
+        }
415
+        return $result->fetchOne();
416
+    }
417
+
418
+    /**
419
+     * returns the username for the given login name in the correct casing
420
+     *
421
+     * @param string $loginName
422
+     * @return string|false
423
+     */
424
+    public function loginName2UserName($loginName) {
425
+        if ($this->userExists($loginName)) {
426
+            return $this->cache[$loginName]['uid'];
427
+        }
428
+
429
+        return false;
430
+    }
431
+
432
+    /**
433
+     * Backend name to be shown in user management
434
+     *
435
+     * @return string the name of the backend to be shown
436
+     */
437
+    public function getBackendName() {
438
+        return 'Database';
439
+    }
440
+
441
+    public static function preLoginNameUsedAsUserName($param) {
442
+        if (!isset($param['uid'])) {
443
+            throw new \Exception('key uid is expected to be set in $param');
444
+        }
445
+
446
+        $backends = \OC::$server->getUserManager()->getBackends();
447
+        foreach ($backends as $backend) {
448
+            if ($backend instanceof Database) {
449
+                /** @var \OC\User\Database $backend */
450
+                $uid = $backend->loginName2UserName($param['uid']);
451
+                if ($uid !== false) {
452
+                    $param['uid'] = $uid;
453
+                    return;
454
+                }
455
+            }
456
+        }
457
+
458
+    }
459 459
 }
Please login to merge, or discard this patch.